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.tinygroup.jspengine.JspC.java

/**
 * Initializes the classloader as/if needed for the given
 * compilation context./*from w  w w  .  j a  v a2s .  c  om*/
 *
 * @param clctxt The compilation context
 * @throws IOException If an error occurs
 */
private void initClassLoader(JspCompilationContext clctxt) throws IOException {

    classPath = getClassPath();

    ClassLoader jspcLoader = getClass().getClassLoader();
    if (jspcLoader instanceof AntClassLoader) {
        classPath += File.pathSeparator + ((AntClassLoader) jspcLoader).getClasspath();
    }

    // Turn the classPath into URLs
    ArrayList urls = new ArrayList();
    StringTokenizer tokenizer = new StringTokenizer(classPath, File.pathSeparator);
    while (tokenizer.hasMoreTokens()) {
        String path = tokenizer.nextToken();
        try {
            File libFile = new File(path);
            urls.add(libFile.toURL());
        } catch (IOException ioe) {
            // Failing a toCanonicalPath on a file that
            // exists() should be a JVM regression test,
            // therefore we have permission to freak uot
            throw new RuntimeException(ioe.toString());
        }
    }

    File webappBase = new File(uriRoot);
    if (webappBase.exists()) {
        File classes = new File(webappBase, "/WEB-INF/classes");
        try {
            if (classes.exists()) {
                classPath = classPath + File.pathSeparator + classes.getCanonicalPath();
                urls.add(classes.getCanonicalFile().toURL());
            }
        } catch (IOException ioe) {
            // failing a toCanonicalPath on a file that
            // exists() should be a JVM regression test,
            // therefore we have permission to freak out
            throw new RuntimeException(ioe.toString());
        }
        File lib = new File(webappBase, "/WEB-INF/lib");
        if (lib.exists() && lib.isDirectory()) {
            String[] libs = lib.list();
            for (int i = 0; i < libs.length; i++) {
                if (libs[i].length() < 5)
                    continue;
                String ext = libs[i].substring(libs[i].length() - 4);
                if (!".jar".equalsIgnoreCase(ext)) {
                    if (".tld".equalsIgnoreCase(ext)) {
                        log.warn("TLD files should not be placed in " + "/WEB-INF/lib");
                    }
                    continue;
                }
                try {
                    File libFile = new File(lib, libs[i]);
                    classPath = classPath + File.pathSeparator + libFile.getCanonicalPath();
                    urls.add(libFile.getCanonicalFile().toURL());
                } catch (IOException ioe) {
                    // failing a toCanonicalPath on a file that
                    // exists() should be a JVM regression test,
                    // therefore we have permission to freak out
                    throw new RuntimeException(ioe.toString());
                }
            }
        }
    }

    // What is this ??
    urls.add(new File(clctxt.getRealPath("/")).getCanonicalFile().toURL());

    URL urlsA[] = new URL[urls.size()];
    urls.toArray(urlsA);

    /* SJSAS 6327357
    loader = new URLClassLoader(urlsA, this.getClass().getClassLoader());
     */
    // START SJSAS 6327357
    ClassLoader sysClassLoader = initSystemClassLoader();
    if (sysClassLoader != null) {
        loader = new URLClassLoader(urlsA, sysClassLoader);
    } else {
        loader = new URLClassLoader(urlsA, this.getClass().getClassLoader());
    }
    // END SJSAS 6327357
}

From source file:com.edgenius.wiki.service.impl.ThemeServiceImpl.java

public void init() throws IOException {
    //detect if explode skin has /skin/init_flag file. If it has, first package this skin, then copy it {DataRoot}/data/skins/ directory.

    //For unit test case, explode directory doesn't exist.
    if (skinExplosionRoot.exists()) {
        File[] deployDirs = skinExplosionRoot.getFile().listFiles((FileFilter) DirectoryFileFilter.INSTANCE);
        for (File dir : deployDirs) {
            File file = new File(dir, "init_flag");
            File skinFile = getSkinXML(dir);
            if (!file.exists() || !skinFile.exists()) {
                continue;
            }/*  w ww.  java  2 s. c  o  m*/
            //delete init_flag file, don't zip it! To avoid do this process again in same deployment.
            file.delete();

            File tgtFile = new File(skinResourcesRoot.getFile(), dir.getName() + INSTALL_EXT_NAME);
            if (!tgtFile.exists()) {
                try {
                    Map<File, String> listToZip = new HashMap<File, String>();
                    String rootDir = dir.getCanonicalPath();
                    listToZip.put(dir, rootDir);
                    ZipFileUtil.createZipFile(tgtFile.getCanonicalPath(), listToZip, false);

                    //this ensure this skin will be deploy in next steps. As skin.xml not exist, the zip file will be exploded.
                    skinFile.delete();
                } catch (ZipFileUtilException e) {
                    log.error("Pack system initial skin failed" + tgtFile.getCanonicalFile(), e);
                }
            }
        }
    }
    //retrieve all zip files under themes and skins, compare its name and version, deploy it if it doesn't install or newer.
    File[] files = skinResourcesRoot.getFile().listFiles((FileFilter) new SuffixFileFilter(INSTALL_EXT_NAME));
    for (File skinFile : files) {
        try {
            explodeSkin(skinFile, false);
        } catch (ThemeInvalidException e) {
            log.info("Skin skip deploy {}", e.getMessage());
        }
    }

    files = themeResourcesRoot.getFile().listFiles((FileFilter) new SuffixFileFilter(INSTALL_EXT_NAME));
    for (File themeFile : files) {
        try {
            explodeTheme(themeFile, false);
        } catch (ThemeInvalidException e) {
            log.info("Theme skip deploy {}", e.getMessage());
        }
    }
}

From source file:org.apache.cocoon.portlet.CocoonPortlet.java

/**
 * Set the ConfigFile for the Cocoon object.
 *
 * @param configFileName The file location for the cocoon.xconf
 *
 * @throws PortletException//from  w  ww  .  j a  v  a  2 s . c o m
 */
private URL getConfigFile(final String configFileName) throws PortletException {
    final String usedFileName;

    if (configFileName == null) {
        if (getLogger().isWarnEnabled()) {
            getLogger().warn(
                    "Portlet initialization argument 'configurations' not specified, attempting to use '/WEB-INF/cocoon.xconf'");
        }
        usedFileName = "/WEB-INF/cocoon.xconf";
    } else {
        usedFileName = configFileName;
    }

    if (getLogger().isDebugEnabled()) {
        getLogger().debug("Using configuration file: " + usedFileName);
    }

    URL result;
    try {
        // test if this is a qualified url
        if (usedFileName.indexOf(':') == -1) {
            result = this.portletContext.getResource(usedFileName);
        } else {
            result = new URL(usedFileName);
        }
    } catch (Exception mue) {
        String msg = "Init parameter 'configurations' is invalid : " + usedFileName;
        getLogger().error(msg, mue);
        throw new PortletException(msg, mue);
    }

    if (result == null) {
        File resultFile = new File(usedFileName);
        if (resultFile.isFile()) {
            try {
                result = resultFile.getCanonicalFile().toURL();
            } catch (Exception e) {
                String msg = "Init parameter 'configurations' is invalid : " + usedFileName;
                getLogger().error(msg, e);
                throw new PortletException(msg, e);
            }
        }
    }

    if (result == null) {
        String msg = "Init parameter 'configuration' doesn't name an existing resource : " + usedFileName;
        getLogger().error(msg);
        throw new PortletException(msg);
    }
    return result;
}

From source file:net.nicholaswilliams.java.licensing.licensor.interfaces.cli.TestConsoleRSAKeyPairGenerator.java

@Test
@Ignore("canRead()/canWrite() do not work on Win; setReadable()/setWritable() do not work on some Macs.")
public void testCheckAndPromptToOverwriteFile07() throws IOException {
    File file = new File("testCheckAndPromptToOverwriteFile07");
    file = file.getCanonicalFile();
    FileUtils.writeStringToFile(file, "test string");

    assertTrue("Setting the file readable flag to false should have succeeded.",
            file.setReadable(false, false));
    assertTrue("The file should still be writable.", file.canWrite());
    assertFalse("The file should not be readable.", file.canRead());

    try {/*from  w  ww  .j  a v  a  2s.  com*/
        this.device.printErrLn(
                "The file " + file.getCanonicalPath() + " already exists and cannot be overwritten.");
        EasyMock.expectLastCall();

        EasyMock.replay(this.generator, this.device);

        assertFalse("The value returned should be true.",
                this.console.checkAndPromptToOverwriteFile("testCheckAndPromptToOverwriteFile07"));
    } finally {
        FileUtils.forceDelete(file);
    }
}

From source file:net.nicholaswilliams.java.licensing.licensor.interfaces.cli.TestConsoleRSAKeyPairGenerator.java

@Test
@Ignore("canRead()/canWrite() do not work on Win; setReadable()/setWritable() do not work on some Macs.")
public void testCheckAndPromptToOverwriteFile08() throws IOException {
    File file = new File("testCheckAndPromptToOverwriteFile08");
    file = file.getCanonicalFile();
    FileUtils.writeStringToFile(file, "test string");

    assertTrue("Setting the file readable flag to false should have succeeded.",
            file.setWritable(false, false));
    assertTrue("The file should still be readable.", file.canRead());
    assertFalse("The file should not be writable.", file.canWrite());

    try {//from   w w  w . j a va2 s.co  m
        this.device.printErrLn(
                "The file " + file.getCanonicalPath() + " already exists and cannot be overwritten.");
        EasyMock.expectLastCall();

        EasyMock.replay(this.generator, this.device);

        assertFalse("The value returned should be true.",
                this.console.checkAndPromptToOverwriteFile("testCheckAndPromptToOverwriteFile08"));
    } finally {
        FileUtils.forceDelete(file);
    }
}

From source file:net.nicholaswilliams.java.licensing.licensor.interfaces.cli.TestConsoleLicenseGenerator.java

@Test
@Ignore("canRead()/canWrite() do not work on Win; setReadable()/setWritable() do not work on some Macs.")
public void testInitializeLicenseCreator02() throws Exception {
    this.resetLicenseCreator();

    String fileName = "testInitializeLicenseCreator02.properties";
    File file = new File(fileName);
    file = file.getCanonicalFile();
    if (file.exists())
        FileUtils.forceDelete(file);/*w  ww.j  ava  2 s.  c  o  m*/

    FileUtils.writeStringToFile(file, "test");

    assertTrue("Setting the file to not readable should have returned true.", file.setReadable(false, false));
    assertTrue("The file should be writable.", file.canWrite());
    assertFalse("The file should not be readable.", file.canRead());

    this.console.cli = EasyMock.createMockBuilder(CommandLine.class).withConstructor()
            .addMockedMethod("hasOption", String.class).addMockedMethod("getOptionValue", String.class)
            .createStrictMock();

    EasyMock.expect(this.console.cli.hasOption("config")).andReturn(true);
    EasyMock.expect(this.console.cli.getOptionValue("config")).andReturn(fileName);

    EasyMock.replay(this.console.cli, this.device);

    try {
        this.console.initializeLicenseCreator();
        fail("Expected exception IOException.");
    } catch (IOException ignore) {
    } finally {
        this.resetLicenseCreator();

        FileUtils.forceDelete(file);

        EasyMock.verify(this.console.cli);
    }
}

From source file:net.nicholaswilliams.java.licensing.licensor.interfaces.cli.TestConsoleLicenseGenerator.java

@Test
@Ignore("canRead()/canWrite() do not work on Win; setReadable()/setWritable() do not work on some Macs.")
public void testGenerateLicense02() throws Exception {
    this.resetLicenseCreator();

    String fileName = "testGenerateLicense02.properties";
    File file = new File(fileName);
    file = file.getCanonicalFile();
    if (file.exists())
        FileUtils.forceDelete(file);//from w  w  w .j  ava 2 s. co m

    FileUtils.writeStringToFile(file, "test");

    assertTrue("Setting the file to not readable should have returned true.", file.setReadable(false, false));
    assertTrue("The file should be writable.", file.canWrite());
    assertFalse("The file should not be readable.", file.canRead());

    this.console.cli = EasyMock.createMockBuilder(CommandLine.class).withConstructor()
            .addMockedMethod("hasOption", String.class).addMockedMethod("getOptionValue", String.class)
            .createStrictMock();

    EasyMock.expect(this.console.cli.hasOption("license")).andReturn(true);
    EasyMock.expect(this.console.cli.getOptionValue("license")).andReturn(fileName);

    EasyMock.replay(this.console.cli, this.device);

    try {
        this.console.generateLicense();
        fail("Expected exception IOException.");
    } catch (IOException ignore) {
    } finally {
        this.resetLicenseCreator();

        FileUtils.forceDelete(file);

        EasyMock.verify(this.console.cli);
    }
}

From source file:org.apache.storm.daemon.logviewer.handler.LogviewerLogSearchHandler.java

/**
 * As the file is read into a buffer, 1/2 the buffer's size at a time, we search the buffer for matches of the
 * substring and return a list of zero or more matches.
 *//* w  ww. j a  v  a 2 s  . co  m*/
private SubstringSearchResult bufferSubstringSearch(boolean isDaemon, File file, int fileLength,
        int offsetToBuf, int initBufOffset, BufferedInputStream stream, Integer bytesSkipped, int bytesRead,
        ByteBuffer haystack, byte[] needle, List<Map<String, Object>> initialMatches, Integer numMatches,
        byte[] beforeBytes) throws IOException {
    int bufOffset = initBufOffset;
    List<Map<String, Object>> matches = initialMatches;

    byte[] newBeforeBytes;
    Integer newByteOffset;

    while (true) {
        int offset = offsetOfBytes(haystack.array(), needle, bufOffset);
        if (matches.size() < numMatches && offset >= 0) {
            final int fileOffset = offsetToBuf + offset;
            final int bytesNeededAfterMatch = haystack.limit() - GREP_CONTEXT_SIZE - needle.length;

            byte[] beforeArg = null;
            byte[] afterArg = null;
            if (offset < GREP_CONTEXT_SIZE) {
                beforeArg = beforeBytes;
            }

            if (offset > bytesNeededAfterMatch) {
                afterArg = tryReadAhead(stream, haystack, offset, fileLength, bytesRead);
            }

            bufOffset = offset + needle.length;
            matches.add(mkMatchData(needle, haystack, offset, fileOffset, file.getCanonicalFile().toPath(),
                    isDaemon, beforeArg, afterArg));
        } else {
            int beforeStrToOffset = Math.min(haystack.limit(), GREP_MAX_SEARCH_SIZE);
            int beforeStrFromOffset = Math.max(0, beforeStrToOffset - GREP_CONTEXT_SIZE);
            newBeforeBytes = Arrays.copyOfRange(haystack.array(), beforeStrFromOffset, beforeStrToOffset);

            // It's OK if new-byte-offset is negative.
            // This is normal if we are out of bytes to read from a small file.
            if (matches.size() >= numMatches) {
                newByteOffset = ((Number) last(matches).get("byteOffset")).intValue() + needle.length;
            } else {
                newByteOffset = bytesSkipped + bytesRead - GREP_MAX_SEARCH_SIZE;
            }

            break;
        }
    }

    return new SubstringSearchResult(matches, newByteOffset, newBeforeBytes);
}

From source file:org.apache.catalina.loader.WebappClassLoader.java

/**
 * Get URL.//from   w  ww  . j ava 2  s .com
 */
protected URL getURL(File file) throws MalformedURLException {

    File realFile = file;
    try {
        realFile = realFile.getCanonicalFile();
    } catch (IOException e) {
        // Ignore
    }
    return realFile.toURL();

}

From source file:org.jsweet.transpiler.JSweetTranspiler.java

/**
 * Creates a JSweet transpiler.// w w  w.  jav a2 s  . com
 * 
 * @param factory
 *            the factory used to create the transpiler objects
 * @param workingDir
 *            the working directory
 * @param tsOutputDir
 *            the directory where TypeScript files are written
 * @param jsOutputDir
 *            the directory where JavaScript files are written
 * @param extractedCandiesJavascriptDir
 *            see {@link #getExtractedCandyJavascriptDir()}
 * @param classPath
 *            the classpath as a string (check out system-specific
 *            requirements for Java classpaths)
 */
public JSweetTranspiler(JSweetFactory<C> factory, File workingDir, File tsOutputDir, File jsOutputDir,
        File extractedCandiesJavascriptDir, String classPath) {
    this.factory = factory;
    readConfiguration();
    this.workingDir = workingDir.getAbsoluteFile();
    this.extractedCandyJavascriptDir = extractedCandiesJavascriptDir;
    try {
        tsOutputDir.mkdirs();
        this.tsOutputDir = tsOutputDir.getCanonicalFile();
        if (jsOutputDir != null && generateJsFiles) {
            jsOutputDir.mkdirs();
            this.jsOutputDir = jsOutputDir.getCanonicalFile();
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("cannot locate output dirs", e);
    }
    this.classPath = classPath == null ? System.getProperty("java.class.path") : classPath;
    logger.info("creating transpiler version " + JSweetConfig.getVersionNumber() + " (build date: "
            + JSweetConfig.getBuildDate() + ")");
    logger.info("curent dir: " + new File(".").getAbsolutePath());
    logger.info("tsOut: " + tsOutputDir + (tsOutputDir == null ? "" : " - " + tsOutputDir.getAbsolutePath()));
    logger.info("jsOut: " + jsOutputDir + (jsOutputDir == null ? "" : " - " + jsOutputDir.getAbsolutePath()));
    logger.info("candyJsOut: " + extractedCandiesJavascriptDir);
    logger.debug("compile classpath: " + classPath);
    logger.debug("runtime classpath: " + System.getProperty("java.class.path"));
    this.candiesProcessor = new CandiesProcessor(workingDir, classPath, extractedCandyJavascriptDir);
}