Example usage for javax.activation MimetypesFileTypeMap MimetypesFileTypeMap

List of usage examples for javax.activation MimetypesFileTypeMap MimetypesFileTypeMap

Introduction

In this page you can find the example usage for javax.activation MimetypesFileTypeMap MimetypesFileTypeMap.

Prototype

public MimetypesFileTypeMap() 

Source Link

Document

The default constructor.

Usage

From source file:eu.planets_project.tb.gui.backing.data.DigitalObjectTreeNode.java

/**
 * @return//from   w ww . java  2s .c  o  m
 */
public String getMimeType() {
    String mimetype = null;

    // Lookup in this:
    MimetypesFileTypeMap mimeMap = new MimetypesFileTypeMap();
    // Ensure the image/png mapping is present, as it appears to be broken in Java 6
    // See http://furiouspurpose.blogspot.com/2009/01/what-does-java-6-have-against-imagepng.html
    mimeMap.addMimeTypes("image/png png");

    // Based only on URI:
    if (getUri() != null)
        mimetype = mimeMap.getContentType(getUri().getPath());

    // Return this if it worked.
    if (mimetype != null)
        return mimetype;

    // Otherwise, inspect content of the Digital Object: Title:
    if (getDob() != null && getDob().getTitle() != null)
        mimetype = mimeMap.getContentType(getDob().getTitle());

    return mimetype;
}

From source file:org.zilverline.core.ExtractorFactory.java

/**
 * Get the MIME-type of a given file.//from w w  w  .j ava2  s .c  o m
 * 
 * @param f the File
 * @return the MIME-type of String
 */
public static String getMimeType(final File f) {
    String type = new MimetypesFileTypeMap().getContentType(f);
    if ("application/octet-stream".equalsIgnoreCase(type)) {
        try {
            Magic parser = new Magic();
            // getMagicMatch accepts Files or byte[],
            // which is nice if you want to test streams
            MagicMatch match = parser.getMagicMatch(f);
            return match.getMimeType();
        } catch (MagicParseException e) {
            log.warn("Can't parse " + f.getName(), e);
        } catch (MagicMatchNotFoundException e) {
            log.warn("Can't find type for " + f.getName(), e);
        } catch (MagicException e) {
            log.warn("Can't find type for " + f.getName(), e);
        }
    }
    return type;
}

From source file:org.sakaiproject.importer.impl.handlers.ResourcesHandler.java

public void handle(Importable thing, String siteId) {
    if (canHandleType(thing.getTypeName())) {
        final String currentUser = sessionManager.getCurrentSessionUserId();
        securityService.pushAdvisor(new SecurityAdvisor() {
            public SecurityAdvice isAllowed(String userId, String function, String reference) {
                if ((userId != null) && (userId.equals(currentUser))
                        && (("content.new".equals(function)) || ("content.read".equals(function)))) {
                    return SecurityAdvice.ALLOWED;
                }//from   w  w w  .ja v a 2 s  .co  m
                return SecurityAdvice.PASS;
            }
        });
        String id = null;
        String contentType = null;
        int notifyOption = NotificationService.NOTI_NONE;
        String title = null;
        String description = null;
        Map resourceProps = new HashMap();

        InputStream contents = null;
        if ("sakai-file-resource".equals(thing.getTypeName())) {
            //title = ((FileResource)thing).getTitle();
            description = ((FileResource) thing).getDescription();
            String fileName = ((FileResource) thing).getFileName();
            id = contentHostingService.getSiteCollection(siteId);

            String contextPath = ((FileResource) thing).getDestinationResourcePath();
            if (contextPath != null && (contextPath.length() + id.length()) > 255) {
                // leave at least 14 characters at end for uniqueness
                contextPath = contextPath.substring(0, (255 - 14 - id.length()));
                // add a timestamp to differentiate it (+14 chars)
                Format f = new SimpleDateFormat("yyyyMMddHHmmss");
                contextPath += f.format(new Date());
                // total new length of 32 chars
            }

            id = id + contextPath;
            contentType = new MimetypesFileTypeMap().getContentType(fileName);
            contents = ((FileResource) thing).getInputStream();
            //            if((title == null) || (title.equals(""))) {
            //               title = fileName;
            //            }
            title = fileName;
            resourceProps.put(ResourceProperties.PROP_DESCRIPTION, description);

            if (title.toLowerCase().endsWith(".zip")) {

                //create a folder with the name of the zip, minus the .zip
                String container = title.substring(0, title.length() - 4);
                resourceProps.put(ResourceProperties.PROP_DISPLAY_NAME, container);

                //get the full path to the current folder
                String path = id.substring(0, id.length() - title.length());

                addContentCollection(path + container, resourceProps);
                addAllResources(contents, path + container, notifyOption);

            } else {
                if (m_log.isDebugEnabled()) {
                    m_log.debug("import ResourcesHandler about to add file entitled '" + title + "'");
                }
                resourceProps.put(ResourceProperties.PROP_DISPLAY_NAME, title);
                addContentResource(id, contentType, contents, resourceProps, notifyOption);
            }

        } else if ("sakai-web-link".equals(thing.getTypeName())) {
            title = ((WebLink) thing).getTitle();
            description = ((WebLink) thing).getDescription();
            id = contentHostingService.getSiteCollection(siteId) + thing.getContextPath();
            contentType = ResourceProperties.TYPE_URL;
            String absoluteUrl = "";
            if (((WebLink) thing).isAbsolute()) {
                absoluteUrl = ((WebLink) thing).getUrl();
            } else {
                absoluteUrl = serverConfigurationService.getServerUrl() + "/access/content"
                        + contentHostingService.getSiteCollection(siteId) + ((WebLink) thing).getUrl();
            }
            contents = new ByteArrayInputStream(absoluteUrl.getBytes());
            if ((title == null) || (title.equals(""))) {
                title = ((WebLink) thing).getUrl();
            }
            resourceProps.put(ResourceProperties.PROP_DISPLAY_NAME, title);
            resourceProps.put(ResourceProperties.PROP_DESCRIPTION, description);
            resourceProps.put(ResourceProperties.PROP_HAS_CUSTOM_SORT, Boolean.TRUE.toString());
            resourceProps.put(ResourceProperties.PROP_CONTENT_PRIORITY,
                    Integer.toString(((WebLink) thing).getSequenceNum()));
            if (m_log.isDebugEnabled()) {
                m_log.debug("import ResourcesHandler about to add web link entitled '" + title + "'");
            }
            ContentResource contentResource = addContentResource(id, contentType, contents, resourceProps,
                    notifyOption);
            if (contentResource != null) {
                try {
                    ContentResourceEdit cre = contentHostingService.editResource(contentResource.getId());
                    cre.setResourceType(ResourceType.TYPE_URL);
                    contentHostingService.commitResource(cre, notifyOption);

                } catch (Exception e1) {
                    m_log.error("import ResourcesHandler tried to set Resource Type of web link and failed",
                            e1);
                }
            }

        } else if ("sakai-html-document".equals(thing.getTypeName())) {
            title = ((HtmlDocument) thing).getTitle();
            contents = new ByteArrayInputStream(((HtmlDocument) thing).getContent().getBytes());
            id = contentHostingService.getSiteCollection(siteId) + thing.getContextPath();
            contentType = "text/html";
            resourceProps.put(ResourceProperties.PROP_DISPLAY_NAME, title);
            if (m_log.isDebugEnabled()) {
                m_log.debug("import ResourcesHandler about to add html document entitled '" + title + "'");
            }
            addContentResource(id, contentType, contents, resourceProps, notifyOption);
        } else if ("sakai-text-document".equals(thing.getTypeName())) {
            title = ((TextDocument) thing).getTitle();
            contents = new ByteArrayInputStream(((TextDocument) thing).getContent().getBytes());
            id = contentHostingService.getSiteCollection(siteId) + thing.getContextPath();
            contentType = "text/plain";
            resourceProps.put(ResourceProperties.PROP_DISPLAY_NAME, title);
            if (m_log.isDebugEnabled()) {
                m_log.debug("import ResourcesHandler about to add text document entitled '" + title + "'");
            }
            addContentResource(id, contentType, contents, resourceProps, notifyOption);
        } else if ("sakai-folder".equals(thing.getTypeName())) {
            title = ((Folder) thing).getTitle();
            description = ((Folder) thing).getDescription();
            resourceProps.put(ResourceProperties.PROP_DISPLAY_NAME, title);
            resourceProps.put(ResourceProperties.PROP_DESCRIPTION, description);
            resourceProps.put(ResourceProperties.PROP_COPYRIGHT, COPYRIGHT);
            /*
             * Added title to the end of the path. Otherwise, we're setting the props on the 
             * containing folder rather than the folder itself.
             */
            String path = contentHostingService.getSiteCollection(siteId) + ((Folder) thing).getPath();
            addContentCollection(path, resourceProps);

        }
        securityService.popAdvisor();
    }

}

From source file:org.esupportail.portlet.filemanager.beans.JsTreeFile.java

public JsTreeFile(String title, String id, String type) {
    this.title = title;
    this.lid = id;
    this.type = type;
    this.state = "closed";
    this.overSizeLimit = false;

    //Added for GIP Recia : Initialize mime type map
    //Do we need to initialize the static mimeMap?  Don't enter the potentially slow sync block unless we have to
    if (mimeMap == null) {
        //Make sure there are no other JsTreeFiles in the constructor at the same time
        synchronized (this) {
            //In the rare cases that there was a 2nd JsTreeFile constructor waiting to enter this block, put another if
            if (mimeMap == null) {
                InputStream is = this.getClass().getResourceAsStream("/mime.types");
                //if we have the mime.types file defined, use it, otherwise, fallback on the system defaults
                mimeMap = (is == null) ? new MimetypesFileTypeMap() : new MimetypesFileTypeMap(is);
            }//ww  w . ja va2  s .co  m
        }
    }
}

From source file:org.talend.components.service.rest.impl.PropertiesControllerImpl.java

@Override
public ResponseEntity<InputStreamResource> getIcon(String definitionName, DefinitionImageType imageType) {
    notNull(definitionName, "Definition name cannot be null.");
    notNull(imageType, "Definition image type cannot be null.");
    final Definition<?> definition = propertiesHelpers.getDefinition(definitionName);
    notNull(definition, "Could not find definition of name %s", definitionName);

    // Undefined and missing icon resources are simply 404.
    String imagePath = definition.getImagePath(imageType);
    if (imagePath == null) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }/*from ww  w  . j  a  v  a2 s  . c o m*/
    InputStream is = definition.getClass().getResourceAsStream(imagePath);
    if (is == null) {
        log.info("The image type %s should exist for %s at %s, but is missing. "
                + "The component should provide this resource.", imageType, definitionName, imagePath);
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    // At this point, we have enough information for a correct response.
    ResponseEntity.BodyBuilder response = ResponseEntity.ok();

    // Add the content type if it can be determined.
    MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
    String contentType = mimeTypesMap.getContentType(imagePath);
    if (contentType != null) {
        response = response.contentType(MediaType.parseMediaType(contentType));
    }

    return response.body(new InputStreamResource(is));
}

From source file:org.estatio.dscm.services.SyncService.java

@Programmatic
public void importAssetsAndCreatePlaylist() {
    final String path = properties.get("dscm.server.path");
    Publisher publisher = publishers.allPublishers().get(0);

    for (Playlist playlist : playlists.allPlaylists()) {
        playlist.removeAllItems();//  w  ww . j  av  a2 s .  co  m
    }

    for (Asset asset : assets.allAssets()) {
        asset.doRemove();
    }

    for (File file : filesForFolder(path.concat("/assets"))) {
        Asset asset = assets.findAssetByName(file.getName());
        if (asset == null) {
            try {
                InputStream is;
                is = new FileInputStream(file);
                final String mimeType = new MimetypesFileTypeMap().getContentType(file);
                Blob blob = new Blob(file.getName(), mimeType, IOUtils.toByteArray(is));
                asset = assets.newAsset(blob, publisher, null, clockService.now(), null, null);
                for (Playlist playlist : playlists.allPlaylists()) {
                    playlist.newItem(asset);
                }
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

From source file:org.bonitasoft.forms.server.ApplicationResourceServlet.java

/**
 * {@inheritDoc}/*from w w w .j a va  2  s. c  om*/
 */
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException {

    final String processUUIDStr = request.getParameter(PROCESS_ID_PARAM);
    final String resourcePath = request.getParameter(RESOURCE_PATH_PARAM);
    String resourceFileName = null;
    byte[] content = null;
    String contentType = null;
    if (resourcePath == null) {
        final String errorMessage = "Error while using the servlet ApplicationResourceServlet to get a resource: the parameter "
                + RESOURCE_PATH_PARAM + " is undefined.";
        if (LOGGER.isLoggable(Level.SEVERE)) {
            LOGGER.log(Level.SEVERE, errorMessage);
        }
        throw new ServletException(errorMessage);
    }
    if (processUUIDStr == null) {
        final String errorMessage = "Error while using the servlet ApplicationResourceServlet to get a resource: the parameter "
                + PROCESS_ID_PARAM + " is undefined.";
        if (LOGGER.isLoggable(Level.SEVERE)) {
            LOGGER.log(Level.SEVERE, errorMessage);
        }
        throw new ServletException(errorMessage);
    }
    try {
        final long tenantID = getTenantID(request);
        final File processDir = new File(WebBonitaConstantsUtils.getInstance(tenantID).getFormsWorkFolder(),
                processUUIDStr);
        if (processDir.exists()) {
            final File[] directories = processDir.listFiles(new FileFilter() {

                @Override
                public boolean accept(final File pathname) {
                    return pathname.isDirectory();
                }
            });
            long lastDeployementDate = 0L;
            for (final File directory : directories) {
                try {
                    final long deployementDate = Long.parseLong(directory.getName());
                    if (deployementDate > lastDeployementDate) {
                        lastDeployementDate = deployementDate;
                    }
                } catch (final Exception e) {
                    if (LOGGER.isLoggable(Level.WARNING)) {
                        LOGGER.log(Level.WARNING,
                                "Process application resources deployment folder contains a directory that does not match a process deployment timestamp: "
                                        + directory.getName(),
                                e);
                    }
                }
            }
            if (lastDeployementDate == 0L) {
                if (LOGGER.isLoggable(Level.WARNING)) {
                    LOGGER.log(Level.WARNING,
                            "Process application resources deployment folder contains no directory that match a process deployment timestamp.");
                }
            } else {
                final File file = new File(processDir, lastDeployementDate + File.separator + WEB_RESOURCES_DIR
                        + File.separator + resourcePath);

                final BonitaHomeFolderAccessor tenantFolder = new BonitaHomeFolderAccessor();
                if (!tenantFolder.isInFolder(file, processDir)) {
                    throw new ServletException("For security reasons, access to this file paths"
                            + file.getAbsolutePath() + " is restricted.");
                }

                resourceFileName = file.getName();
                content = FileUtils.readFileToByteArray(file);
                if (resourceFileName.endsWith(".css")) {
                    contentType = "text/css";
                } else if (resourceFileName.endsWith(".js")) {
                    contentType = "application/x-javascript";
                } else {
                    final FileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();
                    contentType = mimetypesFileTypeMap.getContentType(file);
                }
            }
        } else {
            if (LOGGER.isLoggable(Level.WARNING)) {
                LOGGER.log(Level.WARNING,
                        "The Process application resources deployment directory does not exist.");
            }
        }
    } catch (final Exception e) {
        final String errorMessage = "Error while getting the resource " + resourcePath;
        if (LOGGER.isLoggable(Level.SEVERE)) {
            LOGGER.log(Level.SEVERE, errorMessage, e);
        }
        throw new ServletException(errorMessage, e);
    }
    if (contentType == null) {
        contentType = "application/octet-stream";
    }
    response.setContentType(contentType);
    response.setCharacterEncoding("UTF-8");
    try {
        final String encodedfileName = URLEncoder.encode(resourceFileName, "UTF-8");
        final String userAgent = request.getHeader("User-Agent");
        if (userAgent != null && userAgent.contains("Firefox")) {
            response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedfileName);
        } else {
            response.setHeader("Content-Disposition", "attachment; filename=\""
                    + encodedfileName.replaceAll("\\+", " ") + "\"; filename*=UTF-8''" + encodedfileName);
        }
        response.setContentLength(content.length);
        final OutputStream out = response.getOutputStream();
        out.write(content);
        out.close();
    } catch (final IOException e) {
        if (LOGGER.isLoggable(Level.SEVERE)) {
            LOGGER.log(Level.SEVERE, "Error while generating the response.", e);
        }
        throw new ServletException(e.getMessage(), e);
    }
}

From source file:org.wso2.appmanager.integration.restapi.utils.DataDrivenTestUtils.java

/**
 * This method is used to send the POST request
 *
 * @param resourceUrl     url of the resource
 * @param contentType     content type/*w  w  w  . ja va2 s .c  o m*/
 * @param acceptMediaType accepted media type
 * @param postBody        payload
 * @param queryParamMap   map containing query parameters
 * @param headerMap       map containing headers
 * @param cookie          cookie string if any
 * @return response of the POST request
 */
public Object geneticRestRequestPost(String resourceUrl, String contentType, String acceptMediaType,
        Object postBody, Map<String, String> queryParamMap, Map<String, String> headerMap, String cookie) {

    Client client = ClientBuilder.newClient().register(JacksonJsonProvider.class);
    WebTarget target = client.target(resourceUrl);
    Invocation.Builder builder = getBuilder(acceptMediaType, queryParamMap, headerMap, cookie, target);
    Response response = null;
    Form form = new Form();
    if (contentType == MediaType.APPLICATION_FORM_URLENCODED) {
        for (String formField : postBody.toString().split("&")) {
            form.param(formField.split("=")[0], formField.split("=")[1]);
        }
        response = builder.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED));
    } else if (contentType == MediaType.MULTIPART_FORM_DATA) {

        DefaultClientConfig clientConfig = new DefaultClientConfig();
        clientConfig.getClasses().add(MultiPartWriter.class);
        com.sun.jersey.api.client.Client jerseyClient = com.sun.jersey.api.client.Client.create(clientConfig);

        FormDataMultiPart multiPart = new FormDataMultiPart();
        for (String formField : postBody.toString().split("&")) {
            final String formFieldKey = formField.split("=")[0];
            final String formFieldValue = formField.split("=")[1];
            if (RESTAPITestConstants.FILE.equals(formFieldKey)) {
                //If the form field is a file.
                final File fileToUpload = new File(formFieldValue);
                if (fileToUpload != null) {
                    MediaType fileMediaType;
                    String mimeType = new MimetypesFileTypeMap().getContentType(fileToUpload);
                    if (mimeType.contains(RESTAPITestConstants.IMAGE)) {
                        //If the form field is a image file.
                        fileMediaType = RESTAPITestConstants.IMAGE_JPEG_TYPE;
                    } else {
                        fileMediaType = MediaType.APPLICATION_OCTET_STREAM_TYPE;
                    }
                    final FileDataBodyPart fileDataBodyPart = new FileDataBodyPart(RESTAPITestConstants.FILE,
                            fileToUpload, fileMediaType);
                    multiPart.bodyPart(fileDataBodyPart);
                }
            } else {
                //If the form field is not a file.
                multiPart.field(formFieldKey, formFieldValue, MediaType.MULTIPART_FORM_DATA_TYPE);
            }
        }
        WebResource resource = jerseyClient.resource(resourceUrl);
        WebResource.Builder webResourceBuilder = getWebResourceBuilder(contentType, queryParamMap, headerMap,
                cookie, resource);
        ClientResponse clientResponse = webResourceBuilder.post(ClientResponse.class, multiPart);

        return clientResponse;
    } else if (contentType == MediaType.APPLICATION_JSON) {
        response = builder.post(Entity.json(postBody));
    } else if (contentType == MediaType.APPLICATION_XML) {
        response = builder.post(Entity.entity(Entity.xml(postBody), MediaType.APPLICATION_XML));
    }
    client.close();
    return response;
}