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:org.sansdemeure.zenindex.service.BatchService.java

@Transactional
public void treatDocument(File odtFile, String originals) {
    Doc d = new Doc();
    d.setMd5(FileUtil.calculateMD5(odtFile));
    d.setOriginals(originals);//from  w w w.j a  va  2  s .  co  m
    d.setLastIndex(new Date());
    d.setPath(odtFile.getParent());
    String name = FileUtil.removeExtension(odtFile.getName());
    d.setName(name);
    DocumentIndexer documentIndexer = DocumentIndexerFactory.build();
    Map<String, Object> model = documentIndexer.content(odtFile);
    File htmlDocument = new File(odtFile.getParent(), name + ".html");
    templateService.generateDocumentPage(model, htmlDocument);
    Pair<List<Keyword>, List<DocPart>> tuple = documentIndexer.getKeywordsAndDocParts(odtFile, keywords);
    keywords = tuple.first;
    docRepository.saveNewKeywords(keywords);
    List<DocPart> docParts = tuple.second;
    for (DocPart docPart : docParts) {
        d.addDocPart(docPart);
    }
    docRepository.save(d);
}

From source file:c3.ops.priam.backup.AbstractBackupPath.java

/**
 * Local restore file//from www. ja  v  a  2  s.  c  o  m
 */
public File newRestoreFile() {
    StringBuffer buff = new StringBuffer();
    if (type == BackupFileType.CL) {
        buff.append(config.getBackupCommitLogLocation()).append(PATH_SEP);
    } else {

        buff.append(config.getDataFileLocation()).append(PATH_SEP);
        if (type != BackupFileType.META) {
            if (isCassandra1_0)
                buff.append(keyspace).append(PATH_SEP);
            else
                buff.append(keyspace).append(PATH_SEP).append(columnFamily).append(PATH_SEP);
        }
    }

    buff.append(fileName);

    File return_ = new File(buff.toString());
    File parent = new File(return_.getParent());
    if (!parent.exists())
        parent.mkdirs();
    return return_;
}

From source file:com.aurel.track.dbase.HandleHome.java

public static void writeHash(File existingFile, String hash) {
    try {//from  www  .  j  a va 2  s  .c  o m
        File hashFile = new File(existingFile.getParent() + File.separator + "hash.txt");
        Map<String, Object> hashMap = new HashMap<String, Object>();
        if (hashFile.exists()) {
            String fname = "";
            List<String> hashes = FileUtils.readLines(hashFile);
            for (String fhash : hashes) {
                String[] keyv = fhash.split("=");
                if (keyv != null && keyv.length > 1 && keyv[1] != null) {
                    fname = keyv[0];
                    hashMap.put(fname, keyv[1]);
                }
            }
        }
        hashMap.put(existingFile.getName(), hash);
        PrintWriter output;
        output = new PrintWriter(new FileWriter(hashFile, false));

        for (String key : hashMap.keySet()) {
            output.println(key + "=" + hashMap.get(key));
        }
        output.close();
    } catch (Exception e) {
        LOGGER.warn(e.getMessage());
    }
}

From source file:genepi.db.h2.H2Connector.java

public boolean createBackup(String folder) {

    File file = new File(path + ".h2.db");
    File file2 = new File(path + ".mv.db");

    boolean exists = file.exists() || file2.exists();

    if (exists) {

        FileUtil.copyDirectory(file.getParent(), folder);

    }/*w  w  w.ja v a 2 s  . c  om*/

    log.info("Created backup file " + folder);

    return true;

}

From source file:net.bhl.cdt.connector.avl.strategies.AVLProcessGeneratorStrategy.java

@Override
public void start(ProcessElement processElement) {
    if (processElement instanceof AVLProcessGenerator) {
        AVLProcessGenerator avlProcessGenerator = (AVLProcessGenerator) processElement;
        avlProcessGenerator.setRuncaseCounter(1);
        avlProcessGenerator.getAvlResultImporters().clear();
        FileWriter processFileWriter = null;
        FileWriter commandFileWriter = null;
        try {//from   w ww  .j av  a  2s .  co  m
            File avlEngine = new File(Activator.getDefault().getPreferenceStore().getString("AVLPATH"));
            String avlProcessPath = avlEngine.getParent() + File.separator + avlProcessGenerator.getFileName();
            File file = new File(avlProcessPath);
            processFileWriter = new FileWriter(file, false);
            generateRunCases(avlProcessGenerator, processFileWriter);

            File commandFile = new File(avlEngine.getParent() + File.separator
                    + avlProcessGenerator.getCommandFileName().toString());
            commandFileWriter = new FileWriter(commandFile, false);
            generateCommandFile(avlProcessGenerator, commandFileWriter);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                processFileWriter.flush();
                processFileWriter.close();
                commandFileWriter.flush();
                commandFileWriter.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }
}

From source file:com.mattc.argus.concurrent.ZipProcess.java

public void run() {
    running.set(true);//from  w  w w . j  a  v a 2  s .  co  m

    //Zip Archive Entry Input Stream
    InputStream zis = null;

    try {

        zip = new ZipFile(zipFile);
        ZipArchiveEntry entry;
        Enumeration<ZipArchiveEntry> entries;

        entries = zip.getEntriesInPhysicalOrder();

        //While there are still Entries to process, iterate
        while (entries.hasMoreElements()) {
            entry = entries.nextElement();
            //Create the Empty File to Extract to and its Parent Directory
            //Notify Console and ProgressLog that a File is Being Extracted
            File destination = new File(destDir, entry.getName());
            File dirs = new File(destination.getParent());
            dirs.mkdirs();
            Console.info("EXT: " + Utility.relativizePath(destination, destDir.getParentFile()));
            Notifications.updateLog("Extracting " + destination.getName()
                    + (entry.isDirectory() ? " as Directory" : " as File") + "...");

            /*
             * IMPORTANT
             * 
             * Ensures that All Files have a Directory to go to.
             * 
             * If a Folder is for some reason created as a File, this will
             * detect that. It will delete the file and re-create it as a Directory
             * so that installation can continue.
             * 
             * If all else fails, print debug information and stop extracting. 
             * It is unlikely the installed application will work without all files
             * being extracted.
             */
            try {
                if (!destination.getParentFile().isDirectory()) {
                    destination.getParentFile().delete();
                    destination.getParentFile().mkdirs();
                }
                destination.createNewFile();
            } catch (IOException e) {
                String errMsg = "Failure to Extract " + zipFile.getName();
                String errPath = "PATH = " + destination.getCanonicalPath();
                String errParent = "PARENT = " + destination.getParentFile().getCanonicalPath();
                String errIsDir = "PARENT_IS_DIRECTORY = " + destination.getParentFile().isDirectory();

                //Standard IO Error Information
                e.printStackTrace(System.err);
                System.err.println(errMsg);
                System.err.println(errPath);
                System.err.println(errParent);
                System.err.println(errIsDir);

                //Log File Error Information (Possibly Standard IO if DEBUG = True)
                Console.exception(e);
                Console.error(errMsg);
                Console.error(errPath);
                Console.error(errParent);
                Console.error(errIsDir);

                //GUI Error Information. For End User.
                String msg = errMsg + "\n" + errPath + "\n" + errParent + "\n" + errIsDir;
                Notifications.exception(msg, e);

                //Attempt to Delete the Partially Unzipped and Non-functional install Directory
                if (!Utility.deleteDirectory(destDir)) {
                    Console.error("Although extraction failed, the erroneous directory could not be removed!");
                    Notifications.error("Failure to Delete Partially Unzipped Directory!");
                } else
                    Console.info("Erroneous Directory Deleted Successfully!");

            }

            //Establish a Stream to output data to the destination file
            zis = zip.getInputStream(entry);
            fos = new FileOutputStream(destination);

            //Read Zip Entry data into buffer, output buffer to installation file
            for (int c = zis.read(buffer); c > 0; c = zis.read(buffer))
                fos.write(buffer, 0, c);

            //Close Current Entry and Destination OutputStream
            zis.close();
            fos.close();
        }
    } catch (ZipException e) {
        Console.exception(e);
    } catch (IOException e) {
        Console.exception(e);
    } finally { //Ensure that All Streams Are Closed to prevent Memory Leaks
        Utility.closeStream(zis);
        Utility.closeStream(fos);
        Utility.closeStream(zip);
        running.set(false);
    }
}

From source file:com.voodoowarez.alclassicist.CtDumpMojo.java

protected void writeClass(final CtClass klass) throws MojoExecutionException {
    final String klassName = klass.getName(),
            pathedName = this.outputDirectory + klassName.replace(".", "/") + this.ctSuffix;
    final File file = new File(pathedName);
    try {/*from ww w. ja v a2 s.co m*/
        FileUtils.forceMkdir(file.getParentFile());
    } catch (IOException e) {
        throw new MojoExecutionException("Couldn't create directory " + file.getParent() + " for " + klassName,
                e);
    }
    try {
        this.objectMapper.writeValue(file, klass);
    } catch (Exception e) {
        throw new MojoExecutionException("Couldn't output CtClass " + klassName, e);
    }
}

From source file:com.cubeia.jetty.JettyEmbed.java

/** 
 * Takes a relative to the cwd (current work dir, poker-uar) path and 
 * creates the absolute path to the war file.
 * <p>/*from w w w  .  j  a  va2s . com*/
 * TODO: this needs to be changed to use either java or firebase mechanics
 * to determine cwd and the war location in a more elegant (ideally 
 * generic) way.
 *
 * @return the absolute path to the war
 */
public String getWarPath(String warFile) {
    File sarFile;
    String sarRoot;
    try {
        sarFile = new File(
                caller.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
        sarRoot = sarFile.getParent();
    } catch (URISyntaxException ex) {
        log.debug(null, ex);
        sarRoot = "";
    }
    String libDir = FilenameUtils.concat(sarRoot, "META-INF/lib");
    String filename = this.finalFileName(libDir, warFile);
    String warPath = FilenameUtils.concat(libDir, filename);
    log.debug("warPath : " + warPath);
    return warPath;
}

From source file:com.google.api.ads.adwords.jaxws.extensions.kratu.restserver.RestServer.java

public synchronized Restlet createInboundRoot() {
    Router router = new Router(getContext());

    // *** MCCs ***
    router.attach("/mcc", MccRest.class); //LIST All

    // *** Accounts ***
    router.attach("/mcc/{topAccountId}/accounts", AccountRest.class); //LIST All

    // *** Kratu ***
    // ?includeZeroImpressions=false by default
    router.attach("/mcc/{topAccountId}/kratu", KratuRest.class); // List All
    router.attach("/mcc/{topAccountId}/kratu/{accountId}", KratuRest.class); // LIST Account level

    // Genereate Kratus MCC level
    // ?dateStart=yyyyMMdd&dateEnd=yyyyMMdd
    router.attach("/mcc/{topAccountId}/generatekratus", GenerateKratusRest.class);

    // *** Reporting ***
    // Generate//w w  w . j  a v  a  2s .  c  om
    // ?dateStart=yyyyMMdd&dateEnd=yyyyMMdd
    router.attach("/mcc/{topAccountId}/generatereports", GenerateReportsRest.class);

    // Accounts
    // ?dateStart=yyyyMMdd&dateEnd=yyyyMMdd
    router.attach("/mcc/{topAccountId}/reportaccount", ReportAccountRest.class); //LIST All
    router.attach("/mcc/{topAccountId}/reportaccount/{accountId}", ReportAccountRest.class); //LIST Account level

    // Campaigns
    // ?dateStart=yyyyMMdd&dateEnd=yyyyMMdd
    router.attach("/mcc/{topAccountId}/reportcampaign", ReportCampaignRest.class); //LIST All
    router.attach("/mcc/{topAccountId}/reportcampaign/{accountId}", ReportCampaignRest.class); //LIST Account level
    router.attach("/mcc/{topAccountId}/reportcampaign/campaign/{campaignId}", ReportCampaignRest.class); //LIST Campaign level

    // AdGroups
    // ?dateStart=yyyyMMdd&dateEnd=yyyyMMdd
    router.attach("/mcc/{topAccountId}/reportadgroup", ReportAdGroupRest.class); //LIST All
    router.attach("/mcc/{topAccountId}/reportadgroup/{accountId}", ReportAdGroupRest.class); //LIST Account level
    router.attach("/mcc/{topAccountId}/reportadgroup/campaign/{campaignId}", ReportAdGroupRest.class); //LIST Campaign level
    router.attach("/mcc/{topAccountId}/reportadgroup/adgroup/{adGroupId}", ReportAdGroupRest.class); //LIST AdGroup level

    // Ads
    // ?dateStart=yyyyMMdd&dateEnd=yyyyMMdd
    router.attach("/mcc/{topAccountId}/reportad", ReportAdRest.class); //LIST All
    router.attach("/mcc/{topAccountId}/reportad/{accountId}", ReportAdRest.class); //LIST Account level
    router.attach("/mcc/{topAccountId}/reportad/campaign/{campaignId}", ReportAdRest.class); //LIST Campaign level
    router.attach("/mcc/{topAccountId}/reportad/adgroup/{adGroupId}", ReportAdRest.class); //LIST AdGroup level
    router.attach("/mcc/{topAccountId}/reportad/ad/{adId}", ReportAdRest.class); //LIST Ad level

    // Keywords
    // ?dateStart=yyyyMMdd&dateEnd=yyyyMMdd
    router.attach("/mcc/{topAccountId}/reportkeyword", ReportKeywordRest.class); //LIST All
    router.attach("/mcc/{topAccountId}/reportkeyword/{accountId}", ReportKeywordRest.class); //LIST Account level
    router.attach("/mcc/{topAccountId}/reportkeyword/campaign/{campaignId}", ReportKeywordRest.class); //LIST Campaign level
    router.attach("/mcc/{topAccountId}/reportkeyword/adgroup/{adGroupId}", ReportKeywordRest.class); //LIST AdGroup level
    router.attach("/mcc/{topAccountId}/reportkeyword/keyword/{criterionId}", ReportKeywordRest.class); //LIST Keyword level

    // ReportCampaignNegativeKeyword
    // This one does not support dateStart and dateEnd
    router.attach("/mcc/{topAccountId}/reportcampaignnegativekeyword", ReportCampaignNegativeKeywordRest.class); //LIST All
    router.attach("/mcc/{topAccountId}/reportcampaignnegativekeyword/{accountId}",
            ReportCampaignNegativeKeywordRest.class); //LIST Account level
    router.attach("/mcc/{topAccountId}/reportcampaignnegativekeyword/campaign/{campaignId}",
            ReportCampaignNegativeKeywordRest.class); //LIST Campaign level
    router.attach("/mcc/{topAccountId}/reportcampaignnegativekeyword/keyword/{criterionId}",
            ReportCampaignNegativeKeywordRest.class); //LIST Keyword level

    // ReportAdExtension
    // ?dateStart=yyyyMMdd&dateEnd=yyyyMMdd
    router.attach("/mcc/{topAccountId}/reportadextension", ReportAdExtensionRest.class); //LIST All
    router.attach("/mcc/{topAccountId}/reportadextension/{accountId}", ReportAdExtensionRest.class); //LIST Account level
    router.attach("/mcc/{topAccountId}/reportadextension/campaign/{campaignId}", ReportAdExtensionRest.class); //LIST Campaign level
    router.attach("/mcc/{topAccountId}/reportadextension/adextension/{adExtensionId}",
            ReportAdExtensionRest.class); //LIST Keyword level

    // *** Static files *** 
    // USING FILE
    String target = "index.html";
    Redirector redirector = new Redirector(getContext(), target, Redirector.MODE_CLIENT_FOUND);
    router.attach("/", redirector);
    File currentPath = new File(RestServer.class.getProtectionDomain().getCodeSource().getLocation().getPath());
    String htmlPath = "file:///" + currentPath.getParent() + "/html/";
    router.attach("/", redirector);
    router.attach("", new Directory(getContext(), htmlPath));

    return router;
}

From source file:com.microsoft.alm.plugin.idea.git.ui.simplecheckout.SimpleCheckoutModelTest.java

@Test
public void testValidate_DestinationExists() throws IOException {
    File tempDir = Files.createTempDir();
    SimpleCheckoutModel model = modelCreationAndMocking(SimpleCheckoutModel.DEFAULT_SOURCE_PATH, GIT_URL);
    model.setDirectoryName(tempDir.getName());
    model.setParentDirectory(tempDir.getParent());
    ModelValidationInfo actualValidationInfo = model.validate();
    ModelValidationInfo expectedValidationInfo = ModelValidationInfo.createWithResource(
            SimpleCheckoutModel.PROP_DIRECTORY_NAME,
            TfPluginBundle.KEY_CHECKOUT_DIALOG_ERRORS_DESTINATION_EXISTS, tempDir.getName());
    Assert.assertEquals(expectedValidationInfo.getValidationMessage(),
            actualValidationInfo.getValidationMessage());
    Assert.assertEquals(expectedValidationInfo.getValidationSource(),
            actualValidationInfo.getValidationSource());
}