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:mycontrollers.MyCarController.java

public String submit() {
    //        setCurrent(new Car());
    //        getFacade().create(getCurrent());

    final String fileName = getFile().getName();
    InputStream filecontent;//from ww w .java2s. com
    byte[] bytes = null;
    try {
        filecontent = getFile().getInputStream();
        int read = 0;

        // IOUtils.toByteArray(filecontent); // Apache commons IO.
        getCurrent().setImage(IOUtils.toByteArray(filecontent));

        //while ((read = filecontent.read(current.getImage())) != -1) {
        //            }
        getFacade().edit(getCurrent());
    } catch (IOException ex) {
        Logger.getLogger(MyCarController.class.getName()).log(Level.SEVERE, null, ex);
    }
    setFilename(FilenameUtils.getBaseName(getFile().getSubmittedFileName()));
    setExtension(FilenameUtils.getExtension(getFile().getSubmittedFileName()));
    return "jsfUpload";
}

From source file:com.twosigma.beaker.core.module.elfinder.impl.localfs.LocalFsVolume.java

@Override
public String getMimeType(FsItem fsi) {
    File file = asFile(fsi);//from  ww  w.j  a va  2  s .  co  m
    if (file.isDirectory())
        return "directory";

    String ext = FilenameUtils.getExtension(file.getName());
    if (!ext.isEmpty()) {
        String mimeType = MimeTypesUtils.getMimeType(ext);
        return mimeType == null ? MimeTypesUtils.UNKNOWN_MIME_TYPE : mimeType;
    }

    return MimeTypesUtils.UNKNOWN_MIME_TYPE;
}

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 ww  .  ja  v a2  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:dataMappers.PictureDataMapper.java

public static void addPictureToReport(DBConnector dbconnector, HttpServletRequest request)
        throws FileUploadException, IOException, SQLException {

    if (!ServletFileUpload.isMultipartContent(request)) {
        System.out.println("Invalid upload request");
        return;/* w w  w . java 2  s.co m*/
    }

    // Define limits for disk item
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(THRESHOLD_SIZE);

    // Define limit for servlet upload
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(MAX_REQUEST_SIZE);

    FileItem itemFile = null;
    int reportID = 0;

    // Get list of items in request (parameters, files etc.)
    List formItems = upload.parseRequest(request);
    Iterator iter = formItems.iterator();

    // Loop items
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (!item.isFormField()) {
            itemFile = item; // If not form field, must be item
        } else if (item.getFieldName().equalsIgnoreCase("reportID")) { // else it is a form field
            try {
                System.out.println(item.getString());
                reportID = Integer.parseInt(item.getString());
            } catch (NumberFormatException e) {
                reportID = 0;
            }
        }
    }

    // This will be null if no fields were declared as image/upload.
    // Also, reportID must be > 0
    if (itemFile != null || reportID == 0) {

        try {

            // Create credentials from final vars
            BasicAWSCredentials awsCredentials = new BasicAWSCredentials(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY);

            // Create client with credentials
            AmazonS3 s3client = new AmazonS3Client(awsCredentials);
            // Set region
            s3client.setRegion(Region.getRegion(Regions.EU_WEST_1));

            // Set content length (size) of file
            ObjectMetadata om = new ObjectMetadata();
            om.setContentLength(itemFile.getSize());

            // Get extension for file
            String ext = FilenameUtils.getExtension(itemFile.getName());
            // Generate random filename
            String keyName = UUID.randomUUID().toString() + '.' + ext;

            // This is the actual upload command
            s3client.putObject(new PutObjectRequest(S3_BUCKET_NAME, keyName, itemFile.getInputStream(), om));

            // Picture was uploaded to S3 if we made it this far. Now we insert the row into the database for the report.
            PreparedStatement stmt = dbconnector.getCon()
                    .prepareStatement("INSERT INTO reports_pictures" + "(REPORTID, PICTURE) VALUES (?,?)");

            stmt.setInt(1, reportID);
            stmt.setString(2, keyName);

            stmt.executeUpdate();

            stmt.close();

        } 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());

        } catch (AmazonClientException ace) {

            System.out.println("Caught an AmazonClientException, which " + "means the client encountered "
                    + "an internal error while trying to " + "communicate with S3, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message: " + ace.getMessage());

        }

    }
}

From source file:com.o2d.pkayjava.editor.utils.ImportUtils.java

public static int checkFileTypeByExtension(String path) {
    String ext = FilenameUtils.getExtension(path).toLowerCase();
    if (ext.equals("png")) {
        return TYPE_IMAGE;
    }/*  www .  ja v  a2 s.  c om*/
    if (ext.equals("ttf")) {
        return TYPE_TTF_FONT;
    }
    if (ext.equals("scml")) {
        return TYPE_SPRITER_ANIMATION;
    }
    if (ext.equals("vert") || ext.equals("frag")) {
        return TYPE_SHADER;
    }

    return TYPE_UNCKNOWN;
}

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

private ExportImagePanel(ExportImageConfig inputConfig, Dimension defaultSize) {
    super(inputConfig, defaultSize);
    this.config = inputConfig;

    addCheckBox("Save to clipboard", config.isToClipboard(), new CheckChangedListener() {
        @Override//from   www  . j a  va2s  . c o m
        public void checkChanged(boolean isChecked) {
            ExportImagePanel.this.config.setToClipboard(isChecked);
        }
    });

    addCheckBox("Save to file", config.isToFile(), new CheckChangedListener() {
        @Override
        public void checkChanged(boolean isChecked) {
            ExportImagePanel.this.config.setToFile(isChecked);
            //   updateAppearance();
        }
    });

    addCheckBox("Show viewer", config.isToViewer(), new CheckChangedListener() {
        @Override
        public void checkChanged(boolean isChecked) {
            ExportImagePanel.this.config.setToViewer(isChecked);
            //   updateAppearance();
        }
    });

    FileNameExtensionFilter[] filters = new FileNameExtensionFilter[ImageType.values().length];
    for (int i = 0; i < filters.length; i++) {
        ImageType type = ImageType.values()[i];
        filters[i] = new FileNameExtensionFilter("Image file (" + type.name().toLowerCase() + ")",
                type.name().toLowerCase());
    }
    fileBrowser = new FileBrowserPanel(this.config.getFilename(), new FilenameChangeListener() {

        @Override
        public void filenameChanged(String newFilename) {
            ExportImagePanel.this.config.setFilename(newFilename);
            String ext = FilenameUtils.getExtension(newFilename);
            for (ImageType type : ImageType.values()) {
                if (Strings.equalsStd(ext, type.name())) {
                    imageTypeCombo.getComboBox().setSelectedItem(type);
                    config.setImageType(type);
                    break;
                }
            }
        }
    }, false, "Select file", filters);
    add(fileBrowser);

    validateFilename();
}

From source file:com.ibm.wala.cast.js.nodejs.NodejsRequiredSourceModule.java

@Override
public InputStream getInputStream() {
    String moduleSource = null;//w w  w  .  j a va 2 s.  c o m
    try (final InputStream inputStream = super.getInputStream()) {
        moduleSource = IOUtils.toString(inputStream);
    } catch (IOException e) {
        Assertions.UNREACHABLE(e.getMessage());
    }

    String wrapperSource = null;
    String ext = FilenameUtils.getExtension(getFile().toString()).toLowerCase();
    if (ext.equals("js")) {
        // JS file -> use module wrapper
        wrapperSource = MODULE_WRAPPER_SOURCE;
    } else if (ext.equals("json")) {
        // JSON file -> use JSON wrapper
        wrapperSource = JSON_WRAPPER_SOURCE;
    } else {
        // No clue -> try module wrapper
        System.err.println("NodejsRequiredSourceModule: Unsupported file type (" + ext + "), continue anyway.");
        wrapperSource = MODULE_WRAPPER_SOURCE;
    }

    String wrappedModuleSource = wrapperSource.replace(FILENAME_PLACEHOLDER, getFile().getName())
            .replace(DIRNAME_PLACEHOLDER, getFile().getParent().toString())
            .replace(CODE_PLACEHOLDER, moduleSource);

    return IOUtils.toInputStream(wrappedModuleSource);
}

From source file:it.attocchi.utils.HttpClientUtils.java

public static String getFileNameFromUrl(String url, String paramName) {
    String res = null;/*w  w  w .j  av a2 s .  co  m*/

    String baseName = "";
    String extension = "";
    if (paramName == null || paramName.isEmpty()) {
        baseName = FilenameUtils.getBaseName(url);
        extension = FilenameUtils.getExtension(url);

        res = FilenameUtils.getName(url);

    } else {
        String fileNameOnParam = null;
        List<NameValuePair> params = URLEncodedUtils.parse(url, Charset.defaultCharset());
        if (params != null)
            for (NameValuePair p : params) {
                if (p.getName().contains(paramName)) {
                    fileNameOnParam = p.getValue();
                    break;
                }
            }
        baseName = FilenameUtils.getBaseName(fileNameOnParam);
        extension = FilenameUtils.getExtension(fileNameOnParam);

        res = FilenameUtils.getName(fileNameOnParam);
    }

    return res;
}

From source file:net.sf.jooreports.web.spring.controller.AbstractDocumentGenerator.java

private void renderDocument(Object model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    DocumentConverter converter = (DocumentConverter) getApplicationContext().getBean("documentConverter");
    DocumentFormatRegistry formatRegistry = (DocumentFormatRegistry) getApplicationContext()
            .getBean("documentFormatRegistry");
    String outputExtension = FilenameUtils.getExtension(request.getRequestURI());
    DocumentFormat outputFormat = formatRegistry.getFormatByFileExtension(outputExtension);
    if (outputFormat == null) {
        throw new ServletException("unsupported output format: " + outputExtension);
    }/* w  ww.ja v a 2 s .  c  om*/
    File templateFile = null;
    String documentName = FilenameUtils.getBaseName(request.getRequestURI());
    Resource templateDirectory = getTemplateDirectory(documentName);
    if (templateDirectory.exists()) {
        templateFile = templateDirectory.getFile();
    } else {
        templateFile = getTemplateFile(documentName).getFile();
        if (!templateFile.exists()) {
            throw new ServletException("template not found: " + documentName);
        }
    }

    DocumentTemplateFactory documentTemplateFactory = new DocumentTemplateFactory();
    DocumentTemplate template = documentTemplateFactory.getTemplate(templateFile);

    ByteArrayOutputStream odtOutputStream = new ByteArrayOutputStream();
    try {
        template.createDocument(model, odtOutputStream);
    } catch (DocumentTemplateException exception) {
        throw new ServletException(exception);
    }
    response.setContentType(outputFormat.getMimeType());
    response.setHeader("Content-Disposition",
            "inline; filename=" + documentName + "." + outputFormat.getFileExtension());

    if ("odt".equals(outputFormat.getFileExtension())) {
        // no need to convert
        response.getOutputStream().write(odtOutputStream.toByteArray());
    } else {
        ByteArrayInputStream odtInputStream = new ByteArrayInputStream(odtOutputStream.toByteArray());
        DocumentFormat inputFormat = formatRegistry.getFormatByFileExtension("odt");
        converter.convert(odtInputStream, inputFormat, response.getOutputStream(), outputFormat);
    }
}

From source file:be.fedict.eid.dss.sp.servlet.UploadServlet.java

@Override
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    LOG.debug("doPost");

    String fileName = null;//from  ww  w. j a v a  2 s . c o  m
    String contentType;
    byte[] document = null;

    FileItemFactory factory = new DiskFileItemFactory();
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // Parse the request
    try {
        List<FileItem> items = upload.parseRequest(request);
        if (!items.isEmpty()) {
            fileName = items.get(0).getName();
            // contentType = items.get(0).getContentType();
            document = items.get(0).get();
        }
    } catch (FileUploadException e) {
        throw new ServletException(e);
    }

    String extension = FilenameUtils.getExtension(fileName).toLowerCase();
    contentType = supportedFileExtensions.get(extension);
    if (null == contentType) {
        /*
         * Unsupported content-type is converted to a ZIP container.
         */
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
        ZipEntry zipEntry = new ZipEntry(fileName);
        zipOutputStream.putNextEntry(zipEntry);
        IOUtils.write(document, zipOutputStream);
        zipOutputStream.close();
        fileName = FilenameUtils.getBaseName(fileName) + ".zip";
        document = outputStream.toByteArray();
        contentType = "application/zip";
    }

    LOG.debug("File name: " + fileName);
    LOG.debug("Content Type: " + contentType);

    String signatureRequest = new String(Base64.encode(document));

    request.getSession().setAttribute(DOCUMENT_SESSION_ATTRIBUTE, document);
    request.getSession().setAttribute("SignatureRequest", signatureRequest);
    request.getSession().setAttribute("ContentType", contentType);

    response.sendRedirect(request.getContextPath() + this.postPage);
}