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:com.meltmedia.cadmium.blackbox.test.CadmiumAssertions.java

/**
 * <p>Asserts that the local directory contents have all been deployed to the remote URL prefix.</p>
 * @param message The message that will be in the error if the local directory hasn't been deployed to the remote URL prefix.
 * @param directory The directory locally that should have been deployed.
 * @param urlPrefix The URL prefix that should have the contents of the directory.
 * @param username The Basic HTTP auth username.
 * @param password The Basic HTTP auth password.
 *///  ww w  .  ja  v  a 2 s . c o  m
public static void assertContentDeployed(String message, File directory, String urlPrefix, String username,
        String password) {
    if (directory == null || !directory.isDirectory() || urlPrefix == null) {
        throw new AssertionFailedError(message);
    }
    File files[] = getAllDirectoryContents(directory, "META-INF", ".git");
    String basePath = directory.getAbsoluteFile().getAbsolutePath();
    if (urlPrefix.endsWith("/")) {
        urlPrefix = urlPrefix.substring(0, urlPrefix.length() - 2);
    }
    for (File file : files) {
        if (file.isFile()) {
            String httpPath = urlPrefix + "/"
                    + file.getAbsoluteFile().getAbsolutePath().replaceFirst(basePath + "/", "");
            assertResourcesEqual(message, file, httpPath, username, password);
        }
    }
}

From source file:dk.netarkivet.common.utils.ZipUtils.java

/** Zip the contents of a directory into a file.
 *  Does *not* zip recursively.//from   www . ja  v  a2  s.c  o m
 *
 * @param dir The directory to zip.
 * @param into The (zip) file to create.  The name should typically end
 * in .zip, but that is not required.
 */
public static void zipDirectory(File dir, File into) {
    ArgumentNotValid.checkNotNull(dir, "File dir");
    ArgumentNotValid.checkNotNull(into, "File into");
    ArgumentNotValid.checkTrue(dir.isDirectory(), "directory '" + dir + "' to zip is not a directory");
    ArgumentNotValid.checkTrue(into.getAbsoluteFile().getParentFile().canWrite(),
            "cannot write to '" + into + "'");

    File[] files = dir.listFiles();
    FileOutputStream out;
    try {
        out = new FileOutputStream(into);
    } catch (IOException e) {
        throw new IOFailure("Error creating ZIP outfile file '" + into + "'", e);
    }
    ZipOutputStream zipout = new ZipOutputStream(out);
    try {
        try {
            for (File f : files) {
                if (f.isFile()) {
                    ZipEntry entry = new ZipEntry(f.getName());
                    zipout.putNextEntry(entry);
                    FileUtils.writeFileToStream(f, zipout);
                } // Not doing directories yet.
            }
        } finally {
            zipout.close();
        }
    } catch (IOException e) {
        throw new IOFailure("Failed to zip directory '" + dir + "'", e);
    }
}

From source file:com.github.rinde.gpem17.evo.StatsLogger.java

static File createExperimentDir(File target, String nameExt) {
    final String timestamp = ISODateTimeFormat.dateHourMinuteSecond().print(System.currentTimeMillis())
            .replace(":", "");
    final File experimentDirectory = new File(target, timestamp + nameExt);
    experimentDirectory.mkdirs();/*  www . j  av  a 2s . co m*/

    final Path latest = Paths.get(target.getAbsolutePath(), "latest/");
    try {
        java.nio.file.Files.deleteIfExists(latest);
        java.nio.file.Files.createSymbolicLink(latest, experimentDirectory.getAbsoluteFile().toPath());
    } catch (final IOException e) {
        throw new IllegalStateException(e);
    }
    return experimentDirectory;
}

From source file:com.meltmedia.cadmium.core.FileSystemManager.java

public static void copyAllContent(final String source, final String target, final boolean ignoreHidden)
        throws Exception {
    File sourceFile = new File(source);
    File targetFile = new File(target);
    if (!targetFile.exists()) {
        targetFile.mkdirs();/*from   w w w  .j  a v a2  s  .c  o m*/
    }
    if (sourceFile.exists() && sourceFile.canRead() && sourceFile.isDirectory() && targetFile.exists()
            && targetFile.canWrite() && targetFile.isDirectory()) {
        List<File> copyList = new ArrayList<File>();
        FilenameFilter filter = new FilenameFilter() {

            @Override
            public boolean accept(File file, String name) {
                return !ignoreHidden || !name.startsWith(".");
            }

        };
        File files[] = sourceFile.listFiles(filter);
        if (files.length > 0) {
            copyList.addAll(Arrays.asList(files));
        }
        for (int index = 0; index < copyList.size(); index++) {
            File aFile = copyList.get(index);
            String relativePath = aFile.getAbsoluteFile().getAbsolutePath()
                    .replaceFirst(sourceFile.getAbsoluteFile().getAbsolutePath(), "");
            if (aFile.isDirectory()) {
                File newDir = new File(target, relativePath);
                if (newDir.mkdir()) {
                    newDir.setExecutable(aFile.canExecute(), false);
                    newDir.setReadable(aFile.canRead(), false);
                    newDir.setWritable(aFile.canWrite(), false);
                    newDir.setLastModified(aFile.lastModified());
                    files = aFile.listFiles(filter);
                    if (files.length > 0) {
                        copyList.addAll(index + 1, Arrays.asList(files));
                    }
                } else {
                    log.warn("Failed to create new subdirectory \"{}\" in the target path \"{}\".",
                            relativePath, target);
                }
            } else {
                File newFile = new File(target, relativePath);
                if (newFile.createNewFile()) {
                    FileInputStream inStream = null;
                    FileOutputStream outStream = null;
                    try {
                        inStream = new FileInputStream(aFile);
                        outStream = new FileOutputStream(newFile);
                        streamCopy(inStream, outStream);
                    } finally {
                        if (inStream != null) {
                            try {
                                inStream.close();
                            } catch (Exception e) {
                            }
                        }
                        if (outStream != null) {
                            try {
                                outStream.flush();
                            } catch (Exception e) {
                            }
                            try {
                                outStream.close();
                            } catch (Exception e) {
                            }
                        }
                    }
                    newFile.setExecutable(aFile.canExecute(), false);
                    newFile.setReadable(aFile.canRead(), false);
                    newFile.setWritable(aFile.canWrite(), false);
                    newFile.setLastModified(aFile.lastModified());
                }
            }
        }
    }
}

From source file:com.pinterest.terrapin.tools.HFileGenerator.java

/**
 * Generate hfiles for testing purpose//from w w w  . ja  v a 2 s .co m
 *
 * @param sourceFileSystem source file system
 * @param conf configuration for hfile
 * @param outputFolder output folder for generated hfiles
 * @param partitionerType partitioner type
 * @param numOfPartitions number of partitions
 * @param numOfKeys number of keys
 * @return list of generated hfiles
 * @throws IOException if hfile creation goes wrong
 */
public static List<Path> generateHFiles(FileSystem sourceFileSystem, Configuration conf, File outputFolder,
        PartitionerType partitionerType, int numOfPartitions, int numOfKeys) throws IOException {
    StoreFile.Writer[] writers = new StoreFile.Writer[numOfPartitions];
    for (int i = 0; i < numOfPartitions; i++) {
        writers[i] = new StoreFile.WriterBuilder(conf, new CacheConfig(conf), sourceFileSystem, 4096)
                .withFilePath(new Path(String.format("%s/%s", outputFolder.getAbsoluteFile(),
                        TerrapinUtil.formatPartitionName(i))))
                .withCompression(Compression.Algorithm.NONE).build();
    }
    Partitioner partitioner = PartitionerFactory.getPartitioner(partitionerType);
    for (int i = 0; i < numOfKeys; i++) {
        byte[] key = String.format("%06d", i).getBytes();
        byte[] value;
        if (i <= 1) {
            value = "".getBytes();
        } else {
            value = ("v" + (i + 1)).getBytes();
        }
        KeyValue kv = new KeyValue(key, Bytes.toBytes("cf"), Bytes.toBytes(""), value);
        int partition = partitioner.getPartition(new BytesWritable(key), new BytesWritable(value),
                numOfPartitions);
        writers[partition].append(kv);
    }
    for (int i = 0; i < numOfPartitions; i++) {
        writers[i].close();
    }
    return Lists.transform(Lists.newArrayList(writers), new Function<StoreFile.Writer, Path>() {
        @Override
        public Path apply(StoreFile.Writer writer) {
            return writer.getPath();
        }
    });
}

From source file:mitm.common.tools.SMIME.java

private static KeyStore loadKeyStore(String keyFile, String password) throws Exception {
    File file = new File(keyFile);

    file = file.getAbsoluteFile();

    KeyStore keyStore = securityFactory.createKeyStore("PKCS12");

    /* initialize key store */
    keyStore.load(new FileInputStream(file), password != null ? password.toCharArray() : null);

    return keyStore;
}

From source file:adams.data.image.ImageMetaDataHelper.java

/**
 * Reads the meta-data from the file (using meta-data extractor).
 * /*  w w w .ja va 2  s .  co  m*/
 * @param file   the file to read the meta-data from
 * @return      the meta-data
 * @throws Exception   if failed to read meta-data
 */
public static SpreadSheet metaDataExtractor(File file) throws Exception {
    SpreadSheet sheet;
    Row row;
    com.drew.metadata.Metadata metadata;

    sheet = new DefaultSpreadSheet();

    // header
    row = sheet.getHeaderRow();
    row.addCell("K").setContent("Key");
    row.addCell("V").setContent("Value");

    metadata = ImageMetadataReader.readMetadata(file.getAbsoluteFile());
    for (Directory directory : metadata.getDirectories()) {
        for (Tag tag : directory.getTags()) {
            row = sheet.addRow();
            row.addCell("K").setContent(tag.getTagName());
            row.addCell("V").setContent(fixDateTime(tag.getDescription()));
        }
    }
    return sheet;
}

From source file:org.openhab.io.caldav.internal.Util.java

public static void storeToDisk(String calendarId, String filename, Calendar calendar) {
    File cacheFile = getCacheFile(calendarId, filename);
    try {//from w w  w .j  a  va2 s. c  om
        FileOutputStream fout = new FileOutputStream(cacheFile);
        CalendarOutputter outputter = new CalendarOutputter();
        outputter.setValidating(false);
        outputter.output(calendar, fout);
        fout.flush();
        fout.close();
    } catch (IOException e) {
        log.error("cannot store event '{}' to disk (path={}): {}", filename, cacheFile.getAbsoluteFile(),
                e.getMessage());
    } catch (ValidationException e) {
        log.error("cannot store event '{}' to disk (path={}): {}", filename, cacheFile.getAbsoluteFile(),
                e.getMessage());
    }
}

From source file:ch.admin.suis.msghandler.util.FileUtils.java

/**
 * Returns a {@link File} object pointing to the absolute path for the supplied name. If the
 * <code>name</code> parameter already denotes an absolute path, then a {@link File} object is created solely for this
 * path. Otherwise a {@link File} object is created treating the
 * <code>parent</code> parameter as the parent directory and the
 * <code>name</code> parameter as a child path relative to that parent.
 *
 * @param parent parent directory// w  w  w .j a  va 2  s  .co m
 * @param name   child path relative to that parent
 * @return The object pointing to the absolute path
 */
public static File createPath(String parent, String name) {
    File nameFile = new File(name);
    if (nameFile.isAbsolute()) {
        return nameFile;
    } else if (StringUtils.isEmpty(parent)) { // parent == null || parent.isEmpty()
        return nameFile.getAbsoluteFile();
    } else {
        File concatFile = new File(new File(parent), name);
        return concatFile.isAbsolute() ? concatFile : concatFile.getAbsoluteFile();
    }
}

From source file:gridool.util.GridUtils.java

public static File getIndexDir(boolean verify) {
    if (idxDir == null) {
        return getWorkDir(verify);
    } else {/*from w  w  w. j a v a  2 s .c  o m*/
        File dir = new File(idxDir);
        if (verify && !dir.exists()) {
            throw new IllegalStateException("Database directory not found: " + dir.getAbsoluteFile());
        }
        return dir;
    }
}