Search in sources :

Example 1 with IValidationSourceXML

use of com.helger.phive.engine.source.IValidationSourceXML in project phive by phax.

the class VOM1Converter method convertToVES_XML.

@Nullable
public ValidationExecutorSet<IValidationSourceXML> convertToVES_XML(@Nonnull final VOMType aVOM, @Nonnull final ErrorList aErrorList) {
    ValueEnforcer.notNull(aVOM, "VOM");
    ValueEnforcer.notNull(aErrorList, "ErrorList");
    if (m_bPerformValidation) {
        VOM1Validator.validate(aVOM, m_aXmlSchemaResolver, m_aNamespaceContextResolver, m_aResourceResolver, m_aComplianceSettings, aErrorList);
        if (aErrorList.containsAtLeastOneError())
            return null;
    }
    // Create stub
    final ValidationExecutorSet<IValidationSourceXML> ret = new ValidationExecutorSet<>(_createVESID(aVOM.getId()), aVOM.getName(), false);
    if (m_aComplianceSettings.isAllowEdifact() && aVOM.getValidation().hasEdifactEntries()) {
        if (aVOM.getValidation().hasXsdEntries())
            throw new IllegalStateException("If Edifact is enabled and present, than no XSD can be present!");
        // Add all Edifacts
        for (final VOMEdifactType aEdifact : aVOM.getValidation().getEdifact()) ret.addExecutor(_createExecutorEdifact(aEdifact));
    } else {
        // Add all XSDs
        for (final VOMXSDType aXsd : aVOM.getValidation().getXsd()) ret.addExecutor(_createExecutorXSD(aXsd));
    }
    // Add all XSDs
    for (final VOMSchematronType aSchematron : aVOM.getValidation().getSchematron()) ret.addExecutor(_createExecutorSchematron(aSchematron));
    return ret;
}
Also used : ValidationExecutorSet(com.helger.phive.api.executorset.ValidationExecutorSet) VOMSchematronType(com.helger.phive.engine.vom.v10.VOMSchematronType) VOMEdifactType(com.helger.phive.engine.vom.v10.VOMEdifactType) IValidationSourceXML(com.helger.phive.engine.source.IValidationSourceXML) VOMXSDType(com.helger.phive.engine.vom.v10.VOMXSDType) Nullable(javax.annotation.Nullable)

Example 2 with IValidationSourceXML

use of com.helger.phive.engine.source.IValidationSourceXML in project phive by phax.

the class VOM1Converter method _createExecutorEdifact.

@Nonnull
private IValidationExecutor<IValidationSourceXML> _createExecutorEdifact(@Nonnull final VOMEdifactType aEdifact) {
    final IEdifactValidationExecutorProviderXML aProvider = m_aComplianceSettings.getEdifactValidationExecutorProviderXML();
    final StringMap aOptions = new StringMap();
    for (final VOMOptionType aOption : aEdifact.getOption()) aOptions.put(aOption.getName(), aOption.getValue());
    LOGGER.info("Trying to resolve Edifact artifact '" + aEdifact.getDirectory() + '/' + aEdifact.getMessage() + "'");
    final IValidationExecutor<IValidationSourceXML> aVES = aProvider.createValidationExecutor(aEdifact.getDirectory(), aEdifact.getMessage(), aOptions);
    if (aVES == null)
        throw new IllegalStateException("Failed to resolve Edifact artifact '" + aEdifact.getDirectory() + '/' + aEdifact.getMessage() + "'");
    return aVES;
}
Also used : StringMap(com.helger.commons.collection.attr.StringMap) VOMOptionType(com.helger.phive.engine.vom.v10.VOMOptionType) IValidationSourceXML(com.helger.phive.engine.source.IValidationSourceXML) IEdifactValidationExecutorProviderXML(com.helger.phive.engine.vom.VOM1ComplianceSettings.IEdifactValidationExecutorProviderXML) Nonnull(javax.annotation.Nonnull)

Example 3 with IValidationSourceXML

use of com.helger.phive.engine.source.IValidationSourceXML in project phive by phax.

the class ValidationExecutorXSDPartial method applyValidation.

@Nonnull
public ValidationResult applyValidation(@Nonnull final IValidationSourceXML aSource, @Nullable final Locale aLocale) {
    ValueEnforcer.notNull(aSource, "Source");
    final IValidationArtefact aVA = getValidationArtefact();
    NodeList aNodeSet;
    try {
        aNodeSet = (NodeList) m_aPartialContext.getXPathExpression().evaluate(aSource.getNode(), XPathConstants.NODESET);
    } catch (final XPathExpressionException ex) {
        throw new IllegalStateException(ex);
    }
    final ErrorList aErrorList = new ErrorList();
    final int nMatchingNodes = aNodeSet.getLength();
    if (m_aPartialContext.hasMinNodeCount())
        if (nMatchingNodes < m_aPartialContext.getMinNodeCount()) {
            // Too little matches found
            aErrorList.add(SingleError.builderFatalError().errorLocation(aVA.getRuleResourcePath()).errorText("The minimum number of result nodes (" + m_aPartialContext.getMinNodeCount() + ") is not met").build());
        }
    if (m_aPartialContext.hasMaxNodeCount())
        if (nMatchingNodes > m_aPartialContext.getMaxNodeCount()) {
            // Too little matches found
            aErrorList.add(SingleError.builderFatalError().errorLocation(aVA.getRuleResourcePath()).errorText("The maximum number of result nodes (" + m_aPartialContext.getMaxNodeCount() + ") is not met").build());
        }
    if (nMatchingNodes == 0) {
        // No match found - nothing to do
        return new ValidationResult(aVA, aErrorList);
    }
    // Find the XML schema required for validation
    // as we don't have a node, we need to trust the implementation class
    final Schema aSchema = m_aSchemaProvider.get();
    assert aSchema != null;
    for (int i = 0; i < aNodeSet.getLength(); ++i) {
        // Build a partial source
        final IValidationSourceXML aRealSource = new ValidationSourceXML(aSource.getSystemID(), aNodeSet.item(i), true);
        try {
            // Apply the XML schema validation
            XMLSchemaValidationHelper.validate(aSchema, aRealSource.getAsTransformSource(), aErrorList, aLocale);
        } catch (final IllegalArgumentException ex) {
            // Happens when non-XML document is trying to be parsed
            if (ex.getCause() instanceof SAXParseException) {
                aErrorList.add(AbstractSAXErrorHandler.getSaxParseError(EErrorLevel.FATAL_ERROR, (SAXParseException) ex.getCause()));
            } else {
                aErrorList.add(SingleError.builderFatalError().errorLocation(aVA.getRuleResourcePath()).errorFieldName("Context[" + i + "]").errorText("The document to be validated is not an XML document").linkedException(ex).build());
            }
        }
    }
    // Build result object
    return new ValidationResult(aVA, aErrorList.getAllFailures());
}
Also used : ErrorList(com.helger.commons.error.list.ErrorList) IValidationArtefact(com.helger.phive.api.artefact.IValidationArtefact) XPathExpressionException(javax.xml.xpath.XPathExpressionException) SAXParseException(org.xml.sax.SAXParseException) NodeList(org.w3c.dom.NodeList) Schema(javax.xml.validation.Schema) ValidationSourceXML(com.helger.phive.engine.source.ValidationSourceXML) IValidationSourceXML(com.helger.phive.engine.source.IValidationSourceXML) IValidationSourceXML(com.helger.phive.engine.source.IValidationSourceXML) ValidationResult(com.helger.phive.api.result.ValidationResult) Nonnull(javax.annotation.Nonnull)

Example 4 with IValidationSourceXML

use of com.helger.phive.engine.source.IValidationSourceXML in project phive by phax.

the class PhiveJsonHelperTest method testValidationResultsBackAndForth.

@Test
public void testValidationResultsBackAndForth() {
    // Register
    final ValidationExecutorSetRegistry<IValidationSourceXML> aRegistry = new ValidationExecutorSetRegistry<>();
    final VESID aVESID = new VESID("group", "art", "1.0");
    final ValidationExecutorSet<IValidationSourceXML> aVES = new ValidationExecutorSet<>(aVESID, "name", false);
    aVES.addExecutor(ValidationExecutorXSD.create(new ClassPathResource("test/schema1.xsd")));
    aRegistry.registerValidationExecutorSet(aVES);
    // Validate
    final ValidationResultList aVRL = ValidationExecutionManager.executeValidation(aVES, ValidationSourceXML.create(new ClassPathResource("test/schema1.xml")));
    assertTrue(aVRL.containsAtLeastOneError());
    // To JSON
    final Locale aDisplayLocale = Locale.US;
    final IJsonObject aObj = new JsonObject();
    PhiveJsonHelper.applyValidationResultList(aObj, aVES, aVRL, aDisplayLocale, 123, null, null);
    // And back
    final IValidationExecutorSet<IValidationSourceXML> aVES2 = PhiveJsonHelper.getAsVES(aRegistry, aObj);
    assertNotNull(aVES2);
    assertSame(aVES, aVES2);
    final ValidationResultList aVRL2 = PhiveJsonHelper.getAsValidationResultList(aObj);
    assertNotNull(aVRL2);
    // direct equals doesn't work, because of the restored exception
    assertEquals(aVRL.size(), aVRL2.size());
    assertEquals(1, aVRL.size());
    assertEquals(aVRL.get(0).getErrorList().size(), aVRL2.get(0).getErrorList().size());
    // and forth
    final IJsonObject aObj2 = new JsonObject();
    PhiveJsonHelper.applyValidationResultList(aObj2, aVES2, aVRL2, aDisplayLocale, 123, null, null);
    CommonsTestHelper.testDefaultImplementationWithEqualContentObject(aObj, aObj2);
}
Also used : ValidationExecutorSet(com.helger.phive.api.executorset.ValidationExecutorSet) IValidationExecutorSet(com.helger.phive.api.executorset.IValidationExecutorSet) Locale(java.util.Locale) VESID(com.helger.phive.api.executorset.VESID) IJsonObject(com.helger.json.IJsonObject) ValidationResultList(com.helger.phive.api.result.ValidationResultList) IJsonObject(com.helger.json.IJsonObject) JsonObject(com.helger.json.JsonObject) IValidationSourceXML(com.helger.phive.engine.source.IValidationSourceXML) ClassPathResource(com.helger.commons.io.resource.ClassPathResource) ValidationExecutorSetRegistry(com.helger.phive.api.executorset.ValidationExecutorSetRegistry) Test(org.junit.Test)

Example 5 with IValidationSourceXML

use of com.helger.phive.engine.source.IValidationSourceXML in project phase4 by phax.

the class MainPhase4PeppolSenderQvaliaUBL method main.

public static void main(final String[] args) {
    WebScopeManager.onGlobalBegin(MockServletContext.create());
    // Dump (for debugging purpose only)
    AS4DumpManager.setIncomingDumper(new AS4IncomingDumperFileBased());
    AS4DumpManager.setOutgoingDumper(new AS4OutgoingDumperFileBased());
    try {
        final Element aPayloadElement = DOMReader.readXMLDOM(new File("src/test/resources/examples/example-ubl-en-qvalia.xml")).getDocumentElement();
        if (aPayloadElement == null)
            throw new IllegalStateException("Failed to read XML file to be send");
        // Start configuring here
        final IParticipantIdentifier aReceiverID = Phase4PeppolSender.IF.createParticipantIdentifierWithDefaultScheme("0007:5567321707");
        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() + "'");
                LOGGER.info("Sending out AS4 message with conversation ID '" + aUserMsg.getEbms3UserMessage().getCollaborationInfo().getConversationId() + "'");
            }
        };
        // Add EN16931 rulesets
        final IValidationExecutorSetRegistry<IValidationSourceXML> aVESRegistry = Phase4PeppolValidation.createDefaultRegistry();
        EN16931Validation.initEN16931(aVESRegistry);
        // Invalid certificate is valid until 2029
        final IAS4CryptoFactory cf = AS4CryptoFactoryProperties.getDefaultInstance();
        final ESimpleUserMessageSendResult eResult;
        eResult = Phase4PeppolSender.builder().httpRetrySettings(new HttpRetrySettings().setMaxRetries(0)).cryptoFactory(cf).documentTypeID(Phase4PeppolSender.IF.createDocumentTypeIdentifierWithDefaultScheme("urn:oasis:names:specification:ubl:schema:xsd:Invoice-2::Invoice##urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0::2.1")).processID(Phase4PeppolSender.IF.createProcessIdentifierWithDefaultScheme("urn:fdc:peppol.eu:2017:poacc:billing:01:1.0")).senderParticipantID(Phase4PeppolSender.IF.createParticipantIdentifierWithDefaultScheme("9915:phase4-test-sender")).receiverParticipantID(aReceiverID).senderPartyID("POP000306").payload(aPayloadElement).smpClient(new SMPClientReadOnly(Phase4PeppolSender.URL_PROVIDER, aReceiverID, ESML.DIGIT_TEST)).rawResponseConsumer(new AS4RawResponseConsumerWriteToFile()).validationRegistry(aVESRegistry).validationConfiguration(EN16931Validation.VID_UBL_INVOICE_137, new Phase4PeppolValidatonResultHandler()).buildMessageCallback(aBuildMessageCallback).sendMessageAndCheckForReceipt();
        LOGGER.info("Peppol send result: " + eResult);
    } catch (final Exception ex) {
        LOGGER.error("Error sending Peppol message via AS4", ex);
    } finally {
        WebScopeManager.onGlobalEnd();
    }
}
Also used : IAS4ClientBuildMessageCallback(com.helger.phase4.client.IAS4ClientBuildMessageCallback) IAS4CryptoFactory(com.helger.phase4.crypto.IAS4CryptoFactory) SMPClientReadOnly(com.helger.smpclient.peppol.SMPClientReadOnly) Element(org.w3c.dom.Element) IValidationSourceXML(com.helger.phive.engine.source.IValidationSourceXML) AS4UserMessage(com.helger.phase4.messaging.domain.AS4UserMessage) HttpRetrySettings(com.helger.phase4.http.HttpRetrySettings) AbstractAS4Message(com.helger.phase4.messaging.domain.AbstractAS4Message) ESimpleUserMessageSendResult(com.helger.phase4.sender.AbstractAS4UserMessageBuilder.ESimpleUserMessageSendResult) AS4IncomingDumperFileBased(com.helger.phase4.dump.AS4IncomingDumperFileBased) AS4RawResponseConsumerWriteToFile(com.helger.phase4.dump.AS4RawResponseConsumerWriteToFile) AS4RawResponseConsumerWriteToFile(com.helger.phase4.dump.AS4RawResponseConsumerWriteToFile) File(java.io.File) AS4OutgoingDumperFileBased(com.helger.phase4.dump.AS4OutgoingDumperFileBased) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier)

Aggregations

IValidationSourceXML (com.helger.phive.engine.source.IValidationSourceXML)10 File (java.io.File)5 IParticipantIdentifier (com.helger.peppolid.IParticipantIdentifier)4 AS4RawResponseConsumerWriteToFile (com.helger.phase4.dump.AS4RawResponseConsumerWriteToFile)4 ESimpleUserMessageSendResult (com.helger.phase4.sender.AbstractAS4UserMessageBuilder.ESimpleUserMessageSendResult)4 SMPClientReadOnly (com.helger.smpclient.peppol.SMPClientReadOnly)4 Element (org.w3c.dom.Element)4 AS4IncomingDumperFileBased (com.helger.phase4.dump.AS4IncomingDumperFileBased)3 AS4OutgoingDumperFileBased (com.helger.phase4.dump.AS4OutgoingDumperFileBased)3 ValidationExecutorSet (com.helger.phive.api.executorset.ValidationExecutorSet)3 ErrorList (com.helger.commons.error.list.ErrorList)2 IAS4ClientBuildMessageCallback (com.helger.phase4.client.IAS4ClientBuildMessageCallback)2 HttpRetrySettings (com.helger.phase4.http.HttpRetrySettings)2 AS4UserMessage (com.helger.phase4.messaging.domain.AS4UserMessage)2 AbstractAS4Message (com.helger.phase4.messaging.domain.AbstractAS4Message)2 ValidationResultList (com.helger.phive.api.result.ValidationResultList)2 IEdifactValidationExecutorProviderXML (com.helger.phive.engine.vom.VOM1ComplianceSettings.IEdifactValidationExecutorProviderXML)2 Nonnull (javax.annotation.Nonnull)2 Schema (javax.xml.validation.Schema)2 Test (org.junit.Test)2