Search in sources :

Example 1 with BDXRClientReadOnly

use of com.helger.smpclient.bdxr1.BDXRClientReadOnly in project phoss-directory by phax.

the class SMPBusinessCardProvider method getBusinessCard.

@Nullable
public PDExtendedBusinessCard getBusinessCard(@Nonnull final IParticipantIdentifier aParticipantID) {
    final HttpClientSettings aHCS = new HttpClientSettings().setProxyHost(_getHttpProxy()).setProxyCredentials(_getHttpProxyCredentials());
    PDExtendedBusinessCard aBC;
    if (m_aSMPURI != null) {
        // Use a preselected SMP URI
        switch(m_eSMPMode) {
            case PEPPOL:
                {
                    final SMPClientReadOnly aSMPClient = new SMPClientReadOnly(m_aSMPURI);
                    _configureSMPClient(aSMPClient);
                    aBC = getBusinessCardPeppolSMP(aParticipantID, aSMPClient, aHCS);
                    break;
                }
            case OASIS_BDXR_V1:
                {
                    final BDXRClientReadOnly aSMPClient = new BDXRClientReadOnly(m_aSMPURI);
                    _configureSMPClient(aSMPClient);
                    aBC = getBusinessCardBDXR1(aParticipantID, aSMPClient, aHCS);
                    break;
                }
            case OASIS_BDXR_V2:
                {
                    final BDXR2ClientReadOnly aSMPClient = new BDXR2ClientReadOnly(m_aSMPURI);
                    _configureSMPClient(aSMPClient);
                    aBC = getBusinessCardBDXR2(aParticipantID, aSMPClient, aHCS);
                    break;
                }
            default:
                throw new IllegalStateException("Unsupported SMP mode " + m_eSMPMode);
        }
    } else {
        // SML auto detect
        aBC = null;
        for (final ISMLInfo aSML : m_aSMLInfoProvider.get()) {
            // Create SMP client and query SMP
            switch(m_eSMPMode) {
                case PEPPOL:
                    {
                        try {
                            final SMPClientReadOnly aSMPClient = new SMPClientReadOnly(m_aURLProvider, aParticipantID, aSML);
                            _configureSMPClient(aSMPClient);
                            aBC = getBusinessCardPeppolSMP(aParticipantID, aSMPClient, aHCS);
                        } catch (final SMPDNSResolutionException ex) {
                        // Happens if a non-existing URL is queried
                        }
                        break;
                    }
                case OASIS_BDXR_V1:
                    {
                        try {
                            final BDXRClientReadOnly aSMPClient = new BDXRClientReadOnly(m_aURLProvider, aParticipantID, aSML);
                            _configureSMPClient(aSMPClient);
                            aBC = getBusinessCardBDXR1(aParticipantID, aSMPClient, aHCS);
                        } catch (final SMPDNSResolutionException ex) {
                        // Happens if a non-existing URL is queried
                        }
                        break;
                    }
                case OASIS_BDXR_V2:
                    {
                        try {
                            final BDXR2ClientReadOnly aSMPClient = new BDXR2ClientReadOnly(m_aURLProvider, aParticipantID, aSML);
                            _configureSMPClient(aSMPClient);
                            aBC = getBusinessCardBDXR2(aParticipantID, aSMPClient, aHCS);
                        } catch (final SMPDNSResolutionException ex) {
                        // Happens if a non-existing URL is queried
                        }
                        break;
                    }
                default:
                    throw new IllegalStateException("Unsupported SMP mode " + m_eSMPMode);
            }
            // Found one?
            if (aBC != null)
                break;
        }
    }
    if (aBC != null)
        LOGGER.info("Found BusinessCard for '" + aParticipantID.getURIEncoded() + "' with " + aBC.getBusinessCard().businessEntities().size() + " entities and " + aBC.getDocumentTypeCount() + " document types");
    return aBC;
}
Also used : BDXR2ClientReadOnly(com.helger.smpclient.bdxr2.BDXR2ClientReadOnly) SMPClientReadOnly(com.helger.smpclient.peppol.SMPClientReadOnly) ISMLInfo(com.helger.peppol.sml.ISMLInfo) HttpClientSettings(com.helger.httpclient.HttpClientSettings) SMPDNSResolutionException(com.helger.smpclient.url.SMPDNSResolutionException) BDXRClientReadOnly(com.helger.smpclient.bdxr1.BDXRClientReadOnly) Nullable(javax.annotation.Nullable)

Example 2 with BDXRClientReadOnly

use of com.helger.smpclient.bdxr1.BDXRClientReadOnly 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);
    }
}
Also used : SMPClientReadOnly(com.helger.smpclient.peppol.SMPClientReadOnly) IDocumentTypeIdentifier(com.helger.peppolid.IDocumentTypeIdentifier) BDXRClientReadOnly(com.helger.smpclient.bdxr1.BDXRClientReadOnly) JsonWriter(com.helger.json.serialize.JsonWriter) ESMPAPIType(com.helger.peppol.sml.ESMPAPIType) StopWatch(com.helger.commons.timing.StopWatch) SMPPreconditionFailedException(com.helger.phoss.smp.exception.SMPPreconditionFailedException) 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 3 with BDXRClientReadOnly

use of com.helger.smpclient.bdxr1.BDXRClientReadOnly in project phase4 by phax.

the class MainPhase4CEFSenderToop method main.

public static void main(final String[] args) {
    WebScopeManager.onGlobalBegin(MockServletContext.create());
    // Dump (for debugging purpose only)
    AS4DumpManager.setIncomingDumper(new AS4IncomingDumperFileBased());
    AS4DumpManager.setOutgoingDumper(new AS4OutgoingDumperFileBased());
    try (final WebScoped w = new WebScoped()) {
        final byte[] aPayloadBytes = SimpleFileIO.getAllFileBytes(new File("src/test/resources/examples/base-example.xml"));
        if (aPayloadBytes == null)
            throw new IllegalStateException();
        // Start configuring here
        final IParticipantIdentifier aReceiverID = Phase4CEFSender.IF.createParticipantIdentifier("iso6523-actorid-upis", "9915:tooptest");
        final IAS4ClientBuildMessageCallback aBuildMessageCallback = new IAS4ClientBuildMessageCallback() {

            public void onAS4Message(final AbstractAS4Message<?> aMsg) {
                final AS4UserMessage aUserMsg = (AS4UserMessage) aMsg;
                LOGGER.info("Sending out AS4 message with message ID '" + aUserMsg.getEbms3UserMessage().getMessageInfo().getMessageId() + "'");
                LOGGER.info("Sending out AS4 message with conversation ID '" + aUserMsg.getEbms3UserMessage().getCollaborationInfo().getConversationId() + "'");
            }
        };
        if (Phase4CEFSender.builder().documentTypeID(Phase4CEFSender.IF.createDocumentTypeIdentifier("toop-doctypeid-qns", "urn:eu:toop:ns:dataexchange-1p40::Response##urn:eu.toop.response.registeredorganization::1.40")).processID(Phase4CEFSender.IF.createProcessIdentifier("toop-procid-agreement", "urn:eu.toop.process.datarequestresponse")).senderParticipantID(Phase4CEFSender.IF.createParticipantIdentifier("iso6523-actorid-upis", "9914:phase4-test-sender")).receiverParticipantID(aReceiverID).fromPartyID(new SimpleParticipantIdentifier("type", "POP000306")).fromRole("http://www.toop.eu/edelivery/gateway").toPartyID(new SimpleParticipantIdentifier("type", "POP000306")).toRole("http://www.toop.eu/edelivery/gateway").payload(Phase4OutgoingAttachment.builder().data(aPayloadBytes).mimeTypeXML()).smpClient(new BDXRClientReadOnly(Phase4CEFSender.URL_PROVIDER, aReceiverID, SML_TOOP)).rawResponseConsumer(new AS4RawResponseConsumerWriteToFile()).buildMessageCallback(aBuildMessageCallback).sendMessage().isSuccess()) {
            LOGGER.info("Successfully sent CEF message via AS4");
        } else {
            LOGGER.error("Failed to send CEF message via AS4");
        }
    } catch (final Exception ex) {
        LOGGER.error("Error sending CEF message via AS4", ex);
    } finally {
        WebScopeManager.onGlobalEnd();
    }
}
Also used : WebScoped(com.helger.web.scope.mgr.WebScoped) IAS4ClientBuildMessageCallback(com.helger.phase4.client.IAS4ClientBuildMessageCallback) AS4UserMessage(com.helger.phase4.messaging.domain.AS4UserMessage) BDXRClientReadOnly(com.helger.smpclient.bdxr1.BDXRClientReadOnly) SimpleParticipantIdentifier(com.helger.peppolid.simple.participant.SimpleParticipantIdentifier) AbstractAS4Message(com.helger.phase4.messaging.domain.AbstractAS4Message) AS4IncomingDumperFileBased(com.helger.phase4.dump.AS4IncomingDumperFileBased) AS4RawResponseConsumerWriteToFile(com.helger.phase4.dump.AS4RawResponseConsumerWriteToFile) AS4RawResponseConsumerWriteToFile(com.helger.phase4.dump.AS4RawResponseConsumerWriteToFile) File(java.io.File) AS4OutgoingDumperFileBased(com.helger.phase4.dump.AS4OutgoingDumperFileBased) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier)

Example 4 with BDXRClientReadOnly

use of com.helger.smpclient.bdxr1.BDXRClientReadOnly 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)

Aggregations

BDXRClientReadOnly (com.helger.smpclient.bdxr1.BDXRClientReadOnly)4 IParticipantIdentifier (com.helger.peppolid.IParticipantIdentifier)3 SMPClientReadOnly (com.helger.smpclient.peppol.SMPClientReadOnly)3 StopWatch (com.helger.commons.timing.StopWatch)2 IJsonObject (com.helger.json.IJsonObject)2 JsonWriter (com.helger.json.serialize.JsonWriter)2 ESMPAPIType (com.helger.peppol.sml.ESMPAPIType)2 IIdentifierFactory (com.helger.peppolid.factory.IIdentifierFactory)2 SMPPreconditionFailedException (com.helger.phoss.smp.exception.SMPPreconditionFailedException)2 ISMPServerAPIDataProvider (com.helger.phoss.smp.restapi.ISMPServerAPIDataProvider)2 ZonedDateTime (java.time.ZonedDateTime)2 CommonsTreeMap (com.helger.commons.collection.impl.CommonsTreeMap)1 HttpClientManager (com.helger.httpclient.HttpClientManager)1 HttpClientSettings (com.helger.httpclient.HttpClientSettings)1 ResponseHandlerByteArray (com.helger.httpclient.response.ResponseHandlerByteArray)1 JsonObject (com.helger.json.JsonObject)1 PDBusinessCard (com.helger.pd.businesscard.generic.PDBusinessCard)1 ISMLInfo (com.helger.peppol.sml.ISMLInfo)1 IDocumentTypeIdentifier (com.helger.peppolid.IDocumentTypeIdentifier)1 SimpleParticipantIdentifier (com.helger.peppolid.simple.participant.SimpleParticipantIdentifier)1