Example usage for java.nio.file Path resolve

List of usage examples for java.nio.file Path resolve

Introduction

In this page you can find the example usage for java.nio.file Path resolve.

Prototype

default Path resolve(String other) 

Source Link

Document

Converts a given path string to a Path and resolves it against this Path in exactly the manner specified by the #resolve(Path) resolve method.

Usage

From source file:org.eclipse.cdt.arduino.core.internal.board.Platform.java

public IStatus install(IProgressMonitor monitor) throws CoreException {
    try {/*from  w w  w  .ja  v  a2  s.  c om*/
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpGet get = new HttpGet(url);
            try (CloseableHttpResponse response = client.execute(get)) {
                if (response.getStatusLine().getStatusCode() >= 400) {
                    return new Status(IStatus.ERROR, Activator.getId(),
                            response.getStatusLine().getReasonPhrase());
                } else {
                    HttpEntity entity = response.getEntity();
                    if (entity == null) {
                        return new Status(IStatus.ERROR, Activator.getId(), Messages.ArduinoBoardManager_1);
                    }
                    // the archive has the version number as the root
                    // directory
                    Path installPath = getInstallPath().getParent();
                    Files.createDirectories(installPath);
                    Path archivePath = installPath.resolve(archiveFileName);
                    Files.copy(entity.getContent(), archivePath, StandardCopyOption.REPLACE_EXISTING);

                    // extract
                    ArchiveInputStream archiveIn = null;
                    try {
                        String compressor = null;
                        String archiver = null;
                        if (archiveFileName.endsWith("tar.bz2")) { //$NON-NLS-1$
                            compressor = CompressorStreamFactory.BZIP2;
                            archiver = ArchiveStreamFactory.TAR;
                        } else if (archiveFileName.endsWith(".tar.gz") || archiveFileName.endsWith(".tgz")) { //$NON-NLS-1$ //$NON-NLS-2$
                            compressor = CompressorStreamFactory.GZIP;
                            archiver = ArchiveStreamFactory.TAR;
                        } else if (archiveFileName.endsWith(".tar.xz")) { //$NON-NLS-1$
                            compressor = CompressorStreamFactory.XZ;
                            archiver = ArchiveStreamFactory.TAR;
                        } else if (archiveFileName.endsWith(".zip")) { //$NON-NLS-1$
                            archiver = ArchiveStreamFactory.ZIP;
                        }

                        InputStream in = new BufferedInputStream(new FileInputStream(archivePath.toFile()));
                        if (compressor != null) {
                            in = new CompressorStreamFactory().createCompressorInputStream(compressor, in);
                        }
                        archiveIn = new ArchiveStreamFactory().createArchiveInputStream(archiver, in);

                        for (ArchiveEntry entry = archiveIn.getNextEntry(); entry != null; entry = archiveIn
                                .getNextEntry()) {
                            if (entry.isDirectory()) {
                                continue;
                            }

                            // TODO check for soft links in tar files.
                            Path entryPath = installPath.resolve(entry.getName());
                            Files.createDirectories(entryPath.getParent());
                            Files.copy(archiveIn, entryPath, StandardCopyOption.REPLACE_EXISTING);
                        }
                    } finally {
                        if (archiveIn != null) {
                            archiveIn.close();
                        }
                    }
                }
            }
        }
        return Status.OK_STATUS;
    } catch (IOException | CompressorException | ArchiveException e) {
        throw new CoreException(new Status(IStatus.ERROR, Activator.getId(), "Installing Platform", e));
    }
}

From source file:com.facebook.buck.java.JarDirectoryStepTest.java

@Test
public void jarsShouldContainDirectoryEntries() throws IOException {
    Path zipup = folder.newFolder("dir-zip");

    Path subdir = zipup.resolve("dir/subdir");
    Files.createDirectories(subdir);
    Files.write(subdir.resolve("a.txt"), "cake".getBytes());

    JarDirectoryStep step = new JarDirectoryStep(new ProjectFilesystem(zipup), Paths.get("output.jar"),
            ImmutableSet.of(zipup), /* main class */ null, /* manifest file */ null);
    ExecutionContext context = TestExecutionContext.newInstance();

    int returnCode = step.execute(context);

    assertEquals(0, returnCode);//ww  w.j  a  v a 2 s  . co  m

    Path zip = zipup.resolve("output.jar");
    assertTrue(Files.exists(zip));

    // Iterate over each of the entries, expecting to see the directory names as entries.
    Set<String> expected = Sets.newHashSet("dir/", "dir/subdir/");
    try (ZipInputStream is = new ZipInputStream(Files.newInputStream(zip))) {
        for (ZipEntry entry = is.getNextEntry(); entry != null; entry = is.getNextEntry()) {
            expected.remove(entry.getName());
        }
    }
    assertTrue("Didn't see entries for: " + expected, expected.isEmpty());
}

From source file:com.facebook.buck.java.JarDirectoryStepTest.java

@Test
public void shouldNotThrowAnExceptionWhenAddingDuplicateEntries() throws IOException {
    Path zipup = folder.newFolder("zipup");

    Path first = createZip(zipup.resolve("a.zip"), "example.txt");
    Path second = createZip(zipup.resolve("b.zip"), "example.txt", "com/example/Main.class");

    JarDirectoryStep step = new JarDirectoryStep(new ProjectFilesystem(zipup), Paths.get("output.jar"),
            ImmutableSet.of(first.getFileName(), second.getFileName()), "com.example.Main",
            /* manifest file */ null);
    ExecutionContext context = TestExecutionContext.newInstance();

    int returnCode = step.execute(context);

    assertEquals(0, returnCode);/*from   www.  j  a v  a 2  s.  com*/

    Path zip = zipup.resolve("output.jar");
    assertTrue(Files.exists(zip));

    // "example.txt" "Main.class" and the MANIFEST.MF.
    assertZipFileCountIs(3, zip);
    assertZipContains(zip, "example.txt");
}

From source file:io.stallion.fileSystem.FileSystemWatcherRunner.java

private void doRun() {
    while (shouldRun) {
        Log.fine("Running the file system watcher.");
        WatchKey key;//from ww w  . ja  v a2  s . c o  m
        try {
            key = watcher.take();
        } catch (InterruptedException x) {
            Log.warn("Interuppted the watcher!!!");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Log.info("Exit watcher run method.");
                return;
            }
            continue;
        }
        Log.fine("Watch event key taken. Runner instance is {0}", this.hashCode());

        for (WatchEvent<?> event : key.pollEvents()) {

            WatchEvent.Kind<?> kind = event.kind();
            Log.fine("Event is " + kind);
            // This key is registered only
            // for ENTRY_CREATE events,
            // but an OVERFLOW event can
            // occur regardless if events
            // are lost or discarded.
            if (kind == OVERFLOW) {
                continue;
            }

            // The filename is the
            // context of the event.
            WatchEvent<Path> ev = (WatchEvent<Path>) event;
            Path filename = ev.context();

            // Ignore emacs autosave files
            if (filename.toString().contains(".#")) {
                continue;
            }
            Log.finer("Changed file is {0}", filename);
            Path directory = (Path) key.watchable();
            Log.finer("Changed directory is {0}", directory);
            Path fullPath = directory.resolve(filename);
            Log.fine("Changed path is {0}", fullPath);
            Boolean handlerFound = false;
            for (IWatchEventHandler handler : watchedByPath.values()) {
                Log.finer("Checking matching handler {0} {1}", handler.getInternalHandlerLabel(),
                        handler.getWatchedFolder());
                // Ignore private files
                if (filename.getFileName().startsWith(".")) {
                    continue;
                }
                if ((handler.getWatchedFolder().equals(directory.toAbsolutePath().toString())
                        || (handler.getWatchTree() && directory.startsWith(handler.getWatchedFolder())))
                        && (StringUtils.isEmpty(handler.getExtension())
                                || fullPath.toString().endsWith(handler.getExtension()))) {
                    String relativePath = filename.getFileName().toString();
                    Log.info("Handling {0} with watcher {1} for folder {2}", filename,
                            handler.getClass().getName(), handler.getWatchedFolder());
                    try {
                        handler.handle(relativePath, fullPath.toString(), kind, event);
                        handlerFound = true;
                    } catch (Exception e) {
                        Log.exception(e, "Exception processing path={0} handler={1}", relativePath,
                                handler.getClass().getName());
                    }
                }
            }
            if (!handlerFound) {
                Log.info("No handler found for {0}", fullPath);
            }
        }
        // Reset the key -- this step is critical if you want to
        // receive further watch events.  If the key is no longer valid,
        // the directory is inaccessible so exit the loop.
        boolean valid = key.reset();
        if (!valid) {
            Log.warn("Key invalid! Exit watch.");
            break;
        }
    }
}

From source file:ee.ria.xroad.confproxy.util.OutputBuilder.java

/**
 * Opens a stream for writing the configuration file describes by the metadata to the target location.
 * @param targetPath location to write the file to
 * @param metadata describes the configuration file
 * @return output stream for writing the file
 * @throws Exception if errors during file operations occur
 *//*  ww w.j  av a 2s.  co  m*/
private FileOutputStream createFileOutputStream(final Path targetPath, final ConfigurationPartMetadata metadata)
        throws Exception {
    Path filepath = targetPath
            .resolve(Paths.get(metadata.getInstanceIdentifier(), metadata.getContentLocation()));
    Files.createDirectories(filepath.getParent());
    Path newFile = Files.createFile(filepath);

    log.debug("Copying file '{}' to directory '{}'", newFile.toAbsolutePath(), targetPath);

    return new FileOutputStream(newFile.toAbsolutePath().toFile());
}

From source file:edu.usc.goffish.gofs.partition.gml.GMLPartitionerTest.java

public void testPartitioner() throws IOException {
    Path outputDir = Files.createTempDirectory("gofs_test");
    try {//  w  w  w .  j  a  va  2 s. c o  m
        _partitioner.partitionTemplate(ClassLoader.getSystemResourceAsStream("simple_graph_template.gml"),
                outputDir, "partition_", "_template.gml");
        // TODO: test instance partitions

        Path p1_t = outputDir.resolve("partition_1_template.gml");
        // Path p1_i1 = _outputDir.resolve("partition_1_instance1.gml");
        GMLPartition p1 = GMLPartition.parseGML(1, new WCCComponentizer(), Files.newInputStream(p1_t),
                Collections.<InputStream>emptyList());

        ISubgraph s10 = p1.iterator().next();

        assertTrue(s10.getTemplate().isDirected());
        assertTrue(s10.containsVertex(1));
        assertTrue(s10.containsVertex(2));
        assertTrue(s10.containsVertex(3));
        assertTrue(s10.getVertex(1).containsOutEdgeTo(s10.getVertex(2)));
        assertFalse(s10.getVertex(2).containsOutEdgeTo(s10.getVertex(1)));
        assertFalse(s10.getVertex(1).isRemote());
        assertFalse(s10.getVertex(2).isRemote());
        assertTrue(s10.getVertex(3).isRemote());
        assertEquals(2, s10.getVertex(3).getRemotePartitionId());

        Path p2_t = outputDir.resolve("partition_2_template.gml");
        // Path p2_i1 = _outputDir.resolve("partition_2_instance1.gml");
        GMLPartition p2 = GMLPartition.parseGML(1, new WCCComponentizer(), Files.newInputStream(p2_t),
                Collections.<InputStream>emptyList());

        ISubgraph s20 = p2.iterator().next();

        assertTrue(s20.isDirected());
        assertFalse(s20.containsVertex(1));
        assertFalse(s20.containsVertex(2));
        assertTrue(s20.containsVertex(3));
        assertTrue(s20.containsVertex(4));
        assertTrue(s20.getVertex(3).containsOutEdgeTo(s20.getVertex(4)));
        assertFalse(s20.getVertex(4).containsOutEdgeTo(s20.getVertex(3)));
        assertFalse(s20.getVertex(3).isRemote());
        assertFalse(s20.getVertex(4).isRemote());
    } finally {
        FileUtils.deleteQuietly(outputDir.toFile());
    }
}

From source file:io.github.dsheirer.gui.SDRTrunk.java

/**
 * Loads the application properties file from the user's home directory,
 * creating the properties file for the first-time, if necessary
 *//*from  ww  w  . j  a  v a  2 s.  c o m*/
private void loadProperties(Path homePath) {
    Path propsPath = homePath.resolve("SDRTrunk.properties");

    if (!Files.exists(propsPath)) {
        try {
            mLog.info("SDRTrunk - creating application properties file [" + propsPath.toAbsolutePath() + "]");

            Files.createFile(propsPath);
        } catch (IOException e) {
            mLog.error("SDRTrunk - couldn't create application properties " + "file ["
                    + propsPath.toAbsolutePath(), e);
        }
    }

    if (Files.exists(propsPath)) {
        SystemProperties.getInstance().load(propsPath);
    } else {
        mLog.error("SDRTrunk - couldn't find or recreate the SDRTrunk " + "application properties file");
    }
}

From source file:be.ugent.psb.coexpnetviz.io.JobServer.java

/**
 * Submit run and store the unpacked result in the local file system, synchronously
 * //from w  ww  .j  av  a  2s .c  o  m
 * @throws InterruptedException
 * @throws IOException
 * @throws JobServerException
 * @return Path to unpacked result  
 */
public void runJob(JobDescription job) throws InterruptedException, IOException, JobServerException {
    // Post request and retrieve result
    Path tempDirectory = null;
    try {
        // Run job on server, which returns a tgz archive
        tempDirectory = Files.createTempDirectory("coexpnetviz_result");
        Path packedResultPath = tempDirectory.resolve("network.tgz");
        HttpEntity postEntity = makeRequestEntity(job);
        executeJobOnServer(postEntity, packedResultPath);

        // Unpack the tgz result
        Archiver archiver = ArchiverFactory.createArchiver(packedResultPath.toFile());
        archiver.extract(packedResultPath.toFile(), tempDirectory.toFile());

        // Move to the right spot
        Files.move(tempDirectory.resolve("network"), job.getResultPath());
    } finally {
        if (tempDirectory != null)
            FileUtils.deleteDirectory(tempDirectory.toFile());
    }
}

From source file:com.gs.obevo.db.impl.platforms.oracle.OracleReveng.java

@Override
protected File printInstructions(PrintStream out, AquaRevengArgs args) {
    DbEnvironment env = getDbEnvironment(args);

    JdbcDataSourceFactory jdbcFactory = new OracleJdbcDataSourceFactory();
    DataSource ds = jdbcFactory.createDataSource(env, new Credential(args.getUsername(), args.getPassword()),
            1);/*from w w  w.  j av  a2  s .  com*/
    JdbcHelper jdbc = new JdbcHelper(null, false);

    Path interim = new File(args.getOutputPath(), "interim").toPath();
    interim.toFile().mkdirs();
    try (Connection conn = ds.getConnection();
            BufferedWriter fileWriter = Files.newBufferedWriter(interim.resolve("output.sql"),
                    Charset.defaultCharset())) {
        // https://docs.oracle.com/database/121/ARPLS/d_metada.htm#BGBJBFGE
        // Note - can't remap schema name, object name, tablespace name within JDBC calls; we will leave that to the existing code in AbstractDdlReveng
        jdbc.update(conn,
                "{ CALL DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'STORAGE',false) }");

        MutableList<Map<String, Object>> maps = jdbc.queryForList(conn,
                "SELECT CASE WHEN OBJECT_TYPE = 'TABLE' THEN 1 WHEN OBJECT_TYPE = 'INDEX' THEN 2 ELSE 3 END SORT_ORDER,\n"
                        + "    OBJECT_TYPE,\n"
                        + "    dbms_metadata.get_ddl(REPLACE(object_type,' ','_'), object_name, owner) || ';' AS object_ddl\n"
                        + "FROM DBA_OBJECTS WHERE OWNER = '" + args.getDbSchema()
                        + "' AND OBJECT_TYPE NOT IN ('PACKAGE BODY', 'LOB','MATERIALIZED VIEW', 'TABLE PARTITION')\n"
                        + "ORDER BY 1");

        for (Map<String, Object> map : maps) {
            Clob clobObject = (Clob) map.get("OBJECT_DDL");
            InputStream in = clobObject.getAsciiStream();
            StringWriter w = new StringWriter();
            try {
                IOUtils.copy(in, w);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            String clobAsString = w.toString();
            clobAsString = clobAsString.replaceAll(";.*$", "");

            LOG.debug("Content for {}: ", map.get("OBJECT_TYPE"), clobAsString);
            fileWriter.write(clobAsString);
            fileWriter.newLine();
            fileWriter.write("~");
            fileWriter.newLine();
        }
    } catch (SQLException | IOException e) {
        throw new RuntimeException(e);
    }

    return interim.toFile();
}

From source file:com.thinkbiganalytics.util.TableType.java

public String deriveLocationSpecification(Path tableLocation, String source, String entity) {

    Validate.notNull(tableLocation, "tableLocation expected");
    Validate.notNull(source, "source expected");
    Validate.notNull(entity, "entity expected");

    Path path = tableLocation.resolve(source).resolve(entity).resolve(tableSuffix);
    String location = path.toString().replace(":/", "://");

    StringBuffer sb = new StringBuffer();
    sb.append(" LOCATION '");

    sb.append(location).append("'");

    return sb.toString();
}