Search in sources :

Example 21 with StopWatch

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

the class APIExecutorImportXMLVer1 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 ISMPServerAPIDataProvider aDataProvider = new SMPRestDataProvider(aRequestScope, null);
    // Is the writable API disabled?
    if (SMPMetaManager.getSettings().isRESTWritableAPIDisabled()) {
        throw new SMPPreconditionFailedException("The writable REST API is disabled. importServiceGroups will not be executed", aDataProvider.getCurrentURI());
    }
    final String sLogPrefix = "[REST API Import-XML-V1] ";
    final String sPathUserLoginName = aPathVariables.get(SMPRestFilter.PARAM_USER_ID);
    LOGGER.info(sLogPrefix + "Starting Import");
    // Only authenticated user may do so
    final BasicAuthClientCredentials aBasicAuth = getMandatoryAuth(aRequestScope.headers());
    SMPUserManagerPhoton.validateUserCredentials(aBasicAuth);
    // Start action after authentication
    final ISMPServiceGroupManager aServiceGroupMgr = SMPMetaManager.getServiceGroupMgr();
    final ISMPBusinessCardManager aBusinessCardMgr = SMPMetaManager.getBusinessCardMgr();
    final IUserManager aUserMgr = PhotonSecurityManager.getUserMgr();
    final ICommonsSet<String> aAllServiceGroupIDs = aServiceGroupMgr.getAllSMPServiceGroupIDs();
    final ICommonsSet<String> aAllBusinessCardIDs = aBusinessCardMgr.getAllSMPBusinessCardIDs();
    // Try to use ID or login name
    IUser aDefaultOwner = aUserMgr.getUserOfID(sPathUserLoginName);
    if (aDefaultOwner == null)
        aDefaultOwner = aUserMgr.getUserOfLoginName(sPathUserLoginName);
    if (aDefaultOwner == null || aDefaultOwner.isDeleted()) {
        // Setting the owner to a disabled user might make sense
        throw new SMPBadRequestException(sLogPrefix + "The user ID or login name '" + sPathUserLoginName + "' does not exist", aDataProvider.getCurrentURI());
    }
    LOGGER.info(sLogPrefix + "Using '" + aDefaultOwner.getID() + "' / '" + aDefaultOwner.getLoginName() + "' as the default owner");
    final boolean bOverwriteExisting = aRequestScope.params().getAsBoolean(PARAM_OVERVWRITE_EXISTING, DEFAULT_OVERWRITE_EXISTING);
    final byte[] aPayload = StreamHelper.getAllBytes(aRequestScope.getRequest().getInputStream());
    final IMicroDocument aDoc = MicroReader.readMicroXML(aPayload);
    if (aDoc == null || aDoc.getDocumentElement() == null) {
        // Cannot parse
        throw new SMPBadRequestException("Failed to parse XML payload", aDataProvider.getCurrentURI());
    }
    final String sVersion = aDoc.getDocumentElement().getAttributeValue(CSMPExchange.ATTR_VERSION);
    if (!CSMPExchange.VERSION_10.equals(sVersion)) {
        throw new SMPBadRequestException("The provided payload is not an XML file version 1.0", aDataProvider.getCurrentURI());
    }
    // Version 1.0
    LOGGER.info(sLogPrefix + "The provided payload is an XML file version 1.0");
    final ZonedDateTime aQueryDT = PDTFactory.getCurrentZonedDateTimeUTC();
    final StopWatch aSW = StopWatch.createdStarted();
    // Start the import
    final ICommonsList<ImportActionItem> aActionList = new CommonsArrayList<>();
    final ImportSummary aImportSummary = new ImportSummary();
    ServiceGroupImport.importXMLVer10(aDoc.getDocumentElement(), bOverwriteExisting, aDefaultOwner, aAllServiceGroupIDs, aAllBusinessCardIDs, aActionList, aImportSummary);
    aSW.stop();
    LOGGER.info(sLogPrefix + "Finished import after " + aSW.getMillis() + " milliseconds");
    // Everything added to the action list is already logged
    final boolean bResponseAsXML = true;
    if (bResponseAsXML) {
        // Create XML version
        final IMicroDocument aResponseDoc = new MicroDocument();
        final IMicroElement eRoot = aResponseDoc.appendElement("importResult");
        eRoot.setAttribute("version", "1");
        eRoot.setAttribute("importStartDateTime", PDTWebDateHelper.getAsStringXSD(aQueryDT));
        final IMicroElement eSettings = eRoot.appendElement("settings");
        eSettings.setAttribute("overwriteExisting", bOverwriteExisting);
        eSettings.setAttribute("defaultOwnerID", aDefaultOwner.getID());
        eSettings.setAttribute("defaultOwnerLoginName", aDefaultOwner.getLoginName());
        final ICommonsMap<String, MutableInt> aErrorLevelCount = new CommonsTreeMap<>();
        for (final ImportActionItem aAction : aActionList) {
            eRoot.appendChild(aAction.getAsMicroElement("action"));
            aErrorLevelCount.computeIfAbsent(aAction.getErrorLevelName(), k -> new MutableInt(0)).inc();
        }
        {
            final IMicroElement eSummary = eRoot.appendElement("summary");
            eSummary.setAttribute("durationMillis", aSW.getMillis());
            for (final Map.Entry<String, MutableInt> aEntry : aErrorLevelCount.entrySet()) eSummary.appendElement("errorlevel").setAttribute("id", aEntry.getKey()).setAttribute("count", aEntry.getValue().intValue());
            aImportSummary.appendTo(eSummary);
        }
        final XMLWriterSettings aXWS = new XMLWriterSettings().setIndent(EXMLSerializeIndent.INDENT_AND_ALIGN);
        aUnifiedResponse.setContentAndCharset(MicroWriter.getNodeAsString(aResponseDoc, aXWS), aXWS.getCharset()).setMimeType(new MimeType(CMimeType.APPLICATION_XML).addParameter(CMimeType.PARAMETER_NAME_CHARSET, aXWS.getCharset().name()));
    } else {
        // Create JSON version
        final IJsonObject aJson = new JsonObject();
        aJson.add("version", "1");
        aJson.add("importStartDateTime", DateTimeFormatter.ISO_ZONED_DATE_TIME.format(aQueryDT));
        aJson.addJson("settings", new JsonObject().add("overwriteExisting", bOverwriteExisting).add("defaultOwnerID", aDefaultOwner.getID()).add("defaultOwnerLoginName", aDefaultOwner.getLoginName()));
        final IJsonArray aActions = new JsonArray();
        final ICommonsMap<String, MutableInt> aLevelCount = new CommonsTreeMap<>();
        for (final ImportActionItem aAction : aActionList) {
            aActions.add(aAction.getAsJsonObject());
            aLevelCount.computeIfAbsent(aAction.getErrorLevelName(), k -> new MutableInt(0)).inc();
        }
        aJson.addJson("actions", aActions);
        {
            final IJsonObject aSummary = new JsonObject();
            aSummary.add("durationMillis", aSW.getMillis());
            final IJsonArray aLevels = new JsonArray();
            for (final Map.Entry<String, MutableInt> aEntry : aLevelCount.entrySet()) aLevels.add(new JsonObject().add("id", aEntry.getKey()).add("count", aEntry.getValue().intValue()));
            aSummary.addJson("errorlevels", aLevels);
            aImportSummary.appendTo(aSummary);
            aJson.addJson("summary", aSummary);
        }
        final String sRet = new JsonWriter(JsonWriterSettings.DEFAULT_SETTINGS_FORMATTED).writeAsString(aJson);
        aUnifiedResponse.setContentAndCharset(sRet, StandardCharsets.UTF_8).setMimeType(CMimeType.APPLICATION_JSON);
    }
    aUnifiedResponse.disableCaching();
}
Also used : IAPIDescriptor(com.helger.photon.api.IAPIDescriptor) StreamHelper(com.helger.commons.io.stream.StreamHelper) ZonedDateTime(java.time.ZonedDateTime) LoggerFactory(org.slf4j.LoggerFactory) CommonsTreeMap(com.helger.commons.collection.impl.CommonsTreeMap) IMicroDocument(com.helger.xml.microdom.IMicroDocument) IUserManager(com.helger.photon.security.user.IUserManager) JsonWriterSettings(com.helger.json.serialize.JsonWriterSettings) CMimeType(com.helger.commons.mime.CMimeType) Nonempty(com.helger.commons.annotation.Nonempty) PDTFactory(com.helger.commons.datetime.PDTFactory) ISMPServerAPIDataProvider(com.helger.phoss.smp.restapi.ISMPServerAPIDataProvider) IUser(com.helger.photon.security.user.IUser) IMicroElement(com.helger.xml.microdom.IMicroElement) Map(java.util.Map) XMLWriterSettings(com.helger.xml.serialize.write.XMLWriterSettings) StandardCharsets(java.nio.charset.StandardCharsets) JsonObject(com.helger.json.JsonObject) ICommonsList(com.helger.commons.collection.impl.ICommonsList) IJsonArray(com.helger.json.IJsonArray) UnifiedResponse(com.helger.servlet.response.UnifiedResponse) MimeType(com.helger.commons.mime.MimeType) ICommonsMap(com.helger.commons.collection.impl.ICommonsMap) ISMPServiceGroupManager(com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroupManager) PhotonSecurityManager(com.helger.photon.security.mgr.PhotonSecurityManager) ImportSummary(com.helger.phoss.smp.exchange.ImportSummary) ISMPBusinessCardManager(com.helger.phoss.smp.domain.businesscard.ISMPBusinessCardManager) ICommonsSet(com.helger.commons.collection.impl.ICommonsSet) SMPBadRequestException(com.helger.phoss.smp.exception.SMPBadRequestException) BasicAuthClientCredentials(com.helger.http.basicauth.BasicAuthClientCredentials) CSMPExchange(com.helger.phoss.smp.exchange.CSMPExchange) IJsonObject(com.helger.json.IJsonObject) ImportActionItem(com.helger.phoss.smp.exchange.ImportActionItem) MicroDocument(com.helger.xml.microdom.MicroDocument) JsonArray(com.helger.json.JsonArray) Nonnull(javax.annotation.Nonnull) IRequestWebScopeWithoutResponse(com.helger.web.scope.IRequestWebScopeWithoutResponse) Logger(org.slf4j.Logger) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) MutableInt(com.helger.commons.mutable.MutableInt) SMPPreconditionFailedException(com.helger.phoss.smp.exception.SMPPreconditionFailedException) SMPMetaManager(com.helger.phoss.smp.domain.SMPMetaManager) PDTWebDateHelper(com.helger.commons.datetime.PDTWebDateHelper) ServiceGroupImport(com.helger.phoss.smp.exchange.ServiceGroupImport) JsonWriter(com.helger.json.serialize.JsonWriter) MicroWriter(com.helger.xml.microdom.serialize.MicroWriter) StopWatch(com.helger.commons.timing.StopWatch) DateTimeFormatter(java.time.format.DateTimeFormatter) EXMLSerializeIndent(com.helger.xml.serialize.write.EXMLSerializeIndent) MicroReader(com.helger.xml.microdom.serialize.MicroReader) SMPUserManagerPhoton(com.helger.phoss.smp.domain.user.SMPUserManagerPhoton) ISMPServiceGroupManager(com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroupManager) IUserManager(com.helger.photon.security.user.IUserManager) ImportSummary(com.helger.phoss.smp.exchange.ImportSummary) ImportActionItem(com.helger.phoss.smp.exchange.ImportActionItem) JsonObject(com.helger.json.JsonObject) IJsonObject(com.helger.json.IJsonObject) CMimeType(com.helger.commons.mime.CMimeType) MimeType(com.helger.commons.mime.MimeType) IMicroDocument(com.helger.xml.microdom.IMicroDocument) MicroDocument(com.helger.xml.microdom.MicroDocument) ZonedDateTime(java.time.ZonedDateTime) IJsonObject(com.helger.json.IJsonObject) ISMPServerAPIDataProvider(com.helger.phoss.smp.restapi.ISMPServerAPIDataProvider) IUser(com.helger.photon.security.user.IUser) SMPBadRequestException(com.helger.phoss.smp.exception.SMPBadRequestException) XMLWriterSettings(com.helger.xml.serialize.write.XMLWriterSettings) JsonWriter(com.helger.json.serialize.JsonWriter) CommonsTreeMap(com.helger.commons.collection.impl.CommonsTreeMap) StopWatch(com.helger.commons.timing.StopWatch) IJsonArray(com.helger.json.IJsonArray) JsonArray(com.helger.json.JsonArray) ISMPBusinessCardManager(com.helger.phoss.smp.domain.businesscard.ISMPBusinessCardManager) SMPPreconditionFailedException(com.helger.phoss.smp.exception.SMPPreconditionFailedException) BasicAuthClientCredentials(com.helger.http.basicauth.BasicAuthClientCredentials) IMicroElement(com.helger.xml.microdom.IMicroElement) MutableInt(com.helger.commons.mutable.MutableInt) IJsonArray(com.helger.json.IJsonArray) IMicroDocument(com.helger.xml.microdom.IMicroDocument) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList)

Example 22 with StopWatch

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

the class APIExecutorQueryGetBusinessCard 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. getRemoteBusinessCard 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 ZonedDateTime aQueryDT = PDTFactory.getCurrentZonedDateTimeUTC();
    final StopWatch aSW = StopWatch.createdStarted();
    final String sLogPrefix = "[QueryAPI] ";
    LOGGER.info(sLogPrefix + "BusinessCard of '" + aParticipantID.getURIEncoded() + "' is queried using SMP API '" + eAPIType + "' from '" + aQueryParams.getSMPHostURI() + "'");
    IJsonObject aJson = null;
    final String sBCURL = aQueryParams.getSMPHostURI().toString() + "/businesscard/" + aParticipantID.getURIEncoded();
    LOGGER.info(sLogPrefix + "Querying BC from '" + sBCURL + "'");
    byte[] aData;
    try (HttpClientManager aHttpClientMgr = new HttpClientManager()) {
        final HttpGet aGet = new HttpGet(sBCURL);
        aData = aHttpClientMgr.execute(aGet, new ResponseHandlerByteArray());
    } catch (final Exception ex) {
        aData = null;
    }
    if (aData == null)
        LOGGER.warn(sLogPrefix + "No Business Card is available for that participant.");
    else {
        final PDBusinessCard aBC = PDBusinessCardHelper.parseBusinessCard(aData, (Charset) null);
        if (aBC == null) {
            LOGGER.error(sLogPrefix + "Failed to parse BC:\n" + new String(aData, StandardCharsets.UTF_8));
        } else {
            // Business Card found
            aJson = aBC.getAsJson();
        }
    }
    aSW.stop();
    if (aJson == null) {
        LOGGER.error(sLogPrefix + "Failed to perform the BusinessCard SMP lookup");
        aUnifiedResponse.setStatus(CHttp.HTTP_NOT_FOUND);
    } else {
        LOGGER.info(sLogPrefix + "Succesfully finished BusinessCard 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);
    }
}
Also used : PDBusinessCard(com.helger.pd.businesscard.generic.PDBusinessCard) ResponseHandlerByteArray(com.helger.httpclient.response.ResponseHandlerByteArray) HttpGet(org.apache.http.client.methods.HttpGet) JsonWriter(com.helger.json.serialize.JsonWriter) SMPBadRequestException(com.helger.phoss.smp.exception.SMPBadRequestException) SMPPreconditionFailedException(com.helger.phoss.smp.exception.SMPPreconditionFailedException) ESMPAPIType(com.helger.peppol.sml.ESMPAPIType) StopWatch(com.helger.commons.timing.StopWatch) SMPPreconditionFailedException(com.helger.phoss.smp.exception.SMPPreconditionFailedException) HttpClientManager(com.helger.httpclient.HttpClientManager) ZonedDateTime(java.time.ZonedDateTime) IJsonObject(com.helger.json.IJsonObject) ISMPServerAPIDataProvider(com.helger.phoss.smp.restapi.ISMPServerAPIDataProvider) IIdentifierFactory(com.helger.peppolid.factory.IIdentifierFactory) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier)

Example 23 with StopWatch

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

the class APIExecutorQueryGetDocTypes 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. getRemoteDocTypes 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 boolean bQueryBusinessCard = aRequestScope.params().getAsBoolean("businessCard", false);
    final boolean bXMLSchemaValidation = aRequestScope.params().getAsBoolean("xmlSchemaValidation", true);
    final ZonedDateTime aQueryDT = PDTFactory.getCurrentZonedDateTimeUTC();
    final StopWatch aSW = StopWatch.createdStarted();
    final String sLogPrefix = "[QueryAPI] ";
    LOGGER.info(sLogPrefix + "Document types of '" + aParticipantID.getURIEncoded() + "' are queried using SMP API '" + eAPIType + "' from '" + aQueryParams.getSMPHostURI() + "'; XSD validation=" + bXMLSchemaValidation);
    ICommonsSortedMap<String, String> aSGHrefs = null;
    switch(eAPIType) {
        case PEPPOL:
            {
                final SMPClientReadOnly aSMPClient = new SMPClientReadOnly(aQueryParams.getSMPHostURI());
                aSMPClient.setXMLSchemaValidation(bXMLSchemaValidation);
                // Get all HRefs and sort them by decoded URL
                final com.helger.xsds.peppol.smp1.ServiceGroupType aSG = aSMPClient.getServiceGroupOrNull(aParticipantID);
                // Map from cleaned URL to original URL
                if (aSG != null && aSG.getServiceMetadataReferenceCollection() != null) {
                    aSGHrefs = new CommonsTreeMap<>();
                    for (final com.helger.xsds.peppol.smp1.ServiceMetadataReferenceType aSMR : aSG.getServiceMetadataReferenceCollection().getServiceMetadataReference()) {
                        // Decoded href is important for unification
                        final String sHref = CIdentifier.createPercentDecoded(aSMR.getHref());
                        if (aSGHrefs.put(sHref, aSMR.getHref()) != null)
                            LOGGER.warn(sLogPrefix + "The ServiceGroup list contains the duplicate URL '" + sHref + "'");
                    }
                }
                break;
            }
        case OASIS_BDXR_V1:
            {
                aSGHrefs = new CommonsTreeMap<>();
                final BDXRClientReadOnly aBDXR1Client = new BDXRClientReadOnly(aQueryParams.getSMPHostURI());
                aBDXR1Client.setXMLSchemaValidation(bXMLSchemaValidation);
                // Get all HRefs and sort them by decoded URL
                final com.helger.xsds.bdxr.smp1.ServiceGroupType aSG = aBDXR1Client.getServiceGroupOrNull(aParticipantID);
                // Map from cleaned URL to original URL
                if (aSG != null && aSG.getServiceMetadataReferenceCollection() != null) {
                    aSGHrefs = new CommonsTreeMap<>();
                    for (final com.helger.xsds.bdxr.smp1.ServiceMetadataReferenceType aSMR : aSG.getServiceMetadataReferenceCollection().getServiceMetadataReference()) {
                        // Decoded href is important for unification
                        final String sHref = CIdentifier.createPercentDecoded(aSMR.getHref());
                        if (aSGHrefs.put(sHref, aSMR.getHref()) != null)
                            LOGGER.warn(sLogPrefix + "The ServiceGroup list contains the duplicate URL '" + sHref + "'");
                    }
                }
                break;
            }
    }
    IJsonObject aJson = null;
    if (aSGHrefs != null)
        aJson = SMPJsonResponse.convert(eAPIType, aParticipantID, aSGHrefs, aIF);
    if (bQueryBusinessCard) {
        final String sBCURL = aQueryParams.getSMPHostURI().toString() + "/businesscard/" + aParticipantID.getURIEncoded();
        LOGGER.info(sLogPrefix + "Querying BC from '" + sBCURL + "'");
        byte[] aData;
        try (HttpClientManager aHttpClientMgr = new HttpClientManager()) {
            final HttpGet aGet = new HttpGet(sBCURL);
            aData = aHttpClientMgr.execute(aGet, new ResponseHandlerByteArray());
        } catch (final Exception ex) {
            aData = null;
        }
        if (aData == null)
            LOGGER.warn(sLogPrefix + "No Business Card is available for that participant.");
        else {
            final PDBusinessCard aBC = PDBusinessCardHelper.parseBusinessCard(aData, (Charset) null);
            if (aBC == null) {
                LOGGER.error(sLogPrefix + "Failed to parse BC:\n" + new String(aData, StandardCharsets.UTF_8));
            } else {
                // Business Card found
                if (aJson == null)
                    aJson = new JsonObject();
                aJson.addJson("businessCard", aBC.getAsJson());
            }
        }
    }
    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);
    }
}
Also used : SMPClientReadOnly(com.helger.smpclient.peppol.SMPClientReadOnly) PDBusinessCard(com.helger.pd.businesscard.generic.PDBusinessCard) ResponseHandlerByteArray(com.helger.httpclient.response.ResponseHandlerByteArray) HttpGet(org.apache.http.client.methods.HttpGet) IJsonObject(com.helger.json.IJsonObject) JsonObject(com.helger.json.JsonObject) HttpClientManager(com.helger.httpclient.HttpClientManager) ZonedDateTime(java.time.ZonedDateTime) IJsonObject(com.helger.json.IJsonObject) ISMPServerAPIDataProvider(com.helger.phoss.smp.restapi.ISMPServerAPIDataProvider) IIdentifierFactory(com.helger.peppolid.factory.IIdentifierFactory) BDXRClientReadOnly(com.helger.smpclient.bdxr1.BDXRClientReadOnly) JsonWriter(com.helger.json.serialize.JsonWriter) CommonsTreeMap(com.helger.commons.collection.impl.CommonsTreeMap) SMPBadRequestException(com.helger.phoss.smp.exception.SMPBadRequestException) SMPPreconditionFailedException(com.helger.phoss.smp.exception.SMPPreconditionFailedException) ESMPAPIType(com.helger.peppol.sml.ESMPAPIType) StopWatch(com.helger.commons.timing.StopWatch) SMPPreconditionFailedException(com.helger.phoss.smp.exception.SMPPreconditionFailedException) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier)

Example 24 with StopWatch

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

the class DropFolderUserMessage method _send.

private static void _send(@Nonnull final IAS4CryptoFactory aCF, final Path aSendFile, final Path aIncomingDir) {
    final StopWatch aSW = StopWatch.createdStarted();
    boolean bSuccess = false;
    LOGGER.info("Trying to send " + aSendFile.toString());
    try (final AS4ResourceHelper aResHelper = new AS4ResourceHelper()) {
        // Read generic SBD
        final StandardBusinessDocument aSBD = SBDHReader.standardBusinessDocument().read(Files.newInputStream(aSendFile));
        if (aSBD == null) {
            LOGGER.error("Failed to read " + aSendFile.toString() + " as SBDH document!");
        } else {
            // Extract Peppol specific data
            final PeppolSBDHDocument aSBDH = new PeppolSBDHDocumentReader(IF).extractData(aSBD);
            final ISMPServiceMetadataProvider aSMPClient = new SMPClient(UP, aSBDH.getReceiverAsIdentifier(), ESML.DIGIT_TEST);
            final EndpointType aEndpoint = aSMPClient.getEndpoint(aSBDH.getReceiverAsIdentifier(), aSBDH.getDocumentTypeAsIdentifier(), aSBDH.getProcessAsIdentifier(), ESMPTransportProfile.TRANSPORT_PROFILE_BDXR_AS4);
            if (aEndpoint == null) {
                LOGGER.error("Found no endpoint for:\n  Receiver ID: " + aSBDH.getReceiverAsIdentifier().getURIEncoded() + "\n  Document type ID: " + aSBDH.getDocumentTypeAsIdentifier().getURIEncoded() + "\n  Process ID: " + aSBDH.getProcessAsIdentifier().getURIEncoded());
            } else {
                final KeyStore.PrivateKeyEntry aOurCert = aCF.getPrivateKeyEntry();
                final X509Certificate aTheirCert = CertificateHelper.convertStringToCertficate(aEndpoint.getCertificate());
                final AS4ClientUserMessage aClient = new AS4ClientUserMessage(aResHelper);
                aClient.setSoapVersion(ESoapVersion.SOAP_12);
                // Keystore data
                aClient.setAS4CryptoFactory(aCF);
                aClient.signingParams().setAlgorithmSign(ECryptoAlgorithmSign.RSA_SHA_512);
                aClient.signingParams().setAlgorithmSignDigest(ECryptoAlgorithmSignDigest.DIGEST_SHA_512);
                // FIXME Action, Service etc. are missing
                aClient.setAction("xxx");
                aClient.setServiceType("xxx");
                aClient.setServiceValue("xxx");
                aClient.setConversationID(MessageHelperMethods.createRandomConversationID());
                aClient.setAgreementRefValue("xxx");
                aClient.setFromRole(CAS4.DEFAULT_ROLE);
                aClient.setFromPartyID(PeppolCertificateHelper.getSubjectCN((X509Certificate) aOurCert.getCertificate()));
                aClient.setToRole(CAS4.DEFAULT_ROLE);
                aClient.setToPartyID(PeppolCertificateHelper.getSubjectCN(aTheirCert));
                aClient.ebms3Properties().setAll(MessageHelperMethods.createEbms3Property(CAS4.ORIGINAL_SENDER, aSBDH.getSenderScheme(), aSBDH.getSenderValue()), MessageHelperMethods.createEbms3Property(CAS4.FINAL_RECIPIENT, aSBDH.getReceiverScheme(), aSBDH.getReceiverValue()));
                aClient.setPayload(SBDHWriter.standardBusinessDocument().getAsDocument(aSBD));
                final IAS4ClientBuildMessageCallback aCallback = null;
                final IAS4OutgoingDumper aOutgoingDumper = null;
                final IAS4RetryCallback aRetryCallback = null;
                final AS4ClientSentMessage<byte[]> aResponseEntity = aClient.sendMessageWithRetries(W3CEndpointReferenceHelper.getAddress(aEndpoint.getEndpointReference()), new ResponseHandlerByteArray(), aCallback, aOutgoingDumper, aRetryCallback);
                LOGGER.info("Successfully transmitted document with message ID '" + aResponseEntity.getMessageID() + "' for '" + aSBDH.getReceiverAsIdentifier().getURIEncoded() + "' to '" + W3CEndpointReferenceHelper.getAddress(aEndpoint.getEndpointReference()) + "' in " + aSW.stopAndGetMillis() + " ms");
                if (aResponseEntity.hasResponse()) {
                    final String sMessageID = aResponseEntity.getMessageID();
                    final String sFilename = FilenameHelper.getAsSecureValidASCIIFilename(sMessageID) + "-response.xml";
                    final File aResponseFile = aIncomingDir.resolve(sFilename).toFile();
                    if (SimpleFileIO.writeFile(aResponseFile, aResponseEntity.getResponse()).isSuccess())
                        LOGGER.info("Response file was written to '" + aResponseFile.getAbsolutePath() + "'");
                    else
                        LOGGER.error("Error writing response file to '" + aResponseFile.getAbsolutePath() + "'");
                }
                bSuccess = true;
            }
        }
    } catch (final Exception ex) {
        LOGGER.error("Error sending " + aSendFile.toString(), ex);
    }
    // After the exception handler!
    {
        // Move to done or error directory?
        final Path aDest = aSendFile.resolveSibling(bSuccess ? PATH_DONE : PATH_ERROR).resolve(aSendFile.getFileName());
        try {
            Files.move(aSendFile, aDest);
        } catch (final IOException ex) {
            LOGGER.error("Error moving from '" + aSendFile.toString() + "' to '" + aDest + "'", ex);
        }
    }
}
Also used : Path(java.nio.file.Path) IAS4ClientBuildMessageCallback(com.helger.phase4.client.IAS4ClientBuildMessageCallback) IAS4OutgoingDumper(com.helger.phase4.dump.IAS4OutgoingDumper) PeppolSBDHDocument(com.helger.peppol.sbdh.PeppolSBDHDocument) ISMPServiceMetadataProvider(com.helger.smpclient.peppol.ISMPServiceMetadataProvider) StandardBusinessDocument(org.unece.cefact.namespaces.sbdh.StandardBusinessDocument) ResponseHandlerByteArray(com.helger.httpclient.response.ResponseHandlerByteArray) IAS4RetryCallback(com.helger.phase4.client.IAS4RetryCallback) PeppolSBDHDocumentReader(com.helger.peppol.sbdh.read.PeppolSBDHDocumentReader) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) StopWatch(com.helger.commons.timing.StopWatch) SMPClient(com.helger.smpclient.peppol.SMPClient) EndpointType(com.helger.xsds.peppol.smp1.EndpointType) AS4ClientUserMessage(com.helger.phase4.client.AS4ClientUserMessage) AS4ResourceHelper(com.helger.phase4.util.AS4ResourceHelper) File(java.io.File)

Example 25 with StopWatch

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

the class AbstractAS2ReceiveBaseXServletHandler method onRequest.

public final void onRequest(@Nonnull final HttpServletRequest aHttpRequest, @Nonnull final HttpServletResponse aHttpResponse, @Nonnull final EHttpVersion eHttpVersion, @Nonnull final EHttpMethod eHttpMethod, @Nonnull final IRequestWebScope aRequestScope) throws ServletException, IOException {
    // Handle the incoming message, and return the MDN if necessary
    final String sClientInfo = aHttpRequest.getRemoteAddr() + ":" + aHttpRequest.getRemotePort();
    LOGGER.info("Starting to handle incoming AS2 request - " + sClientInfo);
    // Create empty message
    final AS2Message aMsg = new AS2Message();
    aMsg.attrs().putIn(CNetAttribute.MA_SOURCE_IP, aHttpRequest.getRemoteAddr());
    aMsg.attrs().putIn(CNetAttribute.MA_SOURCE_PORT, aHttpRequest.getRemotePort());
    aMsg.attrs().putIn(CNetAttribute.MA_DESTINATION_IP, aHttpRequest.getLocalAddr());
    aMsg.attrs().putIn(CNetAttribute.MA_DESTINATION_PORT, aHttpRequest.getLocalPort());
    // Request type (e.g. "POST")
    aMsg.attrs().putIn(HTTPHelper.MA_HTTP_REQ_TYPE, aHttpRequest.getMethod());
    // Request URL (e.g. "/as2")
    aMsg.attrs().putIn(HTTPHelper.MA_HTTP_REQ_URL, ServletHelper.getRequestRequestURI(aHttpRequest));
    // Add all request headers to the AS2 message
    aMsg.headers().setAllHeaders(aRequestScope.headers());
    // Build the handler that performs the response handling
    final boolean bQuoteHeaderValues = isQuoteHeaderValues();
    final AS2OutputStreamCreatorHttpServletResponse aResponseHandler = new AS2OutputStreamCreatorHttpServletResponse(aHttpResponse, bQuoteHeaderValues);
    // Read the S/MIME content in a byte array - memory!
    // Chunked encoding was already handled, so read "as-is"
    final long nContentLength = aHttpRequest.getContentLengthLong();
    if (nContentLength > Integer.MAX_VALUE)
        throw new IllegalStateException("Currently only payload with up to 2GB can be handled! This request has " + nContentLength + " bytes.");
    // Open it once, and close it at the end
    try (final ServletInputStream aRequestIS = aHttpRequest.getInputStream()) {
        // 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 AS2HttpRequestDataProviderServletRequest(aRequestScope, aRequestIS), aResponseHandler, aMsg, aIncomingDumper);
        } catch (final Exception ex) {
            AS2Exception.log(ex.getClass(), true, "Failed to read Servlet Request: " + ex.getMessage(), null, null, ex.getCause());
        }
        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 : ServletException(javax.servlet.ServletException) AS2Exception(com.helger.as2lib.exception.AS2Exception) IOException(java.io.IOException) StopWatch(com.helger.commons.timing.StopWatch) ByteArrayDataSource(com.helger.mail.datasource.ByteArrayDataSource) DataSource(javax.activation.DataSource) IHTTPIncomingDumper(com.helger.as2lib.util.dump.IHTTPIncomingDumper) AS2OutputStreamCreatorHttpServletResponse(com.helger.as2servlet.util.AS2OutputStreamCreatorHttpServletResponse) AS2Message(com.helger.as2lib.message.AS2Message) ServletInputStream(javax.servlet.ServletInputStream) ByteArrayDataSource(com.helger.mail.datasource.ByteArrayDataSource)

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