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.github.cxt.Myjersey.jerseycore.FileResource.java

@Path("download")
@GET/*from  w  ww.j  a  va2  s  .c om*/
public Response downloadFile(@Context HttpServletRequest request) throws IOException {
    File file = new File(request.getServletContext().getRealPath("index.html"));
    String mt = new MimetypesFileTypeMap().getContentType(file);
    return Response.ok(file, mt).header("Content-disposition", "attachment;filename=" + file.getName())
            .header("ragma", "No-cache").header("Cache-Control", "no-cache").build();

}

From source file:org.chililog.server.workbench.StaticFileRequestHandler.java

/**
 * Sets the content type header for the HTTP Response
 * // w  w w . j a  v  a2  s .c  om
 * @param response
 *            HTTP response
 * @param file
 *            file to extract content type
 */
private void setContentTypeHeader(HttpResponse response, File file) {
    String mimeType = null;
    String filePath = file.getPath();

    int idx = filePath.lastIndexOf('.');
    if (idx == -1) {
        mimeType = "application/octet-stream";
    } else {
        String fileExtension = filePath.substring(idx).toLowerCase();

        // Try common types first
        if (fileExtension.equals(".html")) {
            mimeType = "text/html";
        } else if (fileExtension.equals(".css")) {
            mimeType = "text/css";
        } else if (fileExtension.equals(".js")) {
            mimeType = "application/javascript";
        } else if (fileExtension.equals(".gif")) {
            mimeType = "image/gif";
        } else if (fileExtension.equals(".png")) {
            mimeType = "image/png";
        } else if (fileExtension.equals(".txt")) {
            mimeType = "text/plain";
        } else if (fileExtension.equals(".xml")) {
            mimeType = "application/xml";
        } else if (fileExtension.equals(".json")) {
            mimeType = "application/json";
        } else {
            MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
            mimeType = mimeTypesMap.getContentType(file.getPath());
        }
    }

    response.setHeader(HttpHeaders.Names.CONTENT_TYPE, mimeType);
}

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

/**
 * ?????????????./*  www.  j  a  v  a 2  s.c o m*/
 * 
 * @param key ?
 * @return ????
 */
@Override
public UrlTreeMetaData<InputStream> generateMetaDataFromReal(String key, UrlTreeContext ctx)
        throws BadContentException {
    if (!this.canLoad(key, ctx)) {
        throw new IllegalArgumentException(
                "Cannot Load it. check before can it load with canLoad(key): " + key);
    }
    Path p = this.generateFileObj(key);
    File f = p.toFile();
    long lastModified = f.lastModified();

    logger.trace("[?]????lastModified: " + p.toString() + ":"
            + lastModified);

    UrlTreeMetaData<InputStream> md = new UrlTreeMetaData<>();
    md.setDirectory(Files.isDirectory(p, LinkOption.NOFOLLOW_LINKS));
    md.setFilename(key);
    md.setOwnerId(ctx.getUserName());
    md.setGroupId(ctx.getPrimaryGroup());
    md.setCreatedTime(lastModified);
    md.setUpdatedTime(lastModified);
    md.setPermission(ctx.getDefaultPermission());
    String contentType = new MimetypesFileTypeMap().getContentType(p.getFileName().toString());
    md.setContentType(contentType);

    return md;
}

From source file:org.betaconceptframework.astroboa.test.engine.AbstractRepositoryTest.java

protected BinaryChannel loadManagedBinaryChannel(File resource, String binaryChannelName) throws IOException {
     BinaryChannel image = cmsRepositoryEntityFactory.newBinaryChannel();
     image.setName(binaryChannelName);//  w  ww  .  jav a2s  . c om
     //image.setSize(resource.length());
     image.setContent(FileUtils.readFileToByteArray(resource));

     image.setSourceFilename(resource.getName());

     image.setMimeType(new MimetypesFileTypeMap().getContentType(resource));

     Calendar lastModifiedDate = Calendar.getInstance();
     lastModifiedDate.setTimeInMillis(resource.lastModified());

     image.setModified(lastModifiedDate);

     return image;
 }

From source file:com.vimeo.VimeoUploadClient.java

/**
 * upload file (streaming)// www.ja v  a2  s .  co  m
 * 
 * @param endpoint
 */
private void doPut(String endpoint) {
    URL endpointUrl;
    HttpURLConnection connection;
    try {
        endpointUrl = new URL(endpoint);
        connection = (HttpURLConnection) endpointUrl.openConnection();
        connection.setRequestMethod("PUT");
        connection.setRequestProperty("Content-Length", videoFile.length() + "");
        connection.setRequestProperty("Content-Type", new MimetypesFileTypeMap().getContentType(videoFile));
        connection.setFixedLengthStreamingMode((int) videoFile.length());
        connection.setDoOutput(true);

        CopyStreamListener listener = new CopyStreamListener() {
            public void bytesTransferred(long totalBytesTransferred, int bytesTransferred, long streamSize) {
                // TODO: get the values to visualize it: currentStreamSize,
                // currentBytesTransferred
                currentStreamSize = streamSize;
                currentBytesTransferred = totalBytesTransferred;

                /*
                 * System.out.printf("\r%-30S: %d / %d (%d %%)", "Sent",
                 * totalBytesTransferred, streamSize, totalBytesTransferred
                 * * 100 / streamSize);
                 */
            }

            public void bytesTransferred(CopyStreamEvent event) {
            }
        };
        InputStream in = new FileInputStream(videoFile);
        OutputStream out = connection.getOutputStream();
        System.out.println("Uploading \"" + videoFile.getAbsolutePath() + "\"... ");
        long c = Util.copyStream(in, out, Util.DEFAULT_COPY_BUFFER_SIZE, videoFile.length(), listener);
        System.out.printf("\n%-30S: %d\n", "Bytes sent", c);
        in.close();
        out.close();

        // return code
        System.out.printf("\n%-30S: %d\n", "Response code", connection.getResponseCode());

        // TODO: Response code, if everything OK the code is 200

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

From source file:org.openmrs.util.OpenmrsUtil.java

/**
 * Get mime type of the given file// w  w w. j  a  v a2s .c  o  m
 *
 * @param file
 * @return mime type
 */
public static String getFileMimeType(File file) {
    MimetypesFileTypeMap mimeMap = new MimetypesFileTypeMap();
    return mimeMap.getContentType(file);
}

From source file:org.esupportail.portlet.filemanager.services.opencmis.CmisAccessImpl.java

@Override
public boolean putFile(String dir, String filename, InputStream inputStream,
        SharedUserPortletParameters userParameters, UploadActionType uploadOption) {
    //must manage the upload option.
    log.error("You need to implements feature about upload options!");
    Folder targetFolder = (Folder) getCmisObject(dir, userParameters);
    Map prop = new HashMap();
    prop.put(PropertyIds.OBJECT_TYPE_ID, BaseTypeId.CMIS_DOCUMENT.value());
    prop.put(PropertyIds.NAME, String.valueOf(filename));
    String mimeType = new MimetypesFileTypeMap().getContentType(filename);
    ContentStream stream = new ContentStreamImpl(filename, null, mimeType, inputStream);
    Document document = targetFolder.createDocument(prop, stream, VersioningState.NONE, null, null, null,
            cmisSession.getDefaultContext());
    HashMap m = new HashMap();
    m.put("cmis:name", filename);
    document.updateProperties(m);//from w w w .java2 s  . c  om
    return true;
}

From source file:com.collabnet.ccf.pi.qc.v90.QCAttachmentHandler.java

/**
 * Constructs the GenericArtifact Java object for the attachment after
 * getting the schema from getSchemaAttachment method It also populates all
 * the values into the attachment artifact.
 * //from  w  w w  .j av  a 2 s  .  com
 * @param qcc
 * @param entityId
 * @param attachmentName
 * @param deletedAttachments
 * @param deleteTransactionId
 * @param shouldShipAttachmentsWithArtifact
 * @param isDefectRepository
 * @return GenericArtifact Containing all the field values.
 */
public GenericArtifact getGenericArtifactObjectOfAttachment(IConnection qcc, String entityId,
        String attachmentName, long maxAttachmentSizePerArtifact, boolean deletedAttachments,
        String deleteTransactionId, boolean shouldShipAttachmentsWithArtifact, boolean isDefectRepository) {
    long attachmentSize = 0;
    String thisMimeType = null;
    if (attachmentName != null) {
        genericArtifact = getSchemaAttachment(qcc, entityId, attachmentName, deletedAttachments,
                deleteTransactionId);
    }
    if (genericArtifact == null)
        return null;
    if (!deletedAttachments) {

        MimetypesFileTypeMap mimeType = new MimetypesFileTypeMap();
        if (attachmentName != null)
            thisMimeType = mimeType.getContentType(attachmentName);
        byte data[] = null;
        File qcAttachmentFile = null;
        String contentType = (String) genericArtifact
                .getAllGenericArtifactFieldsWithSameFieldName(AttachmentMetaData.ATTACHMENT_TYPE).get(0)
                .getFieldValue().toString();
        List<GenericArtifactField> allFields = genericArtifact.getAllGenericArtifactFields();
        int noOfFields = allFields.size();
        for (int cnt = 0; cnt < noOfFields; cnt++) {
            GenericArtifactField thisField = allFields.get(cnt);
            thisField.setFieldAction(GenericArtifactField.FieldActionValue.REPLACE);
            // thisField.setFieldDisplayName(thisField.getFieldName());
            thisField.setFieldValueHasChanged(true);
            if (thisField.getFieldName().equals(AttachmentMetaData.ATTACHMENT_TYPE)) {
                if (contentType.equals("DATA")) {
                    thisField.setFieldValueType(GenericArtifactField.FieldValueTypeValue.STRING);
                    if (!deletedAttachments) {
                        if (isDefectRepository) {
                            IBugFactory bugFactory = null;
                            IBug bug = null;
                            try {
                                bugFactory = qcc.getBugFactory();
                                bug = bugFactory.getItem(entityId);
                                qcAttachmentFile = bug.retrieveAttachmentData(attachmentName,
                                        delayBeforeAttachmentDownload, maximumAttachmentRetryCount);
                            } catch (AttachmentUploadStillInProgressException e) {
                                throw e;
                            } catch (Exception e) {
                                String message = "An Exception occured in QCAttachmentHandler.getGenericArtifactObjectOfAttachment"
                                        + " while trying to do retrieveAttachmentData on Filename "
                                        + attachmentName;
                                log.error(message, e);
                                throw new CCFRuntimeException(message, e);
                            } finally {
                                bugFactory = null;
                                if (bug != null) {
                                    bug.safeRelease();
                                }
                            }
                        } else {
                            IRequirementsFactory reqFactory = null;
                            IRequirement req = null;
                            try {
                                reqFactory = qcc.getRequirementsFactory();
                                req = reqFactory.getItem(entityId);
                                qcAttachmentFile = req.retrieveAttachmentData(attachmentName,
                                        delayBeforeAttachmentDownload, maximumAttachmentRetryCount);
                            } catch (AttachmentUploadStillInProgressException e) {
                                throw e;
                            } catch (Exception e) {
                                String message = "An Exception occured in QCAttachmentHandler.getGenericArtifactObjectOfAttachment"
                                        + " while trying to do retrieveAttachmentData on Filename "
                                        + attachmentName;
                                log.error(message, e);
                                throw new CCFRuntimeException(message, e);
                            } finally {
                                reqFactory = null;
                                if (req != null) {
                                    req.safeRelease();
                                }
                            }
                        }
                        if (qcAttachmentFile == null) {
                            return null;
                        }
                        attachmentSize = qcAttachmentFile.length();

                        if (attachmentSize > maxAttachmentSizePerArtifact) {
                            log.warn("The attachment " + attachmentName
                                    + " is bigger than our maxAttachmentSizePerArtifact, so cannot ship.");
                            return null;
                        } else {
                            if (!shouldShipAttachmentsWithArtifact) {
                                File tempFile = null;
                                try {
                                    if (!qcAttachmentFile.exists()) {
                                        log.warn("Downloaded attachment is not valid");
                                        return null;
                                    }
                                    tempFile = File.createTempFile("QC_Attachment", "file");
                                    boolean renamingSuccessful = qcAttachmentFile.renameTo(tempFile);
                                    if (!renamingSuccessful) {
                                        tempFile = qcAttachmentFile;
                                    }
                                    String attachmentDataFileName = tempFile.getAbsolutePath();
                                    GenericArtifactField attachmentDataFileField = genericArtifact.addNewField(
                                            AttachmentMetaData.ATTACHMENT_DATA_FILE,
                                            GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD);
                                    attachmentDataFileField
                                            .setFieldValueType(GenericArtifactField.FieldValueTypeValue.STRING);
                                    attachmentDataFileField.setFieldAction(FieldActionValue.REPLACE);
                                    attachmentDataFileField.setFieldValue(attachmentDataFileName);
                                    log.debug("Shipping the reference of the attachment "
                                            + attachmentDataFileName);
                                    if (tempFile.length() == 0) {
                                        log.warn("The file " + attachmentDataFileName
                                                + " does not contain any data.");
                                    }
                                    data = null;
                                } catch (IOException e) {
                                    String message = "Could not write attachment content to temp file."
                                            + " Shipping the attachment with the artifact.";
                                    log.error(message, e);
                                    throw new CCFRuntimeException(message, e);
                                }
                            } else {
                                if (!qcAttachmentFile.exists()) {
                                    log.warn("Downloaded attachment is not valid");
                                    return null;
                                }
                                ByteArrayOutputStream baOS = new ByteArrayOutputStream();
                                FileInputStream fis = null;
                                try {
                                    fis = new FileInputStream(qcAttachmentFile);
                                    int readCount = 0;
                                    byte[] tmpData = new byte[1024 * 3];
                                    if ((readCount = fis.read(tmpData)) != -1) {
                                        baOS.write(tmpData, 0, readCount);
                                    }
                                    data = baOS.toByteArray();
                                    fis.close();
                                    baOS.close();
                                } catch (FileNotFoundException e) {
                                    String message = "Could not read attachment content." + " File not found "
                                            + qcAttachmentFile.getAbsolutePath();
                                    log.error(message, e);
                                    throw new CCFRuntimeException(message, e);
                                } catch (IOException e) {
                                    String message = "Could not read attachment content."
                                            + " IOException while reading "
                                            + qcAttachmentFile.getAbsolutePath();
                                    log.error(message, e);
                                    throw new CCFRuntimeException(message, e);
                                }
                            }
                        }
                    }
                }
            }
            if (thisField.getFieldName().equals(AttachmentMetaData.getAttachmentName())) {
                if (contentType.equals("DATA")) {
                    // For defects and requirements, QC adds a prefix consisting of the
                    // artifact type and ID to the file name. Images inserted into
                    // requirement rich text fields do not have a prefix, but are named
                    // RichContentImage_<randomID>.<extension>
                    // We remove the prefix if it exists.
                    String prefix = (isDefectRepository ? "BUG_" : "REQ_") + entityId + "_";
                    String tmpAttachmentName = attachmentName.startsWith(prefix)
                            ? attachmentName.substring(prefix.length())
                            : attachmentName;
                    thisField.setFieldValue(tmpAttachmentName);
                } else
                    thisField.setFieldValue("Unknown");
                thisField.setFieldValueType(GenericArtifactField.FieldValueTypeValue.STRING);
            } else if (thisField.getFieldName().equals(AttachmentMetaData.getAttachmentSize())) {
                thisField.setFieldValue(attachmentSize);
                thisField.setFieldValueType(GenericArtifactField.FieldValueTypeValue.INTEGER);
            } else if (thisField.getFieldName().equals(AttachmentMetaData.getAttachmentSourceUrl())) {
                if (contentType.equals("DATA"))
                    thisField.setFieldValue("Unknown");
                else
                    thisField.setFieldValue(attachmentName);
                thisField.setFieldValueType(GenericArtifactField.FieldValueTypeValue.STRING);
            } else if (thisField.getFieldName().equals(AttachmentMetaData.getAttachmentMimeType())) {
                thisField.setFieldValue(thisMimeType);
                thisField.setFieldValueType(GenericArtifactField.FieldValueTypeValue.STRING);
            } else if (thisField.getFieldName().equals(AttachmentMetaData.getAttachmentValueIsNull())) {
                if (data != null)
                    thisField.setFieldValue(AttachmentMetaData.AttachmentValueIsNull.FALSE);
                else
                    thisField.setFieldValue(AttachmentMetaData.AttachmentValueIsNull.TRUE);
                thisField.setFieldValueType(GenericArtifactField.FieldValueTypeValue.STRING);
            }
        }
        if (data != null) {
            genericArtifact.setRawAttachmentData(data);
        }
    }
    return genericArtifact;
}

From source file:com.nextcont.ecm.fileengine.http.nettyServer.HttpUploadServerHandler.java

private static void setContentTypeHeader(HttpResponse response, FileRecord file) {
    MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
    response.headers().set(CONTENT_TYPE,
            mimeTypesMap.getContentType(file.getFullName()) + "; charset=" + file.getHttpEncoding());
}

From source file:fedorax.server.module.storage.IrodsExternalContentManager.java

/**
 * Determines the mime type of a given file
 * //from   www.  ja v a  2s. c o  m
 * @param file
 *            for which the mime type needs to be detected
 * @return the detected mime type
 */
private String determineMimeType(File file) {
    String mimeType = new MimetypesFileTypeMap().getContentType(file);
    // if mimeType detection failed, fall back to the default
    if (mimeType == null || mimeType.equalsIgnoreCase("")) {
        mimeType = DEFAULT_MIMETYPE;
    }
    return mimeType;
}