Search in sources :

Example 1 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 2 with HttpHeaderMap

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

the class AS2SenderModule method updateHttpHeaders.

/**
 * Update the HTTP headers based on the provided message, before sending takes
 * place.
 *
 * @param aHeaderSetter
 *        The connection abstraction. Never <code>null</code>.
 * @param aMsg
 *        The message to be send. Never <code>null</code>.
 */
protected void updateHttpHeaders(@Nonnull final AS2HttpHeaderSetter aHeaderSetter, @Nonnull final IMessage aMsg) {
    final Partnership aPartnership = aMsg.partnership();
    // Set all custom headers first (so that they are overridden with the
    // mandatory ones in here)
    // Use HttpHeaderMap and not String to ensure name casing is identical!
    final HttpHeaderMap aHeaderMap = aMsg.headers().getClone();
    aHeaderMap.setHeader(CHttpHeader.CONNECTION, CAS2Header.DEFAULT_CONNECTION);
    aHeaderMap.setHeader(CHttpHeader.USER_AGENT, CAS2Header.DEFAULT_USER_AGENT);
    aHeaderMap.setHeader(CHttpHeader.MIME_VERSION, CAS2Header.DEFAULT_MIME_VERSION);
    aHeaderMap.setHeader(CHttpHeader.AS2_VERSION, getSession().getAS2VersionID());
    aHeaderMap.setHeader(CHttpHeader.DATE, AS2DateHelper.getFormattedDateNow(CAS2Header.DEFAULT_DATE_FORMAT));
    aHeaderMap.setHeader(CHttpHeader.MESSAGE_ID, aMsg.getMessageID());
    aHeaderMap.setHeader(CHttpHeader.CONTENT_TYPE, aMsg.getContentType());
    aHeaderMap.setHeader(CHttpHeader.RECIPIENT_ADDRESS, aPartnership.getAS2URL());
    aHeaderMap.setHeader(CHttpHeader.AS2_FROM, aPartnership.getSenderAS2ID());
    aHeaderMap.setHeader(CHttpHeader.AS2_TO, aPartnership.getReceiverAS2ID());
    aHeaderMap.setHeader(CHttpHeader.SUBJECT, aMsg.getSubject());
    aHeaderMap.setHeader(CHttpHeader.FROM, aPartnership.getSenderEmail());
    // Set when compression or encryption is enabled
    aHeaderMap.setHeader(CHttpHeader.CONTENT_TRANSFER_ENCODING, aMsg.getHeader(CHttpHeader.CONTENT_TRANSFER_ENCODING));
    // Determine where to send the MDN to (legacy field)
    final String sDispTo = aPartnership.getAS2MDNTo();
    if (sDispTo != null)
        aHeaderMap.setHeader(CHttpHeader.DISPOSITION_NOTIFICATION_TO, sDispTo);
    // MDN requirements
    final String sDispositionNotificationOptions = aPartnership.getAS2MDNOptions();
    if (sDispositionNotificationOptions != null)
        aHeaderMap.setHeader(CHttpHeader.DISPOSITION_NOTIFICATION_OPTIONS, sDispositionNotificationOptions);
    // Async MDN 2007-03-12
    final String sReceiptDeliveryOption = aPartnership.getAS2ReceiptDeliveryOption();
    if (sReceiptDeliveryOption != null)
        aHeaderMap.setHeader(CHttpHeader.RECEIPT_DELIVERY_OPTION, sReceiptDeliveryOption);
    // As of 2007-06-01
    final String sContententDisposition = aMsg.getContentDisposition();
    if (sContententDisposition != null)
        aHeaderMap.setHeader(CHttpHeader.CONTENT_DISPOSITION, sContententDisposition);
    // Set once, after all were collected
    // Avoid double quoting
    aHeaderMap.forEachSingleHeader(aHeaderSetter::setHttpHeader, false);
}
Also used : HttpHeaderMap(com.helger.commons.http.HttpHeaderMap) Partnership(com.helger.as2lib.partner.Partnership)

Example 3 with HttpHeaderMap

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

the class AsynchMDNSenderModule method _sendViaHTTP.

private void _sendViaHTTP(@Nonnull final AS2Message aMsg, @Nonnull final DispositionType aDisposition, @Nullable final IHTTPOutgoingDumper aOutgoingDumper, @Nonnull final AS2ResourceHelper aResHelper) throws AS2Exception, IOException, MessagingException {
    final IMessageMDN aMdn = aMsg.getMDN();
    // Create a HTTP connection
    final String sUrl = aMsg.getAsyncMDNurl();
    final EHttpMethod eRequestMethod = EHttpMethod.POST;
    // MDN is a small message. We will always use CHttp
    final AS2HttpClient aConn = getHttpClient(sUrl, eRequestMethod, getSession().getHttpProxy());
    try {
        if (aOutgoingDumper != null)
            aOutgoingDumper.start(sUrl, aMsg);
        if (LOGGER.isInfoEnabled())
            LOGGER.info("Connecting to " + sUrl + aMsg.getLoggingText());
        // Set all custom headers first (so that they are overridden with the
        // mandatory ones in here)
        // Use HttpHeaderMap and not String to ensure name casing is identical!
        final HttpHeaderMap aHeaderMap = aMdn.headers().getClone();
        aHeaderMap.setHeader(CHttpHeader.CONNECTION, CAS2Header.DEFAULT_CONNECTION);
        aHeaderMap.setHeader(CHttpHeader.USER_AGENT, CAS2Header.DEFAULT_USER_AGENT);
        final boolean bQuoteHeaderValues = isQuoteHeaderValues();
        final AS2HttpHeaderSetter aHeaderSetter = new AS2HttpHeaderSetter(aConn, aOutgoingDumper, bQuoteHeaderValues);
        // Copy all the header from mdn to the RequestProperties of conn
        // Unification needed, because original MDN headers may contain newlines
        aHeaderMap.forEachSingleHeader(aHeaderSetter::setHttpHeader, true, false);
        if (aOutgoingDumper != null)
            aOutgoingDumper.finishedHeaders();
        aMsg.attrs().putIn(CNetAttribute.MA_DESTINATION_IP, aConn.getURL().getHost());
        aMsg.attrs().putIn(CNetAttribute.MA_DESTINATION_PORT, aConn.getURL().getPort());
        final InputStream aMsgIS = aMdn.getData().getInputStream();
        // Transfer the data
        final StopWatch aSW = StopWatch.createdStarted();
        final long nBytes = aConn.send(aMsgIS, (EContentTransferEncoding) null, aOutgoingDumper, aResHelper);
        aSW.stop();
        if (LOGGER.isInfoEnabled())
            LOGGER.info("AS2 MDN transferred " + AS2IOHelper.getTransferRate(nBytes, aSW) + aMsg.getLoggingText());
        if (aOutgoingDumper != null)
            aOutgoingDumper.finishedPayload();
        final int nHttpResponseCode = aConn.getResponseCode();
        if (getOutgoingHttpCallback() != null)
            getOutgoingHttpCallback().onOutgoingHttpMessage(false, aMsg.getAS2From(), aMsg.getAS2To(), aMsg.getMessageID(), (MIC) null, (EContentTransferEncoding) null, sUrl, nHttpResponseCode);
        // Check the HTTP Response code
        if (AS2HttpClient.isErrorResponseCode(nHttpResponseCode)) {
            if (LOGGER.isErrorEnabled())
                LOGGER.error("sent AsyncMDN [" + aDisposition.getAsString() + "] Fail(" + nHttpResponseCode + ") " + aMsg.getLoggingText());
            throw new AS2HttpResponseException(sUrl, nHttpResponseCode, aConn.getResponseMessage());
        }
        if (LOGGER.isInfoEnabled())
            LOGGER.info("sent AsyncMDN [" + aDisposition.getAsString() + "] OK(" + nHttpResponseCode + ") " + aMsg.getLoggingText());
        // log & store mdn into backup folder.
        try {
            getSession().getMessageProcessor().handle(IProcessorStorageModule.DO_STOREMDN, aMsg, null);
        } catch (final AS2ComponentNotFoundException | AS2NoModuleException ex) {
        // No message processor found
        // Or no module found in message processor
        }
    } finally {
        aConn.disconnect();
    }
}
Also used : EContentTransferEncoding(com.helger.mail.cte.EContentTransferEncoding) InputStream(java.io.InputStream) MIC(com.helger.as2lib.crypto.MIC) StopWatch(com.helger.commons.timing.StopWatch) HttpHeaderMap(com.helger.commons.http.HttpHeaderMap) AS2NoModuleException(com.helger.as2lib.processor.AS2NoModuleException) AS2HttpHeaderSetter(com.helger.as2lib.util.http.AS2HttpHeaderSetter) EHttpMethod(com.helger.commons.http.EHttpMethod) AS2ComponentNotFoundException(com.helger.as2lib.session.AS2ComponentNotFoundException) IMessageMDN(com.helger.as2lib.message.IMessageMDN) AS2HttpClient(com.helger.as2lib.util.http.AS2HttpClient)

Example 4 with HttpHeaderMap

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

the class AS2HttpClient method getResponseHeaderFields.

@Nonnull
@ReturnsMutableCopy
public HttpHeaderMap getResponseHeaderFields() throws AS2Exception {
    // message was not sent yet, not response
    if (m_aCloseableHttpResponse == null)
        throw new AS2Exception("No response as message was yet sent");
    final Header[] aHeaders = m_aCloseableHttpResponse.getAllHeaders();
    final HttpHeaderMap ret = new HttpHeaderMap();
    for (final Header aHeader : aHeaders) ret.addHeader(aHeader.getName(), aHeader.getValue());
    return ret;
}
Also used : HttpHeaderMap(com.helger.commons.http.HttpHeaderMap) Header(org.apache.http.Header) AS2Exception(com.helger.as2lib.exception.AS2Exception) ReturnsMutableCopy(com.helger.commons.annotation.ReturnsMutableCopy) Nonnull(javax.annotation.Nonnull)

Example 5 with HttpHeaderMap

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

the class HTTPHelper method sendSimpleHTTPResponse.

/**
 * Send a simple HTTP response that only contains the HTTP status code and the
 * respective descriptive text. An empty header map us used.
 *
 * @param aResponseHandler
 *        The response handler to be used.
 * @param nResponseCode
 *        The HTTP response code to use.
 * @throws IOException
 *         In case sending fails for whatever reason
 */
public static void sendSimpleHTTPResponse(@Nonnull final IAS2HttpResponseHandler aResponseHandler, @Nonnegative final int nResponseCode) throws IOException {
    try (final NonBlockingByteArrayOutputStream aData = new NonBlockingByteArrayOutputStream()) {
        final String sHTTPLine = Integer.toString(nResponseCode) + " " + CHttp.getHttpResponseMessage(nResponseCode) + CHttp.EOL;
        aData.write(sHTTPLine.getBytes(CHttp.HTTP_CHARSET));
        aResponseHandler.sendHttpResponse(nResponseCode, new HttpHeaderMap(), aData);
    }
}
Also used : HttpHeaderMap(com.helger.commons.http.HttpHeaderMap) NonBlockingByteArrayOutputStream(com.helger.commons.io.stream.NonBlockingByteArrayOutputStream)

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