use of com.helger.peppol.wsclient2.ValidationResultType in project midpoint by Evolveum.
the class ValidateExecutor method execute.
@Override
public PipelineData execute(ActionExpressionType expression, PipelineData input, ExecutionContext context, OperationResult globalResult) throws ScriptExecutionException {
PipelineData output = PipelineData.createEmpty();
for (PipelineItem item : input.getData()) {
PrismValue value = item.getValue();
OperationResult result = operationsHelper.createActionResult(item, this, globalResult);
context.checkTaskStop();
if (value instanceof PrismObjectValue && ((PrismObjectValue<?>) value).asObjectable() instanceof ResourceType) {
// noinspection unchecked
PrismObject<ResourceType> resourceTypePrismObject = ((PrismObjectValue<ResourceType>) value).asPrismObject();
ResourceType resourceType = resourceTypePrismObject.asObjectable();
Operation op = operationsHelper.recordStart(context, resourceType);
try {
ValidationResult validationResult = resourceValidator.validate(resourceTypePrismObject, Scope.THOROUGH, null, context.getTask(), result);
PrismContainerDefinition<ValidationResultType> pcd = prismContext.getSchemaRegistry().findContainerDefinitionByElementName(SchemaConstantsGenerated.C_VALIDATION_RESULT);
PrismContainer<ValidationResultType> pc = pcd.instantiate();
// noinspection unchecked
pc.add(validationResult.toValidationResultType().asPrismContainerValue());
context.println("Validated " + resourceTypePrismObject + ": " + validationResult.getIssues().size() + " issue(s)");
operationsHelper.recordEnd(context, op, null, result);
output.add(new PipelineItem(pc.getValue(), item.getResult()));
} catch (SchemaException | RuntimeException e) {
operationsHelper.recordEnd(context, op, e, result);
context.println("Error validation " + resourceTypePrismObject + ": " + e.getMessage());
// noinspection ThrowableNotThrown
processActionException(e, NAME, value, context);
output.add(item);
}
} else {
// noinspection ThrowableNotThrown
processActionException(new ScriptExecutionException("Item is not a PrismObject<ResourceType>"), NAME, value, context);
}
operationsHelper.trimAndCloneResult(result, item.getResult());
}
return output;
}
use of com.helger.peppol.wsclient2.ValidationResultType in project peppol-practical by phax.
the class WSDVS method validate.
@Nonnull
public ResponseType validate(@Nonnull final RequestType aValidationRequest) throws ValidateFaultError {
final HttpServletRequest aHttpRequest = (HttpServletRequest) m_aWSContext.getMessageContext().get(MessageContext.SERVLET_REQUEST);
final HttpServletResponse aHttpResponse = (HttpServletResponse) m_aWSContext.getMessageContext().get(MessageContext.SERVLET_RESPONSE);
final String sRateLimitKey = "ip:" + aHttpRequest.getRemoteAddr();
final boolean bOverRateLimit = m_aRequestRateLimiter != null ? m_aRequestRateLimiter.overLimitWhenIncremented(sRateLimitKey) : false;
final String sInvocationUniqueID = Integer.toString(INVOCATION_COUNTER.incrementAndGet());
RW_LOCK.writeLocked(() -> {
// Just append to file
try (final CSVWriter w = new CSVWriter(FileHelper.getPrintWriter(WebFileIO.getDataIO().getFile("wsdvs-logs.csv"), EAppend.APPEND, StandardCharsets.ISO_8859_1))) {
w.setSeparatorChar(';');
w.writeNext(SESSION_ID, sInvocationUniqueID, PDTFactory.getCurrentLocalDateTime().toString(), aHttpRequest.getRemoteAddr(), Boolean.toString(bOverRateLimit), aValidationRequest.getVESID(), Integer.toString(StringHelper.getLength(aValidationRequest.getXML())), RequestHelper.getHttpUserAgentStringFromRequest(aHttpRequest));
} catch (final IOException ex) {
LOGGER.error("Error writing CSV: " + ex.getMessage());
}
});
if (LOGGER.isInfoEnabled())
LOGGER.info("Start validating business document with SOAP WS; source [" + aHttpRequest.getRemoteAddr() + ":" + aHttpRequest.getRemotePort() + "]; VESID '" + aValidationRequest.getVESID() + "'; Payload: " + StringHelper.getLength(aValidationRequest.getXML()) + " bytes;" + (bOverRateLimit ? " RATE LIMIT EXCEEDED" : ""));
// Start request scope
try (final WebScoped aWebScoped = new WebScoped(aHttpRequest, aHttpResponse)) {
// Track total invocation
STATS_COUNTER_TOTOAL.increment();
if (bOverRateLimit) {
// Too Many Requests
if (LOGGER.isDebugEnabled())
LOGGER.debug("REST search rate limit exceeded for " + sRateLimitKey);
final HttpServletResponse aResponse = (HttpServletResponse) m_aWSContext.getMessageContext().get(MessageContext.SERVLET_RESPONSE);
try {
aResponse.sendError(CHttp.HTTP_TOO_MANY_REQUESTS);
} catch (final IOException ex) {
throw new UncheckedIOException(ex);
}
return null;
}
// Interpret parameters
final String sVESID = aValidationRequest.getVESID();
final VESID aVESID = VESID.parseIDOrNull(sVESID);
if (aVESID == null)
_throw("Syntactically invalid VESID '" + sVESID + "' provided!");
final IValidationExecutorSet<IValidationSourceXML> aVES = ExtValidationKeyRegistry.getFromIDOrNull(aVESID);
if (aVES == null)
_throw("Unsupported VESID " + aVESID.getAsSingleID() + " provided!");
if (aVES.isDeprecated())
LOGGER.warn(" VESID '" + aVESID.getAsSingleID() + "' is deprecated");
Document aXMLDoc = null;
try {
aXMLDoc = DOMReader.readXMLDOM(aValidationRequest.getXML());
} catch (final Exception ex) {
// fall-through
}
if (aXMLDoc == null)
_throw("Invalid XML provided!");
final String sDisplayLocale = aValidationRequest.getDisplayLocale();
final Locale aDisplayLocale = StringHelper.hasText(sDisplayLocale) ? LocaleCache.getInstance().getLocale(sDisplayLocale) : CPPApp.DEFAULT_LOCALE;
if (aDisplayLocale == null)
_throw("Invalid display locale '" + sDisplayLocale + "' provided!");
// All input parameters are valid!
if (LOGGER.isInfoEnabled())
LOGGER.info("Validating by SOAP WS using " + aVESID.getAsSingleID());
final StopWatch aSW = StopWatch.createdStarted();
// Start validating
final ValidationResultList aVRL = ValidationExecutionManager.executeValidation(aVES, ValidationSourceXML.create("uploaded-file", aXMLDoc), aDisplayLocale);
// Result object
final ResponseType ret = new ResponseType();
int nWarnings = 0;
int nErrors = 0;
boolean bValidationInterrupted = false;
IErrorLevel aMostSevere = EErrorLevel.LOWEST;
for (final ValidationResult aVR : aVRL) {
final ValidationResultType aVRT = new ValidationResultType();
if (aVR.isIgnored()) {
bValidationInterrupted = true;
aVRT.setSuccess(TriStateType.UNDEFINED);
} else {
aVRT.setSuccess(aVR.isSuccess() ? TriStateType.TRUE : TriStateType.FALSE);
}
aVRT.setArtifactType(aVR.getValidationArtefact().getValidationArtefactType().getID());
aVRT.setArtifactPath(aVR.getValidationArtefact().getRuleResource().getPath());
for (final IError aError : aVR.getErrorList()) {
if (aError.getErrorLevel().isGT(aMostSevere))
aMostSevere = aError.getErrorLevel();
if (aError.getErrorLevel().isGE(EErrorLevel.ERROR))
nErrors++;
else if (aError.getErrorLevel().isGE(EErrorLevel.WARN))
nWarnings++;
final ItemType aItem = new ItemType();
aItem.setErrorLevel(_convert(aError.getErrorLevel()));
if (aError.hasErrorID())
aItem.setErrorID(aError.getErrorID());
if (aError.hasErrorFieldName())
aItem.setErrorFieldName(aError.getErrorFieldName());
if (aError.hasErrorLocation())
aItem.setErrorLocation(aError.getErrorLocation().getAsString());
aItem.setErrorText(aError.getErrorText(aDisplayLocale));
if (aError.hasLinkedException())
aItem.setException(StackTraceHelper.getStackAsString(aError.getLinkedException()));
if (aError instanceof SVRLResourceError) {
final String sTest = ((SVRLResourceError) aError).getTest();
aItem.setTest(sTest);
}
aVRT.addItem(aItem);
}
ret.addResult(aVRT);
}
// Success if the worst that happened is a warning
ret.setSuccess(aMostSevere.isLE(EErrorLevel.WARN));
ret.setInterrupted(bValidationInterrupted);
ret.setMostSevereErrorLevel(_convert(aMostSevere));
aSW.stop();
if (LOGGER.isInfoEnabled())
LOGGER.info("Finished validation after " + aSW.getMillis() + "ms; " + nWarnings + " warns; " + nErrors + " errors");
STATS_TIMER.addTime(aSW.getMillis());
// Track validation result
if (ret.getMostSevereErrorLevel().equals(ErrorLevelType.ERROR))
STATS_COUNTER_VALIDATION_ERROR.increment();
else
STATS_COUNTER_VALIDATION_SUCCESS.increment();
// Track API result
if (ret.isSuccess())
STATS_COUNTER_API_SUCCESS.increment();
else
STATS_COUNTER_API_ERROR.increment();
final int nFinalWarnings = nWarnings;
final int nFinalErrors = nErrors;
RW_LOCK.writeLocked(() -> {
// Just append to file
try (final CSVWriter w = new CSVWriter(FileHelper.getPrintWriter(WebFileIO.getDataIO().getFile("wsdvs-results.csv"), EAppend.APPEND, StandardCharsets.ISO_8859_1))) {
w.setSeparatorChar(';');
w.writeNext(SESSION_ID, sInvocationUniqueID, PDTFactory.getCurrentLocalDateTime().toString(), Long.toString(aSW.getMillis()), Integer.toString(nFinalWarnings), Integer.toString(nFinalErrors));
} catch (final IOException ex) {
LOGGER.error("Error writing CSV2: " + ex.getMessage());
}
});
return ret;
} finally {
if (LOGGER.isInfoEnabled())
LOGGER.info("Finished validating business document with SOAP WS");
}
}
use of com.helger.peppol.wsclient2.ValidationResultType 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");
}
Aggregations