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:org.mitre.scap.xccdf.XCCDFInterpreter.java

/**
 * @param args the command line arguments
 *///from  ww w  .  j  a v  a  2  s  .c o  m
public static void main(String[] args) throws IOException, XmlException, URISyntaxException {
    XCCDFInterpreter.generateExecutionTimeStr();
    BuildProperties buildProperties = BuildProperties.getInstance();

    //System.out.println();
    //System.out.println( buildProperties.getApplicationName()+" v"+ buildProperties.getApplicationVersion()+" build "+buildProperties.getApplicationBuild());
    //System.out.println("--------------------");
    //outputOsProperties();
    //System.out.println("--------------------");
    //System.out.println();

    // Define the commandline options
    @SuppressWarnings("static-access")
    Option help = OptionBuilder.withDescription("display usage").withLongOpt("help").create('h');

    @SuppressWarnings("static-access")
    Option workingDir = OptionBuilder.hasArg().withArgName("FILE").withDescription("use result directory FILE")
            .withLongOpt("result-dir").create('R');

    @SuppressWarnings("static-access")
    Option xccdfResultFilename = OptionBuilder.hasArg().withArgName("FILENAME")
            .withDescription("use result filename FILENAME").withLongOpt("xccdf-result-filename").create("F");

    @SuppressWarnings("static-access")
    Option nocpe = OptionBuilder.withDescription("do not process CPE references").withLongOpt("no-cpe")
            .create();

    @SuppressWarnings("static-access")
    Option noresults = OptionBuilder.withDescription("do not display rule results").withLongOpt("no-results")
            .create();

    @SuppressWarnings("static-access")
    Option nocheck = OptionBuilder.withDescription("do not process checks").withLongOpt("no-check").create();

    @SuppressWarnings("static-access")
    Option profile = OptionBuilder.hasArg().withArgName("PROFILE").withDescription("use given profile id")
            .withLongOpt("profile-id").create('P');

    @SuppressWarnings("static-access")
    Option ssValidation = OptionBuilder.hasArg().withArgName("SS-VALIDATION")
            .withDescription("use given validation id").withLongOpt("ssValidation-id").create("S");

    @SuppressWarnings("static-access")
    Option cpeDictionary = OptionBuilder.hasArg().withArgName("FILE")
            .withDescription("use given CPE 2.0 Dictionary file").withLongOpt("cpe-dictionary").create('C');

    @SuppressWarnings("static-access")
    Option cpeOVALDefinition = OptionBuilder.hasArg().withArgName("FILE")
            .withDescription("use given CPE OVAL definition file for CPE evaluation").withLongOpt("cpe-oval")
            .create('c');

    @SuppressWarnings("static-access")
    Option verbose = OptionBuilder.withDescription("produce verbose output").create("v");

    // Build the options list
    Options options = new Options();
    options.addOption(help);
    options.addOption(workingDir);
    options.addOption(xccdfResultFilename);
    options.addOption(profile);
    options.addOption(ssValidation);
    options.addOption(nocpe);
    options.addOption(noresults);
    options.addOption(nocheck);
    options.addOption(cpeDictionary);
    options.addOption(cpeOVALDefinition);
    options.addOption(verbose);

    // create the parser
    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        String[] remainingArgs = line.getArgs();

        if (line.hasOption("help") || remainingArgs.length != 1) {
            if (remainingArgs.length != 1) {
                System.err.print("Invalid arguments: ");
                for (String arg : remainingArgs) {
                    System.err.print("'" + arg + "' ");
                }
                System.out.println();
            }

            // automatically generate the help statement
            System.out.println();
            showHelp(options);
            System.exit(0);
        }

        File xccdfFile = new File(remainingArgs[0]);

        if (!xccdfFile.exists()) {
            System.err.println(
                    "!! the specified XCCDF file '" + xccdfFile.getAbsolutePath() + "' does not exist!");
            System.exit(1);
        }

        XCCDFInterpreter interpreter = new XCCDFInterpreter(xccdfFile.getCanonicalFile());

        //System.out.println("** validating XCCDF content");

        if (!interpreter.validate()) {
            System.err.println("!! the XCCDF document is invalid. aborting.");
            System.exit(8);
        }

        if (line.hasOption(verbose.getOpt())) {
            verboseOutput = true;
            interpreter.setVerboseOutput(true);
        }

        if (line.hasOption(workingDir.getOpt())) {
            String lineOpt = line.getOptionValue(workingDir.getOpt());
            String workingDirValue = (lineOpt == null) ? "" : lineOpt;

            File f = new File(workingDirValue);
            if (!f.exists()) {
                if (verboseOutput)
                    System.out.println("** creating directory: " + f.getAbsolutePath());
                if (!f.mkdirs()) {
                    System.err.println("!! unable to create the result directory: " + f.getAbsolutePath());
                    System.exit(2);
                }
            }

            if (!f.isDirectory()) {
                System.err.println("!! the path specified for the result directory is not a directory: "
                        + f.getAbsolutePath());
                System.exit(3);
            }

            if (!f.canWrite()) {
                System.err.println("!! the path specified for the result directory is not writable: "
                        + f.getAbsolutePath());
                System.exit(4);
            }
            interpreter.setResultDirectory(f);
        }

        if (line.hasOption(xccdfResultFilename.getOpt())) {
            interpreter.setXccdfResultsFilename(line.getOptionValue(xccdfResultFilename.getOpt()));
        }

        if (line.hasOption(profile.getOpt())) {
            interpreter.setProfileId(line.getOptionValue(profile.getOpt()));
        }

        if (line.hasOption(ssValidation.getOpt())) {
            interpreter.setssValidationId(line.getOptionValue(ssValidation.getOpt()));
        }

        if (line.hasOption(nocpe.getLongOpt())) {
            interpreter.setProcessCPE(false);
        }

        if (line.hasOption(noresults.getLongOpt())) {
            interpreter.setDisplayResults(false);
        }

        if (line.hasOption(nocheck.getLongOpt())) {
            interpreter.setProcessChecks(false);
        }

        if (interpreter.processCPE == true) {

            if (line.hasOption(cpeDictionary.getOpt())) {
                String lineOpt = line.getOptionValue(cpeDictionary.getOpt());
                String cpeDict = (lineOpt == null) ? "" : lineOpt;

                File f = new File(cpeDict);

                if (!f.exists()) {
                    System.err.println("The CPE dictionary file does not exist: " + f.getAbsolutePath());
                    System.exit(5);
                }

                if (!f.isFile()) {
                    System.err.println("The path specified for the CPE dictionary file is not a file: "
                            + f.getAbsolutePath());
                    System.exit(6);
                }

                if (!f.canRead()) {
                    System.err.println("The path specified for the CPE dictionary file is not readable: "
                            + f.getAbsolutePath());
                    System.exit(7);
                }
                interpreter.setCPEDictionaryFile(f);
            }

            if (line.hasOption(cpeOVALDefinition.getOpt())) {
                String lineOpt = line.getOptionValue(cpeOVALDefinition.getOpt());
                String cpeOVAL = (lineOpt == null) ? "" : lineOpt;

                File f = new File(cpeOVAL);

                if (!f.exists()) {
                    System.err.println(
                            "!! the CPE OVAL inventory definition file does not exist: " + f.getAbsolutePath());
                    System.exit(5);
                }

                if (!f.isFile()) {
                    System.err.println(
                            "!! the path specified for the CPE OVAL inventory definition file is not a file: "
                                    + f.getAbsolutePath());
                    System.exit(6);
                }

                if (!f.canRead()) {
                    System.err.println(
                            "!! the path specified for the CPE OVAL inventory definition file is not readable: "
                                    + f.getAbsolutePath());
                    System.exit(7);
                }
                interpreter.setCPEOVALDefinitionFile(f);
            }

        } // END IF processCPE

        interpreter.process();

    } catch (ParseException ex) {
        System.err.println("!! parsing failed : " + ex.getMessage());
        System.out.println();
        showHelp(options);
    } catch (ProfileNotFoundException ex) {
        if (verboseOutput == true)
            ex.printStackTrace();
        else
            System.err.println("!! checklist processing failed : " + ex.getMessage());
    } catch (CircularReferenceException ex) {
        System.err.println("!! checklist processing failed : " + ex.getMessage());
        if (verboseOutput == true)
            ex.printStackTrace();
        else
            System.err.println("!! checklist processing failed : " + ex.getMessage());
    } catch (ExtensionScopeException ex) {
        if (verboseOutput == true)
            ex.printStackTrace();
        else
            System.err.println("!! checklist processing failed : " + ex.getMessage());
    } catch (ItemNotFoundException ex) {
        if (verboseOutput == true)
            ex.printStackTrace();
        else
            System.err.println("!! checklist processing failed : " + ex.getMessage());
    } catch (PropertyNotFoundException ex) {
        if (verboseOutput == true)
            ex.printStackTrace();
        else
            System.err.println("!! checklist processing failed : " + ex.getMessage());
    } catch (CPEEvaluationException ex) {
        if (verboseOutput == true)
            ex.printStackTrace();
        else
            System.err.println("!! checklist processing failed : " + ex.getMessage());
    } catch (Exception ex) {
        if (verboseOutput == true)
            ex.printStackTrace();
        else
            System.err.println("!! checklist processing failed : " + ex.getMessage());
    }

}

From source file:Main.java

/**
 * A 'checked exception free' version of {@link File#getCanonicalFile()}.
 *///from   w w  w  . jav a  2 s  .  co  m
public static File canonicalFile(File file) {
    try {
        return file.getCanonicalFile();
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

public static boolean equals(File file1, File file2) {
    try {/* w w  w. j a  va  2s.c o  m*/
        file1 = file1.getCanonicalFile();
        file2 = file2.getCanonicalFile();
    } catch (IOException ignore) {
        return false;
    }
    return file1.equals(file2);
}

From source file:Main.java

/**
 * Gets canonical file.//from  ww  w  .j  a  v a  2s .com
 *
 * @param filePath
 *          String - file path
 * @return file File
 */
private static File getCanonicalFile(final String filePath) {
    final File file = new File(filePath);
    try {
        return file.getCanonicalFile();
    } catch (final IOException e) {
        return file.getAbsoluteFile();
    }
}

From source file:Main.java

private static File getTestDataDir() {
    // Search each parent directory looking for "src/google/protobuf".
    File ancestor = new File(".");
    try {/*  w  ww  .j  a va 2  s . co  m*/
        ancestor = ancestor.getCanonicalFile();
    } catch (IOException e) {
        throw new RuntimeException("Couldn't get canonical name of working directory.", e);
    }
    while (ancestor != null && ancestor.exists()) {
        if (new File(ancestor, "src/google/protobuf").exists()) {
            return new File(ancestor, "src/google/protobuf/testdata");
        }
        ancestor = ancestor.getParentFile();
    }

    throw new RuntimeException("Could not find golden files.  This test must be run from within the "
            + "protobuf source package so that it can read test data files from the " + "C++ source tree.");
}

From source file:Main.java

public static File getRelativePath(final File file, final File relativeToThis) {
    try {/* w w w . java 2s  . co m*/
        return getRelativePath(file.getCanonicalFile(), relativeToThis.getCanonicalFile(), "");
    } catch (final IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:piecework.util.FileUtility.java

public static final boolean isAncestorOf(File parent, File child) throws IOException {
    File canonicalParent = parent.getCanonicalFile();
    File canonicalChild = child.getCanonicalFile();

    File p = canonicalChild.getParentFile();
    while (p != null) {
        if (canonicalParent.equals(p))
            return true;
        p = p.getParentFile();/*from  w  w w .j a v a 2s. c  o  m*/
    }
    return false;
}

From source file:com.igitras.codegen.common.utils.Utils.java

public static File toCanonicalFile(File file) {
    try {//from  w w w  .  j  a va2s . c om
        return file.getCanonicalFile();
    } catch (IOException e) {
        return null;
    }
}

From source file:net.nicholaswilliams.java.teamcity.plugin.buildNumber.PluginFileUtils.java

public static File getCanonicalFile(File file) {
    try {// w  w w .  j  a v  a2s.  c o  m
        return file.getCanonicalFile();
    } catch (IOException e) {
        throw new RuntimeException(
                "Failed to get canonical file for absolute path [" + file.getAbsolutePath() + "].", e);
    }
}

From source file:name.martingeisse.ecobuild.util.EcobuildFileUtil.java

/**
 * Like file.getCanonicalFile(), but wraps {@link IOException} in {@link FatalBuildException}.
 * @param file the file to get the canonical file from
 * @return the canonical file/*from   ww w. j a  v a 2 s .  c om*/
 */
public static File getCanonicalFile(File file) {
    try {
        return file.getCanonicalFile();
    } catch (IOException e) {
        throw new FatalBuildException("getCanonicalFile() failed", e);
    }
}