public String AsXml() { XmlOptions opt = (new XmlOptions()).setSavePrettyPrint(); opt.setSaveSuggestedPrefixes(Utilities.SuggestedNamespaces()); opt.setSaveNamespacesFirst(); opt.setSaveAggressiveNamespaces(); opt.setUseDefaultNamespace(); DescribeSRSResponseDocument document = completeResponse(); ArrayList errorList = new ArrayList(); opt.setErrorListener(errorList); boolean isValid = document.validate(opt); // If the XML isn't valid, loop through the listener's contents, // printing contained messages. if (!isValid) { for (int i = 0; i < errorList.size(); i++) { XmlError error = (XmlError) errorList.get(i); System.out.println("\n"); System.out.println("Message: " + error.getMessage() + "\n"); System.out.println( "Location of invalid XML: " + error.getCursorLocation().xmlText() + "\n"); } } return document.xmlText(opt); }
private List<Resultado> validarEstructura() { final List<Resultado> resultados = new ArrayList<Resultado>(); if (docto == null) { try { docto = ComprobanteDocument.Factory.parse(xmlFile); } catch (Exception e) { throw new RuntimeException( "Error procesando el archivo XML " + ExceptionUtils.getRootCauseMessage(e), e); } } final XmlOptions options = new XmlOptions(); final List<XmlValidationError> errors = new ArrayList<XmlValidationError>(); options.setErrorListener(errors); boolean valid = docto.validate(options); if (valid) { Resultado res = new Resultado("Estructura"); res.setDescripcion("Estructura del CFD segun la versión 2 del schema del SAT"); res.setResultado("CORRECTO"); resultados.add(res); } else { for (XmlValidationError e : errors) { // buff.append(e.getMessage()+"\n"); Resultado res = new Resultado("Estructura"); res.setDescripcion(e.getMessage()); res.setResultado("ERROR"); resultados.add(res); } } return resultados; }
private AssertionError[] assertResponse( RestMessageExchange messageExchange, RestRepresentation.Type type) { List<AssertionError> result = new ArrayList<AssertionError>(); QName responseBodyElementName = getResponseBodyElementName(messageExchange); RestRequestInterface restRequest = messageExchange.getRestRequest(); boolean asserted = false; for (RestRepresentation representation : restRequest.getRepresentations(type, messageExchange.getResponseContentType())) { if (representation.getStatus().isEmpty() || representation.getStatus().contains(messageExchange.getResponseStatusCode())) { SchemaType schemaType = representation.getSchemaType(); if (schemaType != null && representation.getElement().equals(responseBodyElementName)) { try { XmlObject xmlObject = schemaType .getTypeSystem() .parse(messageExchange.getResponseContentAsXml(), schemaType, new XmlOptions()); // create internal error list List<?> list = new ArrayList<Object>(); XmlOptions xmlOptions = new XmlOptions(); xmlOptions.setErrorListener(list); xmlOptions.setValidateTreatLaxAsSkip(); xmlObject.validate(xmlOptions); for (Object o : list) { if (o instanceof XmlError) result.add(new AssertionError((XmlError) o)); else result.add(new AssertionError(o.toString())); } asserted = true; } catch (XmlException e) { SoapUI.logError(e); } } else { asserted = true; } } } if (!asserted && result.isEmpty()) { result.add( new AssertionError( "Missing matching representation for request with contentType [" + messageExchange.getResponseContentType() + "]")); } return result.toArray(new AssertionError[result.size()]); }
private File createXMLMetadata(HashMap<String, Object> inputs) { ArrayList<?> validationErrors = new ArrayList<Object>(); XmlOptions options; options = new XmlOptions(); options.setSavePrettyPrint(); options.setSaveAggressiveNamespaces(); HashMap<String, String> suggestedPrefixes = new HashMap<String, String>(); suggestedPrefixes.put("http://www.geoviqua.org/QualityInformationModel/4.0", "gvq"); options.setSaveSuggestedPrefixes(suggestedPrefixes); options.setErrorListener(validationErrors); GVQMetadataDocument doc = GVQMetadataDocument.Factory.newInstance(); GVQMetadataType gvqMetadata = doc.addNewGVQMetadata(); gvqMetadata.addNewLanguage().setCharacterString("en"); gvqMetadata.addNewMetadataStandardName().setCharacterString("GVQ"); gvqMetadata.addNewMetadataStandardVersion().setCharacterString("1.0.0"); gvqMetadata.addNewDateStamp().setDate(Calendar.getInstance()); DQDataQualityType quality = gvqMetadata.addNewDataQualityInfo2().addNewDQDataQuality(); GVQDataQualityType gvqQuality = (GVQDataQualityType) quality.substitute( new QName("http://www.geoviqua.org/QualityInformationModel/4.0", "GVQ_DataQuality"), GVQDataQualityType.type); GVQDiscoveredIssueType issue = gvqQuality.addNewDiscoveredIssue().addNewGVQDiscoveredIssue(); issue.addNewKnownProblem().setCharacterString(inputs.get("element").toString()); issue.addNewWorkAround().setCharacterString("solution"); // validate schema conformity boolean isValid = doc.validate(); if (!isValid) System.out.println(Arrays.toString(validationErrors.toArray())); // print out as XML System.out.println(doc.xmlText(options)); try { File tempFile = File.createTempFile("wpsMetdataTempFile", "xml"); doc.save(tempFile); return tempFile; } catch (Exception e) { LOGGER.error("createXMLMetadataError " + e); } return null; }
private void validateConfiguration(MpiConfigDocument configuration) { // Set up the validation error listener. ArrayList<XmlError> validationErrors = new ArrayList<XmlError>(); XmlOptions validationOptions = new XmlOptions(); validationOptions.setErrorListener(validationErrors); // During validation, errors are added to the ArrayList for // retrieval and printing by the printErrors method. boolean isValid = configuration.validate(validationOptions); // Print the errors if the XML is invalid. if (!isValid) { java.util.Iterator<XmlError> iter = validationErrors.iterator(); StringBuffer sb = new StringBuffer("MPI Configuration validation errors:\n"); while (iter.hasNext()) { sb.append(">> ").append(iter.next()).append("\n"); } } }
protected void validateXmlDocument(XmlObject xmlDocument) { ArrayList<XmlError> validationErrors = new ArrayList<XmlError>(); XmlOptions validationOptions = new XmlOptions(); validationOptions.setErrorListener(validationErrors); xmlDocument.validate(validationOptions); List<String> excludeErrors = new ArrayList<String>(); excludeErrors.add("Expected element '_Feature@http://www.opengis.net/gml' instead of"); excludeErrors.add("Expected element 'InsertionMetadata@http://www.opengis.net/swes/2.0'"); excludeErrors.add( "Expected element 'AbstractFeature@http://www.opengis.net/gml/3.2' instead of 'SF_SpatialSamplingFeature@http://www.opengis.net/samplingSpatial/2.0'"); for (XmlError validationError : validationErrors) { boolean skip = false; for (String excludeError : excludeErrors) { if (validationError.getMessage().startsWith(excludeError)) { skip = true; } } if (!skip) { fail(validationError.getMessage()); } } }
@Override protected void checkMessageStructure() throws MessageValidationException { boolean messageStructureFailure = false; try { // Create a pseudo XML message XmlObject pseudoMessage = XmlObject.Factory.newInstance(); XmlCursor pmCursor = pseudoMessage.newCursor(); pmCursor.toNextToken(); pmCursor.beginElement(profile.getMessageStructureID(), "urn:hl7-org:v2xml"); BufferedReader br = new BufferedReader(new StringReader(message.getMessageAsString())); String line = null; while ((line = br.readLine()) != null) { if (!line.matches("\\s*")) { String fieldSep = ((Er7Message) message).getFieldSeparatorChar(); try { int idx = line.indexOf(fieldSep); if (idx == -1 && line.length() <= 3) { idx = 3; } line = line.substring(0, idx); if (!line.startsWith("Z")) { pmCursor.beginElement(line, "urn:hl7-org:v2xml"); pmCursor.toNextToken(); } } catch (StringIndexOutOfBoundsException e) { if (line.length() > 3) { System.out.println(line); } } } } pmCursor.dispose(); // Create a schema StreamSource xsltStream = new StreamSource( MessageStructureValidationV2Er7.class .getClassLoader() .getResourceAsStream(MessageValidationConstants.XSLT_CHECK_STRUCTURE)); Transformer t = TransformerFactory.newInstance().newTransformer(xsltStream); t.setParameter("groups", "false"); t.setParameter("xml", "false"); StreamSource src = new StreamSource(profile.getDocument().newInputStream()); ByteArrayOutputStream out = new ByteArrayOutputStream(); t.transform(src, new StreamResult(out)); XmlObject schemaDoc = XmlObject.Factory.parse( new ByteArrayInputStream(out.toByteArray()), (new XmlOptions()).setLoadLineNumbers()); // pseudoMessage.save(new File("tmp/mu/PseudoMessage.xml")); // schemaDoc.save(new File("tmp/mu/Schema.xsd")); // Load the schema SchemaTypeLoader sLoader = null; Collection<Object> compErrors = new ArrayList<Object>(); XmlOptions schemaOptions = new XmlOptions(); schemaOptions.setErrorListener(compErrors); XmlObject[] schemas = new XmlObject[1]; schemas[0] = schemaDoc; sLoader = XmlBeans.compileXsd(schemas, sLoader, schemaOptions); // Load the Message XmlObject xobj = sLoader.parse(pseudoMessage.toString(), null, (new XmlOptions()).setLoadLineNumbers()); // Validate the Message against the schema Collection<XmlValidationError> errors = new ArrayList<XmlValidationError>(); xobj.validate(new XmlOptions().setErrorListener(errors)); Iterator<XmlValidationError> it = errors.iterator(); while (it.hasNext()) { XmlValidationError xve = it.next(); messageFailures.add(interpretSchemaError(xve)); messageStructureFailure = true; } } catch (XmlException xmle) { // This type of exception is thrown when the generated schema is // ambiguous MessageFailureV2 mf = new MessageFailureV2(message.getEncoding()); mf.setDescription( "The message validation can't be performed because the profile is ambiguous." + " Possible reasons for this problem include an ambiguous message definition" + " specified in the standard or an ambiguous message definition caused by the" + " user changing the Usage settings for segments during profile creation." + " Remember that a segment with the same name MUST be separated by at least one" + " non-optional segment with a different name."); mf.setFailureSeverity(ErrorSeverityConstants.FATAL); mf.setFailureType(AssertionTypeV2Constants.AMBIGUOUS_PROFILE); messageFailures.add(mf); } catch (Exception e) { throw new MessageValidationException(e.getMessage()); } finally { if (!messageStructureFailure) { MessageFailureV2 mf = new MessageFailureV2(message.getEncoding()); mf.setDescription("The message structure at the segment level is correct."); mf.setFailureSeverity(ErrorSeverityConstants.NORMAL); mf.setFailureType(AssertionTypeV2Constants.CHECKED); messageFailures.add(mf); } } }