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:com.mycompany.mytubeaws.UploadServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*  ww w.ja  va2 s .  c  o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String result = "";
    String fileName = null;

    boolean uploaded = false;

    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory(); // sets memory threshold - beyond which files are stored in disk
    factory.setSizeThreshold(1024 * 1024 * 3); // 3mb
    factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); // sets temporary location to store files

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(1024 * 1024 * 40); // sets maximum size of upload file
    upload.setSizeMax(1024 * 1024 * 50); // sets maximum size of request (include file + form data)

    try {
        List<FileItem> formItems = upload.parseRequest(request); // parses the request's content to extract file data

        if (formItems != null && formItems.size() > 0) // iterates over form's fields
        {
            for (FileItem item : formItems) // processes only fields that are not form fields
            {
                if (!item.isFormField()) {
                    fileName = item.getName();
                    UUID id = UUID.randomUUID();
                    fileName = FilenameUtils.getBaseName(fileName) + "_ID-" + id.toString() + "."
                            + FilenameUtils.getExtension(fileName);

                    File file = File.createTempFile("aws-java-sdk-upload", "");
                    item.write(file); // write form item to file (?)

                    if (file.length() == 0)
                        throw new RuntimeException("No file selected or empty file uploaded.");

                    try {
                        s3.putObject(new PutObjectRequest(bucketName, fileName, file));
                        result += "File uploaded successfully; ";
                        uploaded = true;
                    } catch (AmazonServiceException ase) {
                        System.out.println("Caught an AmazonServiceException, which means your request made it "
                                + "to Amazon S3, but was rejected with an error response for some reason.");
                        System.out.println("Error Message:    " + ase.getMessage());
                        System.out.println("HTTP Status Code: " + ase.getStatusCode());
                        System.out.println("AWS Error Code:   " + ase.getErrorCode());
                        System.out.println("Error Type:       " + ase.getErrorType());
                        System.out.println("Request ID:       " + ase.getRequestId());

                        result += "AmazonServiceException thrown; ";
                    } catch (AmazonClientException ace) {
                        System.out
                                .println("Caught an AmazonClientException, which means the client encountered "
                                        + "a serious internal problem while trying to communicate with S3, "
                                        + "such as not being able to access the network.");
                        System.out.println("Error Message: " + ace.getMessage());

                        result += "AmazonClientException thrown; ";
                    }

                    file.delete();
                }
            }
        }
    } catch (Exception ex) {
        result += "Generic exception: '" + ex.getMessage() + "'; ";
        ex.printStackTrace();
    }

    if (fileName != null && uploaded)
        result += "Generated file ID: " + fileName;

    System.out.println(result);

    request.setAttribute("resultText", result);
    request.getRequestDispatcher("/UploadResult.jsp").forward(request, response);
}

From source file:com.rubinefocus.admin.servlet.UploadServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*w w w. j a  va  2 s  .com*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //processRequest(request, response);
    try {
        PrintWriter out = response.getWriter();

        File f = new File(this.getServletContext().getRealPath("/admin/assets/images/adminPic"));
        String savePath = f.getPath();
        savePath = savePath.replace("%20", " ");
        savePath = savePath.replace("build", "");
        String fileName = "";

        for (Part part : request.getParts()) {
            fileName = extractFileName(part);
            fileName = fileName.replace(" ", "");
            fileName = fileName.replace("-", "");
            fileName = fileName.replace(":", "");

            File file = new File(savePath + "/" + fileName);
            if (file.exists()) {
                String fileNameWithOutExt = FilenameUtils.removeExtension(fileName);
                String ext = FilenameUtils.getExtension(fileName);
                fileName = fileNameWithOutExt + new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").format(new Date())
                        + "." + ext;
                fileName = fileName.replace(" ", "");
                fileName = fileName.replace("-", "");
                fileName = fileName.replace(":", "");
                part.write(savePath + File.separator + fileName);
            } else {

                part.write(savePath + File.separator + fileName);
            }

        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.simpligility.maven.provisioner.MavenRepositoryHelper.java

public void deployToRemote(String targetUrl, String username, String password) {
    // Using commons-io, if performance or so is a problem it might be worth looking at the Java 8 streams API
    // e.g. http://blog.jooq.org/2014/01/24/java-8-friday-goodies-the-new-new-io-apis/
    // not yet though..
    Collection<File> subDirectories = FileUtils.listFilesAndDirs(repositoryPath,
            (IOFileFilter) DirectoryFileFilter.DIRECTORY, TrueFileFilter.INSTANCE);
    Collection<File> leafDirectories = new ArrayList<File>();
    for (File subDirectory : subDirectories) {
        if (isLeafVersionDirectory(subDirectory)) {

            leafDirectories.add(subDirectory);
        }//from w w w  .j a  va  2s. co  m
    }
    for (File leafDirectory : leafDirectories) {
        String leafAbsolutePath = leafDirectory.getAbsoluteFile().toString();
        int repoAbsolutePathLength = repositoryPath.getAbsoluteFile().toString().length();
        String leafRepoPath = leafAbsolutePath.substring(repoAbsolutePathLength + 1, leafAbsolutePath.length());

        Gav gav = GavUtil.getGavFromRepositoryPath(leafRepoPath);

        // only interested in files using the artifactId-version* pattern
        // don't bother with .sha1 files
        IOFileFilter fileFilter = new AndFileFilter(
                new WildcardFileFilter(gav.getArtifactId() + "-" + gav.getVersion() + "*"),
                new NotFileFilter(new SuffixFileFilter("sha1")));
        Collection<File> artifacts = FileUtils.listFiles(leafDirectory, fileFilter, null);

        Authentication auth = new AuthenticationBuilder().addUsername(username).addPassword(password).build();

        RemoteRepository distRepo = new RemoteRepository.Builder("repositoryIdentifier", "default", targetUrl)
                .setAuthentication(auth).build();

        DeployRequest deployRequest = new DeployRequest();
        deployRequest.setRepository(distRepo);
        for (File file : artifacts) {
            String extension;
            if (file.getName().endsWith("tar.gz")) {
                extension = "tar.gz";
            } else {
                extension = FilenameUtils.getExtension(file.getName());
            }

            String baseFileName = gav.getFilenameStart() + "." + extension;
            String fileName = file.getName();
            String g = gav.getGroupdId();
            String a = gav.getArtifactId();
            String v = gav.getVersion();

            Artifact artifact = null;
            if (gav.getPomFilename().equals(fileName)) {
                artifact = new DefaultArtifact(g, a, "pom", v);
            } else if (gav.getJarFilename().equals(fileName)) {
                artifact = new DefaultArtifact(g, a, "jar", v);
            } else if (gav.getSourceFilename().equals(fileName)) {
                artifact = new DefaultArtifact(g, a, "sources", "jar", v);
            } else if (gav.getJavadocFilename().equals(fileName)) {
                artifact = new DefaultArtifact(g, a, "javadoc", "jar", v);
            } else if (baseFileName.equals(fileName)) {
                artifact = new DefaultArtifact(g, a, extension, v);
            } else {
                String classifier = file.getName().substring(gav.getFilenameStart().length() + 1,
                        file.getName().length() - ("." + extension).length());
                artifact = new DefaultArtifact(g, a, classifier, extension, v);
            }

            if (artifact != null) {
                artifact = artifact.setFile(file);
                deployRequest.addArtifact(artifact);
            }

        }

        try {
            system.deploy(session, deployRequest);
        } catch (Exception e) {
            logger.info("Deployment failed with " + e.getMessage() + ", artifact might be deployed already.");
        }
    }
}

From source file:com.opendoorlogistics.studio.components.map.plugins.snapshot.ExportImagePanel.java

protected void validateFilename() {
    String filename = config.getFilename();
    if (filename.length() > 0 && config.getImageType() != null) {
        //   ImageType type = config.getImageType();
        if (config.getImageType() != null) {
            String ext = FilenameUtils.getExtension(filename);
            if (Strings.equalsStd(ext, config.getImageType().name()) == false) {
                filename = FilenameUtils.removeExtension(filename);
                filename += "." + config.getImageType().name().toLowerCase();
                fileBrowser.setFilename(filename);
                config.setFilename(filename);
            }/*  w w  w  . j a  v  a2s . co m*/
        }
    }

}

From source file:ch.unibas.charmmtools.gui.step1.mdAssistant.CHARMM_GUI_InputAssistant.java

public CHARMM_GUI_InputAssistant(RunCHARMMWorkflow chWflow, List<File> flist) {
    super(title, chWflow);

    logger.info("Creating a new instance of CHARMM_GUI_InputAssistant with a list<File> as parameter.");

    for (File f : flist) {
        String path = f.getAbsolutePath();
        String ext = FilenameUtils.getExtension(path);

        logger.info("File " + path + " is of type '" + ext + "' ");

        switch (ext) {
        case "xyz":
            textfield_COR_gas.setText(convertWithBabel(f).getAbsolutePath());
            COR_selected_gas = true;//from   ww w.j ava  2s  . c o  m
            logger.info("xyz override detected ; converting to a CHARMM compatible format");
            break;
        case "lpun":
            textfield_LPUN.setText(path);
            LPUN_selected = true;
            logger.info("lpun override detected");
            break;
        default:
            break;
        }
    }

    autoFilledLabel.setVisible(true);
}

From source file:edu.si.services.beans.edansidora.IdsPushBean.java

public void createAndPush(Exchange exchange) throws EdanIdsException {

    try {//from www. j  a  v a  2  s  .  c o m
        out = exchange.getIn();

        inputLocation = new File(out.getHeader("CamelFileAbsolutePath", String.class));
        // get a list of files from current directory
        if (inputLocation.isFile()) {
            inputLocation = inputLocation.getParentFile();
            LOG.debug("Input File Location: " + inputLocation);
        }

        deploymentId = out.getHeader("SiteId", String.class);

        String assetName = "ExportEmammal_emammal_image_" + deploymentId;
        String pushDirPath = pushLocation + "/" + assetName + "/";
        File assetXmlFile = new File(pushDirPath + assetName + ".xml");
        if (!assetXmlFile.getParentFile().exists()) {
            assetXmlFile.getParentFile().mkdirs();
        } else {
            LOG.warn("IDS files for deployment: {} already exists!!", deploymentId);
        }

        LOG.debug("IDS Write Asset Files to: {}", assetXmlFile);
        LOG.debug("IDS inputLocation = {}", inputLocation);
        LOG.debug("IDS deploymentId = {}", deploymentId);

        File files[] = inputLocation.listFiles();

        LOG.debug("Input file list: " + Arrays.toString(files));

        int completed = 0;

        StringBuilder assetXml = new StringBuilder();
        assetXml.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n<Assets>");

        try (BufferedWriter writer = new BufferedWriter(new FileWriter(assetXmlFile))) {

            for (int i = 0; i < files.length; i++) {

                String fileName = files[i].getName();

                LOG.debug("Started file: {} has ext = {}", files[i], FilenameUtils.getExtension(fileName));

                // Do not include the manifest file
                if (!FilenameUtils.getExtension(fileName).contains("xml")
                        && !ignored.containsKey(FilenameUtils.getBaseName(fileName))) {

                    LOG.debug("Adding File {}", fileName);

                    File sourceImageFile = new File(files[i].getPath());
                    File destImageFile = new File(pushDirPath + "emammal_image_" + fileName);

                    LOG.debug("Copying image asset from {} to {}", sourceImageFile, destImageFile);
                    FileUtils.copyFile(sourceImageFile, destImageFile);

                    assetXml.append("\r\n  <Asset Name=\"");
                    assetXml.append(FilenameUtils.getName(destImageFile.getPath()));
                    assetXml.append(
                            "\" IsPublic=\"Yes\" IsInternal=\"No\" MaxSize=\"3000\" InternalMaxSize=\"4000\">");
                    assetXml.append(FilenameUtils.getBaseName(destImageFile.getPath()));
                    assetXml.append("</Asset>");
                } else {
                    LOG.debug("Deployment Manifest XML Found! Skipping {}", files[i]);
                }
            }
            assetXml.append("\r\n</Assets>");

            writer.write(assetXml.toString());

            LOG.info("Completed: {} of {}, Wrote Asset XML File to: {}", completed++, files.length,
                    assetXmlFile);
            out.setHeader("idsPushDir", assetXmlFile.getParent());
        } catch (Exception e) {
            throw new EdanIdsException("IdsPushBean error during createAndPush", e);
        }
    } catch (Exception e) {
        throw new EdanIdsException(e);
    }
}

From source file:eu.matejkormuth.crawler2.Document.java

/**
 * Returns extension of this document. Beware that this can returns empty
 * string for index documents with URL like <code>example.com/page/</code>.
 * /*www.  j  a  va 2  s .co  m*/
 * @return extension of this document (file)
 */
public String getExtension() {
    return FilenameUtils.getExtension(this.url.toString());
}

From source file:io.fabric8.maven.core.service.openshift.ImageStreamService.java

private File writeImageStreams(File target, KubernetesList entity) throws MojoExecutionException, IOException {
    final File targetWithoutExt;
    final ResourceFileType type;
    String ext = "";
    try {//ww  w. j a va2s .c o  m
        ext = FilenameUtils.getExtension(target.getPath());
        type = ResourceFileType.fromExtension(ext);
        String p = target.getAbsolutePath();
        targetWithoutExt = new File(p.substring(0, p.length() - ext.length() - 1));
    } catch (IllegalArgumentException exp) {
        throw new MojoExecutionException(String.format(
                "Invalid extension '%s' for ImageStream target file '%s'. Allowed extensions: yml, json", ext,
                target.getPath()), exp);
    }
    return KubernetesResourceUtil.writeResource(entity, targetWithoutExt, type);
}

From source file:com.igormaznitsa.sciareto.ui.editors.PictureViewer.java

@Override
public boolean saveDocument() throws IOException {
    boolean result = false;
    final File docFile = this.title.getAssociatedFile();
    if (docFile != null) {
        final String ext = FilenameUtils.getExtension(docFile.getName()).trim().toLowerCase(Locale.ENGLISH);
        if (SUPPORTED_FORMATS.contains(ext)) {
            try {
                ImageIO.write(this.image, ext, docFile);
                result = true;//from ww w  . j  ava 2s . com
            } catch (Exception ex) {
                if (ex instanceof IOException) {
                    throw (IOException) ex;
                }
                throw new IOException("Can't write image", ex);
            }
        } else {
            try {
                LOGGER.warn("unsupported image format, will be saved as png : " + ext);
                ImageIO.write(this.image, "png", docFile);
                result = true;
            } catch (Exception ex) {
                if (ex instanceof IOException) {
                    throw (IOException) ex;
                }
                throw new IOException("Can't write image", ex);
            }
        }
    }
    return result;
}

From source file:com.stanley.captioner.MainFrame.java

private Object[] getVideoInfo(File file) {
    String path = file.getAbsolutePath();
    Converter converter = new Converter();
    FFprobe ffprobe = null;//w  w w  . j  av a 2s  .  co  m
    try {
        ffprobe = new FFprobe(converter.getFFprobePath());
    } catch (IOException e) {
        System.out.println("Failed to find ffprobe.");
    }

    FFmpegProbeResult probeResult = null;
    try {
        probeResult = ffprobe.probe(path);
    } catch (IOException e) {
        System.out.println("Failed to probe video file.");
    }

    FFmpegFormat format = probeResult.getFormat();
    FFmpegStream stream = probeResult.getStreams().get(0);

    String type = FilenameUtils.getExtension(path).toUpperCase();
    String size = NumberFormat.getNumberInstance(Locale.US).format(file.length() / 1000) + " KB";

    long millis = stream.duration_ts * 1000;
    TimeZone tz = TimeZone.getTimeZone("UTC");
    SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
    df.setTimeZone(tz);
    String duration = df.format(new Date(millis));

    return new Object[] { format.filename, type, size, duration, stream.codec_name, stream.width,
            stream.height };
}