Search in sources :

Example 11 with ESuccess

use of com.helger.commons.state.ESuccess in project phoss-smp by phax.

the class SMPServiceInformationManagerMongoDB method mergeSMPServiceInformation.

@Nonnull
public ESuccess mergeSMPServiceInformation(@Nonnull final ISMPServiceInformation aSMPServiceInformationObj) {
    final SMPServiceInformation aSMPServiceInformation = (SMPServiceInformation) aSMPServiceInformationObj;
    ValueEnforcer.notNull(aSMPServiceInformation, "ServiceInformation");
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("mergeSMPServiceInformation (" + aSMPServiceInformationObj + ")");
    // Check for an update
    boolean bChangedExisting = false;
    final ISMPServiceInformation aOldInformation = getSMPServiceInformationOfServiceGroupAndDocumentType(aSMPServiceInformation.getServiceGroup(), aSMPServiceInformation.getDocumentTypeIdentifier());
    if (aOldInformation != null) {
        // This is not true for the REST API
        if (EqualsHelper.identityEqual(aOldInformation, aSMPServiceInformation))
            bChangedExisting = true;
    }
    if (bChangedExisting) {
        // Edit existing
        getCollection().replaceOne(new Document(BSON_ID, aOldInformation.getID()), toBson(aSMPServiceInformation));
        AuditHelper.onAuditModifySuccess(SMPServiceInformation.OT, "set-all", aOldInformation.getID(), aOldInformation.getServiceGroupID(), aOldInformation.getDocumentTypeIdentifier().getURIEncoded(), aOldInformation.getAllProcesses(), aOldInformation.getExtensionsAsString());
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("mergeSMPServiceInformation - success - updated");
        m_aCBs.forEach(x -> x.onSMPServiceInformationUpdated(aSMPServiceInformation));
    } else {
        // (Optionally delete the old one and) create the new one
        boolean bRemovedOld = false;
        if (aOldInformation != null) {
            // Delete only if present
            final DeleteResult aDR = getCollection().deleteOne(new Document(BSON_ID, aOldInformation.getID()));
            bRemovedOld = aDR.wasAcknowledged() && aDR.getDeletedCount() > 0;
        }
        if (!getCollection().insertOne(toBson(aSMPServiceInformation)).wasAcknowledged())
            throw new IllegalStateException("Failed to insert into MongoDB Collection");
        if (bRemovedOld) {
            AuditHelper.onAuditDeleteSuccess(SMPServiceInformation.OT, aOldInformation.getID(), aOldInformation.getServiceGroupID(), aOldInformation.getDocumentTypeIdentifier().getURIEncoded());
        } else if (aOldInformation != null) {
            AuditHelper.onAuditDeleteFailure(SMPServiceInformation.OT, aOldInformation.getID(), aOldInformation.getServiceGroupID(), aOldInformation.getDocumentTypeIdentifier().getURIEncoded());
        }
        AuditHelper.onAuditCreateSuccess(SMPServiceInformation.OT, aSMPServiceInformation.getID(), aSMPServiceInformation.getServiceGroupID(), aSMPServiceInformation.getDocumentTypeIdentifier().getURIEncoded(), aSMPServiceInformation.getAllProcesses(), aSMPServiceInformation.getExtensionsAsString());
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("mergeSMPServiceInformation - success - created");
        if (bChangedExisting)
            m_aCBs.forEach(x -> x.onSMPServiceInformationUpdated(aSMPServiceInformation));
        else
            m_aCBs.forEach(x -> x.onSMPServiceInformationCreated(aSMPServiceInformation));
    }
    return ESuccess.SUCCESS;
}
Also used : Document(org.bson.Document) ESuccess(com.helger.commons.state.ESuccess) Nonnegative(javax.annotation.Nonnegative) IDocumentTypeIdentifier(com.helger.peppolid.IDocumentTypeIdentifier) Date(java.util.Date) LoggerFactory(org.slf4j.LoggerFactory) EChange(com.helger.commons.state.EChange) SMPServiceInformation(com.helger.phoss.smp.domain.serviceinfo.SMPServiceInformation) CallbackList(com.helger.commons.callback.CallbackList) IProcessIdentifier(com.helger.peppolid.IProcessIdentifier) Filters(com.mongodb.client.model.Filters) IIdentifierFactory(com.helger.peppolid.factory.IIdentifierFactory) ISMPServiceGroup(com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroup) SMPProcess(com.helger.phoss.smp.domain.serviceinfo.SMPProcess) ISMPServiceInformationCallback(com.helger.phoss.smp.domain.serviceinfo.ISMPServiceInformationCallback) ReturnsMutableCopy(com.helger.commons.annotation.ReturnsMutableCopy) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) SMPEndpoint(com.helger.phoss.smp.domain.serviceinfo.SMPEndpoint) Logger(org.slf4j.Logger) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) StringHelper(com.helger.commons.string.StringHelper) ISMPProcess(com.helger.phoss.smp.domain.serviceinfo.ISMPProcess) XMLOffsetDateTime(com.helger.commons.datetime.XMLOffsetDateTime) EqualsHelper(com.helger.commons.equals.EqualsHelper) ValueEnforcer(com.helger.commons.ValueEnforcer) Consumer(java.util.function.Consumer) AuditHelper(com.helger.photon.audit.AuditHelper) List(java.util.List) TypeConverter(com.helger.commons.typeconvert.TypeConverter) ISMPServiceInformationManager(com.helger.phoss.smp.domain.serviceinfo.ISMPServiceInformationManager) ICommonsList(com.helger.commons.collection.impl.ICommonsList) ISMPServiceInformation(com.helger.phoss.smp.domain.serviceinfo.ISMPServiceInformation) ISMPEndpoint(com.helger.phoss.smp.domain.serviceinfo.ISMPEndpoint) ReturnsMutableObject(com.helger.commons.annotation.ReturnsMutableObject) DeleteResult(com.mongodb.client.result.DeleteResult) ISMPTransportProfile(com.helger.peppol.smp.ISMPTransportProfile) ISMPServiceGroupManager(com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroupManager) SMPServiceInformation(com.helger.phoss.smp.domain.serviceinfo.SMPServiceInformation) ISMPServiceInformation(com.helger.phoss.smp.domain.serviceinfo.ISMPServiceInformation) ISMPServiceInformation(com.helger.phoss.smp.domain.serviceinfo.ISMPServiceInformation) Document(org.bson.Document) DeleteResult(com.mongodb.client.result.DeleteResult) Nonnull(javax.annotation.Nonnull)

Example 12 with ESuccess

use of com.helger.commons.state.ESuccess in project phoss-smp by phax.

the class APIExecutorServiceMetadataPut method invokeAPI.

public void invokeAPI(@Nonnull final IAPIDescriptor aAPIDescriptor, @Nonnull @Nonempty final String sPath, @Nonnull final Map<String, String> aPathVariables, @Nonnull final IRequestWebScopeWithoutResponse aRequestScope, @Nonnull final UnifiedResponse aUnifiedResponse) throws Exception {
    final String sPathServiceGroupID = aPathVariables.get(SMPRestFilter.PARAM_SERVICE_GROUP_ID);
    final ISMPServerAPIDataProvider aDataProvider = new SMPRestDataProvider(aRequestScope, sPathServiceGroupID);
    // Is the writable API disabled?
    if (SMPMetaManager.getSettings().isRESTWritableAPIDisabled()) {
        throw new SMPPreconditionFailedException("The writable REST API is disabled. saveServiceRegistration will not be executed", aDataProvider.getCurrentURI());
    }
    // Parse main payload
    final byte[] aPayload = StreamHelper.getAllBytes(aRequestScope.getRequest().getInputStream());
    final Document aServiceMetadataDoc = DOMReader.readXMLDOM(aPayload);
    if (aServiceMetadataDoc == null) {
        throw new SMPBadRequestException("Failed to parse provided payload as XML", aDataProvider.getCurrentURI());
    }
    final String sDocumentTypeID = aPathVariables.get(SMPRestFilter.PARAM_DOCUMENT_TYPE_ID);
    final BasicAuthClientCredentials aBasicAuth = getMandatoryAuth(aRequestScope.headers());
    ESuccess eSuccess = ESuccess.FAILURE;
    switch(SMPServerConfiguration.getRESTType()) {
        case PEPPOL:
            {
                final com.helger.xsds.peppol.smp1.ServiceMetadataType aServiceMetadata = new SMPMarshallerServiceMetadataType(XML_SCHEMA_VALIDATION).read(aServiceMetadataDoc);
                if (aServiceMetadata != null) {
                    eSuccess = new SMPServerAPI(aDataProvider).saveServiceRegistration(sPathServiceGroupID, sDocumentTypeID, aServiceMetadata, aBasicAuth);
                }
                break;
            }
        case OASIS_BDXR_V1:
            {
                final com.helger.xsds.bdxr.smp1.ServiceMetadataType aServiceMetadata = new BDXR1MarshallerServiceMetadataType(XML_SCHEMA_VALIDATION).read(aServiceMetadataDoc);
                if (aServiceMetadata != null) {
                    eSuccess = new BDXR1ServerAPI(aDataProvider).saveServiceRegistration(sPathServiceGroupID, sDocumentTypeID, aServiceMetadata, aBasicAuth);
                }
                break;
            }
        default:
            throw new UnsupportedOperationException("Unsupported REST type specified!");
    }
    if (eSuccess.isFailure())
        aUnifiedResponse.setStatus(CHttp.HTTP_INTERNAL_SERVER_ERROR);
    else
        aUnifiedResponse.setStatus(CHttp.HTTP_OK).disableCaching();
}
Also used : ESuccess(com.helger.commons.state.ESuccess) SMPMarshallerServiceMetadataType(com.helger.smpclient.peppol.marshal.SMPMarshallerServiceMetadataType) SMPBadRequestException(com.helger.phoss.smp.exception.SMPBadRequestException) SMPServerAPI(com.helger.phoss.smp.restapi.SMPServerAPI) BDXR1ServerAPI(com.helger.phoss.smp.restapi.BDXR1ServerAPI) Document(org.w3c.dom.Document) BDXR1MarshallerServiceMetadataType(com.helger.smpclient.bdxr1.marshal.BDXR1MarshallerServiceMetadataType) SMPPreconditionFailedException(com.helger.phoss.smp.exception.SMPPreconditionFailedException) BasicAuthClientCredentials(com.helger.http.basicauth.BasicAuthClientCredentials) ISMPServerAPIDataProvider(com.helger.phoss.smp.restapi.ISMPServerAPIDataProvider) BDXR1MarshallerServiceMetadataType(com.helger.smpclient.bdxr1.marshal.BDXR1MarshallerServiceMetadataType) SMPMarshallerServiceMetadataType(com.helger.smpclient.peppol.marshal.SMPMarshallerServiceMetadataType)

Example 13 with ESuccess

use of com.helger.commons.state.ESuccess in project phase4 by phax.

the class SOAPHeaderElementProcessorWSS4J method processHeaderElement.

@Nonnull
public ESuccess processHeaderElement(@Nonnull final Document aSOAPDoc, @Nonnull final Element aSecurityNode, @Nonnull final ICommonsList<WSS4JAttachment> aAttachments, @Nonnull final AS4MessageState aState, @Nonnull final ErrorList aErrorList) {
    IPMode aPMode = aState.getPMode();
    if (aPMode == null)
        aPMode = m_aFallbackPMode;
    // Safety Check
    if (aPMode == null)
        throw new IllegalStateException("No PMode contained in AS4 state - seems like Ebms3 Messaging header is missing!");
    // Default is Leg 1, gets overwritten when a reference to a message id
    // exists and then uses leg2
    final Locale aLocale = aState.getLocale();
    PModeLeg aPModeLeg = aPMode.getLeg1();
    final Ebms3UserMessage aUserMessage = aState.getEbmsUserMessage();
    if (aUserMessage != null && StringHelper.hasText(aUserMessage.getMessageInfo().getRefToMessageId()))
        aPModeLeg = aPMode.getLeg2();
    // Does security - leg part checks if not <code>null</code>
    if (aPModeLeg.getSecurity() != null) {
        // Get Signature Algorithm
        Element aSignedNode = XMLHelper.getFirstChildElementOfName(aSecurityNode, CAS4.DS_NS, "Signature");
        if (aSignedNode != null) {
            // Go through the security nodes to find the algorithm attribute
            aSignedNode = XMLHelper.getFirstChildElementOfName(aSignedNode, CAS4.DS_NS, "SignedInfo");
            final Element aSignatureAlgorithm = XMLHelper.getFirstChildElementOfName(aSignedNode, CAS4.DS_NS, "SignatureMethod");
            String sAlgorithm = aSignatureAlgorithm == null ? null : aSignatureAlgorithm.getAttribute("Algorithm");
            final ECryptoAlgorithmSign eSignAlgo = ECryptoAlgorithmSign.getFromURIOrNull(sAlgorithm);
            if (eSignAlgo == null) {
                LOGGER.error("Error processing the Security Header, your signing algorithm '" + sAlgorithm + "' is incorrect. Expected one of the following '" + Arrays.asList(ECryptoAlgorithmSign.values()) + "' algorithms");
                aErrorList.add(EEbmsError.EBMS_FAILED_AUTHENTICATION.getAsError(aLocale));
                return ESuccess.FAILURE;
            }
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Using signature algorithm " + eSignAlgo);
            // Get Signature Digest Algorithm
            aSignedNode = XMLHelper.getFirstChildElementOfName(aSignedNode, CAS4.DS_NS, "Reference");
            aSignedNode = XMLHelper.getFirstChildElementOfName(aSignedNode, CAS4.DS_NS, "DigestMethod");
            sAlgorithm = aSignedNode == null ? null : aSignedNode.getAttribute("Algorithm");
            final ECryptoAlgorithmSignDigest eSignDigestAlgo = ECryptoAlgorithmSignDigest.getFromURIOrNull(sAlgorithm);
            if (eSignDigestAlgo == null) {
                LOGGER.error("Error processing the Security Header, your signing digest algorithm is incorrect. Expected one of the following'" + Arrays.toString(ECryptoAlgorithmSignDigest.values()) + "' algorithms");
                aErrorList.add(EEbmsError.EBMS_FAILED_AUTHENTICATION.getAsError(aLocale));
                return ESuccess.FAILURE;
            }
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Using signature digest algorithm " + eSignDigestAlgo);
        }
        // Check attachment validity only if a PartInfo element is available
        if (aUserMessage != null) {
            final boolean bBodyPayloadPresent = aState.isSoapBodyPayloadPresent();
            // Check if Attachment IDs are the same
            for (int i = 0; i < aAttachments.size(); i++) {
                String sAttachmentID = aAttachments.get(i).getHeaders().get(AttachmentUtils.MIME_HEADER_CONTENT_ID);
                if (StringHelper.hasNoText(sAttachmentID)) {
                    LOGGER.error("The provided attachment ID in the 'Content-ID' header may not be empty.");
                    aErrorList.add(EEbmsError.EBMS_VALUE_INCONSISTENT.getAsError(aLocale));
                    return ESuccess.FAILURE;
                }
                if (!sAttachmentID.startsWith(WSS4JAttachment.CONTENT_ID_PREFIX)) {
                    LOGGER.error("The provided attachment ID '" + sAttachmentID + "' in the 'Content-ID' header does not start with the required prefix '" + WSS4JAttachment.CONTENT_ID_PREFIX + "'");
                    aErrorList.add(EEbmsError.EBMS_VALUE_INCONSISTENT.getAsError(aLocale));
                    return ESuccess.FAILURE;
                }
                if (!sAttachmentID.endsWith(WSS4JAttachment.CONTENT_ID_SUFFIX)) {
                    LOGGER.error("The provided attachment ID '" + sAttachmentID + "' in the 'Content-ID' header does not end with the required suffix '" + WSS4JAttachment.CONTENT_ID_SUFFIX + "'");
                    aErrorList.add(EEbmsError.EBMS_VALUE_INCONSISTENT.getAsError(aLocale));
                    return ESuccess.FAILURE;
                }
                // Strip prefix and suffix
                sAttachmentID = sAttachmentID.substring(WSS4JAttachment.CONTENT_ID_PREFIX.length(), sAttachmentID.length() - WSS4JAttachment.CONTENT_ID_SUFFIX.length());
                // Add +1 because the payload has index 0
                final String sHref = aUserMessage.getPayloadInfo().getPartInfoAtIndex((bBodyPayloadPresent ? 1 : 0) + i).getHref();
                if (!sHref.contains(sAttachmentID)) {
                    LOGGER.error("The usermessage part information '" + sHref + "' does not reference the respective attachment ID '" + sAttachmentID + "'");
                    aErrorList.add(EEbmsError.EBMS_VALUE_INCONSISTENT.getAsError(aLocale));
                    return ESuccess.FAILURE;
                }
            }
        }
        final ESuccess eSuccess;
        if (AS4Configuration.isWSS4JSynchronizedSecurity()) {
            // Use static WSSConfig creation
            eSuccess = WSSSynchronizer.call(() -> _verifyAndDecrypt(aSOAPDoc, aAttachments, aState, aErrorList, WSSConfigManager::createStaticWSSConfig));
        } else {
            // Use instance WSSConfig creation
            eSuccess = _verifyAndDecrypt(aSOAPDoc, aAttachments, aState, aErrorList, WSSConfigManager.getInstance()::createWSSConfig);
        }
        if (eSuccess.isFailure())
            return ESuccess.FAILURE;
    }
    return ESuccess.SUCCESS;
}
Also used : Locale(java.util.Locale) ESuccess(com.helger.commons.state.ESuccess) PModeLeg(com.helger.phase4.model.pmode.leg.PModeLeg) Element(org.w3c.dom.Element) IPMode(com.helger.phase4.model.pmode.IPMode) ECryptoAlgorithmSignDigest(com.helger.phase4.crypto.ECryptoAlgorithmSignDigest) WSSConfigManager(com.helger.phase4.wss.WSSConfigManager) Ebms3UserMessage(com.helger.phase4.ebms3header.Ebms3UserMessage) ECryptoAlgorithmSign(com.helger.phase4.crypto.ECryptoAlgorithmSign) Nonnull(javax.annotation.Nonnull)

Example 14 with ESuccess

use of com.helger.commons.state.ESuccess in project ph-schematron by phax.

the class SchematronHelper method _recursiveResolveAllSchematronIncludes.

@SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE")
@Nonnull
private static ESuccess _recursiveResolveAllSchematronIncludes(@Nonnull final IMicroElement eRoot, @Nonnull final IReadableResource aResource, @Nullable final ISAXReaderSettings aSettings, @Nonnull final ISchematronErrorHandler aErrorHandler, final boolean bLenient) {
    if (eRoot != null) {
        final DefaultSchematronIncludeResolver aIncludeResolver = new DefaultSchematronIncludeResolver(aResource);
        for (final IMicroElement aElement : eRoot.getAllChildElementsRecursive()) if (isValidSchematronNS(aElement.getNamespaceURI(), bLenient) && aElement.getLocalName().equals(CSchematronXML.ELEMENT_INCLUDE)) {
            String sHref = aElement.getAttributeValue(CSchematronXML.ATTR_HREF);
            try {
                final int nHashIndex = sHref.indexOf('#');
                String sAnchor = null;
                if (nHashIndex >= 0) {
                    sAnchor = sHref.substring(nHashIndex + 1);
                    sHref = sHref.substring(0, nHashIndex);
                }
                final IReadableResource aIncludeRes = aIncludeResolver.getResolvedSchematronResource(sHref);
                if (aIncludeRes == null) {
                    aErrorHandler.handleError(SingleError.builderError().errorLocation(new SimpleLocation(aResource.getPath())).errorText("Failed to resolve include '" + sHref + "'").build());
                    return ESuccess.FAILURE;
                }
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("Resolved '" + sHref + "' relative to '" + aIncludeResolver.getBaseHref() + "' as '" + aIncludeRes.getPath() + "'");
                // Read XML to be included
                final IMicroDocument aIncludedDoc = MicroReader.readMicroXML(aIncludeRes, aSettings);
                if (aIncludedDoc == null) {
                    aErrorHandler.handleError(SingleError.builderError().errorLocation(new SimpleLocation(aResource.getPath())).errorText("Failed to parse include " + aIncludeRes).build());
                    return ESuccess.FAILURE;
                }
                IMicroElement aIncludedContent;
                if (sAnchor == null) {
                    // no anchor present - include the whole document
                    // Return the document element
                    aIncludedContent = aIncludedDoc.getDocumentElement();
                } else {
                    final String sFinalAnchor = sAnchor;
                    final Wrapper<IMicroElement> aMatch = new Wrapper<>();
                    // Also include the root element in the search
                    ChildrenProviderHierarchyVisitor.visitFrom(aIncludedDoc.getDocumentElement(), new DefaultHierarchyVisitorCallback<IMicroNode>() {

                        @Override
                        public EHierarchyVisitorReturn onItemBeforeChildren(final IMicroNode aItem) {
                            if (aItem.isElement()) {
                                final IMicroElement aCurElement = (IMicroElement) aItem;
                                final String sID = aCurElement.getAttributeValue("id");
                                if (sFinalAnchor.equals(sID))
                                    aMatch.set(aCurElement);
                            }
                            return EHierarchyVisitorReturn.CONTINUE;
                        }
                    }, true);
                    aIncludedContent = aMatch.get();
                    if (aIncludedContent == null) {
                        aErrorHandler.handleError(SingleError.builderWarn().errorLocation(new SimpleLocation(aResource.getPath())).errorText("Failed to resolve an element with the ID '" + sAnchor + "' in " + aIncludeRes + "! Therefore including the whole document!").build());
                        aIncludedContent = aIncludedDoc.getDocumentElement();
                    }
                }
                // Important to detach from parent!
                aIncludedContent.detachFromParent();
                // It is okay to include sthg else
                if (false) {
                    // Check for correct namespace URI of included content
                    if (!isValidSchematronNS(aIncludedContent.getNamespaceURI(), bLenient)) {
                        aErrorHandler.handleError(SingleError.builderError().errorLocation(new SimpleLocation(aResource.getPath())).errorText("The included resource " + aIncludeRes + " contains the wrong XML namespace URI '" + aIncludedContent.getNamespaceURI() + "' but was expected to have: " + StringHelper.getImplodedMapped(", ", getAllValidSchematronNS(bLenient), x -> "'" + x + "'")).build());
                        return ESuccess.FAILURE;
                    }
                }
                // Check that not a whole Schema but only a part is included
                if (isValidSchematronNS(aIncludedContent.getNamespaceURI(), bLenient) && CSchematronXML.ELEMENT_SCHEMA.equals(aIncludedContent.getLocalName())) {
                    aErrorHandler.handleError(SingleError.builderWarn().errorLocation(new SimpleLocation(aResource.getPath())).errorText("The included resource " + aIncludeRes + " seems to be a complete schema. To includes parts of a schema the respective element must be the root element of the included resource.").build());
                }
                // Recursive resolve includes
                if (_recursiveResolveAllSchematronIncludes(aIncludedContent, aIncludeRes, aSettings, aErrorHandler, bLenient).isFailure())
                    return ESuccess.FAILURE;
                // Now replace "include" element with content in MicroDOM
                aElement.getParent().replaceChild(aElement, aIncludedContent);
            } catch (final IOException ex) {
                aErrorHandler.handleError(SingleError.builderError().errorLocation(new SimpleLocation(aResource.getPath())).errorText("Failed to read include '" + sHref + "'").linkedException(ex).build());
                return ESuccess.FAILURE;
            }
        }
    }
    return ESuccess.SUCCESS;
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) ESuccess(com.helger.commons.state.ESuccess) ErrorList(com.helger.commons.error.list.ErrorList) LoggerFactory(org.slf4j.LoggerFactory) IMicroDocument(com.helger.xml.microdom.IMicroDocument) Source(javax.xml.transform.Source) ISAXReaderSettings(com.helger.xml.serialize.read.ISAXReaderSettings) SVRLHelper(com.helger.schematron.svrl.SVRLHelper) Nonempty(com.helger.commons.annotation.Nonempty) ChildrenProviderHierarchyVisitor(com.helger.commons.hierarchy.visit.ChildrenProviderHierarchyVisitor) IMicroElement(com.helger.xml.microdom.IMicroElement) Node(org.w3c.dom.Node) ReturnsMutableCopy(com.helger.commons.annotation.ReturnsMutableCopy) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) InputSource(org.xml.sax.InputSource) EHierarchyVisitorReturn(com.helger.commons.hierarchy.visit.EHierarchyVisitorReturn) DefaultSchematronIncludeResolver(com.helger.schematron.resolve.DefaultSchematronIncludeResolver) Logger(org.slf4j.Logger) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) StringHelper(com.helger.commons.string.StringHelper) IReadableResource(com.helger.commons.io.resource.IReadableResource) InputSourceFactory(com.helger.xml.sax.InputSourceFactory) IOException(java.io.IOException) SVRLResourceError(com.helger.schematron.svrl.SVRLResourceError) DefaultHierarchyVisitorCallback(com.helger.commons.hierarchy.visit.DefaultHierarchyVisitorCallback) ValueEnforcer(com.helger.commons.ValueEnforcer) IMicroNode(com.helger.xml.microdom.IMicroNode) SingleError(com.helger.commons.error.SingleError) ICommonsList(com.helger.commons.collection.impl.ICommonsList) Wrapper(com.helger.commons.wrapper.Wrapper) IHasInputStream(com.helger.commons.io.IHasInputStream) SchematronOutputType(com.helger.schematron.svrl.jaxb.SchematronOutputType) MicroReader(com.helger.xml.microdom.serialize.MicroReader) Immutable(javax.annotation.concurrent.Immutable) IErrorList(com.helger.commons.error.list.IErrorList) SimpleLocation(com.helger.commons.location.SimpleLocation) SVRLFailedAssert(com.helger.schematron.svrl.SVRLFailedAssert) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) PresentForCodeCoverage(com.helger.commons.annotation.PresentForCodeCoverage) Wrapper(com.helger.commons.wrapper.Wrapper) IMicroElement(com.helger.xml.microdom.IMicroElement) IReadableResource(com.helger.commons.io.resource.IReadableResource) IMicroNode(com.helger.xml.microdom.IMicroNode) SimpleLocation(com.helger.commons.location.SimpleLocation) IMicroDocument(com.helger.xml.microdom.IMicroDocument) IOException(java.io.IOException) DefaultHierarchyVisitorCallback(com.helger.commons.hierarchy.visit.DefaultHierarchyVisitorCallback) DefaultSchematronIncludeResolver(com.helger.schematron.resolve.DefaultSchematronIncludeResolver) Nonnull(javax.annotation.Nonnull) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 15 with ESuccess

use of com.helger.commons.state.ESuccess in project phoss-directory by phax.

the class PageSecureIndexImport method fillContent.

@Override
protected void fillContent(final WebPageExecutionContext aWPEC) {
    final HCNodeList aNodeList = aWPEC.getNodeList();
    final Locale aDisplayLocale = aWPEC.getDisplayLocale();
    final IIdentifierFactory aIdentifierFactory = PDMetaManager.getIdentifierFactory();
    final FormErrorList aFormErrors = new FormErrorList();
    {
        final IPDBusinessCardProvider aBCProv = PDMetaManager.getBusinessCardProvider();
        if (aBCProv instanceof SMPBusinessCardProvider) {
            final SMPBusinessCardProvider aSMPBCProv = (SMPBusinessCardProvider) aBCProv;
            if (aSMPBCProv.isFixedSMP()) {
                aNodeList.addChild(info("Fixed SMP URI " + aSMPBCProv.getFixedSMPURI() + " is used."));
            } else {
                aNodeList.addChild(info("The following SMLs are crawled for entries: " + StringHelper.getImplodedMapped(", ", aSMPBCProv.getAllSMLsToUse(), ISMLInfo::getDisplayName)));
            }
        }
    }
    final boolean bIsFormSubmitted = aWPEC.hasAction(CPageParam.ACTION_PERFORM);
    if (bIsFormSubmitted) {
        final IFileItem aFile = aWPEC.params().getAsFileItem(FIELD_FILE);
        if (aFile == null || StringHelper.hasNoText(aFile.getName()))
            aFormErrors.addFieldError(FIELD_FILE, "No file was selected");
        if (aFormErrors.isEmpty()) {
            final HCNodeList aResultNL = new HCNodeList();
            final SAXReaderSettings aSettings = new SAXReaderSettings();
            aSettings.setFeatureValues(EXMLParserFeature.AVOID_DOS_SETTINGS);
            final CollectingSAXErrorHandler aErrorHandler = new CollectingSAXErrorHandler();
            aSettings.setErrorHandler(aErrorHandler);
            final ICommonsList<IParticipantIdentifier> aQueued = new CommonsArrayList<>();
            final ICommonsList<IParticipantIdentifier> aNotQueued = new CommonsArrayList<>();
            aSettings.setContentHandler(new DefaultHandler() {

                @Override
                public void startElement(final String sURI, final String sLocalName, final String sQName, final Attributes aAttributes) throws SAXException {
                    if (sQName.equals("participant")) {
                        final String sScheme = aAttributes.getValue("scheme");
                        final String sValue = aAttributes.getValue("value");
                        final IParticipantIdentifier aParticipantID = aIdentifierFactory.createParticipantIdentifier(sScheme, sValue);
                        if (aParticipantID != null) {
                            if (PDMetaManager.getIndexerMgr().queueWorkItem(aParticipantID, EIndexerWorkItemType.CREATE_UPDATE, "import-triggered", PDIndexerManager.HOST_LOCALHOST).isChanged()) {
                                aQueued.add(aParticipantID);
                            } else {
                                aNotQueued.add(aParticipantID);
                            }
                        } else
                            LOGGER.error("Failed to convert '" + sScheme + "' and '" + sValue + "' to a participant identifier");
                    }
                }
            });
            LOGGER.info("Importing participant IDs from '" + aFile.getNameSecure() + "'");
            final ESuccess eSuccess = SAXReader.readXMLSAX(new FileItemResource(aFile), aSettings);
            LOGGER.info("Finished reading XML file. Queued " + aQueued.size() + "; not queued: " + aNotQueued.size() + "; errors: " + aErrorHandler.getErrorList().size());
            // Some things may have been queued even in case of error
            if (aQueued.isNotEmpty()) {
                final HCUL aUL = new HCUL();
                for (final IParticipantIdentifier aPI : aQueued) aUL.addItem(aPI.getURIEncoded());
                aResultNL.addChild(success(div("The following identifiers were successfully queued for indexing:")).addChild(aUL));
            }
            if (aNotQueued.isNotEmpty()) {
                final HCUL aUL = new HCUL();
                for (final IParticipantIdentifier aPI : aNotQueued) aUL.addItem(aPI.getURIEncoded());
                aResultNL.addChild(warn(div("The following identifiers could not be queued (because they are already in the queue):")).addChild(aUL));
            }
            if (eSuccess.isFailure()) {
                final HCUL aUL = new HCUL();
                for (final IError aError : aErrorHandler.getErrorList()) {
                    final String sMsg = aError.getAsString(AppCommonUI.DEFAULT_LOCALE);
                    LOGGER.error("  " + sMsg);
                    aUL.addItem(sMsg);
                }
                aResultNL.addChild(error(div("Error parsing provided XML:")).addChild(aUL));
            }
            aWPEC.postRedirectGetInternal(aResultNL);
        }
    }
    final BootstrapForm aForm = aNodeList.addAndReturnChild(getUIHandler().createFormFileUploadSelf(aWPEC, bIsFormSubmitted));
    aForm.addFormGroup(new BootstrapFormGroup().setLabelMandatory("Import file").setCtrl(new BootstrapFileUpload(FIELD_FILE, aDisplayLocale)).setHelpText("Select a file that was created from a full XML export to index of all them manually.").setErrorList(aFormErrors.getListOfField(FIELD_FILE)));
    final BootstrapButtonToolbar aToolbar = aForm.addAndReturnChild(new BootstrapButtonToolbar(aWPEC));
    aToolbar.addHiddenField(CPageParam.PARAM_ACTION, CPageParam.ACTION_PERFORM);
    aToolbar.addSubmitButton("Import all", EDefaultIcon.YES);
}
Also used : Locale(java.util.Locale) HCNodeList(com.helger.html.hc.impl.HCNodeList) CollectingSAXErrorHandler(com.helger.xml.sax.CollectingSAXErrorHandler) ISMLInfo(com.helger.peppol.sml.ISMLInfo) FormErrorList(com.helger.photon.core.form.FormErrorList) Attributes(org.xml.sax.Attributes) SAXReaderSettings(com.helger.xml.serialize.read.SAXReaderSettings) SAXException(org.xml.sax.SAXException) BootstrapFileUpload(com.helger.photon.bootstrap4.uictrls.ext.BootstrapFileUpload) IFileItem(com.helger.web.fileupload.IFileItem) BootstrapButtonToolbar(com.helger.photon.bootstrap4.buttongroup.BootstrapButtonToolbar) IIdentifierFactory(com.helger.peppolid.factory.IIdentifierFactory) SMPBusinessCardProvider(com.helger.pd.indexer.businesscard.SMPBusinessCardProvider) ESuccess(com.helger.commons.state.ESuccess) IError(com.helger.commons.error.IError) FileItemResource(com.helger.web.fileupload.FileItemResource) DefaultHandler(org.xml.sax.helpers.DefaultHandler) BootstrapForm(com.helger.photon.bootstrap4.form.BootstrapForm) IPDBusinessCardProvider(com.helger.pd.indexer.businesscard.IPDBusinessCardProvider) HCUL(com.helger.html.hc.html.grouping.HCUL) BootstrapFormGroup(com.helger.photon.bootstrap4.form.BootstrapFormGroup) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier)

Aggregations

ESuccess (com.helger.commons.state.ESuccess)27 Nonnull (javax.annotation.Nonnull)15 ConstantPreparedStatementDataProvider (com.helger.db.jdbc.callback.ConstantPreparedStatementDataProvider)13 DBExecutor (com.helger.db.jdbc.executor.DBExecutor)13 Nullable (javax.annotation.Nullable)9 IParticipantIdentifier (com.helger.peppolid.IParticipantIdentifier)8 MutableBoolean (com.helger.commons.mutable.MutableBoolean)7 Wrapper (com.helger.commons.wrapper.Wrapper)7 CommonsArrayList (com.helger.commons.collection.impl.CommonsArrayList)6 EChange (com.helger.commons.state.EChange)6 IDocumentTypeIdentifier (com.helger.peppolid.IDocumentTypeIdentifier)6 ISMPServiceGroup (com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroup)6 ValueEnforcer (com.helger.commons.ValueEnforcer)5 ReturnsMutableCopy (com.helger.commons.annotation.ReturnsMutableCopy)5 ICommonsList (com.helger.commons.collection.impl.ICommonsList)5 StringHelper (com.helger.commons.string.StringHelper)5 IProcessIdentifier (com.helger.peppolid.IProcessIdentifier)5 Document (org.w3c.dom.Document)5 ReturnsMutableObject (com.helger.commons.annotation.ReturnsMutableObject)4 CallbackList (com.helger.commons.callback.CallbackList)4