Example usage for java.nio.file Path toAbsolutePath

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

Introduction

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

Prototype

Path toAbsolutePath();

Source Link

Document

Returns a Path object representing the absolute path of this path.

Usage

From source file:ch.sourcepond.maven.plugin.jenkins.config.download.DownloaderImpl.java

@Override
public String downloadCliJar(final Log pLog, final Config pValidatedConfig) throws MojoExecutionException {
    try (final CloseableHttpClient client = clientFacade.newClient(pValidatedConfig)) {
        final String jenkinsVersion = determineJenkinsVersion(pLog, client, pValidatedConfig);

        final Path downloadedCliJar = getDownloadedCliJar(pValidatedConfig.getJenkinscliDirectory(),
                jenkinsVersion);// www.j  a  v a  2s  .c o  m

        if (!isRegularFile(downloadedCliJar)) {
            final HttpUriRequest request = clientFacade.newGet(pValidatedConfig.getCliJarUri());
            try {

                try (final CloseableHttpResponse response = client.execute(request)) {
                    final StatusLine statusLine = response.getStatusLine();

                    if (statusLine.getStatusCode() != SC_OK) {
                        throw new MojoExecutionException(messages.getMessage(DOWNLOADER_ERROR_WRONG_STATUS_CODE,
                                statusLine, pValidatedConfig.getCliJarUri()));
                    }

                    final HttpEntity entity = response.getEntity();

                    if (entity != null) {
                        try (final InputStream in = entity.getContent()) {
                            copy(in, downloadedCliJar);
                        }
                    } else {
                        throw new MojoExecutionException(messages.getMessage(DOWNLOADER_ERROR_ENTITY_IS_NULL,
                                pValidatedConfig.getCliJarUri()));
                    }
                }
            } finally {
                request.abort();
            }
        }

        final String absoluteDownloadedCliPath = downloadedCliJar.toAbsolutePath().toString();

        if (pLog.isInfoEnabled()) {
            pLog.info(messages.getMessage(DOWNLOADER_INFO_USED_CLI_JAR, absoluteDownloadedCliPath));
        }

        return absoluteDownloadedCliPath;
    } catch (final IOException | KeyManagementException | NoSuchAlgorithmException | KeyStoreException
            | CertificateException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepositoryHelper.java

private SshSessionFactory getSshSessionFactory(String remotePrivateKey, final Path tempKey) {
    try {/*from   w w w. ja  v a2  s. c  om*/

        Files.write(tempKey, remotePrivateKey.getBytes());
        SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
            @Override
            protected void configure(OpenSshConfig.Host hc, Session session) {
                Properties config = new Properties();
                config.put("StrictHostKeyChecking", "no");
                session.setConfig(config);
            }

            @Override
            protected JSch createDefaultJSch(FS fs) throws JSchException {
                JSch defaultJSch = super.createDefaultJSch(fs);
                defaultJSch.addIdentity(tempKey.toAbsolutePath().toString());
                return defaultJSch;
            }
        };
        return sshSessionFactory;
    } catch (IOException e) {
        logger.error("Failed to create private key for SSH connection.", e);
    }
    return null;
}

From source file:org.codice.ddf.configuration.migration.ExportMigrationEntryImplTest.java

@Test
public void testGetPropertyReferencedEntryWhenValueIsAbsoluteNotUnderDDFHome() throws Exception {
    final Path migratablePath = testFolder.newFile("test.cfg").toPath().toRealPath(LinkOption.NOFOLLOW_LINKS);
    final String migratableName = FilenameUtils.separatorsToUnix(migratablePath.toString());

    storeProperty(PROPERTY_NAME, migratablePath.toAbsolutePath().toString());

    final Optional<ExportMigrationEntry> oentry = entry.getPropertyReferencedEntry(PROPERTY_NAME,
            (r, v) -> true);//  ww w  .j  av  a  2s. c  om

    Assert.assertThat(oentry, OptionalMatchers.isPresent());
    final ExportMigrationEntry entry = oentry.get();

    Assert.assertThat(entry.getId(), Matchers.equalTo(MIGRATABLE_ID));
    Assert.assertThat(entry.getName(), Matchers.equalTo(migratableName));
    Assert.assertThat(entry.getPath(), Matchers.equalTo(migratablePath));
    // now check that it is a java property referenced entry that references the proper property
    // name
    Assert.assertThat(entry, Matchers.instanceOf(ExportMigrationJavaPropertyReferencedEntryImpl.class));
    final ExportMigrationJavaPropertyReferencedEntryImpl jentry = (ExportMigrationJavaPropertyReferencedEntryImpl) entry;

    Assert.assertThat(jentry.getProperty(), Matchers.equalTo(PROPERTY_NAME));
    // finally make sure no warnings or errors were recorded
    Assert.assertThat(report.hasErrors(), Matchers.equalTo(false));
    Assert.assertThat(report.hasWarnings(), Matchers.equalTo(false));
}

From source file:org.apache.openaz.xacml.std.pap.StdEngine.java

private PDPGroup initializeDefaultGroup(Path file, Properties properties) throws PAPException {
    ///*from   w ww.j  av  a  2  s.c o m*/
    // Make sure we have the default group
    //
    PDPGroup group = this.getDefaultGroup();
    if (group != null) {
        return group;
    }
    //
    // We don't have the default group, create it
    //
    String defaultId = properties.getProperty(PROP_PAP_GROUPS_DEFAULT, PROP_PAP_GROUPS_DEFAULT_NAME);
    logger.warn("Default group does NOT exist, creating " + defaultId);
    Path defaultPath = Paths.get(this.repository.toString(), defaultId);
    try {
        //
        // Does it exist?
        //
        if (Files.notExists(defaultPath)) {
            //
            // Create its directory
            //
            Files.createDirectory(defaultPath);
            //
            // Create property files
            //
            {
                Properties props = new Properties();
                props.setProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, "");
                props.setProperty(XACMLProperties.PROP_ROOTPOLICIES, "");
                Path policyPath = Paths.get(defaultPath.toAbsolutePath().toString(), "xacml.policy.properties");
                Files.createFile(policyPath);
                try (OutputStream os = Files.newOutputStream(policyPath)) {
                    props.store(os, "");
                } catch (IOException e) {
                    logger.error("Failed to write default policy properties", e);
                }
            }
            {
                Properties props = new Properties();
                props.setProperty(XACMLProperties.PROP_PIP_ENGINES, "");
                Path pipPath = Paths.get(defaultPath.toAbsolutePath().toString(), "xacml.pip.properties");
                Files.createFile(pipPath);
                try (OutputStream os = Files.newOutputStream(pipPath)) {
                    props.store(os, "");
                } catch (IOException e) {
                    logger.error("Failed to write default pip properties", e);
                }
            }
        }
        //
        // Create the default group
        //
        StdPDPGroup newDefault = new StdPDPGroup(defaultId, true, "default",
                "The default group where new PDP's are put.", defaultPath);
        //
        // Add it to our list
        //
        this.groups.add(newDefault);
        //
        // Save our properties out since we have
        // a new default group.
        //
        StdEngine.setGroupProperties(newDefault, properties);
        //
        // Save it to disk
        //
        try {
            try (OutputStream os = Files.newOutputStream(file)) {
                properties.store(os, "");
            }
        } catch (IOException e) {
            logger.error("Failed to save properties with new default group information.", e);
        }
        //
        // Return it
        //
        return newDefault;
    } catch (IOException e) {
        logger.error("Failed to create default group: " + defaultId, e);
        throw new PAPException("Failed to create default group");
    }
}

From source file:erigo.filewatch.FileWatch.java

/**
 * Creates a WatchService and registers the given directory
 *//*from  w  w w .  ja  v a 2s .  c  om*/
// FileWatch(Path watchDir, String outputFilename, Path outputDirI) throws IOException {
FileWatch(String[] argsI) throws IOException {

    //
    // Parse command line arguments
    //
    // 1. Setup command line options
    //
    Options options = new Options();
    // Boolean options (only the flag, no argument)
    options.addOption("h", "help", false, "Print this message.");
    options.addOption("a", "adjust_latency", false,
            "Divide latency results by 2 because test data files are from a recaster (round-trip).");
    options.addOption("d", "disp_recaster", false, "Display results when operating in recaster mode.");
    // Command line options that include an argument
    Option nextOption = Option.builder("i").argName("watchdir").hasArg().desc(
            "Directory to watch for incoming test data files (must be an existing directory); default = \""
                    + DEFAULT_WATCH_DIR + "\".")
            .build();
    options.addOption(nextOption);
    nextOption = Option.builder("o").argName("outfilename").hasArg()
            .desc("Name of the output metrics data file; must be a new file.").build();
    options.addOption(nextOption);
    nextOption = Option.builder("p").argName("pollinterval_msec").hasArg().desc(
            "Watch for new files by polling (don't use Java WatchService); sleep for <pollinterval_msec> (milliseconds) between scans.")
            .build();
    options.addOption(nextOption);
    nextOption = Option.builder("r").argName("recasterdir").hasArg()
            .desc("Recast test data files to the specified output directory (must be an existing directory).")
            .build();
    options.addOption(nextOption);
    nextOption = Option.builder("t").argName("plottitle").hasArg()
            .desc("Custom title for throughput and latency plots.").build();
    options.addOption(nextOption);

    //
    // 2. Parse command line options
    //
    CommandLineParser parser = new DefaultParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, argsI);
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Command line argument parsing failed: " + exp.getMessage());
        return;
    }

    //
    // 3. Retrieve the command line values
    //
    if (line.hasOption("h")) {
        // Display help message and quit
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(100);
        formatter.printHelp("FileWatch", options);
        return;
    }
    bAdjustLatencyMetrics = line.hasOption("a");
    bOutputResultsInRecastMode = line.hasOption("d");
    // Watch directory
    String watchDirName = line.getOptionValue("i", DEFAULT_WATCH_DIR);
    Path watchDir = Paths.get(watchDirName);
    if (!watchDir.toFile().isDirectory()) {
        System.err.println("\nThe given watch directory does not exist.");
        System.exit(-1);
    }
    // Recaster directory
    Path outputDirPath = null;
    String outputDirName = line.getOptionValue("r");
    if (outputDirName != null) {
        outputDirPath = Paths.get(outputDirName);
        if (!outputDirPath.toFile().isDirectory()) {
            System.err.println("\nThe given recaster output directory does not exist.");
            System.exit(-1);
        }
        // Make sure watchDir and outputDir aren't the same
        if (watchDir.toAbsolutePath().compareTo(outputDirPath.toAbsolutePath()) == 0) {
            System.err.println("\nThe recaster output directory cannot be the same as the watch directory.");
            System.exit(-1);
        }
        bRecast = true;
        outputDir = outputDirPath.toFile();
    }
    // Output filename
    String outputFilename = line.getOptionValue("o");
    if ((outputFilename == null) && (!bRecast || bOutputResultsInRecastMode)) {
        System.err.println("\nMust specify the name of the output data file.");
        System.exit(-1);
    }
    if (outputFilename != null) {
        File outputFile = new File(outputFilename);
        if (outputFile.isDirectory()) {
            System.err.println(
                    "\nThe given output data file is the name of a directory; must specify an output filename.");
            System.exit(-1);
        } else if (outputFile.isFile()) {
            System.err.println(
                    "\nThe given output data file is the name of an existing file; must specify a new filename.");
            System.exit(-1);
        }
    }
    // Use polling to check for new files?
    String pollIntervalStr = line.getOptionValue("p");
    if (pollIntervalStr != null) {
        try {
            pollInterval = Integer.parseInt(pollIntervalStr);
            if ((pollInterval <= 0) || (pollInterval > 1000)) {
                throw new NumberFormatException("Illegal value");
            }
        } catch (NumberFormatException nfe) {
            System.err.println("\nPoll interval must be an integer in the range 0 < x <= 1000");
            System.exit(-1);
        }
    }
    // Title for the throughput and latency plots
    customPlotTitle = line.getOptionValue("t", "");

    // Make sure "end.txt" doesn't already exist in the directory; this file is our signal
    // that we're done processing
    File endFile = new File(watchDir.toFile(), "end.txt");
    if (endFile.exists()) {
        System.err.println("\nMust delete \"" + endFile + "\" before running test.");
        System.exit(-1);
    }
    // If we are recasting, make sure "end.txt" doesn't exist in the output directory either
    if (outputDirPath != null) {
        endFile = new File(outputDirPath.toFile(), "end.txt");
        if (endFile.exists()) {
            System.err.println("\nMust delete \"" + endFile + "\" in output directory before running test.");
            System.exit(-1);
        }
    }

    if (pollInterval > 0) {
        System.err
                .println("\nWatching directory \"" + watchDir + "\" for incoming files; using polling method");
        processEvents_polling(watchDir.toFile());
    } else {
        // Register the directory with the WatchService
        // Only collect data for ENTRY_CREATE events.  Even if a file is just
        // copied into a directory, several ENTRY_MODIFY events can be
        // triggered because the file's content and its parameters (such as
        // timestamp) are independently set.
        watchDir.register(watcher, new WatchEvent.Kind[] { StandardWatchEventKinds.ENTRY_CREATE },
                SensitivityWatchEventModifier.HIGH);
        System.err.println(
                "\nWatching directory \"" + watchDir + "\" for incoming files; using WatchService events");
        processEvents_watchservice();
        watcher.close();
    }

    if (!bRecast || bOutputResultsInRecastMode) {
        System.err.println("\nWrite data to file \"" + outputFilename + "\"...");
    }
    processData(outputFilename);

    System.err.println(
            "\nFileWatch received a total of " + num_received_files + " files (not including \"end.txt\")");
    System.err
            .println("In processing, " + num_skipped_files + " files were skipped (due to wrong name format)");
    int num_files_processed = num_received_files - num_skipped_files;
    System.err.println(
            "Thus, a total of " + num_files_processed + " files with properly formatted names were processed");

    System.err.println("\nTest is complete.");

}

From source file:me.ryanhamshire.griefprevention.FlatFileDataStore.java

@Override
public void loadWorldData(World world) {
    WorldProperties worldProperties = world.getProperties();
    DimensionType dimType = worldProperties.getDimensionType();
    Path dimPath = rootConfigPath.resolve(((IMixinDimensionType) dimType).getModId())
            .resolve(((IMixinDimensionType) dimType).getEnumName());
    if (!Files.exists(dimPath.resolve(worldProperties.getWorldName()))) {
        try {/* w w  w.j  a  v a2s  .  c om*/
            Files.createDirectories(dimPath.resolve(worldProperties.getWorldName()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // create/load configs
    // create dimension config
    DataStore.dimensionConfigMap.put(worldProperties.getUniqueId(),
            new GriefPreventionConfig<DimensionConfig>(Type.DIMENSION, dimPath.resolve("dimension.conf")));
    // create world config
    DataStore.worldConfigMap.put(worldProperties.getUniqueId(), new GriefPreventionConfig<>(Type.WORLD,
            dimPath.resolve(worldProperties.getWorldName()).resolve("world.conf")));

    GPClaimManager claimWorldManager = new GPClaimManager(worldProperties);
    this.claimWorldManagers.put(worldProperties.getUniqueId(), claimWorldManager);

    // check if world has existing data
    Path oldWorldDataPath = rootWorldSavePath.resolve(worldProperties.getWorldName()).resolve(claimDataPath);
    Path oldPlayerDataPath = rootWorldSavePath.resolve(worldProperties.getWorldName()).resolve(playerDataPath);
    if (worldProperties.getUniqueId() == Sponge.getGame().getServer().getDefaultWorld().get().getUniqueId()) {
        oldWorldDataPath = rootWorldSavePath.resolve(claimDataPath);
        oldPlayerDataPath = rootWorldSavePath.resolve(playerDataPath);
    }

    if (DataStore.USE_GLOBAL_PLAYER_STORAGE) {
        // use global player data
        oldPlayerDataPath = rootWorldSavePath.resolve(playerDataPath);
    }

    Path newWorldDataPath = dimPath.resolve(worldProperties.getWorldName());

    try {
        // Check for old data location
        if (Files.exists(oldWorldDataPath)) {
            GriefPreventionPlugin.instance.getLogger().info("Detected GP claim data in old location.");
            GriefPreventionPlugin.instance.getLogger().info("Migrating GP claim data from "
                    + oldWorldDataPath.toAbsolutePath() + " to " + newWorldDataPath.toAbsolutePath() + "...");
            FileUtils.moveDirectoryToDirectory(oldWorldDataPath.toFile(), newWorldDataPath.toFile(), true);
            GriefPreventionPlugin.instance.getLogger().info("Done.");
        }
        if (Files.exists(oldPlayerDataPath)) {
            GriefPreventionPlugin.instance.getLogger().info("Detected GP player data in old location.");
            GriefPreventionPlugin.instance.getLogger().info("Migrating GP player data from "
                    + oldPlayerDataPath.toAbsolutePath() + " to " + newWorldDataPath.toAbsolutePath() + "...");
            FileUtils.moveDirectoryToDirectory(oldPlayerDataPath.toFile(), newWorldDataPath.toFile(), true);
            GriefPreventionPlugin.instance.getLogger().info("Done.");
        }

        // Create data folders if they do not exist
        if (!Files.exists(newWorldDataPath.resolve("ClaimData"))) {
            Files.createDirectories(newWorldDataPath.resolve("ClaimData"));
        }
        if (DataStore.USE_GLOBAL_PLAYER_STORAGE) {
            if (!globalPlayerDataPath.toFile().exists()) {
                Files.createDirectories(globalPlayerDataPath);
            }
        } else if (!Files.exists(newWorldDataPath.resolve("PlayerData"))) {
            Files.createDirectories(newWorldDataPath.resolve("PlayerData"));
        }

        // Migrate RedProtectData if enabled
        if (GriefPreventionPlugin.getGlobalConfig().getConfig().migrator.redProtectMigrator) {
            Path redProtectFilePath = redProtectDataPath
                    .resolve("data_" + worldProperties.getWorldName() + ".conf");
            Path gpMigratedPath = redProtectDataPath.resolve("gp_migrated_" + worldProperties.getWorldName());
            if (Files.exists(redProtectFilePath) && !Files.exists(gpMigratedPath)) {
                RedProtectMigrator.migrate(world, redProtectFilePath, newWorldDataPath.resolve("ClaimData"));
                Files.createFile(gpMigratedPath);
            }
        }
        // Migrate Polis data if enabled
        if (GriefPreventionPlugin.getGlobalConfig().getConfig().migrator.polisMigrator) {
            Path claimsFilePath = polisDataPath.resolve("claims.conf");
            Path teamsFilePath = polisDataPath.resolve("teams.conf");
            Path gpMigratedPath = polisDataPath.resolve("gp_migrated_" + worldProperties.getWorldName());
            if (Files.exists(claimsFilePath) && Files.exists(teamsFilePath) && !Files.exists(gpMigratedPath)) {
                PolisMigrator.migrate(world, claimsFilePath, teamsFilePath,
                        newWorldDataPath.resolve("ClaimData"));
                Files.createFile(gpMigratedPath);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Load Claim Data
    try {
        File[] files = newWorldDataPath.resolve("ClaimData").toFile().listFiles();
        if (files != null && files.length > 0) {
            this.loadClaimData(files, worldProperties);
            GriefPreventionPlugin.instance.getLogger()
                    .info("[" + worldProperties.getWorldName() + "] " + files.length + " total claims loaded.");
        }

        if (GriefPreventionPlugin.getGlobalConfig().getConfig().playerdata.useGlobalPlayerDataStorage) {
            files = globalPlayerDataPath.toFile().listFiles();
        } else {
            files = newWorldDataPath.resolve("PlayerData").toFile().listFiles();
        }
        if (files != null && files.length > 0) {
            this.loadPlayerData(worldProperties, files);
        }

        // If a wilderness claim was not loaded, create a new one
        if (claimWorldManager.getWildernessClaim() == null) {
            claimWorldManager.createWildernessClaim(worldProperties);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    // handle default flag permissions
    this.setupDefaultPermissions(world);
}

From source file:com.qwazr.extractor.ParserTest.java

/**
 * Test inputstream and file parsing/*from w w w . j av a2  s. c o  m*/
 *
 * @param className
 * @param fileName
 * @param keyValueParams
 * @throws Exception
 */
protected ParserResult doTest(Class<? extends ParserAbstract> className, String fileName,
        String expectedMimeType, String expectedField, String expectedText, String... keyValueParams)
        throws Exception {
    LOGGER.info("Testing " + className);

    UriBuilder uriBuilder = new JerseyUriBuilder().uri("http://localhost:9090");
    for (int i = 0; i < keyValueParams.length; i += 2)
        uriBuilder.queryParam(keyValueParams[i], keyValueParams[i + 1]);
    final UriInfo uriInfo = new UriInfoImpl(new URI("http://localhost:9090"), uriBuilder.build());

    final String parserName = StringUtils.removeEnd(className.getSimpleName(), "Parser").toLowerCase();

    // Test service name
    assert service.list().contains(parserName);

    // Check ParserDefinition
    final ParserDefinition parserDefinition = (ParserDefinition) service.get(uriInfo, parserName, null);
    assert parserDefinition != null;
    if (expectedMimeType != null && parserDefinition.mimeTypes != null)
        assert Arrays.asList(parserDefinition.mimeTypes).contains(expectedMimeType);

    final ParserDefinition serialParserDefinition = ObjectMappers.JSON
            .readValue(ObjectMappers.JSON.writeValueAsString(parserDefinition), ParserDefinition.class);
    assert Objects.equals(parserDefinition, serialParserDefinition);

    Path tempFile = getTempFile(fileName);

    // Test stream
    ParserInterface parser = createRegisterInstance(className);

    ParserResultBuilder resultBuilder = new ParserResultBuilder(parser);
    parser.parseContent(uriInfo.getQueryParameters(), getStream(fileName), FilenameUtils.getExtension(fileName),
            null, resultBuilder);
    ParserResult parserResult = resultBuilder.build();
    assert (parserResult != null);

    checkIsMimeType(parser, parserResult, expectedMimeType);

    checkContainsText(parserResult, expectedField, expectedText);

    // Test file
    parser = createRegisterInstance(className);
    resultBuilder = new ParserResultBuilder(parser);
    parser.parseContent(uriInfo.getQueryParameters(), tempFile, null, null, resultBuilder);
    assert (parserResult != null);
    checkContainsText(parserResult, expectedField, expectedText);

    // No magic to test if the parser doesn't support detection
    if (parser.getDefaultMimeTypes() == null && parser.getDefaultExtensions() == null)
        return parserResult;

    // Test stream with magic mime service
    parserResult = service.putMagic(uriInfo, fileName, null, null, getStream(fileName));
    assert (parserResult != null);
    checkContainsText(parserResult, expectedField, expectedText);

    // Test path with magic mime service
    parserResult = service.putMagic(uriInfo, fileName, tempFile.toAbsolutePath().toString(), null, null);
    assert (parserResult != null);
    checkContainsText(parserResult, expectedField, expectedText);

    return parserResult;
}

From source file:org.apache.storm.localizer.LocallyCachedTopologyBlob.java

@Override
public long downloadToTempLocation(ClientBlobStore store)
        throws IOException, KeyNotFoundException, AuthorizationException {
    if (isLocalMode && type == TopologyBlobType.TOPO_JAR) {
        LOG.debug("DOWNLOADING LOCAL JAR to TEMP LOCATION... {}", topologyId);
        //This is a special case where the jar was not uploaded so we will not download it (it is already on the classpath)
        ClassLoader classloader = Thread.currentThread().getContextClassLoader();
        String resourcesJar = resourcesJar();
        URL url = classloader.getResource(ServerConfigUtils.RESOURCES_SUBDIR);
        Path extractionDest = topologyBasicBlobsRootDir
                .resolve(type.getTempExtractionDir(LOCAL_MODE_JAR_VERSION));
        if (resourcesJar != null) {
            LOG.info("Extracting resources from jar at {} to {}", resourcesJar, extractionDest);
            extractDirFromJar(resourcesJar, ServerConfigUtils.RESOURCES_SUBDIR, extractionDest);
        } else if (url != null) {
            LOG.info("Copying resources at {} to {}", url, extractionDest);
            if ("jar".equals(url.getProtocol())) {
                JarURLConnection urlConnection = (JarURLConnection) url.openConnection();
                extractDirFromJar(urlConnection.getJarFileURL().getFile(), ServerConfigUtils.RESOURCES_SUBDIR,
                        extractionDest);
            } else {
                fsOps.copyDirectory(new File(url.getFile()), extractionDest.toFile());
            }// w  w  w.j  a v  a2 s . co m
        }
        return LOCAL_MODE_JAR_VERSION;
    }

    long newVersion;
    Path tmpLocation;
    String key = type.getKey(topologyId);
    try (InputStreamWithMeta in = store.getBlob(key)) {
        newVersion = in.getVersion();
        long expectedSize = in.getFileLength();
        if (newVersion == version) {
            throw new RuntimeException(
                    "The version did not change, but we tried to download it. " + version + " " + key);
        }
        tmpLocation = topologyBasicBlobsRootDir.resolve(type.getTempFileName(newVersion));
        long totalRead = 0;
        //Make sure the parent directory is there and ready to go
        fsOps.forceMkdir(tmpLocation.getParent());
        try (OutputStream outStream = fsOps.getOutputStream(tmpLocation.toFile())) {
            byte[] buffer = new byte[4096];
            int read = 0;
            while ((read = in.read(buffer)) > 0) {
                outStream.write(buffer, 0, read);
                totalRead += read;
            }
        }
        if (totalRead != expectedSize) {
            throw new IOException(
                    "We expected to download " + expectedSize + " bytes but found we got " + totalRead);
        }
    }

    if (type.needsExtraction()) {
        Path extractionDest = topologyBasicBlobsRootDir.resolve(type.getTempExtractionDir(newVersion));
        extractDirFromJar(tmpLocation.toAbsolutePath().toString(), ServerConfigUtils.RESOURCES_SUBDIR,
                extractionDest);
    }
    return newVersion;
}

From source file:org.codice.ddf.catalog.content.impl.FileSystemStorageProvider.java

private ContentItem readContent(URI uri) throws StorageException {
    Path file = getContentFilePath(uri);

    if (file == null) {
        throw new StorageException("Unable to find file for content ID: " + uri.getSchemeSpecificPart());
    }//from w  ww.j  a  v a 2 s.c  om

    String extension = FilenameUtils.getExtension(file.getFileName().toString());

    String mimeType;

    try (InputStream fileInputStream = Files.newInputStream(file)) {
        mimeType = mimeTypeMapper.guessMimeType(fileInputStream, extension);
    } catch (Exception e) {
        LOGGER.warn("Could not determine mime type for file extension = {}; defaulting to {}", extension,
                DEFAULT_MIME_TYPE);
        mimeType = DEFAULT_MIME_TYPE;
    }
    if (mimeType == null || DEFAULT_MIME_TYPE.equals(mimeType)) {
        try {
            mimeType = Files.probeContentType(file);
        } catch (IOException e) {
            LOGGER.warn("Unable to determine mime type using Java Files service.", e);
            mimeType = DEFAULT_MIME_TYPE;
        }
    }

    LOGGER.debug("mimeType = {}", mimeType);
    long size = 0;
    try {
        size = Files.size(file);
    } catch (IOException e) {
        LOGGER.warn("Unable to retrieve size of file: {}", file.toAbsolutePath().toString(), e);
    }
    return new ContentItemImpl(uri.getSchemeSpecificPart(), uri.getFragment(),
            com.google.common.io.Files.asByteSource(file.toFile()), mimeType, file.getFileName().toString(),
            size, null);
}

From source file:org.apache.nifi.minifi.FlowParser.java

/**
 * Generates a {@link Document} from the flow configuration file provided
 *//*from   w  w w .  jav  a 2 s .c  o  m*/
public Document parse(final File flowConfigurationFile) {
    if (flowConfigurationFile == null) {
        logger.debug("Flow Configuration file was null");
        return null;
    }

    // if the flow doesn't exist or is 0 bytes, then return null
    final Path flowPath = flowConfigurationFile.toPath();
    try {
        if (!Files.exists(flowPath) || Files.size(flowPath) == 0) {
            logger.warn("Flow Configuration does not exist or was empty");
            return null;
        }
    } catch (IOException e) {
        logger.error("An error occurred determining the size of the Flow Configuration file");
        return null;
    }

    // otherwise create the appropriate input streams to read the file
    try (final InputStream in = Files.newInputStream(flowPath, StandardOpenOption.READ);
            final InputStream gzipIn = new GZIPInputStream(in)) {

        final byte[] flowBytes = IOUtils.toByteArray(gzipIn);
        if (flowBytes == null || flowBytes.length == 0) {
            logger.warn("Could not extract root group id because Flow Configuration File was empty");
            return null;
        }

        final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setNamespaceAware(true);
        docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

        // parse the flow
        final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        docBuilder.setErrorHandler(new LoggingXmlParserErrorHandler("Flow Configuration", logger));
        final Document document = docBuilder.parse(new ByteArrayInputStream(flowBytes));
        return document;

    } catch (final SAXException | ParserConfigurationException | IOException ex) {
        logger.error("Unable to parse flow {} due to {}", new Object[] { flowPath.toAbsolutePath(), ex });
        return null;
    }
}