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

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

Introduction

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

Prototype

public static String getName(String filename) 

Source Link

Document

Gets the name minus the path from a full filename.

Usage

From source file:fr.certu.chouette.gui.command.ImportCommand.java

/**
 * @param session//from  ww  w. j a  va 2s. c o m
 * @param save
 * @param savedIds
 * @param manager
 * @param importTask
 * @param format
 * @param inputFile
 * @param suffixes
 * @param values
 * @param importHolder
 * @param validationHolder
 * @throws ChouetteException
 */
private int importZipEntries(EntityManager session, boolean save, List<Long> savedIds,
        INeptuneManager<NeptuneIdentifiedObject> manager, ImportTask importTask, String format,
        String inputFile, List<String> suffixes, List<ParameterValue> values, ReportHolder importHolder,
        ReportHolder validationHolder) throws ChouetteException {
    SimpleParameterValue inputFileParam = new SimpleParameterValue("inputFile");
    values.add(inputFileParam);

    ReportHolder zipHolder = new ReportHolder();
    if (format.equalsIgnoreCase("neptune")) {
        SharedImportedData sharedData = new SharedImportedData();
        UnsharedImportedData unsharedData = new UnsharedImportedData();
        SimpleParameterValue sharedDataParam = new SimpleParameterValue("sharedImportedData");
        sharedDataParam.setObjectValue(sharedData);
        values.add(sharedDataParam);
        SimpleParameterValue unsharedDataParam = new SimpleParameterValue("unsharedImportedData");
        unsharedDataParam.setObjectValue(unsharedData);
        values.add(unsharedDataParam);
    }

    // unzip files , import and save contents
    ZipFile zip = null;
    File temp = null;
    File tempRep = new File(FileUtils.getTempDirectory(), "massImport" + importTask.getId());
    if (!tempRep.exists())
        tempRep.mkdirs();
    File zipFile = new File(inputFile);
    ReportItem zipReportItem = new ExchangeReportItem(ExchangeReportItem.KEY.ZIP_FILE, Report.STATE.OK,
            zipFile.getName());
    try {
        Charset encoding = FileTool.getZipCharset(inputFile);
        if (encoding == null) {
            ReportItem fileErrorItem = new ExchangeReportItem(ExchangeReportItem.KEY.ZIP_ERROR,
                    Report.STATE.ERROR, "unknown encoding");
            zipReportItem.addItem(fileErrorItem);
            importHolder.getReport().addItem(zipReportItem);
            saveImportReports(session, importTask, importHolder.getReport(), validationHolder.getReport());
            return 1;
        }
        zip = new ZipFile(inputFile, encoding);
        zipHolder.setReport(zipReportItem);
        for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();) {
            ZipEntry entry = entries.nextElement();

            if (entry.isDirectory()) {
                File dir = new File(tempRep, entry.getName());
                dir.mkdirs();
                continue;
            }
            if (!FilenameUtils.isExtension(entry.getName().toLowerCase(), suffixes)) {
                ReportItem fileReportItem = new ExchangeReportItem(ExchangeReportItem.KEY.FILE_IGNORED,
                        Report.STATE.OK, FilenameUtils.getName(entry.getName()));
                zipReportItem.addItem(fileReportItem);
                log.info("entry " + entry.getName() + " ignored, unknown extension");
                continue;
            }
            InputStream stream = null;
            try {
                stream = zip.getInputStream(entry);
            } catch (IOException e) {
                ReportItem fileReportItem = new ExchangeReportItem(ExchangeReportItem.KEY.FILE_ERROR,
                        Report.STATE.WARNING, FilenameUtils.getName(entry.getName()));
                zipReportItem.addItem(fileReportItem);
                log.error("entry " + entry.getName() + " cannot read", e);
                continue;
            }
            byte[] bytes = new byte[4096];
            int len = stream.read(bytes);
            temp = new File(tempRep.getAbsolutePath() + "/" + entry.getName());
            FileOutputStream fos = new FileOutputStream(temp);
            while (len > 0) {
                fos.write(bytes, 0, len);
                len = stream.read(bytes);
            }
            fos.close();

            // import
            log.info("import file " + entry.getName());
            inputFileParam.setFilepathValue(temp.getAbsolutePath());
            List<NeptuneIdentifiedObject> beans = manager.doImport(null, format, values, zipHolder,
                    validationHolder);
            if (beans != null && !beans.isEmpty()) {
                // save
                if (save) {
                    saveBeans(manager, beans, savedIds, importHolder.getReport());
                } else {
                    for (NeptuneIdentifiedObject bean : beans) {
                        GuiReportItem item = new GuiReportItem(GuiReportItem.KEY.NO_SAVE, Report.STATE.OK,
                                bean.getName());
                        importHolder.getReport().addItem(item);
                    }

                }
            }
            temp.delete();
        }
        try {
            zip.close();
        } catch (IOException e) {
            log.info("cannot close zip file");
        }
        importHolder.getReport().addItem(zipReportItem);
    } catch (IOException e) {
        log.error("IO error", e);
        ReportItem fileErrorItem = new ExchangeReportItem(ExchangeReportItem.KEY.ZIP_ERROR, Report.STATE.ERROR,
                e.getLocalizedMessage());
        zipReportItem.addItem(fileErrorItem);
        importHolder.getReport().addItem(zipReportItem);
        saveImportReports(session, importTask, importHolder.getReport(), validationHolder.getReport());
        return 1;
    } catch (IllegalArgumentException e) {
        log.error("Format error", e);
        ReportItem fileErrorItem = new ExchangeReportItem(ExchangeReportItem.KEY.ZIP_ERROR, Report.STATE.ERROR,
                e.getLocalizedMessage());
        zipReportItem.addItem(fileErrorItem);
        importHolder.getReport().addItem(zipReportItem);
        saveImportReports(session, importTask, importHolder.getReport(), validationHolder.getReport());
        return 1;
    } finally {
        try {
            FileUtils.deleteDirectory(tempRep);
        } catch (IOException e) {
            log.warn("temporary directory " + tempRep.getAbsolutePath() + " could not be deleted");
        }
    }
    return 0;
}

From source file:com.gitpitch.services.OfflineService.java

private void fetchYAMLDependencies(PitchParams pp, Path zipRoot) {

    GRSService grsService = grsManager.getService(grsManager.get(pp));
    YAMLOptions yOpts = YAMLOptions.build(pp, grsService, diskService);
    log.debug("fetchYAMLDependencies: yOpts={}", yOpts);

    try {/*from  ww  w .  j  a va 2s. com*/

        if (yOpts != null && yOpts.hasLogo()) {
            String logoUrl = yOpts.fetchLogo(pp);
            String logoName = FilenameUtils.getName(logoUrl);

            Path zipAssetsPath = diskService.ensure(zipRoot.resolve(ZIP_ASSETS_DIR));
            diskService.download(pp, zipAssetsPath, logoUrl, logoName, grsManager.get(pp).getHeaders());
            log.debug("fetchYAMLDependencies: downloaded logo={}", logoUrl);
        }

    } catch (Exception lex) {
        log.warn("fetchYAMLDependencies: logo ex={}", lex);
    }

    try {

        /*
         * If Math Slides not enabled within PITCHME.yaml, strip
         * Reveal.js math plugin file dependencies from zip.
         */
        if (yOpts == null || !yOpts.mathEnabled(pp)) {

            Path destPath = zipRoot.resolve(ZIP_ASSETS_DIR);
            String revealVersion = configuration.getString("gitpitch.dependency.revealjs");
            Path mathPluginPath = Paths.get(destPath.toString(), "reveal.js", revealVersion, "plugin/math");
            log.debug("fetchYAMLDependencies: removing mathPlugin={}", mathPluginPath);

            diskService.deepDelete(mathPluginPath.toFile());
        }

    } catch (Exception mex) {
        log.warn("fetchYAMLDependencies: math config assets ex={}", mex);
    }
}

From source file:eu.esdihumboldt.hale.io.html.HtmlMappingExporter.java

private File getInputFile(URL url) throws IOException, FileNotFoundException {
    File file = new File(tempDir.toString() + FilenameUtils.getName(url.toString()));
    OutputStream outputStream = new FileOutputStream(file);
    IOUtils.copy(url.openStream(), outputStream);
    outputStream.close();/*from   ww  w.j  a va2  s  .co  m*/
    return file;
}

From source file:hu.tbognar76.apking.ApKing.java

private void reportDuplications(boolean toDelete) {

    for (Map.Entry<String, ArrayList<ApkInfo>> entry : this.packageHash.entrySet()) {
        // String key = entry.getKey();
        ArrayList<ApkInfo> value = entry.getValue();
        if (value.size() > 1) {
            ArrayList<CApkInfo> cvalue = new ArrayList<ApKing.CApkInfo>();
            System.out.println("");

            List<Version> versions = new ArrayList<Version>();

            boolean versionerror = false;
            boolean versionerror2 = false;

            for (ApkInfo ai : value) {

                CApkInfo cai = new CApkInfo();

                cai.apkinfo = ai;//from  ww  w  . j a  va2 s  .c  om

                // System.out.println(ai.fullpath + "     " + ai.version);
                try {
                    versions.add(new Version(ai.version));

                } catch (Exception e) {
                    versionerror = true;
                }

                try {
                    cai.cmp = new ComparableVersion(ai.version);
                } catch (Exception e) {
                    versionerror2 = true;
                }
                cvalue.add(cai);

            }

            if (versionerror2) {
                System.out.println("BAD VERSION FORMAT 2");
                for (ApkInfo ais : value) {
                    System.out.println("#del " + ais.fullpath);
                }

            } else {
                CApkInfo maxi = Collections.max(cvalue, new Comparator<CApkInfo>() {
                    @Override
                    public int compare(CApkInfo left, CApkInfo right) {
                        return left.cmp.compareTo(right.cmp);
                    }
                });
                maxi.max = true;

                String warning = "";
                if (versionerror || versionerror2) {
                    warning = "WARNING!! ";
                }

                String vers = "";
                for (CApkInfo aic : cvalue) {
                    if (aic.max) {
                        vers = vers + "-->" + aic.apkinfo.version + "<-- , ";
                    } else {
                        vers = vers + aic.apkinfo.version + " , ";
                    }
                }
                System.out.println("::" + warning + maxi.apkinfo.name + " // " + vers);

                for (CApkInfo aic : cvalue) {
                    // String max ;
                    if (aic.max) {
                        // max = "rem #";
                        // A LEGUJABB
                        System.out.println("!OK " + aic.apkinfo.fullpath);

                    } else {
                        // REGEBBI , TOROLNI KELL (MOVE TO DELETEFOLDER)
                        System.out.println("del " + aic.apkinfo.fullpath);

                        if (toDelete) {
                            String renamedfile = this.init.deletePath + "/"
                                    + FilenameUtils.getName(aic.apkinfo.fullpath);
                            File file = new File(aic.apkinfo.fullpath);
                            if (file.renameTo(new File(renamedfile))) {

                            } else {
                                System.out.println("File is failed to move!" + renamedfile);
                            }
                        }
                    }

                }

            }
            // System.out.println("MAX: " + maxi.apkinfo.version +
            // "   "+maxi.apkinfo.filename);

        }
        // do stuff
    }

}

From source file:com.perceptivesoftware.mule.connector.PerceptiveContentMuleSoftConnector.java

/**
 * Replace an existing document page in Perceptive Content Document
 * /*from w  w  w. j  a v a2  s  .c o m*/
 * {@sample.xml ../../../doc/perceptive-content-mulesoft-connector.xml.sample perceptive-content:replace-document-page}
 * @param documentId The Perceptive Content Document ID 
 * @param existingPageName This is the existing name of the page in Perceptive Content that will be replaced
 * @param filePath The file location to the page to be added
 * @param replacementPageName This is the replacement name for the page that is being replaced in Perceptive Content page (optional)
 * @throws FileNotFoundException Thrown if the file fails to open
 * @throws IntegrationServerConnectorException Thrown if call fails
 */
@Processor(friendlyName = "Document - Replace Page")
public void replaceDocumentPage(String documentId, String existingPageName, String filePath,
        @Optional String replacementPageName)
        throws IntegrationServerConnectorException, FileNotFoundException {

    if (Strings.isNullOrEmpty(replacementPageName)) {
        replacementPageName = FilenameUtils.getName(filePath);
    }

    File file = new File(filePath);
    FileInputStream input = new FileInputStream(file);

    String pageId = findPageId(documentId, existingPageName);

    client.getDocumentEndpoint().replacePage(documentId, pageId, replacementPageName, file.length(), input);
}

From source file:com.nuvolect.securesuite.webserver.connector.CmdUpload.java

/**
 * Collect chunk data until last chuck is received, then assemble the uploaded file.
 *
 * EXAMPLE, 60.3MB file://www.  ja va2  s .  c  o  m
 * "cmd" -> "upload"
 * "mtime[]" -> "1489684754"
 * "cid" -> "697767115"
 * "upload_path[]" -> "l0_L3Rlc3QvdG1w"
 * "range" -> "0,10485760,60323475"
 x "post_uploads" -> "[{"file_path":"\/data\/user\/0\/com.nuvolect.securesuite.debug\/cache\/NanoHTTPD-340250228","file_name":"blob"}]"
 * "dropWith" -> "0"
 * "chunk" -> "kepler_7_weeks.mp4.0_5.part"
 x "target" -> "l0_L3Rlc3QvdG1w"
 * "unique_id" -> "1489174097708"
 * "upload[]" -> "blob"
 * "queryParameterStrings" -> "cmd=ls&target=l0_L3Rlc3QvdG1w&intersect%5B%5D=kepler_7_weeks.mp4&_=1489697705506"
 * "uri" -> "/connector"
 */
private InputStream chunksUpload(@NonNull Map<String, String> params, OmniFile targetDirectory) {
    String url = params.get("url");
    String targetVolumeId = targetDirectory.getVolumeId();

    JsonObject wrapper = new JsonObject();
    String chunk = params.get("chunk");
    String[] parts = chunk.split(Pattern.quote("."));
    String[] twoNumbers = parts[parts.length - 2].split("_");
    int chunkMax = Integer.valueOf(twoNumbers[1]);
    String targetFilename = parts[0] + "." + parts[1];
    JsonObject fileChunks = new JsonObject(); // Chunks for the target file

    /**
     * Parse the uploads array and collect specific of the current chunk.
     * Metadata for each chunk is saved in a JSONObject using the chunk filename as the key.
     * Move each chunk from the app:/cache folder to app:/chunk.
     * When all chunks are uploaded, the target is assembled and chunks deleted.
     */
    JsonParser parser = new JsonParser();
    JsonArray postUploads = parser.parse(params.get("post_uploads")).getAsJsonArray();

    for (int i = 0; i < postUploads.size(); i++) {
        JsonObject postUpload = postUploads.get(i).getAsJsonObject();
        //app: /cache/xxx
        String cachePath = postUpload.get(CConst.FILE_PATH).getAsString();
        File cacheFile = new File(cachePath);

        String chunkPath = chunkDirPath + FilenameUtils.getName(cachePath);
        File chunkFile = new File(chunkPath);

        /**
         * Move the chunk, otherwise Nanohttpd will delete it.
         */
        cacheFile.renameTo(chunkFile);

        JsonObject chunkObj = new JsonObject();
        chunkObj.addProperty("filepath", chunkPath);
        chunkObj.addProperty("range", params.get("range"));

        if (fileUploads.has(targetFilename)) {
            fileChunks = fileUploads.get(targetFilename).getAsJsonObject();
        } else {
            fileChunks = new JsonObject();
        }
        fileChunks.add(chunk, chunkObj);
        fileUploads.add(targetFilename, fileChunks);
    }

    /**
     * If not complete, return with intermediate results
     */
    if (fileChunks.size() <= chunkMax) {
        wrapper.add("added", new JsonArray());

        return getInputStream(wrapper);
    }

    try {
        int totalSize = 0;
        /**
         * All chunks are uploaded.  Iterate over the chunk meta data and assemble the file.
         * Open the target file.
         */
        OmniFile destFile = new OmniFile(targetVolumeId,
                targetDirectory.getPath() + File.separator + targetFilename);
        OutputStream destOutputStream = destFile.getOutputStream();
        String error = null;

        for (int i = 0; i <= chunkMax; i++) {
            String chunkKey = targetFilename + "." + i + "_" + chunkMax + ".part";

            if (!fileChunks.has(chunk)) {
                error = "Missing chunk: " + chunkKey;
                break;
            }

            JsonObject chunkObj = fileChunks.get(chunkKey).getAsJsonObject();
            String chunkPath = chunkObj.get("filepath").getAsString();
            File sourceFile = new File(chunkPath);
            if (sourceFile.exists()) {
                LogUtil.log(LogUtil.LogType.CMD_UPLOAD, "File exists: " + sourceFile.getPath());
            } else {
                LogUtil.log(LogUtil.LogType.CMD_UPLOAD, "File NOT exists: " + sourceFile.getPath());
                break;
            }

            FileInputStream fis = new FileInputStream(sourceFile);

            //TODO error check range of bytes from each chunk and compare with chunk bytes copied

            /**
             * Append next chunk to the destination file.
             */
            int bytesCopied = OmniFiles.copyFileLeaveOutOpen(fis, destOutputStream);

            totalSize += bytesCopied;

            LogUtil.log(LogUtil.LogType.CMD_UPLOAD, "Bytes copied, total: " + bytesCopied + ", " + totalSize);

            // Delete temp file
            if (!sourceFile.delete()) {
                error = "Delete temp file failed : " + sourceFile.getPath();
                LogUtil.log(LogUtil.LogType.CMD_UPLOAD, error);
                break;
            } else {
                LogUtil.log(LogUtil.LogType.CMD_UPLOAD, "Removed " + sourceFile.getName());
            }
        }
        destOutputStream.flush();
        destOutputStream.close();

        // Done with this file, clean up.
        fileUploads.remove(targetFilename);

        JsonArray added = new JsonArray();
        if (error == null) {
            JsonObject fileObj = FileObj.makeObj(targetVolumeId, destFile, url);
            added.add(fileObj);
            wrapper.add("added", added);
            LogUtil.log(LogUtil.LogType.CMD_UPLOAD, "File upload success: " + destFile.getPath());
        } else {
            JsonArray warning = new JsonArray();
            warning.add(error);
            wrapper.add("warning", warning);
        }

        return getInputStream(wrapper);

    } catch (IOException e) {
        logException(CmdUpload.class, e);
        clearChunkFiles();
    }
    return null;
}

From source file:edu.ku.brc.specify.tasks.AttachmentsTask.java

/**
 * /*  w w w . j  av a 2 s  . c o m*/
 */
private void exportAttachment(final CommandAction cmdAction) {
    exportFile = null;
    Object data = cmdAction.getData();
    if (data instanceof ImageDataItem) {
        ImageDataItem idi = (ImageDataItem) data;
        System.out.println(idi.getImgName());

        String origFilePath = BasicSQLUtils.querySingleObj(
                "SELECT OrigFilename FROM attachment WHERE AttachmentID = " + idi.getAttachmentId());
        if (StringUtils.isNotEmpty(origFilePath)) {
            origFilePath = FilenameUtils.getName(origFilePath);
        } else {
            origFilePath = idi.getTitle();
        }
        String usrHome = System.getProperty("user.home");
        JFileChooser dlg = new JFileChooser(usrHome);
        dlg.setSelectedFile(new File(origFilePath));
        int rv = dlg.showSaveDialog((Frame) UIRegistry.getTopWindow());
        if (rv == JFileChooser.APPROVE_OPTION) {
            File file = dlg.getSelectedFile();
            if (file != null) {
                String fullPath = file.getAbsolutePath();
                String oldExt = FilenameUtils.getExtension(origFilePath);
                String newExt = FilenameUtils.getExtension(fullPath);
                if (StringUtils.isEmpty(newExt) && StringUtils.isNotEmpty(oldExt)) {
                    fullPath += "." + oldExt;
                    exportFile = new File(fullPath);
                } else {
                    exportFile = file;
                }
                boolean isOK = true;
                if (exportFile.exists()) {
                    isOK = UIRegistry.displayConfirmLocalized("ATTCH.FILE_EXISTS", "ATTCH.REPLACE_MSG",
                            "ATTCH.REPLACE", "CANCEL", JOptionPane.QUESTION_MESSAGE);
                }
                if (isOK) {
                    ImageLoader loader = new ImageLoader(idi.getImgName(), idi.getMimeType(), true, -1, this);
                    ImageLoaderExector.getInstance().loadImage(loader);
                }
            }
            System.out.println(file.toPath());
        }
    }
}

From source file:com.alibaba.otter.node.etl.load.loader.db.FileLoadAction.java

private void doMove(FileLoadContext context, File rootDir, FileData fileData) throws IOException {
    boolean isLocal = StringUtils.isBlank(fileData.getNameSpace());
    String entryName = null;/*from w ww  . jav  a 2 s.co  m*/
    if (true == isLocal) {
        entryName = FilenameUtils.getPath(fileData.getPath()) + FilenameUtils.getName(fileData.getPath());
    } else {
        entryName = fileData.getNameSpace() + File.separator + fileData.getPath();
    }
    File sourceFile = new File(rootDir, entryName);
    if (true == sourceFile.exists() && false == sourceFile.isDirectory()) {
        if (false == isLocal) {
            throw new LoadException(fileData + " is not support!");
        } else {
            File targetFile = new File(fileData.getPath());
            // copy to product path
            NioUtils.copy(sourceFile, targetFile, retry);
            if (true == targetFile.exists()) {
                // meta?
                fileData.setSize(sourceFile.length());
                fileData.setLastModifiedTime(sourceFile.lastModified());
                context.getProcessedDatas().add(fileData);
            } else {
                throw new LoadException(String.format("copy/rename [%s] to [%s] failed by unknow reason",
                        sourceFile.getPath(), targetFile.getPath()));
            }

        }

        LoadCounter counter = loadStatsTracker.getStat(context.getIdentity()).getStat(fileData.getPairId());
        counter.getFileCount().incrementAndGet();
        counter.getFileSize().addAndGet(fileData.getSize());
    } else if (fileData.getEventType().isDelete()) {
        // 
        if (false == isLocal) {
            throw new LoadException(fileData + " is not support!");
        } else {
            File targetFile = new File(fileData.getPath());
            if (NioUtils.delete(targetFile, retry)) {
                context.getProcessedDatas().add(fileData);
            } else {
                context.getFailedDatas().add(fileData);
            }
        }
    } else {
        context.getFailedDatas().add(fileData);// 
    }

}

From source file:io.siddhi.extension.io.file.listeners.FileSystemListener.java

private String getFileName(String uri, String protocol) {
    try {//  w ww.j  a v a  2s.co m
        URL url = new URL(String.format("%s%s%s", protocol, File.separator, uri));
        return FilenameUtils.getName(url.getPath());
    } catch (MalformedURLException e) {
        log.error(String.format("Failed to extract file name from the uri '%s'.", uri), e);
        return null;
    }
}

From source file:es.gob.afirma.signers.ooxml.be.fedict.eid.applet.service.signer.AbstractXmlSignatureService.java

private static void addDigestInfosAsReferences(final List<DigestInfo> digestInfos,
        final XMLSignatureFactory signatureFactory, final List<Reference> references)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MalformedURLException {
    if (null == digestInfos) {
        return;/*from  www.  j  a v a 2s .  c om*/
    }
    for (final DigestInfo digestInfo : digestInfos) {
        references.add(signatureFactory.newReference(
                FilenameUtils.getName(new File(digestInfo.getDescription()).toURI().toURL().getFile()),
                signatureFactory.newDigestMethod(getXmlDigestAlgo(digestInfo.getDigestAlgo()), null), null,
                null, null, digestInfo.getDigestValue()));
    }
}