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:kr.ac.kaist.wala.hybridroid.callgraph.AndroidHybridAnalysisScope.java

private static AndroidHybridAnalysisScope setUpJsAnalysisScope(String dir, AndroidHybridAnalysisScope scope,
        Set<URL> htmls) throws IllegalArgumentException, IOException {

    JavaScriptLoader.addBootstrapFile(WebUtil.preamble);
    if (SystemUtils.IS_OS_WINDOWS) {
        scope.addToScope(scope.getJavaScriptLoader(),
                new SourceURLModule(AndroidHybridAppModel.class.getResource("prologue.js")) {
                    @Override/*w w w. j  a v  a2  s.  c  om*/
                    public String getName() {
                        return "prologue.js";
                    }
                });
        scope.addToScope(scope.getJavaScriptLoader(),
                new SourceURLModule(AndroidHybridAppModel.class.getResource("preamble.js")) {
                    @Override
                    public String getName() {
                        return "preamble.js";
                    }
                });
    } else {
        scope.addToScope(scope.getJavaScriptLoader(),
                new SourceURLModule(AndroidHybridAppModel.class.getResource("prologue.js")) {
                    @Override
                    public String getName() {
                        return "prologue.js";
                    }
                });
        scope.addToScope(scope.getJavaScriptLoader(),
                new SourceURLModule(AndroidHybridAppModel.class.getResource("preamble.js")) {
                    @Override
                    public String getName() {
                        return "preamble.js";
                    }
                });
        //scope.addToScope(scope.getJavaScriptLoader(), JSCallGraphBuilderUtil.getPrologueFile("prologue.js"));
        //scope.addToScope(scope.getJavaScriptLoader(), JSCallGraphBuilderUtil.getPrologueFile("preamble.js"));
    }
    for (URL url : htmls) {
        try {
            File f = WebUtil.extractScriptFromHTML(url, DefaultSourceExtractor.factory).snd;
            scope.addToScope(scope.getJavaScriptLoader(), new SourceURLModule(f.toURI().toURL()));

            String jspath = f.getCanonicalPath();
            addScopeMap(Atom.findOrCreateAsciiAtom(url.toString()), Atom.findOrCreateAsciiAtom(
                    jspath.substring(jspath.lastIndexOf(File.separator) + 1, jspath.length())));
            if (DEBUG)
                System.err.println("#Loaded html: " + url.getFile());
        } catch (Error | RuntimeException e) {// | UnimplementedError |
            // Error e) {
            if (url.toString().startsWith("http")) {
                System.err.println("Cannot receive the response from the url: " + url);
            } else {
                String path = url.getPath();
                SourceModule dummy = new SourceURLModule(FileWriter
                        .makeHtmlFile(dir,
                                path.substring(path.lastIndexOf(File.separator) + 1, path.length() - 1), "")
                        .toURI().toURL());
                String dummypath = dummy.getName();
                if (DEBUG)
                    System.err.println("make dummy: " + dummypath);
                addScopeMap(Atom.findOrCreateAsciiAtom(url.toString()), Atom
                        .findOrCreateAsciiAtom(dummypath.substring(dummypath.lastIndexOf(File.separator) + 1)));
                scope.addToScope(scope.getJavaScriptLoader(), dummy);
            }
        }
    }

    return scope;
}

From source file:com.connexta.arbitro.TestUtil.java

/**
 * This creates the XACML request from a file
 *
 * @param rootDirectory   root directory of the  request files
 * @param versionDirectory   version directory of the  request files
 * @param requestId  request file name/*from w w  w. ja va  2s .c  o m*/
 * @return String or null if any error
 */
public static String createRequest(String rootDirectory, String versionDirectory, String requestId) {

    File file = new File(".");
    StringWriter writer = null;
    try {
        String filePath = file.getCanonicalPath() + File.separator + TestConstants.RESOURCE_PATH
                + File.separator + rootDirectory + File.separator + versionDirectory + File.separator
                + TestConstants.REQUEST_DIRECTORY + File.separator + requestId;

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setIgnoringComments(true);
        factory.setNamespaceAware(true);
        DocumentBuilder db = factory.newDocumentBuilder();
        Document doc = db.parse(new FileInputStream(filePath));
        DOMSource domSource = new DOMSource(doc);
        writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.transform(domSource, result);
        return writer.toString();
    } catch (Exception e) {
        log.error("Error while reading expected response from file ", e);
        //ignore any exception and return null
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                log.error("Error closing stream ", e);
                //ignore any exception and return null
            }
        }
    }
    return null;
}

From source file:de.darkblue.bongloader2.utils.ToolBox.java

public static boolean checkFilenamePattern(String pattern, File workingDirectory) {
    String[] fileNames = new String[] {
            ToolBox.getTargetFilename(workingDirectory, pattern, DEMO_RECORDING,
                    Recording.MovieFile.Quality.NQ),
            ToolBox.getTargetFilename(workingDirectory, pattern, DEMO_RECORDING_SERIES,
                    Recording.MovieFile.Quality.HQ) };

    boolean ok = true;
    for (int i = 0; i < fileNames.length; ++i) {
        try {//w  w  w  . j  a  v  a2 s  .  c o  m
            final String fileName = fileNames[i];
            ok = ok & ToolBox.isFilenameValid(fileName);
            final File file = new File(fileName);
            file.getCanonicalPath();
        } catch (IOException ex) {
            ok = false;
        }
    }

    return ok;
}

From source file:dotplugin.GraphViz.java

private static IStatus runDot(String format, File dotInput, File dotOutput) {
    // build the command line
    // double dpi = 96;
    // double widthInInches = -1;
    // double heightInInches = -1;

    List<String> cmd = new ArrayList<String>();
    try {/*from  w  ww. j  a  v  a 2  s.  c o  m*/
        cmd.add("-o" + dotOutput.getCanonicalPath());
        cmd.add("-T" + format);
        String commandLineExtension = Pref.getCommandLineExtension();
        // System.err.println("runDot:" + commandLineExtension);
        if (commandLineExtension != null) {
            String[] tokens = commandLineExtension.split(" ");
            cmd.addAll(Arrays.asList(tokens));
        }
        // System.err.println("runDot:" + dotInput.getAbsolutePath());
        cmd.add(dotInput.getAbsolutePath());
        return runDot(cmd.toArray(new String[cmd.size()]));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }
}

From source file:edu.umd.cs.submit.CommandLineSubmit.java

/**
 * @param p//from w w  w.  j  ava 2s  .  c om
 * @param find
 * @param files
 * @param userProps
 * @return
 * @throws IOException
 * @throws FileNotFoundException
 */
public static MultipartPostMethod createFilePost(Properties p, FindAllFiles find, Collection<File> files,
        Properties userProps) throws IOException, FileNotFoundException {
    // ========================== assemble zip file in byte array
    // ==============================
    String loginName = userProps.getProperty("loginName");
    String classAccount = userProps.getProperty("classAccount");
    String from = classAccount;
    if (loginName != null && !loginName.equals(classAccount))
        from += "/" + loginName;
    System.out.println(" submitted by " + from);
    System.out.println();
    System.out.println("Submitting the following files");
    ByteArrayOutputStream bytes = new ByteArrayOutputStream(4096);
    byte[] buf = new byte[4096];
    ZipOutputStream zipfile = new ZipOutputStream(bytes);
    zipfile.setComment("zipfile for CommandLineTurnin, version " + VERSION);
    for (File resource : files) {
        if (resource.isDirectory())
            continue;
        String relativePath = resource.getCanonicalPath().substring(find.rootPathLength + 1);
        System.out.println(relativePath);
        ZipEntry entry = new ZipEntry(relativePath);
        entry.setTime(resource.lastModified());

        zipfile.putNextEntry(entry);
        InputStream in = new FileInputStream(resource);
        try {
            while (true) {
                int n = in.read(buf);
                if (n < 0)
                    break;
                zipfile.write(buf, 0, n);
            }
        } finally {
            in.close();
        }
        zipfile.closeEntry();

    } // for each file
    zipfile.close();

    MultipartPostMethod filePost = new MultipartPostMethod(p.getProperty("submitURL"));

    p.putAll(userProps);
    // add properties
    for (Map.Entry<?, ?> e : p.entrySet()) {
        String key = (String) e.getKey();
        String value = (String) e.getValue();
        if (!key.equals("submitURL"))
            filePost.addParameter(key, value);
    }
    filePost.addParameter("submitClientTool", "CommandLineTool");
    filePost.addParameter("submitClientVersion", VERSION);
    byte[] allInput = bytes.toByteArray();
    filePost.addPart(new FilePart("submittedFiles", new ByteArrayPartSource("submit.zip", allInput)));
    return filePost;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.common.util.FileUtil.java

public static String getFilenameWithoutExtension(final String filename, final String extension)
        throws IOException {
    final File file = new File(filename);
    return file.getCanonicalPath().substring(file.getCanonicalPath().lastIndexOf(File.separator) + 1,
            file.getCanonicalPath().lastIndexOf(extension));
}

From source file:de.prozesskraft.pkraft.Perlcode.java

/**
 * writes a Process as Perlcode// www  .j  a v  a 2  s .c  o  m
 * @param process
 * @param outputDir
 * @throws IOException
 */
private static void writeProcessAsPerlcode(Process process, java.io.File outputDirProcess,
        java.io.File outputDirStep, boolean nolist) throws IOException {
    System.err.println("generating perlcode for process " + process.getName());
    writeFile.writeFile(new java.io.File(outputDirProcess.getCanonicalPath() + "/" + process.getName()),
            process.getProcessAsPerlScript(nolist));

    for (Step actualStep : process.getStep()) {
        if (!actualStep.getName().matches("^root$") && actualStep.getType().matches("automatic")) {
            writeStepAsPerlcode(process, actualStep.getName(), outputDirStep, nolist);
        }
    }
}

From source file:it.incipict.tool.profiles.util.ProfilesToolUtils.java

public static List<Survey> parseSurvey(File file) throws ProfilesToolException {
    List<Survey> surveys = new ArrayList<Survey>();

    Iterable<CSVRecord> records;
    try {//from  ww  w.j  a  v a  2s.c  o m
        Reader in = new FileReader(file.getCanonicalPath());
        records = CSVFormat.RFC4180.parse(in);
    } catch (IOException e) {
        throw new ProfilesToolException("error while reading files.", e);
    }

    // loop all surveys in CSV line by line
    // note: a single CSV can contain more surveys
    for (CSVRecord record : records) {
        int line = (int) record.getRecordNumber();
        // skip the first line because it simply contains the headers
        if (line > 1) {
            Survey survey = new Survey();
            List<String> answers = new ArrayList<String>();
            List<String> textualAnswers = new ArrayList<String>();
            // in the Survey model we can define a "RECORD OFFSET" by which
            // the parser must start
            for (int i = survey.RECORD_OFFSET; i < record.size(); i++) {
                String r = record.get(i);

                // if the "r" is empty the user has not responded
                // skip to the next answers
                if (r.isEmpty()) {
                    continue;
                }
                // if "r" isn't a numerical value and it is different than
                // ZERO_STRING (Ref. Survey model)
                // Note: the ZERO_STRING is defined in Survey Class. Its
                // value is Zero.
                if ((!r.matches("\\d*") && r.compareTo(survey.ZERO_STRING) != 0)) {
                    // Otherwise the answer is added to a list of Strings.
                    // this list will appended in queue. (*)
                    String[] str = r.split(";");
                    for (String s : str) {
                        textualAnswers.add("\"" + s + "\"");
                    }
                }
                // if "r" is a numeric value, simply add it in the answers
                // list.
                if (r.compareTo(survey.ZERO_STRING) == 0) {
                    answers.add("0");
                }
                if (r.matches("\\d*")) {
                    answers.add(r);
                }
            }
            // add the textual answers in queue (*)
            answers.addAll(textualAnswers);

            String fname = file.getName();
            survey.setProfile(fname.substring(0, fname.lastIndexOf('.')));
            survey.setAnswers(answers);
            surveys.add(survey);
        }
    }
    return (surveys != null) ? surveys : null;
}

From source file:com.ibm.amc.FileManager.java

public static File compress(File pathToCompress) {
    try {//w ww . jav a  2s  .  c o m
        File zipFile = new File(pathToCompress.getCanonicalPath() + ZIP_EXTENSION);
        FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
        CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream, new CRC32());
        ZipOutputStream out = new ZipOutputStream(cos);
        String basedir = "";
        compress(pathToCompress, out, basedir);
        out.close();
        return zipFile;
    } catch (Exception e) {
        throw new AmcRuntimeException(e);
    }
}

From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.util.DirectoryListerImpl.java

/**
 * A method to get all files by a wildcard pattern 
 * @param dirName name of the directory to look
 * @param filePatternList a list of patterns
 * @return an arrays of files that match the patterns
 * @throws IOException //from   ww w. ja va2  s . c om
 */
public static File[] getFilesByPattern(final String dirName, final List<String> filePatternList) {

    File[] listOfFiles = null;

    if (StringUtils.isNotEmpty(dirName) && filePatternList != null && filePatternList.size() > 0) {

        final File dir = new File(dirName);
        String[] dataSetFiles = dir.list(new WildcardFileFilter(filePatternList));
        if (dataSetFiles != null && dataSetFiles.length > 0) {
            listOfFiles = new File[dataSetFiles.length];
            for (int i = 0; i < dataSetFiles.length; i++) {
                try {
                    listOfFiles[i] = new File(dir.getCanonicalPath() + File.separator + dataSetFiles[i]);
                } catch (IOException e) {
                    // should never get here, but just in case we do , just return with null
                    // meaning that no files by pattern could be found
                    return null;
                }
            }
        }

    }
    return listOfFiles;
}