Search in sources :

Example 1 with StopWatch

use of com.helger.commons.timing.StopWatch in project phoss-directory by phax.

the class PDStorageManager method _timedSearch.

private static <T> T _timedSearch(@Nonnull final IThrowingSupplier<T, IOException> aRunnable, @Nonnull final Query aQuery) throws IOException {
    final StopWatch aSW = StopWatch.createdStarted();
    try {
        return aRunnable.get();
    } finally {
        final long nMillis = aSW.stopAndGetMillis();
        s_aStatsQueryTimer.addTime(aQuery.toString(), nMillis);
        if (nMillis > CGlobal.MILLISECONDS_PER_SECOND)
            if (LOGGER.isWarnEnabled())
                LOGGER.warn("Lucene Query " + aQuery + " took too long: " + nMillis + "ms");
    }
}
Also used : StopWatch(com.helger.commons.timing.StopWatch)

Example 2 with StopWatch

use of com.helger.commons.timing.StopWatch in project peppol-commons by phax.

the class MainTestNAPTR method main.

public static void main(final String[] args) {
    // Warm up cache
    URLHelper.getAsURI("http://www.example.org");
    // D2CQSE7LLUJ6H2AR32Z4RCK2M3QXCNQHB7K7QXNUMIYR5ESSXXPQ.ehealth-actorid-qns.acc.edelivery.tech.ec.europa.eu.
    // 60 IN NAPTR 100 10 "U" "Meta:SMP"
    // "!^.*$!http://EHEALTH-TEST-UPRC.publisher.acc.edelivery.tech.ec.europa.eu!"
    // .
    final String sDN = "D2CQSE7LLUJ6H2AR32Z4RCK2M3QXCNQHB7K7QXNUMIYR5ESSXXPQ.ehealth-actorid-qns.acc.edelivery.tech.ec.europa.eu";
    for (int i = 0; i < 10; ++i) {
        final StopWatch aSW = StopWatch.createdStarted();
        final String sURI = _resolveFromNAPTR(sDN);
        LOGGER.info(aSW.stopAndGetMillis() + "ms " + sURI);
    }
}
Also used : StopWatch(com.helger.commons.timing.StopWatch)

Example 3 with StopWatch

use of com.helger.commons.timing.StopWatch in project as2-lib by phax.

the class AS2Client method sendSynchronous.

/**
 * Send the AS2 message synchronously
 *
 * @param aSettings
 *        The settings to be used. May not be <code>null</code>.
 * @param aRequest
 *        The request data to be send. May not be <code>null</code>.
 * @return The response object. Never <code>null</code>.
 */
@Nonnull
public AS2ClientResponse sendSynchronous(@Nonnull final AS2ClientSettings aSettings, @Nonnull final AS2ClientRequest aRequest) {
    ValueEnforcer.notNull(aSettings, "ClientSettings");
    ValueEnforcer.notNull(aRequest, "ClientRequest");
    final AS2ClientResponse aResponse = createResponse();
    IMessage aMsg = null;
    final StopWatch aSW = StopWatch.createdStarted();
    try {
        final Partnership aPartnership = buildPartnership(aSettings);
        aMsg = createMessage(aPartnership, aRequest);
        aResponse.setOriginalMessageID(aMsg.getMessageID());
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("MessageID to send: " + aMsg.getMessageID());
        final boolean bHasRetries = aSettings.getRetryCount() > 0;
        // Start a new session
        final AS2Session aSession = createSession();
        initCertificateFactory(aSettings, aSession);
        initPartnershipFactory(aSession);
        initMessageProcessor(aSession);
        if (bHasRetries) {
            // Use synchronous no-delay resender
            final IProcessorResenderModule aResender = new ImmediateResenderModule();
            aResender.initDynamicComponent(aSession, null);
            aSession.getMessageProcessor().addModule(aResender);
        }
        aSession.getMessageProcessor().startActiveModules();
        try {
            // Invoke callback
            beforeSend(aSettings, aSession, aMsg);
            // Build options map for "handle"
            final ICommonsMap<String, Object> aHandleOptions = new CommonsHashMap<>();
            if (bHasRetries)
                aHandleOptions.put(IProcessorResenderModule.OPTION_RETRIES, Integer.toString(aSettings.getRetryCount()));
            // Content-Transfer-Encoding is a partnership property
            aPartnership.setContentTransferEncodingSend(aRequest.getContentTransferEncoding());
            aPartnership.setContentTransferEncodingReceive(aRequest.getContentTransferEncoding());
            // And create a sender module that directly sends the message
            // The message processor registration is required for the resending
            // feature
            final AS2SenderModule aSender = m_aAS2SenderModuleFactory.get();
            aSender.initDynamicComponent(aSession, null);
            // Set connect and read timeout
            aSender.setConnectionTimeoutMilliseconds(aSettings.getConnectTimeoutMS());
            aSender.setReadTimeoutMilliseconds(aSettings.getReadTimeoutMS());
            aSender.setQuoteHeaderValues(aSettings.isQuoteHeaderValues());
            aSender.setHttpOutgoingDumperFactory(aSettings.getHttpOutgoingDumperFactory());
            aSender.setHttpIncomingDumper(aSettings.getHttpIncomingDumper());
            if (aSettings.getMICMatchingHandler() != null)
                aSender.setMICMatchingHandler(aSettings.getMICMatchingHandler());
            aSender.setVerificationCertificateConsumer(aSettings.getVerificationCertificateConsumer());
            // Add all custom headers
            aMsg.headers().setAllHeaders(aSettings.customHeaders());
            // Added sender as processor
            aSession.getMessageProcessor().addModule(aSender);
            // Main sending
            aSender.handle(IProcessorSenderModule.DO_SEND, aMsg, aHandleOptions);
        } finally {
            aSession.getMessageProcessor().stopActiveModules();
        }
    } catch (final Exception ex) {
        LOGGER.error("Error sending AS2 message", ex);
        aResponse.setException(ex);
    } finally {
        if (aMsg != null && aMsg.getMDN() != null) {
            // May be present, even in case of an exception
            aResponse.setMDN(aMsg.getMDN());
            // Remember the certificate that was used to verify the MDN
            final String sReceivedCert = aMsg.attrs().getAsString(AS2Message.ATTRIBUTE_RECEIVED_SIGNATURE_CERTIFICATE);
            if (sReceivedCert != null) {
                final X509Certificate aReceivedCert = CertificateHelper.convertStringToCertficateOrNull(sReceivedCert);
                aResponse.setMDNVerificationCertificate(aReceivedCert);
            }
        }
    }
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Response retrieved: " + aResponse.getAsString());
    aResponse.setExecutionDuration(aSW.stopAndGetDuration());
    return aResponse;
}
Also used : AS2SenderModule(com.helger.as2lib.processor.sender.AS2SenderModule) IMessage(com.helger.as2lib.message.IMessage) MessagingException(javax.mail.MessagingException) AS2Exception(com.helger.as2lib.exception.AS2Exception) AS2CertificateExistsException(com.helger.as2lib.cert.AS2CertificateExistsException) X509Certificate(java.security.cert.X509Certificate) StopWatch(com.helger.commons.timing.StopWatch) AS2Session(com.helger.as2lib.session.AS2Session) ImmediateResenderModule(com.helger.as2lib.processor.resender.ImmediateResenderModule) Partnership(com.helger.as2lib.partner.Partnership) CommonsHashMap(com.helger.commons.collection.impl.CommonsHashMap) IProcessorResenderModule(com.helger.as2lib.processor.resender.IProcessorResenderModule) Nonnull(javax.annotation.Nonnull)

Example 4 with StopWatch

use of com.helger.commons.timing.StopWatch in project as2-lib by phax.

the class AS2MDNReceiverHandler method handle.

public void handle(@Nonnull final AbstractActiveNetModule aOwner, @Nonnull final Socket aSocket) {
    final String sClientInfo = getClientInfo(aSocket);
    if (LOGGER.isInfoEnabled())
        LOGGER.info("incoming connection for receiving AsyncMDN [" + sClientInfo + "]");
    final AS2Message aMsg = new AS2Message();
    final boolean bQuoteHeaderValues = m_aReceiverModule.isQuoteHeaderValues();
    final IAS2HttpResponseHandler aResponseHandler = new AS2HttpResponseHandlerSocket(aSocket, bQuoteHeaderValues);
    // Time the transmission
    final StopWatch aSW = StopWatch.createdStarted();
    DataSource aMdnDataSource = null;
    try {
        // Read in the message request, headers, and data
        final IHTTPIncomingDumper aIncomingDumper = getEffectiveHttpIncomingDumper();
        aMdnDataSource = HTTPHelper.readAndDecodeHttpRequest(new AS2HttpRequestDataProviderInputStream(aSocket.getInputStream()), aResponseHandler, aMsg, aIncomingDumper);
    } catch (final Exception ex) {
        new AS2NetException(aSocket.getInetAddress(), aSocket.getPort(), ex).terminate();
    }
    aSW.stop();
    if (aMdnDataSource == null) {
        LOGGER.error("Not having a data source to operate on");
    } else {
        if (aMdnDataSource instanceof ByteArrayDataSource) {
            if (LOGGER.isInfoEnabled())
                LOGGER.info("received " + AS2IOHelper.getTransferRate(((ByteArrayDataSource) aMdnDataSource).directGetBytes().length, aSW) + " from " + sClientInfo + aMsg.getLoggingText());
        } else {
            LOGGER.info("received message from " + sClientInfo + aMsg.getLoggingText() + " in " + aSW.getMillis() + " ms");
        }
        handleIncomingMessage(sClientInfo, aMdnDataSource, aMsg, aResponseHandler);
    }
}
Also used : AS2HttpResponseHandlerSocket(com.helger.as2lib.util.http.AS2HttpResponseHandlerSocket) AS2Message(com.helger.as2lib.message.AS2Message) IAS2HttpResponseHandler(com.helger.as2lib.util.http.IAS2HttpResponseHandler) AS2HttpRequestDataProviderInputStream(com.helger.as2lib.util.http.AS2HttpRequestDataProviderInputStream) ByteArrayDataSource(com.helger.mail.datasource.ByteArrayDataSource) MessagingException(javax.mail.MessagingException) AS2NoModuleException(com.helger.as2lib.processor.AS2NoModuleException) AS2Exception(com.helger.as2lib.exception.AS2Exception) WrappedAS2Exception(com.helger.as2lib.exception.WrappedAS2Exception) IOException(java.io.IOException) AS2ComponentNotFoundException(com.helger.as2lib.session.AS2ComponentNotFoundException) StopWatch(com.helger.commons.timing.StopWatch) ByteArrayDataSource(com.helger.mail.datasource.ByteArrayDataSource) DataSource(javax.activation.DataSource) IHTTPIncomingDumper(com.helger.as2lib.util.dump.IHTTPIncomingDumper)

Example 5 with StopWatch

use of com.helger.commons.timing.StopWatch 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)

Aggregations

StopWatch (com.helger.commons.timing.StopWatch)29 IParticipantIdentifier (com.helger.peppolid.IParticipantIdentifier)7 Response (javax.ws.rs.core.Response)7 MockHttpServletRequest (com.helger.servlet.mock.MockHttpServletRequest)6 WebScoped (com.helger.web.scope.mgr.WebScoped)6 AS2Exception (com.helger.as2lib.exception.AS2Exception)5 IJsonObject (com.helger.json.IJsonObject)5 PeppolParticipantIdentifier (com.helger.peppolid.peppol.participant.PeppolParticipantIdentifier)4 SMPServerRESTTestRule (com.helger.phoss.smp.mock.SMPServerRESTTestRule)4 EndpointType (com.helger.xsds.peppol.smp1.EndpointType)4 IOException (java.io.IOException)4 Nonnull (javax.annotation.Nonnull)4 WrappedAS2Exception (com.helger.as2lib.exception.WrappedAS2Exception)3 AS2Message (com.helger.as2lib.message.AS2Message)3 AS2NoModuleException (com.helger.as2lib.processor.AS2NoModuleException)3 HttpClientManager (com.helger.httpclient.HttpClientManager)3 ResponseHandlerByteArray (com.helger.httpclient.response.ResponseHandlerByteArray)3 JsonWriter (com.helger.json.serialize.JsonWriter)3 SimpleParticipantIdentifier (com.helger.peppolid.simple.participant.SimpleParticipantIdentifier)3 SMPBadRequestException (com.helger.phoss.smp.exception.SMPBadRequestException)3