Search in sources :

Example 1 with EHttpMethod

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

the class AS2SenderModule method _sendViaHTTP.

private void _sendViaHTTP(@Nonnull final AS2Message aMsg, @Nonnull final MimeBodyPart aSecuredMimePart, @Nullable final MIC aMIC, @Nullable final EContentTransferEncoding eCTE, @Nullable final IHTTPOutgoingDumper aOutgoingDumper, @Nullable final IHTTPIncomingDumper aIncomingDumper, @Nonnull final AS2ResourceHelper aResHelper) throws AS2Exception, IOException, MessagingException {
    final Partnership aPartnership = aMsg.partnership();
    // Create the HTTP connection
    final String sUrl = aPartnership.getAS2URL();
    final EHttpMethod eRequestMethod = EHttpMethod.POST;
    // decide on the connection type to use according to the MimeBodyPart:
    // If it contains the data, (and no DataHandler), then use HttpUrlClient,
    // otherwise, use HttpClient
    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());
        final boolean bQuoteHeaderValues = isQuoteHeaderValues();
        updateHttpHeaders(new AS2HttpHeaderSetter(aConn, aOutgoingDumper, bQuoteHeaderValues), aMsg);
        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 = aSecuredMimePart.getInputStream();
        // Transfer the data
        final StopWatch aSW = StopWatch.createdStarted();
        final long nBytes = aConn.send(aMsgIS, eCTE, aOutgoingDumper, aResHelper);
        aSW.stop();
        if (LOGGER.isInfoEnabled())
            LOGGER.info("AS2 Message transferred " + AS2IOHelper.getTransferRate(nBytes, aSW) + aMsg.getLoggingText());
        if (aOutgoingDumper != null)
            aOutgoingDumper.finishedPayload();
        final int nHttpResponseCode = aConn.getResponseCode();
        if (getOutgoingHttpCallback() != null)
            getOutgoingHttpCallback().onOutgoingHttpMessage(true, aMsg.getAS2From(), aMsg.getAS2To(), aMsg.getMessageID(), aMIC == null ? null : aMIC.getClone(), eCTE, sUrl, nHttpResponseCode);
        // Check the HTTP Response code
        if (AS2HttpClient.isErrorResponseCode(nHttpResponseCode)) {
            if (LOGGER.isErrorEnabled())
                LOGGER.error("Error URL '" + sUrl + "' - HTTP " + nHttpResponseCode + " " + aConn.getResponseMessage() + " " + aMsg.getLoggingText());
            throw new AS2HttpResponseException(sUrl, nHttpResponseCode, aConn.getResponseMessage());
        }
        // Receive an MDN
        try {
            // Receive an MDN
            if (aMsg.isRequestingMDN()) {
                // Check if the AsyncMDN is required
                if (aPartnership.getAS2ReceiptDeliveryOption() == null) {
                    // Note: If an MDN is requested, a MIC is present
                    assert aMIC != null;
                    receiveSyncMDN(aMsg, aConn, aMIC, aIncomingDumper, aResHelper);
                    if (LOGGER.isInfoEnabled())
                        LOGGER.info("message sent" + aMsg.getLoggingText());
                }
            }
        } catch (final AS2DispositionException ex) {
            // was not successful
            throw ex;
        } catch (final AS2Exception ex) {
            // Don't re-send or fail, just log an error if one occurs while
            // receiving the MDN
            onReceivedMDNError(aMsg, ex);
        }
    } finally {
        // Closes all resources
        aConn.disconnect();
    }
}
Also used : InputStream(java.io.InputStream) StopWatch(com.helger.commons.timing.StopWatch) AS2DispositionException(com.helger.as2lib.disposition.AS2DispositionException) AS2HttpHeaderSetter(com.helger.as2lib.util.http.AS2HttpHeaderSetter) Partnership(com.helger.as2lib.partner.Partnership) EHttpMethod(com.helger.commons.http.EHttpMethod) AS2Exception(com.helger.as2lib.exception.AS2Exception) WrappedAS2Exception(com.helger.as2lib.exception.WrappedAS2Exception) AS2HttpClient(com.helger.as2lib.util.http.AS2HttpClient)

Example 2 with EHttpMethod

use of com.helger.commons.http.EHttpMethod 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 3 with EHttpMethod

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

the class AbstractXFilterUnifiedResponse method onFilterBefore.

@Override
@Nonnull
@OverrideOnDemand
public final EContinue onFilterBefore(@Nonnull final HttpServletRequest aHttpRequest, @Nonnull final HttpServletResponse aHttpResponse, @Nonnull final IRequestWebScope aRequestScope) throws IOException, ServletException {
    // Check HTTP version
    final EHttpVersion eHTTPVersion = RequestHelper.getHttpVersion(aHttpRequest);
    if (eHTTPVersion == null) {
        aHttpResponse.sendError(HttpServletResponse.SC_HTTP_VERSION_NOT_SUPPORTED);
        return EContinue.BREAK;
    }
    // Check HTTP Method
    final EHttpMethod eHTTPMethod = RequestHelper.getHttpMethod(aHttpRequest);
    if (eHTTPMethod == null) {
        if (eHTTPVersion.is10())
            aHttpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
        else
            aHttpResponse.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return EContinue.BREAK;
    }
    // Start unified response handling
    final UnifiedResponse aUnifiedResponse = new UnifiedResponse(eHTTPVersion, eHTTPMethod, aHttpRequest);
    if (onFilterBefore(aRequestScope, aUnifiedResponse).isBreak()) {
        // Filter ended chain -> send response
        aUnifiedResponse.applyToResponse(aHttpResponse);
        return EContinue.BREAK;
    }
    // Discard the content of the unified response
    return EContinue.CONTINUE;
}
Also used : UnifiedResponse(com.helger.servlet.response.UnifiedResponse) EHttpVersion(com.helger.http.EHttpVersion) EHttpMethod(com.helger.commons.http.EHttpMethod) Nonnull(javax.annotation.Nonnull) OverrideOnDemand(com.helger.commons.annotation.OverrideOnDemand)

Example 4 with EHttpMethod

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

the class RequestHelper method getHttpMethodOrDefault.

/**
 * Get the HTTP method associated with the given HTTP request
 *
 * @param aHttpRequest
 *        The http request to query. May not be <code>null</code>.
 * @param eDefault
 *        The default to be returned, if no HTTP method could be found. May be
 *        <code>null</code>.
 * @return <code>null</code> if no supported HTTP method is contained
 * @since 9.1.6
 */
@Nullable
public static EHttpMethod getHttpMethodOrDefault(@Nonnull final HttpServletRequest aHttpRequest, @Nullable final EHttpMethod eDefault) {
    ValueEnforcer.notNull(aHttpRequest, "HttpRequest");
    final String sMethod = aHttpRequest.getMethod();
    final EHttpMethod ret = EHttpMethod.getFromNameOrNull(sMethod);
    if (ret != null)
        return ret;
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Unknown HTTP request method '" + sMethod + "' used in request " + aHttpRequest);
    return eDefault;
}
Also used : EHttpMethod(com.helger.commons.http.EHttpMethod) Nullable(javax.annotation.Nullable)

Example 5 with EHttpMethod

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

the class AbstractXServlet method service.

/**
 * Dispatches client requests to the protected <code>service</code> method.
 * There's no need to override this method.
 *
 * @param aHttpRequest
 *        the {@link HttpServletRequest} object that contains the request the
 *        client made of the servlet
 * @param aHttpResponse
 *        the {@link HttpServletResponse} object that contains the response
 *        the servlet returns to the client
 * @exception IOException
 *            if an input or output error occurs while the servlet is handling
 *            the HTTP request
 * @exception ServletException
 *            if the HTTP request cannot be handled
 * @see javax.servlet.Servlet#service
 */
@Override
protected final void service(@Nonnull final HttpServletRequest aHttpRequest, @Nonnull final HttpServletResponse aHttpResponse) throws ServletException, IOException {
    // Increase counter
    m_aCounterRequestsTotal.increment();
    // Increase per servlet invocation
    m_aStatusMgr.onServletInvocation(getClass());
    // Ensure a valid HTTP version is provided
    final String sProtocol = aHttpRequest.getProtocol();
    final EHttpVersion eHttpVersion = EHttpVersion.getFromNameOrNull(sProtocol);
    if (eHttpVersion == null) {
        // HTTP version disallowed
        logInvalidRequestSetup("Request has unsupported HTTP version (" + sProtocol + ")!", aHttpRequest);
        aHttpResponse.sendError(CHttp.HTTP_VERSION_NOT_SUPPORTED);
        return;
    }
    m_aCounterRequestsPerVersionAccepted.increment(eHttpVersion.getName());
    // Ensure a valid HTTP method is provided
    final String sMethod = aHttpRequest.getMethod();
    final EHttpMethod eHttpMethod = EHttpMethod.getFromNameOrNull(sMethod);
    if (eHttpMethod == null) {
        // HTTP method unknown
        logInvalidRequestSetup("Request has unsupported HTTP method (" + sMethod + ")!", aHttpRequest);
        aHttpResponse.sendError(CHttp.HTTP_NOT_IMPLEMENTED);
        return;
    }
    m_aCounterRequestsPerMethodAccepted.increment(eHttpMethod.getName());
    // May already be set in test cases!
    if (FIRST_REQUEST.getAndSet(false) && !StaticServerInfo.isSet()) {
        // First set the default web server info
        StaticServerInfo.init(aHttpRequest.getScheme(), aHttpRequest.getServerName(), aHttpRequest.getServerPort(), ServletContextPathHolder.getContextPath());
    }
    // Create a wrapper around the Servlet Response that saves the status code
    final StatusAwareHttpResponseWrapper aHttpResponseWrapper = StatusAwareHttpResponseWrapper.wrap(aHttpResponse);
    // Create effective filter list with all internal filters as well
    final ICommonsList<IXServletLowLevelFilter> aEffectiveFilterList = new CommonsArrayList<>(4 + m_aFilterLowLevelList.size());
    // Add internal filters - always first
    aEffectiveFilterList.add(XServletFilterSecurityPoxy.INSTANCE);
    aEffectiveFilterList.add(XServletFilterConsistency.INSTANCE);
    if (m_aSettings.hasHttpReferrerPolicy())
        aEffectiveFilterList.add(new XServletFilterSecurityHttpReferrerPolicy(m_aSettings.getHttpReferrerPolicy()));
    if (m_aSettings.hasXFrameOptions())
        aEffectiveFilterList.add(new XServletFilterSecurityXFrameOptions(m_aSettings.getXFrameOptionsType(), m_aSettings.getXFrameOptionsDomain()));
    // Add custom filters
    aEffectiveFilterList.addAll(m_aFilterLowLevelList);
    // Filter before request scope is created!
    boolean bInvokeHandler = true;
    for (final IXServletLowLevelFilter aFilter : aEffectiveFilterList) if (aFilter.beforeRequest(aHttpRequest, aHttpResponseWrapper, eHttpVersion, eHttpMethod).isBreak()) {
        bInvokeHandler = false;
        return;
    }
    boolean bIsHandledAsync = false;
    Exception aCaughtException = null;
    try {
        if (bInvokeHandler) {
            // Create request scope
            final BiFunction<? super HttpServletRequest, ? super HttpServletResponse, IRequestWebScope> aFactory;
            aFactory = m_aSettings.isMultipartEnabled() ? RequestWebScopeMultipart::new : RequestWebScope::new;
            try (final RequestScopeInitializer aRequestScopeInitializer = RequestScopeInitializer.create(aHttpRequest, aHttpResponseWrapper, aFactory)) {
                final IRequestWebScope aRequestScope = aRequestScopeInitializer.getRequestScope();
                aRequestScope.attrs().putIn(REQUEST_ATTR_SCOPE_CREATED, aRequestScopeInitializer.isNew());
                // Find and invoke handler
                _invokeHandler(aHttpRequest, aHttpResponseWrapper, eHttpVersion, eHttpMethod, aRequestScope);
                bIsHandledAsync = aRequestScope.attrs().getAsBoolean(AbstractXServlet.REQUEST_ATTR_HANDLED_ASYNC, false);
                if (bIsHandledAsync) {
                    // The request scope is needed in the async handler!
                    aRequestScopeInitializer.internalSetDontDestroyRequestScope();
                }
            }
        }
    } catch (final Exception ex) {
        // Remember
        aCaughtException = ex;
        // This log entry is mainly present to have an overview on how often
        // this really happens
        log("Servlet exception propagated to the outside", ex);
        // Ensure only exceptions with the correct type are propagated
        if (ex instanceof IOException)
            throw (IOException) ex;
        if (ex instanceof ServletException)
            throw (ServletException) ex;
        throw new ServletException("Wrapped " + ex.getClass().getName(), ex);
    } finally {
        // Filter after
        for (final IXServletLowLevelFilter aFilter : aEffectiveFilterList) try {
            aFilter.afterRequest(aHttpRequest, aHttpResponseWrapper, eHttpVersion, eHttpMethod, bInvokeHandler, aCaughtException, bIsHandledAsync);
        } catch (final ServletException | IOException ex) {
            LOGGER.error("Exception in low-level filter afterRequest of " + aFilter + " - re-thrown", ex);
        // Don't re-throw in finally
        // throw ex;
        }
    }
}
Also used : XServletFilterSecurityXFrameOptions(com.helger.xservlet.filter.XServletFilterSecurityXFrameOptions) XServletFilterSecurityHttpReferrerPolicy(com.helger.xservlet.filter.XServletFilterSecurityHttpReferrerPolicy) EHttpVersion(com.helger.http.EHttpVersion) IXServletLowLevelFilter(com.helger.xservlet.filter.IXServletLowLevelFilter) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) ForcedRedirectException(com.helger.xservlet.forcedredirect.ForcedRedirectException) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) EHttpMethod(com.helger.commons.http.EHttpMethod) RequestScopeInitializer(com.helger.web.scope.request.RequestScopeInitializer) StatusAwareHttpResponseWrapper(com.helger.servlet.response.StatusAwareHttpResponseWrapper) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) IRequestWebScope(com.helger.web.scope.IRequestWebScope)

Aggregations

EHttpMethod (com.helger.commons.http.EHttpMethod)6 AS2HttpClient (com.helger.as2lib.util.http.AS2HttpClient)2 AS2HttpHeaderSetter (com.helger.as2lib.util.http.AS2HttpHeaderSetter)2 StopWatch (com.helger.commons.timing.StopWatch)2 EHttpVersion (com.helger.http.EHttpVersion)2 InputStream (java.io.InputStream)2 MIC (com.helger.as2lib.crypto.MIC)1 AS2DispositionException (com.helger.as2lib.disposition.AS2DispositionException)1 AS2Exception (com.helger.as2lib.exception.AS2Exception)1 WrappedAS2Exception (com.helger.as2lib.exception.WrappedAS2Exception)1 IMessageMDN (com.helger.as2lib.message.IMessageMDN)1 Partnership (com.helger.as2lib.partner.Partnership)1 AS2NoModuleException (com.helger.as2lib.processor.AS2NoModuleException)1 AS2ComponentNotFoundException (com.helger.as2lib.session.AS2ComponentNotFoundException)1 OverrideOnDemand (com.helger.commons.annotation.OverrideOnDemand)1 CommonsArrayList (com.helger.commons.collection.impl.CommonsArrayList)1 HttpHeaderMap (com.helger.commons.http.HttpHeaderMap)1 EContentTransferEncoding (com.helger.mail.cte.EContentTransferEncoding)1 StatusAwareHttpResponseWrapper (com.helger.servlet.response.StatusAwareHttpResponseWrapper)1 UnifiedResponse (com.helger.servlet.response.UnifiedResponse)1