Example usage for java.io File getCanonicalPath

List of usage examples for java.io File getCanonicalPath

Introduction

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

Prototype

public String getCanonicalPath() throws IOException 

Source Link

Document

Returns the canonical pathname string of this abstract pathname.

Usage

From source file:com.sap.prd.mobile.ios.mios.ScriptRunner.java

private static File copyScript(String script, File workingDirectory) throws IOException {
    if (!workingDirectory.exists())
        if (!workingDirectory.mkdirs())
            throw new IOException("Cannot create directory '" + workingDirectory + "'.");

    final File scriptFile = new File(workingDirectory, getScriptFileName(script));
    scriptFile.deleteOnExit();//from  w  ww.j a  v a 2  s .  c om

    OutputStream os = null;
    InputStream is = null;

    try {
        is = ScriptRunner.class.getResourceAsStream(script);

        if (is == null)
            throw new FileNotFoundException(script + " not found.");

        os = FileUtils.openOutputStream(scriptFile);

        IOUtils.copy(is, os);
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }

    Forker.forkProcess(System.out, null, "chmod", "755", scriptFile.getCanonicalPath());
    return scriptFile;
}

From source file:fr.letroll.ttorrentandroid.client.TorrentHandler.java

@Nonnull
private static TorrentByteStorage toStorage(@Nonnull Torrent torrent, @Nonnull File parent) throws IOException {
    Preconditions.checkNotNull(parent, "Parent directory was null.");

    String parentPath = parent.getCanonicalPath();

    if (!torrent.isMultifile() && parent.isFile())
        return new FileStorage(parent, torrent.getSize());

    List<FileStorage> files = new LinkedList<FileStorage>();
    long offset = 0L;
    for (Torrent.TorrentFile file : torrent.getFiles()) {
        // TODO: Files.simplifyPath() is a security check here to avoid jail-escape.
        // However, it uses "/" not File.separator internally.
        String path = Files.simplifyPath("/" + file.path);
        File actual = new File(parent, path);
        String actualPath = actual.getCanonicalPath();
        if (!actualPath.startsWith(parentPath))
            throw new SecurityException("Torrent file path attempted to break directory jail: " + actualPath
                    + " is not within " + parentPath);

        FileUtils.forceMkdir(actual.getParentFile());
        files.add(new FileStorage(actual, offset, file.size));
        offset += file.size;//  w  w w  .j  a  v  a 2s  . c o m
    }
    return new FileCollectionStorage(files, torrent.getSize());
}

From source file:com.adobe.acs.commons.dam.audio.impl.AbstractFFMpegAudioProcess.java

private static File resolveWorkingDir(String slingHome, String path) {
    if (path == null) {
        path = "";
    }/*from   w  w  w  .  jav  a 2 s  .  c  o m*/
    // ensure proper separator in the path (esp. for systems, which do
    // not use "slash" as a separator, e.g Windows)
    path = path.replace('/', File.separatorChar);

    // create a file instance and check whether this is absolute. If not
    // create a new absolute file instance with the base dir (sling.home or
    // working dir of current JVM) and get the absolute path name from that
    File workingDir = new File(path);
    if (!workingDir.isAbsolute()) {
        File baseDir;
        if (slingHome == null) {
            /* use jvm working dir */
            baseDir = new File("").getAbsoluteFile();
        } else {
            baseDir = new File(slingHome).getAbsoluteFile();
        }
        workingDir = new File(baseDir, path).getAbsoluteFile();
    }
    try {
        log.info("ffmpeg working directory: {}", workingDir.getCanonicalPath());
    } catch (IOException e) {
        log.info("ffmpeg working directory: {}", workingDir.getAbsolutePath());
    }

    return workingDir;
}

From source file:com.idiro.utils.db.mysql.MySqlUtils.java

public static boolean importTable(JdbcConnection conn, String tableName, Map<String, String> features,
        File fileIn, File tablePath, char delimiter, boolean header) {
    boolean ok = true;
    try {/*from w  ww.  ja v  a2s  . c  om*/
        DbChecker dbCh = new DbChecker(conn);
        if (!dbCh.isTableExist(tableName)) {
            logger.debug("The table which has to be imported has not been created");
            logger.debug("Creation of the table");
            Integer ASCIIVal = (int) delimiter;
            String[] options = { ASCIIVal.toString(), tablePath.getCanonicalPath() };
            conn.executeQuery(new MySqlBasicStatement().createExternalTable(tableName, features, options));
        } else {
            //Check if it is the same table 
            if (!dbCh.areFeaturesTheSame(tableName, features.keySet())) {
                logger.warn("Mismatch between the table to import and the table in the database");
                return false;
            }

            logger.warn("Have to check if the table is external or not, I do not know how to do that");

        }
    } catch (SQLException e) {
        logger.debug("Fail to watch the datastore");
        logger.debug(e.getMessage());
        return false;
    } catch (IOException e) {
        logger.warn("Fail to get the output path from a File object");
        logger.warn(e.getMessage());
        return false;
    }

    //Check if the input file has the right number of field
    FileChecker fChIn = new FileChecker(fileIn);
    FileChecker fChOut = new FileChecker(tablePath);
    String strLine = "";
    try {

        if (fChIn.isDirectory() || !fChIn.canRead()) {
            logger.warn("The file " + fChIn.getFilename() + "is a directory or can not be read");
            return false;
        }
        BufferedReader br = new BufferedReader(new FileReader(fileIn));
        //Read first line
        strLine = br.readLine();
        br.close();
    } catch (IOException e1) {
        logger.debug("Fail to open the file" + fChIn.getFilename());
        return false;
    }

    if (StringUtils.countMatches(strLine, String.valueOf(delimiter)) != features.size() - 1) {
        logger.warn("File given does not match with the delimiter '" + delimiter
                + "' given and the number of fields '" + features.size() + "'");
        return false;
    }

    BufferedWriter bw = null;
    BufferedReader br = null;

    try {
        bw = new BufferedWriter(new FileWriter(tablePath));
        logger.debug("read the file" + fileIn.getAbsolutePath());
        br = new BufferedReader(new FileReader(fileIn));
        String delimiterStr = "" + delimiter;
        //Read File Line By Line
        while ((strLine = br.readLine()) != null) {
            bw.write("\"" + strLine.replace(delimiterStr, "\",\"") + "\"\n");
        }
        br.close();

        bw.close();
    } catch (FileNotFoundException e1) {
        logger.error(e1.getCause() + " " + e1.getMessage());
        logger.error("Fail to read " + fileIn.getAbsolutePath());
        ok = false;
    } catch (IOException e1) {
        logger.error("Error writting, reading on the filesystem from the directory" + fChIn.getFilename()
                + " to the file " + fChOut.getFilename());
        ok = false;
    }

    return ok;
}

From source file:io.druid.java.util.common.CompressionUtils.java

public static void validateZipOutputFile(String sourceFilename, final File outFile, final File outDir)
        throws IOException {
    // check for evil zip exploit that allows writing output to arbitrary directories
    final File canonicalOutFile = outFile.getCanonicalFile();
    final String canonicalOutDir = outDir.getCanonicalPath();
    if (!canonicalOutFile.toPath().startsWith(canonicalOutDir)) {
        throw new ISE("Unzipped output path[%s] of sourceFile[%s] does not start with outDir[%s].",
                canonicalOutFile, sourceFilename, canonicalOutDir);
    }/* ww w .ja  v  a 2s  . c o  m*/
}

From source file:edu.ku.brc.specify.tasks.StartUpTask.java

/**
 * @param prefs/*from   w w w  .ja v a  2s .  c  o  m*/
 */
protected static boolean configureAttachmentManager(final AppPreferences prefs) {
    Boolean useFilePath = prefs.getBoolean(USE_FILE_PATH_PREF, null);
    String attchURL = prefs.get(ATTACHMENT_URL_PREF, null);
    String attchKey = prefs.get(ATTACHMENT_KEY_PREF, null);
    String filePath = prefs.get(ATTACHMENT_PATH_PREF, null);

    if (useFilePath == null) {
        if (prefs == AppPreferences.getGlobalPrefs()) {
            return false;
        }
        useFilePath = useFilePath == null ? true : useFilePath;
    }

    AttachmentManagerIface attachMgr = null;
    String msgPath = "";
    String errorKey = "NOT_AVAIL";

    if (StringUtils.isNotEmpty(attchURL)) // Using Web Server for Attachments
    {
        useFilePath = false;
        AttachmentUtils.setConfigForPath(useFilePath);

        WebStoreAttachmentMgr webAssetMgr = null;
        try {
            webAssetMgr = new WebStoreAttachmentMgr(attchURL, attchKey);
        } catch (WebStoreAttachmentKeyException e) {
            errorKey = "KEY_BAD";
        } catch (WebStoreAttachmentException e) {
            errorKey = "URL_BAD";
        }
        if (webAssetMgr != null) {
            attachMgr = webAssetMgr;
        }
    } else {
        useFilePath = true;

        File attLoc = null;
        final File location = UIRegistry.getAppDataSubDir("AttachmentStorage", true); //$NON-NLS-1$
        try {
            attLoc = filePath != null && !UIRegistry.isMobile() ? new File(filePath) : location;
            if (!AttachmentUtils.isAttachmentDirMounted(attLoc)) {
                try {
                    msgPath = attLoc.getCanonicalPath();
                } catch (IOException e) {
                    msgPath = attLoc.getAbsolutePath();
                }
            } else {
                attachMgr = new FileStoreAttachmentManager(attLoc);
            }

            if (filePath == null) {
                prefs.put(ATTACHMENT_PATH_PREF, location.getAbsolutePath());
            }
        } catch (IOException e1) {
            log.warn("Problems setting the FileStoreAttachmentManager at [" + location + "]"); //$NON-NLS-1$ //$NON-NLS-2$
            // TODO RELEASE -  Instead of exiting we need to disable Attachments
            //throw new RuntimeException("Problems setting the FileStoreAttachmentManager at ["+location+"]"); //$NON-NLS-1$ //$NON-NLS-2$
            errorKey = useFilePath ? "LOC_BAD" : "URL_BAD";
        }
    }

    if (attachMgr == null) {
        final String errKey = errorKey;
        log.warn("Problems setting the AttachmentManager at [" + msgPath + "]");
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                UIRegistry.showLocalizedError("AttachmentUtils." + errKey);
            }
        });
    } else {
        prefs.putBoolean(USE_FILE_PATH_PREF, useFilePath);
    }

    AttachmentUtils.setAttachmentManager(attachMgr);

    return attachMgr != null;
}

From source file:com.turn.ttorrent.client.TorrentHandler.java

@Nonnull
private static TorrentByteStorage toStorage(@Nonnull Torrent torrent, @CheckForNull File parent)
        throws IOException {
    if (parent == null)
        throw new NullPointerException("No parent directory given.");

    String parentPath = parent.getCanonicalPath();

    if (!torrent.isMultifile() && parent.isFile())
        return new FileStorage(parent, torrent.getSize());

    List<FileStorage> files = new LinkedList<FileStorage>();
    long offset = 0L;
    for (Torrent.TorrentFile file : torrent.getFiles()) {
        // TODO: Files.simplifyPath() is a security check here to avoid jail-escape.
        // However, it uses "/" not File.separator internally.
        String path = Files.simplifyPath("/" + file.path);
        File actual = new File(parent, path);
        String actualPath = actual.getCanonicalPath();
        if (!actualPath.startsWith(parentPath))
            throw new SecurityException("Torrent file path attempted to break directory jail: " + actualPath
                    + " is not within " + parentPath);

        FileUtils.forceMkdir(actual.getParentFile());
        files.add(new FileStorage(actual, offset, file.size));
        offset += file.size;/*from  w w  w  .  j a va2  s  .  c o  m*/
    }
    return new FileCollectionStorage(files, torrent.getSize());
}

From source file:eu.annocultor.tools.GeneratorOfXmlSchemaForConvertersDoclet.java

public static boolean start(RootDoc root) {
    Logger log = Logger.getLogger("DocletGenerator");

    if (destination == null) {
        try {//ww w  .  ja va  2s .  c om
            // loaded from RuleListenersFragment
            ruleListenerDef = IOUtils.toString(GeneratorOfXmlSchemaForConvertersDoclet.class
                    .getResourceAsStream("/RuleListenersFragment.xsd"), "UTF-8");

            String fn = System.getenv("annocultor.xconverter.destination.file.name");
            fn = (fn == null) ? "./../../../src/site/resources/schema/XConverterInclude.xsd" : fn;

            destination = new File(fn);
            if (destination.exists()) {
                destination.delete();
            }

            // initial copy of the template and include
            FileOutputStream os;
            os = new FileOutputStream(new File(destination.getParentFile(), "XConverter.xsd"));
            IOUtils.copy(new AutoCloseInputStream(GeneratorOfXmlSchemaForConvertersDoclet.class
                    .getResourceAsStream("/XConverterTemplate.xsd")), os);
            os.close();
            os = new FileOutputStream(destination);
            IOUtils.copy(new AutoCloseInputStream(GeneratorOfXmlSchemaForConvertersDoclet.class
                    .getResourceAsStream("/XConverterInclude.xsd")), os);
            os.close();
        } catch (Exception e) {
            try {
                throw new RuntimeException("On destination " + destination.getCanonicalPath(), e);
            } catch (IOException e1) {
                // too bad
                throw new RuntimeException(e1);
            }
        }
    }

    try {
        String s = Utils.loadFileToString(destination.getCanonicalPath(), "\n");
        int breakPoint = s.indexOf(XSD_TEXT_TO_REPLACED_WITH_GENERATED_XML_SIGNATURES);
        if (breakPoint < 0) {
            throw new Exception(
                    "Signature not found in XSD: " + XSD_TEXT_TO_REPLACED_WITH_GENERATED_XML_SIGNATURES);
        }
        String preambula = s.substring(0, breakPoint);
        String appendix = s.substring(breakPoint);

        destination.delete();

        PrintWriter schemaWriter = new PrintWriter(destination);
        schemaWriter.print(preambula);

        ClassDoc[] classes = root.classes();
        for (int i = 0; i < classes.length; ++i) {
            ClassDoc cd = classes[i];
            PrintWriter documentationWriter = null;
            if (getSuperClasses(cd).contains(Rule.class.getName())) {
                for (ConstructorDoc constructorDoc : cd.constructors()) {
                    if (constructorDoc.isPublic()) {
                        if (isMeantForXMLAccess(constructorDoc)) {
                            // dump APT doc
                            if (documentationWriter == null) {
                                // Create APT file and write the rule description
                                File file = new File("./../../../src/site/xdoc/rules." + cd.name() + ".xml");
                                documentationWriter = new PrintWriter(file);
                                log.info("Generating doc for rule " + file.getCanonicalPath());
                                printRuleDocStart(cd, documentationWriter);
                            }

                            // create XSD 

                            // check for the init() method
                            boolean initFound = false;
                            for (MethodDoc methodDoc : cd.methods()) {
                                if ("init".equals(methodDoc.name())) {
                                    if (methodDoc.parameters().length == 0) {
                                        initFound = true;
                                        break;
                                    }
                                }
                            }
                            if (!initFound) {
                                //                           throw new Exception("Method init() is required. Please make sure NOW that it is called in constructor " + cd.name());
                            }

                            printConstructorSchema(constructorDoc, schemaWriter);

                            if (documentationWriter != null) {
                                printConstructorDoc(constructorDoc, documentationWriter);
                            }
                        }
                    }
                }
            }

            if (documentationWriter != null) {
                printRuleDocEnd(documentationWriter);
            }
        }

        schemaWriter.print(appendix);
        schemaWriter.close();
        log.info("Saved to " + destination.getCanonicalPath());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return true;
}

From source file:com.cloudera.flume.conf.FlumeBuilder.java

public static Pair<EventSource, EventSink> buildNode(Context context, File f)
        throws IOException, RecognitionException, FlumeSpecException {
    CommonTree t = parseNodeFile(f.getCanonicalPath());
    if (t.getText() != "NODE") {
        throw new FlumeSpecException("fail, expected node but had " + t.toStringTree());
    }/*from   w ww .  j  a  v  a  2s .  c o m*/
    // String host = t.getChild(0).getText();
    CommonTree tsrc = (CommonTree) t.getChild(0);
    CommonTree tsnk = (CommonTree) t.getChild(1);

    return new Pair<EventSource, EventSink>(buildEventSource(context, tsrc),
            buildEventSink(context, tsnk, sinkFactory));
}

From source file:at.gv.egiz.pdfas.common.utils.ImageUtils.java

public static File getImageFile(String imageFile, ISettings settings) throws PdfAsException, IOException {
    File img_file = new File(imageFile);
    if (!img_file.isAbsolute()) {
        logger.debug("Image file declaration is relative. Prepending path of resources directory.");
        logger.debug("Image Location: " + settings.getWorkingDirectory() + File.separator + imageFile);
        img_file = new File(settings.getWorkingDirectory() + File.separator + imageFile);
    } else {//w  w w  . j av  a2 s  .  c  om
        logger.debug("Image file declaration is absolute. Skipping file relocation.");
    }

    if (!img_file.exists()) {
        logger.debug("Image file \"" + img_file.getCanonicalPath() + "\" doesn't exist.");
        throw new PdfAsException("error.pdf.stamp.04");
    }

    return img_file;
}