Search in sources :

Example 26 with StopWatch

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

the class AS2ReceiverHandler 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 " + sClientInfo);
    final AS2Message aMsg = createMessage(aSocket);
    final boolean bQuoteHeaderValues = m_aReceiverModule.isQuoteHeaderValues();
    final IAS2HttpResponseHandler aResponseHandler = new AS2HttpResponseHandlerSocket(aSocket, bQuoteHeaderValues);
    // Time the transmission
    final StopWatch aSW = StopWatch.createdStarted();
    DataSource aMsgDataSource = null;
    try {
        // Read in the message request, headers, and data
        final IHTTPIncomingDumper aIncomingDumper = getEffectiveHttpIncomingDumper();
        aMsgDataSource = HTTPHelper.readAndDecodeHttpRequest(new AS2HttpRequestDataProviderInputStream(aSocket.getInputStream()), aResponseHandler, aMsg, aIncomingDumper);
    } catch (final Exception ex) {
        new AS2NetException(aSocket.getInetAddress(), aSocket.getPort(), ex).terminate();
    }
    aSW.stop();
    if (aMsgDataSource == null) {
        LOGGER.error("Not having a data source to operate on");
    } else {
        if (aMsgDataSource instanceof ByteArrayDataSource) {
            if (LOGGER.isInfoEnabled())
                LOGGER.info("received " + AS2IOHelper.getTransferRate(((ByteArrayDataSource) aMsgDataSource).directGetBytes().length, aSW) + " from " + sClientInfo + aMsg.getLoggingText());
        } else {
            LOGGER.info("received message from " + sClientInfo + aMsg.getLoggingText() + " in " + aSW.getMillis() + " ms");
        }
        handleIncomingMessage(sClientInfo, aMsgDataSource, 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) 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) StopWatch(com.helger.commons.timing.StopWatch) ByteArrayDataSource(com.helger.mail.datasource.ByteArrayDataSource) DataSource(javax.activation.DataSource) IHTTPIncomingDumper(com.helger.as2lib.util.dump.IHTTPIncomingDumper)

Example 27 with StopWatch

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

the class NaptrLookup method lookup.

/**
 * Perform the DNS lookup based on the parameters provided in the constructor.
 *
 * @return A never <code>null</code> but maybe empty list of records.
 */
@Nonnull
public ICommonsList<NAPTRRecord> lookup() {
    // Omit the final dot
    final String sDomainName = m_aDomainName.toString(true);
    if (LOGGER.isInfoEnabled())
        LOGGER.info("Trying to look up NAPTR on '" + sDomainName + "'" + (m_nMaxRetries > 0 ? " with " + m_nMaxRetries + " retries" : "") + " using network mode " + m_eLookupMode);
    final BooleanSupplier aIsEnabled = m_bDebugMode ? LOGGER::isInfoEnabled : LOGGER::isDebugEnabled;
    final Consumer<String> aLogger = m_bDebugMode ? LOGGER::info : LOGGER::debug;
    final StopWatch aSW = StopWatch.createdStarted();
    try {
        // Use the default (static) cache that is used by default
        final ExtendedResolver aResolver = ResolverHelper.createExtendedResolver(m_aCustomDNSServers);
        aResolver.setRetries(m_nMaxRetries);
        if (m_aTimeout != null)
            aResolver.setTimeout(m_aTimeout);
        final Lookup aLookup = new Lookup(m_aDomainName, Type.NAPTR);
        aLookup.setResolver(aResolver);
        int nLookupRuns = 0;
        boolean bCanTryAgain = true;
        Record[] aRecords = null;
        if (m_eLookupMode.isUDP()) {
            if (aIsEnabled.getAsBoolean())
                aLogger.accept("  Trying UDP for NAPTR lookup after " + nLookupRuns + " unsuccessful lopkups");
            // By default try UDP
            // Stumbled upon an issue, where UDP datagram size was too small for MTU
            // size of 1500
            int nLeft = m_nMaxRetries;
            do {
                aRecords = aLookup.run();
                if (aIsEnabled.getAsBoolean())
                    aLogger.accept("    Result of UDP lookup " + nLookupRuns + ": " + aLookup.getErrorString());
                nLeft--;
                nLookupRuns++;
            } while (aLookup.getResult() == Lookup.TRY_AGAIN && nLeft >= 0);
            if (aLookup.getResult() != Lookup.TRY_AGAIN)
                bCanTryAgain = false;
        }
        if (bCanTryAgain && m_eLookupMode.isTCP()) {
            if (aIsEnabled.getAsBoolean())
                aLogger.accept("  Trying TCP for NAPTR lookup after " + nLookupRuns + " unsuccessful lopkups");
            // Retry with TCP instead of UDP
            aResolver.setTCP(true);
            // Restore max retries for TCP
            int nLeft = m_nMaxRetries;
            do {
                aRecords = aLookup.run();
                if (aIsEnabled.getAsBoolean())
                    aLogger.accept("    Result of TCP lookup " + nLookupRuns + ": " + aLookup.getErrorString());
                nLeft--;
                nLookupRuns++;
            } while (aLookup.getResult() == Lookup.TRY_AGAIN && nLeft >= 0);
        }
        if (aLookup.getResult() != Lookup.SUCCESSFUL) {
            // Wrong domain name
            if (LOGGER.isWarnEnabled())
                LOGGER.warn("Error looking up '" + sDomainName + "': " + aLookup.getErrorString());
            return new CommonsArrayList<>();
        }
        final ICommonsList<NAPTRRecord> ret = new CommonsArrayList<>();
        for (final Record aRecord : aRecords) ret.add((NAPTRRecord) aRecord);
        if (aIsEnabled.getAsBoolean())
            aLogger.accept("  Returning " + ret.size() + " NAPTR record(s) for '" + sDomainName + "' after " + nLookupRuns + " lookups");
        return ret;
    } finally {
        // Check execution time
        aSW.stop();
        final Duration aDuration = aSW.getDuration();
        if (m_aExecutionDurationWarn != null && aDuration.compareTo(m_aExecutionDurationWarn) > 0) {
            final String sMessage = "Looking up NAPTR record of '" + sDomainName + "'" + (m_nMaxRetries > 0 ? " with " + m_nMaxRetries + " retries" : "");
            m_aExecutionTimeExceededHandlers.forEach(x -> x.onLookupTimeExceeded(sMessage, aDuration, m_aExecutionDurationWarn));
        }
    }
}
Also used : ExtendedResolver(org.xbill.DNS.ExtendedResolver) Duration(java.time.Duration) StopWatch(com.helger.commons.timing.StopWatch) NAPTRRecord(org.xbill.DNS.NAPTRRecord) Lookup(org.xbill.DNS.Lookup) NAPTRRecord(org.xbill.DNS.NAPTRRecord) Record(org.xbill.DNS.Record) BooleanSupplier(java.util.function.BooleanSupplier) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) Nonnull(javax.annotation.Nonnull)

Example 28 with StopWatch

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

the class NetworkOnlineStatusDeterminatorTest method testBasic.

@Test
public void testBasic() {
    // Reset default values
    NetworkOnlineStatusDeterminator.setCacheDuration(NetworkOnlineStatusDeterminator.DEFAULT_CACHE_DURATION);
    NetworkOnlineStatusDeterminator.setConnectionTimeoutMilliseconds(NetworkOnlineStatusDeterminator.DEFAULT_CONNECTION_TIMEOUT_MILLISECONDS);
    NetworkOnlineStatusDeterminator.resetCachedStatus();
    StopWatch aSW = StopWatch.createdStarted();
    final ENetworkOnlineStatus eStatus = NetworkOnlineStatusDeterminator.getNetworkStatus();
    final long nTime1 = aSW.stopAndGetMillis();
    assertNotNull(eStatus);
    assertTrue(eStatus.isDefined());
    assertTrue(nTime1 < NetworkOnlineStatusDeterminator.DEFAULT_CONNECTION_TIMEOUT_MILLISECONDS + 500);
    aSW = StopWatch.createdStarted();
    final ENetworkOnlineStatus eStatus2 = NetworkOnlineStatusDeterminator.getNetworkStatus();
    final long nTime2 = aSW.stopAndGetMillis();
    assertNotNull(eStatus2);
    assertTrue(eStatus2.isDefined());
    assertSame(eStatus, eStatus2);
    assertTrue(nTime2 < nTime1);
}
Also used : StopWatch(com.helger.commons.timing.StopWatch) Test(org.junit.Test)

Example 29 with StopWatch

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

the class MainPortScanner method main.

public static void main(final String[] args) {
    final int nStartPort = CNetworkPort.MINIMUM_PORT_NUMBER;
    final int nEndPort = CNetworkPort.MAXIMUM_PORT_NUMBER;
    final EnumSet<ENetworkProtocol> aTypes = EnumSet.allOf(ENetworkProtocol.class);
    final StopWatch aSW = StopWatch.createdStarted();
    for (int nPort = nStartPort; nPort <= nEndPort; ++nPort) for (final ENetworkProtocol eType : aTypes) {
        final int nFinalPort = nPort;
        final boolean bIsUsed = eType.isPortUsed(nPort);
        if (bIsUsed) {
            LOGGER.info(eType.name() + " Port " + nPort + " is used");
            DefaultNetworkPorts.forEachPort(x -> x.getPort() == nFinalPort && x.getProtocol() == eType, x -> LOGGER.info("  " + StringHelper.getConcatenatedOnDemand(x.getName(), ": ", x.getDescription())));
        }
    }
    aSW.stop();
    final int nCount = (nEndPort - nStartPort) * aTypes.size();
    LOGGER.info(nCount + " ports checked in " + aSW.getMillis() + " ms");
}
Also used : DefaultNetworkPorts(com.helger.network.port.DefaultNetworkPorts) Logger(org.slf4j.Logger) StringHelper(com.helger.commons.string.StringHelper) StopWatch(com.helger.commons.timing.StopWatch) LoggerFactory(org.slf4j.LoggerFactory) ENetworkProtocol(com.helger.network.port.ENetworkProtocol) EnumSet(java.util.EnumSet) CNetworkPort(com.helger.network.port.CNetworkPort) ENetworkProtocol(com.helger.network.port.ENetworkProtocol) StopWatch(com.helger.commons.timing.StopWatch)

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