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;
}
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();
}
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;
}
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;
}
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);
}
Aggregations