use of com.helger.commons.state.ESuccess in project phoss-directory by phax.
the class PDIndexExecutor method executeWorkItem.
/**
* This method is responsible for executing the specified work item depending
* on its type.
*
* @param aStorageMgr
* Storage manager.
* @param aWorkItem
* The work item to be executed. May not be <code>null</code>.
* @param nRetryCount
* The retry count. For the initial indexing it is 0, for the first
* retry 1 etc.
* @param aSuccessHandler
* A callback that is invoked upon success only.
* @param aFailureHandler
* A callback that is invoked upon failure only.
* @return {@link ESuccess}
*/
@Nonnull
public static ESuccess executeWorkItem(@Nonnull final IPDStorageManager aStorageMgr, @Nonnull final IIndexerWorkItem aWorkItem, @Nonnegative final int nRetryCount, @Nonnull final Consumer<? super IIndexerWorkItem> aSuccessHandler, @Nonnull final Consumer<? super IIndexerWorkItem> aFailureHandler) {
LOGGER.info("Execute work item " + aWorkItem.getLogText() + " - " + (nRetryCount > 0 ? "retry #" + nRetryCount : "initial try"));
final IPDBusinessCardProvider aBCProvider = PDMetaManager.getBusinessCardProviderOrNull();
if (aBCProvider == null) {
// Maybe null upon shutdown - in that case ignore it and don't reindex
return ESuccess.FAILURE;
}
try {
final IParticipantIdentifier aParticipantID = aWorkItem.getParticipantID();
ESuccess eSuccess;
switch(aWorkItem.getType()) {
case CREATE_UPDATE:
{
// Get BI from participant (e.g. from SMP)
final PDExtendedBusinessCard aBI = aBCProvider.getBusinessCard(aParticipantID);
if (aBI == null) {
// No/invalid extension present - no need to try again
eSuccess = ESuccess.FAILURE;
} else {
// Got data - put in storage
eSuccess = aStorageMgr.createOrUpdateEntry(aParticipantID, aBI, aWorkItem.getAsMetaData());
}
break;
}
case DELETE:
{
// Really delete it
eSuccess = ESuccess.valueOf(aStorageMgr.deleteEntry(aParticipantID, aWorkItem.getAsMetaData(), true) >= 0);
break;
}
case SYNC:
{
// Get BI from participant (e.g. from SMP)
final PDExtendedBusinessCard aBI = aBCProvider.getBusinessCard(aParticipantID);
if (aBI == null) {
// No/invalid extension present - delete from index
eSuccess = ESuccess.valueOf(aStorageMgr.deleteEntry(aParticipantID, aWorkItem.getAsMetaData(), true) >= 0);
} else {
// Got data - put in storage
eSuccess = aStorageMgr.createOrUpdateEntry(aParticipantID, aBI, aWorkItem.getAsMetaData());
}
break;
}
default:
throw new IllegalStateException("Unsupported work item type: " + aWorkItem);
}
if (eSuccess.isSuccess()) {
// Item handled - remove from overall list
aSuccessHandler.accept(aWorkItem);
// And we're done
return ESuccess.SUCCESS;
}
// else error storing data
} catch (final Exception ex) {
LOGGER.error("Error in executing work item " + aWorkItem.getLogText(), ex);
// Fall through
}
// Invoke failure handler
aFailureHandler.accept(aWorkItem);
return ESuccess.FAILURE;
}
use of com.helger.commons.state.ESuccess in project peppol-commons by phax.
the class SignedServiceMetadataTypeFuncTest method testReadValid.
@Test
public void testReadValid() throws Exception {
final SMPMarshallerSignedServiceMetadataType aMarshaller = new SMPMarshallerSignedServiceMetadataType(true);
aMarshaller.setValidationEventHandlerFactory(x -> new LoggingValidationEventHandler());
final byte[] aBytes = StreamHelper.getAllBytes(new ClassPathResource("smp/signed-service-metadata2.xml"));
assertNotNull(aBytes);
final SignedServiceMetadataType aSSM = aMarshaller.read(aBytes);
assertNotNull(aSSM);
final Document aDocument = DOMReader.readXMLDOM(aBytes);
assertNotNull(aDocument);
final TrustStoreBasedX509KeySelector aKeySelector = new TrustStoreBasedX509KeySelector(SMPClientConfiguration.loadTrustStore());
// Certificate expired 2021-03-01
aKeySelector.setValidationDateTime(PDTFactory.createLocalDateTime(2021, Month.JANUARY, 1));
final ESuccess eSuccess = SMPHttpResponseHandlerSigned.checkSignature(aDocument, aKeySelector);
assertTrue(eSuccess.isSuccess());
}
use of com.helger.commons.state.ESuccess in project peppol-commons by phax.
the class SignedServiceMetadataTypeFuncTest method testReadC14NInclusive.
@Test
public void testReadC14NInclusive() throws Exception {
final SMPMarshallerSignedServiceMetadataType aMarshaller = new SMPMarshallerSignedServiceMetadataType(true);
aMarshaller.setValidationEventHandlerFactory(x -> new LoggingValidationEventHandler());
final byte[] aBytes = StreamHelper.getAllBytes(new ClassPathResource("smp/signed-service-metadata3-c14n-inclusive.xml"));
assertNotNull(aBytes);
final SignedServiceMetadataType aSSM = aMarshaller.read(aBytes);
assertNotNull(aSSM);
final Document aDocument = DOMReader.readXMLDOM(aBytes);
assertNotNull(aDocument);
final TrustStoreBasedX509KeySelector aKeySelector = new TrustStoreBasedX509KeySelector(SMPClientConfiguration.loadTrustStore());
// Certificate expired 2020-08-05
aKeySelector.setValidationDateTime(PDTFactory.createLocalDateTime(2020, Month.AUGUST, 1));
final ESuccess eSuccess = SMPHttpResponseHandlerSigned.checkSignature(aDocument, aKeySelector);
assertTrue(eSuccess.isSuccess());
}
use of com.helger.commons.state.ESuccess in project peppol-commons by phax.
the class SMPHttpResponseHandlerSigned method checkSignature.
@Nonnull
public static ESuccess checkSignature(@Nonnull final Document aDocument, @Nonnull final KeySelector aKeySelector) throws MarshalException, XMLSignatureException {
// We make sure that the XML is a Signed. If not, we don't have to check
// any certificates.
// Find all "Signature" elements
final NodeList aNodeList = aDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
if (aNodeList == null || aNodeList.getLength() == 0)
throw new IllegalArgumentException("Element <Signature> not found in SMP XML response");
final int nSignatureCount = aNodeList.getLength();
if (LOGGER.isDebugEnabled())
LOGGER.debug("Found " + nSignatureCount + " <Signature> elements to verify");
final XMLSignatureFactory aSignatureFactory = XMLSignatureFactory.getInstance("DOM");
ESuccess eSuccess = ESuccess.SUCCESS;
// OASIS BDXR SMP v2 can have more than one signature
for (int nSignatureIndex = 0; nSignatureIndex < nSignatureCount; ++nSignatureIndex) {
// Create a DOMValidateContext and specify a KeySelector
final DOMValidateContext aValidateContext = new DOMValidateContext(aKeySelector, aNodeList.item(nSignatureIndex));
final String sSignatureDebug = (nSignatureIndex + 1) + "/" + nSignatureCount;
// Unmarshal the XMLSignature.
final XMLSignature aSignature = aSignatureFactory.unmarshalXMLSignature(aValidateContext);
// Validate the XMLSignature.
final boolean bCoreValid = aSignature.validate(aValidateContext);
if (bCoreValid) {
if (LOGGER.isDebugEnabled())
LOGGER.debug("Signature[" + sSignatureDebug + "] validation was successful");
} else {
eSuccess = ESuccess.FAILURE;
// influence
if (LOGGER.isWarnEnabled())
LOGGER.warn("Signature[" + sSignatureDebug + "] failed core validation");
final boolean bSignatureValueValid = aSignature.getSignatureValue().validate(aValidateContext);
if (bSignatureValueValid) {
if (LOGGER.isInfoEnabled())
LOGGER.info(" Signature[" + sSignatureDebug + "] SignatureValue validity status: valid");
} else {
if (LOGGER.isWarnEnabled())
LOGGER.warn(" Signature[" + sSignatureDebug + "] SignatureValue validity status: NOT valid!");
}
{
// Check the validation status of each Reference.
final List<?> aRefs = aSignature.getSignedInfo().getReferences();
final int nRefCount = aRefs.size();
int nRefIndex = 0;
final Iterator<?> i = aRefs.iterator();
while (i.hasNext()) {
final String sRefDebug = (nRefIndex + 1) + "/" + nRefCount;
final Reference aRef = (Reference) i.next();
if (aRef.getTransforms().size() != 1)
if (LOGGER.isWarnEnabled())
LOGGER.warn(" Signature[" + sSignatureDebug + "] Reference[" + sRefDebug + "] has an invalid number of Transforms. Expected 1 but having " + aRef.getTransforms().size());
final boolean bRefValid = aRef.validate(aValidateContext);
if (bRefValid) {
if (LOGGER.isInfoEnabled())
LOGGER.info(" Signature[" + sSignatureDebug + "] Reference[" + sRefDebug + "] validity status: valid");
} else {
if (LOGGER.isWarnEnabled())
LOGGER.warn(" Signature[" + sSignatureDebug + "] Reference[" + sRefDebug + "] validity status: NOT valid!");
}
++nRefIndex;
}
}
}
}
return eSuccess;
}
use of com.helger.commons.state.ESuccess in project en16931-cii2ubl by phax.
the class CIIToUBLConverter method call.
// doing the business
public Integer call() throws Exception {
m_sOutputDir = _normalizeOutputDirectory(m_sOutputDir);
m_aSourceFiles = _normalizeInputFiles(m_aSourceFiles);
final AbstractCIIToUBLConverter<?> aConverter;
if ("2.1".equals(m_sUBLVersion))
aConverter = new CIIToUBL21Converter();
else if ("2.2".equals(m_sUBLVersion))
aConverter = new CIIToUBL22Converter();
else if ("2.3".equals(m_sUBLVersion))
aConverter = new CIIToUBL23Converter();
else
throw new IllegalStateException("Unsupported UBL version '" + m_sUBLVersion + "' provided.");
aConverter.setUBLCreationMode(m_eMode).setVATScheme(m_sVATScheme).setCustomizationID(m_sCustomizationID).setProfileID(m_sProfileID).setCardAccountNetworkID(m_sCardAccountNetworkID);
final Locale aErrorLocale = Locale.US;
for (final File f : m_aSourceFiles) {
if (LOGGER.isDebugEnabled())
LOGGER.debug("Converting file=" + f.getAbsolutePath());
final File aDestFile = new File(m_sOutputDir, FilenameHelper.getBaseName(f) + "-ubl.xml");
// TODO switch between versions
final ErrorList aErrorList = new ErrorList();
final Serializable aUBL = aConverter.convertCIItoUBL(f, aErrorList);
if (aErrorList.containsAtLeastOneError() || aUBL == null) {
LOGGER.error("Failed to convert CII file '" + f.getAbsolutePath() + "' to UBL:");
for (final IError aError : aErrorList) LOGGER.error(aError.getAsString(aErrorLocale));
} else {
final boolean bFormattedOutput = true;
final ESuccess eSuccess;
if (aUBL instanceof oasis.names.specification.ubl.schema.xsd.invoice_21.InvoiceType) {
eSuccess = UBL21Writer.invoice().setFormattedOutput(bFormattedOutput).write((oasis.names.specification.ubl.schema.xsd.invoice_21.InvoiceType) aUBL, aDestFile);
} else if (aUBL instanceof oasis.names.specification.ubl.schema.xsd.creditnote_21.CreditNoteType) {
eSuccess = UBL21Writer.creditNote().setFormattedOutput(bFormattedOutput).write((oasis.names.specification.ubl.schema.xsd.creditnote_21.CreditNoteType) aUBL, aDestFile);
} else if (aUBL instanceof oasis.names.specification.ubl.schema.xsd.invoice_22.InvoiceType) {
eSuccess = UBL22Writer.invoice().setFormattedOutput(bFormattedOutput).write((oasis.names.specification.ubl.schema.xsd.invoice_22.InvoiceType) aUBL, aDestFile);
} else if (aUBL instanceof oasis.names.specification.ubl.schema.xsd.creditnote_22.CreditNoteType) {
eSuccess = UBL22Writer.creditNote().setFormattedOutput(bFormattedOutput).write((oasis.names.specification.ubl.schema.xsd.creditnote_22.CreditNoteType) aUBL, aDestFile);
} else if (aUBL instanceof oasis.names.specification.ubl.schema.xsd.invoice_23.InvoiceType) {
eSuccess = UBL23Writer.invoice().setFormattedOutput(bFormattedOutput).write((oasis.names.specification.ubl.schema.xsd.invoice_23.InvoiceType) aUBL, aDestFile);
} else if (aUBL instanceof oasis.names.specification.ubl.schema.xsd.creditnote_23.CreditNoteType) {
eSuccess = UBL23Writer.creditNote().setFormattedOutput(bFormattedOutput).write((oasis.names.specification.ubl.schema.xsd.creditnote_23.CreditNoteType) aUBL, aDestFile);
} else
throw new IllegalStateException("Unsupported UBL version '" + m_sUBLVersion + "'");
if (eSuccess.isSuccess())
LOGGER.info("Successfully wrote UBL file " + aDestFile.getAbsolutePath());
else
LOGGER.error("Failed to write UBL file " + aDestFile.getAbsolutePath());
}
}
return Integer.valueOf(0);
}
Aggregations