Search in sources :

Example 86 with IDocumentTypeIdentifier

use of com.helger.peppolid.IDocumentTypeIdentifier in project peppol-practical by phax.

the class PageSecurePeppolSendAS4 method fillContent.

@Override
protected void fillContent(@Nonnull final WebPageExecutionContext aWPEC) {
    final HCNodeList aNodeList = aWPEC.getNodeList();
    final IIdentifierFactory aIF = Phase4PeppolSender.IF;
    final FormErrorList aFormErrors = new FormErrorList();
    if (aWPEC.params().hasStringValue(CPageParam.PARAM_ACTION, CPageParam.ACTION_PERFORM)) {
        final String sSenderID = aWPEC.params().getAsStringTrimmed(FIELD_SENDER_ID);
        final IParticipantIdentifier aSenderID = aIF.parseParticipantIdentifier(sSenderID);
        final String sReceiverID = aWPEC.params().getAsStringTrimmed(FIELD_RECEIVER_ID);
        final IParticipantIdentifier aReceiverID = aIF.parseParticipantIdentifier(sReceiverID);
        final String sDocTypeID = aWPEC.params().getAsStringTrimmed(FIELD_DOCTYPE_ID);
        final IDocumentTypeIdentifier aDocTypeID = aIF.parseDocumentTypeIdentifier(sDocTypeID);
        final String sProcessID = aWPEC.params().getAsStringTrimmed(FIELD_PROCESS_ID);
        final IProcessIdentifier aProcessID = aIF.parseProcessIdentifier(sProcessID);
        final String sPayload = aWPEC.params().getAsStringTrimmed(FIELD_PAYLOAD);
        final Document aPayloadDoc = DOMReader.readXMLDOM(sPayload);
        if (StringHelper.hasNoText(sSenderID))
            aFormErrors.addFieldError(FIELD_SENDER_ID, "A sending participant ID must be provided.");
        else if (aSenderID == null)
            aFormErrors.addFieldError(FIELD_SENDER_ID, "The sending participant ID could not be parsed.");
        if (StringHelper.hasNoText(sReceiverID))
            aFormErrors.addFieldError(FIELD_RECEIVER_ID, "A receiving participant ID must be provided.");
        else if (aReceiverID == null)
            aFormErrors.addFieldError(FIELD_RECEIVER_ID, "The receiving participant ID could not be parsed.");
        if (StringHelper.hasNoText(sDocTypeID))
            aFormErrors.addFieldError(FIELD_DOCTYPE_ID, "A document type ID must be provided.");
        else if (aDocTypeID == null)
            aFormErrors.addFieldError(FIELD_DOCTYPE_ID, "The document type ID could not be parsed.");
        if (StringHelper.hasNoText(sProcessID))
            aFormErrors.addFieldError(FIELD_PROCESS_ID, "A process ID must be provided.");
        else if (aProcessID == null)
            aFormErrors.addFieldError(FIELD_PROCESS_ID, "The process ID could not be parsed.");
        if (StringHelper.hasNoText(sPayload))
            aFormErrors.addFieldError(FIELD_PAYLOAD, "A payload must be provided.");
        else if (aPayloadDoc == null)
            aFormErrors.addFieldError(FIELD_PAYLOAD, "The payload is not wellformed XML.");
        if (aFormErrors.isEmpty()) {
            final HCDiv aNL = new HCDiv().addStyle(CCSSProperties.MAX_WIDTH.newValue("80vw"));
            final String sAS4PayloadDoc = XMLWriter.getNodeAsString(aPayloadDoc);
            final byte[] aAS4PayloadBytes = XMLWriter.getNodeAsBytes(aPayloadDoc);
            aNL.addChild(h3("Sending document"));
            // Show payload
            aNL.addChild(new BootstrapPrismJS(EPrismLanguage.MARKUP).addPlugin(new PrismPluginLineNumbers()).addChild(sAS4PayloadDoc));
            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() + "'");
                }
            };
            try {
                final SMPClientReadOnly aSMPClient = new SMPClientReadOnly(Phase4PeppolSender.URL_PROVIDER, aReceiverID, ESML.DIGIT_TEST);
                // What to remember
                final Wrapper<String> aEndpointURL = new Wrapper<>();
                final Wrapper<X509Certificate> aEndpointCert = new Wrapper<>();
                final Wrapper<EPeppolCertificateCheckResult> aEndpointCertCheck = new Wrapper<>();
                final Wrapper<Phase4Exception> aSendEx = new Wrapper<>();
                final Wrapper<byte[]> aResponseBytes = new Wrapper<>();
                final Wrapper<Ebms3SignalMessage> aResponseMsg = new Wrapper<>();
                LOGGER.info("Sending Peppol AS4 message from '" + aSenderID.getURIEncoded() + "' to '" + aReceiverID.getURIEncoded() + "' using document type '" + aDocTypeID.getURIEncoded() + "' and process ID '" + aProcessID.getURIEncoded() + "'");
                // Try to send message
                final ESimpleUserMessageSendResult eResult = Phase4PeppolSender.builder().cryptoFactory(AS4_CF).documentTypeID(aDocTypeID).processID(aProcessID).senderParticipantID(aSenderID).receiverParticipantID(aReceiverID).senderPartyID("POP000306").payload(aAS4PayloadBytes).smpClient(aSMPClient).endpointURLConsumer(aEndpointURL::set).certificateConsumer((cert, dt, res) -> {
                    aEndpointCert.set(cert);
                    aEndpointCertCheck.set(res);
                }).validationConfiguration(null).buildMessageCallback(aBuildMessageCallback).outgoingDumper(new AS4OutgoingDumperFileBased()).incomingDumper(new AS4IncomingDumperFileBased()).rawResponseConsumer(r -> aResponseBytes.set(r.getResponse())).signalMsgConsumer(aResponseMsg::set).sendMessageAndCheckForReceipt(aSendEx::set);
                LOGGER.info("Sending Peppol AS4 message resulted in " + eResult);
                if (aEndpointURL.isSet())
                    aNL.addChild(div("Sending to this endpoint URL: ").addChild(code(aEndpointURL.get())));
                if (aEndpointCert.isSet())
                    aNL.addChild(div("The message is encrypted for the following receiver: ").addChild(code(aEndpointCert.get().getSubjectX500Principal().getName())));
                if (aEndpointCertCheck.isSet())
                    aNL.addChild(div("The certificate verification resulted in: ").addChild(code(aEndpointCertCheck.get().name())));
                if (eResult.isSuccess())
                    aNL.addChild(success("Successfully send AS4 message to Peppol receiver ").addChild(code(aReceiverID.getURIEncoded())));
                else
                    aNL.addChild(error().addChild(div("Failed to send AS4 message to Peppol receiver ").addChild(code(aReceiverID.getURIEncoded())).addChild(" with result ").addChild(code(eResult.name()))).addChild(AppCommonUI.getTechnicalDetailsUI(aSendEx.get(), true)));
                boolean bShowRaw = true;
                if (aResponseMsg.isSet()) {
                    // Don't do XSD validation here because there is no defined
                    // "SignalMessage" element
                    final String sSignalMessage = new GenericJAXBMarshaller<>(Ebms3SignalMessage.class, GenericJAXBMarshaller.createSimpleJAXBElement(new QName(com.helger.phase4.ebms3header.ObjectFactory._Messaging_QNAME.getNamespaceURI(), "SignalMessage"), Ebms3SignalMessage.class)).setFormattedOutput(true).getAsString(aResponseMsg.get());
                    if (StringHelper.hasText(sSignalMessage)) {
                        // Show payload
                        aNL.addChild(div("Response ebMS Signal Message"));
                        aNL.addChild(new BootstrapPrismJS(EPrismLanguage.MARKUP).addPlugin(new PrismPluginLineNumbers()).addChild(sSignalMessage));
                        bShowRaw = false;
                    }
                }
                if (aResponseBytes.isSet()) {
                    if (bShowRaw) {
                        aNL.addChild(div("Response message - NOT a valid response"));
                        aNL.addChild(new BootstrapPrismJS(EPrismLanguage.MARKUP).addPlugin(new PrismPluginLineNumbers()).addChild(new String(aResponseBytes.get(), StandardCharsets.UTF_8)));
                    }
                // Else already shown above
                } else {
                    if (eResult.isSuccess())
                        aNL.addChild(error("Received no response content :("));
                }
            } catch (final SMPDNSResolutionException ex) {
                aNL.addChild(error(div("Error creating the SMP client.")).addChild(AppCommonUI.getTechnicalDetailsUI(ex, false)));
            }
            if (true)
                aNodeList.addChild(aNL);
            else
                aWPEC.postRedirectGetInternal(aNL);
        }
    }
    aNodeList.addChild(h3("Send new Peppol AS4 message (Test network only)"));
    final BootstrapForm aForm = aNodeList.addAndReturnChild(new BootstrapForm(aWPEC));
    aForm.addFormGroup(new BootstrapFormGroup().setLabelMandatory("Sending participant ID").setCtrl(new HCEdit(new RequestField(FIELD_SENDER_ID, DEFAULT_SENDER_ID))).setHelpText(span("The sending Peppol participant identifier. Must include the ").addChild(code(PeppolIdentifierHelper.DEFAULT_PARTICIPANT_SCHEME)).addChild(" prefix.")).setErrorList(aFormErrors.getListOfField(FIELD_SENDER_ID)));
    aForm.addFormGroup(new BootstrapFormGroup().setLabelMandatory("Receiving participant ID").setCtrl(new HCEdit(new RequestField(FIELD_RECEIVER_ID, DEFAULT_RECEIVER_ID))).setHelpText(span("The receiving Peppol participant identifier. Must include the ").addChild(code(PeppolIdentifierHelper.DEFAULT_PARTICIPANT_SCHEME)).addChild(" prefix.")).setErrorList(aFormErrors.getListOfField(FIELD_RECEIVER_ID)));
    aForm.addFormGroup(new BootstrapFormGroup().setLabelMandatory("Document type ID").setCtrl(new HCEdit(new RequestField(FIELD_DOCTYPE_ID, DEFAULT_DOCTYPE_ID))).setHelpText(span("The Peppol document type identifier. Must include the ").addChild(code(PeppolIdentifierHelper.DOCUMENT_TYPE_SCHEME_BUSDOX_DOCID_QNS)).addChild(" prefix.")).setErrorList(aFormErrors.getListOfField(FIELD_DOCTYPE_ID)));
    aForm.addFormGroup(new BootstrapFormGroup().setLabelMandatory("Process ID").setCtrl(new HCEdit(new RequestField(FIELD_PROCESS_ID, DEFAULT_PROCESS_ID))).setHelpText(span("The Peppol process identifier. Must include the ").addChild(code(PeppolIdentifierHelper.DEFAULT_PROCESS_SCHEME)).addChild(" prefix.")).setErrorList(aFormErrors.getListOfField(FIELD_PROCESS_ID)));
    aForm.addFormGroup(new BootstrapFormGroup().setLabelMandatory("XML Payload to be send").setCtrl(new HCTextArea(new RequestField(FIELD_PAYLOAD, DEFAULT_PAYLOAD.get())).setRows(8)).setHelpText("This MUST be wellformed XML - e.g. a UBL Invoice or a CII Invoice. NO Schematron validation is performed. The SBDH is added automatically.").setErrorList(aFormErrors.getListOfField(FIELD_PAYLOAD)));
    aForm.addChild(new HCHiddenField(CPageParam.PARAM_ACTION, CPageParam.ACTION_PERFORM));
    aForm.addChild(new BootstrapSubmitButton().addChild("Send Peppol AS4 message"));
}
Also used : HCDiv(com.helger.html.hc.html.grouping.HCDiv) Ebms3SignalMessage(com.helger.phase4.ebms3header.Ebms3SignalMessage) X509Certificate(java.security.cert.X509Certificate) AppConfig(com.helger.peppol.app.AppConfig) WebPageExecutionContext(com.helger.photon.uicore.page.WebPageExecutionContext) PeppolIdentifierHelper(com.helger.peppolid.peppol.PeppolIdentifierHelper) IDocumentTypeIdentifier(com.helger.peppolid.IDocumentTypeIdentifier) BootstrapSubmitButton(com.helger.photon.bootstrap4.button.BootstrapSubmitButton) LoggerFactory(org.slf4j.LoggerFactory) HCHiddenField(com.helger.html.hc.html.forms.HCHiddenField) CCSSProperties(com.helger.css.property.CCSSProperties) IKeyStoreType(com.helger.security.keystore.IKeyStoreType) FormErrorList(com.helger.photon.core.form.FormErrorList) BootstrapForm(com.helger.photon.bootstrap4.form.BootstrapForm) Phase4PeppolSender(com.helger.phase4.peppol.Phase4PeppolSender) IIdentifierFactory(com.helger.peppolid.factory.IIdentifierFactory) PrivateKeyEntry(java.security.KeyStore.PrivateKeyEntry) Document(org.w3c.dom.Document) HCTextArea(com.helger.html.hc.html.forms.HCTextArea) CPageParam(com.helger.photon.uicore.css.CPageParam) ESML(com.helger.peppol.sml.ESML) HCDiv(com.helger.html.hc.html.grouping.HCDiv) EPeppolCertificateCheckResult(com.helger.peppol.utils.EPeppolCertificateCheckResult) KeyStoreHelper(com.helger.security.keystore.KeyStoreHelper) LoadedKeyStore(com.helger.security.keystore.LoadedKeyStore) AS4OutgoingDumperFileBased(com.helger.phase4.dump.AS4OutgoingDumperFileBased) StandardCharsets(java.nio.charset.StandardCharsets) EPredefinedProcessIdentifier(com.helger.peppolid.peppol.process.EPredefinedProcessIdentifier) DOMReader(com.helger.xml.serialize.read.DOMReader) EKeyStoreType(com.helger.security.keystore.EKeyStoreType) AbstractAS4Message(com.helger.phase4.messaging.domain.AbstractAS4Message) IValidityIndicator(com.helger.commons.state.IValidityIndicator) QName(javax.xml.namespace.QName) AppCommonUI(com.helger.peppol.ui.AppCommonUI) PrismPluginLineNumbers(com.helger.photon.uictrls.prism.PrismPluginLineNumbers) Ebms3SignalMessage(com.helger.phase4.ebms3header.Ebms3SignalMessage) EPredefinedDocumentTypeIdentifier(com.helger.peppolid.peppol.doctype.EPredefinedDocumentTypeIdentifier) SMPClientReadOnly(com.helger.smpclient.peppol.SMPClientReadOnly) EValidity(com.helger.commons.state.EValidity) IAS4CryptoFactory(com.helger.phase4.crypto.IAS4CryptoFactory) SMPDNSResolutionException(com.helger.smpclient.url.SMPDNSResolutionException) HCEdit(com.helger.html.hc.html.forms.HCEdit) Supplier(java.util.function.Supplier) IProcessIdentifier(com.helger.peppolid.IProcessIdentifier) IConfig(com.helger.config.IConfig) LoadedKey(com.helger.security.keystore.LoadedKey) AS4CryptoFactoryInMemoryKeyStore(com.helger.phase4.crypto.AS4CryptoFactoryInMemoryKeyStore) ESimpleUserMessageSendResult(com.helger.phase4.sender.AbstractAS4UserMessageBuilder.ESimpleUserMessageSendResult) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier) Nonnull(javax.annotation.Nonnull) Phase4Exception(com.helger.phase4.util.Phase4Exception) HCNodeList(com.helger.html.hc.impl.HCNodeList) AS4IncomingDumperFileBased(com.helger.phase4.dump.AS4IncomingDumperFileBased) AbstractBootstrapWebPage(com.helger.photon.bootstrap4.pages.AbstractBootstrapWebPage) BootstrapFormGroup(com.helger.photon.bootstrap4.form.BootstrapFormGroup) Logger(org.slf4j.Logger) StringHelper(com.helger.commons.string.StringHelper) BootstrapPrismJS(com.helger.photon.bootstrap4.uictrls.prism.BootstrapPrismJS) XMLWriter(com.helger.xml.serialize.write.XMLWriter) RequestField(com.helger.photon.core.form.RequestField) IAS4ClientBuildMessageCallback(com.helger.phase4.client.IAS4ClientBuildMessageCallback) Wrapper(com.helger.commons.wrapper.Wrapper) AS4UserMessage(com.helger.phase4.messaging.domain.AS4UserMessage) EPrismLanguage(com.helger.photon.uictrls.prism.EPrismLanguage) GenericJAXBMarshaller(com.helger.jaxb.GenericJAXBMarshaller) PrismPluginLineNumbers(com.helger.photon.uictrls.prism.PrismPluginLineNumbers) IAS4ClientBuildMessageCallback(com.helger.phase4.client.IAS4ClientBuildMessageCallback) SMPClientReadOnly(com.helger.smpclient.peppol.SMPClientReadOnly) HCNodeList(com.helger.html.hc.impl.HCNodeList) FormErrorList(com.helger.photon.core.form.FormErrorList) BootstrapPrismJS(com.helger.photon.bootstrap4.uictrls.prism.BootstrapPrismJS) HCEdit(com.helger.html.hc.html.forms.HCEdit) IDocumentTypeIdentifier(com.helger.peppolid.IDocumentTypeIdentifier) Document(org.w3c.dom.Document) GenericJAXBMarshaller(com.helger.jaxb.GenericJAXBMarshaller) IProcessIdentifier(com.helger.peppolid.IProcessIdentifier) AbstractAS4Message(com.helger.phase4.messaging.domain.AbstractAS4Message) Phase4Exception(com.helger.phase4.util.Phase4Exception) AS4IncomingDumperFileBased(com.helger.phase4.dump.AS4IncomingDumperFileBased) IIdentifierFactory(com.helger.peppolid.factory.IIdentifierFactory) AS4OutgoingDumperFileBased(com.helger.phase4.dump.AS4OutgoingDumperFileBased) RequestField(com.helger.photon.core.form.RequestField) Wrapper(com.helger.commons.wrapper.Wrapper) EPeppolCertificateCheckResult(com.helger.peppol.utils.EPeppolCertificateCheckResult) HCTextArea(com.helger.html.hc.html.forms.HCTextArea) HCHiddenField(com.helger.html.hc.html.forms.HCHiddenField) QName(javax.xml.namespace.QName) AS4UserMessage(com.helger.phase4.messaging.domain.AS4UserMessage) X509Certificate(java.security.cert.X509Certificate) BootstrapForm(com.helger.photon.bootstrap4.form.BootstrapForm) ESimpleUserMessageSendResult(com.helger.phase4.sender.AbstractAS4UserMessageBuilder.ESimpleUserMessageSendResult) BootstrapSubmitButton(com.helger.photon.bootstrap4.button.BootstrapSubmitButton) SMPDNSResolutionException(com.helger.smpclient.url.SMPDNSResolutionException) BootstrapFormGroup(com.helger.photon.bootstrap4.form.BootstrapFormGroup) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier)

Example 87 with IDocumentTypeIdentifier

use of com.helger.peppolid.IDocumentTypeIdentifier in project peppol-practical by phax.

the class APISMPQueryGetServiceInformation method rateLimitedInvokeAPI.

@Override
protected void rateLimitedInvokeAPI(@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 ISMLConfigurationManager aSMLConfigurationMgr = PPMetaManager.getSMLConfigurationMgr();
    final String sSMLID = aPathVariables.get(PPAPI.PARAM_SML_ID);
    final boolean bSMLAutoDetect = ISMLConfigurationManager.ID_AUTO_DETECT.equals(sSMLID);
    ISMLConfiguration aSML = aSMLConfigurationMgr.getSMLInfoOfID(sSMLID);
    if (aSML == null && !bSMLAutoDetect)
        throw new APIParamException("Unsupported SML ID '" + sSMLID + "' provided.");
    final String sParticipantID = aPathVariables.get(PPAPI.PARAM_PARTICIPANT_ID);
    final IParticipantIdentifier aPID = SimpleIdentifierFactory.INSTANCE.parseParticipantIdentifier(sParticipantID);
    if (aPID == null)
        throw new APIParamException("Invalid participant ID '" + sParticipantID + "' provided.");
    final String sDocTypeID = aPathVariables.get(PPAPI.PARAM_DOCTYPE_ID);
    final IDocumentTypeIdentifier aDTID = SimpleIdentifierFactory.INSTANCE.parseDocumentTypeIdentifier(sDocTypeID);
    if (aDTID == null)
        throw new APIParamException("Invalid document type ID '" + sDocTypeID + "' provided.");
    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();
    SMPQueryParams aQueryParams = null;
    if (bSMLAutoDetect) {
        for (final ISMLConfiguration aCurSML : aSMLConfigurationMgr.getAllSorted()) {
            aQueryParams = SMPQueryParams.createForSML(aCurSML, aPID.getScheme(), aPID.getValue(), false);
            if (aQueryParams == null)
                continue;
            try {
                InetAddress.getByName(aQueryParams.getSMPHostURI().getHost());
                // Found it
                aSML = aCurSML;
                break;
            } catch (final UnknownHostException ex) {
            // continue
            }
        }
        // Ensure to go into the exception handler
        if (aSML == null)
            throw new HttpResponseException(CHttp.HTTP_NOT_FOUND, "The participant identifier '" + sParticipantID + "' could not be found in any SML.");
    } else {
        aQueryParams = SMPQueryParams.createForSML(aSML, aPID.getScheme(), aPID.getValue(), true);
    }
    if (aQueryParams == null)
        throw new APIParamException("Failed to resolve participant ID '" + sParticipantID + "' for the provided SML '" + aSML.getID() + "'");
    final IParticipantIdentifier aParticipantID = aQueryParams.getParticipantID();
    final IDocumentTypeIdentifier aDocTypeID = aQueryParams.getIF().createDocumentTypeIdentifier(aDTID.getScheme(), aDTID.getValue());
    if (aDocTypeID == null)
        throw new APIParamException("Invalid document type ID '" + sDocTypeID + "' provided.");
    LOGGER.info("[API] Participant information of '" + aParticipantID.getURIEncoded() + "' is queried using SMP API '" + aQueryParams.getSMPAPIType() + "' from '" + aQueryParams.getSMPHostURI() + "' using SML '" + aSML.getID() + "' for document type '" + aDocTypeID.getURIEncoded() + "'; XSD validation=" + bXMLSchemaValidation + "; signature verification=" + bVerifySignature);
    IJsonObject aJson = null;
    switch(aQueryParams.getSMPAPIType()) {
        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("[API] Failed to perform the SMP lookup");
        aUnifiedResponse.setStatus(CHttp.HTTP_NOT_FOUND);
    } else {
        LOGGER.info("[API] 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(3 * CGlobal.SECONDS_PER_HOUR);
    }
}
Also used : SMPClientReadOnly(com.helger.smpclient.peppol.SMPClientReadOnly) UnknownHostException(java.net.UnknownHostException) ISMLConfiguration(com.helger.peppol.domain.ISMLConfiguration) IDocumentTypeIdentifier(com.helger.peppolid.IDocumentTypeIdentifier) HttpResponseException(org.apache.http.client.HttpResponseException) BDXRClientReadOnly(com.helger.smpclient.bdxr1.BDXRClientReadOnly) JsonWriter(com.helger.json.serialize.JsonWriter) StopWatch(com.helger.commons.timing.StopWatch) SMPQueryParams(com.helger.peppol.domain.SMPQueryParams) ISMLConfigurationManager(com.helger.peppol.app.mgr.ISMLConfigurationManager) ZonedDateTime(java.time.ZonedDateTime) IJsonObject(com.helger.json.IJsonObject) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier)

Example 88 with IDocumentTypeIdentifier

use of com.helger.peppolid.IDocumentTypeIdentifier in project phoss-directory by phax.

the class ExportAllManager method queryAllContainedBusinessCardsAsCSV.

public static void queryAllContainedBusinessCardsAsCSV(@Nonnull final EQueryMode eQueryMode, @Nonnull @WillNotClose final CSVWriter aCSVWriter) throws IOException {
    _unify(aCSVWriter);
    final Query aQuery = eQueryMode.getEffectiveQuery(new MatchAllDocsQuery());
    aCSVWriter.writeNext("Participant ID", "Names (per-row)", "Country code", "Geo info", "Identifier schemes", "Identifier values", "Websites", "Contact type", "Contact name", "Contact phone", "Contact email", "Additional info", "Registration date", "Document types");
    final Consumer<? super PDStoredBusinessEntity> aConsumer = aEntity -> {
        aCSVWriter.writeNext(aEntity.getParticipantID().getURIEncoded(), StringHelper.getImplodedMapped("\n", aEntity.names(), PDStoredMLName::getNameAndLanguageCode), aEntity.getCountryCode(), aEntity.getGeoInfo(), StringHelper.getImplodedMapped("\n", aEntity.identifiers(), PDStoredIdentifier::getScheme), StringHelper.getImplodedMapped("\n", aEntity.identifiers(), PDStoredIdentifier::getValue), StringHelper.getImploded("\n", aEntity.websiteURIs()), StringHelper.getImplodedMapped("\n", aEntity.contacts(), PDStoredContact::getType), StringHelper.getImplodedMapped("\n", aEntity.contacts(), PDStoredContact::getName), StringHelper.getImplodedMapped("\n", aEntity.contacts(), PDStoredContact::getPhone), StringHelper.getImplodedMapped("\n", aEntity.contacts(), PDStoredContact::getEmail), aEntity.getAdditionalInformation(), aEntity.getRegistrationDate() == null ? "" : aEntity.getRegistrationDate().toString(), StringHelper.getImplodedMapped("\n", aEntity.documentTypeIDs(), IDocumentTypeIdentifier::getURIEncoded));
    };
    PDMetaManager.getStorageMgr().searchAllDocuments(aQuery, -1, aConsumer);
    aCSVWriter.flush();
}
Also used : Query(org.apache.lucene.search.Query) EExcelVersion(com.helger.poi.excel.EExcelVersion) CommonsTreeSet(com.helger.commons.collection.impl.CommonsTreeSet) IDocumentTypeIdentifier(com.helger.peppolid.IDocumentTypeIdentifier) PDMetaManager(com.helger.pd.indexer.mgr.PDMetaManager) LoggerFactory(org.slf4j.LoggerFactory) IMicroDocument(com.helger.xml.microdom.IMicroDocument) PDTFactory(com.helger.commons.datetime.PDTFactory) IMicroElement(com.helger.xml.microdom.IMicroElement) PDStoredBusinessEntity(com.helger.pd.indexer.storage.PDStoredBusinessEntity) PDField(com.helger.pd.indexer.storage.field.PDField) ThreadSafe(javax.annotation.concurrent.ThreadSafe) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) ICommonsOrderedMap(com.helger.commons.collection.impl.ICommonsOrderedMap) StandardCharsets(java.nio.charset.StandardCharsets) JsonObject(com.helger.json.JsonObject) WorkbookCreationHelper(com.helger.poi.excel.WorkbookCreationHelper) ICommonsList(com.helger.commons.collection.impl.ICommonsList) IJsonArray(com.helger.json.IJsonArray) UnifiedResponse(com.helger.servlet.response.UnifiedResponse) CSVWriter(com.helger.commons.csv.CSVWriter) PDStoredContact(com.helger.pd.indexer.storage.PDStoredContact) Writer(java.io.Writer) WebFileIO(com.helger.photon.app.io.WebFileIO) ESuccess(com.helger.commons.state.ESuccess) FileSystemResource(com.helger.commons.io.resource.FileSystemResource) IJsonObject(com.helger.json.IJsonObject) MicroDocument(com.helger.xml.microdom.MicroDocument) CHttpHeader(com.helger.commons.http.CHttpHeader) JsonArray(com.helger.json.JsonArray) FileHelper(com.helger.commons.io.file.FileHelper) PDStoredIdentifier(com.helger.pd.indexer.storage.PDStoredIdentifier) ICommonsSortedSet(com.helger.commons.collection.impl.ICommonsSortedSet) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier) Nonnull(javax.annotation.Nonnull) WillNotClose(javax.annotation.WillNotClose) Logger(org.slf4j.Logger) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) StringHelper(com.helger.commons.string.StringHelper) PDTWebDateHelper(com.helger.commons.datetime.PDTWebDateHelper) IOException(java.io.IOException) File(java.io.File) JsonWriter(com.helger.json.serialize.JsonWriter) SimpleReadWriteLock(com.helger.commons.concurrent.SimpleReadWriteLock) MicroWriter(com.helger.xml.microdom.serialize.MicroWriter) Consumer(java.util.function.Consumer) PDStoredMLName(com.helger.pd.indexer.storage.PDStoredMLName) EQueryMode(com.helger.pd.indexer.storage.EQueryMode) CommonsLinkedHashMap(com.helger.commons.collection.impl.CommonsLinkedHashMap) ExcelStyle(com.helger.poi.excel.style.ExcelStyle) Comparator(java.util.Comparator) Query(org.apache.lucene.search.Query) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) PDStoredIdentifier(com.helger.pd.indexer.storage.PDStoredIdentifier) PDStoredMLName(com.helger.pd.indexer.storage.PDStoredMLName) IDocumentTypeIdentifier(com.helger.peppolid.IDocumentTypeIdentifier) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) PDStoredContact(com.helger.pd.indexer.storage.PDStoredContact)

Example 89 with IDocumentTypeIdentifier

use of com.helger.peppolid.IDocumentTypeIdentifier in project phoss-directory by phax.

the class ExportAllManager method queryAllContainedBusinessCardsAsExcel.

@Nonnull
public static WorkbookCreationHelper queryAllContainedBusinessCardsAsExcel(@Nonnull final EQueryMode eQueryMode, final boolean bIncludeDocTypes) throws IOException {
    final Query aQuery = eQueryMode.getEffectiveQuery(new MatchAllDocsQuery());
    final ExcelStyle ES_DATE = new ExcelStyle().setDataFormat("yyyy-mm-dd");
    final ExcelStyle ES_WRAP = new ExcelStyle().setWrapText(true);
    @WillNotClose final WorkbookCreationHelper aWBCH = new WorkbookCreationHelper(EExcelVersion.XLSX);
    aWBCH.createNewSheet();
    aWBCH.addRow();
    aWBCH.addCell("Participant ID");
    aWBCH.addCell("Names (per-row)");
    aWBCH.addCell("Country code");
    aWBCH.addCell("Geo info");
    aWBCH.addCell("Identifier schemes");
    aWBCH.addCell("Identifier values");
    aWBCH.addCell("Websites");
    aWBCH.addCell("Contact type");
    aWBCH.addCell("Contact name");
    aWBCH.addCell("Contact phone");
    aWBCH.addCell("Contact email");
    aWBCH.addCell("Additional info");
    aWBCH.addCell("Registration date");
    if (bIncludeDocTypes)
        aWBCH.addCell("Document types");
    final Consumer<? super PDStoredBusinessEntity> aConsumer = aEntity -> {
        aWBCH.addRow();
        aWBCH.addCell(aEntity.getParticipantID().getURIEncoded());
        aWBCH.addCell(StringHelper.getImplodedMapped("\n", aEntity.names(), PDStoredMLName::getNameAndLanguageCode));
        aWBCH.addCellStyle(ES_WRAP);
        aWBCH.addCell(aEntity.getCountryCode());
        aWBCH.addCell(aEntity.getGeoInfo());
        aWBCH.addCellStyle(ES_WRAP);
        aWBCH.addCell(StringHelper.getImplodedMapped("\n", aEntity.identifiers(), PDStoredIdentifier::getScheme));
        aWBCH.addCellStyle(ES_WRAP);
        aWBCH.addCell(StringHelper.getImplodedMapped("\n", aEntity.identifiers(), PDStoredIdentifier::getValue));
        aWBCH.addCellStyle(ES_WRAP);
        aWBCH.addCell(StringHelper.getImploded("\n", aEntity.websiteURIs()));
        aWBCH.addCellStyle(ES_WRAP);
        aWBCH.addCell(StringHelper.getImplodedMapped("\n", aEntity.contacts(), PDStoredContact::getType));
        aWBCH.addCellStyle(ES_WRAP);
        aWBCH.addCell(StringHelper.getImplodedMapped("\n", aEntity.contacts(), PDStoredContact::getName));
        aWBCH.addCellStyle(ES_WRAP);
        aWBCH.addCell(StringHelper.getImplodedMapped("\n", aEntity.contacts(), PDStoredContact::getPhone));
        aWBCH.addCellStyle(ES_WRAP);
        aWBCH.addCell(StringHelper.getImplodedMapped("\n", aEntity.contacts(), PDStoredContact::getEmail));
        aWBCH.addCellStyle(ES_WRAP);
        aWBCH.addCell(aEntity.getAdditionalInformation());
        aWBCH.addCellStyle(ES_WRAP);
        aWBCH.addCell(aEntity.getRegistrationDate());
        aWBCH.addCellStyle(ES_DATE);
        if (bIncludeDocTypes) {
            aWBCH.addCell(StringHelper.getImplodedMapped("\n", aEntity.documentTypeIDs(), IDocumentTypeIdentifier::getURIEncoded));
            aWBCH.addCellStyle(ES_WRAP);
        }
    };
    // Query all and group by participant ID
    PDMetaManager.getStorageMgr().searchAllDocuments(aQuery, -1, aConsumer);
    aWBCH.autoSizeAllColumns();
    aWBCH.autoFilterAllColumns();
    return aWBCH;
}
Also used : Query(org.apache.lucene.search.Query) EExcelVersion(com.helger.poi.excel.EExcelVersion) CommonsTreeSet(com.helger.commons.collection.impl.CommonsTreeSet) IDocumentTypeIdentifier(com.helger.peppolid.IDocumentTypeIdentifier) PDMetaManager(com.helger.pd.indexer.mgr.PDMetaManager) LoggerFactory(org.slf4j.LoggerFactory) IMicroDocument(com.helger.xml.microdom.IMicroDocument) PDTFactory(com.helger.commons.datetime.PDTFactory) IMicroElement(com.helger.xml.microdom.IMicroElement) PDStoredBusinessEntity(com.helger.pd.indexer.storage.PDStoredBusinessEntity) PDField(com.helger.pd.indexer.storage.field.PDField) ThreadSafe(javax.annotation.concurrent.ThreadSafe) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) ICommonsOrderedMap(com.helger.commons.collection.impl.ICommonsOrderedMap) StandardCharsets(java.nio.charset.StandardCharsets) JsonObject(com.helger.json.JsonObject) WorkbookCreationHelper(com.helger.poi.excel.WorkbookCreationHelper) ICommonsList(com.helger.commons.collection.impl.ICommonsList) IJsonArray(com.helger.json.IJsonArray) UnifiedResponse(com.helger.servlet.response.UnifiedResponse) CSVWriter(com.helger.commons.csv.CSVWriter) PDStoredContact(com.helger.pd.indexer.storage.PDStoredContact) Writer(java.io.Writer) WebFileIO(com.helger.photon.app.io.WebFileIO) ESuccess(com.helger.commons.state.ESuccess) FileSystemResource(com.helger.commons.io.resource.FileSystemResource) IJsonObject(com.helger.json.IJsonObject) MicroDocument(com.helger.xml.microdom.MicroDocument) CHttpHeader(com.helger.commons.http.CHttpHeader) JsonArray(com.helger.json.JsonArray) FileHelper(com.helger.commons.io.file.FileHelper) PDStoredIdentifier(com.helger.pd.indexer.storage.PDStoredIdentifier) ICommonsSortedSet(com.helger.commons.collection.impl.ICommonsSortedSet) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier) Nonnull(javax.annotation.Nonnull) WillNotClose(javax.annotation.WillNotClose) Logger(org.slf4j.Logger) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) StringHelper(com.helger.commons.string.StringHelper) PDTWebDateHelper(com.helger.commons.datetime.PDTWebDateHelper) IOException(java.io.IOException) File(java.io.File) JsonWriter(com.helger.json.serialize.JsonWriter) SimpleReadWriteLock(com.helger.commons.concurrent.SimpleReadWriteLock) MicroWriter(com.helger.xml.microdom.serialize.MicroWriter) Consumer(java.util.function.Consumer) PDStoredMLName(com.helger.pd.indexer.storage.PDStoredMLName) EQueryMode(com.helger.pd.indexer.storage.EQueryMode) CommonsLinkedHashMap(com.helger.commons.collection.impl.CommonsLinkedHashMap) ExcelStyle(com.helger.poi.excel.style.ExcelStyle) Comparator(java.util.Comparator) Query(org.apache.lucene.search.Query) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) ExcelStyle(com.helger.poi.excel.style.ExcelStyle) PDStoredIdentifier(com.helger.pd.indexer.storage.PDStoredIdentifier) PDStoredMLName(com.helger.pd.indexer.storage.PDStoredMLName) IDocumentTypeIdentifier(com.helger.peppolid.IDocumentTypeIdentifier) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) WillNotClose(javax.annotation.WillNotClose) WorkbookCreationHelper(com.helger.poi.excel.WorkbookCreationHelper) PDStoredContact(com.helger.pd.indexer.storage.PDStoredContact) Nonnull(javax.annotation.Nonnull)

Aggregations

IDocumentTypeIdentifier (com.helger.peppolid.IDocumentTypeIdentifier)89 IParticipantIdentifier (com.helger.peppolid.IParticipantIdentifier)62 ISMPServiceGroup (com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroup)36 Nonnull (javax.annotation.Nonnull)36 IIdentifierFactory (com.helger.peppolid.factory.IIdentifierFactory)32 Test (org.junit.Test)30 ISMPServiceGroupManager (com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroupManager)27 ISMPServiceInformationManager (com.helger.phoss.smp.domain.serviceinfo.ISMPServiceInformationManager)20 ISMPServiceInformation (com.helger.phoss.smp.domain.serviceinfo.ISMPServiceInformation)19 CommonsArrayList (com.helger.commons.collection.impl.CommonsArrayList)18 IProcessIdentifier (com.helger.peppolid.IProcessIdentifier)18 ICommonsList (com.helger.commons.collection.impl.ICommonsList)16 ISMPRedirectManager (com.helger.phoss.smp.domain.redirect.ISMPRedirectManager)16 Nullable (javax.annotation.Nullable)13 ESuccess (com.helger.commons.state.ESuccess)11 StringHelper (com.helger.commons.string.StringHelper)11 SimpleDocumentTypeIdentifier (com.helger.peppolid.simple.doctype.SimpleDocumentTypeIdentifier)11 SimpleParticipantIdentifier (com.helger.peppolid.simple.participant.SimpleParticipantIdentifier)11 ISMPProcess (com.helger.phoss.smp.domain.serviceinfo.ISMPProcess)11 ISMPRedirect (com.helger.phoss.smp.domain.redirect.ISMPRedirect)10