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:com.owera.xaps.spp.TFTPServer.java

private void launch(File serverReadDirectory, File serverWriteDirectory) throws IOException {
    Log.notice(TFTPServer.class, "Starting TFTP Server on port " + port_ + ".  Read directory: "
            + serverReadDirectory + " Write directory: " + serverWriteDirectory + " Server Mode is " + mode_);

    serverReadDirectory_ = serverReadDirectory.getCanonicalFile();
    if (!serverReadDirectory_.exists() || !serverReadDirectory.isDirectory()) {
        throw new IOException("The server read directory " + serverReadDirectory_ + " does not exist");
    }/*from  www  .j a v a2  s.  c o m*/

    serverWriteDirectory_ = serverWriteDirectory.getCanonicalFile();
    if (!serverWriteDirectory_.exists() || !serverWriteDirectory.isDirectory()) {
        throw new IOException("The server write directory " + serverWriteDirectory_ + " does not exist");
    }

    serverTftp_ = new TFTP();

    // This is the value used in response to each client.
    socketTimeout_ = serverTftp_.getDefaultTimeout();

    // we want the server thread to listen forever.
    serverTftp_.setDefaultTimeout(0);

    serverTftp_.open(port_);

    serverThread = new Thread(this);
    serverThread.setDaemon(false);
    serverThread.start();
}

From source file:org.commonjava.emb.project.ProjectLoader.java

private void readReactorModels(final File topPom, final File pom, final Map<File, Model> models)
        throws ProjectToolsException {
    final Model model = readModel(pom);
    models.put(pom, model);//from  www  .  j  a  v  a2 s.  c  o  m

    if (model.getModules() != null && !model.getModules().isEmpty()) {
        final File basedir = pom.getParentFile();

        final List<File> moduleFiles = new ArrayList<File>();

        for (String module : model.getModules()) {
            if (StringUtils.isEmpty(module)) {
                continue;
            }

            module = module.replace('\\', File.separatorChar).replace('/', File.separatorChar);

            File moduleFile = new File(basedir, module);

            if (moduleFile.isDirectory()) {
                moduleFile = new File(moduleFile, "pom.xml");
            }

            if (!moduleFile.isFile()) {
                LOGGER.warn(String.format("In reactor of: %s: Child module %s of %s does not exist.", topPom,
                        moduleFile, pom));
                continue;
            }

            if (Os.isFamily(Os.FAMILY_WINDOWS)) {
                // we don't canonicalize on unix to avoid interfering with symlinks
                try {
                    moduleFile = moduleFile.getCanonicalFile();
                } catch (final IOException e) {
                    moduleFile = moduleFile.getAbsoluteFile();
                }
            } else {
                moduleFile = new File(moduleFile.toURI().normalize());
            }

            moduleFiles.add(moduleFile);
            readReactorModels(topPom, moduleFile, models);
        }
    }
}

From source file:ch.randelshofer.cubetwister.HTMLExporter.java

private void putNextEntry(String filename) throws IOException {
    if (zipOut != null) {
        ZipEntry entry = new ZipEntry(filename);
        zipOut.putNextEntry(entry);//  w w w .  j a  va  2s  .  c  o m
        entryOut = zipOut;
    } else {
        File f = new File(dir, filename);
        if (f.exists() && f.getCanonicalFile().getName().equals(f.getName())) {
            // If the filename does not match, we have to delete the
            // file.
            f.delete();
        } else {
            f.getParentFile().mkdirs();
        }
        entryOut = new BufferedOutputStream(new FileOutputStream(f));
    }
}

From source file:com.cti.vpx.listener.VPXTFTPMonitor.java

private void launch(File serverReadDirectory, File serverWriteDirectory) throws IOException {

    log_.println("Starting TFTP Server on port " + port_ + ".  Read directory: " + serverReadDirectory
            + " Write directory: " + serverWriteDirectory + " Server Mode is " + mode_);

    serverReadDirectory_ = serverReadDirectory.getCanonicalFile();

    if (!serverReadDirectory_.exists() || !serverReadDirectory.isDirectory()) {
        throw new IOException("The server read directory " + serverReadDirectory_ + " does not exist");
    }/*from   w  w w  .j ava2s  .  c  om*/

    if (serverWriteDirectory != null) {

        serverWriteDirectory_ = serverWriteDirectory.getCanonicalFile();

        if (!serverWriteDirectory_.exists() || !serverWriteDirectory.isDirectory()) {
            throw new IOException("The server write directory " + serverWriteDirectory_ + " does not exist");
        }

    }

    serverTftp_ = new TFTP();

    // This is the value used in response to each client.
    socketTimeout_ = serverTftp_.getDefaultTimeout();

    // we want the server thread to listen forever.
    serverTftp_.setDefaultTimeout(0);

    serverTftp_.open(port_);

    serverThread = new Thread(this);

    serverThread.setDaemon(true);

    serverThread.start();
}

From source file:com.slytechs.capture.FileFactory.java

public List<File> splitFile(final File file, final long packetCount, final boolean maxCompression)
        throws IOException {

    final FileCapture<? extends FilePacket> source = openFile(file);
    final FormatType type = source.getFormatType();

    final List<File> files = new ArrayList<File>(100);
    final List<Packet> packets = new ArrayList<Packet>((int) packetCount);

    int fileCount = 0;
    int count = 0; // packet count

    final PacketIterator<? extends FilePacket> i = source.getPacketIterator();
    FileCapture<? extends FilePacket> dst = null;
    while (i.hasNext()) {
        if (count % packetCount == 0 && packets.isEmpty() == false) {
            File f = new File(file.getCanonicalFile() + "-" + fileCount);
            files.add(f);// w  w  w .jav  a  2  s . co  m
            fileCount++;

            dst = newFile(type, f);
            try {
                PacketIterator<? extends FilePacket> pi = dst.getPacketIterator();

                pi.addAll(packets);
                packets.clear();
            } finally {
                dst.close();
            }
        }

        final Packet packet = i.next();

        packets.add(packet);
        count++;
    }

    /*
     * Don't forget the remainder
     */
    if (packets.isEmpty() == false) {
        File f = new File(file.getCanonicalFile() + "-" + fileCount);
        files.add(f);
        fileCount++;

        dst = newFile(type, f);
        try {
            PacketIterator<? extends FilePacket> pi = dst.getPacketIterator();

            pi.addAll(packets);
            packets.clear();
        } finally {
            dst.close();
        }
    }

    source.close();

    if (logger.isTraceEnabled()) {
        logger.trace(file.getName() + ", count=" + packetCount + ", compression=" + maxCompression + ", files="
                + files);
    }

    return files;
}

From source file:org.rhq.storage.installer.StorageInstaller.java

private void checkPerms(Option option, String path, List<String> errors) {
    try {/*from w w w .j a  v a  2 s  .com*/
        log.info("Checking perms for " + path);
        File dir = new File(path);
        if (!dir.isAbsolute()) {
            dir = new File(new File(storageBasedir, "bin"), path);
        }
        dir = dir.getCanonicalFile();

        if (dir.exists()) {
            if (dir.isFile()) {
                errors.add(path + " is not a directory. Use the --" + option.getLongOpt()
                        + " to change this value.");
            }
        } else {
            File parentDir = dir.getParentFile();
            while (!parentDir.exists()) {
                parentDir = parentDir.getParentFile();
            }

            if (!parentDir.canWrite()) {
                errors.add("The user running this installer does not appear to have write permissions to "
                        + parentDir
                        + ". Either make sure that the user running the storage node has write permissions or use the --"
                        + option.getLongOpt() + " to change this value.");
            }
        }
    } catch (Exception e) {
        errors.add("The request path cannot be constructed (path: " + path + "). "
                + "Please use a valid and also make sure the user running the storage node has write permissions for the path.");
    }
}

From source file:com.github.webapp_minifier.WebappMinifierMojo.java

/**
 * @see org.apache.maven.plugin.AbstractMojo#execute()
 *//*from w w w. j  ava  2 s. co  m*/
@Override
public void execute() throws MojoExecutionException {
    // Copy the source directory to the target directory.
    try {
        getLog().debug("Copying " + this.sourceDirectory + " to " + this.minifiedDirectory);
        if (this.minifiedDirectory.exists()) {
            FileUtils.deleteDirectory(this.minifiedDirectory);
        }
        FileUtils.copyDirectoryStructure(this.sourceDirectory, this.minifiedDirectory);
    } catch (final IOException e) {
        throw new MojoExecutionException("Failed to copy the source directory", e);
    }

    if (!this.skipMinify) {
        // Process each of the requested files.
        final DefaultTagHandler tagHandler = new DefaultTagHandler(getLog(), this);
        final TagReplacer tagReplacer = TagReplacerFactory.getReplacer(this.parser, getLog(), this.encoding);
        for (final String fileName : getFilesToProcess()) {
            final File htmlFile = new File(this.minifiedDirectory, fileName);
            final File minifiedHtmlFile = new File(this.minifiedDirectory, fileName + ".min");
            final File htmlFileBackup = new File(this.minifiedDirectory, fileName + ".bak");

            InputStream inputStream = null;
            OutputStream outputStream = null;
            try {
                getLog().info("Processing " + htmlFile.getCanonicalFile());
                final String baseUri = CommonUtils.getBaseUri(htmlFile, this.minifiedDirectory);
                inputStream = new BufferedInputStream(new FileInputStream(htmlFile));
                outputStream = new BufferedOutputStream(new FileOutputStream(minifiedHtmlFile));
                tagHandler.start(htmlFile);
                tagReplacer.process(inputStream, tagHandler, baseUri, outputStream);
            } catch (final IOException e) {
                throw new MojoExecutionException("Failed to process " + htmlFile, e);
            } finally {
                IOUtil.close(inputStream);
                IOUtil.close(outputStream);
            }
            if (!htmlFile.renameTo(htmlFileBackup)) {
                throw new MojoExecutionException(
                        "Failed to rename " + htmlFile.getName() + " to " + htmlFileBackup.getName());
            }
            if (!minifiedHtmlFile.renameTo(htmlFile)) {
                throw new MojoExecutionException(
                        "Failed to rename " + minifiedHtmlFile.getName() + " to " + htmlFile.getName());
            }
        }

        // Write out the summary file.
        final File summaryFile = new File(this.minifiedDirectory, "webapp-minifier-summary.xml");
        try {
            final JAXBContext context = JAXBContext.newInstance(MinificationSummary.class);
            final Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, getEncoding());
            marshaller.marshal(tagHandler.getReport(), summaryFile);
            tagHandler.getReport();
        } catch (final JAXBException e) {
            throw new MojoExecutionException("Failed to marshal the plugin's summary to XML", e);
        }

        // Attempt to configure the maven-war-plugin.
        if (this.project != null) {
            this.project.getProperties().setProperty("war.warName", "my-name.war");
            for (final Object object : this.project.getBuildPlugins()) {
                final Plugin plugin = (Plugin) object;
                if (StringUtils.equals("org.apache.maven.plugins", plugin.getGroupId())
                        && StringUtils.equals("maven-war-plugin", plugin.getArtifactId())) {
                    getLog().info("Examining plugin " + plugin.getArtifactId());
                    final Object configuration = plugin.getConfiguration();
                    getLog().info("Fetched configuration " + configuration.getClass() + ": " + configuration);
                    final Xpp3Dom document = (Xpp3Dom) configuration;
                    final Xpp3Dom[] children = document.getChildren("warSourceDirectory");
                    getLog().info("Fetched children " + children.length);
                    for (final Xpp3Dom child : children) {
                        getLog().info("Child: " + child);
                        getLog().info("Child Value: " + child.getValue());
                        child.setValue(child.getValue() + "_oops");
                        getLog().info("Child Value: " + child.getValue());
                    }
                }
            }
        }
    }
}

From source file:org.paxle.tools.mimetype.impl.MimeTypeDetector.java

public String getMimeType(File file) throws Exception {
    r.lock();/*from www . j  a va2  s. c om*/
    try {
        String mimeType = null;
        MagicMatch match = Magic.getMagicMatch(file, false);

        // if a match was found we can return the new mimeType
        if (match != null) {
            Collection<?> subMatches = match.getSubMatches();
            if ((subMatches != null) && (!subMatches.isEmpty())) {
                // if there is a sub-match, use it
                mimeType = ((MagicMatch) subMatches.iterator().next()).getMimeType();
            } else {
                mimeType = match.getMimeType();
            }
        }

        return mimeType;
    } catch (Exception e) {
        if (!(e instanceof MagicMatchNotFoundException)) {
            this.logger
                    .warn(String.format("Unexpected '%s' while trying to determine the mime-type of file '%s'.",
                            e.getClass().getName(), file.getCanonicalFile().toString()), e);
            throw e;
        }
        return null;
    } finally {
        r.unlock();
    }
}

From source file:org.apache.catalina.startup.HostConfig.java

/**
 * Return a File object representing the "application root" directory
 * for our associated Host./*from   w  w w .java  2  s  . c o  m*/
 */
protected File appBase() {

    if (appBase != null) {
        return appBase;
    }

    File file = new File(host.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:uk.ac.soton.simulation.jsit.core.ModelVersioningAssistant.java

private boolean fileIsExcluded(boolean includeHiddenFiles, List<File> fileExclusions,
        String[] filenameExclusions, File checkFile) throws IOException {

    if (!includeHiddenFiles && checkFile.getName().startsWith(".")) {
        return true;
    }//from  ww w  . ja va2  s.  c o m

    if (fileExclusions != null) {
        if (fileExclusions.remove(checkFile.getCanonicalFile())) {
            return true;
        }
    }

    if (filenameExclusions != null) {
        for (String s : filenameExclusions) {
            if (s.equals(checkFile.getName())) {
                return true;
            }
        }
    }

    return false;

}