List of usage examples for javax.mail.internet ContentType getSubType
public String getSubType()
From source file:org.trancecode.xproc.step.HttpResponseHandler.java
private Iterable<XdmNode> constructMultipart(final ContentType contentMimeType, final String contentType, final BodypartResponseParser parser) throws IOException { final SaxonBuilder builder = new SaxonBuilder(processor.getUnderlyingConfiguration()); builder.startDocument();//from w w w. j a v a2 s . co m builder.startElement(XProcXmlModel.Elements.MULTIPART); final String boundary = contentMimeType.getParameter("boundary"); builder.attribute(XProcXmlModel.Attributes.BOUNDARY, boundary); parser.setBoundary(boundary); builder.attribute(XProcXmlModel.Attributes.CONTENT_TYPE, contentType); final List<BodypartResponseParser.BodypartEntity> parts = parser.parseMultipart(); for (final BodypartResponseParser.BodypartEntity part : parts) { final String mimeType = part.getHeaderGroup().getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue(); final ContentType bodyCt = Steps.getContentType(mimeType, null); if (bodyCt.getSubType().contains("xml")) { builder.startElement(XProcXmlModel.Elements.BODY); builder.attribute(XProcXmlModel.Attributes.CONTENT_TYPE, mimeType); } final Iterable<XdmNode> body = constructBody(bodyCt, mimeType, part); if (body != null) { builder.nodes(body); } if (bodyCt.getSubType().contains("xml")) { builder.endElement(); } } builder.endDocument(); return ImmutableList.of(builder.getNode()); }
From source file:com.zimbra.cs.service.formatter.VCard.java
public static VCard formatContact(Contact con, Collection<String> vcattrs, boolean includeXProps, boolean includeZimbraXProps) { Map<String, String> fields = con.getFields(); List<Attachment> attachments = con.getAttachments(); List<String> emails = con.getEmailAddresses(DerefGroupMembersOption.NONE); StringBuilder sb = new StringBuilder(); sb.append("BEGIN:VCARD\r\n"); // This is from RFC 2426 (vCard version 3.0) Section 1: // Profile special notes: The vCard object MUST contain the FN, N and VERSION types. if (vcattrs == null || vcattrs.contains("VERSION")) sb.append("VERSION:3.0\r\n"); // FN is a mandatory component of the vCard -- try our best to find or generate one String fn = fields.get(ContactConstants.A_fullName); if (vcattrs == null || vcattrs.contains("FN")) { if (fn == null || fn.trim().equals("")) try { fn = con.getFileAsString(); } catch (ServiceException e) { fn = ""; }/* w ww. j a v a 2s . c o m*/ if (fn.trim().equals("") && !emails.isEmpty()) fn = emails.get(0); if (fn.trim().equals("")) { String org = fields.get(ContactConstants.A_company); if (org != null && !org.trim().equals("")) { fn = org; } } sb.append("FN:").append(vcfEncode(fn)).append("\r\n"); } if (vcattrs == null || vcattrs.contains("N")) { StringBuilder nSb = new StringBuilder(); nSb.append(vcfEncode(fields.get(ContactConstants.A_lastName))).append(';') .append(vcfEncode(fields.get(ContactConstants.A_firstName))).append(';') .append(vcfEncode(fields.get(ContactConstants.A_middleName))).append(';') .append(vcfEncode(fields.get(ContactConstants.A_namePrefix))).append(';') .append(vcfEncode(fields.get(ContactConstants.A_nameSuffix))); String n = nSb.toString(); // N is mandatory according to RFC 2426 Section 1, so include it even if all components are empty // In fact, clients like Mac OS X Mavericks Contacts will just have blank names if it is blank, // so, try to avoid that. if (";;;;".equals(n)) { n = vcfEncode(fn) + ";;;;"; } sb.append("N:").append(n).append("\r\n"); } if (vcattrs == null || vcattrs.contains("NICKNAME")) encodeField(sb, "NICKNAME", fields.get(ContactConstants.A_nickname)); if (vcattrs == null || vcattrs.contains("PHOTO")) encodeField(sb, "PHOTO;VALUE=URI", fields.get(ContactConstants.A_image)); if (vcattrs == null || vcattrs.contains("BDAY")) { String bday = fields.get(ContactConstants.A_birthday); if (bday != null) { Date date = DateUtil.parseDateSpecifier(bday); if (date != null) sb.append("BDAY;VALUE=date:").append(new SimpleDateFormat("yyyy-MM-dd").format(date)) .append("\r\n"); } } if (vcattrs == null || vcattrs.contains("ADR")) { encodeAddress(sb, "home,postal,parcel", ContactConstants.A_homeStreet, ContactConstants.A_homeCity, ContactConstants.A_homeState, ContactConstants.A_homePostalCode, ContactConstants.A_homeCountry, 2, fields); encodeAddress(sb, "work,postal,parcel", ContactConstants.A_workStreet, ContactConstants.A_workCity, ContactConstants.A_workState, ContactConstants.A_workPostalCode, ContactConstants.A_workCountry, 2, fields); encodeAddress(sb, "postal,parcel", ContactConstants.A_otherStreet, ContactConstants.A_otherCity, ContactConstants.A_otherState, ContactConstants.A_otherPostalCode, ContactConstants.A_otherCountry, 2, fields); } if (vcattrs == null || vcattrs.contains("TEL")) { // omitting callback phone for now encodePhone(sb, "car,voice", ContactConstants.A_carPhone, 2, fields); encodePhone(sb, "home,fax", ContactConstants.A_homeFax, 2, fields); encodePhone(sb, "home,voice", ContactConstants.A_homePhone, 2, fields); encodePhone(sb, "cell,voice", ContactConstants.A_mobilePhone, 2, fields); encodePhone(sb, "fax", ContactConstants.A_otherFax, 2, fields); encodePhone(sb, "voice", ContactConstants.A_otherPhone, 2, fields); encodePhone(sb, "pager", ContactConstants.A_pager, 2, fields); encodePhone(sb, "work,fax", ContactConstants.A_workFax, 2, fields); encodePhone(sb, "work,voice", ContactConstants.A_workPhone, 2, fields); } if (vcattrs == null || vcattrs.contains("EMAIL")) { encodeField(sb, "EMAIL;TYPE=internet", ContactConstants.A_email, false, 2, fields); encodeField(sb, "EMAIL;TYPE=internet", "workEmail", true, 1, fields); } if (vcattrs == null || vcattrs.contains("URL")) { encodeField(sb, "URL;TYPE=home", ContactConstants.A_homeURL, false, 2, fields); encodeField(sb, "URL", ContactConstants.A_otherURL, false, 2, fields); encodeField(sb, "URL;TYPE=work", ContactConstants.A_workURL, false, 2, fields); } if (vcattrs == null || vcattrs.contains("ORG")) { String org = fields.get(ContactConstants.A_company); if (org != null && !org.trim().equals("")) { org = vcfEncode(org); String dept = fields.get(ContactConstants.A_department); if (dept != null && !dept.trim().equals("")) { org += ';' + vcfEncode(dept); } sb.append("ORG:").append(org).append("\r\n"); } } if (vcattrs == null || vcattrs.contains("TITLE")) encodeField(sb, "TITLE", fields.get(ContactConstants.A_jobTitle)); if (vcattrs == null || vcattrs.contains("NOTE")) encodeField(sb, "NOTE", fields.get(ContactConstants.A_notes)); if ((vcattrs == null || vcattrs.contains("PHOTO")) && attachments != null) { for (Attachment attach : attachments) { try { if (attach.getName().equalsIgnoreCase(ContactConstants.A_image)) { String field = "PHOTO;ENCODING=B"; if (attach.getContentType().startsWith("image/")) { // We want just the subtype, ignoring any name etc try { ContentType ct = new ContentType(attach.getContentType()); if (ct != null) { String subType = ct.getSubType(); if (!Strings.isNullOrEmpty(subType)) { field += ";TYPE=" + ct.getSubType().toUpperCase(); } } } catch (ParseException e) { } } String encoded = new String(Base64.encodeBase64Chunked(attach.getContent())).trim() .replace("\r\n", "\r\n "); sb.append(field).append(":\r\n ").append(encoded).append("\r\n"); } } catch (OutOfMemoryError e) { Zimbra.halt("out of memory", e); } catch (Throwable t) { ZimbraLog.misc.info("error fetching attachment content: " + attach.getName(), t); } } } if (vcattrs == null || vcattrs.contains("KEY")) { String smimeCert = fields.get(ContactConstants.A_userSMIMECertificate); if (smimeCert == null) { smimeCert = fields.get(ContactConstants.A_userCertificate); } if (smimeCert != null) { smimeCert = smimeCert.trim().replace("\r\n", "\r\n "); String field = "KEY;ENCODING=B"; sb.append(field).append(":\r\n ").append(smimeCert).append("\r\n"); } } if (vcattrs == null || vcattrs.contains("CATEGORIES")) { String[] tags = con.getTags(); if (tags.length > 0) { StringBuilder sbtags = new StringBuilder(); for (String tagName : tags) { sbtags.append(sbtags.length() == 0 ? "" : ",").append(vcfEncode(tagName)); } sb.append("CATEGORIES:").append(sbtags).append("\r\n"); } } String uid = getUid(con); if (vcattrs == null || vcattrs.contains("REV")) { sb.append("REV:") .append(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(new Date(con.getDate()))) .append("\r\n"); } if (vcattrs == null || vcattrs.contains("UID")) { sb.append("UID:").append(uid).append("\r\n"); } // sb.append("MAILER:Zimbra ").append(BuildInfo.VERSION).append("\r\n"); if ((vcattrs == null && includeZimbraXProps) || (vcattrs != null && vcattrs.contains("X-ZIMBRA-IMADDRESS"))) { encodeField(sb, "X-ZIMBRA-IMADDRESS", "imAddress", true, 1, fields); } if ((vcattrs == null && includeZimbraXProps) || (vcattrs != null && vcattrs.contains("X-ZIMBRA-ANNIVERSARY"))) { encodeField(sb, "X-ZIMBRA-ANNIVERSARY", ContactConstants.A_anniversary, false, 2, fields); } if ((vcattrs == null && includeZimbraXProps) || (vcattrs != null && vcattrs.contains("X-ZIMBRA-MAIDENNAME"))) { String maidenName = con.get(ContactConstants.A_maidenName); if (maidenName != null) sb.append("X-ZIMBRA-MAIDENNAME:").append(maidenName).append("\r\n"); } if (includeXProps) { ListMultimap<String, VCardParamsAndValue> unknownVCardProps = con.getUnknownVCardProps(); for (String key : unknownVCardProps.keySet()) { for (VCardParamsAndValue paramsAndValue : unknownVCardProps.get(key)) { StringWriter sw = new StringWriter(); try (FoldingWriter writer = new FoldingWriter(sw)) { writer.write(key); String value = paramsAndValue.getValue(); Set<String> params = paramsAndValue.getParams(); if (!params.isEmpty()) { writer.write(";"); writer.write(Joiner.on(";").join(params)); } String vcfEncodedValue; if (params.contains("ENCODING=B")) { vcfEncodedValue = value; // should be raw BASE64 } else { vcfEncodedValue = vcfEncode(value); } writer.write(":"); writer.write(vcfEncodedValue); writer.write("\r\n"); sb.append(sw.toString()); } catch (IOException e) { ZimbraLog.misc.debug("Problem with adding property '%s' to VCARD - ignoring", key, e); } } } } sb.append("END:VCARD\r\n"); return new VCard(fn, sb.toString(), fields, attachments, uid); }
From source file:com.eviware.soapui.impl.wsdl.monitor.ContentTypes.java
private boolean contentTypeMatches(ContentType contentType, ContentType respondedContentType) { // ContentType doesn't take wildcards into account for the primary type, but we want to do that return contentType.match(respondedContentType) || ((contentType.getPrimaryType().charAt(0) == '*' || respondedContentType.getPrimaryType().charAt(0) == '*') && (contentType.getSubType().charAt(0) == '*' || respondedContentType.getSubType().charAt(0) == '*' || contentType.getSubType().equalsIgnoreCase(respondedContentType.getSubType()))); }
From source file:com.grameenfoundation.ictc.controllers.SaleforceIntegrationController.java
public static InputSource getInputSource(String ctype, InputStream in) throws Exception { // Creates ContentType ContentType contentType = null; try {// w ww . j a va 2 s . com contentType = new ContentType(ctype) { }; } catch (Exception e) { System.out.println( "Unexpected Error occured while creating content-type object. Reason: " + e.getMessage()); throw new Exception(e.getMessage()); } // Checks primitive type String primaryType = contentType.getPrimaryType(); if (!"text".equals(primaryType) && !"application".equals(primaryType)) { System.out.println("Primary type received is " + primaryType + ". Only text or application primary type is expected"); throw new Exception(ctype); } // Checks sub type String subType = contentType.getSubType(); if (!"xml".equals(subType) && !subType.endsWith("+xml")) { System.out.println("sub type received is " + subType + ". Only xml sub type is expected"); throw new Exception(ctype); } // Gets charset parameter String charset = contentType.getParameter("charset"); if (charset == null) { // no charset // MIME type "text/*" omitted charset should be treated // as us-ascii if ("text".equals(contentType.getPrimaryType())) { charset = "us-ascii"; } } InputSource input; if (charset == null) { // application/xml omitted charset input = new InputSource(in); } else { // Creats a reader with java charset Reader reader = null; try { reader = new InputStreamReader(in, charset); } catch (UnsupportedEncodingException e) { System.out.println("UnsupportedEncodingException. Reason: " + e.getMessage()); throw new Exception(e.getMessage()); } input = new InputSource(reader); } return input; }
From source file:com.predic8.membrane.core.multipart.XOPReconstitutor.java
/** * @return reassembled SOAP message or null if message is not SOAP or not multipart *//*from w ww. j a va 2 s . co m*/ public Message getReconstitutedMessage(Message message) throws ParseException, MalformedStreamException, IOException, EndOfStreamException, XMLStreamException, FactoryConfigurationError { ContentType contentType = message.getHeader().getContentTypeObject(); if (contentType == null || contentType.getPrimaryType() == null) return null; if (!contentType.getPrimaryType().equals("multipart") || !contentType.getSubType().equals("related")) return null; String type = contentType.getParameter("type"); if (!"application/xop+xml".equals(type)) return null; String start = contentType.getParameter("start"); if (start == null) return null; String boundary = contentType.getParameter("boundary"); if (boundary == null) return null; HashMap<String, Part> parts = split(message, boundary); Part startPart = parts.get(start); if (startPart == null) return null; ContentType innerContentType = new ContentType(startPart.getHeader().getContentType()); if (!innerContentType.getPrimaryType().equals("application") || !innerContentType.getSubType().equals("xop+xml")) return null; byte[] body = fillInXOPParts(startPart.getInputStream(), parts); Message m = new Message() { @Override protected void parseStartLine(InputStream in) throws IOException, EndOfStreamException { throw new RuntimeException("not implemented."); } @Override public String getStartLine() { throw new RuntimeException("not implemented."); } }; m.setBodyContent(body); String reconstitutedContentType = innerContentType.getParameter("type"); if (reconstitutedContentType != null) m.getHeader().add(Header.CONTENT_TYPE, reconstitutedContentType); return m; }
From source file:org.trancecode.xproc.step.HttpResponseHandler.java
private Iterable<XdmNode> constructBody(final ContentType contentMimeType, final String contentType, final BodypartResponseParser.BodypartEntity part) throws IOException { final SaxonBuilder builder = new SaxonBuilder(processor.getUnderlyingConfiguration()); builder.startDocument();// ww w .ja v a2s. c o m builder.startElement(XProcXmlModel.Elements.BODY); builder.attribute(XProcXmlModel.Attributes.CONTENT_TYPE, contentType); if (contentMimeType.getSubType().contains("xml")) { try { final XdmNode node = processor.newDocumentBuilder() .build(new StreamSource(part.getEntity().getContent())); if (!detailed) { return ImmutableList.of(node); } else { builder.nodes(node); } } catch (SaxonApiException sae) { return null; } } else { if ("text".equals(contentMimeType.getPrimaryType())) { builder.startContent(); builder.text(IOUtils.toString(part.getEntity().getContent())); } else { builder.attribute(XProcXmlModel.Attributes.ENCODING, Steps.ENCODING_BASE64); builder.startContent(); final String b64 = Base64.encodeBytes(IOUtils.toByteArray(part.getEntity().getContent()), Base64.DO_BREAK_LINES); final Iterable<String> splitter = Splitter.on("\r\n").split(b64); for (final String split : splitter) { builder.text(split); builder.text("\n"); } } } builder.endDocument(); return ImmutableList.of(builder.getNode()); }
From source file:org.trancecode.xproc.step.RequestParser.java
private String getContentString(final XdmNode node, final ContentType contentType, final String encoding, final Processor processor) { if (!StringUtils.isEmpty(encoding) && !StringUtils.equalsIgnoreCase(encoding, Steps.ENCODING_BASE64)) { throw XProcExceptions.xc0052(SaxonLocation.of(node)); }/*from w w w . j ava 2 s . co m*/ final StringBuilder contentBuilder = new StringBuilder(); if (!StringUtils.containsIgnoreCase(contentType.getSubType(), "xml") || StringUtils.equalsIgnoreCase(encoding, Steps.ENCODING_BASE64)) { final Iterable<XdmItem> children = SaxonAxis.axis(node, Axis.CHILD); for (final XdmItem aNode : children) { if (!XdmNodeKind.TEXT.equals(((XdmNode) aNode).getNodeKind())) { throw XProcExceptions.xc0028(SaxonLocation.of(node)); } else { contentBuilder.append(StringEscapeUtils.unescapeHtml(aNode.toString())); } } } else { final Iterable<XdmItem> children = SaxonAxis.axis(node, Axis.CHILD); boolean oneElement = false; for (final XdmItem aNode : children) { final XdmNodeKind kind = ((XdmNode) aNode).getNodeKind(); if (XdmNodeKind.TEXT.equals(kind) && !StringUtils.isEmpty(aNode.getStringValue().trim())) { throw XProcExceptions.xc0022(node); } else if (XdmNodeKind.ELEMENT.equals(kind)) { if (oneElement) { throw XProcExceptions.xc0022(node); } else { oneElement = true; } } } } if (StringUtils.equalsIgnoreCase("xml", contentType.getSubType())) { final ByteArrayOutputStream targetOutputStream = new ByteArrayOutputStream(); final Serializer serializer = Steps.getSerializer(targetOutputStream, serializationOptions, processor); serializer.setOutputProperty(Serializer.Property.MEDIA_TYPE, contentType.toString()); try { processor.writeXdmValue(SaxonAxis.childElement(node), serializer); } catch (final Exception e) { throw new PipelineException("Error while trying to write document", e); } finally { Closeables.closeQuietly(targetOutputStream); } contentBuilder.append(targetOutputStream.toString()); } final String id = node.getAttributeValue(XProcXmlModel.Attributes.ID); verifyHeader(id, "Content-ID", node); final String description = node.getAttributeValue(XProcXmlModel.Attributes.DESCRIPTION); verifyHeader(description, "Content-Description", node); final String disposition = node.getAttributeValue(XProcXmlModel.Attributes.DISPOSITION); verifyHeader(disposition, "Content-Disposition", node); return contentBuilder.toString(); }
From source file:org.trancecode.xproc.step.HttpResponseHandler.java
private ContentType verifyContentType(final ContentType contentMimeType, final String overrideContentType) { ContentType overrideMimeType = null; try {//from ww w . j av a 2 s .com overrideMimeType = new ContentType(overrideContentType); } catch (ParseException e) { throw XProcExceptions.xc0030(); } if (StringUtils.equalsIgnoreCase(overrideMimeType.toString(), contentMimeType.toString())) { return contentMimeType; } if (("multipart".equals(contentMimeType.getPrimaryType()) && !"multipart".equals(overrideMimeType.getPrimaryType())) || ("multipart".equals(overrideMimeType.getPrimaryType()) && !"multipart".equals(contentMimeType.getPrimaryType())) || (contentMimeType.getSubType().contains("xml") || "text".equals(contentMimeType.getPrimaryType()) && "image".equals(overrideMimeType.getPrimaryType())) || ("image".equals(contentMimeType.getPrimaryType()) && (overrideMimeType.getSubType().contains("xml") || "text".equals(overrideMimeType.getPrimaryType())))) { throw XProcExceptions.xc0030(); } return overrideMimeType; }
From source file:org.mule.module.http.internal.HttpParser.java
/** * Extracts the subtype from a content type * * @param contentType the content type/*from ww w.ja v a 2 s. co m*/ * @return subtype of the content type. */ public static String getContentTypeSubType(String contentType) { final ContentType contentTypeValue; try { contentTypeValue = new ContentType(contentType); return contentTypeValue.getSubType(); } catch (ParseException e) { throw new MuleRuntimeException(e); } }
From source file:org.trancecode.xproc.binding.DataPortBinding.java
private void writeContent(final SaxonBuilder builder) { final URI uri = URI.create(href); if (uri.getScheme() != null && !StringUtils.equals("file", uri.getScheme()) && !StringUtils.equals("http", uri.getScheme())) { throw XProcExceptions.xd0012(this.getLocation(), uri.toASCIIString()); }/*from w ww . jav a 2s.com*/ try { final URL url; if (uri.isAbsolute()) { url = uri.toURL(); } else { url = node.getBaseURI().resolve(uri).toURL(); } final QName contentTypeAtt = (wrapper == null) ? XProcXmlModel.Attributes.CONTENT_TYPE : XProcXmlModel.Attributes.C_CONTENT_TYPE; final QName encodingAtt = (wrapper == null) ? XProcXmlModel.Attributes.ENCODING : XProcXmlModel.Attributes.C_ENCODING; final URLConnection urlConnection = url.openConnection(); final ContentType guessContentType; if (StringUtils.equals("http", url.getProtocol())) { guessContentType = Steps.getContentType(urlConnection.getContentType(), node); } else { if (contentType != null) { guessContentType = contentType; } else { guessContentType = Steps .getContentType("application/octet-stream ; encoding=" + Steps.ENCODING_BASE64, node); } } final Charset charset; if (contentType != null && contentType.getParameter("charset") != null) { charset = Charset.forName(contentType.getParameter("charset")); } else { charset = Charset.forName("UTF-8"); } final InputStream stream = urlConnection.getInputStream(); builder.attribute(contentTypeAtt, Steps.contentTypeToString(guessContentType)); if (StringUtils.equals("text", guessContentType.getPrimaryType()) || StringUtils.contains(guessContentType.getSubType(), "xml")) { if (guessContentType.getParameter("encoding") != null) { builder.attribute(encodingAtt, guessContentType.getParameter("encoding")); } builder.startContent(); builder.text(IOUtils.toString(stream, charset.name())); } else { builder.attribute(encodingAtt, Steps.ENCODING_BASE64); builder.startContent(); builder.text(Base64.encodeBytes(IOUtils.toByteArray(stream), Base64.DO_BREAK_LINES)); } } catch (final IOException ioe) { throw XProcExceptions.xd0029(this.getLocation()); } }