Example usage for java.io File getParent

List of usage examples for java.io File getParent

Introduction

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

Prototype

public String getParent() 

Source Link

Document

Returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.

Usage

From source file:com.redhat.red.offliner.ftest.SkipMavenMetadataGenerateFTest.java

/**
 * In general, we should only have one test method per functional test. This allows for the best parallelism when we
 * execute the tests, especially if the setup takes some time.
 *
 * @throws Exception In case anything (anything at all) goes wrong!
 *//*w  w  w  .j a  va2 s  . c om*/
@Test
public void run() throws Exception {
    // We only need one repo server.
    TestRepositoryServer server = newRepositoryServer();

    // Generate some test content
    byte[] content = contentGenerator.newBinaryContent(1024);

    Dependency dep = contentGenerator.newDependency();
    Model pom = contentGenerator.newPom();
    pom.addDependency(dep);

    String path = contentGenerator.pathOf(dep);

    // Register the generated content by writing it to the path within the repo server's dir structure.
    // This way when the path is requested it can be downloaded instead of returning a 404.
    server.registerContent(path, content);
    server.registerContent(path + Main.SHA_SUFFIX, sha1Hex(content));
    server.registerContent(path + Main.MD5_SUFFIX, md5Hex(content));

    // All deps imply an accompanying POM file when using the POM artifact list reader, so we have to register one of these too.
    Model pomDep = contentGenerator.newPomFor(dep);
    String pomPath = contentGenerator.pathOf(pomDep);
    String md5Path = pomPath + Main.MD5_SUFFIX;
    String shaPath = pomPath + Main.SHA_SUFFIX;

    String pomStr = contentGenerator.pomToString(pomDep);

    server.registerContent(pomPath, pomStr);
    server.registerContent(md5Path, md5Hex(pomStr));
    server.registerContent(shaPath, sha1Hex(pomStr));

    // Write the plaintext file we'll use as input.
    File pomFile = temporaryFolder.newFile(getClass().getSimpleName() + ".pom");

    FileUtils.write(pomFile, contentGenerator.pomToString(pom));

    Options opts = new Options();
    opts.setBaseUrls(Collections.singletonList(server.getBaseUri()));

    // Capture the downloads here so we can verify the content.
    File downloads = temporaryFolder.newFolder();

    opts.setDownloads(downloads);
    opts.setLocations(Collections.singletonList(pomFile.getAbsolutePath()));

    // THIS IS THE KEY TO THIS TEST.
    opts.setSkipMetadata(true);

    // run `new Main(opts).run()` and return the Main instance so we can query it for errors, etc.
    Main finishedMain = run(opts);
    assertThat("Errors should be empty!", finishedMain.getErrors().isEmpty(), equalTo(true));

    // get the ProjectVersion info by pomPath reading from ArtifactPathInfo parse.
    ArtifactPathInfo artifactPathInfo = ArtifactPathInfo.parse(pomPath);
    ProjectVersionRef gav = artifactPathInfo.getProjectId();
    File metadataFile = Paths.get(opts.getDownloads().getAbsolutePath(),
            gav.getGroupId().replace('.', File.separatorChar), gav.getArtifactId(), "maven-metadata.xml")
            .toFile();
    assertThat("maven-metadata.xml for path: " + metadataFile.getParent()
            + " doesn't seem to have been generated!", metadataFile.exists(), equalTo(false));
}

From source file:com.terradue.dsi.UploadAppliance.java

private File zip(File directory) throws IOException {
    final URI base = directory.getParentFile().toURI();

    File zipFile = new File(directory.getParent(), format("%s.zip", directory.getName()));

    logger.info("Archiving directory {} to zip archive {}", directory, zipFile);

    FileOutputStream fos = null;/*from   ww  w  .ja  v  a 2s  .com*/
    ZipOutputStream os = null;
    try {
        fos = new FileOutputStream(zipFile);
        os = new ZipOutputStream(fos);
        os.setComment(format("Created by %s %s", getProperty("project.name"), getProperty("project.version")));

        addToZip(os, base, directory);
    } finally {
        try {
            os.finish();
        } finally {
            logger.info("ZIP archive complete");
            closeQuietly(os);
            closeQuietly(fos);
        }
    }

    return zipFile;
}

From source file:lyonlancer5.karasu.util.ModFileUtils.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public synchronized void doHashCheck(File jarFile) {
    if (doHashCheck) {
        if (hasInitialized) {
            LOGGER.info("Mod source file " + jarFile.getName() + " located at " + jarFile.getParent());
            if (jarFile.isFile() && !jarFile.getName().endsWith("bin")) {
                try {
                    HashMap params = (HashMap) ((HashMap) Yaml.loadType(remoteHashes, HashMap.class)
                            .get("version")).get(Constants.VERSION);
                    if (!params.get("jar").equals(jarFile.getName())) {
                        LOGGER.warn("JAR filename has been changed");

                    }/* w ww  .  j a va  2s . c  o m*/
                    FileInputStream fis = new FileInputStream(jarFile);
                    HashMap<String, String> theHashes = (HashMap<String, String>) params.get("hash");
                    String md5 = DigestUtils.md5Hex(fis);
                    String sha1 = DigestUtils.sha1Hex(fis);
                    fis.close();

                    if (md5.equals(theHashes.get("md5"))) {
                        LOGGER.info("Validated MD5 hash - " + md5);
                    } else {
                        throw new RuntimeException(
                                "MD5 check FAILED: Expected " + md5 + " - Received " + theHashes.get("md5"));
                    }

                    if (sha1.equals(theHashes.get("sha1"))) {
                        LOGGER.info("Validated SHA1 hash - " + sha1);
                    } else {
                        throw new RuntimeException(
                                "SHA1 check FAILED: Expected " + sha1 + " - Received " + theHashes.get("sha1"));
                    }

                } catch (IOException e) {
                    throw new RuntimeException("Validation FAILED - I/O error", e);
                }
            } else {
                LOGGER.warn(
                        "The mod is currently running on a development environment - Integrity checking will not proceed");
            }
        } else {
            throw new RuntimeException("Validation FAILED - Validation utilites have not been initialized!");
        }
    } else {
        LOGGER.warn("#########################################################################");
        LOGGER.warn("WARNING: Integrity checks have been DISABLED!");
        LOGGER.warn("Hash checks will not be performed - this mod may not run correctly");
        LOGGER.warn("Any changes made to this mod will not be validated, whether it came from");
        LOGGER.warn("a legitimate edit or an attempt to insert code into this modification");
        LOGGER.warn("#########################################################################");
    }
}

From source file:com.ephesoft.dcma.util.TIFFUtil.java

/**
 * The <code>getSelectedTiffFile</code> method is used to limit the file
 * to the page limit given.//from w w w . ja v  a  2  s .  co m
 * 
 * @param tiffFile {@link File} tiff file from which limit has to be applied
 * @param pageLimit int
 * @throws IOException if file is not found
 */
public static void getSelectedTiffFile(final File tiffFile, final int pageLimit) throws IOException {
    OutputStream out = null;
    File newTiffFile = null;
    if (null != tiffFile && getTIFFPageCount(tiffFile.getAbsolutePath()) > pageLimit) {
        try {
            final List<BufferedImage> imageList = new ArrayList<BufferedImage>();
            final SeekableStream seekableStream = new FileSeekableStream(tiffFile);
            final ImageDecoder decoder = ImageCodec.createImageDecoder("tiff", seekableStream, null);
            for (int i = 1; i < pageLimit; i++) {
                final PlanarImage planarImage = new NullOpImage(decoder.decodeAsRenderedImage(i), null, null,
                        OpImage.OP_IO_BOUND);
                imageList.add(planarImage.getAsBufferedImage());
            }
            seekableStream.close();
            final TIFFEncodeParam params = new TIFFEncodeParam();
            params.setCompression(TIFFEncodeParam.COMPRESSION_GROUP4);
            String name = tiffFile.getName();
            final int indexOf = name.lastIndexOf(IUtilCommonConstants.DOT);
            name = name.substring(0, indexOf);
            final String finalPath = tiffFile.getParent() + File.separator + name + System.currentTimeMillis()
                    + IUtilCommonConstants.EXTENSION_TIF;
            newTiffFile = new File(finalPath);
            out = new FileOutputStream(finalPath);
            final ImageEncoder encoder = ImageCodec.createImageEncoder("tiff", out, params);
            params.setExtraImages(imageList.iterator());
            encoder.encode(imageList.get(0));
        } finally {
            if (null != out) {
                out.flush();
                out.close();
            }
        }
        if (tiffFile.delete() && null != newTiffFile) {
            newTiffFile.renameTo(tiffFile);
        } else {
            if (null != newTiffFile) {
                newTiffFile.delete();
            }
        }
    }
}

From source file:io.stallion.tools.ScriptExecBase.java

@Override
public void execute(ScriptOptions options) throws Exception {
    if (options.getArguments().size() < 2) {
        throw new CommandException(
                "You must pass in the script that you want to execute as a positional argument");
    }// ww w .  ja  v a  2 s . c o  m
    String scriptArg = options.getArguments().get(1);

    String plugin = "";
    String path = scriptArg;
    String[] parts = scriptArg.split(":");
    String scriptPath = "";
    if (parts.length > 1) {
        plugin = parts[0];
        path = parts[1];
    }

    URL url = null;
    String folder = null;
    if (!empty(plugin)) {
        if ("stallion".equals(plugin)) {
            url = getClass().getResource(path);
        }
        if (url == null && PluginRegistry.instance() != null) {
            StallionJavaPlugin booter = PluginRegistry.instance().getJavaPluginByName().getOrDefault(plugin,
                    null);
            if (booter != null) {
                url = booter.getClass().getResource(path);
            }
        }
        if (url == null) {
            if (plugin.equals("js")) {
                String fullPath = settings().getTargetFolder() + "/js" + path;
                File file = new File(fullPath);
                if (file.isFile()) {
                    url = new URL("file:" + fullPath);
                    scriptPath = file.getParent();
                    folder = settings().getTargetFolder() + "/js";
                }

            } else {

                String fullPath = settings().getTargetFolder() + "/plugins/" + plugin + path;
                File file = new File(fullPath);
                if (file.isFile()) {
                    url = new URL("file:" + fullPath);
                    scriptPath = file.getParent();
                    folder = settings().getTargetFolder() + "/plugins/" + plugin;
                }
            }
        }
    } else {
        url = new URL("file:" + settings().getTargetFolder() + "/js/" + path);
        folder = settings().getTargetFolder() + "/js/";
    }
    if (url == null) {
        throw new CommandException(
                "Could not find matching script for '" + scriptArg + "' in any folder or jar resource.");
    }
    if (empty(folder)) {
        folder = new File(url.toString()).getParent();
    }
    String source = IOUtils.toString(url, UTF8);
    List<String> args = list(path);
    if (options.getArguments().size() > 2) {
        args.addAll(options.getArguments().subList(2, options.getArguments().size()));
    }
    if (path.endsWith(".js")) {
        executeJavascript(source, url, scriptPath, folder, args, plugin);
    } else {
        throw new CommandException(
                "Unknown extension for path. Supported extensions are .py for jython and .js for javascript. Path was: "
                        + path);
    }
}

From source file:com.liferay.ide.alloy.core.webresources_src.PortalResourcesProvider.java

@Override
public File[] getResources(IWebResourcesContext context) {
    File[] retval = null;// w ww.j  a  va2s .  c  om
    IFile htmlFile = context.getHtmlFile();

    ILiferayProject project = LiferayCore.create(htmlFile.getProject());

    if ((htmlFile != null) && (project != null)) {
        ILiferayPortal portal = project.adapt(ILiferayPortal.class);

        if ((portal != null) && ProjectUtil.isPortletProject(htmlFile.getProject())) {
            IPath portalDir = portal.getAppServerPortalDir();

            if (portalDir != null) {
                IPath cssPath = portalDir.append("html/themes/_unstyled/css");

                if (FileUtil.exists(cssPath)) {
                    synchronized (_fileCache) {
                        Collection<File> cachedFiles = _fileCache.get(cssPath);

                        if (cachedFiles != null) {
                            retval = cachedFiles.toArray(new File[0]);
                        } else {
                            String types = new String[] { "css", "scss" };

                            Collection<File> files = FileUtils.listFiles(cssPath.toFile(), types, true);

                            Collection<File> cached = new HashSet<>();

                            for (File file : files) {
                                String fileName = file.getName();

                                if (fileName.endsWith("scss")) {
                                    File cachedFile = new File(file.getParent(),
                                            ".sass-cache/" + fileName.replaceAll("scss$", "css"));

                                    if (FileUtil.exists(cachedFile)) {
                                        cached.add(file);
                                    }
                                }
                            }

                            files.removeAll(cached);

                            if (files != null) {
                                retval = files.toArray(new File[0]);
                            }

                            _fileCache.put(cssPath, files);
                        }
                    }
                }
            }
        } else if ((portal != null) && ProjectUtil.isLayoutTplProject(htmlFile.getProject())) {

            // return the static css resource for layout template names based on the version

            String version = portal.getVersion();

            try {
                if ((version != null) && (version.startsWith("6.0") || version.startsWith("6.1"))) {
                    retval = _createLayoutHelperFiles("resources/layouttpl-6.1.css");
                } else if (version != null) {
                    retval = _createLayoutHelperFiles("resources/layouttpl-6.2.css");
                }
            } catch (IOException ioe) {
                AlloyCore.logError("Unable to load layout template helper css files", ioe);
            }
        }
    }

    return retval;
}

From source file:de.tudarmstadt.ukp.dkpro.tc.ml.report.BatchPredictionReport.java

@Override
public void execute() throws Exception {
    StorageService store = getContext().getStorageService();

    FlexTable<String> table = FlexTable.forClass(String.class);

    for (TaskContextMetadata subcontext : getSubtasks()) {
        // FIXME this is a bad hack
        if (subcontext.getType().contains("ExtractFeaturesAndPredictTask")) {

            Map<String, String> discriminatorsMap = store
                    .retrieveBinary(subcontext.getId(), Task.DISCRIMINATORS_KEY, new PropertiesAdapter())
                    .getMap();//from w w w  . ja va2  s  . c o  m

            // deserialize file
            FileInputStream f = new FileInputStream(
                    store.getStorageFolder(subcontext.getId(), PREDICTION_MAP_FILE_NAME));
            ObjectInputStream s = new ObjectInputStream(f);
            Map<String, List<String>> resultMap = (Map<String, List<String>>) s.readObject();
            s.close();

            // write one file per batch
            // in files: one line per instance

            for (String id : resultMap.keySet()) {
                Map<String, String> row = new HashMap<String, String>();
                row.put(predicted_value, StringUtils.join(resultMap.get(id), ","));
                table.addRow(id, row);
            }
            // create a separate output folder for each execution of
            // ExtractFeaturesAndPredictTask, 36 is the length of the UUID hash
            File contextFolder = store.getStorageFolder(getContext().getId(),
                    subcontext.getId().substring(subcontext.getId().length() - 36));
            // Excel cannot cope with more than 255 columns
            if (table.getColumnIds().length <= 255) {
                getContext().storeBinary(contextFolder.getName() + System.getProperty("file.separator")
                        + report_name + SUFFIX_EXCEL, table.getExcelWriter());
            }
            getContext().storeBinary(
                    contextFolder.getName() + System.getProperty("file.separator") + report_name + SUFFIX_CSV,
                    table.getCsvWriter());
            getContext().storeBinary(
                    contextFolder.getName() + System.getProperty("file.separator") + Task.DISCRIMINATORS_KEY,
                    new PropertiesAdapter(discriminatorsMap));
        }
    }

    // output the location of the batch evaluation folder
    // otherwise it might be hard for novice users to locate this
    File dummyFolder = store.getStorageFolder(getContext().getId(), "dummy");
    // TODO can we also do this without creating and deleting the dummy folder?
    getContext().getLoggingService().message(getContextLabel(),
            "Storing detailed results in:\n" + dummyFolder.getParent() + "\n");
    dummyFolder.delete();
}

From source file:de.tudarmstadt.ukp.dkpro.tc.weka.report.WekaBatchPredictionReport.java

@Override
public void execute() throws Exception {
    StorageService store = getContext().getStorageService();

    FlexTable<String> table = FlexTable.forClass(String.class);

    for (TaskContextMetadata subcontext : getSubtasks()) {
        if (subcontext.getType().startsWith(ExtractFeaturesAndPredictTask.class.getName())) {

            Map<String, String> discriminatorsMap = store
                    .retrieveBinary(subcontext.getId(), Task.DISCRIMINATORS_KEY, new PropertiesAdapter())
                    .getMap();/*w w  w . j  av a  2  s. c om*/

            // deserialize file
            FileInputStream f = new FileInputStream(store.getStorageFolder(subcontext.getId(),
                    ExtractFeaturesAndPredictConnector.PREDICTION_MAP_FILE_NAME));
            ObjectInputStream s = new ObjectInputStream(f);
            Map<String, List<String>> resultMap = (Map<String, List<String>>) s.readObject();
            s.close();

            // write one file per batch
            // in files: one line per instance

            for (String id : resultMap.keySet()) {
                Map<String, String> row = new HashMap<String, String>();
                row.put(predicted_value, StringUtils.join(resultMap.get(id), ","));
                table.addRow(id, row);
            }
            // create a separate output folder for each execution of
            // ExtractFeaturesAndPredictTask, 36 is the length of the UUID hash
            File contextFolder = store.getStorageFolder(getContext().getId(),
                    subcontext.getId().substring(subcontext.getId().length() - 36));
            // Excel cannot cope with more than 255 columns
            if (table.getColumnIds().length <= 255) {
                getContext().storeBinary(contextFolder.getName() + System.getProperty("file.separator")
                        + report_name + SUFFIX_EXCEL, table.getExcelWriter());
            }
            getContext().storeBinary(
                    contextFolder.getName() + System.getProperty("file.separator") + report_name + SUFFIX_CSV,
                    table.getCsvWriter());
            getContext().storeBinary(
                    contextFolder.getName() + System.getProperty("file.separator") + Task.DISCRIMINATORS_KEY,
                    new PropertiesAdapter(discriminatorsMap));
        }
    }

    // output the location of the batch evaluation folder
    // otherwise it might be hard for novice users to locate this
    File dummyFolder = store.getStorageFolder(getContext().getId(), "dummy");
    // TODO can we also do this without creating and deleting the dummy folder?
    getContext().getLoggingService().message(getContextLabel(),
            "Storing detailed results in:\n" + dummyFolder.getParent() + "\n");
    dummyFolder.delete();
}

From source file:dkpro.similarity.uima.io.WebisCPC11Reader.java

@Override
public List<CombinationPair> getAlignedPairs() throws ResourceInitializationException {
    List<CombinationPair> pairs = new ArrayList<CombinationPair>();

    List<File> originals = listFiles(inputDir, "-original.txt", false);
    for (File original : originals) {
        try {//from  w  ww .jav  a 2s .c o m
            String textOriginal = FileUtils.readFileToString(original);

            String id = original.getName().substring(original.getName().length() - 5,
                    original.getName().length() - 4);

            File paraphrase = new File(original.getParent() + "/" + id + "-paraphrase.txt");
            String textParaphrase = FileUtils.readFileToString(paraphrase);

            CombinationPair pair = new CombinationPair(inputDir.getAbsolutePath());
            pair.setID1(original.getName().substring(0, original.getName().length() - 4));
            pair.setID2(paraphrase.getName().substring(0, paraphrase.getName().length() - 4));
            pair.setText1(textOriginal);
            pair.setText2(textParaphrase);

            pairs.add(pair);
        } catch (IOException e) {
            throw new ResourceInitializationException(e);
        }
    }

    return pairs;
}

From source file:com.ephesoft.dcma.util.FileUtils.java

/**
 * This method zips the contents of Directory specified into a zip file whose name is provided.
 * /*w  w  w  . j av  a  2 s .  c o  m*/
 * @param dir2zip {@link String}
 * @param zout {@link String}
 * @param dir2zipName {@link String}
 * @throws IOException in case of error
 */
public static void zipDirectory(String dir2zip, ZipOutputStream zout, String dir2zipName) throws IOException {
    File srcDir = new File(dir2zip);
    List<String> fileList = listDirectory(srcDir);
    for (String fileName : fileList) {
        File file = new File(srcDir.getParent(), fileName);
        String zipName = fileName;
        if (File.separatorChar != FORWARD_SLASH) {
            zipName = fileName.replace(File.separatorChar, FORWARD_SLASH);
        }
        zipName = zipName.substring(
                zipName.indexOf(dir2zipName + BACKWARD_SLASH) + 1 + (dir2zipName + BACKWARD_SLASH).length());

        ZipEntry zipEntry;
        if (file.isFile()) {
            zipEntry = new ZipEntry(zipName);
            zipEntry.setTime(file.lastModified());
            zout.putNextEntry(zipEntry);
            FileInputStream fin = new FileInputStream(file);
            byte[] buffer = new byte[UtilConstants.BUFFER_CONST];
            for (int n; (n = fin.read(buffer)) > 0;) {
                zout.write(buffer, 0, n);
            }
            if (fin != null) {
                fin.close();
            }
        } else {
            zipEntry = new ZipEntry(zipName + FORWARD_SLASH);
            zipEntry.setTime(file.lastModified());
            zout.putNextEntry(zipEntry);
        }
    }
    if (zout != null) {
        zout.close();
    }
}