001/*
002 *  Licensed to the Apache Software Foundation (ASF) under one or more
003 *  contributor license agreements.  See the NOTICE file distributed with
004 *  this work for additional information regarding copyright ownership.
005 *  The ASF licenses this file to You under the Apache License, Version 2.0
006 *  (the "License"); you may not use this file except in compliance with
007 *  the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 *  Unless required by applicable law or agreed to in writing, software
012 *  distributed under the License is distributed on an "AS IS" BASIS,
013 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 *  See the License for the specific language governing permissions and
015 *  limitations under the License.
016 *
017 */
018
019package org.apache.commons.compress.archivers.zip;
020
021import java.io.IOException;
022import java.nio.file.Files;
023import java.nio.file.Path;
024import java.util.concurrent.atomic.AtomicInteger;
025
026import org.apache.commons.compress.parallel.FileBasedScatterGatherBackingStore;
027import org.apache.commons.compress.parallel.ScatterGatherBackingStore;
028import org.apache.commons.compress.parallel.ScatterGatherBackingStoreSupplier;
029
030/**
031 * Implements {@link ScatterGatherBackingStoreSupplier} using a temporary folder.
032 * <p>
033 * For example:
034 * </p>
035 * <pre>
036 * final Path dir = Paths.get("target/custom-temp-dir");
037 * Files.createDirectories(dir);
038 * final ParallelScatterZipCreator zipCreator = new ParallelScatterZipCreator(
039 *     Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()),
040 *     new DefaultBackingStoreSupplier(dir));
041 * </pre>
042 *
043 * @since 1.23
044 */
045public class DefaultBackingStoreSupplier implements ScatterGatherBackingStoreSupplier {
046
047    private static final String PREFIX = "parallelscatter";
048
049    private final AtomicInteger storeNum = new AtomicInteger();
050
051    private final Path dir;
052    /**
053     * Constructs a new instance. If {@code dir} is null, then use the default temporary-file directory.
054     *
055     * @param dir temporary folder, may be null, must exist if non-null.
056     */
057    public DefaultBackingStoreSupplier(final Path dir) {
058        this.dir = dir;
059    }
060
061    @Override
062    public ScatterGatherBackingStore get() throws IOException {
063        final String suffix = "n" + storeNum.incrementAndGet();
064        final Path tempFile = dir == null ? Files.createTempFile(PREFIX, suffix) : Files.createTempFile(dir, PREFIX, suffix);
065        return new FileBasedScatterGatherBackingStore(tempFile);
066    }
067}