Example usage for java.io File getCanonicalFile

List of usage examples for java.io File getCanonicalFile

Introduction

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

Prototype

public File getCanonicalFile() throws IOException 

Source Link

Document

Returns the canonical form of this abstract pathname.

Usage

From source file:json_to_xml_1.java

public int execute(String args[]) throws ProgramTerminationException {
    this.getInfoMessages().clear();

    if (args.length < 2) {
        throw constructTermination("messageArgumentsMissing", null,
                getI10nString("messageArgumentsMissingUsage") + "\n\tjson_to_xml_1 "
                        + getI10nString("messageParameterList") + "\n");
    }// w  ww.  j av  a  2s .com

    File resultInfoFile = new File(args[1]);

    try {
        resultInfoFile = resultInfoFile.getCanonicalFile();
    } catch (SecurityException ex) {
        throw constructTermination("messageResultInfoFileCantGetCanonicalPath", ex, null,
                resultInfoFile.getAbsolutePath());
    } catch (IOException ex) {
        throw constructTermination("messageResultInfoFileCantGetCanonicalPath", ex, null,
                resultInfoFile.getAbsolutePath());
    }

    if (resultInfoFile.exists() == true) {
        if (resultInfoFile.isFile() == true) {
            if (resultInfoFile.canWrite() != true) {
                throw constructTermination("messageResultInfoFileIsntWritable", null, null,
                        resultInfoFile.getAbsolutePath());
            }
        } else {
            throw constructTermination("messageResultInfoPathIsntAFile", null, null,
                    resultInfoFile.getAbsolutePath());
        }
    }

    json_to_xml_1.resultInfoFile = resultInfoFile;

    File jobFile = new File(args[0]);

    try {
        jobFile = jobFile.getCanonicalFile();
    } catch (SecurityException ex) {
        throw constructTermination("messageJobFileCantGetCanonicalPath", ex, null, jobFile.getAbsolutePath());
    } catch (IOException ex) {
        throw constructTermination("messageJobFileCantGetCanonicalPath", ex, null, jobFile.getAbsolutePath());
    }

    if (jobFile.exists() != true) {
        throw constructTermination("messageJobFileDoesntExist", null, null, jobFile.getAbsolutePath());
    }

    if (jobFile.isFile() != true) {
        throw constructTermination("messageJobPathIsntAFile", null, null, jobFile.getAbsolutePath());
    }

    if (jobFile.canRead() != true) {
        throw constructTermination("messageJobFileIsntReadable", null, null, jobFile.getAbsolutePath());
    }

    System.out.println("json_to_xml_1: " + getI10nStringFormatted("messageCallDetails",
            jobFile.getAbsolutePath(), resultInfoFile.getAbsolutePath()));

    File inputFile = null;
    File outputFile = null;

    try {
        XMLInputFactory inputFactory = XMLInputFactory.newInstance();
        InputStream in = new FileInputStream(jobFile);
        XMLEventReader eventReader = inputFactory.createXMLEventReader(in);

        while (eventReader.hasNext() == true) {
            XMLEvent event = eventReader.nextEvent();

            if (event.isStartElement() == true) {
                String tagName = event.asStartElement().getName().getLocalPart();

                if (tagName.equals("json-input-file") == true) {
                    StartElement inputFileElement = event.asStartElement();
                    Attribute pathAttribute = inputFileElement.getAttributeByName(new QName("path"));

                    if (pathAttribute == null) {
                        throw constructTermination("messageJobFileEntryIsMissingAnAttribute", null, null,
                                jobFile.getAbsolutePath(), tagName, "path");
                    }

                    String inputFilePath = pathAttribute.getValue();

                    if (inputFilePath.isEmpty() == true) {
                        throw constructTermination("messageJobFileAttributeValueIsEmpty", null, null,
                                jobFile.getAbsolutePath(), tagName, "path");
                    }

                    inputFile = new File(inputFilePath);

                    if (inputFile.isAbsolute() != true) {
                        inputFile = new File(
                                jobFile.getAbsoluteFile().getParent() + File.separator + inputFilePath);
                    }

                    try {
                        inputFile = inputFile.getCanonicalFile();
                    } catch (SecurityException ex) {
                        throw constructTermination("messageInputFileCantGetCanonicalPath", ex, null,
                                new File(inputFilePath).getAbsolutePath(), jobFile.getAbsolutePath());
                    } catch (IOException ex) {
                        throw constructTermination("messageInputFileCantGetCanonicalPath", ex, null,
                                new File(inputFilePath).getAbsolutePath(), jobFile.getAbsolutePath());
                    }

                    if (inputFile.exists() != true) {
                        throw constructTermination("messageInputFileDoesntExist", null, null,
                                inputFile.getAbsolutePath(), jobFile.getAbsolutePath());
                    }

                    if (inputFile.isFile() != true) {
                        throw constructTermination("messageInputPathIsntAFile", null, null,
                                inputFile.getAbsolutePath(), jobFile.getAbsolutePath());
                    }

                    if (inputFile.canRead() != true) {
                        throw constructTermination("messageInputFileIsntReadable", null, null,
                                inputFile.getAbsolutePath(), jobFile.getAbsolutePath());
                    }
                } else if (tagName.equals("xml-output-file") == true) {
                    StartElement outputFileElement = event.asStartElement();
                    Attribute pathAttribute = outputFileElement.getAttributeByName(new QName("path"));

                    if (pathAttribute == null) {
                        throw constructTermination("messageJobFileEntryIsMissingAnAttribute", null, null,
                                jobFile.getAbsolutePath(), tagName, "path");
                    }

                    String outputFilePath = pathAttribute.getValue();

                    if (outputFilePath.isEmpty() == true) {
                        throw constructTermination("messageJobFileAttributeValueIsEmpty", null, null,
                                jobFile.getAbsolutePath(), tagName, "path");
                    }

                    outputFile = new File(outputFilePath);

                    if (outputFile.isAbsolute() != true) {
                        outputFile = new File(
                                jobFile.getAbsoluteFile().getParent() + File.separator + outputFilePath);
                    }

                    try {
                        outputFile = outputFile.getCanonicalFile();
                    } catch (SecurityException ex) {
                        throw constructTermination("messageOutputFileCantGetCanonicalPath", ex, null,
                                new File(outputFilePath).getAbsolutePath(), jobFile.getAbsolutePath());
                    } catch (IOException ex) {
                        throw constructTermination("messageOutputFileCantGetCanonicalPath", ex, null,
                                new File(outputFilePath).getAbsolutePath(), jobFile.getAbsolutePath());
                    }

                    if (outputFile.exists() == true) {
                        if (outputFile.isFile() == true) {
                            if (outputFile.canWrite() != true) {
                                throw constructTermination("messageOutputFileIsntWritable", null, null,
                                        outputFile.getAbsolutePath());
                            }
                        } else {
                            throw constructTermination("messageOutputPathIsntAFile", null, null,
                                    outputFile.getAbsolutePath());
                        }
                    }
                }
            }
        }
    } catch (XMLStreamException ex) {
        throw constructTermination("messageJobFileErrorWhileReading", ex, null, jobFile.getAbsolutePath());
    } catch (SecurityException ex) {
        throw constructTermination("messageJobFileErrorWhileReading", ex, null, jobFile.getAbsolutePath());
    } catch (IOException ex) {
        throw constructTermination("messageJobFileErrorWhileReading", ex, null, jobFile.getAbsolutePath());
    }

    if (inputFile == null) {
        throw constructTermination("messageJobFileNoInputFile", null, null, jobFile.getAbsolutePath());
    }

    if (outputFile == null) {
        throw constructTermination("messageJobFileNoOutputFile", null, null, jobFile.getAbsolutePath());
    }

    StringBuilder stringBuilder = new StringBuilder();

    try {
        JSONObject json = new JSONObject(new JSONTokener(new BufferedReader(new FileReader(inputFile))));

        stringBuilder.append(XML.toString(json));
    } catch (Exception ex) {
        throw constructTermination("messageConversionError", ex, null, inputFile.getAbsolutePath());
    }

    try {
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8"));

        writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        writer.write(
                "<!-- This file was created by json_to_xml_1, which is free software licensed under the GNU Affero General Public License 3 or any later version (see https://github.com/publishing-systems/digital_publishing_workflow_tools/ and http://www.publishing-systems.org). -->\n");
        writer.write(stringBuilder.toString());

        writer.flush();
        writer.close();
    } catch (FileNotFoundException ex) {
        throw constructTermination("messageOutputFileWritingError", ex, null, outputFile.getAbsolutePath());
    } catch (UnsupportedEncodingException ex) {
        throw constructTermination("messageOutputFileWritingError", ex, null, outputFile.getAbsolutePath());
    } catch (IOException ex) {
        throw constructTermination("messageOutputFileWritingError", ex, null, outputFile.getAbsolutePath());
    }

    return 0;
}

From source file:io.spring.initializr.web.project.MainController.java

@RequestMapping(path = "/starter.tgz", produces = "application/x-compress")
@ResponseBody/*from   w  w w  .j av  a 2  s.  c o m*/
public ResponseEntity<byte[]> springTgz(BasicProjectRequest basicRequest) throws IOException {
    ProjectRequest request = (ProjectRequest) basicRequest;
    File dir = this.projectGenerator.generateProjectStructure(request);

    File download = this.projectGenerator.createDistributionFile(dir, ".tar.gz");

    String wrapperScript = getWrapperScript(request);
    new File(dir, wrapperScript).setExecutable(true);
    Tar zip = new Tar();
    zip.setProject(new Project());
    zip.setDefaultexcludes(false);
    TarFileSet set = zip.createTarFileSet();
    set.setDir(dir);
    set.setFileMode("755");
    set.setIncludes(wrapperScript);
    set.setDefaultexcludes(false);
    set = zip.createTarFileSet();
    set.setDir(dir);
    set.setIncludes("**,");
    set.setExcludes(wrapperScript);
    set.setDefaultexcludes(false);
    zip.setDestFile(download.getCanonicalFile());
    Tar.TarCompressionMethod method = new Tar.TarCompressionMethod();
    method.setValue("gzip");
    zip.setCompression(method);
    zip.execute();
    return upload(download, dir, generateFileName(request, "tar.gz"), "application/x-compress");
}

From source file:fur.shadowdrake.minecraft.InstallPanel.java

/**
 * Determines whether the specified file is a Symbolic Link rather than an
 * actual file.//from   w w  w  . j av  a  2s .co m
 * <p>
 * Will not return true if there is a Symbolic Link anywhere in the path,
 * only if the specific file is.
 * <p>
 * <b>Note:</b> the current implementation always returns {@code false} if
 * the system is detected as Windows using
 * {@link FilenameUtils#isSystemWindows()}
 *
 * @param file the file to check
 * @return true if the file is a Symbolic Link
 * @throws IOException if an IO error occurs while checking the file
 * @since 2.0
 */
private static boolean isSymlink(File file) throws IOException {
    if (file == null) {
        throw new NullPointerException("File must not be null");
    }

    File fileInCanonicalDir;
    if (file.getParent() == null) {
        fileInCanonicalDir = file;
    } else {
        File canonicalDir = file.getParentFile().getCanonicalFile();
        fileInCanonicalDir = new File(canonicalDir, file.getName());
    }

    return !fileInCanonicalDir.getCanonicalFile().equals(fileInCanonicalDir.getAbsoluteFile());
}

From source file:org.opennms.upgrade.implementations.JmxRrdMigratorOffline.java

/**
 * Fixes a JMX graph template file./* w  ww  .  j  a va  2  s .co m*/
 *
 * @param jmxTemplateFile the JMX template file
 * @throws OnmsUpgradeException the OpenNMS upgrade exception
 */
private void fixJmxGraphTemplateFile(File jmxTemplateFile) throws OnmsUpgradeException {
    try {
        log("Updating JMX graph templates on %s\n", jmxTemplateFile);
        zipFile(jmxTemplateFile);
        backupFiles.add(new File(jmxTemplateFile.getAbsolutePath() + ZIP_EXT));
        File outputFile = new File(jmxTemplateFile.getCanonicalFile() + ".temp");
        FileWriter w = new FileWriter(outputFile);
        Pattern defRegex = Pattern.compile("DEF:.+:(.+\\..+):");
        Pattern colRegex = Pattern.compile("\\.columns=(.+)$");
        Pattern incRegex = Pattern.compile("^include.directory=(.+)$");
        List<File> externalFiles = new ArrayList<File>();
        boolean override = false;
        LineIterator it = FileUtils.lineIterator(jmxTemplateFile);
        while (it.hasNext()) {
            String line = it.next();
            Matcher m = incRegex.matcher(line);
            if (m.find()) {
                File includeDirectory = new File(jmxTemplateFile.getParentFile(), m.group(1));
                if (includeDirectory.isDirectory()) {
                    FilenameFilter propertyFilesFilter = new FilenameFilter() {
                        @Override
                        public boolean accept(File dir, String name) {
                            return (name.endsWith(".properties"));
                        }
                    };
                    for (File file : includeDirectory.listFiles(propertyFilesFilter)) {
                        externalFiles.add(file);
                    }
                }
            }
            m = colRegex.matcher(line);
            if (m.find()) {
                String[] badColumns = m.group(1).split(",(\\s)?");
                for (String badDs : badColumns) {
                    String fixedDs = getFixedDsName(badDs);
                    if (fixedDs.equals(badDs)) {
                        continue;
                    }
                    if (badMetrics.contains(badDs)) {
                        override = true;
                        log("  Replacing bad data source %s with %s on %s\n", badDs, fixedDs, line);
                        line = line.replaceAll(badDs, fixedDs);
                    } else {
                        log("  Warning: a bad data source not related with JMX has been found: %s (this won't be updated)\n",
                                badDs);
                    }
                }
            }
            m = defRegex.matcher(line);
            if (m.find()) {
                String badDs = m.group(1);
                if (badMetrics.contains(badDs)) {
                    override = true;
                    String fixedDs = getFixedDsName(badDs);
                    log("  Replacing bad data source %s with %s on %s\n", badDs, fixedDs, line);
                    line = line.replaceAll(badDs, fixedDs);
                } else {
                    log("  Warning: a bad data source not related with JMX has been found: %s (this won't be updated)\n",
                            badDs);
                }
            }
            w.write(line + "\n");
        }
        LineIterator.closeQuietly(it);
        w.close();
        if (override) {
            FileUtils.deleteQuietly(jmxTemplateFile);
            FileUtils.moveFile(outputFile, jmxTemplateFile);
        } else {
            FileUtils.deleteQuietly(outputFile);
        }
        if (!externalFiles.isEmpty()) {
            for (File configFile : externalFiles) {
                fixJmxGraphTemplateFile(configFile);
            }
        }
    } catch (Exception e) {
        throw new OnmsUpgradeException("Can't fix " + jmxTemplateFile + " because " + e.getMessage(), e);
    }
}

From source file:org.wso2.carbon.webapp.mgt.WebApplication.java

/**
 * Return a File object representing the "application root" directory
 * for our associated Host.//from ww w.  j a  va 2 s.  c o m
 *
 * @return The AppBase
 *         //TODO - when webapp exploding is supported for stratos, this should return the tenant's webapp dir
 */
protected File getAppBase() {
    File appBase = null;
    File file = new File(DataHolder.getCarbonTomcatService().getTomcat().getHost().getAppBase());
    /*if (!file.isAbsolute()) {
    file = new File(System.getProperty("catalina.base"),
                    host.getAppBase());
    }*/
    try {
        appBase = file.getCanonicalFile();
    } catch (IOException e) {
        appBase = file;
    }
    return appBase;
}

From source file:de.adv_online.aaa.profiltool.ProfilDialog.java

public void initialise(Converter c, Options o, ShapeChangeResult r, String xmi)
        throws ShapeChangeAbortException {

    try {/*from   ww w  .j a  v a  2  s . co m*/
        String msg = "Akzeptieren Sie die in der mit diesem Tool ausgelieferten Datei 'Lizenzbedingungen zur Nutzung von Softwareskripten.doc' beschriebenen Lizenzbedingungen?"; // Meldung
        if (msg != null) {
            Object[] options = { "Ja", "Nein" };
            int val = JOptionPane.showOptionDialog(null, msg, "Confirmation", JOptionPane.OK_CANCEL_OPTION,
                    JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
            if (val == 1)
                System.exit(0);
        }
    } catch (Exception e) {
        System.out.println("Fehler in Dialog: " + e.toString());
    }

    options = o;

    File eapFile = new File(xmi);
    try {
        eap = eapFile.getCanonicalFile().getAbsolutePath();
    } catch (IOException e) {
        eap = "ERROR.eap";
    }

    converter = new Converter(options, r);
    result = r;
    modelTransformed = false;
    transformationRunning = false;

    StatusBoard.getStatusBoard().registerStatusReader(this);

    // frame
    setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

    // panel
    newContentPane = new JPanel(new BorderLayout());
    newContentPane.setOpaque(true);
    setContentPane(newContentPane);

    newContentPane.add(createMainTab(), BorderLayout.CENTER);

    statusBar = new StatusBar();

    Box fileBox = Box.createVerticalBox();
    fileBox.add(createStartPanel());
    fileBox.add(statusBar);

    newContentPane.add(fileBox, BorderLayout.SOUTH);

    int height = 610;
    int width = 560;

    pack();

    Insets fI = getInsets();
    setSize(width + fI.right + fI.left, height + fI.top + fI.bottom);
    Dimension sD = Toolkit.getDefaultToolkit().getScreenSize();
    setLocation((sD.width - width) / 2, (sD.height - height) / 2);
    this.setMinimumSize(new Dimension(width, height));

    // frame closing
    WindowListener listener = new WindowAdapter() {
        public void windowClosing(WindowEvent w) {
            //JOptionPane.showMessageDialog(null, "Nein", "NO", JOptionPane.ERROR_MESSAGE);
            closeDialog();
        }
    };
    addWindowListener(listener);
}

From source file:io.spring.initializr.web.project.MainController.java

@RequestMapping("/starter.zip")
@ResponseBody/*from  ww  w  .j  a v a2  s. c o m*/
public ResponseEntity<byte[]> springZip(BasicProjectRequest basicRequest) throws IOException {
    ProjectRequest request = (ProjectRequest) basicRequest;
    File dir = this.projectGenerator.generateProjectStructure(request);

    File download = this.projectGenerator.createDistributionFile(dir, ".zip");

    String wrapperScript = getWrapperScript(request);
    new File(dir, wrapperScript).setExecutable(true);
    Zip zip = new Zip();
    zip.setProject(new Project());
    zip.setDefaultexcludes(false);
    ZipFileSet set = new ZipFileSet();
    set.setDir(dir);
    set.setFileMode("755");
    set.setIncludes(wrapperScript);
    set.setDefaultexcludes(false);
    zip.addFileset(set);
    set = new ZipFileSet();
    set.setDir(dir);
    set.setIncludes("**,");
    set.setExcludes(wrapperScript);
    set.setDefaultexcludes(false);
    zip.addFileset(set);
    zip.setDestFile(download.getCanonicalFile());
    zip.execute();
    return upload(download, dir, generateFileName(request, "zip"), "application/zip");
}

From source file:uk.ac.soton.simulation.jsit.core.ModelVersioningAssistant.java

boolean isInDirectoryList(List<File> dirs, File checkFile) {

    assert checkFile.isFile();

    try {/*from   w w w.  java  2  s .c om*/
        for (File dir : dirs) {
            assert dir.isDirectory();
            File checkDir = dir.getCanonicalFile();
            logger.trace("Checking if {} is under {}...", checkFile.getAbsolutePath(),
                    checkDir.getAbsolutePath());
            File currCheckParent = checkFile.getParentFile();
            while (currCheckParent != null) {
                currCheckParent = currCheckParent.getCanonicalFile();
                if (currCheckParent.equals(checkDir)) {
                    logger.trace("Found {} in {}", checkFile.getName(), currCheckParent.getAbsolutePath());
                    return true;
                }

                currCheckParent = currCheckParent.getParentFile();
            }
        }
    } catch (IOException e) {
        throw new ModelVersioningException("Error getting canonical files from filesystem", e);
    }
    return false; // Didn't find it anywhere

}

From source file:com.sikulix.core.SX.java

private static File getFileMake(Object... args) {
    if (args.length < 1) {
        return null;
    }/*  w  w w  .j  av  a  2  s. co  m*/
    Object oPath = args[0];
    Object oSub = "";
    if (args.length > 1) {
        oSub = args[1];
    }
    File fPath = null;
    if (isNotSet(oSub)) {
        fPath = new File(oPath.toString());
    } else {
        fPath = new File(oPath.toString(), oSub.toString());
    }
    try {
        fPath = fPath.getCanonicalFile();
    } catch (IOException e) {
        error("getFile: %s %s error(%s)", oPath, oSub, e.getMessage());
    }
    return fPath;
}

From source file:org.finra.herd.tools.uploader.UploaderController.java

/**
 * Returns the list of File objects created from the specified list of local files after they are validated for existence and read access.
 *
 * @param localDir the local path to directory to be used to construct the relative absolute paths for the files to be validated
 * @param manifestFiles the list of manifest files that contain file paths relative to <code>localDir</code> to be validated.
 *
 * @return the list of validated File objects
 * @throws IllegalArgumentException if <code>localDir</code> or local files are not valid
 * @throws IOException if there is a filesystem query issue to construct a canonical form of an abstract file path
 *//*from  www.  j a  v a  2s. c  om*/
private List<File> getValidatedLocalFiles(String localDir, List<ManifestFile> manifestFiles)
        throws IllegalArgumentException, IOException {
    // Create a "directory" file and ensure it is valid.
    File directory = new File(localDir);

    if (!directory.isDirectory() || !directory.canRead()) {
        throw new IllegalArgumentException(
                String.format("Invalid local base directory: %s", directory.getAbsolutePath()));
    }

    // For each file path from the list, create Java "File" objects to the real file location (i.e. with the directory
    // prepended to it), and verify that the file exists. If not, an IllegalArgumentException will be thrown.
    String basedir = directory.getAbsolutePath();
    List<File> resultFiles = new ArrayList<>();

    for (ManifestFile manifestFile : manifestFiles) {
        // Create a "real file" that points to the actual file on the file system (i.e. directory + manifest file path).
        String realFullPathFileName = Paths.get(basedir, manifestFile.getFileName()).toFile().getPath();
        realFullPathFileName = realFullPathFileName.replaceAll("\\\\", "/");
        File realFile = new File(realFullPathFileName);

        // Verify that the file exists and is readable.
        HerdFileUtils.verifyFileExistsAndReadable(realFile);

        // Verify that the name of the actual file on the file system exactly matches the name of the real file on the file system.
        // This will handle potential case issues on Windows systems. Note that the canonical file gives the actual file name on the system.
        // The non-canonical file gives the name as it was specified in the manifest.
        String realFileName = realFile.getName();
        String manifestFileName = realFile.getCanonicalFile().getName();

        if (!realFileName.equals(manifestFileName)) {
            throw new IllegalArgumentException("Manifest filename \"" + manifestFileName
                    + "\" does not match actual filename \"" + realFileName + "\".");
        }

        resultFiles.add(realFile);
    }

    return resultFiles;
}