org.apache.xmlbeans.XmlError Java Examples

The following examples show how to use org.apache.xmlbeans.XmlError. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DefaultEbicsRootElement.java    From ebics-java-client with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
 public void validate() throws EbicsException {
   ArrayList<XmlError>		validationMessages;
   boolean     		isValid;

   validationMessages = new ArrayList<XmlError>();
   isValid = document.validate(new XmlOptions().setErrorListener(validationMessages));

   if (!isValid) {
     String			message;
     Iterator<XmlError>    	iter;

     iter = validationMessages.iterator();
     message = "";
     while (iter.hasNext()) {
if (!message.equals("")) {
  message += ";";
}
message += iter.next().getMessage();
     }

     throw new EbicsException(message);
   }
 }
 
Example #2
Source File: XmlBeanWrapper.java    From mdw with Apache License 2.0 6 votes vote down vote up
/**
 * Performs validation on the XmlBean, populating the error message if failed.
 * @return false if the XmlBean is invalid (error message is available in getValidationError()).
 */
public boolean validate() {
    _validationError = null;
    List<XmlError> errors = new ArrayList<XmlError>();

    boolean valid = _xmlBean.validate(new XmlOptions().setErrorListener(errors));
    if (!valid) {
        _validationError = "";
        for (int i = 0; i < errors.size(); i++) {
            _validationError += errors.get(i).toString();
            if (i < errors.size() - 1)
                _validationError += '\n';
        }
    }

    return valid;
}
 
Example #3
Source File: DnxMapperImpl.java    From webcurator with Apache License 2.0 6 votes vote down vote up
private void checkForErrors(WctDataExtractor wctData, MetsWriter metsWriter) {
    List<XmlError> errors = new ArrayList<XmlError>();
    XmlOptions opts = new XmlOptions();
    opts.setErrorListener(errors);
    if (!metsWriter.validate(opts)) {
        StringBuilder errorMessage = new StringBuilder();

        for (XmlError error : errors)
        	// ignore error relating to missing structure map as we are not adding one.
        	if(!error.getMessage().matches("(Expected element).*(structMap).*")){
        		errorMessage.append(error.toString());
        	}
            

        if(errorMessage.length() > 0){
        	String msg = String.format("WCT Harvest Instance %s: The METs writer failed to produce a valid document, error message: %s",
                    wctData.getWctTargetInstanceID(), errorMessage);
            log.error(msg);
            throw new RuntimeException(msg);
        }
        
    }
}
 
Example #4
Source File: DefaultEbicsRootElement.java    From axelor-open-suite with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void validate() throws AxelorException {
  ArrayList<XmlError> validationMessages;
  boolean isValid;

  validationMessages = new ArrayList<XmlError>();
  isValid = document.validate(new XmlOptions().setErrorListener(validationMessages));

  if (!isValid) {
    String message;
    Iterator<XmlError> iter;

    iter = validationMessages.iterator();
    message = "";
    while (iter.hasNext()) {
      if (!message.equals("")) {
        message += ";";
      }
      message += iter.next().getMessage();
    }

    throw new AxelorException(TraceBackRepository.CATEGORY_CONFIGURATION_ERROR, message);
  }
}
 
Example #5
Source File: SoapHttpTestRunner.java    From microcks with Apache License 2.0 5 votes vote down vote up
@Override
protected int extractTestReturnCode(Service service, Operation operation, Request request,
												ClientHttpResponse httpResponse, String responseContent){
	int code = TestReturn.SUCCESS_CODE;

	// Checking HTTP return code: delegating to super class.
	code = super.extractTestReturnCode(service, operation, request, httpResponse, responseContent);
	// If test is already a failure (40x code), no need to pursue...
	if (TestReturn.FAILURE_CODE == code){
		return code;
	}

	try{
		// Validate Soap message body according to operation output part.
		List<XmlError> errors = SoapMessageValidator.validateSoapMessage(
              operation.getOutputName(), service.getXmlNS(), responseContent, resourceUrl
                    +  UriUtils.encodeFragment(service.getName(), "UTF-8") + "-" + service.getVersion() + ".wsdl", true
        );

		if (!errors.isEmpty()){
			log.debug("Soap validation errors found " + errors.size() + ", marking test as failed.");
			return TestReturn.FAILURE_CODE;
		}
	} catch (XmlException e) {
		log.debug("XmlException while validating Soap response message", e);
		return TestReturn.FAILURE_CODE;
	}
	return code;
}
 
Example #6
Source File: SoapController.java    From microcks with Apache License 2.0 4 votes vote down vote up
@RequestMapping(value = "/{service}/{version}/**", method = RequestMethod.POST)
public ResponseEntity<?> execute(
      @PathVariable("service") String serviceName,
      @PathVariable("version") String version,
      @RequestParam(value="validate", required=false) Boolean validate,
      @RequestParam(value="delay", required=false) Long delay,
      @RequestBody String body,
      HttpServletRequest request
   ) {
   log.info("Servicing mock response for service [{}, {}]", serviceName, version);
   log.debug("Toto");
   log.debug("Request body: " + body);

   long startTime = System.currentTimeMillis();

   // If serviceName was encoded with '+' instead of '%20', replace them.
   if (serviceName.contains("+")) {
      serviceName = serviceName.replace('+', ' ');
   }
   log.info("Service name: " + serviceName);
   // Retrieve service and correct operation.
   Service service = serviceRepository.findByNameAndVersion(serviceName, version);
   Operation rOperation = null;
   for (Operation operation : service.getOperations()) {
      // Enhancement : try getting operation from soap:body directly!
      if (hasPayloadCorrectStructureForOperation(body, operation.getInputName())) {
         rOperation = operation;
         log.info("Found valid operation {}", rOperation.getName());
         break;
      }
   }

   if (rOperation != null) {
      log.debug("Found a valid operation with rules: {}", rOperation.getDispatcherRules());

      if (validate != null && validate) {
         log.debug("Soap message validation is turned on, validating...");
         try {
            List<XmlError> errors = SoapMessageValidator.validateSoapMessage(
                  rOperation.getInputName(), service.getXmlNS(), body,
                  resourceUrl + service.getName() + "-" + version + ".wsdl", true);
            log.debug("SoapBody validation errors: " + errors.size());

            // Return a 400 http code with errors.
            if (errors != null && errors.size() > 0) {
               return new ResponseEntity<Object>(errors, HttpStatus.BAD_REQUEST);
            }
         } catch (Exception e) {
            log.error("Error during Soap validation", e);
         }
      }

      Response response = null;
      String dispatchCriteria = null;

      // Depending on dispatcher, evaluate request with rules.
      if (DispatchStyles.QUERY_MATCH.equals(rOperation.getDispatcher())) {
         dispatchCriteria = getDispatchCriteriaFromXPathEval(rOperation, body);

      } else if (DispatchStyles.SCRIPT.equals(rOperation.getDispatcher())) {
         dispatchCriteria = getDispatchCriteriaFromScriptEval(rOperation, body, request);
      }

      log.debug("Dispatch criteria for finding response is {}", dispatchCriteria);
      List<Response> responses = responseRepository.findByOperationIdAndDispatchCriteria(
            IdBuilder.buildOperationId(service, rOperation), dispatchCriteria);
      if (!responses.isEmpty()) {
         response = responses.get(0);
      }

      // Set Content-Type to "text/xml".
      HttpHeaders responseHeaders = new HttpHeaders();
      responseHeaders.setContentType(MediaType.valueOf("text/xml;charset=UTF-8"));

      // Render response content before waiting and returning.
      String responseContent = MockControllerCommons.renderResponseContent(body, null, request, response);

      // Setting delay to default one if not set.
      if (delay == null && rOperation.getDefaultDelay() != null) {
         delay = rOperation.getDefaultDelay();
      }
      MockControllerCommons.waitForDelay(startTime, delay);

      // Publish an invocation event before returning.
      MockControllerCommons.publishMockInvocation(applicationContext, this, service, response, startTime);

      if (response.isFault()) {
         return new ResponseEntity<Object>(responseContent, responseHeaders, HttpStatus.INTERNAL_SERVER_ERROR);
      }
      return new ResponseEntity<Object>(responseContent, responseHeaders, HttpStatus.OK);
   }

   log.debug("No valid operation found and Microcks...");
   return new ResponseEntity<Object>(HttpStatus.NOT_FOUND);
}
 
Example #7
Source File: SoapMessageValidator.java    From microcks with Apache License 2.0 4 votes vote down vote up
/**
 * Validate a soap message accordingly to its WSDL and linked XSD resources. The validation is
 * done for a specified message part (maybe be the input, output or fault of an operation).
 * @param partName The name of the part to validate ie. name of the input, output or fault part (ex: sayHello)
 * @param partNamespace The namespace of the part to validate (ex: http://www.mma.fr/test/service)
 * @param message The full soap message as a string
 * @param wsdlUrl The URL where we can resolve service and operation WSDL
 * @param validateMessageBody Should we validate also the body ? If false, only Soap envelope is validated.
 * @return The list of validation failures. If empty, message is valid !
 * @throws org.apache.xmlbeans.XmlException if given message is not a valid Xml document
 */
public static List<XmlError> validateSoapMessage(String partName, String partNamespace, String message, String wsdlUrl, boolean validateMessageBody) 
      throws XmlException {
   //
   WsdlContext ctx = new WsdlContext(wsdlUrl);
   List<XmlError> errors = new ArrayList<XmlError>();
   ctx.getSoapVersion().validateSoapEnvelope(message, errors);
   
   log.debug("SoapEnvelope validation errors: " + errors.size());

   if (validateMessageBody){
      // Create XmlBeans object for the soap message.
      XmlOptions xmlOptions = new XmlOptions();
      xmlOptions.setLoadLineNumbers();
      xmlOptions.setLoadLineNumbers( XmlOptions.LOAD_LINE_NUMBERS_END_ELEMENT );
      XmlObject xml = XmlUtils.createXmlObject(message, xmlOptions);

      // Build the QName string of the part name. Ex: {http://www.github.com/lbroudoux/service}sayHello
      String fullPartName = "{" + partNamespace + "}" + partName;
      
      // Extract the corresponding part from soap body.
      XmlObject[] paths = xml.selectPath( "declare namespace env='" + ctx.getSoapVersion().getEnvelopeNamespace() + "';" 
            + "declare namespace ns='" + partNamespace + "';" + "$this/env:Envelope/env:Body/ns:" + partName);
         
      SchemaGlobalElement elm;
      try {
         elm = ctx.getSchemaTypeLoader().findElement(QName.valueOf(fullPartName));
      } catch (Exception e) {
         log.error("Exception while loading schema information for " + fullPartName, e);
         throw new XmlException("Exception while loading schema information for " + fullPartName, e);
      }
      
      if ( elm != null ){
         validateMessageBody(ctx, errors, elm.getType(), paths[0]);
   
         // Ensure no other elements in body.
         NodeList children = XmlUtils.getChildElements((Element) paths[0].getDomNode().getParentNode());
         for (int c = 0; c < children.getLength(); c++){
            QName childName = XmlUtils.getQName(children.item(c));
            // Compare child QName to full part QName.
            if (!fullPartName.equals(childName.toString())){
               XmlCursor cur = paths[0].newCursor();
               cur.toParent();
               cur.toChild( childName );
               errors.add( XmlError.forCursor( "Invalid element [" + childName + "] in SOAP Body", cur ) );
               cur.dispose();
            }
         }
      }
      log.debug("SoapBody validation errors: " + errors.size());
   } 
   return errors;
}