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

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

Introduction

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

Prototype

public static String getPath(String filename) 

Source Link

Document

Gets the path from a full filename, which excludes the prefix.

Usage

From source file:org.geoserver.csw.DownloadLinkHandler.java

/**
 * Return a SHA-1 based hash for the specified file, by appending the file's base name to the hashed full path. This allows to hide the underlying
 * file system structure./*  w  w w .j a  v  a2  s.  c  om*/
 */
public static String hashFile(File mainFile) throws IOException, NoSuchAlgorithmException {
    String canonicalPath = mainFile.getCanonicalPath();
    String mainFilePath = FilenameUtils.getPath(canonicalPath);

    MessageDigest md = MessageDigest.getInstance("SHA-1");
    md.update(mainFilePath.getBytes());
    return Hex.encodeHexString(md.digest()) + "-" + mainFile.getName();
}

From source file:org.jasig.resourceserver.utils.aggr.ResourcesElementsProviderImpl.java

/**
 * Build XML {@link DocumentFragment} of link and script tags for the specified skin file 
 *///  w  w  w . ja  v  a2  s  .  co m
protected DocumentFragment getResourcesXml(HttpServletRequest request, String skinXml) {
    final Included includedType = this.getIncludedType(request);

    DocumentFragment headFragment;
    if (Included.AGGREGATED == includedType) {
        headFragment = this.xmlResourcesCache.get(skinXml);
        if (headFragment != null) {
            return headFragment;
        }
    }

    final Resources skinResources = this.getResources(request, skinXml);
    if (skinResources == null) {
        logger.warn("Could not find skin file " + skinXml);
        return null;
    }

    final Document doc = this.documentBuilder.newDocument();
    headFragment = doc.createDocumentFragment();

    final String relativeRoot = request.getContextPath() + "/" + FilenameUtils.getPath(skinXml);
    for (final Css css : skinResources.getCss()) {
        appendCssNode(request, doc, headFragment, css, relativeRoot);
    }
    for (final Js js : skinResources.getJs()) {
        appendJsNode(request, doc, headFragment, js, relativeRoot);
    }

    if (Included.AGGREGATED == includedType) {
        this.xmlResourcesCache.put(skinXml, headFragment);
    }
    return headFragment;
}

From source file:org.javabeanstack.io.IOUtil.java

/**
 * Devuelve el path de un archivo ejemplo c:/carpeta1/subcarpeta1/archivo.txt
 * retorna /carpeta1/subcarpeta1/// ww  w  . j a  v a2s. c om
 * @param file nombre y path del archivo
 * @return el path del archivo
 */
public static String getPath(String file) {
    return FilenameUtils.getPath(file);
}

From source file:org.jenkinsci.plugins.skytap.SkytapUtils.java

/**
 * Prepends the workspace path to a save file name as a default if user has
 * not provided a full path.//from  w w w. ja  v  a2 s.com
 * 
 * @param build
 * @param savefile
 * 
 * @return fullpath
 * 
 */
public static String convertFileNameToFullPath(AbstractBuild build, String savefile) {

    FilenameUtils fu = new FilenameUtils();

    // if its just a filename with no path, prepend workspace dir

    if (fu.getPath(savefile).equals("")) {
        JenkinsLogger.log(
                "File: " + savefile + " was specified without a path. Defaulting path to Jenkins workspace.");
        String workspacePath = SkytapUtils.expandEnvVars(build, "${WORKSPACE}");

        savefile = workspacePath + "/" + savefile;
        savefile = fu.separatorsToSystem(savefile);
        return savefile;

    } else {
        return fu.separatorsToSystem(savefile);
    }

}

From source file:org.kitodo.production.metadata.MetadataProcessor.java

/**
 * Checks and returns whether access is granted to the image with the given
 * filepath "imagePath".//  w  w w.  j  a  v a 2  s . co  m
 *
 * @param imagePath
 *            the filepath of the image for which access rights are checked
 * @return true if access is granted and false otherwise
 */
public boolean isAccessGranted(String imagePath) {
    String imageName = FilenameUtils.getName(imagePath);
    String filePath;
    if (FilenameUtils.getPath(imagePath).endsWith(FULLSIZE_FOLDER_NAME + "/")) {
        filePath = fullsizePath + imageName;
    } else if (FilenameUtils.getPath(imagePath).endsWith(THUMBNAIL_FOLDER_NAME + "/")) {
        filePath = thumbnailPath + imageName;
    } else {
        logger.error("ERROR: Image path '" + imagePath + "' is invalid!");
        return false;
    }
    File image = new File(filePath);
    return image.canRead();
}

From source file:org.lightjason.examples.pokemon.CConfiguration.java

/**
 * loads the configuration from a file/*from  w w  w  .j a  va  2  s  . c o  m*/
 *
 * @param p_input YAML configuration file
 * @return instance
 *
 * @throws IOException on io errors
 * @throws URISyntaxException on URI syntax error
 */
@SuppressWarnings("unchecked")
public final CConfiguration load(final String p_input) throws IOException, URISyntaxException {
    final URL l_path = CCommon.getResourceURL(p_input);

    // read configuration
    final Map<String, Object> l_data = (Map<String, Object>) new Yaml().load(l_path.openStream());
    m_configurationpath = FilenameUtils.getPath(l_path.toString());

    // get initial values
    m_stacktrace = (boolean) l_data.getOrDefault("stacktrace", false);
    m_threadsleeptime = (int) l_data.getOrDefault("threadsleeptime", 0);
    m_simulationstep = (int) l_data.getOrDefault("steps", Integer.MAX_VALUE);
    if (!(boolean) l_data.getOrDefault("logging", false))
        LogManager.getLogManager().reset();

    m_windowweight = ((Map<String, Integer>) l_data.getOrDefault("window",
            Collections.<String, Integer>emptyMap())).getOrDefault("weight", 800);
    m_windowheight = ((Map<String, Integer>) l_data.getOrDefault("window",
            Collections.<String, Integer>emptyMap())).getOrDefault("height", 600);
    m_zoomspeed = ((Map<String, Integer>) l_data.getOrDefault("window",
            Collections.<String, Integer>emptyMap())).getOrDefault("zoomspeed", 2) / 100f;
    m_zoomspeed = m_zoomspeed <= 0 ? 0.02f : m_zoomspeed;
    m_dragspeed = ((Map<String, Integer>) l_data.getOrDefault("window",
            Collections.<String, Integer>emptyMap())).getOrDefault("dragspeed", 100) / 1000f;
    m_dragspeed = m_dragspeed <= 0 ? 1f : m_dragspeed;

    m_screenshot = new ImmutableTriple<>(
            (String) ((Map<String, Object>) l_data.getOrDefault("screenshot",
                    Collections.<String, Integer>emptyMap())).getOrDefault("file", ""),
            (String) ((Map<String, Object>) l_data.getOrDefault("screenshot",
                    Collections.<String, Integer>emptyMap())).getOrDefault("format", ""),
            (Integer) ((Map<String, Object>) l_data.getOrDefault("screenshot",
                    Collections.<String, Integer>emptyMap())).getOrDefault("step", -1));

    // create static objects - static object are needed by the environment
    final List<IItem> l_static = new LinkedList<>();
    this.createStatic((List<Map<String, Object>>) l_data.getOrDefault("element",
            Collections.<Map<String, Object>>emptyList()), l_static);
    m_staticelements = Collections.unmodifiableList(l_static);

    // create environment - static items must be exists
    m_environment = new CEnvironment(
            (Integer) ((Map<String, Object>) l_data.getOrDefault("environment",
                    Collections.<String, Integer>emptyMap())).getOrDefault("rows", -1),
            (Integer) ((Map<String, Object>) l_data.getOrDefault("environment",
                    Collections.<String, Integer>emptyMap())).getOrDefault("columns", -1),
            (Integer) ((Map<String, Object>) l_data.getOrDefault("environment",
                    Collections.<String, Integer>emptyMap())).getOrDefault("cellsize", -1),
            ERoutingFactory.valueOf(((String) ((Map<String, Object>) l_data.getOrDefault("environment",
                    Collections.<String, Integer>emptyMap())).getOrDefault("routing", "")).trim().toUpperCase())
                    .get(),
            m_staticelements);

    // create executable object list and check number of elements - environment must be exists
    final List<IAgent> l_agents = new LinkedList<>();
    this.createAgent((Map<String, Object>) l_data.getOrDefault("agent", Collections.<String, Object>emptyMap()),
            l_agents, (boolean) l_data.getOrDefault("agentprint", true));
    m_agents = Collections.unmodifiableList(l_agents);

    if (m_agents.size() + m_staticelements.size() > m_environment.column() * m_environment.row() / 2)
        throw new IllegalArgumentException(MessageFormat.format(
                "number of simulation elements are very large [{0}], so the environment size is too small, the environment "
                        + "[{1}x{2}] must define a number of cells which is greater than the two-time number of elements",
                m_agents.size(), m_environment.row(), m_environment.column()));

    // create evaluation
    m_evaluation = new CEvaluation(m_agents.parallelStream());

    // run initialization processes
    m_environment.initialize();

    return this;
}

From source file:org.limy.eclipse.qalab.task.Java2HtmlTask.java

/**
 * Javat@CHTML?o?B/*from   w  w  w .  j a v  a 2  s. c  o  m*/
 * @param cmd java->htmlR}h
 * @param targetFile Javat@C
 * @param targetBaseDir Javat@C?fBNg
 * @throws IOException I/OO
 */
private void writeFile(JavaToHtml cmd, File targetFile, File targetBaseDir) throws IOException {
    if (!"java".equals(FilenameUtils.getExtension(targetFile.getName()))) {
        return;
    }
    String lines = FileUtils.readFileToString(targetFile, inputCharset);

    String relativePath = targetFile.getAbsolutePath().substring(targetBaseDir.getAbsolutePath().length() + 1);
    File outputFile = new File(destDir,
            FilenameUtils.getPath(relativePath) + FilenameUtils.getBaseName(relativePath) + ".html");

    String fileName = FilenameUtils.getPath(relativePath) + FilenameUtils.getBaseName(relativePath);
    fileName = fileName.replace('/', '.');
    fileName = fileName.replace('\\', '.');
    String result = convertHtml(cmd, lines, fileName);
    outputFile.getParentFile().mkdirs();
    FileUtils.writeStringToFile(outputFile, result, "UTF-8");
}

From source file:org.marmots.opencms.plugin.OpencmsPackager.java

/**
 * Adds a file to the module zip and updates manifest.xml accordingly
 * @param output zip stream/*  w  w  w . j a v a  2  s . co m*/
 * @param file file to add
 * @param folder zip folder onto append it (corresponds to opencms folder)
 * @throws Exception xml and io related exceptions 
 */
private void addToZip(ZipOutputStream output, File file, String folder) throws Exception {
    // Fix folder name
    if (!StringUtils.isEmpty(folder)) {
        folder += "/";
    }

    // File name
    String name = OpencmsUtils.fixFilename(folder + file.getName());
    logger.info("processing file: " + name);

    // Module config
    if (FilenameUtils.getName(name).equals("module-config.xml")) {
        name = FilenameUtils.getPath(name) + ".config";
        logger.info("module config file: " + name);
    }

    // Check if it's manifest
    if (!name.equals("manifest.xml")) {
        manifestBuilder.addToManifest(name, file.isDirectory());
    }

    // Process entry
    if (file.isDirectory()) {
        File[] files = file.listFiles();
        for (File f : files) {
            addToZip(output, f, name);
        }
    } else {
        output.putNextEntry(new ZipEntry(name));
        FileInputStream input = new FileInputStream(file);
        IOUtils.copy(input, output);
        IOUtils.closeQuietly(input);
    }
}

From source file:org.mitre.honeyclient.WorkerThread.java

@Override
public void run() {

    Logger.getLogger(WorkerThread.class.getName()).log(Level.FINEST, getName() + " accepted a new connection");

    byte[] buf = new byte[1024];
    StringBuffer buffer = new StringBuffer();
    InputStream in = null;//from   ww w .j a v  a 2 s .c o  m
    OutputStream out = null;

    try {

        in = socket.getInputStream();
        out = socket.getOutputStream();

        int len;
        boolean cont = true;

        while (cont) {
            len = in.read(buf);
            buffer.append(new String(buf, 0, len));
            if (buffer.charAt(buffer.length() - 1) == '}') {
                cont = false;
            }
            Logger.getLogger(WorkerThread.class.getName()).log(Level.FINEST,
                    getName() + " read: '" + new String(buf, 0, len) + "'");
            Logger.getLogger(WorkerThread.class.getName()).log(Level.FINEST, getName()
                    + " last charcted read: '" + Character.toString(buffer.charAt(buffer.length() - 1)) + "'");
            Logger.getLogger(WorkerThread.class.getName()).log(Level.FINEST,
                    getName() + " continue reading on port: " + Boolean.toString(cont));
        }

        String text = buffer.toString();
        File inputFile = null, outputFile = null;
        Response response = null;
        Request request = null;
        byte[] file_bytes;

        try {

            Logger.getLogger(WorkerThread.class.getName()).log(Level.FINEST,
                    getName() + " request text : " + text);

            request = server.getMapper().readValue(text, Request.class);

            if ((FilenameUtils.getPath(request.getInputFilename()) != null)
                    && (FilenameUtils.getPath(request.getOutputFilename()) != null)
                    && (new File(request.getInputFilename()).exists())) {

                inputFile = new File(request.getInputFilename());
                outputFile = new File(request.getOutputFilename());

            } else if (request.getInputBase64FileContents() != null) {

                file_bytes = Base64.decodeBase64(request.getInputBase64FileContents().getBytes());

                if (file_bytes.length > server.getFileSizeMax()) {
                    throw new RuntimeException("Fail; File too big to process.");
                }

                FileUtils.writeByteArrayToFile(
                        inputFile = File.createTempFile(FilenameUtils.getBaseName(request.getInputFilename()),
                                "." + FilenameUtils.getExtension(request.getInputFilename())),
                        file_bytes);

                outputFile = File.createTempFile(FilenameUtils.getBaseName(request.getOutputFilename()),
                        "." + FilenameUtils.getExtension(request.getOutputFilename()));

            } else {
                throw new RuntimeException(
                        "No Base64 encoded input file content, nor path provided with input filename.");
            }

            Logger.getLogger(WorkerThread.class.getName()).log(Level.FINEST,
                    "calling convert of " + inputFile.getPath() + " to " + outputFile.getPath());

            // TODO: convert using convert(File inputFile, File outputFile, DocumentFormat outputFormat), modify Request to handle
            server.getDocumentConverter().convert(inputFile, outputFile);

            if (!outputFile.exists())
                throw new RuntimeException("The file could not be converted.");

            if (request.inputBase64FileContents != null) {
                byte[] outputFileBytes = new byte[(int) outputFile.length()];
                FileInputStream f = new FileInputStream(outputFile.getPath());
                f.read(outputFileBytes, 0, outputFileBytes.length);
                f.close();

                String outputBase64encoded = new String(Base64.encodeBase64(outputFileBytes));

                response = new Response("Success; output returned in Base64 format",
                        request.getOutputFilename(), outputBase64encoded);
            } else {
                response = new Response("Success; output can found in the output file",
                        request.getOutputFilename(), null);
            }

        } catch (RuntimeException e) {
            Logger.getLogger(WorkerThread.class.getName()).log(Level.SEVERE, e.toString());
            response = new Response(e.getMessage(), null, null);
            //} catch (java.io.EOFException e) {
            //swallow
        } finally {
            if ((request != null) && (request.getInputBase64FileContents() != null)) {
                if (inputFile != null) {
                    inputFile.delete();
                }

                if (outputFile != null) {
                    outputFile.delete();
                }
            }

            server.getMapper().writeValue(out, response);

        }

    } catch (Exception e) {
        // catch everything else
        Logger.getLogger(WorkerThread.class.getName()).log(Level.SEVERE, e.getMessage());
    } finally {
        try {
            in.close();
            out.close();
            socket.close();

        } catch (IOException e) {
            Logger.getLogger(WorkerThread.class.getName()).log(Level.SEVERE, null, e);
        }
    }
    Logger.getLogger(WorkerThread.class.getName()).log(Level.FINEST, getName() + " done");
}

From source file:org.ngrinder.perftest.service.PerfTestService.java

/**
 * Create {@link GrinderProperties} based on the passed {@link PerfTest}.
 *
 * @param perfTest      base data/*from  ww  w .j  ava2 s  .com*/
 * @param scriptHandler scriptHandler
 * @return created {@link GrinderProperties} instance
 */
public GrinderProperties getGrinderProperties(PerfTest perfTest, ScriptHandler scriptHandler) {
    try {
        // Use default properties first
        GrinderProperties grinderProperties = new GrinderProperties(
                config.getHome().getDefaultGrinderProperties());

        User user = perfTest.getCreatedUser();

        // Get all files in the script path
        String scriptName = perfTest.getScriptName();
        FileEntry userDefinedGrinderProperties = fileEntryService.getOne(user,
                FilenameUtils.concat(FilenameUtils.getPath(scriptName), DEFAULT_GRINDER_PROPERTIES), -1L);
        if (!config.isSecurityEnabled() && userDefinedGrinderProperties != null) {
            // Make the property overridden by user property.
            GrinderProperties userProperties = new GrinderProperties();
            userProperties.load(new StringReader(userDefinedGrinderProperties.getContent()));
            grinderProperties.putAll(userProperties);
        }
        grinderProperties.setAssociatedFile(new File(DEFAULT_GRINDER_PROPERTIES));
        grinderProperties.setProperty(GRINDER_PROP_SCRIPT, scriptHandler.getScriptExecutePath(scriptName));

        grinderProperties.setProperty(GRINDER_PROP_TEST_ID, "test_" + perfTest.getId());
        grinderProperties.setInt(GRINDER_PROP_AGENTS, getSafe(perfTest.getAgentCount()));
        grinderProperties.setInt(GRINDER_PROP_PROCESSES, getSafe(perfTest.getProcesses()));
        grinderProperties.setInt(GRINDER_PROP_THREAD, getSafe(perfTest.getThreads()));
        if (perfTest.isThresholdDuration()) {
            grinderProperties.setLong(GRINDER_PROP_DURATION, getSafe(perfTest.getDuration()));
            grinderProperties.setInt(GRINDER_PROP_RUNS, 0);
        } else {
            grinderProperties.setInt(GRINDER_PROP_RUNS, getSafe(perfTest.getRunCount()));
            if (grinderProperties.containsKey(GRINDER_PROP_DURATION)) {
                grinderProperties.remove(GRINDER_PROP_DURATION);
            }
        }
        grinderProperties.setProperty(GRINDER_PROP_ETC_HOSTS,
                StringUtils.defaultIfBlank(perfTest.getTargetHosts(), ""));
        grinderProperties.setBoolean(GRINDER_PROP_USE_CONSOLE, true);
        if (BooleanUtils.isTrue(perfTest.getUseRampUp())) {
            grinderProperties.setBoolean(GRINDER_PROP_THREAD_RAMPUP, perfTest.getRampUpType() == RampUp.THREAD);
            grinderProperties.setInt(GRINDER_PROP_PROCESS_INCREMENT, getSafe(perfTest.getRampUpStep()));
            grinderProperties.setInt(GRINDER_PROP_PROCESS_INCREMENT_INTERVAL,
                    getSafe(perfTest.getRampUpIncrementInterval()));
            if (perfTest.getRampUpType() == RampUp.PROCESS) {
                grinderProperties.setInt(GRINDER_PROP_INITIAL_SLEEP_TIME,
                        getSafe(perfTest.getRampUpInitSleepTime()));
            } else {
                grinderProperties.setInt(GRINDER_PROP_INITIAL_THREAD_SLEEP_TIME,
                        getSafe(perfTest.getRampUpInitSleepTime()));
            }
            grinderProperties.setInt(GRINDER_PROP_INITIAL_PROCESS, getSafe(perfTest.getRampUpInitCount()));
        } else {
            grinderProperties.setInt(GRINDER_PROP_PROCESS_INCREMENT, 0);
        }
        grinderProperties.setInt(GRINDER_PROP_REPORT_TO_CONSOLE, 500);
        grinderProperties.setProperty(GRINDER_PROP_USER, perfTest.getCreatedUser().getUserId());
        grinderProperties.setProperty(GRINDER_PROP_JVM_CLASSPATH, getCustomClassPath(perfTest));
        grinderProperties.setInt(GRINDER_PROP_IGNORE_SAMPLE_COUNT, getSafe(perfTest.getIgnoreSampleCount()));
        grinderProperties.setBoolean(GRINDER_PROP_SECURITY, config.isSecurityEnabled());
        // For backward agent compatibility.
        // If the security is not enabled, pass it as jvm argument.
        // If enabled, pass it to grinder.param. In this case, I drop the
        // compatibility.
        if (StringUtils.isNotBlank(perfTest.getParam())) {
            String param = perfTest.getParam().replace("'", "\\'").replace(" ", "");
            if (config.isSecurityEnabled()) {
                grinderProperties.setProperty(GRINDER_PROP_PARAM, StringUtils.trimToEmpty(param));
            } else {
                String property = grinderProperties.getProperty(GRINDER_PROP_JVM_ARGUMENTS, "");
                property = property + " -Dparam=" + param + " ";
                grinderProperties.setProperty(GRINDER_PROP_JVM_ARGUMENTS, property);
            }
        }
        LOGGER.info("Grinder Properties : {} ", grinderProperties);
        return grinderProperties;
    } catch (Exception e) {
        throw processException("error while prepare grinder property for " + perfTest.getTestName(), e);
    }
}