Example usage for java.nio.file Path toFile

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

Introduction

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

Prototype

default File toFile() 

Source Link

Document

Returns a File object representing this path.

Usage

From source file:io.uploader.drive.drive.DriveOperations.java

private static String findMineType(Path path) {
    if (path == null) {
        return null;
    }/*w w  w  . j av  a2  s .  com*/
    try {
        //return Files.probeContentType(path) ;
        return tika.detect(new FileInputStream(path.toFile()));
    } catch (IOException e) {
        logger.error("Error occurred while attempting to determine the mine type of " + path.toString(), e);
        return null;
    }
}

From source file:com.ttech.cordovabuild.infrastructure.archive.ArchiveUtils.java

public static void compressDirectory(Path path, OutputStream output) {
    try {/*w  ww. j a v a 2  s.  c  om*/
        // Wrap the output file stream in streams that will tar and gzip everything
        TarArchiveOutputStream taos = new TarArchiveOutputStream(new GZIPOutputStream(output));
        // TAR has an 8 gig file limit by default, this gets around that
        taos.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_STAR); // to get past the 8 gig limit
        // TAR originally didn't support long file names, so enable the support for it
        taos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
        for (File child : path.toFile().listFiles()) {
            addFileToTarGz(taos, child.toPath(), "");
        }
        taos.close();
    } catch (IOException e) {
        throw new ApplicationSourceException(e);
    }
}

From source file:de.unirostock.sems.cbarchive.web.Tools.java

/**
 * writes a input stream entirely into a newly created temp file.
 * Closes all streams afterwards/*from   www.jav  a 2 s.  c o  m*/
 *
 * @param tempFileName the temp file name
 * @param input the input
 * @return Path to temp file
 * @throws IOException the IO exception
 */
public static Path writeStreamToTempFile(String tempFileName, InputStream input) throws IOException {

    // copy the stream to a temp file
    Path temp = Files.createTempFile(Fields.TEMP_FILE_PREFIX, tempFileName);
    // write file to disk
    OutputStream output = new FileOutputStream(temp.toFile());
    IOUtils.copy(input, output);

    output.flush();
    output.close();
    input.close();

    return temp;
}

From source file:divconq.tool.Updater.java

static public boolean tryUpdate() {
    @SuppressWarnings("resource")
    final Scanner scan = new Scanner(System.in);

    FuncResult<RecordStruct> ldres = Updater.loadDeployed();

    if (ldres.hasErrors()) {
        System.out.println("Error reading deployed.json file: " + ldres.getMessage());
        return false;
    }//from ww  w  .  j a va 2  s .  c  om

    RecordStruct deployed = ldres.getResult();

    String ver = deployed.getFieldAsString("Version");
    String packfolder = deployed.getFieldAsString("PackageFolder");
    String packprefix = deployed.getFieldAsString("PackagePrefix");

    if (StringUtil.isEmpty(ver) || StringUtil.isEmpty(packfolder)) {
        System.out.println("Error reading deployed.json file: Missing Version or PackageFolder");
        return false;
    }

    if (StringUtil.isEmpty(packprefix))
        packprefix = "DivConq";

    System.out.println("Current Version: " + ver);

    Path packpath = Paths.get(packfolder);

    if (!Files.exists(packpath) || !Files.isDirectory(packpath)) {
        System.out.println("Error reading PackageFolder - it may not exist or is not a folder.");
        return false;
    }

    File pp = packpath.toFile();
    RecordStruct deployment = null;
    File matchpack = null;

    for (File f : pp.listFiles()) {
        if (!f.getName().startsWith(packprefix + "-") || !f.getName().endsWith("-bin.zip"))
            continue;

        System.out.println("Checking: " + f.getName());

        // if not a match before, clear this
        deployment = null;

        try {
            ZipFile zf = new ZipFile(f);

            Enumeration<ZipArchiveEntry> entries = zf.getEntries();

            while (entries.hasMoreElements()) {
                ZipArchiveEntry entry = entries.nextElement();

                if (entry.getName().equals("deployment.json")) {
                    //System.out.println("crc: " + entry.getCrc());

                    FuncResult<CompositeStruct> pres = CompositeParser.parseJson(zf.getInputStream(entry));

                    if (pres.hasErrors()) {
                        System.out.println("Error reading deployment.json file");
                        break;
                    }

                    deployment = (RecordStruct) pres.getResult();

                    break;
                }
            }

            zf.close();
        } catch (IOException x) {
            System.out.println("Error reading deployment.json file: " + x);
        }

        if (deployment != null) {
            String fndver = deployment.getFieldAsString("Version");
            String fnddependson = deployment.getFieldAsString("DependsOn");

            if (ver.equals(fnddependson)) {
                System.out.println("Found update: " + fndver);
                matchpack = f;
                break;
            }
        }
    }

    if ((matchpack == null) || (deployment == null)) {
        System.out.println("No updates found!");
        return false;
    }

    String fndver = deployment.getFieldAsString("Version");
    String umsg = deployment.getFieldAsString("UpdateMessage");

    if (StringUtil.isNotEmpty(umsg)) {
        System.out.println("========================================================================");
        System.out.println(umsg);
        System.out.println("========================================================================");
    }

    System.out.println();
    System.out.println("Do you want to install?  (y/n)");
    System.out.println();

    String p = scan.nextLine().toLowerCase();

    if (!p.equals("y"))
        return false;

    System.out.println();

    System.out.println("Intalling: " + fndver);

    Set<String> ignorepaths = new HashSet<>();

    ListStruct iplist = deployment.getFieldAsList("IgnorePaths");

    if (iplist != null) {
        for (Struct df : iplist.getItems())
            ignorepaths.add(df.toString());
    }

    ListStruct dflist = deployment.getFieldAsList("DeleteFiles");

    // deleting
    if (dflist != null) {
        for (Struct df : dflist.getItems()) {
            Path delpath = Paths.get(".", df.toString());

            if (Files.exists(delpath)) {
                System.out.println("Deleting: " + delpath.toAbsolutePath());

                try {
                    Files.delete(delpath);
                } catch (IOException x) {
                    System.out.println("Unable to Delete: " + x);
                }
            }
        }
    }

    // copying updates

    System.out.println("Checking for updated files: ");

    try {
        @SuppressWarnings("resource")
        ZipFile zf = new ZipFile(matchpack);

        Enumeration<ZipArchiveEntry> entries = zf.getEntries();

        while (entries.hasMoreElements()) {
            ZipArchiveEntry entry = entries.nextElement();

            String entryname = entry.getName().replace('\\', '/');
            boolean xfnd = false;

            for (String exculde : ignorepaths)
                if (entryname.startsWith(exculde)) {
                    xfnd = true;
                    break;
                }

            if (xfnd)
                continue;

            System.out.print(".");

            Path localpath = Paths.get(".", entryname);

            if (entry.isDirectory()) {
                if (!Files.exists(localpath))
                    Files.createDirectories(localpath);
            } else {
                boolean hashmatch = false;

                if (Files.exists(localpath)) {
                    String local = null;
                    String update = null;

                    try (InputStream lin = Files.newInputStream(localpath)) {
                        local = HashUtil.getMd5(lin);
                    }

                    try (InputStream uin = zf.getInputStream(entry)) {
                        update = HashUtil.getMd5(uin);
                    }

                    hashmatch = (StringUtil.isNotEmpty(local) && StringUtil.isNotEmpty(update)
                            && local.equals(update));
                }

                if (!hashmatch) {
                    System.out.print("[" + entryname + "]");

                    try (InputStream uin = zf.getInputStream(entry)) {
                        Files.createDirectories(localpath.getParent());

                        Files.copy(uin, localpath, StandardCopyOption.REPLACE_EXISTING);
                    } catch (Exception x) {
                        System.out.println("Error updating: " + entryname + " - " + x);
                        return false;
                    }
                }
            }
        }

        zf.close();
    } catch (IOException x) {
        System.out.println("Error reading update package: " + x);
    }

    // updating local config
    deployed.setField("Version", fndver);

    OperationResult svres = Updater.saveDeployed(deployed);

    if (svres.hasErrors()) {
        System.out.println("Intalled: " + fndver
                + " but could not update deployed.json.  Repair the file before continuing.\nError: "
                + svres.getMessage());
        return false;
    }

    System.out.println("Intalled: " + fndver);

    return true;
}

From source file:com.bbva.kltt.apirest.core.util.parser.ParserUtil.java

/**
 * Read the file content//from w  w  w. j a v  a2 s.c om
 *
 * @param filePath with the file path
 * @return the file content
 * @throws APIRestGeneratorException with an occurred exception
 */
public static String readFileContent(final String filePath) throws APIRestGeneratorException {
    Path path = null;

    if (filePath.toLowerCase().startsWith(ConstantsInput.SO_PATH_STRING_PREFIX)) {
        path = Paths.get(URI.create(filePath));
    } else {
        path = Paths.get(filePath, new String[0]);
    }

    String fileContent = null;

    if (Files.exists(path, new LinkOption[0])) {
        try {
            fileContent = FileUtils.readFileToString(path.toFile(), "UTF-8");
        } catch (IOException ioException) {
            final String errorString = "IOException when reading the file: " + ioException;

            ParserUtil.LOGGER.error(errorString, ioException);
            throw new APIRestGeneratorException(errorString, ioException);
        }
    } else {
        fileContent = FilesUtility.loadFileContentFromClasspath(filePath);
    }

    return fileContent;
}

From source file:com.liferay.sync.engine.service.SyncAccountService.java

public static void updateSyncAccountSyncFile(Path targetFilePath, long syncAccountId, boolean moveFile)
        throws Exception {

    SyncAccount syncAccount = fetchSyncAccount(syncAccountId);

    if (!moveFile) {
        SyncFile syncFile = SyncFileService.fetchSyncFile(syncAccount.getFilePathName());

        if (!FileKeyUtil.hasFileKey(targetFilePath, syncFile.getSyncFileId())) {

            throw new Exception("Target folder is not the moved sync data folder");
        }//from   w  w w.  j  av a 2  s .co m
    }

    syncAccount.setActive(false);

    update(syncAccount);

    boolean resetFileKeys = false;

    if (moveFile) {
        Path sourceFilePath = Paths.get(syncAccount.getFilePathName());

        try {
            FileUtil.moveFile(sourceFilePath, targetFilePath, false);
        } catch (Exception e1) {
            try {
                FileUtils.copyDirectory(sourceFilePath.toFile(), targetFilePath.toFile());

                FileUtil.deleteFile(sourceFilePath);

                resetFileKeys = true;
            } catch (Exception e2) {
                syncAccount.setActive(true);

                update(syncAccount);

                throw e2;
            }
        }
    }

    syncAccount = setFilePathName(syncAccountId, targetFilePath.toString());

    if (resetFileKeys) {
        FileKeyUtil.writeFileKeys(targetFilePath);
    }

    syncAccount.setActive(true);
    syncAccount.setUiEvent(SyncAccount.UI_EVENT_NONE);

    update(syncAccount);
}

From source file:com.codedx.burp.security.SSLConnectionSocketFactoryFactory.java

/**
 * Determines the location for the <code>truststore</code> file for the
 * given host. Each {@link SSLConnectionSocketFactory} returned by
 * {@link #initializeFactory(String)} needs to have a file to store
 * user-accepted invalid certificates; these files will be stored in the
 * user's OS-appropriate "appdata" directory.
 * //ww  w.  j a  v a2  s.c o  m
 * @param host A URL hostname, e.g. "www.google.com"
 * @return The file where the trust store for the given host should be
 *         stored
 */
private static File getTrustStoreForHost(String host) {
    String OS = System.getProperty("os.name").toUpperCase(Locale.getDefault());
    Path env;
    if (OS.contains("WIN")) {
        env = Paths.get(System.getenv("APPDATA"), "Code Dx", "Burp Extension");
    } else if (OS.contains("MAC")) {
        env = Paths.get(System.getProperty("user.home"), "Library", "Application Support", "Code Dx",
                "Burp Extension");
    } else if (OS.contains("NUX")) {
        env = Paths.get(System.getProperty("user.home"), ".codedx", "burp-extension");
    } else {
        env = Paths.get(System.getProperty("user.dir"), "codedx", "burp-extension");
    }

    File keystoreDir = new File(env.toFile(), ".usertrust");
    keystoreDir.mkdirs();

    // Host may only contain alphanumerics, dash, and dot.
    // Replace anything else with an underscore.
    String safeHost = host.replaceAll("[^a-zA-Z0-9\\-\\.]", "_");

    // <pluginstate>/.usertrust/<hostname>.truststore
    return new File(keystoreDir, safeHost + ".truststore");
}

From source file:io.github.collaboratory.LauncherCWL.java

/**
 *
 * @param workingDir where to save stderr and stdout
 * @param execute a pair holding the unformatted stderr and stderr
 * @param stdout formatted stdout for outpuit
 * @param stderr formatted stderr for output
 * @param cwltool help text explaining name of integration
 *///from  w w w  . j  av  a  2 s .co  m
public static void outputIntegrationOutput(String workingDir, ImmutablePair<String, String> execute,
        String stdout, String stderr, String cwltool) {
    System.out.println(cwltool + " stdout:\n" + stdout);
    System.out.println(cwltool + " stderr:\n" + stderr);
    try {
        final Path path = Paths.get(workingDir + File.separator + cwltool + ".stdout.txt");
        FileUtils.writeStringToFile(path.toFile(), execute.getLeft(), StandardCharsets.UTF_8, false);
        System.out.println("Saving copy of " + cwltool + " stdout to: " + path.toAbsolutePath().toString());
        final Path txt2 = Paths.get(workingDir + File.separator + cwltool + ".stderr.txt");
        FileUtils.writeStringToFile(txt2.toFile(), execute.getRight(), StandardCharsets.UTF_8, false);
        System.out.println("Saving copy of " + cwltool + " stderr to: " + txt2.toAbsolutePath().toString());
    } catch (IOException e) {
        throw new RuntimeException("unable to save " + cwltool + " output", e);
    }
}

From source file:com.fizzed.stork.deploy.Archive.java

static public void packEntry(ArchiveOutputStream aos, Path dirOrFile, String base, boolean appendName)
        throws IOException {
    String entryName = base;/*from  w ww  .  j  a  va  2s  .  c  om*/

    if (appendName) {
        if (!entryName.equals("")) {
            if (!entryName.endsWith("/")) {
                entryName += "/" + dirOrFile.getFileName();
            } else {
                entryName += dirOrFile.getFileName();
            }
        } else {
            entryName += dirOrFile.getFileName();
        }
    }

    ArchiveEntry entry = aos.createArchiveEntry(dirOrFile.toFile(), entryName);

    if (Files.isRegularFile(dirOrFile)) {
        if (entry instanceof TarArchiveEntry && Files.isExecutable(dirOrFile)) {
            // -rwxr-xr-x
            ((TarArchiveEntry) entry).setMode(493);
        } else {
            // keep default mode
        }
    }

    aos.putArchiveEntry(entry);

    if (Files.isRegularFile(dirOrFile)) {
        Files.copy(dirOrFile, aos);
        aos.closeArchiveEntry();
    } else {
        aos.closeArchiveEntry();
        List<Path> children = Files.list(dirOrFile).collect(Collectors.toList());
        if (children != null) {
            for (Path childFile : children) {
                packEntry(aos, childFile, entryName + "/", true);
            }
        }
    }
}

From source file:com.ibm.streamsx.topology.internal.context.remote.ZippedToolkitRemoteContext.java

private static Path pack(final Path folder, JsonObject graph, String tkName)
        throws IOException, URISyntaxException {
    String namespace = splAppNamespace(graph);
    String name = splAppName(graph);

    Path zipFilePath = Paths.get(folder.toAbsolutePath().toString() + ".zip");
    String workingDir = zipFilePath.getParent().toString();

    Path topologyToolkit = TkInfo.getTopologyToolkitRoot().getAbsoluteFile().toPath();

    // Paths to copy into the toolkit
    Map<Path, String> paths = new HashMap<>();

    // tkManifest is the list of toolkits contained in the archive
    try (PrintWriter tkManifest = new PrintWriter("manifest_tk.txt", "UTF-8")) {
        tkManifest.println(tkName);/*  ww  w.ja  va2  s.  c  o  m*/
        tkManifest.println("com.ibm.streamsx.topology");

        JsonObject configSpl = object(graph, CONFIG, "spl");
        if (configSpl != null) {
            objectArray(configSpl, "toolkits", tk -> {
                File tkRoot = new File(jstring(tk, "root"));
                String tkRootName = tkRoot.getName();
                tkManifest.println(tkRootName);
                paths.put(tkRoot.toPath(), tkRootName);
            });
        }
    }

    // mainComposite is a string of the namespace and the main composite.
    // This is used by the Makefile
    try (PrintWriter mainComposite = new PrintWriter("main_composite.txt", "UTF-8")) {
        mainComposite.print(namespace + "::" + name);
    }

    Path manifest = Paths.get(workingDir, "manifest_tk.txt");
    Path mainComp = Paths.get(workingDir, "main_composite.txt");
    Path makefile = topologyToolkit
            .resolve(Paths.get("opt", "python", "templates", "common", "Makefile.template"));

    paths.put(topologyToolkit, topologyToolkit.getFileName().toString());
    paths.put(manifest, "manifest_tk.txt");
    paths.put(mainComp, "main_composite.txt");
    paths.put(makefile, "Makefile");
    paths.put(folder, folder.getFileName().toString());

    addAllToZippedArchive(paths, zipFilePath);
    manifest.toFile().delete();
    mainComp.toFile().delete();

    return zipFilePath;
}