Search in sources :

Example 1 with GenericJAXBMarshaller

use of com.helger.jaxb.GenericJAXBMarshaller in project peppol-practical by phax.

the class MainWSDVSClient method main.

public static void main(final String[] args) throws ValidateFaultError {
    WSHelper.enableSoapLogging(true);
    LOGGER.info("Starting the engines");
    final String sXML = StreamHelper.getAllBytesAsString(new ClassPathResource("ws/invoice1.xml"), StandardCharsets.UTF_8);
    final WSDVSService aService = new WSDVSService(new FileSystemResource("src/main/webapp/WEB-INF/wsdl/pp-dvs.wsdl").getAsURL());
    final WSDVSPort aPort = aService.getWSDVSPort();
    final WSClientConfig aWsClientConfig = new WSClientConfig(URLHelper.getAsURL(true ? "https://peppol.helger.com/wsdvs" : "http://localhost:8080/wsdvs"));
    aWsClientConfig.applyWSSettingsToBindingProvider((BindingProvider) aPort);
    LOGGER.info("Starting validation process");
    final RequestType aRequest = new RequestType();
    aRequest.setVESID(PeppolValidation3_13_0.VID_OPENPEPPOL_INVOICE_V3.getAsSingleID());
    aRequest.setXML(sXML);
    aRequest.setDisplayLocale("en");
    final ResponseType aResponse = aPort.validate(aRequest);
    if (false)
        LOGGER.info("Result:\n" + new GenericJAXBMarshaller<>(ResponseType.class, com.helger.peppol.wsclient2.ObjectFactory._ValidateResponseOutput_QNAME).getAsString(aResponse));
    LOGGER.info("Success: " + aResponse.isSuccess());
    LOGGER.info("Interrupted: " + aResponse.isInterrupted());
    LOGGER.info("Most severe error level: " + aResponse.getMostSevereErrorLevel());
    int nPos = 1;
    final int nMaxPos = aResponse.getResultCount();
    for (final ValidationResultType aResult : aResponse.getResult()) {
        LOGGER.info("  [" + nPos + "/" + nMaxPos + "] " + aResult.getArtifactType() + " - " + aResult.getArtifactPath());
        ++nPos;
        LOGGER.info("  Success: " + aResult.getSuccess());
        for (final ItemType aItem : aResult.getItem()) {
            LOGGER.info("    Error Level: " + aItem.getErrorLevel());
            if (aItem.getErrorID() != null)
                LOGGER.info("    Error ID: " + aItem.getErrorID());
            if (aItem.getErrorFieldName() != null)
                LOGGER.info("    Error Field: " + aItem.getErrorFieldName());
            LOGGER.info("    Error Text: " + aItem.getErrorText());
            if (aItem.getErrorLocation() != null)
                LOGGER.info("    Location: " + aItem.getErrorLocation());
            if (aItem.getTest() != null)
                LOGGER.info("    Test: " + aItem.getTest());
            LOGGER.info("--");
        }
    }
    LOGGER.info("Done");
}
Also used : WSDVSService(com.helger.peppol.wsclient2.WSDVSService) WSDVSPort(com.helger.peppol.wsclient2.WSDVSPort) WSClientConfig(com.helger.wsclient.WSClientConfig) ValidationResultType(com.helger.peppol.wsclient2.ValidationResultType) ItemType(com.helger.peppol.wsclient2.ItemType) FileSystemResource(com.helger.commons.io.resource.FileSystemResource) GenericJAXBMarshaller(com.helger.jaxb.GenericJAXBMarshaller) ClassPathResource(com.helger.commons.io.resource.ClassPathResource) RequestType(com.helger.peppol.wsclient2.RequestType) ResponseType(com.helger.peppol.wsclient2.ResponseType)

Example 2 with GenericJAXBMarshaller

use of com.helger.jaxb.GenericJAXBMarshaller in project peppol-practical by phax.

the class PagePublicToolsParticipantInformation method _queryParticipant.

private void _queryParticipant(@Nonnull final WebPageExecutionContext aWPEC, final String sParticipantIDScheme, final String sParticipantIDValue, final ISMLConfiguration aSMLConfiguration, final boolean bSMLAutoDetect, final boolean bQueryBusinessCard, final boolean bShowTime, final boolean bXSDValidation, final boolean bVerifySignatures) {
    final HCNodeList aNodeList = aWPEC.getNodeList();
    final Locale aDisplayLocale = aWPEC.getDisplayLocale();
    final IRequestWebScopeWithoutResponse aRequestScope = aWPEC.getRequestScope();
    final ISMLConfigurationManager aSMLConfigurationMgr = PPMetaManager.getSMLConfigurationMgr();
    final String sParticipantIDUriEncoded = CIdentifier.getURIEncoded(sParticipantIDScheme, sParticipantIDValue);
    LOGGER.info("Start querying the Participant information of '" + sParticipantIDUriEncoded + "'");
    // Try to print the basic information before an error occurs
    aNodeList.addChild(div("Querying the following SMP for ").addChild(code(sParticipantIDUriEncoded)).addChild(":"));
    final ICommonsList<JAXBException> aSMPExceptions = new CommonsArrayList<>();
    try {
        SMPQueryParams aQueryParams = null;
        ISMLConfiguration aRealSMLConfiguration = aSMLConfiguration;
        if (bSMLAutoDetect) {
            final ICommonsList<ISMLConfiguration> aSortedList = aSMLConfigurationMgr.getAllSorted();
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Sorted SML Configs: " + StringHelper.getImplodedMapped(", ", aSortedList, ISMLConfiguration::getID));
            for (final ISMLConfiguration aCurSML : aSortedList) {
                aQueryParams = SMPQueryParams.createForSML(aCurSML, sParticipantIDScheme, sParticipantIDValue, false);
                if (aQueryParams == null)
                    continue;
                try {
                    InetAddress.getByName(aQueryParams.getSMPHostURI().getHost());
                    // Found it
                    aRealSMLConfiguration = aCurSML;
                    break;
                } catch (final UnknownHostException ex) {
                // continue
                }
            }
            // Ensure to go into the exception handler
            if (aRealSMLConfiguration == null) {
                LOGGER.error("Failed to autodetect a matching SML for '" + sParticipantIDUriEncoded + "'");
                aNodeList.addChild(error(div("Seems like the participant ID " + sParticipantIDUriEncoded + " is not known in any of the configured networks.")));
                // Audit failure
                AuditHelper.onAuditExecuteFailure("participant-information", sParticipantIDUriEncoded, "no-sml-found");
                return;
            }
            LOGGER.info("Participant ID '" + sParticipantIDUriEncoded + "': auto detected SML " + aRealSMLConfiguration.getID());
        } else {
            // SML configuration is not null
            aQueryParams = SMPQueryParams.createForSML(aRealSMLConfiguration, sParticipantIDScheme, sParticipantIDValue, true);
        }
        if (aQueryParams == null) {
            LOGGER.error("Participant ID '" + sParticipantIDUriEncoded + "': failed to resolve SMP query parameters for SML '" + aRealSMLConfiguration.getID() + "'");
            aNodeList.addChild(error(div("Failed to resolve participant ID " + sParticipantIDUriEncoded + " for the provided network.")).addChild(bSMLAutoDetect ? null : div("Try selecting a different SML - maybe this helps")));
            // Audit failure
            AuditHelper.onAuditExecuteFailure("participant-information", sParticipantIDUriEncoded, "smp-query-params-null");
            return;
        }
        LOGGER.info("Participant information of '" + sParticipantIDUriEncoded + "' is queried using SMP API '" + aQueryParams.getSMPAPIType() + "' from '" + aQueryParams.getSMPHostURI() + "' using SML '" + aRealSMLConfiguration + "'; XSD validation=" + bXSDValidation + "; verify signatures=" + bVerifySignatures);
        final IParticipantIdentifier aParticipantID = aQueryParams.getParticipantID();
        final URL aSMPHost = URLHelper.getAsURL(aQueryParams.getSMPHostURI());
        {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Trying to resolve SMP '" + aSMPHost.getHost() + "' by DNS");
            final HCUL aUL = new HCUL();
            aNodeList.addChild(aUL);
            aUL.addItem(div("SML used: ").addChild(code(aRealSMLConfiguration.getDisplayName() + " / " + aRealSMLConfiguration.getDNSZone())).addChild(" ").addChild(aRealSMLConfiguration.isProduction() ? badgeSuccess("production SML") : badgeWarn("test SML")));
            aUL.addItem(div("Query API: " + aRealSMLConfiguration.getSMPAPIType().getDisplayName()));
            final String sURL1 = aSMPHost.toExternalForm();
            aUL.addItem(div("Resolved name: ").addChild(code(sURL1)), div(_createOpenInBrowser(sURL1)));
            if (aWPEC.params().hasStringValue("dnsjava", "true")) {
                LOGGER.info("Start DNSJava lookup");
                Record[] aRecords = null;
                try {
                    aRecords = new Lookup(aSMPHost.getHost(), Type.A).run();
                } catch (final TextParseException ex) {
                // Ignore
                }
                if (aRecords != null)
                    for (final Record aRecord : aRecords) {
                        final ARecord aARec = (ARecord) aRecord;
                        final String sURL2 = aARec.rdataToString();
                        final InetAddress aNice = aARec.getAddress();
                        final String sURL3 = aNice != null ? aNice.getCanonicalHostName() : null;
                        final HCDiv aDiv1 = div("[dnsjava] IP addressX: ").addChild(code(sURL2));
                        if (sURL3 != null)
                            aDiv1.addChild(" - reverse lookup: ").addChild(code(sURL3));
                        else
                            aDiv1.addChild(" - reverse lookup failed");
                        final HCDiv aDiv2 = div(_createOpenInBrowser("http://" + sURL2, "Open IP in browser"));
                        if (sURL3 != null)
                            aDiv2.addChild(" ").addChild(_createOpenInBrowser("http://" + sURL3, "Open name in browser"));
                        aUL.addItem(aDiv1, aDiv2);
                    }
                LOGGER.info("Finished DNSJava lookup - " + (aRecords == null ? "no results" : aRecords.length + " result records"));
            }
            try {
                final InetAddress[] aInetAddresses = InetAddress.getAllByName(aSMPHost.getHost());
                for (final InetAddress aInetAddress : aInetAddresses) {
                    final String sURL2 = new IPV4Addr(aInetAddress).getAsString();
                    final InetAddress aNice = InetAddress.getByAddress(aInetAddress.getAddress());
                    final String sURL3 = aNice.getCanonicalHostName();
                    aUL.addItem(div("IP address: ").addChild(code(sURL2)).addChild(" - reverse lookup: ").addChild(code(sURL3)), div(_createOpenInBrowser("http://" + sURL2, "Open IP in browser")).addChild(" ").addChild(_createOpenInBrowser("http://" + sURL3, "Open name in browser")));
                }
                // Show only once
                final String sURL4 = sURL1 + (sURL1.endsWith("/") ? "" : "/") + sParticipantIDUriEncoded;
                aUL.addItem(div("Query base URL: ").addChild(code(sURL4)), div(_createOpenInBrowser(sURL4)));
                if (!bXSDValidation)
                    aUL.addItem(badgeWarn("XML Schema validation of SMP responses is disabled."));
                if (!bVerifySignatures)
                    aUL.addItem(badgeDanger("Signature verification of SMP responses is disabled."));
            } catch (final UnknownHostException ex) {
                LOGGER.error("Failed to resolve SMP host '" + aSMPHost.getHost() + "' for the participant ID '" + sParticipantIDUriEncoded + "'");
                aNodeList.addChild(error(div("Seems like the participant ID " + sParticipantIDUriEncoded + " is not registered to the selected network.")).addChild(AppCommonUI.getTechnicalDetailsUI(ex, false)).addChild(bSMLAutoDetect ? null : div("Try selecting a different SML - maybe this helps")));
                // Audit failure
                AuditHelper.onAuditExecuteFailure("participant-information", sParticipantIDUriEncoded, "unknown-host", ex.getMessage());
                return;
            }
        }
        // Determine all document types
        final ICommonsList<IDocumentTypeIdentifier> aDocTypeIDs = new CommonsArrayList<>();
        SMPClientReadOnly aSMPClient = null;
        BDXRClientReadOnly aBDXR1Client = null;
        final Consumer<GenericJAXBMarshaller<?>> aSMPMarshallerCustomizer = m -> {
            aSMPExceptions.clear();
            // Remember exceptions
            m.readExceptionCallbacks().add(aSMPExceptions::add);
        };
        try {
            final StopWatch aSWGetDocTypes = StopWatch.createdStarted();
            final HCUL aSGUL = new HCUL();
            final ICommonsSortedMap<String, String> aSGHrefs = new CommonsTreeMap<>();
            IHCNode aSGExtension = null;
            switch(aQueryParams.getSMPAPIType()) {
                case PEPPOL:
                    {
                        aSMPClient = new SMPClientReadOnly(aQueryParams.getSMPHostURI());
                        aSMPClient.setXMLSchemaValidation(bXSDValidation);
                        aSMPClient.setVerifySignature(bVerifySignatures);
                        aSMPClient.setMarshallerCustomizer(aSMPMarshallerCustomizer);
                        // Get all HRefs and sort them by decoded URL
                        final com.helger.xsds.peppol.smp1.ServiceGroupType aSG = aSMPClient.getServiceGroupOrNull(aParticipantID);
                        if (aSG != null) {
                            // Map from cleaned URL to original URL
                            if (aSG.getServiceMetadataReferenceCollection() != null)
                                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)
                                        aSGUL.addItem(warn("The ServiceGroup list contains the duplicate URL ").addChild(code(sHref)));
                                }
                            if (aSG.getExtension() != null && aSG.getExtension().getAny() != null) {
                                aSGExtension = new HCPrismJS(EPrismLanguage.MARKUP).addChild(XMLWriter.getNodeAsString(aSG.getExtension().getAny()));
                            }
                        }
                        break;
                    }
                case OASIS_BDXR_V1:
                    {
                        aBDXR1Client = new BDXRClientReadOnly(aQueryParams.getSMPHostURI());
                        aBDXR1Client.setXMLSchemaValidation(bXSDValidation);
                        aBDXR1Client.setVerifySignature(bVerifySignatures);
                        aBDXR1Client.setMarshallerCustomizer(aSMPMarshallerCustomizer);
                        // 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) {
                            if (aSG.getServiceMetadataReferenceCollection() != null)
                                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)
                                        aSGUL.addItem(warn("The ServiceGroup list contains the duplicate URL ").addChild(code(sHref)));
                                }
                            if (aSG.getExtensionCount() > 0) {
                                final HCUL aNL2 = new HCUL();
                                for (final com.helger.xsds.bdxr.smp1.ExtensionType aExt : aSG.getExtension()) if (aExt.getAny() != null) {
                                    if (aExt.getAny() instanceof Element)
                                        aNL2.addItem(new HCPrismJS(EPrismLanguage.MARKUP).addChild(XMLWriter.getNodeAsString((Element) aExt.getAny())));
                                    else
                                        aNL2.addItem(code(aExt.getAny().toString()));
                                }
                                if (aNL2.hasChildren())
                                    aSGExtension = aNL2;
                            }
                        }
                        break;
                    }
            }
            aSWGetDocTypes.stop();
            LOGGER.info("Participant information of '" + aParticipantID.getURIEncoded() + "' returned " + aSGHrefs.size() + " entries");
            final HCH3 aH3 = h3("ServiceGroup contents");
            if (bShowTime)
                aH3.addChild(" ").addChild(_createTimingNode(aSWGetDocTypes.getMillis()));
            aNodeList.addChild(aH3);
            final String sPathStart = "/" + aParticipantID.getURIEncoded() + "/services/";
            // Show all ServiceGroup hrefs
            for (final Map.Entry<String, String> aEntry : aSGHrefs.entrySet()) {
                final String sHref = aEntry.getKey();
                final String sOriginalHref = aEntry.getValue();
                final IHCLI<?> aLI = aSGUL.addAndReturnItem(div(code(sHref)));
                // Should be case insensitive "indexOf" here
                final int nPathStart = sHref.toLowerCase(Locale.US).indexOf(sPathStart.toLowerCase(Locale.US));
                if (nPathStart >= 0) {
                    final String sDocType = sHref.substring(nPathStart + sPathStart.length());
                    final IDocumentTypeIdentifier aDocType = aQueryParams.getIF().parseDocumentTypeIdentifier(sDocType);
                    if (aDocType != null) {
                        aDocTypeIDs.add(aDocType);
                        aLI.addChild(div(EFontAwesome4Icon.ARROW_RIGHT.getAsNode()).addChild(" ").addChild(AppCommonUI.createDocTypeID(aDocType, false)));
                        aLI.addChild(div(EFontAwesome4Icon.ARROW_RIGHT.getAsNode()).addChild(" ").addChild(_createOpenInBrowser(sOriginalHref)));
                    } else {
                        aLI.addChild(error("The document type ").addChild(code(sDocType)).addChild(" could not be interpreted as a structured document type!"));
                    }
                } else {
                    aLI.addChild(error().addChildren(div("Contained href does not match the rules!"), div("Found href: ").addChild(code(sHref)), div("Expected path part: ").addChild(code(sPathStart))));
                }
            }
            if (!aSGUL.hasChildren())
                aSGUL.addItem(warn("No service group entries were found for " + aParticipantID.getURIEncoded()));
            if (aSGExtension != null)
                aSGUL.addAndReturnItem(div("Extension:")).addChild(aSGExtension);
            aNodeList.addChild(aSGUL);
        } catch (final SMPClientException ex) {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Participant DocTypes Error", ex);
            else if (LOGGER.isWarnEnabled())
                LOGGER.warn("Participant DocTypes Error: " + ex.getClass().getName() + " - " + ex.getMessage());
            final BootstrapErrorBox aErrorBox = error(div("Error querying SMP.")).addChild(AppCommonUI.getTechnicalDetailsUI(ex, false));
            for (final JAXBException aItem : aSMPExceptions) aErrorBox.addChild(AppCommonUI.getTechnicalDetailsUI(aItem, false));
            aNodeList.addChild(aErrorBox);
            // Audit failure
            AuditHelper.onAuditExecuteFailure("participant-doctypes", sParticipantIDUriEncoded, ex.getClass(), ex.getMessage());
        }
        // List document type details
        if (aDocTypeIDs.isNotEmpty()) {
            final OffsetDateTime aNowDateTime = PDTFactory.getCurrentOffsetDateTime();
            final ICommonsOrderedSet<X509Certificate> aAllUsedEndpointCertifiactes = new CommonsLinkedHashSet<>();
            long nTotalDurationMillis = 0;
            aNodeList.addChild(h3("Document type details"));
            final HCUL aULDocTypeIDs = new HCUL();
            for (final IDocumentTypeIdentifier aDocTypeID : aDocTypeIDs.getSortedInline(IDocumentTypeIdentifier.comparator())) {
                final HCDiv aDocTypeDiv = div(AppCommonUI.createDocTypeID(aDocTypeID, true));
                final IHCLI<?> aLIDocTypeID = aULDocTypeIDs.addAndReturnItem(aDocTypeDiv);
                LOGGER.info("Now SMP querying '" + aParticipantID.getURIEncoded() + "' / '" + aDocTypeID.getURIEncoded() + "'");
                final StopWatch aSWGetDetails = StopWatch.createdStarted();
                try {
                    switch(aQueryParams.getSMPAPIType()) {
                        case PEPPOL:
                            {
                                final com.helger.xsds.peppol.smp1.SignedServiceMetadataType aSSM = aSMPClient.getServiceMetadataOrNull(aParticipantID, aDocTypeID);
                                aSWGetDetails.stop();
                                if (aSSM != null) {
                                    final com.helger.xsds.peppol.smp1.ServiceMetadataType aSM = aSSM.getServiceMetadata();
                                    if (aSM.getRedirect() != null)
                                        aLIDocTypeID.addChild(div("Redirect to " + aSM.getRedirect().getHref()));
                                    else {
                                        // For all processes
                                        final HCUL aULProcessID = new HCUL();
                                        for (final com.helger.xsds.peppol.smp1.ProcessType aProcess : aSM.getServiceInformation().getProcessList().getProcess()) if (aProcess.getProcessIdentifier() != null) {
                                            final IHCLI<?> aLIProcessID = aULProcessID.addItem();
                                            aLIProcessID.addChild(div("Process ID: ").addChild(AppCommonUI.createProcessID(aDocTypeID, SimpleProcessIdentifier.wrap(aProcess.getProcessIdentifier()))));
                                            final HCUL aULEndpoint = new HCUL();
                                            // For all endpoints of the process
                                            for (final com.helger.xsds.peppol.smp1.EndpointType aEndpoint : aProcess.getServiceEndpointList().getEndpoint()) {
                                                final IHCLI<?> aLIEndpoint = aULEndpoint.addItem();
                                                // Endpoint URL
                                                final String sEndpointRef = aEndpoint.getEndpointReference() == null ? null : W3CEndpointReferenceHelper.getAddress(aEndpoint.getEndpointReference());
                                                _printEndpointURL(aLIEndpoint, sEndpointRef);
                                                // Valid from
                                                _printActivationDate(aLIEndpoint, aEndpoint.getServiceActivationDate(), aDisplayLocale);
                                                // Valid to
                                                _printExpirationDate(aLIEndpoint, aEndpoint.getServiceExpirationDate(), aDisplayLocale);
                                                // Transport profile
                                                _printTransportProfile(aLIEndpoint, aEndpoint.getTransportProfile());
                                                // Technical infos
                                                _printTecInfo(aLIEndpoint, aEndpoint.getTechnicalInformationUrl(), aEndpoint.getTechnicalContactUrl());
                                                // Certificate (also add null values)
                                                final X509Certificate aCert = CertificateHelper.convertStringToCertficateOrNull(aEndpoint.getCertificate());
                                                aAllUsedEndpointCertifiactes.add(aCert);
                                            }
                                            aLIProcessID.addChild(aULEndpoint);
                                        }
                                        aLIDocTypeID.addChild(aULProcessID);
                                    }
                                } else {
                                    aLIDocTypeID.addChild(error("Failed to read service metadata from SMP (not found)"));
                                }
                                break;
                            }
                        case OASIS_BDXR_V1:
                            {
                                final com.helger.xsds.bdxr.smp1.SignedServiceMetadataType aSSM = aBDXR1Client.getServiceMetadataOrNull(aParticipantID, aDocTypeID);
                                aSWGetDetails.stop();
                                if (aSSM != null) {
                                    final com.helger.xsds.bdxr.smp1.ServiceMetadataType aSM = aSSM.getServiceMetadata();
                                    if (aSM.getRedirect() != null)
                                        aLIDocTypeID.addChild(div("Redirect to " + aSM.getRedirect().getHref()));
                                    else {
                                        // For all processes
                                        final HCUL aULProcessID = new HCUL();
                                        for (final com.helger.xsds.bdxr.smp1.ProcessType aProcess : aSM.getServiceInformation().getProcessList().getProcess()) if (aProcess.getProcessIdentifier() != null) {
                                            final IHCLI<?> aLIProcessID = aULProcessID.addItem();
                                            aLIProcessID.addChild(div("Process ID: ").addChild(AppCommonUI.createProcessID(aDocTypeID, SimpleProcessIdentifier.wrap(aProcess.getProcessIdentifier()))));
                                            final HCUL aULEndpoint = new HCUL();
                                            // For all endpoints of the process
                                            for (final com.helger.xsds.bdxr.smp1.EndpointType aEndpoint : aProcess.getServiceEndpointList().getEndpoint()) {
                                                final IHCLI<?> aLIEndpoint = aULEndpoint.addItem();
                                                // Endpoint URL
                                                _printEndpointURL(aLIEndpoint, aEndpoint.getEndpointURI());
                                                // Valid from
                                                _printActivationDate(aLIEndpoint, aEndpoint.getServiceActivationDate(), aDisplayLocale);
                                                // Valid to
                                                _printExpirationDate(aLIEndpoint, aEndpoint.getServiceExpirationDate(), aDisplayLocale);
                                                // Transport profile
                                                _printTransportProfile(aLIEndpoint, aEndpoint.getTransportProfile());
                                                // Technical infos
                                                _printTecInfo(aLIEndpoint, aEndpoint.getTechnicalInformationUrl(), aEndpoint.getTechnicalContactUrl());
                                                // Certificate (also add null values)
                                                try {
                                                    final X509Certificate aCert = CertificateHelper.convertByteArrayToCertficateDirect(aEndpoint.getCertificate());
                                                    aAllUsedEndpointCertifiactes.add(aCert);
                                                } catch (final CertificateException ex) {
                                                    aAllUsedEndpointCertifiactes.add(null);
                                                }
                                            }
                                            aLIProcessID.addChild(aULEndpoint);
                                        }
                                        aLIDocTypeID.addChild(aULProcessID);
                                    }
                                } else {
                                    aLIDocTypeID.addChild(error("Failed to read service metadata from SMP (not found)"));
                                }
                                break;
                            }
                    }
                } catch (final SMPClientBadResponseException ex) {
                    if (LOGGER.isDebugEnabled())
                        LOGGER.debug("Participant Information Error", ex);
                    else if (LOGGER.isWarnEnabled())
                        LOGGER.warn("Participant Information Error: " + ex.getClass().getName() + " - " + ex.getMessage());
                    final BootstrapErrorBox aErrorBox = error(div("Error querying SMP. Try disabling 'XML Schema validation'.")).addChild(AppCommonUI.getTechnicalDetailsUI(ex, false));
                    for (final JAXBException aItem : aSMPExceptions) aErrorBox.addChild(AppCommonUI.getTechnicalDetailsUI(aItem, false));
                    aLIDocTypeID.addChild(aErrorBox);
                    // Audit failure
                    AuditHelper.onAuditExecuteFailure("participant-information", sParticipantIDUriEncoded, ex.getClass(), ex.getMessage());
                } catch (final SMPClientException ex) {
                    if (LOGGER.isDebugEnabled())
                        LOGGER.debug("Participant Information Error", ex);
                    else if (LOGGER.isWarnEnabled())
                        LOGGER.warn("Participant Information Error: " + ex.getClass().getName() + " - " + ex.getMessage());
                    final BootstrapErrorBox aErrorBox = error(div("Error querying SMP.")).addChild(AppCommonUI.getTechnicalDetailsUI(ex, false));
                    for (final JAXBException aItem : aSMPExceptions) aErrorBox.addChild(AppCommonUI.getTechnicalDetailsUI(aItem, false));
                    aLIDocTypeID.addChild(aErrorBox);
                    // Audit failure
                    AuditHelper.onAuditExecuteFailure("participant-information", sParticipantIDUriEncoded, ex.getClass(), ex.getMessage());
                }
                if (bShowTime)
                    aDocTypeDiv.addChild(" ").addChild(_createTimingNode(aSWGetDetails.getMillis()));
                nTotalDurationMillis += aSWGetDetails.getMillis();
            }
            aNodeList.addChild(aULDocTypeIDs);
            if (bShowTime)
                aNodeList.addChild(div("Overall time: ").addChild(_createTimingNode(nTotalDurationMillis)));
            aNodeList.addChild(h3("Endpoint Certificate details"));
            if (aAllUsedEndpointCertifiactes.isEmpty()) {
                aNodeList.addChild(warn("No Endpoint Certificate information was found."));
            } else {
                final HCUL aULCerts = new HCUL();
                for (final X509Certificate aEndpointCert : aAllUsedEndpointCertifiactes) {
                    final IHCLI<?> aLICert = aULCerts.addItem();
                    if (aEndpointCert != null) {
                        aLICert.addChild(div("Subject: " + aEndpointCert.getSubjectX500Principal().getName()));
                        aLICert.addChild(div("Issuer: " + aEndpointCert.getIssuerX500Principal().getName()));
                        final OffsetDateTime aNotBefore = PDTFactory.createOffsetDateTime(aEndpointCert.getNotBefore());
                        aLICert.addChild(div("Not before: " + PDTToString.getAsString(aNotBefore, aDisplayLocale)));
                        if (aNotBefore.isAfter(aNowDateTime))
                            aLICert.addChild(error("This Endpoint Certificate is not yet valid!"));
                        final OffsetDateTime aNotAfter = PDTFactory.createOffsetDateTime(aEndpointCert.getNotAfter());
                        aLICert.addChild(div("Not after: " + PDTToString.getAsString(aNotAfter, aDisplayLocale)));
                        if (aNotAfter.isBefore(aNowDateTime))
                            aLICert.addChild(error("This Endpoint Certificate is no longer valid!"));
                        aLICert.addChild(div("Serial number: " + aEndpointCert.getSerialNumber().toString() + " / 0x" + _inGroupsOf(aEndpointCert.getSerialNumber().toString(16), 4)));
                        if (aQueryParams.getSMPAPIType() == ESMPAPIType.PEPPOL) {
                            // Check Peppol certificate status
                            final EPeppolCertificateCheckResult eCertStatus = PeppolCertificateChecker.checkPeppolAPCertificate(aEndpointCert, aNowDateTime, ETriState.FALSE, null);
                            if (eCertStatus.isValid())
                                aLICert.addChild(success("The Endpoint Certificate appears to be a valid Peppol certificate."));
                            else {
                                aLICert.addChild(error().addChild(div("The Endpoint Certificate appears to be an invalid Peppol certificate. Reason: " + eCertStatus.getReason())));
                            }
                        }
                        final HCTextArea aTextArea = new HCTextArea().setReadOnly(true).setRows(4).setValue(CertificateHelper.getPEMEncodedCertificate(aEndpointCert)).addStyle(CCSSProperties.FONT_FAMILY.newValue(CCSSValue.FONT_MONOSPACE));
                        BootstrapFormHelper.markAsFormControl(aTextArea);
                        aLICert.addChild(div(aTextArea));
                    } else {
                        aLICert.addChild(error("Failed to interpret the data as a X509 certificate"));
                    }
                }
                aNodeList.addChild(aULCerts);
            }
        }
        if (bQueryBusinessCard) {
            final StopWatch aSWGetBC = StopWatch.createdStarted();
            aNodeList.addChild(h3("Business Card details"));
            EFamFamFlagIcon.registerResourcesForThisRequest();
            final String sBCURL = aSMPHost.toExternalForm() + "/businesscard/" + aParticipantID.getURIEncoded();
            LOGGER.info("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;
            }
            aSWGetBC.stop();
            if (aData == null)
                aNodeList.addChild(warn("No Business Card is available for that participant."));
            else {
                final ICommonsList<JAXBException> aPDExceptions = new CommonsArrayList<>();
                final Consumer<GenericJAXBMarshaller<?>> aPMarshallerCustomizer = m -> {
                    aPDExceptions.clear();
                    // Remember errors
                    m.readExceptionCallbacks().add(aPDExceptions::add);
                    m.setCharset(StandardCharsets.UTF_8);
                };
                final PDBusinessCard aBC = PDBusinessCardHelper.parseBusinessCard(aData, aPMarshallerCustomizer);
                if (aBC == null) {
                    final BootstrapErrorBox aError = error("Failed to parse the response data as a Business Card.");
                    for (final JAXBException aItem : aPDExceptions) aError.addChild(AppCommonUI.getTechnicalDetailsUI(aItem, false));
                    aNodeList.addChild(aError);
                    final String sBC = new String(aData, StandardCharsets.UTF_8);
                    if (StringHelper.hasText(sBC))
                        aNodeList.addChild(new HCPrismJS(EPrismLanguage.MARKUP).addChild(sBC));
                    LOGGER.error("Failed to parse BC:\n" + sBC);
                } else {
                    final HCH4 aH4 = h4("Business Card contains " + (aBC.businessEntities().size() == 1 ? "1 entity" : aBC.businessEntities().size() + " entities"));
                    if (bShowTime)
                        aH4.addChild(" ").addChild(_createTimingNode(aSWGetBC.getMillis()));
                    aNodeList.addChild(aH4);
                    aNodeList.addChild(div(_createOpenInBrowser(sBCURL)));
                    final HCUL aUL = new HCUL();
                    for (final PDBusinessEntity aEntity : aBC.businessEntities()) {
                        final HCLI aLI = aUL.addItem();
                        // Name
                        for (final PDName aName : aEntity.names()) {
                            final Locale aLanguage = LanguageCache.getInstance().getLanguage(aName.getLanguageCode());
                            final String sLanguageName = aLanguage == null ? "" : " (" + aLanguage.getDisplayLanguage(aDisplayLocale) + ")";
                            aLI.addChild(div(aName.getName() + sLanguageName));
                        }
                        // Country
                        {
                            final String sCountryCode = aEntity.getCountryCode();
                            final Locale aCountryCode = CountryCache.getInstance().getCountry(sCountryCode);
                            final String sCountryName = aCountryCode == null ? sCountryCode : aCountryCode.getDisplayCountry(aDisplayLocale) + " (" + sCountryCode + ")";
                            final EFamFamFlagIcon eIcon = EFamFamFlagIcon.getFromIDOrNull(sCountryCode);
                            aLI.addChild(div("Country: " + sCountryName + " ").addChild(eIcon == null ? null : eIcon.getAsNode()));
                        }
                        // Geo info
                        if (aEntity.hasGeoInfo()) {
                            aLI.addChild(div("Geographical information: ").addChildren(HCExtHelper.nl2brList(aEntity.getGeoInfo())));
                        }
                        // Additional IDs
                        if (aEntity.identifiers().isNotEmpty()) {
                            final BootstrapTable aIDTab = new BootstrapTable().setCondensed(true);
                            aIDTab.addHeaderRow().addCells("Scheme", "Value");
                            for (final PDIdentifier aItem : aEntity.identifiers()) {
                                // Avoid empty rows
                                if (StringHelper.hasText(aItem.getScheme()) || StringHelper.hasText(aItem.getValue()))
                                    aIDTab.addBodyRow().addCells(aItem.getScheme(), aItem.getValue());
                            }
                            if (aIDTab.hasBodyRows())
                                aLI.addChild(div("Additional identifiers: ").addChild(aIDTab));
                        }
                        // Website URLs
                        if (aEntity.websiteURIs().isNotEmpty()) {
                            final HCNodeList aWebsites = new HCNodeList();
                            for (final String sItem : aEntity.websiteURIs()) if (StringHelper.hasText(sItem))
                                aWebsites.addChild(div(HCA.createLinkedWebsite(sItem)));
                            if (aWebsites.hasChildren())
                                aLI.addChild(div("Website URLs: ").addChild(aWebsites));
                        }
                        // Contacts
                        if (aEntity.contacts().isNotEmpty()) {
                            final BootstrapTable aContactTab = new BootstrapTable().setCondensed(true);
                            aContactTab.addHeaderRow().addCells("Type", "Name", "Phone", "Email");
                            for (final PDContact aItem : aEntity.contacts()) {
                                // Avoid empty rows
                                if (StringHelper.hasText(aItem.getType()) || StringHelper.hasText(aItem.getName()) || StringHelper.hasText(aItem.getPhoneNumber()) || StringHelper.hasText(aItem.getEmail()))
                                    aContactTab.addBodyRow().addCell(aItem.getType()).addCell(aItem.getName()).addCell(aItem.getPhoneNumber()).addCell(HCA_MailTo.createLinkedEmail(aItem.getEmail()));
                            }
                            if (aContactTab.hasBodyRows())
                                aLI.addChild(div("Contact points: ").addChild(aContactTab));
                        }
                        if (aEntity.hasAdditionalInfo()) {
                            aLI.addChild(div("Additional information: ").addChildren(HCExtHelper.nl2brList(aEntity.getAdditionalInfo())));
                        }
                        if (aEntity.hasRegistrationDate()) {
                            aLI.addChild(div("Registration date: ").addChild(PDTToString.getAsString(aEntity.getRegistrationDate(), aDisplayLocale)));
                        }
                    }
                    aNodeList.addChild(aUL);
                }
            }
        }
        // Audit success
        AuditHelper.onAuditExecuteSuccess("participant-information", aParticipantID.getURIEncoded());
    } catch (final RuntimeException ex) {
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Participant Information Error", ex);
        else if (LOGGER.isWarnEnabled())
            LOGGER.warn("Participant Information Error: " + ex.getClass().getName() + " - " + ex.getMessage());
        new InternalErrorBuilder().setRequestScope(aRequestScope).setDisplayLocale(aDisplayLocale).setThrowable(ex).handle();
        aNodeList.addChild(error(div("Error querying participant information.")).addChild(AppCommonUI.getTechnicalDetailsUI(ex, true)));
        // Audit failure
        AuditHelper.onAuditExecuteFailure("participant-information", sParticipantIDUriEncoded, ex.getClass(), ex.getMessage());
    }
    aNodeList.addChild(new HCHR());
}
Also used : Locale(java.util.Locale) HCDiv(com.helger.html.hc.html.grouping.HCDiv) IDocumentTypeIdentifier(com.helger.peppolid.IDocumentTypeIdentifier) ETriState(com.helger.commons.state.ETriState) EFontAwesome4Icon(com.helger.photon.icon.fontawesome.EFontAwesome4Icon) CommonsTreeMap(com.helger.commons.collection.impl.CommonsTreeMap) CCSSProperties(com.helger.css.property.CCSSProperties) BootstrapButtonToolbar(com.helger.photon.bootstrap4.buttongroup.BootstrapButtonToolbar) FormErrorList(com.helger.photon.core.form.FormErrorList) BootstrapForm(com.helger.photon.bootstrap4.form.BootstrapForm) InetAddress(java.net.InetAddress) IIdentifierFactory(com.helger.peppolid.factory.IIdentifierFactory) ResponseHandlerByteArray(com.helger.httpclient.response.ResponseHandlerByteArray) Nonempty(com.helger.commons.annotation.Nonempty) PDTFactory(com.helger.commons.datetime.PDTFactory) EBootstrapButtonType(com.helger.photon.bootstrap4.button.EBootstrapButtonType) Map(java.util.Map) HCA(com.helger.html.hc.html.textlevel.HCA) HCTextArea(com.helger.html.hc.html.forms.HCTextArea) CPageParam(com.helger.photon.uicore.css.CPageParam) PDTToString(com.helger.commons.datetime.PDTToString) Lookup(org.xbill.DNS.Lookup) HCDiv(com.helger.html.hc.html.grouping.HCDiv) ISMLConfiguration(com.helger.peppol.domain.ISMLConfiguration) HCTextNode(com.helger.html.hc.impl.HCTextNode) StandardCharsets(java.nio.charset.StandardCharsets) AuditHelper(com.helger.photon.audit.AuditHelper) PDName(com.helger.pd.businesscard.generic.PDName) ICommonsList(com.helger.commons.collection.impl.ICommonsList) HCExtHelper(com.helger.html.hc.ext.HCExtHelper) ISMLConfigurationManager(com.helger.peppol.app.mgr.ISMLConfigurationManager) ESMPTransportProfile(com.helger.peppol.smp.ESMPTransportProfile) EmailAddressHelper(com.helger.commons.email.EmailAddressHelper) CIdentifier(com.helger.peppolid.CIdentifier) TextParseException(org.xbill.DNS.TextParseException) HCEdit(com.helger.html.hc.html.forms.HCEdit) PDBusinessCardHelper(com.helger.pd.businesscard.helper.PDBusinessCardHelper) LanguageCache(com.helger.commons.locale.language.LanguageCache) IHCNode(com.helger.html.hc.IHCNode) ICommonsSortedMap(com.helger.commons.collection.impl.ICommonsSortedMap) Nullable(javax.annotation.Nullable) IPV4Addr(com.helger.dns.ip.IPV4Addr) IHCLI(com.helger.html.hc.html.grouping.IHCLI) BootstrapFormGroup(com.helger.photon.bootstrap4.form.BootstrapFormGroup) StringHelper(com.helger.commons.string.StringHelper) PDBusinessCard(com.helger.pd.businesscard.generic.PDBusinessCard) SMLConfigurationSelect(com.helger.peppol.ui.select.SMLConfigurationSelect) BootstrapFormHelper(com.helger.photon.bootstrap4.form.BootstrapFormHelper) W3CEndpointReferenceHelper(com.helger.smpclient.peppol.utils.W3CEndpointReferenceHelper) HCA_MailTo(com.helger.html.hc.ext.HCA_MailTo) UnknownHostException(java.net.UnknownHostException) ESMPAPIType(com.helger.peppol.sml.ESMPAPIType) RequestField(com.helger.photon.core.form.RequestField) BDXRClientReadOnly(com.helger.smpclient.bdxr1.BDXRClientReadOnly) SMPQueryParams(com.helger.peppol.domain.SMPQueryParams) StopWatch(com.helger.commons.timing.StopWatch) HCHR(com.helger.html.hc.html.grouping.HCHR) InternalErrorBuilder(com.helger.photon.core.interror.InternalErrorBuilder) GenericJAXBMarshaller(com.helger.jaxb.GenericJAXBMarshaller) X509Certificate(java.security.cert.X509Certificate) WebPageExecutionContext(com.helger.photon.uicore.page.WebPageExecutionContext) PeppolIdentifierHelper(com.helger.peppolid.peppol.PeppolIdentifierHelper) BootstrapLinkButton(com.helger.photon.bootstrap4.button.BootstrapLinkButton) URL(java.net.URL) LoggerFactory(org.slf4j.LoggerFactory) SimpleURL(com.helger.commons.url.SimpleURL) PDIdentifier(com.helger.pd.businesscard.generic.PDIdentifier) Locale(java.util.Locale) RequestFieldBoolean(com.helger.photon.core.form.RequestFieldBoolean) BootstrapErrorBox(com.helger.photon.bootstrap4.alert.BootstrapErrorBox) CCSSValue(com.helger.css.propertyvalue.CCSSValue) EPeppolCertificateCheckResult(com.helger.peppol.utils.EPeppolCertificateCheckResult) SMPClientBadResponseException(com.helger.smpclient.exception.SMPClientBadResponseException) XMLOffsetDateTime(com.helger.commons.datetime.XMLOffsetDateTime) JAXBException(javax.xml.bind.JAXBException) EHCFormMethod(com.helger.html.hc.html.forms.EHCFormMethod) ICommonsOrderedSet(com.helger.commons.collection.impl.ICommonsOrderedSet) CertificateHelper(com.helger.security.certificate.CertificateHelper) OffsetDateTime(java.time.OffsetDateTime) AbstractAppWebPage(com.helger.peppol.ui.page.AbstractAppWebPage) HttpGet(org.apache.http.client.methods.HttpGet) CountryCache(com.helger.commons.locale.country.CountryCache) LocalDate(java.time.LocalDate) AppCommonUI(com.helger.peppol.ui.AppCommonUI) SMPClientException(com.helger.smpclient.exception.SMPClientException) PDBusinessEntity(com.helger.pd.businesscard.generic.PDBusinessEntity) HCH3(com.helger.html.hc.html.sections.HCH3) SMPClientReadOnly(com.helger.smpclient.peppol.SMPClientReadOnly) SimpleProcessIdentifier(com.helger.peppolid.simple.process.SimpleProcessIdentifier) HCUL(com.helger.html.hc.html.grouping.HCUL) PPMetaManager(com.helger.peppol.app.mgr.PPMetaManager) BootstrapTable(com.helger.photon.bootstrap4.table.BootstrapTable) ARecord(org.xbill.DNS.ARecord) HCPrismJS(com.helger.photon.uictrls.prism.HCPrismJS) HCCheckBox(com.helger.html.hc.html.forms.HCCheckBox) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier) Nonnull(javax.annotation.Nonnull) HCH4(com.helger.html.hc.html.sections.HCH4) Record(org.xbill.DNS.Record) HCNodeList(com.helger.html.hc.impl.HCNodeList) IRequestWebScopeWithoutResponse(com.helger.web.scope.IRequestWebScopeWithoutResponse) HCLI(com.helger.html.hc.html.grouping.HCLI) Logger(org.slf4j.Logger) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) CommonsLinkedHashSet(com.helger.commons.collection.impl.CommonsLinkedHashSet) CertificateException(java.security.cert.CertificateException) SimpleIdentifierFactory(com.helger.peppolid.factory.SimpleIdentifierFactory) XMLWriter(com.helger.xml.serialize.write.XMLWriter) HttpClientManager(com.helger.httpclient.HttpClientManager) EBootstrapButtonSize(com.helger.photon.bootstrap4.button.EBootstrapButtonSize) Consumer(java.util.function.Consumer) Type(org.xbill.DNS.Type) EFamFamFlagIcon(com.helger.photon.uictrls.famfam.EFamFamFlagIcon) Element(org.w3c.dom.Element) URLHelper(com.helger.commons.url.URLHelper) PeppolCertificateChecker(com.helger.peppol.utils.PeppolCertificateChecker) EPrismLanguage(com.helger.photon.uictrls.prism.EPrismLanguage) PDContact(com.helger.pd.businesscard.generic.PDContact) SMPClientReadOnly(com.helger.smpclient.peppol.SMPClientReadOnly) HCNodeList(com.helger.html.hc.impl.HCNodeList) ResponseHandlerByteArray(com.helger.httpclient.response.ResponseHandlerByteArray) HCH4(com.helger.html.hc.html.sections.HCH4) HCH3(com.helger.html.hc.html.sections.HCH3) IDocumentTypeIdentifier(com.helger.peppolid.IDocumentTypeIdentifier) CertificateException(java.security.cert.CertificateException) PDTToString(com.helger.commons.datetime.PDTToString) GenericJAXBMarshaller(com.helger.jaxb.GenericJAXBMarshaller) SMPClientBadResponseException(com.helger.smpclient.exception.SMPClientBadResponseException) InternalErrorBuilder(com.helger.photon.core.interror.InternalErrorBuilder) IHCLI(com.helger.html.hc.html.grouping.IHCLI) HCLI(com.helger.html.hc.html.grouping.HCLI) Lookup(org.xbill.DNS.Lookup) PDIdentifier(com.helger.pd.businesscard.generic.PDIdentifier) EPeppolCertificateCheckResult(com.helger.peppol.utils.EPeppolCertificateCheckResult) BootstrapErrorBox(com.helger.photon.bootstrap4.alert.BootstrapErrorBox) JAXBException(javax.xml.bind.JAXBException) X509Certificate(java.security.cert.X509Certificate) PDContact(com.helger.pd.businesscard.generic.PDContact) SMPQueryParams(com.helger.peppol.domain.SMPQueryParams) BootstrapTable(com.helger.photon.bootstrap4.table.BootstrapTable) XMLOffsetDateTime(com.helger.commons.datetime.XMLOffsetDateTime) OffsetDateTime(java.time.OffsetDateTime) SMPClientException(com.helger.smpclient.exception.SMPClientException) InetAddress(java.net.InetAddress) CommonsTreeMap(com.helger.commons.collection.impl.CommonsTreeMap) Map(java.util.Map) ICommonsSortedMap(com.helger.commons.collection.impl.ICommonsSortedMap) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier) TextParseException(org.xbill.DNS.TextParseException) PDBusinessCard(com.helger.pd.businesscard.generic.PDBusinessCard) Element(org.w3c.dom.Element) HttpGet(org.apache.http.client.methods.HttpGet) ISMLConfiguration(com.helger.peppol.domain.ISMLConfiguration) URL(java.net.URL) SimpleURL(com.helger.commons.url.SimpleURL) ISMLConfigurationManager(com.helger.peppol.app.mgr.ISMLConfigurationManager) ARecord(org.xbill.DNS.ARecord) HttpClientManager(com.helger.httpclient.HttpClientManager) ARecord(org.xbill.DNS.ARecord) Record(org.xbill.DNS.Record) UnknownHostException(java.net.UnknownHostException) HCHR(com.helger.html.hc.html.grouping.HCHR) HCTextArea(com.helger.html.hc.html.forms.HCTextArea) HCPrismJS(com.helger.photon.uictrls.prism.HCPrismJS) BDXRClientReadOnly(com.helger.smpclient.bdxr1.BDXRClientReadOnly) CommonsTreeMap(com.helger.commons.collection.impl.CommonsTreeMap) TextParseException(org.xbill.DNS.TextParseException) UnknownHostException(java.net.UnknownHostException) SMPClientBadResponseException(com.helger.smpclient.exception.SMPClientBadResponseException) JAXBException(javax.xml.bind.JAXBException) SMPClientException(com.helger.smpclient.exception.SMPClientException) CertificateException(java.security.cert.CertificateException) StopWatch(com.helger.commons.timing.StopWatch) IRequestWebScopeWithoutResponse(com.helger.web.scope.IRequestWebScopeWithoutResponse) IPV4Addr(com.helger.dns.ip.IPV4Addr) HCUL(com.helger.html.hc.html.grouping.HCUL) EFamFamFlagIcon(com.helger.photon.uictrls.famfam.EFamFamFlagIcon) PDName(com.helger.pd.businesscard.generic.PDName) PDBusinessEntity(com.helger.pd.businesscard.generic.PDBusinessEntity) CommonsLinkedHashSet(com.helger.commons.collection.impl.CommonsLinkedHashSet) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) IHCNode(com.helger.html.hc.IHCNode)

Example 3 with GenericJAXBMarshaller

use of com.helger.jaxb.GenericJAXBMarshaller 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)

Aggregations

GenericJAXBMarshaller (com.helger.jaxb.GenericJAXBMarshaller)3 StringHelper (com.helger.commons.string.StringHelper)2 CCSSProperties (com.helger.css.property.CCSSProperties)2 HCEdit (com.helger.html.hc.html.forms.HCEdit)2 HCTextArea (com.helger.html.hc.html.forms.HCTextArea)2 HCDiv (com.helger.html.hc.html.grouping.HCDiv)2 HCNodeList (com.helger.html.hc.impl.HCNodeList)2 AppCommonUI (com.helger.peppol.ui.AppCommonUI)2 EPeppolCertificateCheckResult (com.helger.peppol.utils.EPeppolCertificateCheckResult)2 IDocumentTypeIdentifier (com.helger.peppolid.IDocumentTypeIdentifier)2 IParticipantIdentifier (com.helger.peppolid.IParticipantIdentifier)2 IIdentifierFactory (com.helger.peppolid.factory.IIdentifierFactory)2 PeppolIdentifierHelper (com.helger.peppolid.peppol.PeppolIdentifierHelper)2 BootstrapForm (com.helger.photon.bootstrap4.form.BootstrapForm)2 BootstrapFormGroup (com.helger.photon.bootstrap4.form.BootstrapFormGroup)2 FormErrorList (com.helger.photon.core.form.FormErrorList)2 RequestField (com.helger.photon.core.form.RequestField)2 CPageParam (com.helger.photon.uicore.css.CPageParam)2 WebPageExecutionContext (com.helger.photon.uicore.page.WebPageExecutionContext)2 EPrismLanguage (com.helger.photon.uictrls.prism.EPrismLanguage)2