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:com.xyxy.platform.examples.showcase.demos.web.StaticContentServlet.java

/**
 * ?.//  w  w  w .j  av  a  2s .c om
 */
@Override
public void init() throws ServletException {
    // ?applicationContext?.
    applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());

    // ?mimeTypes, css,.
    mimetypesFileTypeMap = new MimetypesFileTypeMap();
    mimetypesFileTypeMap.addMimeTypes("text/css css");
}

From source file:org.mobicents.servlet.restcomm.amazonS3.S3AccessTool.java

public URI uploadFile(final String fileToUpload) {
    AWSCredentials credentials = new BasicAWSCredentials(accessKey, securityKey);
    AmazonS3 s3client = new AmazonS3Client(credentials);
    s3client.setRegion(Region.getRegion(Regions.fromName(bucketRegion)));
    if (logger.isInfoEnabled()) {
        logger.info("S3 Region: " + bucketRegion.toString());
    }//from   w ww .  j a  v a  2 s .c o  m
    try {
        StringBuffer bucket = new StringBuffer();
        bucket.append(bucketName);
        if (folder != null && !folder.isEmpty())
            bucket.append("/").append(folder);
        URI fileUri = URI.create(fileToUpload);
        if (logger.isInfoEnabled()) {
            logger.info("File to upload to S3: " + fileUri.toString());
        }
        File file = new File(fileUri);
        //            while (!file.exists()){}
        //            logger.info("File exist: "+file.exists());
        //First generate the Presigned URL, buy some time for the file to be written on the disk
        Date date = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        if (daysToRetainPublicUrl > 0) {
            cal.add(Calendar.DATE, daysToRetainPublicUrl);
        } else {
            //By default the Public URL will be valid for 180 days
            cal.add(Calendar.DATE, 180);
        }
        date = cal.getTime();
        GeneratePresignedUrlRequest generatePresignedUrlRequestGET = new GeneratePresignedUrlRequest(
                bucket.toString(), file.getName());
        generatePresignedUrlRequestGET.setMethod(HttpMethod.GET);
        generatePresignedUrlRequestGET.setExpiration(date);

        URL downloadUrl = s3client.generatePresignedUrl(generatePresignedUrlRequestGET);

        //Second upload the file to S3
        //            while (!file.exists()){}
        while (!FileUtils.waitFor(file, 30)) {
        }
        if (file.exists()) {
            PutObjectRequest putRequest = new PutObjectRequest(bucket.toString(), file.getName(), file);
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(new MimetypesFileTypeMap().getContentType(file));
            putRequest.setMetadata(metadata);
            if (reducedRedundancy)
                putRequest.setStorageClass(StorageClass.ReducedRedundancy);
            s3client.putObject(putRequest);

            if (removeOriginalFile) {
                removeLocalFile(file);
            }
            return downloadUrl.toURI();
        } else {
            logger.error("Timeout waiting for the recording file: " + file.getAbsolutePath());
            return null;
        }
    } catch (AmazonServiceException ase) {
        logger.error("Caught an AmazonServiceException");
        logger.error("Error Message:    " + ase.getMessage());
        logger.error("HTTP Status Code: " + ase.getStatusCode());
        logger.error("AWS Error Code:   " + ase.getErrorCode());
        logger.error("Error Type:       " + ase.getErrorType());
        logger.error("Request ID:       " + ase.getRequestId());
        return null;
    } catch (AmazonClientException ace) {
        logger.error("Caught an AmazonClientException, which ");
        logger.error("Error Message: " + ace.getMessage());
        return null;
    } catch (URISyntaxException e) {
        logger.error("URISyntaxException: " + e.getMessage());
        return null;
    }
}

From source file:org.apache.stratos.theme.mgt.util.ThemeUtil.java

public static void transferAllThemesToRegistry(File rootDirectory, Registry registry, String registryPath)
        throws RegistryException {
    try {//from www .  j  a v  a 2s. c om
        // adding the common media types
        Map<String, String> extensionToMediaTypeMap = new HashMap<String, String>();
        extensionToMediaTypeMap.put("gif", "image/gif");
        extensionToMediaTypeMap.put("jpg", "image/jpeg");
        extensionToMediaTypeMap.put("jpe", "image/jpeg");
        extensionToMediaTypeMap.put("jpeg", "image/jpeg");
        extensionToMediaTypeMap.put("png", "image/png");
        extensionToMediaTypeMap.put("css", "text/css");

        File[] filesAndDirs = rootDirectory.listFiles();
        if (filesAndDirs == null) {
            return;
        }
        List<File> filesDirs = Arrays.asList(filesAndDirs);

        for (File file : filesDirs) {
            String filename = file.getName();
            String fileRegistryPath = registryPath + RegistryConstants.PATH_SEPARATOR + filename;
            if (!file.isFile()) {
                // This is a Directory add a new collection
                // This path is used to store the file resource under registry
                Collection newCollection = registry.newCollection();
                registry.put(fileRegistryPath, newCollection);

                // recur
                transferAllThemesToRegistry(file, registry, fileRegistryPath);
            } else {
                // Add the file to registry
                Resource newResource = registry.newResource();
                String mediaType = null;
                if (filename.contains(".")) {
                    String fileExt = filename.substring(filename.lastIndexOf(".") + 1);
                    mediaType = extensionToMediaTypeMap.get(fileExt.toLowerCase());
                }
                if (mediaType == null) {
                    mediaType = new MimetypesFileTypeMap().getContentType(file);
                }
                newResource.setMediaType(mediaType);
                newResource.setContentStream(new FileInputStream(file));
                registry.put(fileRegistryPath, newResource);
            }
        }
    } catch (Exception e) {
        String msg = "Error loading theme to the sytem registry for registry path: " + registryPath;
        log.error(msg, e);
        throw new RegistryException(msg, e);
    }

}

From source file:org.restcomm.connect.commons.amazonS3.S3AccessTool.java

public URI uploadFile(final String fileToUpload) {
    if (s3client == null) {
        s3client = getS3client();//from   w w w. ja  v a  2s  . c  o  m
    }
    if (logger.isInfoEnabled()) {
        logger.info("S3 Region: " + bucketRegion.toString());
    }
    try {
        if (testing && (!testingUrl.isEmpty() || !testingUrl.equals(""))) {
            //                s3client.setEndpoint(testingUrl);
            //                s3client.setS3ClientOptions(new S3ClientOptions().withPathStyleAccess(true));
            FileUtils.touch(new File(URI.create(fileToUpload)));
        }
        StringBuffer bucket = new StringBuffer();
        bucket.append(bucketName);
        if (folder != null && !folder.isEmpty())
            bucket.append("/").append(folder);
        URI fileUri = URI.create(fileToUpload);
        if (logger.isInfoEnabled()) {
            logger.info("File to upload to S3: " + fileUri.toString());
        }
        File file = new File(fileUri);

        while (!FileUtils.waitFor(file, 30)) {
        }
        if (file.exists()) {
            PutObjectRequest putRequest = new PutObjectRequest(bucket.toString(), file.getName(), file);
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(new MimetypesFileTypeMap().getContentType(file));
            putRequest.setMetadata(metadata);
            if (reducedRedundancy)
                putRequest.setStorageClass(StorageClass.ReducedRedundancy);
            s3client.putObject(putRequest);

            if (removeOriginalFile) {
                removeLocalFile(file);
            }
            URI recordingS3Uri = s3client.getUrl(bucket.toString(), file.getName()).toURI();
            return recordingS3Uri;
            //                return downloadUrl.toURI();
        } else {
            logger.error("Timeout waiting for the recording file: " + file.getAbsolutePath());
            return null;
        }
    } catch (AmazonServiceException ase) {
        logger.error("Caught an AmazonServiceException");
        logger.error("Error Message:    " + ase.getMessage());
        logger.error("HTTP Status Code: " + ase.getStatusCode());
        logger.error("AWS Error Code:   " + ase.getErrorCode());
        logger.error("Error Type:       " + ase.getErrorType());
        logger.error("Request ID:       " + ase.getRequestId());
        return null;
    } catch (AmazonClientException ace) {
        logger.error("Caught an AmazonClientException ");
        logger.error("Error Message: " + ace.getMessage());
        return null;
    } catch (URISyntaxException e) {
        logger.error("URISyntaxException: " + e.getMessage());
        return null;
    } catch (IOException e) {
        logger.error("Problem while trying to touch recording file for testing", e);
        return null;
    }
}

From source file:org.paolomoz.zehnkampf.utils.GenHTTPResponse.java

public HttpResponse setOK(File requestedFile) throws FileNotFoundException, UnsupportedEncodingException {
    HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    HttpEntity entity = null;//from  w w w  .ja v  a2s  . co m
    if (requestedFile.isDirectory()) {
        entity = getDirectoryEntity(requestedFile);
    } else {
        int fileLen = (int) requestedFile.length();
        BufferedInputStream fileIn = new BufferedInputStream(new FileInputStream(requestedFile));

        // Detect the content mimetype
        String mimeTypeName = new MimetypesFileTypeMap().getContentType(requestedFile);

        response.setHeader("Content-Type", mimeTypeName);
        response.setHeader("Content-length", new Integer(fileLen).toString());
        entity = new InputStreamEntity(fileIn, fileLen);
    }
    response.setEntity(entity);
    return response;
}

From source file:org.alfresco.tutorial.repoaction.SendAsEmailActionExecuter.java

@Override
protected void executeImpl(Action action, NodeRef actionedUponNodeRef) {
    if (serviceRegistry.getNodeService().exists(actionedUponNodeRef) == true) {
        // Get the email properties entered via Share Form
        String to = (String) action.getParameterValue(PARAM_EMAIL_TO_NAME);
        String subject = (String) action.getParameterValue(PARAM_EMAIL_SUBJECT_NAME);
        String body = (String) action.getParameterValue(PARAM_EMAIL_BODY_NAME);

        // Get document filename
        Serializable filename = serviceRegistry.getNodeService().getProperty(actionedUponNodeRef,
                ContentModel.PROP_NAME);
        if (filename == null) {
            throw new AlfrescoRuntimeException("Document filename is null");
        }// w ww  . ja  v a  2  s  .  c  o m
        String documentName = (String) filename;

        try {
            // Create mail session
            Properties mailServerProperties = new Properties();
            mailServerProperties = System.getProperties();
            mailServerProperties.put("mail.smtp.host", "localhost");
            mailServerProperties.put("mail.smtp.port", "2525");
            Session session = Session.getDefaultInstance(mailServerProperties, null);
            session.setDebug(false);

            // Define message
            Message message = new MimeMessage(session);
            String fromAddress = "training@alfresco.com";
            message.setFrom(new InternetAddress(fromAddress));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject(subject);

            // Create the message part with body text
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(body);
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);

            // Create the Attachment part
            //
            //  Get the document content bytes
            byte[] documentData = getDocumentContentBytes(actionedUponNodeRef, documentName);
            if (documentData == null) {
                throw new AlfrescoRuntimeException("Document content is null");
            }
            //  Attach document
            messageBodyPart = new MimeBodyPart();
            messageBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(documentData,
                    new MimetypesFileTypeMap().getContentType(documentName))));
            messageBodyPart.setFileName(documentName);
            multipart.addBodyPart(messageBodyPart);

            // Put parts in message
            message.setContent(multipart);

            // Send mail
            Transport.send(message);

            // Set status on node as "sent via email"
            Map<QName, Serializable> properties = new HashMap<QName, Serializable>();
            properties.put(ContentModel.PROP_ORIGINATOR, fromAddress);
            properties.put(ContentModel.PROP_ADDRESSEE, to);
            properties.put(ContentModel.PROP_SUBJECT, subject);
            properties.put(ContentModel.PROP_SENTDATE, new Date());
            serviceRegistry.getNodeService().addAspect(actionedUponNodeRef, ContentModel.ASPECT_EMAILED,
                    properties);
        } catch (MessagingException me) {
            me.printStackTrace();
            throw new AlfrescoRuntimeException("Could not send email: " + me.getMessage());
        }
    }
}

From source file:de.iai.ilcd.services.SourceResource.java

/**
 * Get the first external file from the source
 * /*from  w  w w .  j  a  v a  2  s.  c  om*/
 * @param uuid
 *            UUID of the source
 * @return response for client
 */
@GET
@Path("{uuid}/digitalfile")
@Produces({ "image/*", "application/*" })
public Response getExternalFile(@PathParam("uuid") String uuid) {

    DataSetDao<Source, ?, ?> daoObject = this.getFreshDaoInstance();

    // fix uuid, if not in the right format
    GlobalRefUriAnalyzer analyzer = new GlobalRefUriAnalyzer(uuid);
    uuid = analyzer.getUuidAsString();

    Source source = daoObject.getByUuid(uuid);

    if (source == null) {
        throw new WebApplicationException(404);
    }

    DigitalFile requestedFile = null;
    for (DigitalFile file : source.getFiles()) {
        requestedFile = file;
        break;
    }

    if (requestedFile == null) {
        throw new WebApplicationException(404);
    }

    File file = new File(requestedFile.getAbsoluteFileName());
    if (!file.exists()) {
        throw new WebApplicationException(404);
    }

    String mt = new MimetypesFileTypeMap().getContentType(file);
    // if it's a PDF document, set MIME type to application/pdf
    if (file.getName().toLowerCase().endsWith(".pdf"))
        mt = "application/pdf";

    return Response.ok(file, mt).build();
}

From source file:be.fedict.eid.dss.document.zip.ZIPDSSDocumentService.java

public DocumentVisualization findDocument(byte[] parentDocument, String resourceId) throws Exception {

    ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(parentDocument));
    ZipEntry zipEntry;/*  www.  ja  va 2s.  co m*/

    while (null != (zipEntry = zipInputStream.getNextEntry())) {

        if (getResourceId(zipEntry).equals(resourceId)) {

            LOG.debug("Found file: " + resourceId);

            byte[] data = IOUtils.toByteArray(zipInputStream);
            return new DocumentVisualization(new MimetypesFileTypeMap().getContentType(zipEntry.getName()),
                    data);
        }
    }

    return null;
}

From source file:de.mprengemann.intellij.plugin.androidicons.util.RefactorHelper.java

public static void move(Project project, final String description, final List<File> sources,
        final List<File> targets) throws IOException {
    copy(project, description, sources, targets);
    RunnableHelper.runWriteCommand(project, new Runnable() {
        @Override/*w w w . jav a 2  s  .co  m*/
        public void run() {
            try {
                File dir = null;
                for (File source : sources) {
                    if (dir == null) {
                        dir = source.getParentFile();
                    }
                    FileUtils.forceDelete(source);
                }

                if (dir != null) {
                    if (dir.isDirectory()) {
                        File[] images = dir.listFiles(new FilenameFilter() {
                            @Override
                            public boolean accept(File file, String s) {
                                String mimetype = new MimetypesFileTypeMap().getContentType(file);
                                String type = mimetype.split("/")[0];
                                return type.equals("image");
                            }
                        });
                        if (images == null || images.length == 0) {
                            FileUtils.forceDelete(dir);
                        }
                    }
                }
            } catch (IOException ignored) {
            }
        }
    }, description);
}

From source file:com.htmlhifive.visualeditor.persister.LocalFileContentsPersister.java

/**
 * ????.//from   www.  ja  va2  s.  co  m
 * 
 * @param metadata urlTree
 * @param ctx urlTree
 * @return ??
 */
@Override
public InputStream load(UrlTreeMetaData<InputStream> metadata, UrlTreeContext ctx)
        throws BadContentException, TargetNotFoundException {
    Path f = this.generateFileObj(metadata.getAbsolutePath());

    if (!Files.exists(f) || !Files.isReadable(f)) {
        throw new TargetNotFoundException("cannot read real file");
    }

    InputStream contents;
    try {
        contents = Files.newInputStream(f);
    } catch (IOException e) {
        throw new GenericResourceException(e);
    }

    String contentType = new MimetypesFileTypeMap().getContentType(f.getFileName().toString());
    metadata.setContentType(contentType);

    return contents;
}