Example usage for org.apache.commons.io FilenameUtils getFullPath

List of usage examples for org.apache.commons.io FilenameUtils getFullPath

Introduction

In this page you can find the example usage for org.apache.commons.io FilenameUtils getFullPath.

Prototype

public static String getFullPath(String filename) 

Source Link

Document

Gets the full path from a full filename, which is the prefix + path.

Usage

From source file:eu.esdihumboldt.hale.io.project.jaxb.reader.ProjectParser.java

/**
 * @see AbstractIOProvider#execute(ProgressIndicator, IOReporter)
 *//*from w  w w  .  j a v  a2 s  .c  o  m*/
@Override
protected IOReport execute(ProgressIndicator progress, IOReporter reporter)
        throws IOProviderConfigurationException, IOException {
    progress.begin(Messages.ProjectParser_0, ProgressIndicator.UNKNOWN);
    try {
        File file;
        try {
            file = new File(getSource().getLocation());
        } catch (IllegalArgumentException e) {
            file = null;
        }
        String basePath = (file == null) ? (new File(".").getAbsolutePath())
                : (FilenameUtils.getFullPath(file.getAbsolutePath()));

        // Unmarshal the project file
        JAXBContext jc;
        JAXBElement<HaleProject> root;
        try {
            jc = JAXBContext.newInstance(PROJECT_CONTEXT, ObjectFactory.class.getClassLoader());
            Unmarshaller u = jc.createUnmarshaller();
            u.setEventHandler(new javax.xml.bind.helpers.DefaultValidationEventHandler());
            root = u.unmarshal(new StreamSource(getSource().getInput()), HaleProject.class);
        } catch (JAXBException e) {
            reporter.error(
                    new IOMessageImpl("Unmarshalling the HaleProject from the given resource failed: {0}", e,
                            -1, -1, getSource().getLocation()));
            reporter.setSuccess(false);
            return reporter;
        }

        project = new Project();
        projectFiles = new HashMap<String, ProjectFile>();
        report = reporter;

        HaleProject haleProject = root.getValue();

        // populate project and project files
        loadProject(haleProject);
        loadSchemas(haleProject, basePath);
        loadAlignment(haleProject, basePath);
        loadStyle(haleProject, basePath);
        loadInstances(haleProject, basePath);
        loadTasks(haleProject, basePath);
        loadConfig(haleProject);

        report = null;

        reporter.setSuccess(true);
        return reporter;
    } finally {
        progress.end();
    }
}

From source file:edu.ku.brc.af.core.db.BackupServiceFactory.java

/**
 * @param restoreName/* ww  w  .  j av  a  2 s . c  o  m*/
 * @return
 */
protected String getStatsName(final String restoreName) {
    String baseFileName = FilenameUtils.getBaseName(restoreName);
    String path = FilenameUtils.getFullPath(restoreName);
    return FilenameUtils.concat(path, baseFileName + ".stats");
}

From source file:ie.deri.unlp.javaservices.topicextraction.topicextractor.gate.TopicExtractorGate.java

/**
 * //from ww  w  . j  a  v a 2 s.c o  m
 * Extract a directory in a JAR on the classpath to an output folder.
 * 
 * Note: User's responsibility to ensure that the files are actually in a JAR.
 * 
 * @param classInJar A class in the JAR file which is on the classpath
 * @param resourceDirectory Path to resource directory in JAR
 * @param outputDirectory Directory to write to  
 * @return String containing the path to the outputDirectory
 * @throws IOException
 */
private static String extractDirectoryFromClasspathJAR(Class<?> classInJar, String resourceDirectory,
        String outputDirectory) throws IOException {

    resourceDirectory = StringUtils.strip(resourceDirectory, "\\/") + File.separator;

    URL jar = classInJar.getProtectionDomain().getCodeSource().getLocation();
    JarFile jarFile = new JarFile(new File(jar.getFile()));

    byte[] buf = new byte[1024];
    Enumeration<JarEntry> jarEntries = jarFile.entries();
    while (jarEntries.hasMoreElements()) {
        JarEntry jarEntry = jarEntries.nextElement();
        if (jarEntry.isDirectory() || !jarEntry.getName().startsWith(resourceDirectory)) {
            continue;
        }

        String outputFileName = FilenameUtils.concat(outputDirectory, jarEntry.getName());
        //Create directories if they don't exist
        new File(FilenameUtils.getFullPath(outputFileName)).mkdirs();

        //Write file
        FileOutputStream fileOutputStream = new FileOutputStream(outputFileName);
        int n;
        InputStream is = jarFile.getInputStream(jarEntry);
        while ((n = is.read(buf, 0, 1024)) > -1) {
            fileOutputStream.write(buf, 0, n);
        }
        is.close();
        fileOutputStream.close();
    }
    jarFile.close();

    String fullPath = FilenameUtils.concat(outputDirectory, resourceDirectory);
    return fullPath;
}

From source file:com.nagarro.core.util.ws.impl.AddonAwareMessageSource.java

/**
 * Formats absolute file path using basePath to format acceptable by @link ReloadableResourceBundleMessageSource}
 * Basename property//from  w  w w  .j  a v a2 s .  c o  m
 */
protected String formatPath(final String path, final String basePath) {
    int pos = path.lastIndexOf(basePath);
    //base path is not in the path -> shouldn't happen
    if (pos == -1) {
        return null;
    }

    final String pathFromBase = path.substring(pos);
    String fileName = FilenameUtils.getBaseName(pathFromBase);
    final String targetPath = FilenameUtils.getFullPath(pathFromBase);

    pos = fileName.indexOf("_");
    if (pos != -1) {
        fileName = fileName.substring(0, pos);
    }

    return FilenameUtils.concat(targetPath, fileName);
}

From source file:com.qualogy.qafe.bind.core.application.ApplicationStack.java

private void loadExternalProperties() {
    if (getGlobalConfiguration().get(Configuration.EXTERNAL_PROPERTIES_FILE) != null) {
        try {// w w w  .j  a  v a  2 s. c  o m
            File file = new File(applicationFilePath);
            String path = file.getAbsolutePath();
            path = FilenameUtils.getFullPath(path);

            loadDefaultExternalPropertiesFile(path);
            if (isNonDefaultExternalPropertiesSpecified()) {
                loadCustomExternalPropertiesFile(path);
            }

        } catch (FileNotFoundException e) {
            logger.fine(ExceptionHelper.printStackTrace(e));
            throw new LoadFailedException("Global Configuration", "The external properties file ("
                    + globalConfiguration.get(Configuration.EXTERNAL_PROPERTIES_FILE)
                    + ") could not be found (make sure it is in the same location as where the application-config.xml is)",
                    e);
        } catch (IOException e) {
            logger.fine(ExceptionHelper.printStackTrace(e));
            throw new LoadFailedException("Global Configuration", "The external properties file ("
                    + globalConfiguration.get(Configuration.EXTERNAL_PROPERTIES_FILE)
                    + ") has an I/O problem (make sure it is in the same location as where the application-config.xml is and not locked by another program)",
                    e);
        }
    }
}

From source file:com.photon.maven.plugins.android.standalonemojos.PullMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {

    parseConfiguration();/* www.  jav a 2s.  c  o m*/

    doWithDevices(new DeviceCallback() {
        public void doWithDevice(final IDevice device) throws MojoExecutionException {
            // message will be set later according to the processed files
            String message = "";
            try {
                SyncService syncService = device.getSyncService();
                FileListingService fileListingService = device.getFileListingService();

                FileEntry sourceFileEntry = getFileEntry(parsedSource, fileListingService);

                if (sourceFileEntry.isDirectory()) {
                    // pulling directory
                    File destinationDir = new File(parsedDestination);
                    if (!destinationDir.exists()) {
                        getLog().info("Creating destination directory " + destinationDir);
                        destinationDir.mkdirs();
                        destinationDir.mkdir();
                    }
                    String destinationDirPath = destinationDir.getAbsolutePath();

                    FileEntry[] fileEntries;
                    if (parsedDestination.endsWith(File.separator)) {
                        // pull source directory directly
                        fileEntries = new FileEntry[] { sourceFileEntry };
                    } else {
                        // pull the children of source directory only
                        fileEntries = fileListingService.getChildren(sourceFileEntry, true, null);
                    }

                    message = "Pull of " + parsedSource + " to " + destinationDirPath + " from ";

                    syncService.pull(fileEntries, destinationDirPath, new LogSyncProgressMonitor(getLog()));
                } else {
                    // pulling file
                    File parentDir = new File(FilenameUtils.getFullPath(parsedDestination));
                    if (!parentDir.exists()) {
                        getLog().info("Creating destination directory " + parentDir);
                        parentDir.mkdirs();
                    }

                    String destinationFileName;
                    if (parsedDestination.endsWith(File.separator)) {
                        // keep original filename
                        destinationFileName = FilenameUtils.getName(parsedSource);
                    } else {
                        // rename filename
                        destinationFileName = FilenameUtils.getName(parsedDestination);
                    }

                    File destinationFile = new File(parentDir, destinationFileName);
                    String destionationFilePath = destinationFile.getAbsolutePath();

                    message = "Pull of " + parsedSource + " to " + destionationFilePath + " from ";

                    syncService.pullFile(sourceFileEntry, destionationFilePath,
                            new LogSyncProgressMonitor(getLog()));
                }

                getLog().info(message + device.getSerialNumber() + " (avdName=" + device.getAvdName()
                        + ") successful.");
            } catch (SyncException e) {
                throw new MojoExecutionException(
                        message + device.getSerialNumber() + " (avdName=" + device.getAvdName() + ") failed.",
                        e);
            } catch (IOException e) {
                throw new MojoExecutionException(
                        message + device.getSerialNumber() + " (avdName=" + device.getAvdName() + ") failed.",
                        e);
            } catch (TimeoutException e) {
                throw new MojoExecutionException(
                        message + device.getSerialNumber() + " (avdName=" + device.getAvdName() + ") failed.",
                        e);
            } catch (AdbCommandRejectedException e) {
                throw new MojoExecutionException(
                        message + device.getSerialNumber() + " (avdName=" + device.getAvdName() + ") failed.",
                        e);
            }
        }
    });

}

From source file:com.jayway.maven.plugins.android.standalonemojos.PullMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {

    ConfigHandler configHandler = new ConfigHandler(this, this.session, this.execution);
    configHandler.parseConfiguration();//from  w w  w. j av  a 2  s  .  c  o  m

    doWithDevices(new DeviceCallback() {
        public void doWithDevice(final IDevice device) throws MojoExecutionException {
            String deviceLogLinePrefix = DeviceHelper.getDeviceLogLinePrefix(device);

            // message will be set later according to the processed files
            String message = "";
            try {
                SyncService syncService = device.getSyncService();
                FileListingService fileListingService = device.getFileListingService();

                FileEntry sourceFileEntry = getFileEntry(parsedSource, fileListingService);

                if (sourceFileEntry.isDirectory()) {
                    // pulling directory
                    File destinationDir = new File(parsedDestination);
                    if (!destinationDir.exists()) {
                        getLog().info("Creating destination directory " + destinationDir);
                        destinationDir.mkdirs();
                        destinationDir.mkdir();
                    }
                    String destinationDirPath = destinationDir.getAbsolutePath();

                    FileEntry[] fileEntries;
                    if (parsedDestination.endsWith(File.separator)) {
                        // pull source directory directly
                        fileEntries = new FileEntry[] { sourceFileEntry };
                    } else {
                        // pull the children of source directory only
                        fileEntries = fileListingService.getChildren(sourceFileEntry, true, null);
                    }

                    message = deviceLogLinePrefix + "Pull of " + parsedSource + " to " + destinationDirPath
                            + " from ";

                    syncService.pull(fileEntries, destinationDirPath, new LogSyncProgressMonitor(getLog()));
                } else {
                    // pulling file
                    File parentDir = new File(FilenameUtils.getFullPath(parsedDestination));
                    if (!parentDir.exists()) {
                        getLog().info(deviceLogLinePrefix + "Creating destination directory " + parentDir);
                        parentDir.mkdirs();
                    }

                    String destinationFileName;
                    if (parsedDestination.endsWith(File.separator)) {
                        // keep original filename
                        destinationFileName = FilenameUtils.getName(parsedSource);
                    } else {
                        // rename filename
                        destinationFileName = FilenameUtils.getName(parsedDestination);
                    }

                    File destinationFile = new File(parentDir, destinationFileName);
                    String destinationFilePath = destinationFile.getAbsolutePath();
                    message = deviceLogLinePrefix + "Pull of " + parsedSource + " to " + destinationFilePath
                            + " from " + DeviceHelper.getDescriptiveName(device);

                    syncService.pullFile(sourceFileEntry, destinationFilePath,
                            new LogSyncProgressMonitor(getLog()));
                }

                getLog().info(message + " successful.");
            } catch (SyncException e) {
                throw new MojoExecutionException(message + " failed.", e);
            } catch (IOException e) {
                throw new MojoExecutionException(message + " failed.", e);
            } catch (TimeoutException e) {
                throw new MojoExecutionException(message + " failed.", e);
            } catch (AdbCommandRejectedException e) {
                throw new MojoExecutionException(message + " failed.", e);
            }
        }
    });
}

From source file:de.uzk.hki.da.grid.IrodsGridFacade.java

@Override
public boolean storagePolicyAchieved(String gridPath2, StoragePolicy sp, String checksum, Set<Node> cnodes) {
    irodsSystemConnector.establishConnect();

    String gridPath = "/" + irodsSystemConnector.getZone() + "/" + WorkArea.AIP + "/" + gridPath2;

    int minNodes = sp.getMinNodes();
    if (minNodes == 0) {
        logger.error("Given minnodes setting 0 violates long term preservation");
        return false;
    }// w  w  w  . ja  va 2  s  .  c o  m
    try {
        logger.debug("checking StoragePolicy achieved for " + gridPath);
        List<String> targetResgroups = Arrays.asList(sp.getReplDestinations().split(","));
        int replicasTotal = 0;
        for (String targetResgroup : targetResgroups) {
            int replicas = 0;
            String res = targetResgroup;
            if (targetResgroup.startsWith("cp_"))
                res = targetResgroup.substring(3);
            replicas = irodsSystemConnector.getNumberOfReplsForDataObjectInResGroup(
                    FilenameUtils.getFullPath(gridPath), FilenameUtils.getName(gridPath), res);
            if (targetResgroup.startsWith("cp_") && replicas > 1)
                replicas--;
            replicasTotal = replicasTotal + replicas;
        }
        logger.debug("Number of Total Replications on LZA Nodes is now (" + replicasTotal
                + "). Total Checked Ressources " + targetResgroups.size() + " Has to exist on (" + minNodes
                + ")");

        if (replicasTotal >= minNodes) {
            irodsSystemConnector.saveOrUpdateAVUMetadataDataObject(gridPath, "replicated", "1");
            irodsSystemConnector.saveOrUpdateAVUMetadataDataObject(gridPath, "min_repls",
                    String.valueOf(minNodes));
            irodsSystemConnector.logoff();
            return true;
        } else {
            irodsSystemConnector.saveOrUpdateAVUMetadataDataObject(gridPath, "replicated", "0");
        }
        irodsSystemConnector.logoff();
        return false;

    } catch (IrodsRuntimeException e) {
        logger.error("Failure acquiring repl status of " + gridPath);
        irodsSystemConnector.logoff();
    }
    return false;
}

From source file:edu.ur.ir.ir_export.service.DefaultCollectionExportService.java

/**
 * Export all collections in the repository.
 * //from w ww  .  ja  v  a2  s . c om
 * @param repository - repository to export
 * @throws IOException 
 */
public void export(Repository repository, File zipFileDestination) throws IOException {
    // create the path if it doesn't exist
    String path = FilenameUtils.getPath(zipFileDestination.getCanonicalPath());
    if (!path.equals("")) {
        File pathOnly = new File(FilenameUtils.getFullPath(zipFileDestination.getCanonicalPath()));
        FileUtils.forceMkdir(pathOnly);
    }

    File collectionXmlFile = temporaryFileCreator.createTemporaryFile(extension);
    Set<FileInfo> allPictures = createXmlFile(collectionXmlFile, repository.getInstitutionalCollections(),
            true);

    FileOutputStream out = new FileOutputStream(zipFileDestination);
    ArchiveOutputStream os = null;
    try {
        os = new ArchiveStreamFactory().createArchiveOutputStream("zip", out);
        os.putArchiveEntry(new ZipArchiveEntry("collection.xml"));

        FileInputStream fis = null;
        try {
            log.debug("adding xml file");
            fis = new FileInputStream(collectionXmlFile);
            IOUtils.copy(fis, os);
        } finally {
            if (fis != null) {
                fis.close();
                fis = null;
            }
        }

        log.debug("adding pictures size " + allPictures.size());
        for (FileInfo fileInfo : allPictures) {
            File f = new File(fileInfo.getFullPath());
            String name = FilenameUtils.getName(fileInfo.getFullPath());
            name = name + '.' + fileInfo.getExtension();
            log.debug(" adding name " + name);
            os.putArchiveEntry(new ZipArchiveEntry(name));
            try {
                log.debug("adding input stream");
                fis = new FileInputStream(f);
                IOUtils.copy(fis, os);
            } finally {
                if (fis != null) {
                    fis.close();
                    fis = null;
                }
            }
        }

        os.closeArchiveEntry();
        out.flush();
    } catch (ArchiveException e) {
        throw new IOException(e);
    } finally {
        if (os != null) {
            os.close();
            os = null;
        }
    }

    FileUtils.deleteQuietly(collectionXmlFile);

}

From source file:com.enioka.jqm.tools.JqmEngine.java

/**
 * Starts the engine//from  w  ww  . ja  v a  2 s .c o m
 * 
 * @param nodeName
 *            the name of the node to start, as in the NODE table of the database.
 * @throws JqmInitError
 */
void start(String nodeName) {
    if (nodeName == null || nodeName.isEmpty()) {
        throw new IllegalArgumentException("nodeName cannot be null or empty");
    }

    // Set thread name - used in audits
    Thread.currentThread().setName("JQM engine;;" + nodeName);
    Helpers.setLogFileName(nodeName);

    // Log: we are starting...
    jqmlogger.info("JQM engine version " + this.getVersion() + " for node " + nodeName + " is starting");
    jqmlogger.info("Java version is " + System.getProperty("java.version") + ". JVM was made by "
            + System.getProperty("java.vendor") + " as " + System.getProperty("java.vm.name") + " version "
            + System.getProperty("java.vm.version"));

    // JNDI first - the engine itself uses JNDI to fetch its connections!
    Helpers.registerJndiIfNeeded();

    // Database connection
    EntityManager em = Helpers.getNewEm();

    // Node configuration is in the database
    node = em.createQuery("SELECT n FROM Node n WHERE n.name = :l", Node.class).setParameter("l", nodeName)
            .getSingleResult();

    // Check if double-start
    long toWait = (long) (1.1 * Long.parseLong(Helpers.getParameter("internalPollingPeriodMs", "60000", em)));
    if (node.getLastSeenAlive() != null
            && Calendar.getInstance().getTimeInMillis() - node.getLastSeenAlive().getTimeInMillis() <= toWait) {
        long r = Calendar.getInstance().getTimeInMillis() - node.getLastSeenAlive().getTimeInMillis();
        throw new JqmInitErrorTooSoon("Another engine named " + nodeName + " was running less than " + r / 1000
                + " seconds ago. Either stop the other node, or if it already stopped, please wait "
                + (toWait - r) / 1000 + " seconds");
    }

    // Prevent very quick multiple starts by immediately setting the keep-alive
    em.getTransaction().begin();
    node.setLastSeenAlive(Calendar.getInstance());
    em.getTransaction().commit();

    // Only start if the node configuration seems OK
    Helpers.checkConfiguration(nodeName, em);

    // Log parameters
    Helpers.dumpParameters(em, node);

    // Log level
    Helpers.setLogLevel(node.getRootLogLevel());

    // Log multicasting (& log4j stdout redirect)
    GlobalParameter gp1 = em
            .createQuery("SELECT g FROM GlobalParameter g WHERE g.key = :k", GlobalParameter.class)
            .setParameter("k", "logFilePerLaunch").getSingleResult();
    if ("true".equals(gp1.getValue()) || "both".equals(gp1.getValue())) {
        RollingFileAppender a = (RollingFileAppender) Logger.getRootLogger().getAppender("rollingfile");
        MultiplexPrintStream s = new MultiplexPrintStream(System.out, FilenameUtils.getFullPath(a.getFile()),
                "both".equals(gp1.getValue()));
        System.setOut(s);
        ((ConsoleAppender) Logger.getRootLogger().getAppender("consoleAppender"))
                .setWriter(new OutputStreamWriter(s));
        s = new MultiplexPrintStream(System.err, FilenameUtils.getFullPath(a.getFile()),
                "both".equals(gp1.getValue()));
        System.setErr(s);
    }

    // Remote JMX server
    if (node.getJmxRegistryPort() != null && node.getJmxServerPort() != null && node.getJmxRegistryPort() > 0
            && node.getJmxServerPort() > 0) {
        JmxAgent.registerAgent(node.getJmxRegistryPort(), node.getJmxServerPort(), node.getDns());
    } else {
        jqmlogger.info(
                "JMX remote listener will not be started as JMX registry port and JMX server port parameters are not both defined");
    }

    // Jetty
    this.server = new JettyServer();
    this.server.start(node, em);

    // JMX
    if (node.getJmxServerPort() != null && node.getJmxServerPort() > 0) {
        try {
            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
            name = new ObjectName("com.enioka.jqm:type=Node,name=" + this.node.getName());
            mbs.registerMBean(this, name);
        } catch (Exception e) {
            throw new JqmInitError("Could not create JMX beans", e);
        }
        jqmlogger.info("JMX management bean for the engine was registered");
    } else {
        loadJmxBeans = false;
        jqmlogger.info("JMX management beans will not be loaded as JMX server port is null or zero");
    }

    // Security
    if (System.getSecurityManager() == null) {
        System.setSecurityManager(new SecurityManagerPayload());
    }
    jqmlogger.info("Security manager was registered");

    // Cleanup
    purgeDeadJobInstances(em, this.node);

    // Force Message EMF load
    em.createQuery("SELECT m FROM Message m WHERE 1=0", Message.class).getResultList();

    // Pollers
    syncPollers(em, this.node);
    jqmlogger.info("All required queues are now polled");

    // Internal poller (stop notifications, keepalive)
    intPoller = new InternalPoller(this);
    Thread t = new Thread(intPoller);
    t.start();

    // Kill notifications
    killHook = new SignalHandler(this);
    Runtime.getRuntime().addShutdownHook(killHook);

    // Done
    em.close();
    em = null;
    latestNodeStartedName = node.getName();
    jqmlogger.info("End of JQM engine initialization");
}