use of javax.mail.internet.ParseException in project zm-mailbox by Zimbra.
the class ImapMessage method naddresses.
private static void naddresses(PrintStream ps, InternetAddress[] addrs) {
int count = 0;
if (addrs != null && addrs.length > 0) {
for (InternetAddress addr : addrs) {
if (addr.isGroup()) {
// group marker, and the mailbox name field holds the group name phrase."
try {
String serialized = addr.getAddress();
int colon = serialized.indexOf(':');
String name = colon == -1 ? serialized : serialized.substring(0, colon);
InternetAddress[] members = addr.getGroup(false);
if (count++ == 0) {
ps.write('(');
}
ps.print("(NIL NIL ");
nstring(ps, name);
ps.print(" NIL)");
if (members != null) {
for (InternetAddress member : members) {
address(ps, member);
}
}
ps.print("(NIL NIL NIL NIL)");
} catch (ParseException e) {
}
} else if (addr.getAddress() == null) {
continue;
} else {
// name, [SMTP] at-domain-list (source route), mailbox name, and host name."
if (count++ == 0) {
ps.write('(');
}
address(ps, addr);
}
}
}
if (count == 0) {
ps.write(NIL, 0, 3);
} else {
ps.write(')');
}
}
use of javax.mail.internet.ParseException in project rest.li by linkedin.
the class RestLiServer method isMultipart.
private boolean isMultipart(final Request request, final RequestContext requestContext, final Callback<?> callback) {
// In process requests don't support multipart.
if (Boolean.TRUE.equals(requestContext.getLocalAttr(ServerResourceContext.CONTEXT_IN_PROCESS_RESOLUTION_KEY))) {
return false;
}
final Map<String, String> requestHeaders = request.getHeaders();
try {
final String contentTypeString = requestHeaders.get(RestConstants.HEADER_CONTENT_TYPE);
if (contentTypeString != null) {
final ContentType contentType = new ContentType(contentTypeString);
if (contentType.getBaseType().equalsIgnoreCase(RestConstants.HEADER_VALUE_MULTIPART_RELATED)) {
callback.onError(RestException.forError(415, "This server cannot handle requests with a content type of multipart/related"));
return true;
}
}
final String acceptTypeHeader = requestHeaders.get(RestConstants.HEADER_ACCEPT);
if (acceptTypeHeader != null) {
final List<String> acceptTypes = MIMEParse.parseAcceptType(acceptTypeHeader);
for (final String acceptType : acceptTypes) {
if (acceptType.equalsIgnoreCase(RestConstants.HEADER_VALUE_MULTIPART_RELATED)) {
callback.onError(RestException.forError(406, "This server cannot handle requests with an accept type of multipart/related"));
return true;
}
}
}
} catch (ParseException parseException) {
callback.onError(RestException.forError(400, "Unable to parse content or accept types."));
return true;
}
return false;
}
use of javax.mail.internet.ParseException in project rest.li by linkedin.
the class AttachmentHandlingRestLiServer method handleRequestAttachments.
/**
* Handles multipart/related request as Rest.li payload with attachments.
*
* @return Whether or not the request is a multipart/related Rest.li request with attachments.
*/
private boolean handleRequestAttachments(StreamRequest request, RequestContext requestContext, Callback<StreamResponse> callback) {
// At this point we need to check the content-type to understand how we should handle the request.
String header = request.getHeader(RestConstants.HEADER_CONTENT_TYPE);
if (header != null) {
ContentType contentType;
try {
contentType = new ContentType(header);
} catch (ParseException e) {
callback.onError(Messages.toStreamException(RestException.forError(400, "Unable to parse Content-Type: " + header)));
return true;
}
if (contentType.getBaseType().equalsIgnoreCase(RestConstants.HEADER_VALUE_MULTIPART_RELATED)) {
// We need to reconstruct a RestRequest that has the first part of the multipart/related payload as the
// traditional rest.li payload of a RestRequest.
final MultiPartMIMEReader multiPartMIMEReader = MultiPartMIMEReader.createAndAcquireStream(request);
RoutingResult routingResult;
try {
routingResult = getRoutingResult(request, requestContext);
} catch (Exception e) {
callback.onError(buildPreRoutingStreamException(e, request));
return true;
}
final TopLevelReaderCallback firstPartReader = new TopLevelReaderCallback(routingResult, callback, multiPartMIMEReader, request);
multiPartMIMEReader.registerReaderCallback(firstPartReader);
return true;
}
}
return false;
}
use of javax.mail.internet.ParseException in project zm-mailbox by Zimbra.
the class VCard method formatContact.
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");
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 = "";
}
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();
// 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")) {
// should be raw BASE64
vcfEncodedValue = value;
} 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);
}
use of javax.mail.internet.ParseException in project wso2-axis2-transports by wso2.
the class JMSUtils method setSOAPEnvelope.
/**
* Set the SOAPEnvelope to the Axis2 MessageContext, from the JMS Message passed in
* @param message the JMS message read
* @param msgContext the Axis2 MessageContext to be populated
* @param contentType content type for the message
* @throws AxisFault
* @throws JMSException
*/
public static void setSOAPEnvelope(Message message, MessageContext msgContext, String contentType) throws AxisFault, JMSException {
if (contentType == null) {
if (message instanceof TextMessage) {
contentType = "text/plain";
msgContext.setProperty(org.apache.axis2.Constants.Configuration.CONTENT_TYPE, "text/plain");
} else {
contentType = "application/octet-stream";
}
if (log.isDebugEnabled()) {
log.debug("No content type specified; assuming " + contentType);
}
}
int index = contentType.indexOf(';');
String type = index > 0 ? contentType.substring(0, index) : contentType;
Builder builder = BuilderUtil.getBuilderFromSelector(type, msgContext);
if (builder == null) {
if (log.isDebugEnabled()) {
log.debug("No message builder found for type '" + type + "'. Falling back to SOAP.");
}
builder = new SOAPBuilder();
}
OMElement documentElement;
if (message instanceof BytesMessage) {
// Extract the charset encoding from the content type and
// set the CHARACTER_SET_ENCODING property as e.g. SOAPBuilder relies on this.
String charSetEnc = null;
try {
if (contentType != null) {
charSetEnc = new ContentType(contentType).getParameter("charset");
}
} catch (ParseException ex) {
// ignore
}
msgContext.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc);
if (builder instanceof DataSourceMessageBuilder) {
documentElement = ((DataSourceMessageBuilder) builder).processDocument(new BytesMessageDataSource((BytesMessage) message), contentType, msgContext);
} else {
documentElement = builder.processDocument(new BytesMessageInputStream((BytesMessage) message), contentType, msgContext);
}
} else if (message instanceof TextMessage) {
TextMessageBuilder textMessageBuilder;
if (builder instanceof TextMessageBuilder) {
textMessageBuilder = (TextMessageBuilder) builder;
} else {
textMessageBuilder = new TextMessageBuilderAdapter(builder);
}
String content = ((TextMessage) message).getText();
documentElement = textMessageBuilder.processDocument(content, contentType, msgContext);
} else if (message instanceof MapMessage) {
documentElement = convertJMSMapToXML((MapMessage) message);
} else {
Class msgClass = message.getClass();
String content = "Unsupported JMS message type : " + (msgClass != null ? msgClass.getName() : "undefined.");
log.error(content);
msgContext.setProperty(JMSConstants.SENDING_FAULT, true);
msgContext.setProperty(JMSConstants.ERROR_MESSAGE, content);
// ERROR_CODE is not set for msg context since it will suspend the ep if not defined in the configs and
// under this case we don't need the default behavior to get the endpoint suspended.
TextMessageBuilder textMessageBuilder = new TextMessageBuilderAdapter(builder);
documentElement = textMessageBuilder.processDocument(content, contentType, msgContext);
}
msgContext.setEnvelope(TransportUtils.createSOAPEnvelope(documentElement));
}
Aggregations