Example usage for java.io File toString

List of usage examples for java.io File toString

Introduction

In this page you can find the example usage for java.io File toString.

Prototype

public String toString() 

Source Link

Document

Returns the pathname string of this abstract pathname.

Usage

From source file:net.morimekta.idltool.IdlUtils.java

public static File findHomeDotCacheIdlTool(File cacheOverride) throws IOException {
    if (cacheOverride != null) {
        cacheOverride = cacheOverride.getCanonicalFile();
        if (cacheOverride.exists() && cacheOverride.isDirectory()) {
            return cacheOverride;
        }/*  w  w  w. j a  v a2 s  .c o  m*/
        throw new IOException("No such cache directory: " + cacheOverride.toString());
    }

    File home = new File(System.getenv("HOME")).getAbsoluteFile().getCanonicalFile();
    cacheOverride = new File(new File(home, ".cache"), "idltool");
    if (!cacheOverride.exists()) {
        if (!cacheOverride.mkdirs()) {
            throw new IOException("Unable to create RC directory: " + cacheOverride.toString());
        }
    }
    if (!cacheOverride.isDirectory()) {
        throw new IOException("RC location is not a directory: " + cacheOverride.toString());
    }
    return cacheOverride;
}

From source file:Exec.java

static Process execUnix(String[] cmdarray, String[] envp, File directory) throws IOException {
    // instead of calling command directly, we'll call the shell to change
    // directory and set environment variables.

    // start constructing the sh command line.
    StringBuffer buf = new StringBuffer();

    if (directory != null) {
        // change to directory
        buf.append("cd '");
        buf.append(escapeQuote(directory.toString()));
        buf.append("'; ");
    }//from   w  ww .  j  a v  a 2s  .c  o m

    if (envp != null) {
        // set environment variables.  Quote the value (but not the name).
        for (int i = 0; i < envp.length; ++i) {
            String nameval = envp[i];
            int equals = nameval.indexOf('=');
            if (equals == -1)
                throw new IOException("environment variable '" + nameval + "' should have form NAME=VALUE");
            buf.append(nameval.substring(0, equals + 1));
            buf.append('\'');
            buf.append(escapeQuote(nameval.substring(equals + 1)));
            buf.append("\' ");
        }
    }

    // now that we have the directory and environment, run "which" 
    // to test if the command name is found somewhere in the path.
    // If "which" fails, throw an IOException.
    String cmdname = escapeQuote(cmdarray[0]);
    Runtime rt = Runtime.getRuntime();
    String[] sharray = new String[] { "sh", "-c", buf.toString() + " which \'" + cmdname + "\'" };
    Process which = rt.exec(sharray);
    try {
        which.waitFor();
    } catch (InterruptedException e) {
        throw new IOException("interrupted");
    }

    if (which.exitValue() != 0)
        throw new IOException("can't execute " + cmdname + ": bad command or filename");

    // finish in 
    buf.append("exec \'");
    buf.append(cmdname);
    buf.append("\' ");

    // quote each argument in the command
    for (int i = 1; i < cmdarray.length; ++i) {
        buf.append('\'');
        buf.append(escapeQuote(cmdarray[i]));
        buf.append("\' ");
    }

    System.out.println("executing " + buf);
    sharray[2] = buf.toString();
    return rt.exec(sharray);
}

From source file:com.ColonelHedgehog.Sites.Services.URLServices.DLC.java

public static void parseCrossNetworkParseable(final File f) {
    new BukkitRunnable() {

        @Override//  w  w  w .  j a  va  2 s  .  c o m
        public void run() {

            try {
                BufferedReader br = null;
                try {
                    br = new BufferedReader(new FileReader(f));
                    int linenum = 1;
                    String read;

                    while ((read = br.readLine()) != null) {
                        //System.out.println("[CS | CNP] Reading... " + linenum + ". Parsing... " + reading);
                        if (read.startsWith("~ (action#copyfiles) ")) {
                            System.out.println(
                                    "[CS | CNP] Found action#copyfiles at line " + linenum + ". Parsing...");
                            String[] sy = read.split(" : ");
                            File source = new File(sy[0].replace("~ (action#copyfiles) ", "")
                                    .replace("#pluginsfolder#", plugin.getDataFolder().getParent()));
                            File dest = new File(
                                    sy[1].replace("#pluginsfolder#", plugin.getDataFolder().getParent()));

                            System.out.println("[CS | CNP] Copying source: " + source.toString());
                            System.out.println("[CS | CNP] Copying to destination: " + dest.toString());
                            int schematicscount = 0;

                            File[] files = source.listFiles();

                            if (files == null) {
                                System.out.println(
                                        "[CS | CNP] ERROR: No files in directory: " + source.getPath());
                                return;
                            }
                            for (File schematic : files) {
                                FileUtils.copyFileToDirectory(schematic, dest);
                                schematicscount++;
                            }

                            System.out.println("[CS | CNP] Copied files. Total copied: " + schematicscount);
                        } else if (read.startsWith("~ (action#writetoconfig) ")) {
                            //System.out.println("[CS | CNP] Found action#writetoconfig at line " + linenum + ". Parsing...");
                            //String[] sy = read.split(" : ");

                            //File source = new File(sy[0].replace("~ (action#writetoconfig) ", "").replace("#pluginsfolder#", plugin.getDataFolder().getParent()));
                            //parseCrossNetworkParseableScript(source);
                            /* ===== Not nescessary right now! ===== */
                        }
                        linenum++;
                    }
                } catch (IOException ex) {
                    Logger.getLogger(DLC.class.getName()).log(Level.SEVERE, null, ex);
                } finally {
                    try {
                        if (br != null) {
                            br.close();
                        } else {
                            System.out.println("[CS | CNP] Failed to close buffered reader!");
                        }
                    } catch (IOException ex) {
                        Logger.getLogger(DLC.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                System.out.println("[CS | CNP] Finished parsing. Deleting package...");
                FileUtils.deleteDirectory(f.getParentFile());
            } catch (IOException ex) {
                Logger.getLogger(DLC.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }.runTaskAsynchronously(plugin);
}

From source file:com.taobao.diamond.common.Constants.java

/** ?-D &gt; env &gt; diamond.properties  */
public static void init() {
    File diamondFile = new File(System.getProperty("user.home"), "diamond/ServerAddress");
    if (!diamondFile.exists()) {
        diamondFile.getParentFile().mkdirs();
        try (OutputStream out = new FileOutputStream(diamondFile)) {
            out.write("localhost".getBytes());
        } catch (IOException e) {
            throw new IllegalStateException(diamondFile.toString(), e);
        }//from   ww  w  .ja v  a 2s.co  m
    }
    List<Field> fields = new ArrayList<>();
    for (Field field : Constants.class.getDeclaredFields()) {
        if (Modifier.isPublic(field.getModifiers()) && !Modifier.isFinal(field.getModifiers())) {
            fields.add(field);
        }
    }

    Properties props = new Properties();
    {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        if (cl == null)
            cl = Constants.class.getClassLoader();
        try (InputStream in = cl.getResourceAsStream("diamond.properties")) {
            if (in != null)
                props.load(in);
        } catch (IOException e) {
            log.warn("load diamond.properties", e);
        }
    }
    props.putAll(System.getenv());
    props.putAll(System.getProperties());

    Map<String, Object> old = new HashMap<>();
    try {
        for (Field field : fields) {
            if (!props.containsKey(field.getName()))
                continue;
            old.put(field.getName(), field.get(Constants.class));

            String value = props.getProperty(field.getName());
            Class<?> clazz = field.getType();
            if (String.class.equals(clazz)) {
                field.set(Constraints.class, value);
            } else if (int.class.equals(clazz)) {
                if (value != null) {
                    field.set(Constraints.class, Integer.parseInt(value));
                }
            } else {
                throw new IllegalArgumentException(field + "  " + value + " ?");
            }
        }
    } catch (IllegalAccessException e) {
        throw new IllegalStateException(e);
    }

    setValue(old, "CONFIG_HTTP_URI_FILE", "HTTP_URI_FILE");
    setValue(old, "HTTP_URI_LOGIN", "HTTP_URI_FILE");
    setValue(old, "DAILY_DOMAINNAME", "DEFAULT_DOMAINNAME");
}

From source file:net.nifheim.beelzebu.coins.common.utils.dependencies.DependencyManager.java

private static File downloadDependency(File libDir, Dependency dependency) throws Exception {
    String fileName = dependency.name().toLowerCase() + "-" + dependency.getVersion() + ".jar";

    File file = new File(libDir, fileName);
    if (file.exists()) {
        return file;
    }// w  ww.  jav  a  2  s  . c o  m

    URL url = new URL(dependency.getUrl());

    core.getMethods().log("Dependency '" + fileName + "' could not be found. Attempting to download.");
    try (InputStream in = url.openStream()) {
        Files.copy(in, file.toPath());
    }

    if (!file.exists()) {
        throw new IllegalStateException("File not present. - " + file.toString());
    } else {
        core.getMethods().log("Dependency '" + fileName + "' successfully downloaded.");
        return file;
    }
}

From source file:au.org.ands.vocabs.toolkit.utils.ToolkitFileUtils.java

/** Compress the files in the backup folder for a project.
 * @param projectId The project ID//  w  ww.  jav a  2s .c  o m
 * @throws IOException Any exception when reading/writing data.
 */
public static void compressBackupFolder(final String projectId) throws IOException {
    String backupPath = getBackupPath(projectId);
    if (!Files.isDirectory(Paths.get(backupPath))) {
        // No such directory, so nothing to do.
        return;
    }
    String projectSlug = makeSlug(projectId);
    // The name of the ZIP file that does/will contain all
    // backups for this project.
    Path zipFilePath = Paths.get(backupPath).resolve(projectSlug + ".zip");
    // A temporary ZIP file. Any existing content in the zipFilePath
    // will be copied into this, followed by any other files in
    // the directory that have not yet been added.
    Path tempZipFilePath = Paths.get(backupPath).resolve("temp" + ".zip");

    File tempZipFile = tempZipFilePath.toFile();
    if (!tempZipFile.exists()) {
        tempZipFile.createNewFile();
    }

    ZipOutputStream tempZipOut = new ZipOutputStream(new FileOutputStream(tempZipFile));

    File existingZipFile = zipFilePath.toFile();
    if (existingZipFile.exists()) {
        ZipFile zipIn = new ZipFile(existingZipFile);

        Enumeration<? extends ZipEntry> entries = zipIn.entries();
        while (entries.hasMoreElements()) {
            ZipEntry e = entries.nextElement();
            logger.debug("compressBackupFolder copying: " + e.getName());
            tempZipOut.putNextEntry(e);
            if (!e.isDirectory()) {
                copy(zipIn.getInputStream(e), tempZipOut);
            }
            tempZipOut.closeEntry();
        }
        zipIn.close();
    }

    File dir = new File(backupPath);
    File[] files = dir.listFiles();

    for (File source : files) {
        if (!source.getName().toLowerCase().endsWith(".zip")) {
            logger.debug("compressBackupFolder compressing and " + "deleting file: " + source.toString());
            if (zipFile(tempZipOut, source)) {
                source.delete();
            }
        }
    }

    tempZipOut.flush();
    tempZipOut.close();
    tempZipFile.renameTo(existingZipFile);
}

From source file:edu.uci.ics.asterix.installer.test.AsterixClusterLifeCycleIT.java

@BeforeClass
public static void setUp() throws Exception {
    //testcase setup
    TestCaseContext.Builder b = new TestCaseContext.Builder();
    testCaseCollection = b.build(new File(PATH_BASE));
    File outdir = new File(PATH_ACTUAL);
    outdir.mkdirs();/*w w  w  .j  a v  a2 s.  c om*/

    //vagrant setup
    File installerTargetDir = new File(asterixProjectDir, "target");
    System.out.println(managixFolderName);
    managixFolderName = installerTargetDir.list(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return new File(dir, name).isDirectory() && name.startsWith("asterix-installer")
                    && name.endsWith("binary-assembly");
        }

    })[0];
    invoke("cp", "-r", installerTargetDir.toString() + "/" + managixFolderName,
            asterixProjectDir + "/" + CLUSTER_BASE);

    logOutput(remoteInvoke("cp -r /vagrant/" + managixFolderName + " /tmp/asterix").getInputStream());

    logOutput(managixInvoke("configure").getInputStream());
    logOutput(managixInvoke("validate").getInputStream());

    Process p = managixInvoke("create -n vagrant-ssh -c /vagrant/cluster.xml");
    String pout = processOut(p);
    LOGGER.info(pout);
    Assert.assertTrue(checkOutput(pout, "ACTIVE"));
    //TODO: I should check for 'WARNING' here, but issue 764 stops this from being reliable 
    LOGGER.info("Test start active cluster instance PASSED");

    Process stop = managixInvoke("stop -n vagrant-ssh");
    Assert.assertTrue(checkOutput(stop.getInputStream(), "Stopped Asterix instance"));
    LOGGER.info("Test stop active cluster instance PASSED");
}

From source file:com.sustainalytics.crawlerfilter.PDFTitleGeneration.java

/**
 * This method extracts creation date/ custom date of a PDF file
 * @param file is a File object/*from  www.  j a  v  a  2s  . co m*/
 * @return String that contains the creation date/ custom date of the PDF
 */
public static String extractDate(File file) {
    PDDocument document = null;
    boolean isDamaged = false; //to deal with damaged pdf
    String creationDateMetaData = "";
    try {
        document = PDDocument.load(file.toString());
        /*If the PDF file is not damanged --->*/
        if (!isDamaged) {
            /*...but the file is encrypted --->*/
            if (document.isEncrypted()) {
                logger.info("File " + file.getName() + "is encrypted. Trying to decrypt...");
                try {
                    /*...then decryptt it --->*/
                    document.decrypt("");
                    document.setAllSecurityToBeRemoved(true);
                    logger.info("File " + file.getName() + "successfully decrypted!");
                } catch (CryptographyException e) {
                    logger.info("Error decrypting file " + file.getName());
                    isDamaged = true;
                }

            } /*<--work around to decrypt an encrypted pdf ends here*/

            /*Metadata extraction --->*/
            PDDocumentInformation info = document.getDocumentInformation();

            /*We are only interested in date data--->*/
            Calendar calendar = info.getCreationDate();
            int creationYear = 0, creationMonth = 0, creationDate = 0;
            if (calendar != null) {
                creationYear = calendar.get(Calendar.YEAR);
                creationMonth = calendar.get(Calendar.MONTH) + 1;
                creationDate = calendar.get(Calendar.DATE);

            } /*<---Date data extraction complete*/

            /*If creation date is not empty --->*/
            if (creationYear != 0) {
                creationDateMetaData = creationYear + "-" + creationMonth + "-" + creationDate;
            } //<--- creation date found and the date part of the title is generated
            /*No creation date is found --->*/
            else {
                SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy");
                Date customDate = null;
                /*But we have custom date some times --->*/
                try {
                    customDate = dateFormatter.parse(info.getCustomMetadataValue("customdate"));
                } catch (ParseException e) {
                    logger.info("Error parsing date from custom date");
                }
                calendar = Calendar.getInstance();
                calendar.setTime(customDate);
                if (calendar != null) {
                    creationYear = calendar.get(Calendar.YEAR);
                    creationMonth = calendar.get(Calendar.MONTH) + 1;
                    creationDate = calendar.get(Calendar.DATE);

                } /*<---Date data extraction complete from customdate*/
                if (creationYear != 0) {
                    creationDateMetaData = creationYear + "-" + creationMonth + "-" + creationDate;
                }
            } //<--- work around if no creation date is found

        } /*<--- Good to know that the PDF was not damaged*/
    } catch (IOException e) { /*If the PDF was not read by the system --->*/
        logger.info("Error processing file " + file.getName());
        /*... then maybe it is damaged*/
        isDamaged = true;
    } finally {
        try {
            /*If the file was good, not damaged, then please close it --->*/
            if (!isDamaged) {
                document.close();
                logger.info("File " + file.getName() + " is closed successfully!");
            }
        } catch (IOException e) {
            logger.info("Error closing file " + file.getName());
        }
    } /*<--- PDF closing done!*/
    return creationDateMetaData;
}

From source file:at.spardat.xma.boot.BootRuntime.java

/**
 * Read the BootCfg properties. First the default properties are read from a
 * property file in the class path. In a second step these properties are overloaded
 * from the bootruntime configuration file located in the base directory.
 * // www  .  ja v  a  2s .co m
 * @param baseDir
 * @param l
 * @return
 * @throws IOException
 */
static Properties readBootCfgProperties(File baseDir, Logger l) throws IOException {

    Properties props = new Properties();

    /* load default properties from classpath */
    InputStream is = BootRuntime.class.getClassLoader()
            .getResourceAsStream("at/spardat/xma/boot/bootcfg.properties");
    props.load(is); //$NON-NLS-1$
    is.close();

    /* load additional properties from runtime directory, if exist.
     * can replace default properties.
     */
    File configFile = new File(baseDir, Statics.SETTINGS_DIRNAME + "/" + Statics.BRT_CONFIGFILE); //$NON-NLS-1$
    if (configFile.exists()) {
        l.log(LogLevel.FINE, "Using Configuration File: {0}", configFile.toString());
        InputStream cfis = new FileInputStream(configFile);
        props.load(cfis);
        cfis.close();
    }

    return props;
}

From source file:io.github.bonigarcia.wdm.Downloader.java

public static final File extractMsi(File msi) throws IOException {
    File tmpMsi = new File(Files.createTempDir().getAbsoluteFile() + File.separator + msi.getName());
    Files.move(msi, tmpMsi);/* w ww .ja  va 2s  .c om*/
    log.trace("Temporal msi file: {}", tmpMsi);

    Process process = Runtime.getRuntime()
            .exec(new String[] { "msiexec", "/a", tmpMsi.toString(), "/qb", "TARGETDIR=" + msi.getParent() });
    try {
        process.waitFor();
    } catch (InterruptedException e) {
        log.error("Exception waiting to msiexec to be finished", e);
    } finally {
        process.destroy();
    }

    tmpMsi.delete();

    Collection<File> listFiles = FileUtils.listFiles(new File(msi.getParent()), new String[] { "exe" }, true);
    return listFiles.iterator().next();
}