Пример #1
0
  public GetSupportedTypesRequest(Document doc) throws ExceptionReport {

    try {
      XmlOptions option = new XmlOptions();
      option.setLoadTrimTextBuffer();
      this.supportedTypesDoc = GetSupportedTypesDocument.Factory.parse(doc, option);
      if (supportedTypesDoc == null) {
        LOGGER.error("GetSupportedTypesDocument is null");
        throw new ExceptionReport(
            "Error while parsing post data", ExceptionReport.MISSING_PARAMETER_VALUE);
      }
    } catch (XmlException e) {
      throw new ExceptionReport(
          "Error while parsing post data", ExceptionReport.MISSING_PARAMETER_VALUE, e);
    }

    this.complexTypesOnly = supportedTypesDoc.getGetSupportedTypes().getComplexTypesOnly();

    if (this.complexTypesOnly) {
      LOGGER.info("GetSupportedTypes for complex types only.");
    } else {
      LOGGER.info("GetSupportedTypes for all available types.");
    }

    responseBuilder = new GetSupportedTypesResponseBuilder(this);
    responseBuilder.updateSupportedTypes();
  }
Пример #2
0
  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;
  }
Пример #3
0
 public final String modelToXmlString() {
   TiersInformationsType object = (TiersInformationsType) this.modelToXml();
   XmlOptions opts = new XmlOptions();
   opts.setSavePrettyPrint();
   opts.setSavePrettyPrintIndent(4);
   opts.setUseDefaultNamespace();
   opts.setCharacterEncoding("UTF-8");
   return object.xmlText(opts);
 }
  /**
   * Builds the SRA {@link SpotDescriptorType}, this is taken from the ISATAB "sequencing" protocol
   * that has been used for this assay.
   *
   * <p>Some of these parameters are mandatory in SRA, and/or constrained to certain values, so the
   * method raises an exception in case they're not defined.
   */
  protected SpotDescriptorType buildExportedSpotDescriptor(Assay assay) {
    ProtocolApplication pApp = getProtocol(assay, "sequencing");
    if (pApp == null) {
      return null;
    }

    String barcode = getParameterValue(assay, pApp, "barcode", false);

    System.out.println("barcode: " + barcode);

    String adapterSpec = getParameterValue(assay, pApp, "Adapter Spec", false);
    String numOfSpotReads = getParameterValue(assay, pApp, "Number of reads per spot", false);

    boolean usesBarcode = (barcode != null);

    SRATemplate sraTemplateToInject =
        getSRATemplateToInject(SRASection.SPOT_DESCRIPTOR, assay, pApp, usesBarcode);

    SpotDescriptorType xspotd = SpotDescriptorType.Factory.newInstance();

    Map<SRAAttributes, String> userDefinedAttributes = new HashMap<SRAAttributes, String>();

    if (!StringUtils.isEmpty(adapterSpec)) {
      userDefinedAttributes.put(SRAAttributes.ADAPTER_SPEC, adapterSpec);
    }

    if (!StringUtils.isEmpty(numOfSpotReads)) {
      userDefinedAttributes.put(SRAAttributes.NUMBER_OF_READS_PER_SPOT, numOfSpotReads);
    }

    if (!StringUtils.isEmpty(barcode)) {
      userDefinedAttributes.put(SRAAttributes.READ_GROUP_TAG, barcode);
    }

    try {
      String sraTemplate =
          sraTemplateLoader.getSRAProcessingTemplate(sraTemplateToInject, userDefinedAttributes);

      System.out.println(sraTemplate);

      XmlOptions xmlOptions = new XmlOptions();
      xmlOptions.setDocumentType(SpotDescriptorType.Factory.newInstance().schemaType());

      XmlObject parsedAttr = XmlObject.Factory.parse(sraTemplate, xmlOptions);

      xspotd.set(parsedAttr);

      return xspotd;

    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (XmlException e) {
      e.printStackTrace();
    }

    return xspotd;
  }
Пример #5
0
 public static OMElement xmlObjectToOMElement(XmlObject responseXmlObj) throws XMLStreamException {
   String responseXml;
   XmlOptions opts = new XmlOptions();
   opts.setSaveOuter();
   responseXml = responseXmlObj.xmlText(opts);
   OMElement outgoingMsg =
       org.apache.airavata.commons.WorkFlowUtils.reader2OMElement(new StringReader(responseXml));
   return outgoingMsg;
 }
 @Override
 public final String modelToXmlString() {
   TechnicalInterventionRequestDocument object = this.modelToXml();
   XmlOptions opts = new XmlOptions();
   opts.setSavePrettyPrint();
   opts.setSavePrettyPrintIndent(4);
   opts.setUseDefaultNamespace();
   opts.setCharacterEncoding("UTF-8");
   return object.xmlText(opts);
 }
Пример #7
0
  @Override
  protected void commit() throws IOException {
    XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
    Map<String, String> map = new HashMap<String, String>();
    map.put(STRelationshipId.type.getName().getNamespaceURI(), "r");
    xmlOptions.setSaveSuggestedPrefixes(map);

    PackagePart part = getPackagePart();
    OutputStream out = part.getOutputStream();
    _presentation.save(out, xmlOptions);
    out.close();
  }
Пример #8
0
  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()]);
  }
Пример #9
0
  private void createConfigFile(
      String issuer,
      String nameQualifier,
      String ksType,
      String ksFile,
      String ksPassword,
      String privKeyAlias,
      String privKeyPassword,
      String certAlias)
      throws IOException {

    String SSO_CONFIG_FILE = "/WEB-INF/guanxi_idp/config/idp.xml";
    String KEYSTORE_KEY_TYPE = "dsa";

    IdpDocument idpDoc = null;
    try {
      idpDoc = IdpDocument.Factory.parse(new File(servletContext.getRealPath(SSO_CONFIG_FILE)));
    } catch (XmlException xe) {
      logger.error("Can't create config file", xe);
      return;
    }

    IdpDocument.Idp idp = idpDoc.getIdp();

    idp.getServiceProviderArray(0).setIdentity("exampleIdentity");
    idp.getServiceProviderArray(0).setCreds("exampleCreds");
    idp.getServiceProviderArray(0).setName("REPLACE_WITH_PROVIDER_ID_OF_SERVICE_PROVIDER");

    idp.getIdentityArray(0).setName("exampleIdentity");
    idp.getIdentityArray(0).setNameQualifier(nameQualifier);
    idp.getIdentityArray(0).setIssuer(issuer);

    idp.getCredsArray(0).setName("exampleCreds");
    idp.getCredsArray(0).setKeystoreType("jks");
    idp.getCredsArray(0).setKeyType(ksType);
    idp.getCredsArray(0).setKeystoreFile(ksFile);
    idp.getCredsArray(0).setKeystorePassword(ksPassword);
    idp.getCredsArray(0).setPrivateKeyAlias(privKeyAlias);
    idp.getCredsArray(0).setPrivateKeyPassword(privKeyPassword);
    idp.getCredsArray(0).setCertificateAlias(certAlias);
    idp.getCredsArray(0).setKeyType(KEYSTORE_KEY_TYPE);

    XmlOptions xmlOptions = new XmlOptions();
    xmlOptions.setSavePrettyPrint();
    xmlOptions.setSavePrettyPrintIndent(2);
    xmlOptions.setUseDefaultNamespace();

    idpDoc.save(new File(servletContext.getRealPath(SSO_CONFIG_FILE)), xmlOptions);

    servletContext.setAttribute(Guanxi.CONTEXT_ATTR_IDP_CONFIG_DOC, idpDoc);
    servletContext.setAttribute(Guanxi.CONTEXT_ATTR_IDP_CONFIG, idpDoc.getIdp());
  }
Пример #10
0
 public void saveConfiguration() {
   File file = getDefaultConfigurationFile();
   log.info("Storing current configuration in file: " + file.getAbsolutePath());
   try {
     XmlOptions opts = new XmlOptions();
     opts.setSavePrettyPrint();
     opts.setSavePrettyPrintIndent(4);
     configuration.save(file, opts);
   } catch (IOException e) {
     log.error("Unable to save the updated configuration in file: " + file.getAbsolutePath());
     throw new RuntimeException("Unable to save the updated configuration: " + e.getMessage());
   }
 }
Пример #11
0
  @Test
  public void validFullResponse() {
    XmlOptions opt = (new XmlOptions()).setSavePrettyPrint();
    opt.setSaveSuggestedPrefixes(Utilities.SuggestedNamespaces());
    opt.setSaveNamespacesFirst();
    opt.setSaveAggressiveNamespaces();
    opt.setUseDefaultNamespace();

    XmlObject co = completeResponse();
    ArrayList errorList = new ArrayList();
    boolean validXml = Utilities.validateXml(opt, co, errorList);
    assertTrue(errorList.toString(), validXml);
  }
  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;
  }
Пример #13
0
 /**
  * Returns an XMLBeans document as a String with full Fedora/RDF namespace support
  *
  * @param doc The document to parse to a String
  * @return String version of the document. This will contain prefixes for rdf and myns
  */
 public static String xmlToString(XmlObject doc) {
   HashMap<String, String> namespaces = new HashMap<String, String>();
   namespaces.put("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf");
   namespaces.put("http://www.nsdl.org/ontologies/relationships#", "myns");
   XmlOptions xmlOptions = new XmlOptions();
   xmlOptions.setSaveSuggestedPrefixes(namespaces);
   xmlOptions.setSaveAggressiveNamespaces();
   StringWriter out = new StringWriter();
   try {
     doc.save(out, xmlOptions);
     return out.toString();
   } catch (Exception e) {
     return null;
   }
 }
Пример #14
0
  @Override
  protected void commit() throws IOException {

    XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
    xmlOptions.setSaveSyntheticDocumentElement(
        new QName(CTSettings.type.getName().getNamespaceURI(), "settings"));
    Map<String, String> map = new HashMap<String, String>();
    map.put("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w");
    xmlOptions.setSaveSuggestedPrefixes(map);

    PackagePart part = getPackagePart();
    OutputStream out = part.getOutputStream();
    ctSettings.save(out, xmlOptions);
    out.close();
  }
Пример #15
0
  @Override
  public InputStream generateStream(IData data, String mimeType, String schema) throws IOException {

    if (data instanceof GenericXMLDataBinding) {

      XmlObject xmlData = ((GenericXMLDataBinding) data).getPayload();

      XmlOptions xmlOptions = new XmlOptions();

      xmlOptions.setSaveNoXmlDecl();

      return xmlData.newInputStream(xmlOptions);
    }

    return XmlObject.Factory.newInstance().newInputStream();
  }
Пример #16
0
  /**
   * Dumps an XML document to disk.
   *
   * @param doc The document to dump to disk
   * @param filePath The full path and name of the file
   */
  public static void dumpXML(XmlObject doc, String filePath) {
    HashMap<String, String> namespaces = new HashMap<String, String>();
    namespaces.put("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf");
    namespaces.put("http://www.nsdl.org/ontologies/relationships#", "myns");
    XmlOptions xmlOptions = new XmlOptions();
    xmlOptions.setSavePrettyPrint();
    xmlOptions.setSavePrettyPrintIndent(2);
    // xmlOptions.setUseDefaultNamespace();
    // xmlOptions.setSaveAggressiveNamespaces();
    xmlOptions.setSaveSuggestedPrefixes(namespaces);
    // xmlOptions.setSaveNamespacesFirst();

    try {
      doc.save(new File(filePath), xmlOptions);
    } catch (Exception e) {
    }
  }
Пример #17
0
  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");
      }
    }
  }
Пример #18
0
  public static String createSampleForElement(SchemaGlobalElement element) {
    XmlObject xml = XmlObject.Factory.newInstance();

    XmlCursor c = xml.newCursor();
    c.toNextToken();
    c.beginElement(element.getName());

    new SampleXmlUtil(false).createSampleForType(element.getType(), c);

    c.dispose();

    XmlOptions options = new XmlOptions();
    options.put(XmlOptions.SAVE_PRETTY_PRINT);
    options.put(XmlOptions.SAVE_PRETTY_PRINT_INDENT, 3);
    options.put(XmlOptions.SAVE_AGGRESSIVE_NAMESPACES);
    options.setSaveOuter();
    String result = xml.xmlText(options);

    return result;
  }
Пример #19
0
 /** save and commit numbering */
 @Override
 protected void commit() throws IOException {
   XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
   xmlOptions.setSaveSyntheticDocumentElement(
       new QName(CTNumbering.type.getName().getNamespaceURI(), "numbering"));
   Map map = new HashMap();
   map.put("http://schemas.openxmlformats.org/markup-compatibility/2006", "ve");
   map.put("urn:schemas-microsoft-com:office:office", "o");
   map.put("http://schemas.openxmlformats.org/officeDocument/2006/relationships", "r");
   map.put("http://schemas.openxmlformats.org/officeDocument/2006/math", "m");
   map.put("urn:schemas-microsoft-com:vml", "v");
   map.put("http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing", "wp");
   map.put("urn:schemas-microsoft-com:office:word", "w10");
   map.put("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w");
   map.put("http://schemas.microsoft.com/office/word/2006/wordml", "wne");
   xmlOptions.setSaveSuggestedPrefixes(map);
   PackagePart part = getPackagePart();
   OutputStream out = part.getOutputStream();
   ctNumbering.save(out, xmlOptions);
   out.close();
 }
Пример #20
0
  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);
  }
Пример #21
0
  private SoapVersion11() {
    try {
      XmlOptions options = new XmlOptions();
      options.setCompileNoValidation();
      options.setCompileNoPvrRule();
      options.setCompileDownloadUrls();
      options.setCompileNoUpaRule();
      options.setValidateTreatLaxAsSkip();

      URL soapSchemaXmlResource =
          ResourceUtils.getResourceWithAbsolutePackagePath(
              getClass(), "/xsds/", "soapEnvelope.xsd");
      soapSchemaXml = XmlUtils.createXmlObject(soapSchemaXmlResource, options);
      soapSchema = XmlBeans.loadXsd(new XmlObject[] {soapSchemaXml});

      soapEnvelopeType = soapSchema.findDocumentType(envelopeQName);
      soapFaultType = soapSchema.findDocumentType(faultQName);

      URL soapEncodingXmlResource =
          ResourceUtils.getResourceWithAbsolutePackagePath(
              getClass(), "/xsds/", "soapEncoding.xsd");
      soapEncodingXml = XmlUtils.createXmlObject(soapEncodingXmlResource, options);

    } catch (XmlException ex) {
      throw new SoapBuilderException(ex);
    }
  }
Пример #22
0
  private byte[] generateXml(
      Integer demographicNo, Integer rourkeFdid, Integer nddsFdid, Integer report18mFdid) {
    HashMap<String, String> suggestedPrefixes = new HashMap<String, String>();
    suggestedPrefixes.put("http://www.w3.org/2001/XMLSchema-instance", "xsi");
    XmlOptions opts = new XmlOptions();
    opts.setSaveSuggestedPrefixes(suggestedPrefixes);
    opts.setSavePrettyPrint();
    opts.setSaveNoXmlDecl();
    opts.setUseDefaultNamespace();
    opts.setSaveNamespacesFirst();
    ByteArrayOutputStream os = null;
    PrintWriter pw = null;
    boolean xmlCreated = false;

    BORN18MFormToXML xml = new BORN18MFormToXML(demographicNo);
    try {
      os = new ByteArrayOutputStream();
      pw = new PrintWriter(os, true);
      pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
      xmlCreated = xml.addXmlToStream(pw, opts, rourkeFdid, nddsFdid, report18mFdid);

      pw.close();
      if (xmlCreated) return os.toByteArray();
    } catch (Exception e) {
      logger.warn("Unable to add record", e);
    }

    return null;
  }
Пример #23
0
  public static String createSampleForType(SchemaType sType) {
    XmlObject object = XmlObject.Factory.newInstance();
    XmlCursor cursor = object.newCursor();
    // Skip the document node
    cursor.toNextToken();
    // Using the type and the cursor, call the utility method to get a
    // sample XML payload for that Schema element
    new SampleXmlUtil(false).createSampleForType(sType, cursor);
    // Cursor now contains the sample payload
    // Pretty print the result. Note that the cursor is positioned at the
    // end of the doc so we use the original xml object that the cursor was
    // created upon to do the xmlText() against.

    cursor.dispose();
    XmlOptions options = new XmlOptions();
    options.put(XmlOptions.SAVE_PRETTY_PRINT);
    options.put(XmlOptions.SAVE_PRETTY_PRINT_INDENT, 3);
    options.put(XmlOptions.SAVE_AGGRESSIVE_NAMESPACES);
    options.setSaveOuter();
    String result = object.xmlText(options);

    return result;
  }
  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());
      }
    }
  }
Пример #25
0
 /**
  * Generate the ExceptionReport as an XML string.
  *
  * @return the ExceptionReport as an XML string
  */
 public String getXMLExceptionReport() {
   Map<String, String> suggestedPrefixes = new HashMap<String, String>();
   suggestedPrefixes.put("http://www.opengis.net/ows/2.0", "ows");
   XmlOptions opts = new XmlOptions();
   opts.setSavePrettyPrint();
   opts.setSaveSuggestedPrefixes(suggestedPrefixes);
   opts.setSaveNamespacesFirst();
   opts.setSaveAggressiveNamespaces();
   opts.setUseDefaultNamespace();
   return exceptionReportDoc.xmlText(opts);
 }
  @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);
      }
    }
  }
Пример #27
0
 public ReginfoHandler() {
   _xmlOptions = new XmlOptions();
   _xmlOptions.setUseDefaultNamespace();
   _xmlOptions.setSavePrettyPrint();
 }
  public static void main(String[] args) throws Exception {

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("DownloadContraArticlesJPA");
    em = emf.createEntityManager();
    SimpleDateFormat dtf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String outfolder = "import-stories-arch-1";

    opt = new XmlOptions();
    opt.setUseCDataBookmarks();
    opt.setSaveCDataLengthThreshold(0);
    opt.setSaveCDataEntityCountThreshold(-1);

    int i = 0;
    int maxResults = 1000;

    competitions = em.createQuery(" SELECT c FROM Competition c ").getResultList();
    sports = em.createQuery(" SELECT c FROM Sport c ").getResultList();

    Query q = em.createQuery(queryString).setFirstResult(i * maxResults).setMaxResults(maxResults);
    List<Articles_Archives100_130000> results = q.getResultList();

    while (!results.isEmpty()) {
      EscenicDocument escenicDocument = EscenicDocument.Factory.newInstance(opt);
      initializeEscenic(escenicDocument);
      for (Articles_Archives100_130000 article : results) {

        Content content = escenicDocument.getEscenic().addNewContent();
        content.addNewSource().setStringValue("ContraNews");
        content.addNewSourceid().setStringValue(Integer.toString(article.getArticleID()));
        content.addNewType().setStringValue("news");
        content.setState(State.PUBLISHED);
        content.addNewPublishdate().setStringValue(dtf.format(article.getArticleDate()));
        content.addNewCreationdate().setStringValue(dtf.format(article.getArticleDate()));

        SectionRef sectionRef = content.addNewSectionRef();
        try {
          if (article.getCompetition().getCompetitionID() != 0) {
            sectionRef
                .addNewUniqueName()
                .setStringValue(article.getCompetition().getCompetitionName_url());
          } else if (article.getCompetition().getCompetitionID() == 0
              && article.getPlace().getPlaceID() != 0
              && article.getSport().getSportID() != 0
              && existCompetition(article.getSport(), article.getPlace())) {
            sectionRef
                .addNewUniqueName()
                .setStringValue(
                    article.getPlace().getPlaceName_url()
                        + "_"
                        + article.getSport().getSportName_url());
          } else if (article.getSport().getSportID() != 0) {
            sectionRef.addNewUniqueName().setStringValue(article.getSport().getSportName_url());
          } else {
            sectionRef.addNewUniqueName().setStringValue("ece_incoming");
          }
        } catch (Exception e) {
          System.out.println("No section found for article" + article.getArticleID());
          throw new Exception(e.getMessage());
        }

        if (article.getSubSection().getSubSectionID() != 1) {
          sectionRef = content.addNewSectionRef();
          sectionRef
              .addNewUniqueName()
              .setStringValue(article.getSubSection().getSubSectionName_url());
        }
        sectionRef.setHomeSection(true);

        //				List<Image> images = em.createQuery(" SELECT i FROM Image i WHERE i.articleId = " +
        // article.getId()).getResultList();
        //
        //				for (Image image : images) {
        //					// picture relation

        //				if(article.getArticlePhoto() !=null && !article.getArticlePhoto().trim().isEmpty()){
        //					String fullPath = "/home/vassilis/Pictures/contra/"+article.getArticlePhoto().trim();
        //
        //					//check if file
        //					if(new File(fullPath).exists()){
        //						Relation relation = content.addNewRelation();
        //						relation.addNewType().setStringValue("PICTUREREL");
        //						relation.addNewSource().setStringValue("ContraImages");
        //						relation.addNewSourceid().setStringValue(article.getArticlePhoto().trim());
        //					}
        //				}

        if (article.getLinks() != null) {
          for (String articleId : article.getLinks().split(",")) {
            articleId = articleId.trim();
            if (articleId.isEmpty()) continue;

            if (articleId.startsWith("ph")) {
              //						try {
              //							em.createQuery("SELECT p.photoStoryID FROM PhotoStory p WHERE p.photoStoryID
              // = :thePhotoStoryID ")
              //							.setParameter("thePhotoStoryID",
              // Integer.valueOf(articleId.toLowerCase().replaceAll("ph", "")))
              //							.getSingleResult();
              //							Relation relationStory = content.addNewRelation();
              //							relationStory.addNewType().setStringValue("PHOTOSTORYREL");
              //							relationStory.addNewSource().setStringValue("ContraPhotostory");
              //							relationStory.addNewSourceid().setStringValue(articleId.replaceAll("ph",
              // ""));
              //						} catch (Exception e) {
              //							e.printStackTrace();
              //							System.out.println("No PhotoStory found with id " +
              // articleId.replaceAll("ph", ""));
              //						}
            } else if (!articleId.matches("[0-9]*")) {
              continue;
            } else {
              Relation relationStory = content.addNewRelation();
              relationStory.addNewType().setStringValue("STORYREL");
              relationStory.addNewSource().setStringValue("ContraNews");
              relationStory.addNewSourceid().setStringValue(articleId);
            }
          }
        }
        if (article.getTeam1() != null
            && article.getTeam1().getTeamID() > 0
            && article.getTeam1().getTeamName_url() != null) {
          Relation relationTag = content.addNewRelation();
          relationTag.addNewType().setStringValue("TAGREL");
          relationTag.addNewSource().setStringValue("ContraTags");
          relationTag
              .addNewSourceid()
              .setStringValue(Integer.toString(article.getTeam1().getTeamID()));
        }

        if (article.getTeam2() != null
            && article.getTeam2().getTeamID() > 0
            && article.getTeam2().getTeamName_url() != null) {
          Relation relationTag = content.addNewRelation();
          relationTag.addNewType().setStringValue("TAGREL");
          relationTag.addNewSource().setStringValue("ContraTags");
          relationTag
              .addNewSourceid()
              .setStringValue(Integer.toString(article.getTeam2().getTeamID()));
        }
        //					Field titlePictureField = relation.addNewField();
        //					titlePictureField.addNewName().setStringValue("title");
        //					titlePictureField.newCursor().setTextValue(image.getCaption());
        //
        //					Field captionTitlePictureField = relation.addNewField();
        //					captionTitlePictureField.addNewName().setStringValue("captiontitle");
        //					Field captionPictureField = relation.addNewField();
        //					captionPictureField.addNewName().setStringValue("caption");
        //					captionPictureField.newCursor().setTextValue(image.getCaption());
        //				}
        Priority priority = content.addNewPriority();
        priority.setValue(0);

        Field titleField = content.addNewField();
        titleField.addNewName().setStringValue("title");
        titleField.newCursor().setTextValue(article.getArticleTitle());
        ////				Field superTitleField = content.addNewField();
        ////				superTitleField.addNewName().setStringValue("supertitle");
        ////				superTitleField.newCursor().setTextValue(article.getTitle());
        //
        Field leadtextField = content.addNewField();
        leadtextField.addNewName().setStringValue("leadtext");
        leadtextField
            .newCursor()
            .setTextValue(
                article.getArticleSummary() == null
                    ? ""
                    : article.getArticleSummary().replaceAll("\\<.*?\\>", ""));
        //				Field quoteField = content.addNewField();
        //				quoteField.addNewName().setStringValue("quote");

        if (article.getArticleBody() != null && !article.getArticleBody().trim().isEmpty()) {
          Field bodyField = content.addNewField();
          bodyField.addNewName().setStringValue("body");
          //				//body
          XmlCursor bodyCursor = bodyField.newCursor();
          bodyCursor.xmlText(opt);
          String fixedBody = article.getArticleBody().trim();
          fixedBody = HTMLFilter.fixHtml(fixedBody);
          bodyCursor.setTextValue(fixedBody);
        }
        //
        Field bylineField = content.addNewField();
        bylineField.addNewName().setStringValue("byline");
        bylineField
            .newCursor()
            .setTextValue(
                article.getArticleAuthor() == null ? "" : article.getArticleAuthor().trim());

        String tagFieldString = "";
        if (article.getTeam1() != null
            && article.getTeam1().getTeamID() > 0
            && article.getTeam1().getTeamName_url() != null) {
          tagFieldString = "tagppo" + article.getTeam1().getTeamName_url().toLowerCase();
        }

        if (article.getTeam2() != null
            && article.getTeam2().getTeamID() > 0
            && article.getTeam2().getTeamName_url() != null) {
          tagFieldString =
              tagFieldString + " tagppo" + article.getTeam2().getTeamName_url().toLowerCase();
        }

        if (!tagFieldString.isEmpty()) {
          Field tagField = content.addNewField();
          tagField.addNewName().setStringValue("tag");
          tagField.newCursor().setTextValue(tagFieldString);
        }

        //
        //
        //				if(article.getTeam1()!=null && article.getTeam1().getTeamID()!=0){
        //					Tag tag = content.addNewTag();
        //					tag.newCursor().setTextValue(article.getTeam1().getTeamName_url());
        //				}
        //
        //				if(article.getTeam2()!=null && article.getTeam2().getTeamID()!=0){
        //					Tag tag = content.addNewTag();
        //					tag.newCursor().setTextValue(article.getTeam2().getTeamName_url());
        //				}

        //				Field bylineprefixField = content.addNewField();
        //				bylineprefixField.addNewName().setStringValue("bylineprefix");
        //
        //				Field notesField = content.addNewField();
        //				notesField.addNewName().setStringValue("notes");
        //
        //				Field geocodeField = content.addNewField();
        //				geocodeField.addNewName().setStringValue("com.escenic.geocode");
      }

      String counterString = "";
      ++i;
      if (i < 10) {
        counterString = "000";
      } else if (i < 100) {
        counterString = "00";
      } else if (i < 1000) {
        counterString = "0";
      } else if (i < 10000) {
        counterString = "";
      }
      counterString = counterString + i;

      String outFileName = outfolder + "/stories1-arch" + (counterString) + ".xml";
      File f = new File(outFileName);
      escenicDocument.save(f);

      q = em.createQuery(queryString).setFirstResult(i * maxResults).setMaxResults(maxResults);
      results = q.getResultList();
    }
    ReplaceCDATA.replace(outfolder);
  }
Пример #29
0
  @Override
  public void process(ProcessletInputs in, ProcessletOutputs out, ProcessletExecutionInfo info)
      throws ProcessletException {
    try {

      // validate against allowed values in process definition file
      URL processDefinitionUrl =
          this.getClass().getResource("/" + this.getClass().getSimpleName() + ".xml");

      // get validated data inputs or default values
      DataInputHandler dataInputHandler =
          new DataInputHandler(new File(processDefinitionUrl.toURI()));
      String srsName = dataInputHandler.getValidatedStringValue(in, "srsName");
      String filter = dataInputHandler.getValidatedStringValue(in, "filter");
      double x = DataInputHandler.getDoubleInputValue(in, "x");
      double y = DataInputHandler.getDoubleInputValue(in, "y");
      double z = DataInputHandler.getDoubleInputValue(in, "z");

      LOG.debug(
          String.format(
              "DataInputs: srsName: %s, poi: (%f, %f, %f), filter: %s", srsName, x, y, z, filter));

      responseValues = new ResponseValues();
      responseValues.clientSrsName = srsName;

      // transform non-AGEA coordinates to AGEA
      if (!srsName.equals("Mouse_AGEA_1.0")) {
        ABAServiceVO vo = getTransformPOI(srsName, x, y, z);
        if (vo.getTransformationXMLResponseString().startsWith("Error:")) {
          throw new OWSException(
              "Transformation Coordinates Error: ", vo.getTransformationXMLResponseString());
        }
        x = Double.parseDouble(vo.getTransformedCoordinateX());
        y = Double.parseDouble(vo.getTransformedCoordinateY());
        z = Double.parseDouble(vo.getTransformedCoordinateZ());
      }

      LOG.debug("X from Transformation Method: " + x);
      LOG.debug("Y from Transformation Method: " + y);
      LOG.debug("Z from Transformation Method: " + z);

      String srsFromClient = srsName;
      Point3d poiFromClient = new Point3d(x, y, z);

      // get plane; defaults to sagittal
      ImageSeriesPlane desiredPlane =
          filter.equals("maptype:coronal") ? ImageSeriesPlane.CORONAL : ImageSeriesPlane.SAGITTAL;

      // 1. get strong gene(s) at POI
      List<ABAGene> strongGenes = ABAUtil.retrieveStrongGenesAtAGEAPOI(x, y, z, NBR_STRONG_GENES);

      // make sure we have something
      if (strongGenes.size() == 0) {
        throw new OWSException(
            "No 'strong genes' found at " + "coordinates, hence no images to return.",
            ControllerException.NO_APPLICABLE_CODE);
      }

      if (LOG.isDebugEnabled()) {
        StringBuilder buf = new StringBuilder();
        for (ABAGene gene : strongGenes) {
          buf.append(gene.getGenesymbol()).append(", ");
        }
        LOG.debug("Strong genes: {}", buf.toString());
      }

      // 2. get image series'es for strong genes and desired plane
      List<ImageSeries> imageSerieses = new ArrayList<ImageSeries>();
      for (ABAGene gene : strongGenes) {
        ImageSeries imageSeries = retrieveImagesSeriesForGene(gene.getGenesymbol(), desiredPlane);
        if (imageSeries != null) {
          imageSerieses.add(imageSeries);
        }
      }

      // make sure we have something
      if (imageSerieses.size() == 0) {
        throw new OWSException(
            "No image series found for 'strong "
                + "genes' and desired plane, hence no images to "
                + "return.",
            ControllerException.NO_APPLICABLE_CODE);
      }

      if (LOG.isDebugEnabled()) {
        StringBuilder buf = new StringBuilder();
        for (ImageSeries is : imageSerieses) {
          buf.append(is.imageSeriesId).append(':');
          buf.append(is.imageSeriesPlane).append(", ");
        }
        LOG.debug("Image Serieses id:plane: {}", buf.toString());
      }

      Point3d poiForProximity = new Point3d(poiFromClient);

      // divide POI coords by 100
      Point3d poi100 = new Point3d();
      poi100.scale(0.01, poiForProximity);

      LOG.debug("POI for closest position (srs, xyz): {}, {}", srsFromClient, poi100.toString());

      // 3. get ......... for each image series
      for (ImageSeries imageSeries : imageSerieses) {

        // begin to add values to image
        Image image = new Image(imageSeries.imageSeriesId);

        // get atlas map
        // find closest point, get other values including position
        // add more (atlas map) values to image
        getClosestPosition(imageSeries, poi100, image);

        LOG.debug("Position: {}", image.abaImagePosition);

        // get best image id in image series based on position
        // add more (image elements) values to image
        // match position to find image in series, get imageid
        //  /image-series/images/image/position
        //  /image-series/images/image/imageid
        retrieveImageForPosition(imageSeries.imageSeriesId, image.abaImagePosition, image);

        LOG.debug("Image id: {}", image.imageId);

        // zoom level not applicable
        // image.zoomLevel = zoomLevel;

        // assemble aba view image uri
        image.imageURI = assembleImageURI(image.downloadImagePath, HI_RES, MIME);
        image.thumbnailurl = assembleImageURI(image.downloadImagePath, THUMB, MIME);

        LOG.debug("Image URI: {}", image.imageURI.toString());

        responseValues.images.add(image);
      } // for

      // ImagesResponseDocument 'is a' org.apache.xmlbeans.XmlObject
      //	'is a' org.apache.xmlbeans.XmlTokenSource
      ImagesResponseDocument document = completeResponse();

      if (LOG.isDebugEnabled()) {
        XmlOptions opt = (new XmlOptions()).setSavePrettyPrint();
        opt.setSaveSuggestedPrefixes(Utilities.SuggestedNamespaces());
        opt.setSaveNamespacesFirst();
        opt.setSaveAggressiveNamespaces();
        opt.setUseDefaultNamespace();
        LOG.debug("Xml:\n{}", document.xmlText(opt));
      }

      // 4. Send it
      // get reader on document
      XMLStreamReader reader = document.newXMLStreamReader();

      // get ComplexOutput object from ProcessletOutput...
      ComplexOutput complexOutput = (ComplexOutput) out.getParameter("Get2DImagesByPOIOutput");

      LOG.debug("Setting complex output (requested=" + complexOutput.isRequested() + ")");

      // ComplexOutput objects can be huge so stream it
      XMLStreamWriter writer = complexOutput.getXMLStreamWriter();
      XMLAdapter.writeElement(writer, reader);

      // transform any exceptions into ProcessletException wrapping
      // OWSException
    } catch (MissingParameterException e) {
      LOG.error(e.getMessage(), e);
      throw new ProcessletException(new OWSException(e));
    } catch (InvalidParameterValueException e) {
      LOG.error(e.getMessage(), e);
      throw new ProcessletException(new OWSException(e));
    } catch (InvalidDataInputValueException e) {
      LOG.error(e.getMessage(), e);
      throw new ProcessletException(e); // is already OWSException
    } catch (OWSException e) {
      LOG.error(e.getMessage(), e);
      throw new ProcessletException(e); // is already OWSException
    } catch (Throwable e) {
      String message = "Unexpected exception occurred: " + e.getMessage();
      LOG.error(message, e);
      throw new ProcessletException(
          new OWSException(message, e, ControllerException.NO_APPLICABLE_CODE));
    }
  }
  /**
   * Builds the SRA {@link PROCESSING}, this is taken from the ISATAB "sequencing" protocol that has
   * been used for this assay.
   *
   * <p>Some of these parameters are mandatory in SRA, and/or constrained to certain values, so the
   * method raises an exception in case they're not defined.
   */
  protected PROCESSING buildExportedProcessing(final Assay assay) {
    ProtocolApplication pApp = getProtocol(assay, "sequencing");

    SRATemplate sraTemplateToInject = getSRATemplateToInject(SRASection.PROCESSING, assay, pApp);

    String seqSpaceStr = getParameterValue(assay, pApp, "Sequence space", false);

    String baseCaller = getParameterValue(assay, pApp, "Base caller", false);

    String qualityScorer = getParameterValue(assay, pApp, "Quality scorer", false);

    String numberOfLevels = getParameterValue(assay, pApp, "Number of levels", false);

    String multiplier = getParameterValue(assay, pApp, "Multiplier", false);

    Map<SRAAttributes, String> userDefinedAttributes = new HashMap<SRAAttributes, String>();

    if (!StringUtils.isEmpty(seqSpaceStr)) {
      userDefinedAttributes.put(SRAAttributes.SEQUENCE_SPACE, seqSpaceStr);
    }

    if (!StringUtils.isEmpty(baseCaller)) {
      userDefinedAttributes.put(SRAAttributes.BASE_CALLER, baseCaller);
    }

    if (!StringUtils.isEmpty(qualityScorer)) {
      userDefinedAttributes.put(SRAAttributes.QUALITY_SCORER, qualityScorer);
    }

    if (!StringUtils.isEmpty(numberOfLevels)) {
      userDefinedAttributes.put(SRAAttributes.NUMBER_OF_LEVELS, numberOfLevels);
    }

    if (!StringUtils.isEmpty(multiplier)) {
      userDefinedAttributes.put(SRAAttributes.MULTIPLIER, multiplier);
    }

    // TODO: modify to pull out the technology and library using Parameter Value[platform] &
    // ParameterValue[library layout] respectively
    // TODO: PRS-> according to new configuration for sequencing, Parameter Value[library layout] is
    // moved to the library construction protocol
    // TODO: PRS-> replace Parameter Value[platform] with Parameter Value[sequencing instrument] and
    // checks on values.
    // TODO: PRS-> add support for Immunoprecipitation techniques, requires detection of Protocol
    // TODO: PRS-> add support for 'Targeted Loci' in SRA experiment and find in ISA-TAB file if
    // assay is environmental gene survey

    try {
      String sraTemplate =
          sraTemplateLoader.getSRAProcessingTemplate(sraTemplateToInject, userDefinedAttributes);

      XmlOptions xmlOptions = new XmlOptions();
      xmlOptions.setDocumentType(PROCESSING.Factory.newInstance().schemaType());

      PROCESSING processing = PROCESSING.Factory.newInstance();

      XmlObject processingObject = XmlObject.Factory.parse(sraTemplate, xmlOptions);

      processing.set(processingObject);
      return processing;

    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (XmlException e) {
      e.printStackTrace();
    }

    return PROCESSING.Factory.newInstance();
  }