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.zimbra.cs.service.util.ItemDataFile.java

public static void extract(InputStream is, boolean meta, Set<MailItem.Type> types, String cset, String dir)
        throws IOException {
    byte[] buf = new byte[TarBuffer.DEFAULT_BLKSIZE];
    TarEntry te;//from  w w w.jav  a 2s.com
    TarInputStream tis = new TarInputStream(new GZIPInputStream(is), cset == null ? "UTF-8" : cset);

    if (dir == null)
        dir = ".";
    try {
        while ((te = tis.getNextEntry()) != null) {
            if (skip(types, MailItem.Type.of((byte) te.getMajorDeviceId()))) {
                continue;
            }

            File f = new File(dir + File.separator + te.getName());
            FileOutputStream out;

            if (!f.getParent().equals("."))
                f.getParentFile().mkdir();
            if (te.getName().endsWith(".meta")) {
                if (!meta)
                    continue;
                System.out.println(f);
                out = new FileOutputStream(f);
                ItemData id = new ItemData(getData(tis, te));
                out.write(id.encode(2).getBytes("UTF-8"));
            } else {
                int in;

                System.out.println(f);
                out = new FileOutputStream(f);
                while ((in = tis.read(buf)) != -1)
                    out.write(buf, 0, in);
            }
            out.close();
            f.setLastModified(te.getModTime().getTime());
        }
    } finally {
        tis.close();
    }
}

From source file:com.adito.agent.client.ProxyUtil.java

private static boolean checkProfileActive(File prefsJS) {
    String parentFile = prefsJS.getParent();
    File lockFile = new File(parentFile, "parent.lock");
    if (lockFile.exists()) {
        return true;
    } else {/*  w  w  w.j ava  2  s. c  o  m*/
        return false;
    }

}

From source file:com.germinus.easyconf.FileUtil.java

public static void write(File file, String s) throws IOException {
    if (file.getParent() != null) {
        mkdirs(file.getParent());/*from  w ww .  j  a  v  a 2s . c o  m*/
    }

    BufferedWriter bw = new BufferedWriter(new FileWriter(file));

    bw.flush();
    bw.write(s);
    bw.flush();

    bw.close();
}

From source file:gabi.FileUploadServlet.java

private static void unzip(String zipFilePath, String destDir) {
    File dir = new File(destDir);
    // create output directory if it doesn't exist
    if (!dir.exists())
        dir.mkdirs();// ww w.j ava2  s.  c  o m
    FileInputStream fis;
    //buffer for read and write data to file
    byte[] buffer = new byte[1024];
    try {
        fis = new FileInputStream(zipFilePath);
        ZipInputStream zis = new ZipInputStream(fis);
        ZipEntry ze = zis.getNextEntry();
        while (ze != null) {
            String fileName = ze.getName();
            File newFile = new File(destDir + File.separator + fileName);
            System.out.println("Unzipping to " + newFile.getAbsolutePath());
            //create directories for sub directories in zip
            new File(newFile.getParent()).mkdirs();
            FileOutputStream fos = new FileOutputStream(newFile);
            int len;
            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fos.close();
            //close this ZipEntry
            zis.closeEntry();
            ze = zis.getNextEntry();
        }
        //close last ZipEntry
        zis.closeEntry();
        zis.close();
        fis.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:org.ala.spatial.web.services.DownloadController.java

private static void fixAlocFiles(String pid, File dir) {
    try {/*  ww  w . j a v  a  2  s .c  o  m*/
        File tmpdir = new File(dir.getParent() + "/temp/" + pid);
        //FileCopyUtils.copy(new FileInputStream(dir), new FileOutputStream(tmpdir));
        FileUtils.copyDirectory(dir, tmpdir);

        //File grd = new File(tmpdir.getAbsolutePath() + "/" + pid + ".grd");
        //File grdnew = new File(tmpdir.getAbsolutePath() + "/classfication.grd");

        //File gri = new File(tmpdir.getAbsolutePath() + "/" + pid + ".gri");
        //File grinew = new File(tmpdir.getAbsolutePath() + "/classfication.gri");

        File asc = new File(tmpdir.getAbsolutePath() + "/" + pid + ".asc");
        File ascnew = new File(tmpdir.getAbsolutePath() + "/classfication.asc");

        File prj = new File(tmpdir.getAbsolutePath() + "/" + pid + ".prj");
        File prjnew = new File(tmpdir.getAbsolutePath() + "/classfication.prj");

        File png = new File(tmpdir.getAbsolutePath() + "/aloc.png");
        File pngnew = new File(tmpdir.getAbsolutePath() + "/classfication.png");

        File pgw = new File(tmpdir.getAbsolutePath() + "/aloc.pgw");
        File pgwnew = new File(tmpdir.getAbsolutePath() + "/classfication.pgw");

        File log = new File(tmpdir.getAbsolutePath() + "/aloc.log");
        File lognew = new File(tmpdir.getAbsolutePath() + "/classfication.log");

        //grd.renameTo(grdnew);
        //gri.renameTo(grinew);
        asc.renameTo(ascnew);
        prj.renameTo(prjnew);
        png.renameTo(pngnew);
        pgw.renameTo(pgwnew);
        log.renameTo(lognew);

        (new File(tmpdir.getAbsolutePath() + "/" + pid + ".asc.zip")).delete();
        (new File(tmpdir.getAbsolutePath() + "/" + pid + ".sld")).delete();
        (new File(tmpdir.getAbsolutePath() + "/aloc.pngextents.txt")).delete();
        (new File(tmpdir.getAbsolutePath() + "/aloc.prj")).delete();
        (new File(tmpdir.getAbsolutePath() + "/t_aloc.tif")).delete();
        (new File(tmpdir.getAbsolutePath() + "/t_aloc.png")).delete();
        (new File(tmpdir.getAbsolutePath() + "/" + pid + ".grd")).delete();
        (new File(tmpdir.getAbsolutePath() + "/" + pid + ".gri")).delete();

    } catch (Exception e) {
        System.out.println("Unable to fix Classification files");
        e.printStackTrace(System.out);
    }
}

From source file:com.openkm.module.db.stuff.FsDataStore.java

/**
 * Purge data store file/*from  w  w  w . j  ava 2  s . c  o m*/
 */
public static void delete(String uuid) throws IOException {
    log.debug("delete({})", uuid);
    File fs = resolveFile(uuid);

    if (!fs.delete()) {
        if (fs.exists()) {
            throw new IOException(
                    "Can't delete file (locked) '" + fs.getParent() + File.separator + uuid + "'");
        } else {
            throw new IOException(
                    "Cant' delete file (not exists) '" + fs.getParent() + File.separator + uuid + "'");
        }
    }
}

From source file:dynamicrefactoring.domain.xml.ExportImportUtilities.java

/**
 * Se encarga del proceso de importacin de una refactorizacin dinmica.
 * /*  ww  w  .  j a  v a 2s. c o m*/
 * @param definition
 *            ruta del fichero con la definicin de la refactorizacin.
 * @param importingFromPlan
 *            indica si la importacin de la refactorizacin ha sido
 *            solicitada cuando se importaba un plan de refactorizaciones.
 * @param catalog
 *            catlogo de refactorizaciones
 * @throws IOException
 *             IOException en caso de fallo al copiar la carpeta
 * @throws XMLRefactoringReaderException
 *             XMLRefactoringReaderException
 */
public static void importRefactoring(String definition, boolean importingFromPlan, RefactoringsCatalog catalog)
        throws IOException, XMLRefactoringReaderException {
    File definitionFile = new File(definition);
    final String originalFolder = definitionFile.getParent();
    String namefolder = definitionFile.getParentFile().getName();

    DynamicRefactoringDefinition refact = new JDOMXMLRefactoringReaderImp()
            .getDynamicRefactoringDefinition(new File(definition));
    DynamicRefactoringDefinition newRefactToImport = modifyRefactToImportIt(definitionFile, refact);

    // Pasamos a copiar los .class de las precondiciones, postcondiciones
    // y acciones en su lugar
    for (RefactoringMechanismInstance predicado : refact.getAllMechanisms()) {
        copyRefactoringFileClassIfNeeded(importingFromPlan, originalFolder, PluginStringUtils
                .getMechanismFullyQualifiedName(predicado.getType(), predicado.getClassName()));
    }

    if (catalog.hasRefactoring(newRefactToImport.getName())) {
        catalog.updateRefactoring(newRefactToImport.getName(), newRefactToImport);
    } else {
        catalog.addRefactoring(newRefactToImport);
    }

    if (importingFromPlan) {
        FileManager.emptyDirectories(RefactoringPlugin.getDynamicRefactoringsDir() + File.separatorChar
                + namefolder + File.separatorChar + "repository");
        FileManager.deleteDirectories(RefactoringPlugin.getDynamicRefactoringsDir() + File.separatorChar
                + namefolder + File.separatorChar + "repository", true);

    }
}

From source file:net.sourceforge.dita4publishers.tools.dxp.DitaDxpHelper.java

/**
 * @param zipFile//from  w ww. ja  v a  2 s . co  m
 * @param dxpOptions 
 * @return
 * @throws DitaDxpException 
 */
public static ZipEntry getDxpPackageRootMap(ZipFile zipFile, MapBosProcessorOptions dxpOptions)
        throws DitaDxpException {

    List<ZipEntry> candidateRootEntries = new ArrayList<ZipEntry>();
    List<ZipEntry> candidateDirs = new ArrayList<ZipEntry>();

    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        File temp = new File(entry.getName());
        String parentPath = temp.getParent();
        if (entry.isDirectory()) {
            if (parentPath == null || "".equals(parentPath)) {
                candidateDirs.add(entry);
            }
        } else {
            if (entry.getName().equals("dita_dxp_manifest.ditamap")) {
                return entry;
            }
            if (entry.getName().endsWith(".ditamap")) {
                if (parentPath == null || "".equals(parentPath)) {
                    candidateRootEntries.add(entry);
                }
            }
        }
    }

    // If we get here then we didn't find a manifest map, so look for
    // root map.

    // If exactly one map at the top level, must be the root map of the package.
    if (candidateRootEntries.size() == 1) {
        if (!dxpOptions.isQuiet())
            log.info("Using root map " + candidateRootEntries.get(0).getName());
        return candidateRootEntries.get(0);
    }

    // If there is more than one top-level dir, thank you for playing:

    if (candidateRootEntries.size() == 0 & candidateDirs.size() > 1) {
        throw new DitaDxpException(
                "No manifest map, no map in root of package, and more than one top-level directory in package.");
    }

    // If there is exactly one root directory, look in it for exactly one map:
    if (candidateDirs.size() == 1) {
        String parentPath = candidateDirs.get(0).getName();
        entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            File temp = new File(entry.getName());
            String entryParent = temp.getParent();
            if (entryParent == null)
                entryParent = "/";
            else
                entryParent += "/";
            if (parentPath.equals(entryParent) && entry.getName().endsWith(".ditamap")) {
                candidateRootEntries.add(entry);
            }
        }
        if (candidateRootEntries.size() == 1) {
            // Must be the root map
            if (!dxpOptions.isQuiet())
                log.info("Using root map " + candidateRootEntries.get(0).getName());
            return candidateRootEntries.get(0);
        }
        if (candidateRootEntries.size() > 1) {
            throw new DitaDxpException(
                    "No manifest map and found more than one map in the root directory of the package.");
        }
    }

    // Should never get here:

    throw new DitaDxpException("Unable to find package manifest map or single root map in DXP package.");

}

From source file:is.landsbokasafn.deduplicator.indexer.IndexingLauncher.java

private static void loadConfiguration() {
    // Load properties file, either from heritrix.home/conf or
    // path specified via -Ddeduplicator.config JVM option
    String configFilename = System.getProperty("deduplicator.config");
    if (configFilename == null || configFilename.isEmpty()) {
        // Configuration file not explicitly set. Use default.
        // This works if invoked via the provided script. Will fail otherwise unless -Ddeduplicator.home is set
        configFilename = System.getProperty("deduplicator.home") + File.separator + "conf" + File.separator
                + "deduplicator.properties";
    }//from www  .  j a  v a 2  s. c  o  m
    File configFile = new File(configFilename);
    if (configFile.exists() == false) {
        System.out.println("Unable to find configuration file " + configFilename);
        System.exit(1);
    }

    // Load log4j config, assumes same path as config file
    String log4jconfig = configFile.getParent() + File.separator + "deduplicator-log4j.properties";
    PropertyConfigurator.configure(log4jconfig);

    // Copy properties from config file to System properties
    try {
        System.getProperties().load(new FileReader(configFile));
    } catch (IOException e) {
        System.err.println("Unable to read configuration file");
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:net.sourceforge.dita4publishers.tools.dxp.DitaDxpHelper.java

/**
 * Given a DITA map bounded object set, zips it up into a DXP Zip package.
 * @param mapBos/*from   w  w  w. j ava  2s.  c om*/
 * @param outputZipFile
 * @throws Exception 
 */
public static void zipMapBos(DitaBoundedObjectSet mapBos, File outputZipFile, MapBosProcessorOptions options)
        throws Exception {
    /*
     *  Some potential complexities:
     *  
     *  - DXP package spec requires either a map manifest or that 
     *  there be exactly one map at the root of the zip package. This 
     *  means that the file structure of the BOS needs to be checked to
     *  see if the files already conform to this structure and, if not,
     *  they need to be reorganized and have pointers rewritten if a 
     *  map manifest has not been requested.
     *  
     *  - If the file structure of the original data includes files not
     *  below the root map, the file organization must be reworked whether
     *  or not a map manifest has been requested.
     *  
     *  - Need to generate DXP map manifest if a manifest is requested.
     *  
     *  - If user has requested that the original file structure be 
     *  remembered, a manifest must be generated.
     */

    log.debug("Determining zip file organization...");

    BosVisitor visitor = new DxpFileOrganizingBosVisitor();
    visitor.visit(mapBos);

    if (!options.isQuiet())
        log.info("Creating DXP package \"" + outputZipFile.getAbsolutePath() + "\"...");
    OutputStream outStream = new FileOutputStream(outputZipFile);
    ZipOutputStream zipOutStream = new ZipOutputStream(outStream);

    ZipEntry entry = null;

    // At this point, URIs of all members should reflect their
    // storage location within the resulting DXP package. There
    // must also be a root map, either the original map
    // we started with or a DXP manifest map.

    URI rootMapUri = mapBos.getRoot().getEffectiveUri();
    URI baseUri = null;
    try {
        baseUri = AddressingUtil.getParent(rootMapUri);
    } catch (URISyntaxException e) {
        throw new BosException("URI syntax exception getting parent URI: " + e.getMessage());
    }

    Set<String> dirs = new HashSet<String>();

    if (!options.isQuiet())
        log.info("Constructing DXP package...");
    for (BosMember member : mapBos.getMembers()) {
        if (!options.isQuiet())
            log.info("Adding member " + member + " to zip...");
        URI relativeUri = baseUri.relativize(member.getEffectiveUri());
        File temp = new File(relativeUri.getPath());
        String parentPath = temp.getParent();
        if (parentPath != null && !"".equals(parentPath) && !parentPath.endsWith("/")) {
            parentPath += "/";
        }
        log.debug("parentPath=\"" + parentPath + "\"");
        if (!"".equals(parentPath) && parentPath != null && !dirs.contains(parentPath)) {
            entry = new ZipEntry(parentPath);
            zipOutStream.putNextEntry(entry);
            zipOutStream.closeEntry();
            dirs.add(parentPath);
        }
        entry = new ZipEntry(relativeUri.getPath());
        zipOutStream.putNextEntry(entry);
        IOUtils.copy(member.getInputStream(), zipOutStream);
        zipOutStream.closeEntry();
    }

    zipOutStream.close();
    if (!options.isQuiet())
        log.info("DXP package \"" + outputZipFile.getAbsolutePath() + "\" created.");
}