private void writeBodyPart(byte[] bodyContent, Part part, ContentType contentType)
     throws MessagingException {
   DataSource ds = new ByteArrayDataSource(bodyContent, contentType.toString());
   part.setDataHandler(new DataHandler(ds));
   part.setHeader(CONTENT_TYPE, contentType.toString());
   if (contentType.match("text/*")) {
     part.setHeader(CONTENT_TRANSFER_ENCODING, "8bit");
   } else if (binaryContent) {
     part.setHeader(CONTENT_TRANSFER_ENCODING, "binary");
   } else {
     part.setHeader(CONTENT_TRANSFER_ENCODING, "base64");
   }
 }
 public AlfrescoMimeMultipart(String subtype, FileInfo messageFileInfo) {
   super();
   String boundary = getBoundaryValue(messageFileInfo);
   ContentType cType = new ContentType("multipart", subtype, null);
   cType.setParameter("boundary", boundary);
   contentType = cType.toString();
 }
Example #3
0
  // Request content type resolution follows similar precedence order to accept type:
  // 1. Request header
  // 2. RestLiRequestOption
  // 3. RestClient configuration
  private void addEntityAndContentTypeHeaders(
      RestRequestBuilder builder, DataMap dataMap, ContentType contentType) throws IOException {
    if (dataMap != null) {
      String header = builder.getHeader(RestConstants.HEADER_CONTENT_TYPE);

      ContentType type;
      if (header == null) {
        if (contentType != null) {
          type = contentType;
        } else if (_contentType != null) {
          type = _contentType;
        } else {
          type = DEFAULT_CONTENT_TYPE;
        }
        builder.setHeader(RestConstants.HEADER_CONTENT_TYPE, type.getHeaderKey());
      } else {
        javax.mail.internet.ContentType headerContentType;
        try {
          headerContentType = new javax.mail.internet.ContentType(header);
        } catch (ParseException e) {
          throw new IllegalStateException("Unable to parse Content-Type: " + header);
        }

        if (headerContentType
            .getBaseType()
            .equalsIgnoreCase(RestConstants.HEADER_VALUE_APPLICATION_JSON)) {
          type = ContentType.JSON;
        } else if (headerContentType
            .getBaseType()
            .equalsIgnoreCase(RestConstants.HEADER_VALUE_APPLICATION_PSON)) {
          type = ContentType.PSON;
        } else {
          throw new IllegalStateException("Unknown Content-Type: " + headerContentType.toString());
        }
      }

      switch (type) {
        case PSON:
          builder.setEntity(PSON_DATA_CODEC.mapToBytes(dataMap));
          break;
        case JSON:
          builder.setEntity(JACKSON_DATA_CODEC.mapToBytes(dataMap));
          break;
        default:
          throw new IllegalStateException("Unknown ContentType:" + type);
      }
    }
  }
Example #4
0
  /**
   * This method can be used to handle an incoming HTTP message AFTER the headers where extracted.
   *
   * @param sClientInfo Client connection info
   * @param aMsgData The message body
   * @param aMsg The AS2 message that will be filled by this method
   * @param aResponseHandler The response handler which handles HTTP error messages as well as
   *     synchronous MDN.
   */
  public void handleIncomingMessage(
      @Nonnull final String sClientInfo,
      @Nonnull final byte[] aMsgData,
      @Nonnull final AS2Message aMsg,
      @Nonnull final IAS2HttpResponseHandler aResponseHandler) {
    // TODO store HTTP request, headers, and data to file in Received folder
    // -> use message-id for filename?
    try {
      final IAS2Session aSession = m_aReceiverModule.getSession();

      try {
        // Put received data in a MIME body part
        final ContentType aReceivedContentType =
            new ContentType(aMsg.getHeader(CAS2Header.HEADER_CONTENT_TYPE));
        final String sReceivedContentType = aReceivedContentType.toString();

        final MimeBodyPart aReceivedPart = new MimeBodyPart();
        aReceivedPart.setDataHandler(
            new DataHandler(new ByteArrayDataSource(aMsgData, sReceivedContentType, null)));

        // Header must be set AFTER the DataHandler!
        aReceivedPart.setHeader(CAS2Header.HEADER_CONTENT_TYPE, sReceivedContentType);
        aMsg.setData(aReceivedPart);
      } catch (final Exception ex) {
        throw new DispositionException(
            DispositionType.createError("unexpected-processing-error"),
            AbstractActiveNetModule.DISP_PARSING_MIME_FAILED,
            ex);
      }

      // Extract AS2 ID's from header, find the message's partnership and
      // update the message
      try {
        final String sAS2From = aMsg.getAS2From();
        aMsg.getPartnership().setSenderAS2ID(sAS2From);

        final String sAS2To = aMsg.getAS2To();
        aMsg.getPartnership().setReceiverAS2ID(sAS2To);

        // Fill all partnership attributes etc.
        aSession.getPartnershipFactory().updatePartnership(aMsg, false);
      } catch (final OpenAS2Exception ex) {
        throw new DispositionException(
            DispositionType.createError("authentication-failed"),
            AbstractActiveNetModule.DISP_PARTNERSHIP_NOT_FOUND,
            ex);
      }

      // Per RFC5402 compression is always before encryption but can be before
      // or after signing of message but only in one place
      final ICryptoHelper aCryptoHelper = AS2Helper.getCryptoHelper();
      boolean bIsDecompressed = false;

      // Decrypt and verify signature of the data, and attach data to the
      // message
      decrypt(aMsg);

      if (aCryptoHelper.isCompressed(aMsg.getContentType())) {
        if (s_aLogger.isTraceEnabled())
          s_aLogger.trace("Decompressing received message before checking signature...");
        decompress(aMsg);
        bIsDecompressed = true;
      }

      verify(aMsg);

      if (aCryptoHelper.isCompressed(aMsg.getContentType())) {
        // Per RFC5402 compression is always before encryption but can be before
        // or after signing of message but only in one place
        if (bIsDecompressed) {
          throw new DispositionException(
              DispositionType.createError("decompression-failed"),
              AbstractActiveNetModule.DISP_DECOMPRESSION_ERROR,
              new Exception(
                  "Message has already been decompressed. Per RFC5402 it cannot occur twice."));
        }

        if (s_aLogger.isTraceEnabled())
          if (aMsg.containsAttribute(AS2Message.ATTRIBUTE_RECEIVED_SIGNED))
            s_aLogger.trace("Decompressing received message after verifying signature...");
          else s_aLogger.trace("Decompressing received message after decryption...");
        decompress(aMsg);
        bIsDecompressed = true;
      }

      if (s_aLogger.isTraceEnabled())
        try {
          s_aLogger.trace(
              "SMIME Decrypted Content-Disposition: "
                  + aMsg.getContentDisposition()
                  + "\n      Content-Type received: "
                  + aMsg.getContentType()
                  + "\n      HEADERS after decryption: "
                  + aMsg.getData().getAllHeaders()
                  + "\n      Content-Disposition in MSG detData() MIMEPART after decryption: "
                  + aMsg.getData().getContentType());
        } catch (final MessagingException ex) {
          s_aLogger.error("Failed to trace message: " + aMsg, ex);
        }

      // Validate the received message before storing
      try {
        aSession
            .getMessageProcessor()
            .handle(IProcessorStorageModule.DO_VALIDATE_BEFORE_STORE, aMsg, null);
      } catch (final NoModuleException ex) {
        // No module installed - ignore
      } catch (final OpenAS2Exception ex) {
        throw new DispositionException(
            DispositionType.createError("unexpected-processing-error"),
            AbstractActiveNetModule.DISP_VALIDATION_FAILED
                + "\n"
                + StackTraceHelper.getStackAsString(ex),
            ex);
      }

      // Store the received message
      try {
        aSession.getMessageProcessor().handle(IProcessorStorageModule.DO_STORE, aMsg, null);
      } catch (final NoModuleException ex) {
        // No module installed - ignore
      } catch (final OpenAS2Exception ex) {
        throw new DispositionException(
            DispositionType.createError("unexpected-processing-error"),
            AbstractActiveNetModule.DISP_STORAGE_FAILED + "\n" + ex.getMessage(),
            ex);
      }

      // Validate the received message after storing
      try {
        aSession
            .getMessageProcessor()
            .handle(IProcessorStorageModule.DO_VALIDATE_AFTER_STORE, aMsg, null);
      } catch (final NoModuleException ex) {
        // No module installed - ignore
      } catch (final OpenAS2Exception ex) {
        throw new DispositionException(
            DispositionType.createError("unexpected-processing-error"),
            AbstractActiveNetModule.DISP_VALIDATION_FAILED
                + "\n"
                + StackTraceHelper.getStackAsString(ex),
            ex);
      }

      try {
        if (aMsg.isRequestingMDN()) {
          // Transmit a success MDN if requested
          sendSyncMDN(
              sClientInfo,
              aResponseHandler,
              aMsg,
              DispositionType.createSuccess(),
              AbstractActiveNetModule.DISP_SUCCESS);
        } else {
          // Just send a HTTP OK
          HTTPHelper.sendSimpleHTTPResponse(aResponseHandler, HttpURLConnection.HTTP_OK);
          s_aLogger.info("sent HTTP OK " + sClientInfo + aMsg.getLoggingText());
        }
      } catch (final Exception ex) {
        throw new WrappedOpenAS2Exception(
            "Error creating and returning MDN, message was stilled processed", ex);
      }
    } catch (final DispositionException ex) {
      sendSyncMDN(sClientInfo, aResponseHandler, aMsg, ex.getDisposition(), ex.getText());
      m_aReceiverModule.handleError(aMsg, ex);
    } catch (final OpenAS2Exception ex) {
      m_aReceiverModule.handleError(aMsg, ex);
    }
  }