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:biz.dfch.j.graylog.plugin.filter.metricsValidation.java

public metricsValidation() throws IOException, URISyntaxException {
    try {/*w  w  w  .  java 2 s. c  o m*/
        LOG.debug(String.format("[%d] Initialising plugin ...\r\n", Thread.currentThread().getId()));

        // get config file
        CodeSource codeSource = this.getClass().getProtectionDomain().getCodeSource();
        URI uri = codeSource.getLocation().toURI();

        // String path = uri.getSchemeSpecificPart();
        // path would contain absolute path including jar file name with extension
        // String path = FilenameUtils.getPath(uri.getPath());
        // path would contain relative path (no leading '/' and no jar file name

        String path = FilenameUtils.getPath(uri.getPath());
        if (!path.startsWith("/")) {
            path = String.format("/%s", path);
        }
        String baseName = FilenameUtils.getBaseName(uri.getSchemeSpecificPart());
        if (null == baseName || baseName.isEmpty()) {
            baseName = this.getClass().getPackage().getName();
        }

        // get config values
        configurationFileName = FilenameUtils.concat(path, baseName + ".conf");
        JSONParser jsonParser = new JSONParser();
        LOG.info(String.format("Loading configuration file '%s' ...", configurationFileName));
        Object object = jsonParser.parse(new FileReader(configurationFileName));

        JSONObject jsonObject = (JSONObject) object;
        String pluginPriority = (String) jsonObject.get(DF_PLUGIN_PRIORITY);
        Boolean pluginDropMessage = (Boolean) jsonObject.get(DF_PLUGIN_DROP_MESSAGE);
        Boolean pluginDisabled = (Boolean) jsonObject.get(DF_PLUGIN_DISABLED);
        //            metrics = (HashMap) jsonObject.get("metrics");
        //            String fieldName = "cpu.average";
        //            Set<String> keys = metrics.keySet();
        //            for(String key : keys)
        //            {
        //                Map metric = (Map) metrics.get(key);
        //                LOG.info(String.format("%s [type %s] [range %s .. %s]", key, metric.get("type").toString(), metric.get("minValue").toString(), metric.get("maxValue").toString()));
        //            }
        // set configuration
        Map<String, Object> map = new HashMap<>();
        map.put(DF_PLUGIN_PRIORITY, pluginPriority);
        map.put(DF_PLUGIN_DROP_MESSAGE, pluginDropMessage);
        map.put(DF_PLUGIN_DISABLED, pluginDisabled);
        //map.put(DF_PLUGIN_METRICS, metrics);

        initialize(new Configuration(map));
    } catch (IOException ex) {
        LOG.error(String.format("[%d] Initialising plugin FAILED. Filter will be disabled.\r\n%s\r\n",
                Thread.currentThread().getId(), ex.getMessage()));
        LOG.error("*** " + DF_PLUGIN_NAME + "::dfchBizExecScript() - IOException - Filter will be disabled.");
        ex.printStackTrace();
    } catch (Exception ex) {
        LOG.error(String.format("[%d] Initialising plugin FAILED. Filter will be disabled.\r\n",
                Thread.currentThread().getId()));
        LOG.error("*** " + DF_PLUGIN_NAME + "::dfchBizExecScript() - Exception - Filter will be disabled.");
        ex.printStackTrace();
    }
}

From source file:hoot.services.ingest.MultipartSerializer.java

protected void _serializeFGDB(List<FileItem> fileItemsList, String jobId, Map<String, String> uploadedFiles,
        Map<String, String> uploadedFilesPaths) throws Exception {
    Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
    Map<String, String> folderMap = new HashMap<String, String>();

    while (fileItemsIterator.hasNext()) {
        FileItem fileItem = fileItemsIterator.next();
        String fileName = fileItem.getName();

        String relPath = FilenameUtils.getPath(fileName);
        if (relPath.endsWith("/")) {
            relPath = relPath.substring(0, relPath.length() - 1);
        }/*  w ww . j  av  a  2s  . c  om*/
        fileName = FilenameUtils.getName(fileName);

        String fgdbFolderPath = homeFolder + "/upload/" + jobId + "/" + relPath;

        String pathVal = folderMap.get(fgdbFolderPath);
        if (pathVal == null) {
            File folderPath = new File(fgdbFolderPath);
            FileUtils.forceMkdir(folderPath);
            folderMap.put(fgdbFolderPath, relPath);
        }

        if (fileName == null) {
            ResourceErrorHandler.handleError("A valid file name was not specified.", Status.BAD_REQUEST, log);
        }

        String uploadedPath = fgdbFolderPath + "/" + fileName;
        File file = new File(uploadedPath);
        fileItem.write(file);
    }

    Iterator it = folderMap.entrySet().iterator();
    while (it.hasNext()) {
        String nameOnly = "";
        Map.Entry pairs = (Map.Entry) it.next();
        String fgdbName = pairs.getValue().toString();
        String[] nParts = fgdbName.split("\\.");

        for (int i = 0; i < nParts.length - 1; i++) {
            if (nameOnly.length() > 0) {
                nameOnly += ".";
            }
            nameOnly += nParts[i];
        }
        uploadedFiles.put(nameOnly, "GDB");
        uploadedFilesPaths.put(nameOnly, fgdbName);
    }
}

From source file:com.github.drxaos.jvmvm.compiler.javac.MemoryFileManager.java

@Override
public Iterable<JavaFileObject> list(Location location, String packageName, Set<JavaFileObject.Kind> kinds,
        boolean recurse) throws IOException {
    if (packageName.startsWith("java.")) {
        return super.list(location, packageName, kinds, recurse);
    }//from   w w w  .j a va 2 s  .  co  m
    ArrayList<JavaFileObject> list = new ArrayList<JavaFileObject>();
    for (Map.Entry<String, MemoryJavaFile> e : inputs.entrySet()) {
        try {
            MemoryJavaFile f = e.getValue();
            String p = new URI(f.getPath()).getPath();
            String path = FilenameUtils.getPath(p);
            String name = FilenameUtils.getBaseName(p);
            String ext = FilenameUtils.getExtension(p);
            if (kinds.contains(f.getKind()) && (packageName.replace(".", "/") + "/").equals(path)) {
                list.add(f);
            }
        } catch (URISyntaxException e1) {
            throw new RuntimeException(e1);
        }
    }
    return list;
}

From source file:biz.dfch.j.graylog2.plugin.filter.dfchBizExecScript.java

public dfchBizExecScript() throws IOException, URISyntaxException {
    try {/*from w w  w  .j  a v a  2 s.  c  o m*/
        LOG.debug(String.format("*** [%d] %s: Initialising plugin ...\r\n", Thread.currentThread().getId(),
                DF_PLUGIN_NAME));

        // get config file
        CodeSource codeSource = this.getClass().getProtectionDomain().getCodeSource();
        URI uri = codeSource.getLocation().toURI();

        // String path = uri.getSchemeSpecificPart();
        // path would contain absolute path including jar file name with extension
        // String path = FilenameUtils.getPath(uri.getPath());
        // path would contain relative path (no leadig '/' and no jar file name

        String path = FilenameUtils.getPath(uri.getPath());
        if (!path.startsWith("/")) {
            path = String.format("/%s", path);
        }
        String baseName = FilenameUtils.getBaseName(uri.getSchemeSpecificPart());
        if (null == baseName || baseName.isEmpty()) {
            baseName = this.getClass().getPackage().getName();
        }

        // get config values
        configurationFileName = FilenameUtils.concat(path, baseName + ".conf");
        JSONParser jsonParser = new JSONParser();
        Object object = jsonParser.parse(new FileReader(configurationFileName));

        JSONObject jsonObject = (JSONObject) object;
        String scriptEngine = (String) jsonObject.get(DF_SCRIPT_ENGINE);
        String scriptPathAndName = (String) jsonObject.get(DF_SCRIPT_PATH_AND_NAME);
        if (null == scriptPathAndName || scriptPathAndName.isEmpty()) {
            scriptPathAndName = FilenameUtils.concat(path, (String) jsonObject.get(DF_SCRIPT_NAME));
        }
        Boolean scriptCacheContents = (Boolean) jsonObject.get(DF_SCRIPT_CACHE_CONTENTS);
        Boolean scriptDisplayOutput = (Boolean) jsonObject.get(DF_SCRIPT_DISPLAY_OUTPUT);
        String pluginPriority = (String) jsonObject.get(DF_PLUGIN_PRIORITY);
        Boolean pluginDropMessage = (Boolean) jsonObject.get(DF_PLUGIN_DROP_MESSAGE);
        Boolean pluginDisabled = (Boolean) jsonObject.get(DF_PLUGIN_DISABLED);

        // set configuration
        Map<String, Object> map = new HashMap<>();
        map.put(DF_SCRIPT_ENGINE, scriptEngine);
        map.put(DF_SCRIPT_PATH_AND_NAME, scriptPathAndName);
        map.put(DF_SCRIPT_DISPLAY_OUTPUT, scriptDisplayOutput);
        map.put(DF_SCRIPT_CACHE_CONTENTS, scriptCacheContents);
        map.put(DF_PLUGIN_PRIORITY, pluginPriority);
        map.put(DF_PLUGIN_DROP_MESSAGE, pluginDropMessage);
        map.put(DF_PLUGIN_DISABLED, pluginDisabled);

        initialize(new Configuration(map));
    } catch (IOException ex) {
        LOG.error(String.format("*** [%d] %s: Initialising plugin FAILED. Filter will be disabled.\r\n%s\r\n",
                Thread.currentThread().getId(), DF_PLUGIN_NAME, ex.getMessage()));
        LOG.error("*** " + DF_PLUGIN_NAME + "::dfchBizExecScript() - IOException - Filter will be disabled.");
        ex.printStackTrace();
    } catch (Exception ex) {
        LOG.error(String.format("*** [%d] %s: Initialising plugin FAILED. Filter will be disabled.\r\n",
                Thread.currentThread().getId(), DF_PLUGIN_NAME));
        LOG.error("*** " + DF_PLUGIN_NAME + "::dfchBizExecScript() - Exception - Filter will be disabled.");
        ex.printStackTrace();
    }
}

From source file:jp.vmi.selenium.selenese.command.AttachFile.java

@Override
protected Result executeImpl(Context context, String... curArgs) {
    String name = curArgs[ARG_FILENAME];
    File outputTo = null;/*from  www .j  a va  2  s.  co m*/
    if (name.contains("://")) {
        // process (remote) url
        URL url;
        try {
            url = new URL(name);
        } catch (MalformedURLException e) {
            return new Error("Malformed URL: " + name);
        }
        File dir = TemporaryFilesystem.getDefaultTmpFS().createTempDir("attachFile", "dir");
        outputTo = new File(dir, new File(url.getFile()).getName());
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(outputTo);
            Resources.copy(url, fos);
        } catch (IOException e) {
            return new Error("Can't access file to upload: " + url, e);
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                return new Warning("Unable to close stream used for reading file: " + name, e);
            }
        }
    } else {
        // process file besides testcase file
        outputTo = new File(FilenameUtils.getPath(context.getCurrentTestCase().getFilename()), name);
        if (!outputTo.exists()) {
            return new Error("Can't access file: " + outputTo);
        }
    }

    WebElement element = context.findElement(curArgs[ARG_LOCATOR]);
    try {
        element.clear();
    } catch (Exception e) {
        // ignore exceptions from some drivers when file-input cannot be cleared;
    }
    element.sendKeys(outputTo.getAbsolutePath());
    return SUCCESS;
}

From source file:com.alibaba.otter.node.etl.common.pipe.impl.memory.RowDataMemoryPipe.java

@SuppressWarnings("unused")
private File prepareFile(FileBatch fileBatch) {
    // ?url/*from   w ww.j av a 2  s .c  o m*/
    String dirname = buildFileName(fileBatch.getIdentity(), ClassUtils.getShortClassName(fileBatch.getClass()));
    File dir = new File(downloadDir, dirname);
    NioUtils.create(dir, false, 3);// 
    // ?
    List<FileData> fileDatas = fileBatch.getFiles();

    for (FileData fileData : fileDatas) {
        String namespace = fileData.getNameSpace();
        String path = fileData.getPath();
        boolean isLocal = StringUtils.isBlank(namespace);
        String entryName = null;
        if (true == isLocal) {
            entryName = FilenameUtils.getPath(path) + FilenameUtils.getName(path);
        } else {
            entryName = namespace + File.separator + path;
        }

        InputStream input = retrive(fileBatch.getIdentity(), fileData);
        if (input == null) {
            continue;
        }
        File entry = new File(dir, entryName);
        NioUtils.create(entry.getParentFile(), false, retry);// ?
        FileOutputStream output = null;
        try {
            output = new FileOutputStream(entry);
            NioUtils.copy(input, output);// ?
        } catch (Exception e) {
            throw new PipeException("prepareFile error for file[" + entry.getPath() + "]");
        } finally {
            IOUtils.closeQuietly(output);
        }
    }

    return dir;
}

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

/**
 * Export the specified institutional collection.
 * /*from  w w w . ja v a2 s .  c om*/
 * @param collection - collection to export
 * @param includeChildren - if true children should be exported
 * @param zipFileDestination - zip file destination to store the collection information
 * @throws IOException 
 */
public void export(InstitutionalCollection collection, boolean includeChildren, 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);
    }

    List<InstitutionalCollection> collections = new LinkedList<InstitutionalCollection>();
    collections.add(collection);
    File collectionXmlFile = temporaryFileCreator.createTemporaryFile(extension);
    Set<FileInfo> allPictures = createXmlFile(collectionXmlFile, collections, includeChildren);

    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:it.biztech.btable.util.Utils.java

public static IRWAccess getSystemOrUserRWAccess(String filePath) {
    IRWAccess rwAccess = null;// www.  ja va 2  s.co  m

    if (filePath.startsWith("/" + BTableConstants.SYSTEM_DIR + "/")
            && filePath.endsWith(BTableConstants.FILE_EXTENSION)) {
        rwAccess = getSystemRWAccess(filePath.split("/")[2], null);
    } else if (PentahoPluginEnvironment.getInstance().getUserContentAccess("/").fileExists(filePath)) {
        if (PentahoPluginEnvironment.getInstance().getUserContentAccess("/").hasAccess(filePath,
                FileAccess.EXECUTE)) {
            if (PentahoPluginEnvironment.getInstance().getUserContentAccess("/").hasAccess(filePath,
                    FileAccess.WRITE)) {
                rwAccess = PentahoPluginEnvironment.getInstance().getUserContentAccess("/");
            }
        } else {
            return null;
        }
    } else if (PentahoPluginEnvironment.getInstance().getUserContentAccess("/")
            .hasAccess("/" + FilenameUtils.getPath(filePath), FileAccess.EXECUTE)) {
        rwAccess = PentahoPluginEnvironment.getInstance().getUserContentAccess("/");
    }

    return rwAccess;
}

From source file:de.uzk.hki.da.cb.RetrievalAction.java

private void specialRetrieval(Path tempFolder) throws IOException {

    for (Package p : packagesToRetrieve()) {

        for (DAFile f : p.getFiles()) {

            File destDir = Path.makeFile(tempFolder, WorkArea.DATA, f.getRep_name(),
                    FilenameUtils.getPath(f.getRelative_path()));
            destDir.mkdirs();/*  w w w.j  a va  2 s  . c o  m*/
            FileUtils.copyFileToDirectory(wa.toFile(f), destDir);
        }
    }
}

From source file:de.hybris.platform.refund.RefundServiceTest.java

private boolean hasResourceFolder(final String fileName) {
    return FilenameUtils.getPath(fileName).equals("") ? false : true;
}