javax.mail.internet.InternetHeaders Java Examples

The following examples show how to use javax.mail.internet.InternetHeaders. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ExchangeSession.java    From davmail with GNU General Public License v2.0 6 votes vote down vote up
public Enumeration<?> getMatchingHeaderLinesFromHeaders(String[] headerNames) throws MessagingException {
    Enumeration<?> result = null;
    if (mimeMessage == null) {
        // message not loaded, try to get headers only
        InputStream headers = getMimeHeaders();
        if (headers != null) {
            InternetHeaders internetHeaders = new InternetHeaders(headers);
            if (internetHeaders.getHeader("Subject") == null) {
                // invalid header content
                return null;
            }
            if (headerNames == null) {
                result = internetHeaders.getAllHeaderLines();
            } else {
                result = internetHeaders.getMatchingHeaderLines(headerNames);
            }
        }
    }
    return result;
}
 
Example #2
Source File: BaseMessageMDN.java    From OpenAs2App with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
    // read in partnership
    partnership = (Partnership) in.readObject();

    // read in attributes
    attributes = (Map<String, String>) in.readObject();

    // read in text
    text = (String) in.readObject();

    try {
        // read in message headers
        headers = new InternetHeaders(in);

        // read in mime body
        if (in.read() == 1) {
            data = new MimeBodyPart(in);
        } else {
            data = null;
        }
    } catch (MessagingException me) {
        throw new IOException("Messaging exception: " + me.getMessage());
    }
}
 
Example #3
Source File: MimeUtil.java    From OpenAs2App with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static int getContentLength(InternetHeaders headers) throws IOException {
    // get the content length
    String contentLengthStr = getHeader(headers, "Content-Length");

    // content-length is required
    if (contentLengthStr == null) {
        throw new IOException("Content-Length missing");
    }

    // convert the content length to an int
    try {
        return Integer.parseInt(contentLengthStr);
    } catch (NumberFormatException nfe) {
        throw new IOException("Invalid Content-Length: " + contentLengthStr);
    }
}
 
Example #4
Source File: MimeUtil.java    From OpenAs2App with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static MimeBodyPart readMimeBodyPart(InputStream source, InternetHeaders headers) throws IOException, MessagingException {
    // get the length of the Mime body's data
    int contentLength = getContentLength(headers);

    // read the data into a byte array
    DataInputStream dataIn = new DataInputStream(source);
    byte[] data = new byte[contentLength];
    dataIn.readFully(data);

    // convert the byte array to a MimeBodyPart
    String contentTransferEncoding = getHeader(headers, "Content-Transfer-Encoding");
    if (contentTransferEncoding == null) {
        contentTransferEncoding = Session.DEFAULT_CONTENT_TRANSFER_ENCODING;
    }
    return createMimeBodyPart(data, getHeader(headers, "Content-Type"), contentTransferEncoding);
}
 
Example #5
Source File: HTTPUtilTest.java    From OpenAs2App with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void handlesMultiEntryAS2IdWithSpacesAndQuotes() {
    String fromIdKey = "AS2-From";
    String toIdKey = "AS2-To";
    String fromId = "Thats You";
    String toId = "Thats Me";

    Message msg = new AS2Message();
    InternetHeaders hdrs = new InternetHeaders();
    msg.setHeaders(hdrs);
    hdrs.addHeader(fromIdKey, fromId);
    hdrs.addHeader(fromIdKey, "\"" + fromId + "\"");
    hdrs.addHeader(fromIdKey, fromId);
    hdrs.addHeader(toIdKey, toId);
    hdrs.addHeader(toIdKey, "\"" + toId + "\"");
    HTTPUtil.cleanIdHeaders(msg.getHeaders());
    msg.getPartnership().setSenderID(Partnership.PID_AS2, msg.getHeader(fromIdKey));
    msg.getPartnership().setReceiverID(Partnership.PID_AS2, msg.getHeader(toIdKey));
    assertThat("Duplicate FROM headers have been removed", msg.getPartnership().getSenderID(Partnership.PID_AS2), equalTo(fromId));
    assertThat("Duplicate TO headers have been removed", msg.getPartnership().getReceiverID(Partnership.PID_AS2), equalTo(toId));
}
 
Example #6
Source File: SmtpManager.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #7
Source File: RMetadataUtils.java    From nexus-repository-r with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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);
  }
}
 
Example #8
Source File: RPackagesBuilder.java    From nexus-repository-r with Eclipse Public License 1.0 6 votes vote down vote up
private void writePackageInfo(final OutputStreamWriter writer, final Map<String, String> packageInfo)
    throws IOException
{
  InternetHeaders headers = new InternetHeaders();
  headers.addHeader(P_PACKAGE, packageInfo.get(P_PACKAGE));
  headers.addHeader(P_VERSION, packageInfo.get(P_VERSION));
  headers.addHeader(P_DEPENDS, packageInfo.get(P_DEPENDS));
  headers.addHeader(P_IMPORTS, packageInfo.get(P_IMPORTS));
  headers.addHeader(P_SUGGESTS, packageInfo.get(P_SUGGESTS));
  headers.addHeader(P_LINKINGTO, packageInfo.get(P_LINKINGTO));
  headers.addHeader(P_LICENSE, packageInfo.get(P_LICENSE));
  headers.addHeader(P_NEEDS_COMPILATION, packageInfo.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');
}
 
Example #9
Source File: MimeMessageTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
protected MimeMessage getMissingEncodingMessage() 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: 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;
}
 
Example #10
Source File: MimeMessageTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultipartMessageChanges() throws Exception {

    MimeMessage mm = getMultipartMessage();

    MimeMultipart content1 = (MimeMultipart) mm.getContent();
    BodyPart b1 = content1.getBodyPart(0);
    b1.setContent("test€", "text/plain; charset=Cp1252");
    mm.setContent(content1, mm.getContentType());
    // .setHeader(RFC2822Headers.CONTENT_TYPE,contentType);
    mm.saveChanges();

    assertThat(getCleanedMessageSource(mm)).isEqualTo(getMultipartMessageExpected1());

    MimeMultipart content2 = (MimeMultipart) mm.getContent();
    content2.addBodyPart(new MimeBodyPart(new InternetHeaders(new ByteArrayInputStream(
            "Subject: test3\r\n".getBytes())), "third part".getBytes()));
    mm.setContent(content2, mm.getContentType());
    mm.saveChanges();

    assertThat(getCleanedMessageSource(mm)).isEqualTo(getMultipartMessageExpected2());

    mm.setContent("mynewcoòàùntent€à!", "text/plain; charset=cp1252");
    mm.setHeader(RFC2822Headers.CONTENT_TYPE, "binary/octet-stream");
    // mm.setHeader("Content-Transfer-Encoding","8bit");
    mm.saveChanges();

    assertThat(getCleanedMessageSource(mm)).isEqualTo(getMultipartMessageExpected3());

    LifecycleUtil.dispose(mm);

}
 
Example #11
Source File: MimeMessageTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
protected MimeMessage getMultipartMessage() throws Exception {
    MimeMessage mmCreated = MimeMessageUtil.defaultMimeMessage();
    mmCreated.setSubject("test");
    mmCreated.addHeader("Date", "Tue, 16 Jan 2018 09:56:01 +0700 (ICT)");
    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 òàù".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;
}
 
Example #12
Source File: MimeMessageWrapper.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * If we already parsed the headers then we simply return the updated ones.
 * Otherwise we parse
 */
@Override
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;
    }
}
 
Example #13
Source File: HTTPUtil.java    From OpenAs2App with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void copyHttpHeaders(HttpURLConnection conn, InternetHeaders headers) {
    Iterator<Map.Entry<String, List<String>>> connHeadersIt = conn.getHeaderFields().entrySet().iterator();
    Iterator<String> connValuesIt;
    Map.Entry<String, List<String>> connHeader;
    String headerName;

    while (connHeadersIt.hasNext()) {
        connHeader = connHeadersIt.next();
        headerName = connHeader.getKey();

        if (headerName != null) {
            connValuesIt = connHeader.getValue().iterator();

            while (connValuesIt.hasNext()) {
                String value = connValuesIt.next();

                String[] existingVals = headers.getHeader(headerName);
                if (existingVals == null) {
                    headers.setHeader(headerName, value);
                } else {
                    // Avoid duplicates of the same value since headers that exist in the HTTP
                    // headers
                    // may already have been inserted in the Message object
                    boolean exists = false;
                    for (int i = 0; i < existingVals.length; i++) {
                        if (value.equals(existingVals[i])) {
                            exists = true;
                        }
                    }
                    if (!exists) {
                        headers.addHeader(headerName, value);
                    }
                }
            }
        }
    }
}
 
Example #14
Source File: HTTPUtil.java    From OpenAs2App with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Cleans specific headers to ensure AS2 compatibility
 *
 * @param hdrs Headers to be cleaned
 */
public static void cleanIdHeaders(InternetHeaders hdrs) {
    // Handle the case where the AS2 ID could be encapsulated in double quotes per RFC4130
    // some AS2 applications will send the quoted AND the unquoted ID so need
    String[] idHeaders = {"AS2-From", "AS2-To"};
    for (int i = 0; i < idHeaders.length; i++) {
        // Target only the first entry if there is more than one to get a single value
        String value = StringUtil.removeDoubleQuotes(hdrs.getHeader(idHeaders[i], null));
        // Delete all headers with the same key
        hdrs.removeHeader(idHeaders[i]);
        // Add back as a single value without quotes
        hdrs.setHeader(idHeaders[i], value);
    }
}
 
Example #15
Source File: MimeUtil.java    From OpenAs2App with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static String getHeader(InternetHeaders headers, String key, String delimiter) {
    // TODO test this to make sure it returns null if no header values exist
    // - I remember something about it returning a blank string instead
    String value = headers.getHeader(key, delimiter);

    if (value == null) {
        return null;
    } else if (value.equalsIgnoreCase("null")) {
        return null;
    } else {
        return value;
    }
}
 
Example #16
Source File: AS2SenderModule.java    From OpenAs2App with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void sendMessage(String url, Message msg, MimeBodyPart securedData, String retries) throws Exception {
    URL urlObj = new URL(url);
    InternetHeaders ih = getHttpHeaders(msg, securedData);
    msg.setAttribute(NetAttribute.MA_DESTINATION_IP, urlObj.getHost());
    msg.setAttribute(NetAttribute.MA_DESTINATION_PORT, Integer.toString(urlObj.getPort()));

    if (logger.isInfoEnabled()) {
        logger.info("Connecting to: " + url + msg.getLogMsgID());
    }

    Map<String, String> httpOptions = getHttpOptions();
    httpOptions.put(HTTPUtil.PARAM_HTTP_USER, msg.getPartnership().getAttribute(HTTPUtil.PARAM_HTTP_USER));
    httpOptions.put(HTTPUtil.PARAM_HTTP_PWD, msg.getPartnership().getAttribute(HTTPUtil.PARAM_HTTP_PWD));
    long maxSize = msg.getPartnership().getNoChunkedMaxSize();
    ResponseWrapper resp = HTTPUtil.execRequest(HTTPUtil.Method.POST, url, ih.getAllHeaders(), null, securedData.getInputStream(), httpOptions, maxSize);
    if (logger.isInfoEnabled()) {
        logger.info("Message sent and response received in " + resp.getTransferTimeMs() + "ms" + msg.getLogMsgID());
    }

    // Check the HTTP Response code
    int rc = resp.getStatusCode();
    if ((rc != HttpURLConnection.HTTP_OK) && (rc != HttpURLConnection.HTTP_CREATED) && (rc != HttpURLConnection.HTTP_ACCEPTED) && (rc != HttpURLConnection.HTTP_PARTIAL) && (rc != HttpURLConnection.HTTP_NO_CONTENT)) {
        msg.setLogMsg("Error sending message. URL: " + url + " ::: Response Code: " + rc + " " + resp.getStatusPhrase() + " ::: Response Message: " + resp.getBody().toString());
        logger.error(msg);
        throw new HttpResponseException(url, rc, resp.getStatusPhrase());
    }
    // So far so good ...
    processResponse(msg, resp);
}
 
Example #17
Source File: SmtpManager.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
protected MimeMultipart getMimeMultipart(final byte[] encodedBytes, final InternetHeaders headers)
    throws MessagingException {
    final MimeMultipart mp = new MimeMultipart();
    final MimeBodyPart part = new MimeBodyPart(headers, encodedBytes);
    mp.addBodyPart(part);
    return mp;
}
 
Example #18
Source File: BaseMessageMDN.java    From OpenAs2App with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void copyHeaders(InternetHeaders srcHeaders) {
    Enumeration<Header> headerEn = srcHeaders.getAllHeaders();
    while (headerEn.hasMoreElements()) {
        Header header = headerEn.nextElement();
        setHeader(header.getName(), header.getValue());
    }
}
 
Example #19
Source File: RPackagesUtils.java    From nexus-repository-r with Eclipse Public License 1.0 5 votes vote down vote up
public 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_LINKINGTO, entry.get(P_LINKINGTO));
        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"));
}
 
Example #20
Source File: BaseMessage.java    From OpenAs2App with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
    // read in partnership
    partnership = (Partnership) in.readObject();

    // read in attributes
    attributes = (Map<String, String>) in.readObject();

    // read in data history
    history = (DataHistory) in.readObject();

    try {
        // read in message headers
        headers = new InternetHeaders(in);

        // read in mime body 
        if (in.read() == 1) {
            data = new MimeBodyPart(in);
        }
    } catch (MessagingException me) {
        throw new IOException("Messaging exception: " + me.getMessage());
    }

    // read in MDN
    MDN = (MessageMDN) in.readObject();

    if (MDN != null) {
        MDN.setMessage(this);
    }

    customOuterMimeHeaders = new HashMap<String, String>();
}
 
Example #21
Source File: FileUploadsUtil.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
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;
  }
 
Example #22
Source File: PyPiInfoUtils.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Parses the PKG-INFO content as RFC 822 headers (per PEPs 241 and 314). (Yes, Python PKG-INFO information is
 * essentially stored as a file of email headers.)
 */
@VisibleForTesting
static Map<String, List<String>> parsePackageInfo(final InputStream in) throws Exception {
  checkNotNull(in);
  LinkedHashMap<String, List<String>> results = new LinkedHashMap<>();

  // All package info or metadata file types have their metadata stored in the same manner as email headers
  InternetHeaders headers = new InternetHeaders(in);
  Enumeration<Header> headerEnumeration = headers.getAllHeaders();
  while (headerEnumeration.hasMoreElements()) {
    Header header = headerEnumeration.nextElement();
    String underscoreName = header.getName().toLowerCase().replace('-', '_');
    String name = NAME_SUBSTITUTIONS.getOrDefault(underscoreName, underscoreName);
    String value = convertHeaderValue(header.getValue());
    if (!results.containsKey(name)) {
      results.put(name, new ArrayList<>());
    }
    results.get(name).add(value);
  }

  // Wheel metadata can also be stored in the payload section (description only, so far as I'm aware)
  if (!results.containsKey(PyPiAttributes.P_DESCRIPTION)) {
    String text =  Strings.nullToEmpty(CharStreams.toString(new InputStreamReader(in, StandardCharsets.UTF_8))).trim();
    if (!text.isEmpty()) {
      List<String> description = new ArrayList<>();
      description.add(text.replace("\r\n", "\n").replaceAll("[ ]*\\n[ ]*", "\n") + "\n");
      results.put(PyPiAttributes.P_DESCRIPTION, description);
    }
  }

  return results;
}
 
Example #23
Source File: AS2ReceiverHandler.java    From OpenAs2App with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void createMDNData(Session session, MessageMDN mdn, String micAlg, String signatureProtocol) throws Exception {
    // Create the report and sub-body parts
    MimeMultipart reportParts = new MimeMultipart();

    // Create the text part
    MimeBodyPart textPart = new MimeBodyPart();
    String text = mdn.getText() + "\r\n";
    textPart.setContent(text, "text/plain");
    textPart.setHeader("Content-Type", "text/plain");
    reportParts.addBodyPart(textPart);

    // Create the report part
    MimeBodyPart reportPart = new MimeBodyPart();
    InternetHeaders reportValues = new InternetHeaders();
    reportValues.setHeader("Reporting-UA", mdn.getAttribute(AS2MessageMDN.MDNA_REPORTING_UA));
    reportValues.setHeader("Original-Recipient", mdn.getAttribute(AS2MessageMDN.MDNA_ORIG_RECIPIENT));
    reportValues.setHeader("Final-Recipient", mdn.getAttribute(AS2MessageMDN.MDNA_FINAL_RECIPIENT));
    reportValues.setHeader("Original-Message-ID", mdn.getAttribute(AS2MessageMDN.MDNA_ORIG_MESSAGEID));
    reportValues.setHeader("Disposition", mdn.getAttribute(AS2MessageMDN.MDNA_DISPOSITION));
    reportValues.setHeader("Received-Content-MIC", mdn.getAttribute(AS2MessageMDN.MDNA_MIC));

    Enumeration<String> reportEn = reportValues.getAllHeaderLines();
    StringBuffer reportData = new StringBuffer();

    while (reportEn.hasMoreElements()) {
        reportData.append(reportEn.nextElement()).append("\r\n");
    }

    reportData.append("\r\n");

    String reportText = reportData.toString();
    reportPart.setContent(reportText, AS2Standards.DISPOSITION_TYPE);
    reportPart.setHeader("Content-Type", AS2Standards.DISPOSITION_TYPE);
    reportParts.addBodyPart(reportPart);

    // Convert report parts to MimeBodyPart
    MimeBodyPart report = new MimeBodyPart();
    reportParts.setSubType(AS2Standards.REPORT_SUBTYPE);
    report.setContent(reportParts);
    String contentType = reportParts.getContentType();
    if ("true".equalsIgnoreCase(Properties.getProperty("remove_multipart_content_type_header_folding", "false"))) {
        contentType = contentType.replaceAll("\r\n[ \t]*", " ");
    }
    report.setHeader("Content-Type", contentType);

    // Sign the data if needed
    if (signatureProtocol != null) {
        CertificateFactory certFx = session.getCertificateFactory();

        try {
            // The receiver of the original message is the sender of the MDN....
            X509Certificate senderCert = certFx.getCertificate(mdn, Partnership.PTYPE_RECEIVER);
            PrivateKey senderKey = certFx.getPrivateKey(mdn, senderCert);
            Partnership p = mdn.getPartnership();
            String contentTxfrEncoding = p.getAttribute(Partnership.PA_CONTENT_TRANSFER_ENCODING);
            boolean isRemoveCmsAlgorithmProtectionAttr = "true".equalsIgnoreCase(p.getAttribute(Partnership.PA_REMOVE_PROTECTION_ATTRIB));
            if (contentTxfrEncoding == null) {
                contentTxfrEncoding = Session.DEFAULT_CONTENT_TRANSFER_ENCODING;
            }
            // sign the data using CryptoHelper
            MimeBodyPart signedReport = AS2Util.getCryptoHelper().sign(report, senderCert, senderKey, micAlg, contentTxfrEncoding, false, isRemoveCmsAlgorithmProtectionAttr);
            mdn.setData(signedReport);
        } catch (CertificateNotFoundException cnfe) {
            cnfe.terminate();
            mdn.setData(report);
        } catch (KeyNotFoundException knfe) {
            knfe.terminate();
            mdn.setData(report);
        }
    } else {
        mdn.setData(report);
    }

    // Update the MDN headers with content information
    MimeBodyPart data = mdn.getData();
    String headerContentType = data.getContentType();
    if ("true".equalsIgnoreCase(Properties.getProperty("remove_http_header_folding", "true"))) {
        headerContentType = headerContentType.replaceAll("\r\n[ \t]*", " ");
    }
    mdn.setHeader("Content-Type", headerContentType);

    // int size = getSize(data);
    // mdn.setHeader("Content-Length", Integer.toString(size));
}
 
Example #24
Source File: MessageHelper.java    From FairEmail with GNU General Public License v3.0 4 votes vote down vote up
String[] getReferences() throws MessagingException {
    ensureMessage(false);

    List<String> result = new ArrayList<>();
    String refs = imessage.getHeader("References", null);
    if (refs != null)
        result.addAll(Arrays.asList(getReferences(refs)));

    try {
        // Merge references of original message for threading
        if (imessage.isMimeType("multipart/report")) {
            ContentType ct = new ContentType(imessage.getContentType());
            String reportType = ct.getParameter("report-type");
            if ("delivery-status".equalsIgnoreCase(reportType) ||
                    "disposition-notification".equalsIgnoreCase(reportType)) {
                String arefs = null;
                String amsgid = null;

                MessageParts parts = new MessageParts();
                getMessageParts(imessage, parts, null);
                for (AttachmentPart apart : parts.attachments)
                    if ("text/rfc822-headers".equalsIgnoreCase(apart.attachment.type)) {
                        InternetHeaders iheaders = new InternetHeaders(apart.part.getInputStream());
                        arefs = iheaders.getHeader("References", null);
                        amsgid = iheaders.getHeader("Message-Id", null);
                        break;
                    } else if ("message/rfc822".equalsIgnoreCase(apart.attachment.type)) {
                        Properties props = MessageHelper.getSessionProperties();
                        Session isession = Session.getInstance(props, null);
                        MimeMessage amessage = new MimeMessage(isession, apart.part.getInputStream());
                        arefs = amessage.getHeader("References", null);
                        amsgid = amessage.getHeader("Message-Id", null);
                        break;
                    }

                if (arefs != null)
                    for (String ref : getReferences(arefs))
                        if (!result.contains(ref)) {
                            Log.i("rfc822 ref=" + ref);
                            result.add(ref);
                        }

                if (amsgid != null) {
                    String msgid = MimeUtility.unfold(amsgid);
                    if (!result.contains(msgid)) {
                        Log.i("rfc822 id=" + msgid);
                        result.add(msgid);
                    }
                }
            }
        }
    } catch (Throwable ex) {
        Log.w(ex);
    }

    return result.toArray(new String[0]);
}
 
Example #25
Source File: SmtpManager.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
protected InternetHeaders getHeaders(final String contentType, final String encoding) {
    final InternetHeaders headers = new InternetHeaders();
    headers.setHeader("Content-Type", contentType + "; charset=UTF-8");
    headers.setHeader("Content-Transfer-Encoding", encoding);
    return headers;
}
 
Example #26
Source File: MimeMessageBuilder.java    From james-project with Apache License 2.0 4 votes vote down vote up
public MimeMessageBuilder setMultipartWithSubMessage(MimeMessage mimeMessage) throws MessagingException, IOException {
    return setMultipartWithBodyParts(
        new MimeBodyPart(
            new InternetHeaders(new ByteArrayInputStream("Content-Type: multipart/mixed".getBytes(StandardCharsets.US_ASCII))),
            IOUtils.toByteArray(mimeMessage.getInputStream())));
}
 
Example #27
Source File: InternetHeadersInputStream.java    From james-project with Apache License 2.0 4 votes vote down vote up
public InternetHeadersInputStream(InternetHeaders headers) {
    this(headers.getAllHeaderLines());
}
 
Example #28
Source File: ResponseWrapper.java    From OpenAs2App with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void setHeaders(InternetHeaders headers) {
    this._headers = headers;
}
 
Example #29
Source File: ResponseWrapper.java    From OpenAs2App with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public InternetHeaders getHeaders() {
    return _headers;
}
 
Example #30
Source File: BaseMessage.java    From OpenAs2App with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void setHeaders(InternetHeaders headers) {
    this.headers = headers;
}