Search in sources :

Example 11 with HttpHeaderMap

use of com.helger.commons.http.HttpHeaderMap in project as2-peppol-servlet by phax.

the class AS2ServletSBDModule method handle.

public void handle(@Nonnull final String sAction, @Nonnull final IMessage aMsg, @Nullable final Map<String, Object> aOptions) throws AS2Exception {
    try {
        // Set the signing algorithm, so that the MIC calculation is done
        // correctly
        aMsg.partnership().setSigningAlgorithm(m_eAS2Version.getCryptoAlgorithmSign());
        aMsg.partnership().setVerifyUseCertificateInBodyPart(ETriState.TRUE);
        // Interpret content as SBD
        final StandardBusinessDocument aSBD = new SBDMarshaller().read(aMsg.getData().getInputStream());
        if (aSBD == null)
            throw new IllegalArgumentException("Failed to interpret the passed document as a Standard Business Document!");
        if (AS2PeppolServletConfiguration.isReceiverCheckEnabled()) {
            final PeppolSBDHDocument aDD = new PeppolSBDHDocumentReader().extractData(aSBD);
            final String sLogPrefix = "[" + aDD.getInstanceIdentifier() + "] ";
            // Get the endpoint information required from the recipient
            final EndpointType aReceiverEndpoint = _getReceiverEndpoint(sLogPrefix, aDD.getReceiverAsIdentifier(), aDD.getDocumentTypeAsIdentifier(), aDD.getProcessAsIdentifier());
            if (aReceiverEndpoint == null) {
                throw new AS2Exception(sLogPrefix + "Failed to resolve endpoint for provided receiver/documentType/process - not handling document");
            }
            // Check if the message is for us
            _checkIfReceiverEndpointURLMatches(sLogPrefix, aReceiverEndpoint);
            // Get the recipient certificate from the SMP
            _checkIfEndpointCertificateMatches(sLogPrefix, aReceiverEndpoint);
        } else {
            LOGGER.info("Endpoint checks for the AS2 AP are disabled");
        }
        // Handle incoming document via SPI
        final HttpHeaderMap aHeaders = aMsg.headers().getClone();
        for (final IAS2IncomingSBDHandlerSPI aHandler : m_aHandlers) aHandler.handleIncomingSBD(aHeaders, aSBD);
    } catch (final Exception ex) {
        // Something went wrong
        throw WrappedAS2Exception.wrap(ex);
    }
}
Also used : SBDMarshaller(com.helger.sbdh.SBDMarshaller) HttpHeaderMap(com.helger.commons.http.HttpHeaderMap) PeppolSBDHDocument(com.helger.peppol.sbdh.PeppolSBDHDocument) StandardBusinessDocument(org.unece.cefact.namespaces.sbdh.StandardBusinessDocument) AS2Exception(com.helger.as2lib.exception.AS2Exception) WrappedAS2Exception(com.helger.as2lib.exception.WrappedAS2Exception) EndpointType(com.helger.smpclient.peppol.jaxb.EndpointType) PeppolSBDHDocumentReader(com.helger.peppol.sbdh.read.PeppolSBDHDocumentReader) AS2Exception(com.helger.as2lib.exception.AS2Exception) WrappedAS2Exception(com.helger.as2lib.exception.WrappedAS2Exception) CertificateException(java.security.cert.CertificateException)

Example 12 with HttpHeaderMap

use of com.helger.commons.http.HttpHeaderMap in project as2-lib by phax.

the class AS2ReceiverHandler method sendMDN.

protected void sendMDN(@Nonnull final String sClientInfo, @Nonnull final IAS2HttpResponseHandler aResponseHandler, @Nonnull final AS2Message aMsg, @Nonnull final DispositionType aDisposition, @Nonnull final String sText, @Nonnull final ESuccess eSuccess) {
    final boolean bAllowErrorMDN = !aMsg.partnership().isBlockErrorMDN();
    if (eSuccess.isSuccess() || bAllowErrorMDN) {
        try {
            final IAS2Session aSession = m_aReceiverModule.getSession();
            final IMessageMDN aMdn = AS2Helper.createMDN(aSession, aMsg, aDisposition, sText);
            if (aMsg.isRequestingAsynchMDN()) {
                // if asyncMDN requested, close existing synchronous connection and
                // initiate separate MDN send
                final HttpHeaderMap aHeaders = new HttpHeaderMap();
                aHeaders.setContentLength(0);
                try (final NonBlockingByteArrayOutputStream aData = new NonBlockingByteArrayOutputStream()) {
                    // Empty data
                    // Ideally this would be HTTP 204 (no content)
                    aResponseHandler.sendHttpResponse(CHttp.HTTP_OK, aHeaders, aData);
                }
                if (LOGGER.isInfoEnabled())
                    LOGGER.info("Setup to send async MDN [" + aDisposition.getAsString() + "] " + sClientInfo + aMsg.getLoggingText());
                // trigger explicit async sending
                aSession.getMessageProcessor().handle(IProcessorSenderModule.DO_SEND_ASYNC_MDN, aMsg, null);
            } else {
                // otherwise, send sync MDN back on same connection
                if (LOGGER.isInfoEnabled())
                    LOGGER.info("Sending back sync MDN [" + aDisposition.getAsString() + "] " + sClientInfo + aMsg.getLoggingText());
                // Get data and therefore content length for sync MDN
                try (final NonBlockingByteArrayOutputStream aData = new NonBlockingByteArrayOutputStream()) {
                    final MimeBodyPart aPart = aMdn.getData();
                    StreamHelper.copyInputStreamToOutputStream(aPart.getInputStream(), aData);
                    aMdn.headers().setContentLength(aData.size());
                    // start HTTP response
                    aResponseHandler.sendHttpResponse(CHttp.HTTP_OK, aMdn.headers(), aData);
                }
                // Save sent MDN for later examination
                try {
                    aSession.getMessageProcessor().handle(IProcessorStorageModule.DO_STOREMDN, aMsg, null);
                } catch (final AS2ComponentNotFoundException | AS2NoModuleException ex) {
                // No message processor found
                // or No module found in message processor
                }
                if (LOGGER.isInfoEnabled())
                    LOGGER.info("sent MDN [" + aDisposition.getAsString() + "] " + sClientInfo + aMsg.getLoggingText());
            }
        } catch (final Exception ex) {
            WrappedAS2Exception.wrap(ex).terminate(aMsg);
        }
    }
}
Also used : HttpHeaderMap(com.helger.commons.http.HttpHeaderMap) AS2NoModuleException(com.helger.as2lib.processor.AS2NoModuleException) NonBlockingByteArrayOutputStream(com.helger.commons.io.stream.NonBlockingByteArrayOutputStream) AS2ComponentNotFoundException(com.helger.as2lib.session.AS2ComponentNotFoundException) IMessageMDN(com.helger.as2lib.message.IMessageMDN) MimeBodyPart(javax.mail.internet.MimeBodyPart) MessagingException(javax.mail.MessagingException) AS2NoModuleException(com.helger.as2lib.processor.AS2NoModuleException) AS2DispositionException(com.helger.as2lib.disposition.AS2DispositionException) AS2ProcessorException(com.helger.as2lib.processor.AS2ProcessorException) CMSException(org.bouncycastle.cms.CMSException) AS2Exception(com.helger.as2lib.exception.AS2Exception) WrappedAS2Exception(com.helger.as2lib.exception.WrappedAS2Exception) IOException(java.io.IOException) SMIMEException(org.bouncycastle.mail.smime.SMIMEException) AS2ComponentNotFoundException(com.helger.as2lib.session.AS2ComponentNotFoundException) IAS2Session(com.helger.as2lib.session.IAS2Session)

Example 13 with HttpHeaderMap

use of com.helger.commons.http.HttpHeaderMap in project as2-lib by phax.

the class ReadMDNFuncTest method testReadMDNIssue97.

@Test
@Ignore("Part does not contain MimeMultipart")
public void testReadMDNIssue97() throws Exception {
    final String sPrefix = "mdn/issue97";
    final IReadableResource aHeaderRes = new ClassPathResource(sPrefix + ".header");
    assertTrue(aHeaderRes.exists());
    final IReadableResource aPayloadRes = new ClassPathResource(sPrefix + ".payload");
    assertTrue(aPayloadRes.exists());
    if (false) {
        final IReadableResource aCertRes = new ClassPathResource(sPrefix + ".pem");
        assertTrue(aCertRes.exists());
    }
    final HttpHeaderMap aHeaders = new HttpHeaderMap();
    try (NonBlockingBufferedReader aBR = new NonBlockingBufferedReader(aHeaderRes.getReader(StandardCharsets.ISO_8859_1))) {
        String s;
        while ((s = aBR.readLine()) != null) {
            final int i = s.indexOf(':');
            final String sName = s.substring(0, i).trim();
            final String sValue = s.substring(i + 1).trim();
            aHeaders.addHeader(sName, sValue);
        }
    }
    if (false)
        assertEquals("<MOKOsi42435716cf621589dnode1POP000046@sfgt1.unix.fina.hr>", aHeaders.getFirstHeaderValue("Message-ID"));
    // final X509Certificate aCert =
    // CertificateHelper.convertStringToCertficateOrNull
    // (StreamHelper.getAllBytesAsString (aCertRes,
    // StandardCharsets.ISO_8859_1));
    // assertNotNull (aCert);
    final AS2Message aMsg = new AS2Message();
    // Create a MessageMDN and copy HTTP headers
    final IMessageMDN aMDN = new AS2MessageMDN(aMsg);
    aMDN.headers().addAllHeaders(aHeaders);
    final MimeBodyPart aPart = new MimeBodyPart(AS2HttpHelper.getAsInternetHeaders(aMDN.headers()), StreamHelper.getAllBytes(aPayloadRes));
    assertNotNull(aPart);
    aMsg.getMDN().setData(aPart);
    final ICryptoHelper aCryptoHelper = AS2Helper.getCryptoHelper();
    assertTrue(aCryptoHelper.isSigned(aPart));
    assertFalse(aCryptoHelper.isEncrypted(aPart));
    assertFalse(aCryptoHelper.isCompressed(aPart.getContentType()));
    try (final AS2ResourceHelper aResHelper = new AS2ResourceHelper()) {
        final Consumer<X509Certificate> aCertHolder = null;
        AS2Helper.parseMDN(aMsg, null, true, aCertHolder, aResHelper);
    }
}
Also used : AS2MessageMDN(com.helger.as2lib.message.AS2MessageMDN) IReadableResource(com.helger.commons.io.resource.IReadableResource) ICryptoHelper(com.helger.as2lib.crypto.ICryptoHelper) ClassPathResource(com.helger.commons.io.resource.ClassPathResource) X509Certificate(java.security.cert.X509Certificate) AS2ResourceHelper(com.helger.as2lib.util.AS2ResourceHelper) HttpHeaderMap(com.helger.commons.http.HttpHeaderMap) AS2Message(com.helger.as2lib.message.AS2Message) IMessageMDN(com.helger.as2lib.message.IMessageMDN) MimeBodyPart(javax.mail.internet.MimeBodyPart) NonBlockingBufferedReader(com.helger.commons.io.stream.NonBlockingBufferedReader) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 14 with HttpHeaderMap

use of com.helger.commons.http.HttpHeaderMap in project as2-lib by phax.

the class ReadMDNFuncTest method testReadMDN02.

@Test
public void testReadMDN02() throws Exception {
    String sPrefix = "mdn/4af6f84c-d882-4466-8e0c-305a7fbe37b3";
    sPrefix = "mdn/20190925-david";
    final IReadableResource aHeaderRes = new ClassPathResource(sPrefix + ".header");
    assertTrue(aHeaderRes.exists());
    final IReadableResource aPayloadRes = new ClassPathResource(sPrefix + ".payload");
    assertTrue(aPayloadRes.exists());
    final IReadableResource aCertRes = new ClassPathResource(sPrefix + ".pem");
    assertTrue(aCertRes.exists());
    final HttpHeaderMap aHeaders = new HttpHeaderMap();
    try (NonBlockingBufferedReader aBR = new NonBlockingBufferedReader(aHeaderRes.getReader(StandardCharsets.ISO_8859_1))) {
        String s;
        while ((s = aBR.readLine()) != null) {
            final int i = s.indexOf(':');
            final String sName = s.substring(0, i).trim();
            final String sValue = s.substring(i + 1).trim();
            aHeaders.addHeader(sName, sValue);
        }
    }
    if (false)
        assertEquals("<MOKOsi42435716cf621589dnode1POP000046@sfgt1.unix.fina.hr>", aHeaders.getFirstHeaderValue("Message-ID"));
    final X509Certificate aCert = CertificateHelper.convertStringToCertficateOrNull(StreamHelper.getAllBytesAsString(aCertRes, StandardCharsets.ISO_8859_1));
    assertNotNull(aCert);
    final AS2Message aMsg = new AS2Message();
    // Create a MessageMDN and copy HTTP headers
    final IMessageMDN aMDN = new AS2MessageMDN(aMsg);
    aMDN.headers().addAllHeaders(aHeaders);
    final MimeBodyPart aPart = new MimeBodyPart(AS2HttpHelper.getAsInternetHeaders(aMDN.headers()), StreamHelper.getAllBytes(aPayloadRes));
    assertNotNull(aPart);
    aMsg.getMDN().setData(aPart);
    final ICryptoHelper aCryptoHelper = AS2Helper.getCryptoHelper();
    assertTrue(aCryptoHelper.isSigned(aPart));
    assertFalse(aCryptoHelper.isEncrypted(aPart));
    assertFalse(aCryptoHelper.isCompressed(aPart.getContentType()));
    final Consumer<X509Certificate> aCertHolder = null;
    try (final AS2ResourceHelper aResHelper = new AS2ResourceHelper()) {
        AS2Helper.parseMDN(aMsg, aCert, true, aCertHolder, aResHelper);
        fail();
    } catch (final CertificateExpiredException ex) {
        // expected to fail
        if (false)
            ex.printStackTrace();
    }
}
Also used : AS2MessageMDN(com.helger.as2lib.message.AS2MessageMDN) CertificateExpiredException(java.security.cert.CertificateExpiredException) IReadableResource(com.helger.commons.io.resource.IReadableResource) ICryptoHelper(com.helger.as2lib.crypto.ICryptoHelper) ClassPathResource(com.helger.commons.io.resource.ClassPathResource) X509Certificate(java.security.cert.X509Certificate) AS2ResourceHelper(com.helger.as2lib.util.AS2ResourceHelper) HttpHeaderMap(com.helger.commons.http.HttpHeaderMap) AS2Message(com.helger.as2lib.message.AS2Message) IMessageMDN(com.helger.as2lib.message.IMessageMDN) MimeBodyPart(javax.mail.internet.MimeBodyPart) NonBlockingBufferedReader(com.helger.commons.io.stream.NonBlockingBufferedReader) Test(org.junit.Test)

Example 15 with HttpHeaderMap

use of com.helger.commons.http.HttpHeaderMap in project ph-web by phax.

the class ResponseHelper method getResponseHeaderMap.

/**
 * Get a complete response header map as a copy.
 *
 * @param aHttpResponse
 *        The source HTTP response. May not be <code>null</code>.
 * @return Never <code>null</code>.
 * @since 8.7.3
 */
@Nonnull
@ReturnsMutableCopy
public static HttpHeaderMap getResponseHeaderMap(@Nonnull final HttpServletResponse aHttpResponse) {
    ValueEnforcer.notNull(aHttpResponse, "HttpResponse");
    final HttpHeaderMap ret = new HttpHeaderMap();
    for (final String sName : aHttpResponse.getHeaderNames()) for (final String sValue : aHttpResponse.getHeaders(sName)) ret.addHeader(sName, sValue);
    return ret;
}
Also used : HttpHeaderMap(com.helger.commons.http.HttpHeaderMap) ReturnsMutableCopy(com.helger.commons.annotation.ReturnsMutableCopy) Nonnull(javax.annotation.Nonnull)

Aggregations

HttpHeaderMap (com.helger.commons.http.HttpHeaderMap)22 Nonnull (javax.annotation.Nonnull)7 ICommonsList (com.helger.commons.collection.impl.ICommonsList)5 IOException (java.io.IOException)5 Nullable (javax.annotation.Nullable)5 MessagingException (javax.mail.MessagingException)5 IMessageMDN (com.helger.as2lib.message.IMessageMDN)4 Ebms3SignalMessage (com.helger.phase4.ebms3header.Ebms3SignalMessage)4 Ebms3UserMessage (com.helger.phase4.ebms3header.Ebms3UserMessage)4 IPMode (com.helger.phase4.model.pmode.IPMode)4 Phase4Exception (com.helger.phase4.util.Phase4Exception)4 MimeBodyPart (javax.mail.internet.MimeBodyPart)4 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)4 Test (org.junit.Test)4 Node (org.w3c.dom.Node)4 ValueEnforcer (com.helger.commons.ValueEnforcer)3 ReturnsMutableCopy (com.helger.commons.annotation.ReturnsMutableCopy)3 CommonsArrayList (com.helger.commons.collection.impl.CommonsArrayList)3 IHasInputStream (com.helger.commons.io.IHasInputStream)3 NonBlockingByteArrayOutputStream (com.helger.commons.io.stream.NonBlockingByteArrayOutputStream)3