Example usage for javax.activation MimeType getBaseType

List of usage examples for javax.activation MimeType getBaseType

Introduction

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

Prototype

public String getBaseType() 

Source Link

Document

Return a String representation of this object without the parameter list.

Usage

From source file:com.github.restdriver.serverdriver.http.RequestBody.java

private ContentType createContentType(String contentType) {
    try {//from w  w  w .j a  v a  2s .  co  m

        MimeType mimeType = new MimeType(contentType);

        String mediaType = mimeType.getBaseType();
        String charset = defaultString(mimeType.getParameter("charset"), DEFAULT_CONTENT_ENCODING);

        return ContentType.create(mediaType, charset);

    } catch (MimeTypeParseException e) {
        throw new IllegalArgumentException("Invalid content type: " + contentType, e);
    }
}

From source file:com.googlecode.ddom.saaj.SOAPMessageTest.java

@Validated
@Test/*ww w . j  av a2s . c o m*/
public void testAddAttachmentPart() throws Exception {
    SOAPMessage message = getFactory().createMessage();
    AttachmentPart attachment = message.createAttachmentPart();
    message.addAttachmentPart(attachment);
    Iterator it = message.getAttachments();
    assertTrue(it.hasNext());
    assertSame(attachment, it.next());
    assertFalse(it.hasNext());
    // Check that the content type automatically changes to SwA
    if (message.saveRequired()) {
        message.saveChanges();
    }
    String[] contentTypeArray = message.getMimeHeaders().getHeader("Content-Type");
    assertNotNull(contentTypeArray);
    assertEquals(1, contentTypeArray.length);
    MimeType contentType = new MimeType(contentTypeArray[0]);
    assertEquals("multipart/related", contentType.getBaseType());
    assertEquals(messageSet.getVersion().getContentType(), contentType.getParameter("type"));
    assertNotNull(contentType.getParameter("boundary"));
}

From source file:ddf.mime.mapper.MimeTypeToTransformerMapperImpl.java

@Override
public <T> List<T> findMatches(Class<T> clazz, MimeType userMimeType) {
    BundleContext bundleContext = getContext();
    ServiceReference[] refs = null;//from ww  w  .  ja v a2  s  .  c  o m
    List<T> list = new ArrayList<T>();

    if (bundleContext == null) {
        LOGGER.debug("Cannot find matches, bundle context is null.");
        return list;
    }
    if (clazz == null) {
        LOGGER.warn("Cannot find matches, service argument is null.");
        throw new IllegalArgumentException("Invalid argument supplied, null service argument");
    }

    /*
     * Extract the services using the bundle context.
     */
    try {
        refs = bundleContext.getServiceReferences(clazz.getName(), null);
    } catch (InvalidSyntaxException e) {
        LOGGER.warn("Invalid filter syntax ", e);
        throw new IllegalArgumentException("Invalid syntax supplied: " + userMimeType.toString());
    }

    // If no InputTransformers found, return empty list
    if (refs == null) {
        LOGGER.debug("No {} services found - return empty list", clazz.getName());
        return list;
    }

    /*
     * Sort the list of service references based in it's Comparable interface.
     */
    Arrays.sort(refs, Collections.reverseOrder());

    /*
     * If the mime type is null return the whole list of service references
     */
    if (userMimeType == null) {
        if (refs.length > 0) {
            for (ServiceReference ref : refs) {
                Object service = (bundleContext.getService(ref));
                T typedService = clazz.cast(service);
                list.add(typedService);
            }
        }
        return list;
    }

    String userIdValue = userMimeType.getParameter(MimeTypeToTransformerMapper.ID_KEY);
    List<T> strictlyMatching = new ArrayList<T>();

    for (ServiceReference ref : refs) {

        List<String> mimeTypesServicePropertyList = getServiceMimeTypesList(ref);

        String serviceId = getServiceId(ref);

        for (String mimeTypeRawEntry : mimeTypesServicePropertyList) {

            MimeType mimeTypeEntry = constructMimeType(mimeTypeRawEntry);

            if (mimeTypeEntry != null
                    && StringUtils.equals(mimeTypeEntry.getBaseType(), userMimeType.getBaseType())
                    && (userIdValue == null || StringUtils.equals(userIdValue, serviceId))) {

                try {
                    Object service = bundleContext.getService(ref);
                    T typedService = clazz.cast(service);
                    strictlyMatching.add(typedService);
                    break; // found exact mimetype, no need to continue within
                    // the same service

                } catch (ClassCastException cce) {
                    LOGGER.debug("Caught illegal cast to transformer type. ", cce);
                }
            }
        }
    }

    return strictlyMatching;
}

From source file:com.duroty.lucene.bookmark.BookmarkToLuceneBookmark.java

/**
 * DOCUMENT ME!//  w  w w  .  j  a  va 2 s  . c  om
 *
 * @param mime DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 * @throws URISyntaxException
 * @throws IOException
 */
public LuceneBookmark parse(String idint, BookmarkObj bookmarkObj) throws URISyntaxException, IOException {
    if ((idint == null) || (bookmarkObj == null)) {
        return null;
    }

    LuceneBookmark luceneBookmark = new LuceneBookmark(idint);

    luceneBookmark.setCacheDate(new Date());

    String comments = null;

    try {
        comments = factory.parse(bookmarkObj.getComments(), "text/html",
                Charset.defaultCharset().displayName());
    } catch (Exception ex) {
        if (ex != null) {
            comments = ex.getMessage();
        }
    }

    luceneBookmark.setComments(comments);

    if (!StringUtils.isBlank(comments)) {
        luceneBookmark.setNotebook(true);
    }

    String url = bookmarkObj.getUrl();
    HttpContent httpContent = new HttpContent(new URL(url));
    MimeType mimeType = httpContent.getContentType();
    String contentType = "text/html";

    if (mimeType != null) {
        contentType = mimeType.getBaseType();
    }

    InputStream inputStream = httpContent.newInputStream();

    if (!StringUtils.isBlank(bookmarkObj.getTitle())) {
        luceneBookmark.setTitle(bookmarkObj.getTitle());
    } else {
        Vector elements = Extractor.getElements(httpContent.newInputStream(), null, "title");

        Text text = null;

        if ((elements != null) && (elements.size() == 1)) {
            Element element = (Element) elements.get(0);
            text = (Text) element.getFirstChild();
        }

        if (text != null) {
            luceneBookmark.setTitle(text.getData());
        } else {
            luceneBookmark.setTitle(url);
        }
    }

    String charset = httpContent.getCharset();

    if (charset == null) {
        charset = Charset.defaultCharset().displayName();
    }

    String contents = null;

    try {
        contents = factory.parse(inputStream, contentType, charset);
    } catch (Exception ex) {
        if (ex != null) {
            contents = ex.getMessage();
        }
    }

    luceneBookmark.setContents(contents);

    luceneBookmark.setDepth(bookmarkObj.getDepth());
    luceneBookmark.setFlagged(bookmarkObj.isFlagged());
    luceneBookmark.setInsertDate(new Date());
    luceneBookmark.setKeywords(bookmarkObj.getKeywords());

    //luceneBookmark.setNotebook(bookmarkObj.isNotebook());
    luceneBookmark.setParent(String.valueOf(bookmarkObj.getParent()));
    luceneBookmark.setUrl(url);
    luceneBookmark.setUrlStr(url);

    return luceneBookmark;
}

From source file:ddf.content.provider.filesystem.FileSystemProvider.java

private String getMimeType(MimeType mimeType) {
    LOGGER.trace("ENTERING: getMimeType");

    String mimeTypeStr = mimeType.getBaseType();
    String mimeTypeIdValue = mimeType.getParameter(ID_PARAMETER);
    if (!StringUtils.isEmpty(mimeTypeIdValue)) {
        mimeTypeStr += ";id=" + mimeTypeIdValue;
    }//  w  w  w .  ja  v a  2  s.  c om

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("mimeTypeStr = " + mimeTypeStr);
    }

    LOGGER.trace("EXITING: getMimeType");

    return mimeTypeStr;
}

From source file:ddf.catalog.transformer.resource.ResourceMetacardTransformerTest.java

private Resource getResource(MimeType mimeType, URI uri) throws Exception {
    Resource resource = mock(Resource.class);
    when(resource.getMimeType()).thenReturn(mimeType);
    when(resource.getMimeTypeValue()).thenReturn((mimeType == null) ? null : mimeType.getBaseType());
    when(resource.getInputStream()).thenReturn(uri.toURL().openConnection().getInputStream());
    return resource;
}

From source file:mitm.common.pdf.MessagePDFBuilder.java

private void addAttachment(final Part part, PdfWriter pdfWriter) throws IOException, MessagingException {
    byte[] content = IOUtils.toByteArray(part.getInputStream());

    String filename = StringUtils
            .defaultString(HeaderUtils.decodeTextQuietly(MimeUtils.getFilenameQuietly(part)), "attachment.bin");

    String baseType;//from   w  ww .  jav a2  s.  com

    String contentType = null;

    try {
        contentType = part.getContentType();

        MimeType mimeType = new MimeType(contentType);

        baseType = mimeType.getBaseType();
    } catch (MimeTypeParseException e) {
        /*
         * Can happen when the content-type is not correct. Example with missing ; between charset and name:
         * 
         * Content-Type: application/pdf;
         *      charset="Windows-1252" name="postcard2010.pdf"
         */
        logger.warn("Unable to infer MimeType from content type. Fallback to application/octet-stream. "
                + "Content-Type: " + contentType);

        baseType = MimeTypes.OCTET_STREAM;
    }

    PdfFileSpecification fileSpec = PdfFileSpecification.fileEmbedded(pdfWriter, null, filename, content,
            true /* compress */, baseType, null);

    pdfWriter.addFileAttachment(fileSpec);
}

From source file:net.www_eee.portal.channels.ProxyChannel.java

/**
 * Should the content contained within the supplied <code>proxyResponse</code> having the supplied
 * <code>responseContentType</code> be
 * {@linkplain #renderTextView(Page.Request, Channel.ViewResponse, HttpResponse, URL, MimeType) rendered using the
 * Text view}?/*from   w  w  w .  j  av  a2  s  .c o m*/
 * 
 * @param pageRequest The {@link net.www_eee.portal.Page.Request Request} currently being processed.
 * @param proxyResponse The {@link HttpResponse} received for the proxied file.
 * @param responseContentType The {@link MimeType} of the proxied file.
 * @return If the <code>proxyResponse</code> content should be
 * {@linkplain #renderTextView(Page.Request, Channel.ViewResponse, HttpResponse, URL, MimeType) rendered using the
 * Text view}.
 * @throws WWWEEEPortal.Exception If a problem occurred while determining the result.
 * @see #renderTextView(Page.Request, Channel.ViewResponse, HttpResponse, URL, MimeType)
 * @see #IS_RENDERED_USING_TEXT_VIEW_HOOK
 */
protected boolean isRenderedUsingTextView(final Page.Request pageRequest, final HttpResponse proxyResponse,
        final @Nullable MimeType responseContentType) throws WWWEEEPortal.Exception {
    final Object[] context = new Object[] { proxyResponse, responseContentType };
    Boolean isRenderedUsingTextView = IS_RENDERED_USING_TEXT_VIEW_HOOK.value(plugins, context, pageRequest);
    if (isRenderedUsingTextView == null) {

        isRenderedUsingTextView = Boolean.valueOf((responseContentType != null)
                && (IOUtil.TEXT_PLAIN_MIME_TYPE.getBaseType().equals(responseContentType.getBaseType())));

    }
    return Boolean.TRUE.equals(
            IS_RENDERED_USING_TEXT_VIEW_HOOK.filter(plugins, context, pageRequest, isRenderedUsingTextView));
}

From source file:fi.foyt.fni.materials.MaterialController.java

public Material createMaterial(Folder parentFolder, User user, FileData fileData)
        throws MimeTypeParseException, IOException, GeneralSecurityException {
    MimeType mimeType = parseMimeType(fileData.getContentType());

    if ("image".equals(mimeType.getPrimaryType())) {
        if ("svg".equals(mimeType.getSubType()) || "svg+xml".equals(mimeType.getSubType())) {
            return createVectorImage(parentFolder, user, new String(fileData.getData(), "UTF-8"),
                    fileData.getFileName());
        } else {/*from  ww  w  . j av  a  2s  . c o  m*/
            if (fileData.getContentType().equals("image/png")) {
                return createImage(parentFolder, user, fileData.getData(), fileData.getContentType(),
                        fileData.getFileName());
            } else {
                return uploadImage(parentFolder, user, fileData);
            }
        }
    } else {
        switch (mimeType.getBaseType()) {
        case "application/pdf":
            return uploadPdf(parentFolder, user, fileData);
        case "text/plain":
            return uploadText(parentFolder, user, fileData);
        case "text/html":
        case "application/xhtml+xml":
            return uploadHtml(parentFolder, user, fileData);
        case "application/vnd.oasis.opendocument.text":
        case "application/vnd.sun.xml.writer":
        case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
        case "application/msword":
        case "application/x-mswrite":
        case "application/rtf":
        case "text/richtext":
            return uploadDocument(parentFolder, user, fileData);
        case "application/vnd.openxmlformats-officedocument.presentationml.slideshow":
        case "application/vnd.ms-powerpoint":
            // TODO: Warning: presentation
            return uploadDocument(parentFolder, user, fileData);
        case "application/vnd.ms-excel":
        case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
        case "application/vnd.oasis.opendocument.spreadsheet":
        case "text/csv":
        case "text/tab-separated-values":
            // TODO: Warning, spreadsheet
            return uploadDocument(parentFolder, user, fileData);
        }
    }

    return createFile(parentFolder, user, fileData.getData(), fileData.getContentType(),
            fileData.getFileName());
}

From source file:net.di2e.ecdr.search.transform.atom.response.AtomResponseTransformer.java

private Metacard entryToMetacard(Entry entry, String siteName) {
    CDRMetacard metacard = new CDRMetacard(CDRMetacardType.CDR_METACARD);

    String id = entry.getIdElement().getText();
    // id may be formatted catalog:id:<id>, so we parse out the <id>
    if (StringUtils.isNotBlank(id) && (id.startsWith("urn:uuid:") || id.startsWith("urn:catalog:id:"))) {
        id = id.substring(id.lastIndexOf(':') + 1);
    }// w ww .ja va 2 s.c o m
    metacard.setId(id);

    metacard.setSourceId(siteName);

    List<Category> categories = entry.getCategories();
    if (categories != null && !categories.isEmpty()) {
        Category category = categories.get(0);
        metacard.setContentTypeName(category.getTerm());
        IRI scheme = category.getScheme();
        if (scheme != null) {
            metacard.setContentTypeVersion(scheme.toString());
        }
    }

    try {
        metacard.setModifiedDate(entry.getUpdated());
    } catch (IllegalArgumentException e) {
        LOGGER.warn("InvalidDate found in atom reponse, setting Metacard modified time to now ");
        metacard.setEffectiveDate(new Date());
    }
    try {
        metacard.setEffectiveDate(entry.getPublished());
    } catch (IllegalArgumentException e) {
        LOGGER.warn("InvalidDate found in atom reponse, setting Metacard Effective time to now ");
        metacard.setEffectiveDate(new Date());
    }

    String createdDate = entry.getSimpleExtension(new QName(AtomResponseConstants.METACARD_ATOM_NAMESPACE,
            AtomResponseConstants.METACARD_CREATED_DATE_ELEMENT));
    if (createdDate != null) {
        metacard.setCreatedDate(new Date(DATE_FORMATTER.parseMillis(createdDate)));
    }

    String expirationDate = entry.getSimpleExtension(new QName(AtomResponseConstants.METACARD_ATOM_NAMESPACE,
            AtomResponseConstants.METADATA_EXPIRATION_DATE_ELEMENT));
    if (expirationDate != null) {
        metacard.setExpirationDate(new Date(DATE_FORMATTER.parseMillis(expirationDate)));
    }

    AtomContentXmlWrapOption wrap = filterConfig.getAtomContentXmlWrapOption();
    String metadata = entry.getContent();
    populateMetadata(entry, metacard, wrap, metadata);

    metacard.setLocation(getWKT(entry));

    Link productLink = entry.getLink(filterConfig.getProductLinkRelation());
    if (productLink != null) {

        metacard.setResourceURI(URI.create(productLink.getHref().toASCIIString()));
        long resourceSize = productLink.getLength();
        if (resourceSize > 0) {
            metacard.setResourceSize(String.valueOf(resourceSize));
        }
        String productTitle = productLink.getTitle();
        if (productTitle != null) {
            metacard.setAttribute(CDRMetacard.RESOURCE_TITLE, productTitle);
        }
        // ECDR-41 figure out MIMEType
        MimeType productType = productLink.getMimeType();
        if (productType != null) {
            metacard.setAttribute(CDRMetacard.RESOURCE_MIME_TYPE, productType.toString());
        }
    }

    String thumbnailLinkRel = filterConfig.getThumbnailLinkRelation();
    if (thumbnailLinkRel != null) {
        List<Link> links = entry.getLinks(thumbnailLinkRel);
        if (links != null && !links.isEmpty()) {
            for (Link link : links) {
                MimeType mimeType = link.getMimeType();
                if (mimeType == null || "image".equals(mimeType.getPrimaryType())) {

                    metacard.setThumbnailLinkURI(URI.create(link.getHref().toASCIIString()));
                    long thumbnailSize = link.getLength();
                    if (thumbnailSize > 0) {
                        metacard.setAttribute(CDRMetacard.THUMBNAIL_LENGTH, Long.valueOf(thumbnailSize));
                    }
                    // ECDR-41 figure out MIMEType
                    metacard.setAttribute(CDRMetacard.THUMBNAIL_MIMETYPE, link.getMimeType());
                    metacard.setAttribute(CDRMetacard.THUMBNAIL_LINK_TITLE, link.getTitle());
                    break;
                }
            }
        }
    }
    metacard.setTitle(entry.getTitle());

    boolean isMetadataSet = false;
    ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(AtomResponseTransformer.class.getClassLoader());
        List<Element> extensions = entry.getExtensions();
        for (Element element : extensions) {
            if (METADATA_ELEMENT_NAME.equalsIgnoreCase(element.getQName().getLocalPart())) {
                StringWriter writer = new StringWriter();
                try {
                    element.writeTo(writer);
                    metacard.setMetadata(writer.toString());
                    isMetadataSet = true;
                    break;
                } catch (IOException e) {
                    LOGGER.error(
                            "Could not convert Metadata String value from Atom to Metacard.METADATA attribute",
                            e);
                }

            }
        }
    } finally {
        Thread.currentThread().setContextClassLoader(tccl);
    }
    if (!isMetadataSet) {
        String metadataLinkRel = filterConfig.getMetadataLinkRelation();
        if (metadataLinkRel != null) {
            List<Link> metadataLinks = entry.getLinks(metadataLinkRel);
            String metadataLink = null;
            for (Link link : metadataLinks) {
                MimeType mimeType = link.getMimeType();
                if (mimeType != null) {
                    if (mimeType.getSubType().contains("xml")) {
                        metadataLink = link.getHref().toASCIIString();
                        metacard.setMetadataLinkURI(URI.create(metadataLink));
                        metacard.setAttribute(CDRMetacard.WRAP_METADATA, null);
                        break;
                    } else if (mimeType.getBaseType().contains("text")) {
                        metadataLink = link.getHref().toASCIIString();
                        metacard.setMetadataLinkURI(URI.create(metadataLink));
                        metacard.setAttribute(CDRMetacard.WRAP_METADATA, Boolean.TRUE);
                    }
                }
            }
        }
    }
    Metacard returnMetacard = SecurityMarkingParser.addSecurityToMetacard(metacard, entry);
    return new CDRMetacard(returnMetacard);
}