Example usage for javax.activation MimeType toString

List of usage examples for javax.activation MimeType toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Return the String representation of this object.

Usage

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   w w  w.  jav 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.trsst.client.Client.java

/**
 * Returns a Feed for the specified feed id, and will attempt to decrypt any
 * encrypted content with the specified key.
 * //from w w  w. ja v a  2s  .c  o  m
 * @param urn
 *            a feed or entry urn id.
 * @param decryptionKey
 *            one or more private keys used to attempt to decrypt content.
 * @return a Feed containing the latest entries for this feed id.
 */
public Feed pull(String urn, PrivateKey[] decryptionKeys) {
    Feed feed = pull(urn);
    if (feed == null) {
        return null;
    }

    Content content;
    MimeType contentType;
    for (Entry entry : feed.getEntries()) {
        content = entry.getContentElement();
        if (content != null && (contentType = content.getMimeType()) != null
                && "application/xenc+xml".equals(contentType.toString())) {

            // if this message was intended for us, we will be able to
            // decrypt one of the elements into an AES key to decrypt the
            // encrypted entry itself

            QName publicEncryptName = new QName(Common.NS_URI, Common.ENCRYPT);
            QName publicSignName = new QName(Common.NS_URI, Common.SIGN);
            QName encryptedDataName = new QName("http://www.w3.org/2001/04/xmlenc#", "EncryptedData");
            QName cipherDataName = new QName("http://www.w3.org/2001/04/xmlenc#", "CipherData");
            QName cipherValueName = new QName("http://www.w3.org/2001/04/xmlenc#", "CipherValue");

            String encodedBytes;
            byte[] decodedBytes;
            Element publicKeyElement, cipherData, cipherValue, result;
            List<Element> encryptedElements = content.getElements();
            int lastIndex = encryptedElements.size() - 1;
            Element element;
            PublicKey publicKey = null;
            byte[] decryptedKey = null;

            publicKeyElement = feed.getFirstChild(publicEncryptName);
            if (publicKeyElement == null) {
                // fall back on signing key
                publicKeyElement = feed.getFirstChild(publicSignName);
            }
            if (publicKeyElement != null && publicKeyElement.getText() != null) {
                try {
                    publicKey = Common.toPublicKeyFromX509(publicKeyElement.getText());
                } catch (GeneralSecurityException gse) {
                    log.error("Could not parse public key: " + publicKeyElement);
                }
            }

            if (publicKey != null) {

                // TODO: if we're the author, we can start loop at
                // (lastIndex-1)
                for (int i = 0; i < encryptedElements.size(); i++) {
                    element = encryptedElements.get(i);
                    if (encryptedDataName.equals(element.getQName())) {
                        cipherData = element.getFirstChild(cipherDataName);
                        if (cipherData != null) {
                            cipherValue = cipherData.getFirstChild(cipherValueName);
                            if (cipherValue != null) {
                                encodedBytes = cipherValue.getText();
                                if (encodedBytes != null) {
                                    decodedBytes = new Base64().decode(encodedBytes);
                                    if (i != lastIndex) {
                                        // if we're not at the last index
                                        // (the payload) so we should
                                        // attempt
                                        // to decrypt this AES key
                                        for (PrivateKey decryptionKey : decryptionKeys) {
                                            try {
                                                decryptedKey = Crypto.decryptKeyWithIES(decodedBytes,
                                                        entry.getUpdated().getTime(), publicKey, decryptionKey);
                                                if (decryptedKey != null) {
                                                    // success:
                                                    // skip to lastIndex
                                                    i = lastIndex - 1;
                                                    break;
                                                }
                                            } catch (GeneralSecurityException e) {
                                                // key did not fit
                                                log.trace("Could not decrypt key: " + entry.getId(), e);
                                            } catch (Throwable t) {
                                                log.warn(
                                                        "Error while decrypting key on entry: " + entry.getId(),
                                                        t);
                                            }
                                        }
                                    } else if (decryptedKey != null) {
                                        // if we're at the last index
                                        // (the payload) and we have an
                                        // AES key: attempt to decrypt
                                        try {
                                            result = decryptElementAES(decodedBytes, decryptedKey);
                                            for (Element ee : encryptedElements) {
                                                ee.discard();
                                            }
                                            content.setValueElement(result);
                                            break;
                                        } catch (SecurityException e) {
                                            log.error("Key did not decrypt element: " + entry.getId(), e);
                                        } catch (Throwable t) {
                                            log.warn("Could not decrypt element on entry: " + entry.getId(), t);
                                        }
                                    }
                                } else {
                                    log.warn("No cipher text for entry: " + entry.getId());
                                }
                            } else {
                                log.warn("No cipher value for entry: " + entry.getId());
                            }
                        } else {
                            log.warn("No cipher data for entry: " + entry.getId());
                        }
                    }
                }

            } else {
                log.error("No public key for feed: " + feed.getId());
            }
        }
    }
    return feed;
}

From source file:fedora.server.storage.translation.AtomDODeserializer.java

private String getDSMimeType(Entry entry) {
    String dsMimeType = "application/unknown";
    MimeType mimeType = entry.getContentMimeType();
    if (mimeType == null) {
        Content.Type type = entry.getContentType();
        if (type != null) {
            if (type == Content.Type.HTML) {
                dsMimeType = "text/html";
            } else if (type == Content.Type.TEXT) {
                dsMimeType = "text/plain";
            } else if (type == Content.Type.XHTML) {
                dsMimeType = "application/xhtml+xml";
            } else if (type == Content.Type.XML) {
                dsMimeType = "text/xml";
            }/*from   w  ww.  ja v a 2s. c  o m*/
        }
    } else {
        dsMimeType = mimeType.toString();
    }
    return dsMimeType;
}

From source file:it.qvc.ClientHttpRequest.java

/**
 * Adds a file parameter to the request.
 * /*from  ww  w.j av  a 2 s  .c  o  m*/
 * @param sName
 *            Parameter name.
 * @param sFileName
 *            The name of the file.
 * @param aInputStream
 *            input stream to read the contents of the file from
 * @throws IOException
 */
public void setParameter(final String sName, final String sFileName, final InputStream aInputStream,
        final MimeType mimeType) throws IOException {
    logger.trace("setParameter(String, String, InputStream)");
    logger.debug("Name : " + sName + ".");
    logger.debug("File name : " + sFileName + ".");
    logger.debug("InputStream : " + aInputStream + ".");
    this.boundary();
    this.writeName(sName);
    this.write("; filename=\"");
    this.write(sFileName);
    this.write('"');
    this.newline();
    //      String sType = URLConnection.guessContentTypeFromName(sFileName);
    //      if (sType == null) {
    //         sType = URLConnection.guessContentTypeFromStream(aInputStream);
    //         if (sType == null) {
    //            sType = "application/octet-stream";
    //         }
    //      }
    this.write("Content-Type: ");
    this.writeln(mimeType.toString());
    this.newline();
    ClientHttpRequest.pipe(aInputStream, this.aOutputStream);
    this.newline();
}

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

/**
 * Add an <code>&lt;object&gt;</code> element to the channel
 * {@link net.www_eee.portal.Channel.ViewResponse#getContentContainerElement() content} creating an external resource
 * reference to the content at the given <code>proxiedFileURL</code> (link
 * {@linkplain #rewriteProxiedFileLink(Page.Request, URL, URI, boolean, boolean) rewritten} if necessary).
 * /*from  www  . j a  v a  2  s . c  o m*/
 * @param pageRequest The {@link net.www_eee.portal.Page.Request Request} currently being processed.
 * @param viewResponse The {@link net.www_eee.portal.Channel.ViewResponse ViewResponse} currently being generated.
 * @param proxiedFileURL The {@linkplain #getProxiedFileURL(Page.Request, Channel.Mode, boolean) proxied file URL}.
 * @param contentType The {@link MimeType} of the proxied file.
 * @throws WWWEEEPortal.Exception If a problem occurred while determining the result.
 * @throws WebApplicationException If a problem occurred while determining the result.
 */
protected void renderResourceReferenceView(final Page.Request pageRequest, final ViewResponse viewResponse,
        final URL proxiedFileURL, final @Nullable MimeType contentType)
        throws WWWEEEPortal.Exception, WebApplicationException {
    final Element contentContainerElement = viewResponse.getContentContainerElement();
    final Document contentContainerDocument = DOMUtil.getDocument(contentContainerElement);

    final Element objectElement = DOMUtil.createElement(HTMLUtil.HTML_NS_URI, HTMLUtil.HTML_NS_PREFIX, "object",
            contentContainerElement, contentContainerDocument, true, true);

    final String[][] extraObjectClasses;
    if (contentType != null) {
        final String contentTypeString = contentType.toString();

        DOMUtil.createAttr(null, null, "type", contentTypeString, objectElement);

        final StringBuffer safeTypeClass = new StringBuffer();
        for (int i = 0; i < contentTypeString.length(); i++) {
            char c = contentTypeString.charAt(i);
            if (Character.isLetterOrDigit(c)) {
                safeTypeClass.append(c);
            } else {
                safeTypeClass.append('_');
            }
        }
        extraObjectClasses = new String[][] { new String[] { portal.getPortalID(), "channel",
                channelDef.getID(), "resource", "type", safeTypeClass.toString() } };

    } else {
        extraObjectClasses = null;
    }
    setIDAndClassAttrs(objectElement, Arrays.asList("proxy", "resource"), extraObjectClasses, null);

    final URI resourceURI = rewriteProxiedFileLink(pageRequest, proxiedFileURL, null, false, false).getKey();
    DOMUtil.createAttr(null, null, "data", resourceURI.toString(), objectElement);

    return;
}

From source file:org.apache.abdera.protocol.client.AbstractClientResponse.java

/**
 * Get the response payload as a parsed Abdera FOM Document using the specified parser and parser options
 * /*from   w  ww.  j a  v a  2 s  .  co m*/
 * @param parser The parser
 * @param options The parser options
 */
public <T extends Element> Document<T> getDocument(Parser parser, ParserOptions options) throws ParseException {
    try {
        if (options == null)
            options = parser.getDefaultParserOptions();
        String charset = getCharacterEncoding();
        if (charset != null)
            options.setCharset(charset);
        IRI cl = getContentLocation();
        if (cl != null && !cl.isAbsolute()) {
            IRI r = new IRI(getUri());
            cl = r.resolve(cl);
        }
        String base = (cl != null) ? cl.toASCIIString() : getUri();
        Document<T> doc = parser.parse(getReader(), base, options);
        EntityTag etag = getEntityTag();
        if (etag != null)
            doc.setEntityTag(etag);
        Date lm = getLastModified();
        if (lm != null)
            doc.setLastModified(lm);
        MimeType mt = getContentType();
        if (mt != null)
            doc.setContentType(mt.toString());
        String language = getContentLanguage();
        if (language != null)
            doc.setLanguage(language);
        String slug = getSlug();
        if (slug != null)
            doc.setSlug(slug);
        return doc;
    } catch (Exception e) {
        throw new ParseException(e);
    }
}

From source file:org.apache.abdera.protocol.client.RequestOptions.java

/**
 * Set the value of the HTTP Content-Type header
 *//*from   w ww  . ja v a  2s . c o  m*/
public RequestOptions setContentType(MimeType value) {
    return setHeader("Content-Type", value.toString());
}

From source file:org.apache.abdera.protocol.server.adapters.jcr.JcrCollectionAdapter.java

@Override
public Node postMedia(MimeType mimeType, String slug, InputStream inputStream, RequestContext request)
        throws ResponseContextException {
    if (slug == null) {
        throw new ResponseContextException("A slug header must be supplied.", 500);
    }/*w w  w  . ja va2  s  . co m*/
    Node n = postEntry(slug, null, null, new Date(), null, null, request);

    try {
        n.setProperty(MEDIA, inputStream);
        n.setProperty(CONTENT_TYPE, mimeType.toString());

        String summary = postSummaryForEntry(n);
        if (summary != null) {
            n.setProperty(SUMMARY, summary);
        }

        getSession(request).save();

        return n;
    } catch (RepositoryException e) {
        try {
            getSession(request).refresh(false);
        } catch (Throwable t) {
            log.warn(t);
        }
        throw new ResponseContextException(500, e);
    }
}

From source file:org.apache.abdera.protocol.server.impl.AbstractEntityCollectionAdapter.java

public ResponseContext putEntry(RequestContext request) {
    try {//from w  w w  .j av  a 2  s .  c o m
        String id = getResourceName(request);
        T entryObj = getEntry(id, request);

        if (entryObj == null) {
            return new EmptyResponseContext(404);
        }

        Entry orig_entry = getEntryFromCollectionProvider(entryObj,
                new IRI(getFeedIriForEntry(entryObj, request)), request);
        if (orig_entry != null) {

            MimeType contentType = request.getContentType();
            if (contentType != null && !MimeTypeHelper.isAtom(contentType.toString()))
                return new EmptyResponseContext(415);

            Entry entry = getEntryFromRequest(request);
            if (entry != null) {
                if (!entry.getId().equals(orig_entry.getId()))
                    return new EmptyResponseContext(409);

                if (!ProviderHelper.isValidEntry(entry))
                    return new EmptyResponseContext(400);

                putEntry(entryObj, entry.getTitle(), new Date(), entry.getAuthors(), entry.getSummary(),
                        entry.getContentElement(), request);
                return new EmptyResponseContext(204);
            } else {
                return new EmptyResponseContext(400);
            }
        } else {
            return new EmptyResponseContext(404);
        }
    } catch (ResponseContextException e) {
        return createErrorResponse(e);
    } catch (ParseException pe) {
        return new EmptyResponseContext(415);
    } catch (ClassCastException cce) {
        return new EmptyResponseContext(415);
    } catch (Exception e) {
        log.warn(e.getMessage(), e);
        return new EmptyResponseContext(400);
    }

}

From source file:org.apache.abdera.protocol.server.ProviderHelper.java

public static boolean isAtom(RequestContext request) {
    MimeType mt = request.getContentType();
    String ctype = (mt != null) ? mt.toString() : null;
    return ctype != null && MimeTypeHelper.isAtom(ctype);
}