/** * Parses metadata stored in a Debian Control File-like format. * * @see <a href="https://cran.r-project.org/doc/manuals/r-release/R-exts.html#The-DESCRIPTION-file">Description File</a> */ public static Map<String, String> parseDescriptionFile(final InputStream in) { checkNotNull(in); try { LinkedHashMap<String, String> results = new LinkedHashMap<>(); InternetHeaders headers = new InternetHeaders(in); Enumeration headerEnumeration = headers.getAllHeaders(); while (headerEnumeration.hasMoreElements()) { Header header = (Header) headerEnumeration.nextElement(); String name = header.getName(); String value = header.getValue() .replace("\r\n", "\n") .replace("\r", "\n"); // TODO: "should" be ASCII only, otherwise need to know encoding? results.put(name, value); // TODO: Supposedly no duplicates, is this true? } return results; } catch (MessagingException e) { throw new RException(null, e); } }
/** * Adds the given name-values header to the given headers object. * * @param headers the headers object. * @param name the header name. * @param values the header values. */ private void addHeaders(Object headers, String name, Object[] values) { if (name != null) { for (int i=0; i<values.length; i++) { if (headers instanceof StringWriter) { StringWriter outs = (StringWriter)headers; outs.write(name+": "+values[i]+"\r\n"); continue; } StringTokenizer subvalues = new StringTokenizer( values[i].toString(), ","); while (subvalues.hasMoreTokens()) { String subvalue = subvalues.nextToken().trim(); if (headers instanceof MimeHeaders) { ((MimeHeaders)headers).addHeader(name, subvalue); } else if (headers instanceof InternetHeaders) { ((InternetHeaders)headers).addHeader(name, subvalue); } } } } }
/** * Creates a new instance of AS2Message. * * @param headers the headers of this message. * @param content the content stream. * @throws AS2MessageException if unable to construct from the given content stream. */ public AS2Message(InternetHeaders headers, InputStream content) throws AS2MessageException { try { load(headers, content); } catch (Exception e) { throw new AS2MessageException( "Unable to construct AS2 message from content stream", e); } }
public static void setBodyPart(Multipart multipart, byte[] content, String contentType) throws MessagingException { String disposition = null; for (int i = 0; i < multipart.getCount(); i++) { BodyPart bp = multipart.getBodyPart(i); if (contentType.equalsIgnoreCase(bp.getContentType())) { disposition = bp.getDisposition(); multipart.removeBodyPart(i); break; } } InternetHeaders ih1 = new InternetHeaders(); ih1.setHeader("Content-Type", contentType); BodyPart bodyPart = new MimeBodyPart(ih1, content); if (disposition != null) { bodyPart.setDisposition(disposition); } multipart.addBodyPart(bodyPart); }
/** * Provides parsed email headers from the "headers" param in a multipart/form-data request. * <p> * Although SendGrid parses some headers for us, it doesn't parse "reply-to", so we need to do * this. Once we are doing it, it's easier to be consistent and use this as the sole source of * truth for information that originates in the headers. */ @Provides @Singleton InternetHeaders provideHeaders(FileItemIterator iterator) { try { while (iterator != null && iterator.hasNext()) { FileItemStream item = iterator.next(); // SendGrid sends us the headers in the "headers" param. if (item.getFieldName().equals("headers")) { try (InputStream stream = item.openStream()) { // SendGrid always sends headers in UTF-8 encoding. return new InternetHeaders(new ByteArrayInputStream( CharStreams.toString(new InputStreamReader(stream, UTF_8.name())).getBytes(UTF_8))); } } } } catch (MessagingException | FileUploadException | IOException e) { // If we fail parsing the headers fall through returning the empty header object below. } return new InternetHeaders(); // Parsing failed or there was no "headers" param. }
/** * Add the defined package data to an RFC822 formatted header formatted for a Debian package * control file. * Order of fields determined from: * <a href="http://www.debian.org/doc/debian-policy/ch-controlfields.html#s-binarycontrolfiles">Debian Policy Manual</a> */ public InternetHeaders getControlHeaders () { final InternetHeaders headers = new InternetHeaders(); headers.addHeader(_name.getField(), _name.getFieldValue()); headers.addHeader(_version.getField(), _version.getFieldValue()); headers.addHeader(_section.getField(), _section.getFieldValue()); headers.addHeader(_priority.getField(), _priority.getFieldValue()); headers.addHeader(_architecture.getField(), _architecture.getFieldValue()); if (_dependencies.size() > 0) { headers.addHeader(_dependencies.getField(), _dependencies.getFieldValue()); } if (_conflicts.size() > 0) { headers.addHeader(_conflicts.getField(), _conflicts.getFieldValue()); } if (_replacements.size() > 0) { headers.addHeader(_replacements.getField(), _replacements.getFieldValue()); } headers.addHeader(_maintainer.getField(), _maintainer.getFieldValue()); headers.addHeader(_description.getField(), _description.getFieldValue()); return headers; }
/** * Add the control file to the tar file. */ private void addControlFile (TarOutputStream tar, PackageInfo info, PackageTarFile dataTar) throws IOException { // setup the RFC822 formatted header used for package metadata. final InternetHeaders headers = info.getControlHeaders(); // add the "Installed-Size" field. headers.addHeader(INSTALLED_SIZE, String.valueOf(dataTar.getTotalDataSize())); final StringBuilder controlFile = new StringBuilder(); @SuppressWarnings("unchecked") final Enumeration<String> en = headers.getAllHeaderLines(); while (en.hasMoreElements()) { controlFile.append(en.nextElement()).append('\n'); } final TarEntry entry = standardEntry(DEB_CONTROL_FILE, UnixStandardPermissions.STANDARD_FILE_MODE, controlFile.length()); tar.putNextEntry(entry); IOUtils.write(controlFile.toString(), tar); tar.closeEntry(); }
private static File saveStreamToFile(InternetHeaders headers, InputStream content, File tempFile) throws IOException { OutputStream out = new FileOutputStream(tempFile); Enumeration en = headers.getAllHeaderLines(); while (en.hasMoreElements()) { writeHeader(out, (String)en.nextElement()); } writeSeperator(out); saveContentToStream(out, content); return tempFile; }
@SuppressWarnings("unchecked") public static MimeBodyPart createBodyPart(Providers providers, SMIMEOutput out) throws IOException, MessagingException { ByteArrayOutputStream bodyOs = new ByteArrayOutputStream(); MessageBodyWriter writer = providers.getMessageBodyWriter(out.getType(), out.getGenericType(), null, out.getMediaType()); if (writer == null) { throw new RuntimeException("Failed to find writer for type: " + out.getType().getName()); } MultivaluedMap<String, String> bodyHeaders = new MultivaluedHashMap<String, String>(); bodyHeaders.add("Content-Type", out.getMediaType().toString()); writer.writeTo(out.getEntity(), out.getType(), out.getGenericType(), null, out.getMediaType(), bodyHeaders, bodyOs); InternetHeaders ih = new InternetHeaders(); for (Map.Entry<String, List<String>> entry : bodyHeaders.entrySet()) { for (String value : entry.getValue()) { ih.addHeader(entry.getKey(), value); } } return new MimeBodyPart(ih, bodyOs.toByteArray()); }
@Test public void testHeaders() throws Exception { InternetHeaders ih = new InternetHeaders(); ih.addHeader("Content-Type", "application/xml"); MimeBodyPart _msg = new MimeBodyPart(ih, "<customer name=\"bill\"/>".getBytes()); SMIMEEnvelopedGenerator gen = new SMIMEEnvelopedGenerator(); OutputEncryptor encryptor = new JceCMSContentEncryptorBuilder(CMSAlgorithm.DES_EDE3_CBC) .setProvider("BC") .build(); RecipientInfoGenerator generator = new JceKeyTransRecipientInfoGenerator(cert); gen.addRecipientInfoGenerator(generator); // // generate a MimeBodyPart object which encapsulates the content // we want encrypted. // MimeBodyPart mp = gen.generate(_msg, encryptor); output(mp); }
@Test public void testFromPythonGenerated() throws Exception { InternetHeaders ih = new InternetHeaders(); ih.addHeader("Content-Disposition", "attachment; filename=\"smime.p7m\""); ih.addHeader("Content-Type", "application/pkcs7-mime; smime-type=enveloped-data; name=\"smime.p7m\""); ih.addHeader("Content-Transfer-Encoding", "base64"); MimeBodyPart mp = new MimeBodyPart(ih, python_smime.getBytes()); output(mp); System.out.println("------------"); mp = decode2Mime(mp); Assert.assertEquals("application/xml", mp.getContentType()); String body = toString(mp.getInputStream()); Assert.assertEquals("<customer name=\"bill\"/>", body.trim()); }
/** * Send the contents of the cyclic buffer as an e-mail message. * @param layout The layout for formatting the events. * @param appendEvent The event that triggered the send. */ public void sendEvents(final Layout<?> layout, final LogEvent appendEvent) { if (message == null) { connect(appendEvent); } try { final LogEvent[] priorEvents = buffer.removeAll(); // LOG4J-310: log appendEvent even if priorEvents is empty final byte[] rawBytes = formatContentToBytes(priorEvents, appendEvent, layout); final String contentType = layout.getContentType(); final String encoding = getEncoding(rawBytes, contentType); final byte[] encodedBytes = encodeContentToBytes(rawBytes, encoding); final InternetHeaders headers = getHeaders(contentType, encoding); final MimeMultipart mp = getMimeMultipart(encodedBytes, headers); sendMultipartMessage(message, mp); } catch (final MessagingException | IOException | RuntimeException e) { logError("Caught exception while sending e-mail notification.", e); throw new LoggingException("Error occurred while sending email", e); } }
static Content buildPackages(final Collection<Map<String, String>> entries) throws IOException { CompressorStreamFactory compressorStreamFactory = new CompressorStreamFactory(); ByteArrayOutputStream os = new ByteArrayOutputStream(); try (CompressorOutputStream cos = compressorStreamFactory.createCompressorOutputStream(GZIP, os)) { try (OutputStreamWriter writer = new OutputStreamWriter(cos, UTF_8)) { for (Map<String, String> entry : entries) { InternetHeaders headers = new InternetHeaders(); headers.addHeader(P_PACKAGE, entry.get(P_PACKAGE)); headers.addHeader(P_VERSION, entry.get(P_VERSION)); headers.addHeader(P_DEPENDS, entry.get(P_DEPENDS)); headers.addHeader(P_IMPORTS, entry.get(P_IMPORTS)); headers.addHeader(P_SUGGESTS, entry.get(P_SUGGESTS)); headers.addHeader(P_LICENSE, entry.get(P_LICENSE)); headers.addHeader(P_NEEDS_COMPILATION, entry.get(P_NEEDS_COMPILATION)); Enumeration<String> headerLines = headers.getAllHeaderLines(); while (headerLines.hasMoreElements()) { String line = headerLines.nextElement(); writer.write(line, 0, line.length()); writer.write('\n'); } writer.write('\n'); } } } catch ( CompressorException e ) { throw new RException(null, e); } return new Content(new BytesPayload(os.toByteArray(), "application/x-gzip")); }
/** * processRequest * @param request * @param response * @return String * @throws RequestListenerException * @see hk.hku.cecid.piazza.commons.servlet.http.HttpRequestListener#processRequest(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ public String processRequest(HttpServletRequest request, HttpServletResponse response) throws RequestListenerException { try { Headers headers = new Headers(request, response); InternetHeaders requestHeaders = headers.getInternetHeaders(); InputStream requestStream = request.getInputStream(); AS2Message requestMessage = new AS2Message(requestHeaders, requestStream); if (requestMessage.getFromPartyID() == null || requestMessage.getToPartyID() == null) { response.sendError(HttpURLConnection.HTTP_BAD_REQUEST, "Invalid AS2 Message"); return null; } AS2Request as2request = new AS2Request(request); as2request.setMessage(requestMessage); AS2Response as2response = new AS2Response(response); processRequest(as2request, as2response); AS2Message responseMessage = as2response.getMessage(); if (responseMessage == null) { return null; } InternetHeaders responseHeaders = responseMessage.getHeaders(); headers.putInternetHeaders(responseHeaders); InputStream contentStream= responseMessage.getContentStream(); OutputStream responseStream= response.getOutputStream(); IOHandler.pipe(contentStream, responseStream); return null; } catch (Exception e) { throw new RequestListenerException("Error in processing AS2 request", e); } }
public DispositionNotification() throws AS2MessageException { multiPart = new MimeMultipart(); textPart = new MimeBodyPart(); reportPart = new MimeBodyPart(); reportValues = new InternetHeaders(); try { multiPart.setSubType(CONTENT_SUBTYPE); multiPart.addBodyPart(textPart); multiPart.addBodyPart(reportPart); } catch (MessagingException e) { throw new AS2MessageException("Unable to construct a new disposition notification", e); } }
private void parseMDN(MimeMultipart report) throws AS2MessageException { try { int reportCount = report.getCount(); for (int i = 0; i < reportCount; i++) { MimeBodyPart reportsPart = (MimeBodyPart) report.getBodyPart(i); if (reportsPart.isMimeType("text/plain")) { setText(reportsPart.getContent().toString()); } else if (reportsPart.isMimeType(AS2Header.CONTENT_TYPE_MESSAGE_DISPOSITION_NOTIFICATION)) { InternetHeaders rptValues = new InternetHeaders(reportsPart .getInputStream()); setReportValue(REPORTING_UA, rptValues.getHeader( REPORTING_UA, ", ")); setOriginalMessageID(rptValues.getHeader( ORIG_RECIPIENT, ", ")); setReportValue(FINAL_RECIPIENT, rptValues.getHeader( FINAL_RECIPIENT, ", ")); setReportValue(ORIG_MESSAGE_ID, rptValues.getHeader( ORIG_MESSAGE_ID, ", ")); setReportValue(DISPOSITION, rptValues.getHeader( DISPOSITION, ", ")); setReportValue(RECEIVED_CONTENT_MIC, rptValues .getHeader(RECEIVED_CONTENT_MIC, ", ")); } } } catch (Exception e) { throw new AS2MessageException("Error in parsing MDN", e); } }
/** * Creates a new instance of AS2Message. */ public AS2Message() { this.headers = new InternetHeaders(); this.bodyPart = new MimeBodyPart(); setHeader(AS2Header.SUBJECT, "AS2 Message"); setHeader(AS2Header.FROM, getDefaultEmailAddress()); setHeader(AS2Header.AS2_VERSION, "1.1"); setHeader(AS2Header.DATE, StringUtilities.toGMTString(new Date())); setMessageID(generateID()); }
/** * Creates a new instance of AS2Message. * * @param message the message as input stream. * @throws AS2MessageException if unable to construct from the given input stream. */ public AS2Message(InputStream message) throws AS2MessageException { try { BufferedInputStream bis= new BufferedInputStream(message); load(new InternetHeaders(bis), bis); bis.close(); } catch (Exception e) { throw new AS2MessageException( "Unable to construct AS2 message from input stream", e); } }
/** * Loads the given headers and content to this message. * * @param headers the message headers. * @param content the message content. * @throws MessagingException if unable to construct the mime body part. * @throws IOException unable to read the content stream. */ private void load(InternetHeaders headers, InputStream content) throws MessagingException, IOException { InternetHeaders bodyHeaders = new InternetHeaders(); copyHeaders(headers, bodyHeaders, "(?i)(?s)content-.*", true); this.headers = headers; this.bodyPart = new MimeBodyPart(bodyHeaders, IOHandler .readBytes(content)); }
/** * Gets the headers of this message. * * @return a copy of the headers of this message. */ public InternetHeaders getHeaders() { InternetHeaders h = new InternetHeaders(); copyHeaders(headers, h, null, false); copyHeaders(bodyPart, h, null, false); return h; }
/** * Creates a new instance of SFRM Message. * * @param message * the message as input stream. * @throws SFRMMessageException * if unable to construct from the given input stream. */ public SFRMMessage(InputStream message) throws SFRMMessageException { try { BufferedInputStream bis = new BufferedInputStream(message); this.load(new InternetHeaders(bis), bis); bis.close(); } catch (Exception e) { throw new SFRMMessageException( "Unable to construct SFRM message from input stream", e); } }
private static MimeMultipart split(byte[] pattern, byte[] input, int sizeLimit) { MimeMultipart mmp = new MimeMultipart(); int start = 0; int pos = Bytes.indexOf(input, pattern); int size = input.length; int entryCount = 0; ByteBuffer buffer = ByteBuffer.wrap(input); while(pos != -1 && start < size){ int end = pos + pattern.length; if(entryCount != 0){ //dont add the boundary itself - which is what you have in the first iteration buffer.position(start); //not a copy but points to the buffer //used for the indexOf functionality to keep checking //further on in the buffer - current pos -> end of buffer byte[] tmpBuffer = buffer.slice().array(); //set limit - now that limit is set re-slice to only get the needed //area - buffer.limit(end); try { MimeBodyPart mbp = new MimeBodyPart(new InternetHeaders(), buffer.slice().array()); mmp.addBodyPart(mbp); } catch (MessagingException e) { log.error(e.getMessage(), e); } pos = Bytes.indexOf(tmpBuffer, pattern); } entryCount++; start = end; } return mmp; }
private void extractHeader(String headerMame, Message camelMessage, InternetHeaders headers) { String h = camelMessage.getHeader(headerMame, String.class); if (h != null) { headers.addHeader(headerMame, h); camelMessage.removeHeader(headerMame); } }
public MediaBodyPart(InputStream is) throws MessagingException { // Process the headers from the input stream super(new InternetHeaders(is), null); // Create a media stream source to read the remaining data, using the // content type information from the headers. mediaSource = new MediaStreamSource(is, getContentType()); initMediaDataHandler(); }
public MediaBodyPart(InternetHeaders headers, byte [] content) throws MessagingException { super(headers, content); // javax.mail.util.SharedByteArrayInputStream here. String contentType = getContentType(); MediaStreamSource mediaStreamSource = new MediaStreamSource(new ByteArrayInputStream(content), contentType); String etag = getHeader(GDataProtocol.Header.ETAG, null); if (etag != null) { mediaStreamSource.setEtag(etag); } mediaSource = mediaStreamSource; initMediaDataHandler(); }
private Enumeration createCopyOfHeaders(BodyPart part) throws MessagingException { Enumeration headers = part.getAllHeaders(); InternetHeaders internetHeaders = new InternetHeaders(); while (headers.hasMoreElements()) { Header header = (Header) headers.nextElement(); internetHeaders.addHeader(header.getName(), header.getValue()); } return internetHeaders.getAllHeaders(); }
/** * If we already parsed the headers then we simply return the updated ones. * Otherwise we parse * * @see javax.mail.internet.MimeMessage#createInternetHeaders(java.io.InputStream) */ protected synchronized InternetHeaders createInternetHeaders(InputStream is) throws MessagingException { /* * This code is no more needed: see JAMES-570 and new tests * * InternetHeaders can be a bit awkward to work with due to its own * internal handling of header order. This hack may not always be * necessary, but for now we are trying to ensure that there is a * Return-Path header, even if just a placeholder, so that later, e.g., * in LocalDelivery, when we call setHeader, it will remove any other * Return-Path headers, and ensure that ours is on the top. addHeader * handles header order, but not setHeader. This may change in future * JavaMail. But if there are other Return-Path header values, let's * drop our placeholder. * * MailHeaders newHeaders = new MailHeaders(new * ByteArrayInputStream((f.RETURN_PATH + ": placeholder").getBytes())); * newHeaders.setHeader(RFC2822Headers.RETURN_PATH, null); * newHeaders.load(is); String[] returnPathHeaders = * newHeaders.getHeader(RFC2822Headers.RETURN_PATH); if * (returnPathHeaders.length > 1) * newHeaders.setHeader(RFC2822Headers.RETURN_PATH, * returnPathHeaders[1]); */ // Keep this: skip the headers from the stream // we could put that code in the else and simple write an "header" // skipping // reader for the others. MailHeaders newHeaders = new MailHeaders(is); if (headers != null) { return headers; } else { initialHeaderSize = newHeaders.getSize(); return newHeaders; } }
protected MimeMessage getMultipartMessage() throws Exception { MimeMessage mmCreated = new MimeMessage(Session.getDefaultInstance(new Properties())); mmCreated.setSubject("test"); MimeMultipart mm = new MimeMultipart("alternative"); mm.addBodyPart(new MimeBodyPart(new InternetHeaders(new ByteArrayInputStream("X-header: test1\r\nContent-Type: text/plain; charset=Cp1252\r\n".getBytes())), "first part \u00F2\u00E0\u00F9".getBytes())); mm.addBodyPart(new MimeBodyPart(new InternetHeaders(new ByteArrayInputStream("X-header: test2\r\nContent-Type: text/plain; charset=Cp1252\r\nContent-Transfer-Encoding: quoted-printable\r\n".getBytes())), "second part =E8=E8".getBytes())); mmCreated.setContent(mm); mmCreated.saveChanges(); return mmCreated; }