Example usage for java.io File getAbsoluteFile

List of usage examples for java.io File getAbsoluteFile

Introduction

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

Prototype

public File getAbsoluteFile() 

Source Link

Document

Returns the absolute form of this abstract pathname.

Usage

From source file:inventory.pl.services.BackupService.java

private void generateFileList(File node) {

    //add file only
    if (node.isFile()) {
        entries.add(generateZipEntry(node.getAbsoluteFile().toString()));
    }//w  w  w.j  ava2  s .c  om

    if (node.isDirectory()) {
        String[] subNote = node.list();
        for (String filename : subNote) {
            generateFileList(new File(node, filename));
        }
    }

}

From source file:adams.core.io.TarUtils.java

/**
 * Decompresses the specified file from a tar file.
 *
 * @param input   the tar file to decompress
 * @param archiveFile   the file from the archive to extract
 * @param output   the name of the output file
 * @param createDirs   whether to create the directory structure represented
 *          by output file//w w  w  .j ava  2s . c om
 * @param bufferSize   the buffer size to use
 * @param errors   for storing potential errors
 * @return      whether file was successfully extracted
 */
public static boolean decompress(File input, String archiveFile, File output, boolean createDirs,
        int bufferSize, StringBuilder errors) {
    boolean result;
    FileInputStream fis;
    TarArchiveInputStream archive;
    TarArchiveEntry entry;
    File outFile;
    String outName;
    byte[] buffer;
    FileOutputStream fos;
    BufferedOutputStream out;
    int len;
    String error;
    long size;
    long read;

    result = false;
    archive = null;
    fis = null;
    fos = null;
    try {
        // decompress archive
        buffer = new byte[bufferSize];
        fis = new FileInputStream(input.getAbsoluteFile());
        archive = openArchiveForReading(input, fis);
        while ((entry = archive.getNextTarEntry()) != null) {
            if (entry.isDirectory())
                continue;
            if (!entry.getName().equals(archiveFile))
                continue;

            out = null;
            outName = null;
            try {
                // output name
                outName = output.getAbsolutePath();

                // create directory, if necessary
                outFile = new File(outName).getParentFile();
                if (!outFile.exists()) {
                    if (!createDirs) {
                        error = "Output directory '" + outFile.getAbsolutePath() + " does not exist', "
                                + "skipping extraction of '" + outName + "'!";
                        System.err.println(error);
                        errors.append(error + "\n");
                        break;
                    } else {
                        if (!outFile.mkdirs()) {
                            error = "Failed to create directory '" + outFile.getAbsolutePath() + "', "
                                    + "skipping extraction of '" + outName + "'!";
                            System.err.println(error);
                            errors.append(error + "\n");
                            break;
                        }
                    }
                }

                // extract data
                fos = new FileOutputStream(outName);
                out = new BufferedOutputStream(fos, bufferSize);
                size = entry.getSize();
                read = 0;
                while (read < size) {
                    len = archive.read(buffer);
                    read += len;
                    out.write(buffer, 0, len);
                }

                result = true;
                break;
            } catch (Exception e) {
                result = false;
                error = "Error extracting '" + entry.getName() + "' to '" + outName + "': " + e;
                System.err.println(error);
                errors.append(error + "\n");
            } finally {
                FileUtils.closeQuietly(out);
                FileUtils.closeQuietly(fos);
            }
        }
    } catch (Exception e) {
        result = false;
        e.printStackTrace();
        errors.append("Error occurred: " + e + "\n");
    } finally {
        FileUtils.closeQuietly(fis);
        if (archive != null) {
            try {
                archive.close();
            } catch (Exception e) {
                // ignored
            }
        }
    }

    return result;
}

From source file:org.jasig.portlet.announcements.Importer.java

private void importTopics() {
    try {//from   www  . j a  va2s .  c o  m
        JAXBContext jc = JAXBContext.newInstance(Topic.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();

        File[] files = dataDirectory.listFiles(new TopicImportFileFilter());

        if (files == null) {
            errors.add("Directory " + dataDirectory + " is not a valid directory");
        } else {

            for (File f : files) {
                log.info("Processing file " + f.toString());
                StreamSource xmlFile = new StreamSource(f.getAbsoluteFile());
                try {
                    JAXBElement<Topic> je1 = unmarshaller.unmarshal(xmlFile, Topic.class);
                    Topic topic = je1.getValue();

                    if (StringUtils.isBlank(topic.getTitle())) {
                        String msg = "Error parsing file " + f.toString() + "; did not get valid record:\n"
                                + topic.toString();
                        log.error(msg);
                        errors.add(msg);
                    } else {
                        announcementService.addOrSaveTopic(topic);
                        log.info("Successfully imported topic '" + topic.getTitle() + "'");
                    }
                } catch (JAXBException e) {
                    String msg = "JAXB exception " + e.getCause().getMessage() + " processing file "
                            + f.toString();
                    log.error(msg, e);
                    errors.add(msg + ". See stack trace");
                } catch (HibernateException e) {
                    String msg = "Hibernate exception " + e.getCause().getMessage() + " processing file "
                            + f.toString();
                    log.error(msg, e);
                    errors.add(msg + ". See stack trace");
                }
            }
        }
    } catch (JAXBException e) {
        String msg = "Fatal JAXBException in importTopics - no topics imported";
        log.fatal(msg, e);
        errors.add(msg + ".  See stack trace");
    }
}

From source file:de.lgohlke.sonar.maven.lint.LintSensorTest.java

private Results getResultsFromXml(String xml) throws IOException {
    File tempFile = File.createTempFile(Math.random() + "", Math.random() + "");
    FileUtils.write(tempFile, xml);//  w ww . j  av  a2s .c  o m
    tempFile.deleteOnExit();

    File projectDir = tempFile.getParentFile();
    String xmlReport = tempFile.getAbsoluteFile().getName();
    return new XmlReader().readXmlFromFile(projectDir, xmlReport, Results.class);
}

From source file:org.jasig.portlet.announcements.Importer.java

private void importAnnouncements() {
    try {/*from   w  ww.  j ava 2s . co m*/
        JAXBContext jc = JAXBContext.newInstance(Announcement.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();

        File[] files = dataDirectory.listFiles(new AnnouncementImportFileFilter());

        if (files == null) {
            errors.add("Directory " + dataDirectory + " is not a valid directory");
        } else {

            for (File f : files) {
                log.info("Processing file " + f.toString());
                StreamSource xml = new StreamSource(f.getAbsoluteFile());
                try {
                    JAXBElement<Announcement> je1 = unmarshaller.unmarshal(xml, Announcement.class);
                    Announcement announcement = je1.getValue();
                    if (StringUtils.isBlank(announcement.getTitle())) {
                        String msg = "Error parsing " + f.toString() + "; did not get valid record:\n"
                                + announcement.toString();
                        log.error(msg);
                        errors.add(msg);
                    } else if (announcement.getParent() == null
                            || StringUtils.isBlank(announcement.getParent().getTitle())) {
                        String msg = "Announcement in file " + f.toString()
                                + " does not reference a topic with a title";
                        log.error(msg);
                        errors.add(msg);
                    } else {
                        Topic topic = findTopicForAnnouncement(announcement);
                        announcement.setParent(topic);
                        announcementService.addOrSaveAnnouncement(announcement);
                        log.info("Successfully imported announcement '" + announcement.getTitle() + "'");
                    }
                } catch (ImportException e) {
                    log.error(e.getMessage());
                    errors.add(e.getMessage());
                } catch (JAXBException e) {
                    String msg = "JAXB exception " + e.getCause().getMessage() + " processing file "
                            + f.toString();
                    log.error(msg, e);
                    errors.add(msg + ". See stack trace");
                } catch (HibernateException e) {
                    String msg = "Hibernate exception " + e.getCause().getMessage() + " processing file "
                            + f.toString();
                    log.error(msg, e);
                    errors.add(msg + ". See stack trace");
                }
            }
        }
    } catch (JAXBException e) {
        String msg = "Fatal JAXBException in importAnnouncements - no Announcements imported";
        log.fatal(msg, e);
        errors.add(msg + ".  See stack trace");
    }
}

From source file:org.apache.maven.indexer.examples.boot.RepositoryBooter.java

private void initializeRepository(File repositoriesBaseDir, String repositoryName)
        throws IOException, PlexusContainerException, ComponentLookupException {
    createRepositoryStructure(repositoriesBaseDir.getAbsolutePath(), repositoryName);

    initializeRepositoryIndex(new File(repositoriesBaseDir.getAbsoluteFile(), repositoryName), repositoryName);
}

From source file:com.splunk.shuttl.archiver.filesystem.hadoop.HadoopArchiveFileSystem.java

private void putFile(File src, Path temp, Path dst) throws IOException {
    if (hadoopFileSystem.exists(dst))
        throw new FileOverwriteException();
    hadoopFileSystem.delete(temp, true);
    hadoopFileSystem.copyFromLocalFile(new Path(src.getAbsoluteFile().toURI()), temp);
}

From source file:com.ibm.util.merge.persistence.FilesystemPersistence.java

/**********************************************************************************
 * save provided template to the Template Folder as JSON, and add it to the Cache
 *
 * @param Template template the Template to save
 * @return a cloned copy of the Template ready for Merge Processing
 *//*from   w w w .  j  av a  2s .c  o  m*/
@Override
public void saveTemplate(Template template) {
    deleteTemplate(template);
    String fileName = templateFolder + File.separator + template.getFullName() + ".json";
    File file = new File(fileName);
    BufferedWriter bw = null;
    try {
        if (!file.exists()) {
            file.createNewFile();
        }
        File path = file.getAbsoluteFile();
        log.info("Saving " + template.getFullName() + " to " + path.getAbsolutePath());
        FileWriter fw = new FileWriter(path);
        bw = new BufferedWriter(fw);
        bw.write(jsonProxy.toJson(template));
        bw.flush();
        bw.close();
    } catch (IOException e) {
        throw new RuntimeException(
                "Could not write template " + template.getFullName() + " to JSON folder : " + file.getPath(),
                e);
    } finally {
        IOUtils.closeQuietly(bw);
    }
    return;
}

From source file:com.github.riccardove.easyjasub.EasyJaSubInputFromCommand.java

private static File getOutputHtmlDirectory(EasyJaSubInputCommand command, File outputbdnFile,
        DefaultFileList defaultFileList) throws EasyJaSubException {
    String directoryName = command.getOutputHtmlDirectory();
    if (isDisabled(directoryName)) {
        return null;
    }//from  w w w.  java 2s  .co m
    File directory = null;
    if (directoryName != null && !isDefault(directoryName)) {
        directory = new File(directoryName);
    } else if (outputbdnFile != null) {
        directory = new File(outputbdnFile.getAbsoluteFile().getParentFile(), "html");
    } else {
        directory = new File(defaultFileList.getDefaultDirectory(),
                defaultFileList.getDefaultFileNamePrefix() + "_html");
    }
    if (directoryName == null) {
        directoryName = directory.getAbsolutePath();
    }
    if (directory.exists()) {
        checkDirectory(directoryName, directory);
    }
    return directory;
}

From source file:de.thischwa.pmcms.view.context.object.GalleryLinkTool.java

/**
 * Getting the link tool to the zip file containing the {@link Image}s of the desired gallery. The zip file will
 * be built.//from w  w w .  j  a  v a2s .c o  m
 * 
 * @param gallery
 * @param siteRelativePath
 * @return Link tool to the zip file containing the {@link Image}s of the desired gallery. 
 * @throws RenderingException
 */
public GalleryLinkTool getLinkToZip(final Gallery gallery, final String siteRelativePath)
        throws RenderingException {
    if (isExportView && CollectionUtils.isNotEmpty(gallery.getImages())) {
        String urlPathToZip = PathTool.getURLRelativePathToRoot(gallery.getParent()).concat(siteRelativePath)
                .concat("/").concat(gallery.getName()).concat(".zip");
        setLink(urlPathToZip);
        Map<File, String> zipEntries = new HashMap<File, String>();
        for (Image image : gallery.getImages()) { // TODO check it: order the images, if not, the hash of the zip is always different
            VirtualImage imageFile = new VirtualImage(PoInfo.getSite(gallery), false, true);
            imageFile.constructFromImage(image);
            zipEntries.put(imageFile.getBaseFile(),
                    "/".concat(FilenameUtils.getName(imageFile.getBaseFile().getAbsolutePath())));
        }
        try {
            String zipName = siteRelativePath.concat(File.separator).concat(gallery.getName()).concat(".zip");
            File zipFile = new File(PoPathInfo.getSiteExportDirectory(PoInfo.getSite(gallery)), zipName);
            zipFile.getParentFile().mkdirs();
            Zip.compressFiles(zipFile.getAbsoluteFile(), zipEntries);
        } catch (IOException e) {
            throw new RenderingException("While creating image zip file: ".concat(e.getMessage()), e);
        }
    } else {
        setLink("javascript:alert('Zip will be constructed not until export!');");
    }
    return this;
}