コード例 #1
0
 /**
  * This method is used to get RRFedNonFedBudget from BudgetSubAwards
  *
  * @param budgetSubAwards(BudgetSubAwards) budget sub awards entry.
  * @return RRFedNonFedBudget corresponding to the BudgetSubAwards object.
  */
 private RRFedNonFedBudgetDocument getRRFedNonFedBudget(BudgetSubAwards budgetSubAwards) {
   RRFedNonFedBudgetDocument rrBudget = RRFedNonFedBudgetDocument.Factory.newInstance();
   String subAwdXML = budgetSubAwards.getSubAwardXmlFileData();
   Document subAwdFormsDoc;
   try {
     subAwdFormsDoc = stringToDom(subAwdXML);
   } catch (S2SException e1) {
     return rrBudget;
   }
   Element subAwdFormsElement = subAwdFormsDoc.getDocumentElement();
   NodeList subAwdNodeList =
       subAwdFormsElement.getElementsByTagNameNS(
           RR_FED_NON_FED_BUDGET30_11_NAMESPACE_URI, LOCAL_FED_NON_FED_NAME);
   Node subAwdNode = null;
   if (subAwdNodeList != null) {
     if (subAwdNodeList.getLength() == 0) {
       return null;
     }
     subAwdNode = subAwdNodeList.item(0);
   }
   byte[] subAwdNodeBytes = null;
   try {
     subAwdNodeBytes = docToBytes(nodeToDom(subAwdNode));
     InputStream bgtIS = new ByteArrayInputStream(subAwdNodeBytes);
     rrBudget = (RRFedNonFedBudgetDocument) XmlObject.Factory.parse(bgtIS);
   } catch (S2SException e) {
     return rrBudget;
   } catch (XmlException e) {
     return rrBudget;
   } catch (IOException e) {
     return rrBudget;
   }
   return rrBudget;
 }
コード例 #2
0
ファイル: XmlHelper.java プロジェクト: shane-axiom/SOS
 /**
  * Parse XML document from HTTP-Post request.
  *
  * @param request HTTP-Post request
  * @return XML document
  * @throws OwsExceptionReport If an error occurs
  */
 public static XmlObject parseXmlSosRequest(final HttpServletRequest request)
     throws OwsExceptionReport {
   XmlObject doc;
   try {
     if (request.getParameterMap().isEmpty()) {
       final String requestContent =
           StringHelper.convertStreamToString(
               HTTPUtils.getInputStream(request), request.getCharacterEncoding());
       doc = parseXmlString(requestContent);
     } else {
       doc =
           XmlObject.Factory.parse(
               SosHelper.parseHttpPostBodyWithParameter(
                   request.getParameterNames(), request.getParameterMap()));
     }
   } catch (final XmlException xmle) {
     throw new NoApplicableCodeException()
         .causedBy(xmle)
         .withMessage(
             "An xml error occured when parsing the request! Message: %s", xmle.getMessage());
   } catch (final IOException ioe) {
     throw new NoApplicableCodeException()
         .causedBy(ioe)
         .withMessage("Error while reading request! Message: %s", ioe.getMessage());
   }
   // validateDocument(doc);
   return doc;
 }
コード例 #3
0
 public void afterSubmit(Submit submit, SubmitContext context) {
   if (submit.getResponse() == null) return;
   HttpResponse httpResponse = (HttpResponse) submit.getResponse();
   String content = httpResponse.getContentAsXml();
   if (content == null || content.equals("<xml/>")) return;
   XmlObject xml;
   try {
     URL url = httpResponse.getURL();
     String defaultNamespace = url.getProtocol() + "://" + url.getHost();
     XmlOptions options =
         new XmlOptions()
             .setLoadSubstituteNamespaces(Collections.singletonMap("", defaultNamespace));
     xml = XmlObject.Factory.parse(content, options);
   } catch (XmlException e) {
     e.printStackTrace();
     return;
   }
   if (!submit.getStatus().equals(Status.CANCELED)
       && !InferredSchemaManager.getInferredSchema(service).validate(xml)) {
     setTitle("Schema (conflicts)");
     if (thread != null && thread.isAlive()) {
       handler.kill();
       try {
         thread.join();
       } catch (InterruptedException e) {
         e.printStackTrace();
       }
     }
     handler = new Handler(tabs, xml);
     thread = new Thread(handler);
     thread.start();
   }
 }
コード例 #4
0
  /**
   * HAVE message notification handler.
   *
   * @param message the message
   * @ssdd
   */
  @Override
  public void haveMessageNotificationHandler(Core2CoreMessage message) {

    log.debug("haveMessageNotificationHandler: received messagefrom " + message.getFromCore());
    // =[" + message.getMessage()+ "]

    XmlObject xmlObj;
    try {

      EDXLDistributionDocument edxlDoc =
          EDXLDistributionDocument.Factory.parse(message.getMessage());

      if (edxlDoc.getEDXLDistribution().sizeOfExplicitAddressArray() > 0) {
        // Find core name for each explicit address.
        for (ValueSchemeType type : edxlDoc.getEDXLDistribution().getExplicitAddressArray()) {
          if (type.getExplicitAddressScheme()
              .equals(CommunicationsService.UICDSExplicitAddressScheme)) {
            for (String address : type.getExplicitAddressValueArray()) {
              xmlObj = XmlObject.Factory.parse(edxlDoc.toString());
              // log.debug("broadcastMessageNotificationHandler: sending notification ["
              // + xmlObj.toString() + "]  to " + address);
              sendMessageNotification(xmlObj, address);
            }
          }
        }
      }

    } catch (Throwable e) {
      log.error(
          "resourceMessageNotificationHandler: Error parsing message - not a valid XML string");
      throw new IllegalArgumentException("Message is not a valid XML string");
    }
  }
コード例 #5
0
 /**
  * Creates the administrative metadata section of a mets document.
  *
  * @param id the id of this amdSec
  * @param owner the rights owner of the item
  * @param logo the logo of the organization
  * @param url the url of the organization
  * @param reference the items url
  */
 public void createAmdSec(String id, String owner, String logo, String url, String reference) {
   this.amdSec = this.mets.addNewAmdSec();
   this.amdSec.setID(id);
   // DVRights
   MdSecType rightsMD = this.amdSec.addNewRightsMD();
   rightsMD.setID("rights" + id);
   MdWrap wrap = rightsMD.addNewMdWrap();
   wrap.setMIMETYPE("text/xml");
   wrap.setMDTYPE(MdWrap.MDTYPE.OTHER);
   wrap.setOTHERMDTYPE("DVRIGHTS");
   XmlData xml = wrap.addNewXmlData();
   XmlObject dvrights = XmlObject.Factory.newInstance();
   XmlCursor cur = dvrights.newCursor();
   cur.toNextToken();
   cur.beginElement("rights", "http://dfg-viewer.de/");
   cur.insertElementWithText("owner", "http://dfg-viewer.de/", owner);
   cur.insertElementWithText("ownerLogo", "http://dfg-viewer.de/", logo);
   cur.insertElementWithText("ownerSiteURL", "http://dfg-viewer.de/", url);
   cur.insertElementWithText("contact", "http://dfg-viewer.de/", "*****@*****.**");
   cur.dispose();
   xml.set(dvrights);
   wrap.setXmlData(xml);
   rightsMD.setMdWrap(wrap);
   this.amdSec.setRightsMDArray(0, rightsMD);
   // DVLinks
   MdSecType digiprovMD = this.amdSec.addNewDigiprovMD();
   digiprovMD.setID("digiprov" + id);
   MdWrap dpWrap = digiprovMD.addNewMdWrap();
   dpWrap.setMIMETYPE("text/xml");
   dpWrap.setMDTYPE(MdWrap.MDTYPE.OTHER);
   dpWrap.setOTHERMDTYPE("DVLINKS");
   XmlData dpXml = dpWrap.addNewXmlData();
   XmlObject dvdigiprov = XmlObject.Factory.newInstance();
   XmlCursor dpCur = dvdigiprov.newCursor();
   dpCur.toNextToken();
   dpCur.beginElement("links", "http://dfg-viewer.de/");
   dpCur.insertElementWithText("reference", "http://dfg-viewer.de/", reference);
   dpCur.insertElementWithText(
       "presentation", "http://dfg-viewer.de/", "http://vm38.mpdl.mpg.de:8080/dlib-journals/");
   dpCur.dispose();
   dpXml.set(dvdigiprov);
   dpWrap.setXmlData(dpXml);
   digiprovMD.setMdWrap(dpWrap);
   this.amdSec.setDigiprovMDArray(0, digiprovMD);
 }
  /**
   * 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;
  }
コード例 #7
0
ファイル: DefaultXmlDocument.java プロジェクト: TouK/soapuii
  public SchemaTypeSystem getTypeSystem() {
    if (typeSystem != null) return typeSystem;

    try {
      typeSystem = XmlObject.Factory.parse(xml).schemaType().getTypeSystem();
      return typeSystem;
    } catch (Exception e) {
      return XmlBeans.getBuiltinTypeSystem();
    }
  }
コード例 #8
0
ファイル: XmlHelper.java プロジェクト: shane-axiom/SOS
 public static XmlObject parseXmlString(final String xmlString) throws OwsExceptionReport {
   try {
     return XmlObject.Factory.parse(xmlString);
   } catch (final XmlException xmle) {
     throw new NoApplicableCodeException()
         .causedBy(xmle)
         .withMessage(
             "An xml error occured when parsing the request! Message: %s", xmle.getMessage());
   }
 }
コード例 #9
0
ファイル: WadlValidator.java プロジェクト: TouK/soapuii
  private QName getResponseBodyElementName(RestMessageExchange messageExchange) {
    try {
      XmlObject xmlObject = XmlObject.Factory.parse(messageExchange.getResponseContentAsXml());
      Element docElement = ((Document) xmlObject.getDomNode()).getDocumentElement();

      return new QName(docElement.getNamespaceURI(), docElement.getLocalName());
    } catch (XmlException e) {
      SoapUI.logError(e);
    }

    return null;
  }
コード例 #10
0
ファイル: SelectPath.java プロジェクト: sukrupa/spikes
  /**
   * Uses the XPath text() function to get values from <name> elements in received XML, then
   * collects those values as the value of a <names> element created here.
   *
   * <p>Demonstrates the following characteristics of the selectPath method:
   *
   * <p>- It supports expressions that include XPath function calls. - selectPath called from an
   * XmlCursor instance (instead of an XMLBeans type) places results (if any) into the cursor's
   * selection set.
   *
   * @param empDoc The incoming XML.
   * @return <code>true</code> if the XPath expression returned results; otherwise, <code>false
   *     </code>.
   */
  public boolean collectNames(XmlObject empDoc) {
    boolean hasResults = false;

    // Create a cursor with which to execute query expressions. The cursor
    // is inserted at the very beginning of the incoming XML, then moved to
    // the first element's START token.
    XmlCursor pathCursor = empDoc.newCursor();
    pathCursor.toFirstChild();

    // Execute the path expression, qualifying it with the namespace
    // declaration.
    pathCursor.selectPath(m_namespaceDeclaration + "$this//xq:employee/xq:name/text()");

    // If there are results, then go ahead and do stuff.
    if (pathCursor.getSelectionCount() > 0) {
      hasResults = true;

      // Create a new <names> element into which names from the XML
      // will be copied. Note that this element is in the default
      // namespace; it's not part of the schema.
      XmlObject namesElement = null;
      try {
        namesElement = XmlObject.Factory.parse("<names/>");
      } catch (XmlException e) {
        e.printStackTrace();
      }

      // Add a cursor the new element and put it between its START and END
      // tokens, where new values can be inserted.
      XmlCursor namesCursor = namesElement.newCursor();
      namesCursor.toFirstContentToken();
      namesCursor.toEndToken();

      // Loop through the selections, appending the incoming <name> element's
      // value to the new <name> element's value. (Of course, this could have
      // been done with a StringBuffer, but that wouldn't show the cursor in
      // use.)
      while (pathCursor.toNextSelection()) {
        namesCursor.insertChars(pathCursor.getTextValue());
        if (pathCursor.hasNextSelection()) {
          namesCursor.insertChars(", ");
        }
      }
      // Dispose of the cursors now that they're not needed.
      pathCursor.dispose();
      namesCursor.dispose();

      // Print the new element.
      System.out.println("\nNames collected by collectNames method: \n\n" + namesElement + "\n");
    }
    return hasResults;
  }
コード例 #11
0
 /**
  * Loads XML files which can be found via the <code>clazz</code>'s {@link ClassLoader}. If not
  * found the {@link FileContentLoader}'s {@link ClassLoader} is asked to load the file. If file
  * could not be found an exception is thrown.
  *
  * @param filePath the path to the file to be loaded.
  * @param clazz the class which {@link ClassLoader} to be used.
  * @return an XmlObject of the loaded file.
  * @throws XmlException if file could not be parsed into XML
  * @throws IOException if file could not be read.
  * @throws IllegalArgumentException if file path is <code>null</code> or empty
  * @throws FileNotFoundException if the resource could not be found be the <code>clazz</code>'s
  *     {@link ClassLoader}
  */
 public static XmlObject loadXmlFileViaClassloader(String filePath, Class<?> clazz)
     throws XmlException, IOException {
   if (filePath == null || filePath.isEmpty()) {
     throw new IllegalArgumentException("Check file path: '" + filePath + "'.");
   }
   InputStream is = clazz.getResourceAsStream(filePath);
   if (is == null) {
     is = XmlFileLoader.class.getResourceAsStream(filePath);
     if (is == null) {
       throw new FileNotFoundException("The resource at '" + filePath + "' cannot be found.");
     }
   }
   return XmlObject.Factory.parse(is);
 }
コード例 #12
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();
  }
コード例 #13
0
ファイル: SampleXmlUtil.java プロジェクト: hborham/soapui
  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;
  }
コード例 #14
0
  /**
   * Finds nested XML schema definition and compiles it to a schema type system instance.
   *
   * @param wsdl
   * @return
   * @throws MojoExecutionException
   */
  private SchemaTypeSystem compileXsd(XmlObject wsdl) throws MojoExecutionException {
    // extract namespaces defined on wsdl-level:
    String[] namespacesWsdl = extractNamespacesOnWsdlLevel(wsdl);

    // calc the namespace-prefix of the schema-tag, default ""
    String schemaNsPrefix = extractSchemaNamespacePrefix(wsdl);

    // extract each schema-element and add missing namespaces defined on wsdl-level
    String[] schemas = getNestedSchemas(wsdl, namespacesWsdl, schemaNsPrefix);

    XmlObject[] xsd = new XmlObject[schemas.length];
    try {
      for (int i = 0; i < schemas.length; i++) {
        xsd[i] =
            XmlObject.Factory.parse(
                schemas[i],
                (new XmlOptions())
                    .setLoadLineNumbers()
                    .setLoadMessageDigest()
                    .setCompileDownloadUrls());
      }
    } catch (Exception e) {
      throw new MojoExecutionException("Failed to parse XSD schema", e);
    }

    SchemaTypeSystem schemaTypeSystem = null;
    try {
      schemaTypeSystem =
          XmlBeans.compileXsd(xsd, XmlBeans.getContextTypeLoader(), new XmlOptions());
    } catch (XmlException e) {
      for (Object error : e.getErrors()) {
        getLog().error("Line " + ((XmlError) error).getLine() + ": " + error.toString());
      }
      throw new MojoExecutionException("Failed to compile XSD schema", e);
    } catch (Exception e) {
      throw new MojoExecutionException("Failed to compile XSD schema", e);
    }
    return schemaTypeSystem;
  }
コード例 #15
0
ファイル: SampleXmlUtil.java プロジェクト: hborham/soapui
  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;
  }
コード例 #16
0
ファイル: XmlHelper.java プロジェクト: shane-axiom/SOS
 /**
  * Loads a XML document from File.
  *
  * @param file File
  * @return XML document
  * @throws OwsExceptionReport If an error occurs
  */
 public static XmlObject loadXmlDocumentFromFile(final File file) throws OwsExceptionReport {
   InputStream is = null;
   try {
     is = FileIOHelper.loadInputStreamFromFile(file);
     return XmlObject.Factory.parse(is);
   } catch (final XmlException xmle) {
     throw new NoApplicableCodeException()
         .causedBy(xmle)
         .withMessage("Error while parsing file %s!", file.getName());
   } catch (final IOException ioe) {
     throw new NoApplicableCodeException()
         .causedBy(ioe)
         .withMessage("Error while parsing file %s!", file.getName());
   } finally {
     if (is != null) {
       try {
         is.close();
       } catch (final IOException ioe) {
         LOGGER.warn("Error while closing the file " + file.getName() + " input stream!", ioe);
       }
     }
   }
 }
コード例 #17
0
  /**
   * Compiles WSDL file resource to a XmlObject.
   *
   * @return
   * @throws MojoExecutionException
   * @throws IOException
   */
  private XmlObject compileWsdl() throws MojoExecutionException, IOException {
    Resource wsdlFile = new PathMatchingResourcePatternResolver().getResource(pathToWsdl);
    if (!wsdlFile.exists()) {
      throw new MojoExecutionException(
          "Unable to read WSDL - does not exist in " + wsdlFile.getFile().getAbsolutePath());
    }

    if (!wsdlFile.getFile().canRead()) {
      throw new MojoExecutionException("Unable to read WSDL - could not open in read mode");
    }

    try {
      return XmlObject.Factory.parse(
          wsdlFile.getFile(),
          (new XmlOptions()).setLoadLineNumbers().setLoadMessageDigest().setCompileDownloadUrls());
    } catch (XmlException e) {
      for (Object error : e.getErrors()) {
        getLog().error(((XmlError) error).getLine() + "" + error.toString());
      }
      throw new MojoExecutionException("WSDL could not be parsed", e);
    } catch (Exception e) {
      throw new MojoExecutionException("WSDL could not be parsed", e);
    }
  }
コード例 #18
0
  @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);
      }
    }
  }
  /**
   * 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();
  }
コード例 #20
0
  /**
   * add an input element. sets the data in the xml request
   *
   * @param parameterID the ID of the input (see process description)
   * @param value the actual value (for xml data xml for binary data is should be base64 encoded
   *     data)
   * @param schema schema if applicable otherwise null
   * @param encoding encoding if not the default encoding (for default encoding set it to null)
   *     (i.e. binary data, use base64)
   * @param mimeType mimetype of the data, has to be set
   * @throws WPSClientException
   */
  public void addComplexData(
      String parameterID, IData value, String schema, String encoding, String mimeType)
      throws WPSClientException {
    GeneratorFactory fac = StaticDataHandlerRepository.getGeneratorFactory();
    InputDescriptionType inputDesc = getParameterDescription(parameterID);
    if (inputDesc == null) {
      throw new IllegalArgumentException("inputDesription is null for: " + parameterID);
    }
    if (inputDesc.getComplexData() == null) {
      throw new IllegalArgumentException(
          "inputDescription is not of type ComplexData: " + parameterID);
    }

    LOGGER.debug(
        "Looking for matching Generator ..."
            + " schema: "
            + schema
            + " mimeType: "
            + mimeType
            + " encoding: "
            + encoding);

    IGenerator generator = fac.getGenerator(schema, mimeType, encoding, value.getClass());

    if (generator == null) {
      // generator is still null
      throw new IllegalArgumentException(
          "Could not find an appropriate generator for parameter: " + parameterID);
    }

    InputStream stream = null;

    InputType input = execute.getExecute().getDataInputs().addNewInput();
    input.addNewIdentifier().setStringValue(inputDesc.getIdentifier().getStringValue());
    // encoding is UTF-8 (or nothing and we default to UTF-8)
    // everything that goes to this condition should be inline xml data
    try {

      if (encoding == null
          || encoding.equals("")
          || encoding.equalsIgnoreCase(IOHandler.DEFAULT_ENCODING)) {
        stream = generator.generateStream(value, mimeType, schema);

      } else if (encoding.equalsIgnoreCase("base64")) {
        stream = generator.generateBase64Stream(value, mimeType, schema);
      } else {
        throw new WPSClientException("Encoding not supported");
      }
      ComplexDataType data = input.addNewData().addNewComplexData();
      data.set(XmlObject.Factory.parse(stream));
      if (schema != null) {
        data.setSchema(schema);
      }
      if (mimeType != null) {
        data.setMimeType(mimeType);
      }
      if (encoding != null) {
        data.setEncoding(encoding);
      }
    } catch (XmlException e) {
      throw new IllegalArgumentException("error inserting node into execute request", e);
    } catch (IOException e) {
      throw new IllegalArgumentException("error reading generator output", e);
    }
  }
コード例 #21
0
 private String readMessage() throws XmlException, IOException {
   XmlObject xo = XmlObject.Factory.parse(getClass().getResourceAsStream("NotifyMessage.xml"));
   return xo.xmlText(new XmlOptions().setSavePrettyPrint());
 }
コード例 #22
0
 private boolean validateSensorMLDocument(String s) throws XmlException, IOException {
   boolean b = this.validator.validate(XmlObject.Factory.parse(s));
   return b;
 }
コード例 #23
0
ファイル: XmlHolder.java プロジェクト: TouK/soapuii
 public XmlHolder(Node node) throws XmlException {
   xmlObject = XmlObject.Factory.parse(node);
 }
コード例 #24
0
ファイル: XmlHolder.java プロジェクト: TouK/soapuii
 public XmlHolder(String xml) throws XmlException {
   xmlObject = XmlObject.Factory.parse(xml);
 }