Example usage for java.nio.file Files createTempDirectory

List of usage examples for java.nio.file Files createTempDirectory

Introduction

In this page you can find the example usage for java.nio.file Files createTempDirectory.

Prototype

public static Path createTempDirectory(String prefix, FileAttribute<?>... attrs) throws IOException 

Source Link

Document

Creates a new directory in the default temporary-file directory, using the given prefix to generate its name.

Usage

From source file:cpcc.ros.sim.osm.TileCacheTest.java

@BeforeMethod
public void setUp() throws Exception {
    File path = new File("target/");
    tempDirectory = Files.createTempDirectory(path.toPath(), "tmp-test").toFile();
    assertThat(tempDirectory).exists();//from   w  w w. java2 s  .c o  m

    config = PowerMockito.mock(Configuration.class);
    PowerMockito.doReturn(tempDirectory.getAbsolutePath()).when(config).getTileCacheBaseDir();
    PowerMockito.doReturn("http://my.tile.server/%1$d/%2$d/%3$d.png").when(config).getTileServerUrl();

    sut = new TileCache(config);

    entity = Mockito.mock(HttpEntity.class);
    when(entity.getContent()).thenReturn(new ByteArrayInputStream(responseData.getBytes("UTF-8")));

    response = PowerMockito.mock(CloseableHttpResponse.class);
    PowerMockito.when(response.getStatusLine()).thenReturn(statusLine200ok);
    PowerMockito.when(response.getEntity()).thenReturn(entity);

    client = PowerMockito.mock(CloseableHttpClient.class);
    PowerMockito.doReturn(response).when(client).execute(any(HttpUriRequest.class));

    httpClientBuilderMock = PowerMock.createMock(HttpClientBuilder.class);

    PowerMock.mockStatic(HttpClientBuilder.class);
    EasyMock.expect(HttpClientBuilder.create()).andReturn(httpClientBuilderMock).anyTimes();
    PowerMock.replay(HttpClientBuilder.class);
    EasyMock.expect(httpClientBuilderMock.setUserAgent(USER_AGENT)).andReturn(httpClientBuilderMock).anyTimes();
    PowerMock.replay(HttpClientBuilder.class);
    EasyMock.expect(httpClientBuilderMock.build()).andReturn(client).anyTimes();
    PowerMock.replay(HttpClientBuilder.class, httpClientBuilderMock);
}

From source file:fr.treeptik.cloudunit.utils.GitUtils.java

/**
 * List all GIT Tags of an application with an index
 * After this index is use to choose on which tag user want to restre his application
 * with resetOnChosenGitTag() method//www  . j  a v a 2s . c om
 *
 * @param application
 * @param dockerManagerAddress
 * @param containerGitAddress
 * @return
 * @throws GitAPIException
 * @throws IOException
 */
public static List<String> listGitTagsOfApplication(Application application, String dockerManagerAddress,
        String containerGitAddress) throws GitAPIException, IOException {

    List<String> listTagsName = new ArrayList<>();

    User user = application.getUser();
    String sshPort = application.getServers().get(0).getSshPort();
    String password = user.getPassword();
    String userNameGit = user.getLogin();
    String dockerManagerIP = dockerManagerAddress.substring(0, dockerManagerAddress.length() - 5);
    String remoteRepository = "ssh://" + userNameGit + "@" + dockerManagerIP + ":" + sshPort
            + containerGitAddress;

    Path myTempDirPath = Files.createTempDirectory(Paths.get("/tmp"), null);
    File gitworkDir = myTempDirPath.toFile();

    InitCommand initCommand = Git.init();
    initCommand.setDirectory(gitworkDir);
    initCommand.call();
    FileRepository gitRepo = new FileRepository(gitworkDir);
    LsRemoteCommand lsRemoteCommand = new LsRemoteCommand(gitRepo);

    CredentialsProvider credentialsProvider = configCredentialsForGit(userNameGit, password);

    lsRemoteCommand.setCredentialsProvider(credentialsProvider);
    lsRemoteCommand.setRemote(remoteRepository);
    lsRemoteCommand.setTags(true);
    Collection<Ref> collectionRefs = lsRemoteCommand.call();
    List<Ref> listRefs = new ArrayList<>(collectionRefs);

    for (Ref ref : listRefs) {
        listTagsName.add(ref.getName());
    }
    Collections.sort(listTagsName);
    FilesUtils.deleteDirectory(gitworkDir);

    return listTagsName;

}

From source file:org.apache.tika.batch.fs.FSBatchTestBase.java

Path getNewOutputDir(String subdirPrefix) throws IOException {
    Path outputDir = Files.createTempDirectory(outputRoot, subdirPrefix);
    assert (countChildren(outputDir) == 0);
    return outputDir;
}

From source file:data.NeustarDatabaseUpdaterTest.java

@Before
public void before() throws Exception {
    initMocks(this);

    when(neustarOldDatabaseDirectory.isDirectory()).thenReturn(true);
    when(neustarOldDatabaseDirectory.lastModified()).thenReturn(1425236082000L);

    mockTmpDir = mock(File.class);
    when(mockTmpDir.getName()).thenReturn("123-abc-tmp");
    when(mockTmpDir.getParentFile()).thenReturn(neustarDatabaseDirectory);

    when(neustarDatabaseDirectory.listFiles())
            .thenReturn(new File[] { neustarOldDatabaseDirectory, mockTmpDir });

    Path path = mock(Path.class);
    when(path.toFile()).thenReturn(mockTmpDir);

    mockStatic(Files.class);
    when(Files.createTempDirectory(any(Path.class), eq("neustar-"))).thenReturn(path);
    when(tarExtractor.extractTo(eq(mockTmpDir), any(GZIPInputStream.class))).thenReturn(true);
}

From source file:jenkins.plugins.pbs.tasks.Qsub.java

public Boolean call() {
    final String myLogBasename = (logBasename.length() > 0) ? logBasename : System.getenv("java.io.tmpdir");

    try {//from   w ww .j  a v  a  2  s  . c o  m
        // If we are running as another user, we are going to make sure we
        // set permissions more loosely
        Path tmpDir = Files.createTempDirectory(Paths.get(myLogBasename), "jenkinsPBS_");
        File tmpDirFile = tmpDir.toFile();
        if (!tmpDirFile.exists()) {
            if (!tmpDirFile.mkdirs()) {
                listener.getLogger().println("Failed to create working directory: " + tmpDir.toString());
                throw new PBSException("Failed to create working directory: " + tmpDir.toString());
            }
        }

        this.executionDirectory = tmpDir.toString();
        if (this.runUser.length() > 0) {
            Files.setPosixFilePermissions(Paths.get(this.executionDirectory),
                    PosixFilePermissions.fromString("rwxrwxrwx"));
        }
        listener.getLogger()
                .println(String.format("Created working directory '%s' with permissions '%s'",
                        this.executionDirectory, PosixFilePermissions
                                .toString(Files.getPosixFilePermissions(Paths.get(this.executionDirectory)))));
    } catch (IOException e) {
        listener.fatalError(e.getMessage(), e);
        throw new PBSException("Failed to create working directory: " + e.getMessage(), e);
    }

    if (StringUtils.isNotBlank(logHostname)) {
        this.errFileName = String.format("%s:%s", logHostname, Paths.get(this.executionDirectory, "err"));
        this.outFileName = String.format("%s:%s", logHostname, Paths.get(this.executionDirectory, "out"));
    } else {
        this.errFileName = Paths.get(this.executionDirectory, "err").toString();
        this.outFileName = Paths.get(this.executionDirectory, "out").toString();
    }

    OutputStream tmpScriptOut = null;
    try {
        Path tmpScript = Paths.get(this.executionDirectory, "script");
        tmpScriptOut = Files.newOutputStream(tmpScript);
        tmpScriptOut.write(script.getBytes());
        tmpScriptOut.flush();

        listener.getLogger().println("PBS script: " + tmpScript.toString());
        String[] argList;
        if (this.runUser.length() > 0) {
            argList = new String[] { "-P", this.runUser, "-e", this.errFileName, "-o", this.outFileName,
                    tmpScript.toString(), "-W", "umask=022" };
        } else {
            argList = new String[] { "-e", this.errFileName, "-o", this.outFileName, tmpScript.toString() };
        }
        String jobId = PBS.qsub(argList, this.environment);

        listener.getLogger().println("PBS Job submitted: " + jobId);

        return this.seekEnd(jobId, numberOfDays, span);
    } catch (IOException e) {
        e.printStackTrace(listener.getLogger());
        throw new PBSException("Failed to create temp script");
    } finally {
        IOUtils.closeQuietly(tmpScriptOut);
    }
}

From source file:com.cloudera.livy.rsc.driver.RSCDriver.java

public RSCDriver(SparkConf conf, RSCConf livyConf) throws Exception {
    Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwx------");
    this.localTmpDir = Files.createTempDirectory("rsc-tmp", PosixFilePermissions.asFileAttribute(perms))
            .toFile();/*from   ww w . j  a  v  a 2s .  c o  m*/
    this.executor = Executors.newCachedThreadPool();
    this.jobQueue = new LinkedList<>();
    this.clients = new ConcurrentLinkedDeque<>();
    this.serializer = new Serializer();

    this.conf = conf;
    this.livyConf = livyConf;
    this.jcLock = new Object();
    this.shutdownLock = new Object();

    this.activeJobs = new ConcurrentHashMap<>();
    this.bypassJobs = new ConcurrentLinkedDeque<>();
    this.idleTimeout = new AtomicReference<>();
}

From source file:com.linkedin.pinot.core.segment.index.converter.SegmentV1V2ToV3FormatConverter.java

@VisibleForTesting
public File v3ConversionTempDirectory(File v2SegmentDirectory) throws IOException {
    File v3TempDirectory = Files
            .createTempDirectory(v2SegmentDirectory.toPath(), v2SegmentDirectory.getName() + V3_TEMP_DIR_SUFFIX)
            .toFile();/*ww  w. j a va2 s .co m*/
    return v3TempDirectory;

}

From source file:org.apache.zeppelin.search.LuceneSearch.java

@Inject
public LuceneSearch(ZeppelinConfiguration zeppelinConfiguration) {
    super("LuceneSearch-Thread");
    this.zeppelinConfiguration = zeppelinConfiguration;
    if (zeppelinConfiguration.isZeppelinSearchUseDisk()) {
        try {/*from  ww w.  j a va2  s . c  o m*/
            this.directoryPath = Files.createTempDirectory(
                    Paths.get(zeppelinConfiguration.getZeppelinSearchTempPath()), "zeppelin-search-");
            this.directory = new MMapDirectory(directoryPath);
        } catch (IOException e) {
            throw new RuntimeException(
                    "Failed to create temporary directory for search service. Use memory instead", e);
        }
    } else {
        this.directory = new RAMDirectory();
    }
    this.analyzer = new StandardAnalyzer();
    this.indexWriterConfig = new IndexWriterConfig(analyzer);
    try {
        this.indexWriter = new IndexWriter(directory, indexWriterConfig);
    } catch (IOException e) {
        logger.error("Failed to create new IndexWriter", e);
    }
}

From source file:io.syndesis.git.GitWorkflow.java

/**
 * Updates an existing git repository with the current version of project files.
 *
 * @param remoteGitRepoHttpUrl- the HTML (not ssh) url to a git repository
 * @param repoName              - the name of the git repository
 * @param author                author//from   w  w w . java2 s  .  c o m
 * @param message-              commit message
 * @param files-                map of file paths along with their content
 * @param credentials-          Git credentials, for example username/password, authToken, personal access token
 */
public void updateFiles(String remoteGitRepoHttpUrl, String repoName, User author, String message,
        Map<String, byte[]> files, UsernamePasswordCredentialsProvider credentials) {

    // create temporary directory
    try {
        Path workingDir = Files.createTempDirectory(Paths.get(gitProperties.getLocalGitRepoPath()), repoName);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Created temporary directory {}", workingDir.toString());
        }

        // git clone
        Git git = Git.cloneRepository().setDirectory(workingDir.toFile()).setURI(remoteGitRepoHttpUrl).call();
        writeFiles(workingDir, files);

        commitAndPush(git, authorName(author), author.getEmail(), message, credentials);
        removeWorkingDir(workingDir);
    } catch (IOException | GitAPIException e) {
        throw SyndesisServerException.launderThrowable(e);
    }
}

From source file:com.spectralogic.ds3client.metadata.WindowsMetadataRestore_Test.java

@Test
public void restoreUserAndOwner_Test() throws Exception {
    final ImmutableMap.Builder<String, String> metadataMap = new ImmutableMap.Builder<>();
    final WindowsMetadataStore windowsMetadataStore = new WindowsMetadataStore(metadataMap);
    final Class aClass = WindowsMetadataStore.class;
    final Method method = aClass.getDeclaredMethod("saveWindowsDescriptors", new Class[] { Path.class });
    method.setAccessible(true);/*from ww w .j av a  2s. co m*/

    final String tempPathPrefix = null;
    final Path tempDirectory = Files.createTempDirectory(Paths.get("."), tempPathPrefix);

    final String fileName = "Gracie.txt";

    try {
        final Path filePath = Files.createFile(Paths.get(tempDirectory.toString(), fileName));

        method.invoke(windowsMetadataStore, filePath);

        final BasicHeader basicHeader[] = new BasicHeader[3];
        basicHeader[0] = new BasicHeader(METADATA_PREFIX + KEY_OWNER,
                metadataMap.build().get(METADATA_PREFIX + KEY_OWNER));
        basicHeader[1] = new BasicHeader(METADATA_PREFIX + KEY_GROUP,
                metadataMap.build().get(METADATA_PREFIX + KEY_GROUP));
        basicHeader[2] = new BasicHeader(METADATA_PREFIX + MetadataKeyConstants.KEY_OS, localOS);
        final Metadata metadata = genMetadata(basicHeader);
        final WindowsMetadataRestore windowsMetadataRestore = new WindowsMetadataRestore(metadata,
                filePath.toString(), MetaDataUtil.getOS());
        windowsMetadataRestore.restoreOSName();
        windowsMetadataRestore.restoreUserAndOwner();

        final ImmutableMap.Builder<String, String> mMetadataMapAfterRestore = new ImmutableMap.Builder<>();
        final WindowsMetadataStore windowsMetadataStoreAfterRestore = new WindowsMetadataStore(
                mMetadataMapAfterRestore);
        final Class aClassAfterRestore = WindowsMetadataStore.class;
        final Method methodAfterRestore = aClassAfterRestore.getDeclaredMethod("saveWindowsDescriptors",
                new Class[] { Path.class });
        methodAfterRestore.setAccessible(true);
        methodAfterRestore.invoke(windowsMetadataStoreAfterRestore, filePath);

        Assert.assertEquals(mMetadataMapAfterRestore.build().get(METADATA_PREFIX + KEY_OWNER),
                basicHeader[0].getValue());
        Assert.assertEquals(mMetadataMapAfterRestore.build().get(METADATA_PREFIX + KEY_GROUP),
                basicHeader[1].getValue());
    } finally {
        FileUtils.deleteDirectory(tempDirectory.toFile());
    }
}