use of com.helger.commons.timing.StopWatch 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();
}
}
use of com.helger.commons.timing.StopWatch in project phoss-smp by phax.
the class APIExecutorQueryGetServiceMetadata method invokeAPI.
public void invokeAPI(@Nonnull final IAPIDescriptor aAPIDescriptor, @Nonnull @Nonempty final String sPath, @Nonnull final Map<String, String> aPathVariables, @Nonnull final IRequestWebScopeWithoutResponse aRequestScope, @Nonnull final UnifiedResponse aUnifiedResponse) throws Exception {
final String sPathServiceGroupID = aPathVariables.get(SMPRestFilter.PARAM_SERVICE_GROUP_ID);
final ISMPServerAPIDataProvider aDataProvider = new SMPRestDataProvider(aRequestScope, sPathServiceGroupID);
// Is the remote query API disabled?
if (SMPServerConfiguration.isRestRemoteQueryAPIDisabled()) {
throw new SMPPreconditionFailedException("The remote query API is disabled. getRemoteServiceInformation will not be executed", aDataProvider.getCurrentURI());
}
final IIdentifierFactory aIF = SMPMetaManager.getIdentifierFactory();
final ESMPAPIType eAPIType = SMPServerConfiguration.getRESTType().getAPIType();
final IParticipantIdentifier aParticipantID = aIF.parseParticipantIdentifier(sPathServiceGroupID);
if (aParticipantID == null) {
throw SMPBadRequestException.failedToParseSG(sPathServiceGroupID, aDataProvider.getCurrentURI());
}
final SMPQueryParams aQueryParams = SMPQueryParams.create(eAPIType, aParticipantID);
final String sDocTypeID = aPathVariables.get(SMPRestFilter.PARAM_DOCUMENT_TYPE_ID);
final IDocumentTypeIdentifier aDocTypeID = aIF.parseDocumentTypeIdentifier(sDocTypeID);
if (aDocTypeID == null)
throw SMPBadRequestException.failedToParseDocType(sDocTypeID, null);
final boolean bXMLSchemaValidation = aRequestScope.params().getAsBoolean("xmlSchemaValidation", true);
final boolean bVerifySignature = aRequestScope.params().getAsBoolean("verifySignature", true);
final ZonedDateTime aQueryDT = PDTFactory.getCurrentZonedDateTimeUTC();
final StopWatch aSW = StopWatch.createdStarted();
final String sLogPrefix = "[QueryAPI] ";
LOGGER.info(sLogPrefix + "Participant information of '" + aParticipantID.getURIEncoded() + "' is queried using SMP API '" + eAPIType + "' from '" + aQueryParams.getSMPHostURI() + "' for document type '" + aDocTypeID.getURIEncoded() + "'; XSD validation=" + bXMLSchemaValidation + "; signature verification=" + bVerifySignature);
IJsonObject aJson = null;
switch(eAPIType) {
case PEPPOL:
{
final SMPClientReadOnly aSMPClient = new SMPClientReadOnly(aQueryParams.getSMPHostURI());
aSMPClient.setXMLSchemaValidation(bXMLSchemaValidation);
aSMPClient.setVerifySignature(bVerifySignature);
final com.helger.xsds.peppol.smp1.SignedServiceMetadataType aSSM = aSMPClient.getServiceMetadataOrNull(aParticipantID, aDocTypeID);
if (aSSM != null) {
final com.helger.xsds.peppol.smp1.ServiceMetadataType aSM = aSSM.getServiceMetadata();
aJson = SMPJsonResponse.convert(aParticipantID, aDocTypeID, aSM);
}
break;
}
case OASIS_BDXR_V1:
{
final BDXRClientReadOnly aBDXR1Client = new BDXRClientReadOnly(aQueryParams.getSMPHostURI());
aBDXR1Client.setXMLSchemaValidation(bXMLSchemaValidation);
aBDXR1Client.setVerifySignature(bVerifySignature);
final com.helger.xsds.bdxr.smp1.SignedServiceMetadataType aSSM = aBDXR1Client.getServiceMetadataOrNull(aParticipantID, aDocTypeID);
if (aSSM != null) {
final com.helger.xsds.bdxr.smp1.ServiceMetadataType aSM = aSSM.getServiceMetadata();
aJson = SMPJsonResponse.convert(aParticipantID, aDocTypeID, aSM);
}
break;
}
}
aSW.stop();
if (aJson == null) {
LOGGER.error(sLogPrefix + "Failed to perform the SMP lookup");
aUnifiedResponse.setStatus(CHttp.HTTP_NOT_FOUND);
} else {
LOGGER.info(sLogPrefix + "Succesfully finished lookup lookup after " + aSW.getMillis() + " milliseconds");
aJson.add("queryDateTime", DateTimeFormatter.ISO_ZONED_DATE_TIME.format(aQueryDT));
aJson.add("queryDurationMillis", aSW.getMillis());
final String sRet = new JsonWriter(JsonWriterSettings.DEFAULT_SETTINGS_FORMATTED).writeAsString(aJson);
aUnifiedResponse.setContentAndCharset(sRet, StandardCharsets.UTF_8).setMimeType(CMimeType.APPLICATION_JSON).enableCaching(1 * CGlobal.SECONDS_PER_HOUR);
}
}
use of com.helger.commons.timing.StopWatch in project phoss-smp by phax.
the class SMPStatusProvider method getDefaultStatusData.
@Nonnull
@ReturnsMutableCopy
public static IJsonObject getDefaultStatusData(final boolean bDisableLongRunningOperations) {
if (LOGGER.isDebugEnabled())
LOGGER.debug("Building status data");
final StopWatch aSW = StopWatch.createdStarted();
final ISMPSettings aSettings = SMPMetaManager.getSettings();
final LocalDateTime aNow = PDTFactory.getCurrentLocalDateTime();
final ISMLInfo aSMLInfo = aSettings.getSMLInfo();
final IJsonObject aStatusData = new JsonObject();
// Since 5.0.7
aStatusData.add("build.timestamp", CSMPServer.getBuildTimestamp());
// Since 5.3.3
aStatusData.addIfNotNull("startup.datetime", PDTWebDateHelper.getAsStringXSD(SMPWebAppListener.getStartupDateTime()));
aStatusData.add("status.datetime", PDTWebDateHelper.getAsStringXSD(PDTFactory.getCurrentOffsetDateTimeUTC()));
aStatusData.add("version.smp", CSMPServer.getVersionNumber());
aStatusData.add("version.java", SystemProperties.getJavaVersion());
aStatusData.add("global.debug", GlobalDebug.isDebugMode());
aStatusData.add("global.production", GlobalDebug.isProductionMode());
aStatusData.add("smp.backend", SMPServerConfiguration.getBackend());
aStatusData.add("smp.mode", SMPWebAppConfiguration.isTestVersion() ? "test" : "production");
aStatusData.add("smp.resttype", SMPServerConfiguration.getRESTType().getID());
aStatusData.add("smp.identifiertype", SMPServerConfiguration.getIdentifierType().getID());
aStatusData.add("smp.id", SMPServerConfiguration.getSMLSMPID());
aStatusData.add("smp.writable-rest-api.enabled", !aSettings.isRESTWritableAPIDisabled());
// New in 5.1.0
aStatusData.add("smp.publicurl", SMPServerConfiguration.getPublicServerURL());
// New in 5.1.0
aStatusData.add("smp.forceroot", SMPServerConfiguration.isForceRoot());
// New in 5.2.0
aStatusData.add("smp.rest.log-exceptions", SMPServerConfiguration.isRESTLogExceptions());
// New in 5.2.1
aStatusData.add("smp.rest.payload-on-error", SMPServerConfiguration.isRESTPayloadOnError());
// SML information
aStatusData.add("smp.sml.enabled", aSettings.isSMLEnabled());
aStatusData.add("smp.sml.needed", aSettings.isSMLRequired());
if (aSMLInfo != null) {
aStatusData.add("smp.sml.url", aSMLInfo.getManagementServiceURL());
aStatusData.add("smp.sml.dnszone", aSMLInfo.getDNSZone());
}
aStatusData.addIfNotNull("smp.sml.connection-timeout-ms", SMPServerConfiguration.getSMLConnectionTimeoutMS());
aStatusData.add("smp.sml.request-timeout-ms", SMPServerConfiguration.getSMLRequestTimeoutMS());
// Directory information
aStatusData.add("smp.pd.enabled", aSettings.isDirectoryIntegrationEnabled());
// New in 5.1.0
aStatusData.add("smp.pd.needed", aSettings.isDirectoryIntegrationRequired());
aStatusData.add("smp.pd.auto-update", aSettings.isDirectoryIntegrationAutoUpdate());
aStatusData.add("smp.pd.hostname", aSettings.getDirectoryHostName());
// Certificate information
final boolean bCertConfigOk = SMPKeyManager.isKeyStoreValid();
aStatusData.add("smp.certificate.configuration-valid", bCertConfigOk);
if (bCertConfigOk) {
final SMPKeyManager aKeyMgr = SMPKeyManager.getInstance();
final PrivateKeyEntry aKeyEntry = aKeyMgr.getPrivateKeyEntry();
if (aKeyEntry != null) {
final Certificate[] aChain = aKeyEntry.getCertificateChain();
if (aChain.length > 0 && aChain[0] instanceof X509Certificate) {
final X509Certificate aX509Cert = (X509Certificate) aChain[0];
aStatusData.add("smp.certificate.issuer", aX509Cert.getIssuerX500Principal().getName());
aStatusData.add("smp.certificate.subject", aX509Cert.getSubjectX500Principal().getName());
final LocalDateTime aNotAfter = PDTFactory.createLocalDateTime(aX509Cert.getNotAfter());
final boolean bIsExpired = aNow.isAfter(aNotAfter);
aStatusData.add("smp.certificate.expired", bIsExpired);
}
}
}
// Proxy configuration (since 5.2.0)
aStatusData.add("proxy.http.configured", SMPServerConfiguration.getAsHttpProxySettings() != null);
aStatusData.add("proxy.https.configured", SMPServerConfiguration.getAsHttpsProxySettings() != null);
aStatusData.add("proxy.username.configured", StringHelper.hasText(SMPServerConfiguration.getProxyUsername()));
// CSP configuration (since 5.2.6)
aStatusData.add("csp.enabled", SMPWebAppConfiguration.isCSPEnabled());
aStatusData.add("csp.reporting.only", SMPWebAppConfiguration.isCSPReportingOnly());
aStatusData.add("csp.reporting.enabled", SMPWebAppConfiguration.isCSPReportingEnabled());
// Add SPI data as well
for (final ISMPStatusProviderExtensionSPI aImpl : LIST) {
final ICommonsOrderedMap<String, ?> aMap = aImpl.getAdditionalStatusData(bDisableLongRunningOperations);
aStatusData.addAll(aMap);
}
final long nMillis = aSW.stopAndGetMillis();
if (nMillis > 100)
LOGGER.info("Finished building status data after " + nMillis + " milliseconds which is considered to be too long");
else if (LOGGER.isDebugEnabled())
LOGGER.debug("Finished building status data");
return aStatusData;
}
use of com.helger.commons.timing.StopWatch in project phoss-smp by phax.
the class ServiceGroupInterfaceFillDBTest method testCreateAFewServiceGroups.
@Test
public void testCreateAFewServiceGroups() throws SMPClientException {
final SMPClient aSMPClient = new MockSMPClient();
final StopWatch aSW = StopWatch.createdStarted();
final int nCount = 2_000;
for (int i = 0; i < nCount; ++i) {
final IParticipantIdentifier aPI = PeppolIdentifierFactory.INSTANCE.createParticipantIdentifierWithDefaultScheme(PID_PREFIX_9999_PHOSS + StringHelper.getLeadingZero(i, 4));
final ServiceGroupType aSG = new ServiceGroupType();
aSG.setParticipantIdentifier(new SimpleParticipantIdentifier(aPI));
aSG.setServiceMetadataReferenceCollection(new ServiceMetadataReferenceCollectionType());
aSMPClient.saveServiceGroup(aSG, CREDENTIALS);
}
aSW.stop();
LOGGER.info("Created " + nCount + " ServiceGroups in " + aSW.getDuration() + " (= " + (aSW.getMillis() / nCount) + " ms/entry)");
}
use of com.helger.commons.timing.StopWatch in project phoss-smp by phax.
the class ServiceMetadataInterfaceFillDBTest method testCreateAndDeleteServiceInformationSMPClient.
@Test
public void testCreateAndDeleteServiceInformationSMPClient() throws SMPClientException {
final SMPClient aSMPClient = new MockSMPClient();
final StopWatch aSW = StopWatch.createdStarted();
int nEndpoints = 0;
try (final WebScoped aWS = new WebScoped(new MockHttpServletRequest())) {
final int nCount = 2_000;
for (int i = 0; i < nCount; ++i) {
final IParticipantIdentifier aPI_LC = PeppolIdentifierFactory.INSTANCE.createParticipantIdentifierWithDefaultScheme(PID_PREFIX_9999_PHOSS + StringHelper.getLeadingZero(i, 4));
final PeppolDocumentTypeIdentifier aDT = EPredefinedDocumentTypeIdentifier.INVOICE_EN16931_PEPPOL_V30.getAsDocumentTypeIdentifier();
final PeppolProcessIdentifier aProcID = EPredefinedProcessIdentifier.BIS3_BILLING.getAsProcessIdentifier();
for (final ESMPTransportProfile eTP : new ESMPTransportProfile[] { ESMPTransportProfile.TRANSPORT_PROFILE_AS2, ESMPTransportProfile.TRANSPORT_PROFILE_PEPPOL_AS4_V2 }) {
final ServiceInformationType aSI = new ServiceInformationType();
aSI.setParticipantIdentifier(new SimpleParticipantIdentifier(aPI_LC));
aSI.setDocumentIdentifier(aDT);
{
final ProcessListType aPL = new ProcessListType();
final ProcessType aProcess = new ProcessType();
aProcess.setProcessIdentifier(aProcID);
final ServiceEndpointList aSEL = new ServiceEndpointList();
final EndpointType aEndpoint = new EndpointType();
aEndpoint.setEndpointReference(W3CEndpointReferenceHelper.createEndpointReference("http://test.smpserver/" + eTP.getID()));
aEndpoint.setRequireBusinessLevelSignature(false);
aEndpoint.setCertificate("blacert");
aEndpoint.setServiceDescription("Unit test service");
aEndpoint.setTechnicalContactUrl("https://github.com/phax/phoss-smp");
aEndpoint.setTransportProfile(eTP.getID());
aSEL.addEndpoint(aEndpoint);
aProcess.setServiceEndpointList(aSEL);
aPL.addProcess(aProcess);
aSI.setProcessList(aPL);
}
aSMPClient.saveServiceInformation(aSI, CREDENTIALS);
++nEndpoints;
}
}
}
aSW.stop();
LOGGER.info("Created " + nEndpoints + " ServiceInformation in " + aSW.getDuration() + " (= " + (aSW.getMillis() / nEndpoints) + " ms/entry)");
}
Aggregations