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

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

Introduction

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

Prototype

public static String getExtension(String filename) 

Source Link

Document

Gets the extension of a filename.

Usage

From source file:net.sf.jvifm.util.FileComprator.java

public int compare(File file1, File file2) {
    String file1Ext = FilenameUtils.getExtension(file1.getName());
    String file2Ext = FilenameUtils.getExtension(file2.getName());
    if (file1.isFile() && file2.isDirectory()) {
        if (isReverse)
            return -1;
        return 1;
    }/*  w  ww  .ja  v a  2 s .  c  o  m*/
    if (file1.isDirectory() && file2.isFile()) {
        if (isReverse)
            return 1;
        return -1;
    }
    int result = 0;
    if (isReverse) {
        result = file2Ext.compareTo(file1Ext);
    } else {
        result = file1Ext.compareTo(file2Ext);
    }
    if (result == 0)
        result = 1;
    return result;
}

From source file:eu.edisonproject.training.term.extraction.AprioriExtraction.java

@Override
public Map<String, Double> termXtraction(String inDir) throws IOException {
    try {//w ww  . j  av a  2  s .c o m
        int count = 0;
        HashMap<String, Double> keywordsDictionaray = new HashMap();
        File dir = new File(inDir);

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

        if (dir.isDirectory()) {
            for (File f : dir.listFiles()) {
                if (FilenameUtils.getExtension(f.getName()).endsWith("txt")) {
                    count++;
                    Logger.getLogger(AprioriExtraction.class.getName()).log(Level.INFO, "{0}: {1} of {2}",
                            new Object[] { f.getName(), count, dir.list().length });
                    terms.addAll(extractFromFile(f));
                }
            }
        } else if (dir.isFile()) {
            if (FilenameUtils.getExtension(dir.getName()).endsWith("txt")) {
                terms.addAll(extractFromFile(dir));
            }

        }
        MaxentTagger tagger = new MaxentTagger(taggerPath);
        for (String t : terms) {
            Double tf = 0.0;
            String term = t.toLowerCase().trim().replaceAll(" ", "_").split("/")[0];
            while (term.endsWith("_")) {
                term = term.substring(0, term.lastIndexOf("_"));
            }
            while (term.startsWith("_")) {
                term = term.substring(term.indexOf("_") + 1, term.length());
            }
            String tagged = null;
            //                if (!term.contains("_")) {
            tagged = tagger.tagString(term);
            //                }
            boolean add = true;
            if (tagged != null) {
                if (!tagged.contains("NN") || tagged.contains("RB")) {
                    add = false;
                }
                //                    }
            } else {
                add = true;
            }
            if (add) {
                if (keywordsDictionaray.containsKey(term)) {
                    tf = keywordsDictionaray.get(term);
                    tf++;
                } else {
                    tf = 1.0;
                }
                keywordsDictionaray.put(term, tf);
            }

        }
        return keywordsDictionaray;

    } catch (Exception ex) {
        Logger.getLogger(AprioriExtraction.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

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

@Override
public InputStream go(@NonNull Map<String, String> params) {

    String url = params.get("url");
    String suffix = "~";

    /**/*  w ww  . jav  a  2  s  .c  om*/
     * Params only has the first element of the targets[] array.
     * This is fine if there is only one target but an issue for multiple file operations.
     * Manually parse the query parameter strings to get all targets.
     */
    String[] qps = params.get("queryParameterStrings").split("&");

    JsonArray added = new JsonArray();
    boolean hasFailed = false;
    for (String candidate : qps) {
        if (!candidate.contains("targets")) {
            continue;
        }

        String[] parts = candidate.split("=");

        OmniFile fromFile = new OmniFile(parts[1]);
        String toPath = fromFile.getPath();
        OmniFile toFile = null;
        for (int dupCount = 0; dupCount < 10; dupCount++) { // add no more than 10 tilda
            toFile = new OmniFile(fromFile.getVolumeId(), toPath);

            if (!toFile.exists()) {
                break;
            }

            String extension = FilenameUtils.getExtension(toPath);// add ~ to filename, keep extension
            if (!extension.isEmpty()) {
                extension = "." + extension;
            }
            toPath = FilenameUtils.removeExtension(toPath) + suffix;
            toPath = toPath + extension;
        }
        LogUtil.log(LogUtil.LogType.CMD_DUPLICATE, "file path: " + fromFile.getPath());
        LogUtil.log(LogUtil.LogType.CMD_DUPLICATE, "file exists: " + fromFile.exists());

        boolean success;
        if (fromFile.isDirectory()) {
            success = OmniFiles.copyDirectory(fromFile, toFile);
        } else {
            success = OmniFiles.copyFile(fromFile, toFile);
        }
        /**
         * If there's just only one fail, set this to include warning
         */
        hasFailed = hasFailed || !success;

        /**
         * Duplicate files have a new name, so update the modification time to present
         */
        toFile.setLastModified(System.currentTimeMillis() / 1000);

        if (success) {
            added.add(FileObj.makeObj(toFile, url));// note: full depth of directory not added
        } else {
            LogUtil.log(LogUtil.LogType.CMD_DUPLICATE, "Duplicate failed: " + toFile.getPath());
        }
    }

    JsonObject wrapper = new JsonObject();
    if (hasFailed) {
        JsonArray warning = new JsonArray();
        warning.add("errPerm");
        wrapper.add("warning", warning);
    } else {
        wrapper.add("added", added);
    }

    if (DEBUG) {
        LogUtil.log(LogUtil.LogType.CMD_DUPLICATE, "json result: " + wrapper.toString());
    }

    return getInputStream(wrapper);
}

From source file:de.uzk.hki.da.format.TiffConversionStrategy.java

@Override
public List<Event> convertFile(ConversionInstruction ci) {

    List<Event> resultEvents = new ArrayList<Event>();

    String input = ci.getSource_file().toRegularFile().getAbsolutePath();
    if (getEncoding(input).equals("None"))
        return resultEvents;

    // create subfolder if necessary
    Path.make(object.getPath("newest"), ci.getTarget_folder()).toFile().mkdirs();

    String[] commandAsArray = new String[] { "convert", "+compress", input, generateTargetFilePath(ci) };
    logger.info("Executing conversion command: {}", commandAsArray);
    ProcessInformation pi = CommandLineConnector.runCmdSynchronously(commandAsArray);
    if (pi.getExitValue() != 0) {
        logger.error(// ww  w  . j  av  a  2 s .  c om
                this.getClass() + ": Recieved return code from terminal based command: " + pi.getExitValue());
        throw new RuntimeException("cli conversion failed!\n\nstdOut: ------ \n\n\n" + pi.getStdOut()
                + "\n\n ----- end of stdOut\n\nstdErr: ------ \n\n\n" + pi.getStdErr()
                + "\n\n ----- end of stdErr");
    }

    File result = new File(generateTargetFilePath(ci));

    String baseName = FilenameUtils.getBaseName(result.getAbsolutePath());
    String extension = FilenameUtils.getExtension(result.getAbsolutePath());
    logger.info("Finding files matching wildcard expression \"" + baseName + "*." + extension
            + "\" in order to check them and test if conversion was successful");
    List<File> results = findFilesWithWildcard(new File(FilenameUtils.getFullPath(result.getAbsolutePath())),
            baseName + "*." + extension);

    for (File f : results) {
        DAFile daf = new DAFile(pkg, object.getPath("newest").getLastElement(),
                Utilities.slashize(ci.getTarget_folder()) + f.getName());
        logger.debug("new dafile:" + daf);

        Event e = new Event();
        e.setType("CONVERT");
        e.setDetail(Utilities.createString(commandAsArray));
        e.setSource_file(ci.getSource_file());
        e.setTarget_file(daf);
        e.setDate(new Date());

        resultEvents.add(e);
    }

    return resultEvents;
}

From source file:easycare.web.InfoController.java

private String getRegistrationFormUrlByBrowserLanguage() {
    String registrationFormExtension = FilenameUtils.getExtension(registrationFormUrl);
    String registrationFormName = registrationFormUrl.replace("." + registrationFormExtension, "");
    String languageBrowser = localeResolverSupport.resolveLocale().getLanguage();
    return registrationFormName + "_" + languageBrowser + "." + registrationFormExtension;
}

From source file:com.uas.Files.FilesDAO.java

@Override
public File getUniqueFilename(File file) {
    String baseName = FilenameUtils.getBaseName(file.getName());
    String extension = FilenameUtils.getExtension(file.getName());
    int counter = 1;

    while (file.exists()) {
        file = new File(file.getParent(), baseName + "-" + (counter++) + "." + extension);
    }/*w w w  . j  av  a  2 s.  c  o  m*/
    return file;
}

From source file:gdv.xport.Main.java

/**
 * Hier werden die Optionen "-xml" und "-html" abgehandelt.
 * Die Option "-java" wird seit 0.9 nicht mehr unterstuetzt.
 *
 * @param cmd the cmd/*from w  w w  .j a v  a  2 s  .  c o m*/
 * @param datenpaket the datenpaket
 * @throws IOException Signals that an I/O exception has occurred.
 */
private static void formatDatenpaket(final CommandLine cmd, final Datenpaket datenpaket) throws IOException {
    AbstractFormatter formatter = new NullFormatter(new NullWriter());
    if (cmd.hasOption("xml")) {
        formatter = new XmlFormatter();
    } else if (cmd.hasOption("html")) {
        formatter = new HtmlFormatter();
    }
    if (cmd.hasOption("export")) {
        File file = new File(cmd.getOptionValue("export"));
        if (formatter instanceof NullFormatter) {
            String suffix = FilenameUtils.getExtension(file.getName());
            if ("xml".equalsIgnoreCase(suffix)) {
                formatter = new XmlFormatter();
            } else if ("html".equalsIgnoreCase(suffix)) {
                formatter = new HtmlFormatter();
            }
        }
        OutputStream ostream = new FileOutputStream(file);
        try {
            formatter.setWriter(ostream);
            formatter.write(datenpaket);
        } finally {
            ostream.close();
        }
    } else {
        formatter.write(datenpaket);
    }
}

From source file:ddf.camel.component.catalog.content.ContentProducer.java

@Override
public void process(Exchange exchange)
        throws ContentComponentException, SourceUnavailableException, IngestException {
    LOGGER.debug("ENTERING: process");

    if (!exchange.getPattern().equals(ExchangePattern.InOnly)) {
        return;//  w w  w .  ja v a2 s  . c  o  m
    }

    Message in = exchange.getIn();
    Object body = in.getBody();
    File ingestedFile;

    if (body instanceof GenericFile) {
        GenericFile<File> genericFile = (GenericFile<File>) body;
        ingestedFile = genericFile.getFile();
    } else {
        LOGGER.warn("Unable to cast message body to Camel GenericFile, so unable to process ingested file");
        throw new ContentComponentException(
                "Unable to cast message body to Camel GenericFile, so unable to process ingested file");
    }

    if (ingestedFile == null) {
        LOGGER.debug("EXITING: process - ingestedFile is NULL");
        return;
    }

    String fileExtension = FilenameUtils.getExtension(ingestedFile.getAbsolutePath());

    String mimeType;
    MimeTypeMapper mimeTypeMapper = endpoint.getComponent().getMimeTypeMapper();
    if (mimeTypeMapper != null) {
        try (InputStream inputStream = Files.asByteSource(ingestedFile).openStream()) {
            if (fileExtension.equals("xml")) {
                mimeType = mimeTypeMapper.guessMimeType(inputStream, fileExtension);
            } else {
                mimeType = mimeTypeMapper.getMimeTypeForFileExtension(fileExtension);
            }

        } catch (MimeTypeResolutionException | IOException e) {
            throw new ContentComponentException(e);
        }
    } else {
        LOGGER.error("Did not find a MimeTypeMapper service");
        throw new ContentComponentException(
                "Unable to find a mime type for the ingested file " + ingestedFile.getName());
    }

    LOGGER.debug("Preparing content item for mimeType = {}", mimeType);

    if (StringUtils.isNotEmpty(mimeType)) {
        ContentItem newItem;
        newItem = new ContentItemImpl(Files.asByteSource(ingestedFile), mimeType, ingestedFile.getName(), null);

        LOGGER.debug("Creating content item.");

        CreateStorageRequest createRequest = new CreateStorageRequestImpl(Collections.singletonList(newItem),
                null);

        String attributeOverrideHeaders = (String) exchange.getIn().getHeaders()
                .get(Constants.ATTRIBUTE_OVERRIDES_KEY);
        createRequest.getProperties().put(Constants.ATTRIBUTE_OVERRIDES_KEY,
                createAttributeOverrideMapFromHeaders(attributeOverrideHeaders));

        CreateResponse createResponse = endpoint.getComponent().getCatalogFramework().create(createRequest);
        if (createResponse != null) {
            List<Metacard> createdMetacards = createResponse.getCreatedMetacards();

            if (LOGGER.isDebugEnabled()) {
                for (Metacard metacard : createdMetacards) {
                    LOGGER.debug("content item created with id = {}", metacard.getId());
                }
            }
        }
    } else {
        LOGGER.debug("mimeType is NULL");
        throw new ContentComponentException(
                "Unable to determine mime type for the file " + ingestedFile.getName());
    }

    LOGGER.debug("EXITING: process");
}

From source file:me.kartikarora.transfersh.adapters.FileGridAdapter.java

@Override
public void bindView(View view, final Context context, Cursor cursor) {
    FileItemViewHolder holder = (FileItemViewHolder) view.getTag();
    int nameCol = cursor.getColumnIndex(FilesContract.FilesEntry.COLUMN_NAME);
    int typeCol = cursor.getColumnIndex(FilesContract.FilesEntry.COLUMN_TYPE);
    int sizeCol = cursor.getColumnIndex(FilesContract.FilesEntry.COLUMN_SIZE);
    int urlCol = cursor.getColumnIndex(FilesContract.FilesEntry.COLUMN_URL);
    final String name = cursor.getString(nameCol);
    final String type = cursor.getString(typeCol);
    final String size = cursor.getString(sizeCol);
    final String url = cursor.getString(urlCol);
    holder.fileNameTextView.setText(name);
    String ext = FilenameUtils.getExtension(name);
    int identifier = context.getResources().getIdentifier("t" + ext, "drawable", context.getPackageName());
    try {/*from   w w  w.ja v  a 2s .  co  m*/
        holder.fileTypeImageView
                .setImageDrawable(ResourcesCompat.getDrawable(context.getResources(), identifier, null));
    } catch (Resources.NotFoundException e) {
        e.printStackTrace();
        holder.fileTypeImageView
                .setImageDrawable(ResourcesCompat.getDrawable(context.getResources(), R.drawable.tblank, null));
    }

    holder.fileInfoImageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String message = "Name: " + name + "\n" + "File type: " + type + "\n" + "URL: " + url;
            new AlertDialog.Builder(activity).setMessage(message).setPositiveButton(android.R.string.ok, null)
                    .create().show();
        }
    });

    holder.fileShareImageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            tracker.send(
                    new HitBuilders.EventBuilder().setCategory("Action").setAction("Share : " + url).build());
            context.startActivity(new Intent().setAction(Intent.ACTION_SEND).putExtra(Intent.EXTRA_TEXT, url)
                    .setType("text/plain").addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
        }
    });

    holder.fileDownloadImageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            checkForDownload(name, type, url, view);
        }
    });
}

From source file:net.sf.jvifm.control.MetaCommand.java

public void execute() {

    if (cmd.equals("kill")) {
        CommandRunner commandRunner = CommandRunner.getInstance();
        commandRunner.killCurrentJob();/*  w  ww.j av a 2 s . c  om*/
        return;
    }
    if (cmd.equals("about")) {
        AboutShell aboutShell = new AboutShell();
        aboutShell.showGUI();
    }

    if (cmd.equals("quit")) {
        fileManager.quit();
        return;
    }
    if (cmd.equals("quitall")) {
        Main.exit();
        return;
    }

    if (cmd.equals("hide")) {
        fileManager.hide();
        return;
    }

    if (cmd.equals("only")) {
        fileManager.only();
    }
    if (cmd.equals("split")) {
        fileManager.split();
    }
    /*
     * if (cmd.equals("preview")) {
     * fileManager.getActivePanel().addListener(fileManager);
     * fileManager.getActivePanel().notifyChangeSelection(); } if
     * (cmd.equals("nopreview")) {
     * fileManager.getActivePanel().removeListener(fileManager);
     * fileManager.nopreview(); }
     */

    if (cmd.equals("detail")) {
        fileManager.getActivePanel().detail();
    }
    if (cmd.equals("brief")) {
        fileManager.getActivePanel().brief();
    }

    if (cmd.equals("help")) {
        String EDITOR = Preference.getInstance().getEditorApp();
        String workdir = System.getProperty("user.dir");
        String path = new File(workdir).getParent() + "/doc/help.txt";
        String cmd[] = { EDITOR, path };
        try {
            Runtime.getRuntime().exec(cmd);
        } catch (Exception ex) {
            // ex.printStackTrace(); //if can't open help file with default
            // editor,
            // open it with default application in system
            String ext = FilenameUtils.getExtension(path);
            Program program = Program.findProgram(ext);
            if (program != null)
                program.execute(path);
        }
        return;
    }
    if (cmd.equals("sync")) {
        if (inActiveFileLister != null)
            inActiveFileLister.visit(pwd);
        return;
    }
    if (cmd.equals("conf")) {
        Util.openPreferenceShell(fileManager.getShell());
        return;
    }

    if (cmd.equals("sh")) {
        Util.openTerminal(pwd);
    }
    if (cmd.equals("bookmarks")) {
        fileManager.showBookmarkSidevew();
        fileManager.activeSideView();
    }
    if (cmd.equals("history")) {
        fileManager.showHistorySideview();
        fileManager.activeSideView();
    }
    if (cmd.equals("shortcuts")) {
        fileManager.showShortcutsSideview();
        fileManager.activeSideView();
    }
    if (cmd.equals("folder")) {
        fileManager.showFileTree(FileTree.FS_TREE);
        fileManager.activeSideView();
    }
    if (cmd.equals("locate")) {
        fileManager.locateFolderView();
    }
    if (cmd.equals("bmfolder")) {
        fileManager.showFileTree(FileTree.BM_TREE);
        fileManager.activeSideView();
    }
    if (cmd.equals("hidesidebar")) {
        Main.fileManager.hideSideBar();
    }
}