Example #1
0
  @Override
  public String encode(Resource resource, List<String> includeAttributes) {
    try {
      x0.scimSchemasCore1.Resource xmlResource = this.internalEncode(resource, includeAttributes);

      Complex complex = resource.getClass().getAnnotation(Complex.class);
      Class<?> factory = ReflectionHelper.getFactory(complex.xmlDoc());
      XmlObject doc = (XmlObject) factory.getMethod("newInstance").invoke(null);

      String name = complex.xmlType().getName();
      String setterName = "set";
      setterName += name.substring(name.lastIndexOf('.') + 1);
      doc.getClass().getMethod(setterName, complex.xmlType()).invoke(doc, xmlResource);

      return (PRETTY_PRINT ? doc.toString() : doc.xmlText());
    } catch (FactoryNotFoundException e) {
      throw new RuntimeException("Internal error, xml encode failed", e);
    } catch (NoSuchMethodException e) {
      throw new RuntimeException("Internal error, xml encode failed", e);
    } catch (SecurityException e) {
      throw new RuntimeException("Internal error, xml encode failed", e);
    } catch (IllegalAccessException e) {
      throw new RuntimeException("Internal error, xml encode failed", e);
    } catch (IllegalArgumentException e) {
      throw new RuntimeException("Internal error, xml encode failed", e);
    } catch (InvocationTargetException e) {
      throw new RuntimeException("Internal error, xml encode failed", e);
    }
  }
Example #2
0
 public static String getNamespace(final XmlObject doc) {
   String namespaceURI = doc.getDomNode().getNamespaceURI();
   if (namespaceURI == null && doc.getDomNode().getFirstChild() != null) {
     namespaceURI = doc.getDomNode().getFirstChild().getNamespaceURI();
   }
   /*
    * if document starts with a comment, get next sibling (and ignore
    * initial comment)
    */
   if (namespaceURI == null
       && doc.getDomNode().getFirstChild() != null
       && doc.getDomNode().getFirstChild().getNextSibling() != null) {
     namespaceURI = doc.getDomNode().getFirstChild().getNextSibling().getNamespaceURI();
   }
   // check with schemaType namespace, necessary for anyType elements
   final String schemaTypeNamespace = getSchemaTypeNamespace(doc);
   if (schemaTypeNamespace == null) {
     return namespaceURI;
   } else {
     if (schemaTypeNamespace.equals(namespaceURI)) {
       return namespaceURI;
     } else {
       return schemaTypeNamespace;
     }
   }
 }
  private void buildCapabilityList() {

    capabilityList = new ArrayList<ExtendedCapability>();
    // System.out.println("Selected Resource: " + resourceIndex);

    ExtendedRegistry tempExtendedRegistry = this.extendedRegistryList.get(resourceIndex);
    Resource tempResource = tempExtendedRegistry.getResource();

    XmlObject tempObject = tempResource.copy();
    XmlObject xmlObjectCapabilityChild[] = tempObject.selectChildren(new QName("", "capability"));

    Capability capabilityTemp = null;
    ExtendedCapability extendedCapabilityTemp = null;

    for (int j = 0; j < xmlObjectCapabilityChild.length; j++) {
      try {
        capabilityTemp = Capability.Factory.parse(xmlObjectCapabilityChild[j].xmlText());

        extendedCapabilityTemp = new ExtendedCapability(j, capabilityTemp);
      } catch (XmlException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

      capabilityList.add(extendedCapabilityTemp);
    }
  }
  private String[] buildCapabilityList(Resource resourceValue) {

    Resource tempResource = resourceValue;
    // First for Tap and second for Tap-XSAMs
    String[] accessURLs = new String[] {null, null};

    XmlObject tempObject = tempResource.copy();
    XmlObject xmlObjectCapabilityChild[] = tempObject.selectChildren(new QName("", "capability"));

    Capability capabilityTemp = null;

    for (int j = 0; j < xmlObjectCapabilityChild.length; j++) {
      try {
        capabilityTemp = Capability.Factory.parse(xmlObjectCapabilityChild[j].xmlText());
        if (capabilityTemp.getStandardID() != null) {
          if (capabilityTemp.getStandardID().toUpperCase().contains("ivo://vamdc/std/TAP-XSAMS")) {
            accessURLs[1] = buildInterfaceList(capabilityTemp);
          }
          if (capabilityTemp.getStandardID().toUpperCase().contains("TAP")) {

            if (capabilityTemp.getStandardID().toUpperCase().contains("TAP-XSAMS")) {
              accessURLs[1] = buildInterfaceList(capabilityTemp);
            } else {
              accessURLs[0] = buildInterfaceList(capabilityTemp);
            }
          }
        }

      } catch (XmlException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    return accessURLs;
  }
Example #5
0
  /**
   * Prints the XML bound to <em>empDoc</em>, uses XPath to retrieve elements containing work phone
   * numbers, changes the numbers to another number, then prints the XML again to display the
   * changes.
   *
   * <p>This method demonstrates the following characteristics of the selectPath method:
   *
   * <p>- it supports expressions that include predicates - the XML it returns is the XML queried
   * against -- not a copy, as with results returned via execQuery methods and XQuery. Changes to
   * this XML update the XML queried against. - selectPath called from an XMLBean type (instead of a
   * cursor) returns an array of results (if any). These results can be cast to a matching type
   * generated from schema.
   *
   * @param empDoc The incoming XML.
   * @return <code>true</code> if the XPath expression returned results; otherwise, <code>false
   *     </code>.
   */
  public boolean updateWorkPhone(XmlObject empDoc) {
    boolean hasResults = false;

    // Print the XML received.
    System.out.println("XML as received by updateWorkPhone method: \n\n" + empDoc.toString());

    // Create a variable with the query expression.
    String pathExpression = "$this/xq:employees/xq:employee/xq:phone[@location='work']";

    // Execute the query.
    XmlObject[] results = empDoc.selectPath(m_namespaceDeclaration + pathExpression);
    if (results.length > 0) {
      hasResults = true;

      // <phone> elements returned from the expression will conform to the
      // schema, so bind them to the appropriate XMLBeans type generated
      // from the schema.
      PhoneType[] phones = (PhoneType[]) results;

      // Change all the work phone numbers to the same number.
      for (int i = 0; i < phones.length; i++) {
        phones[i].setStringValue("(206)555-1234");
      }
      // Print the XML with updates.
      System.out.println(
          "\nXML as updated by updateWorkPhone method (each work \n"
              + "phone number has been changed to the same number): \n\n"
              + empDoc.toString()
              + "\n");
    }
    return hasResults;
  }
  private String getCurrentValue(String xpath) {
    XmlObject[] paths =
        outlineEditor.getOutlineTable().getXmlObjectTreeModel().getXmlObject().selectPath(xpath);

    String v = "";
    for (XmlObject obj : paths) v += obj.toString();
    return v;
  }
  /**
   * Check a segment
   *
   * @param segmentObj the segment object (from profile)
   * @param segment the segment string (from ER7)
   */
  private void checkSegment(XmlObject segmentObj, String segment) {
    locFieldInstanceNumber = -1;
    String segmentName = segmentObj.newCursor().getAttributeText(QName.valueOf("Name"));
    String segmentUsage = segmentObj.newCursor().getAttributeText(QName.valueOf("Usage"));
    XmlObject[] fieldsObj = segmentObj.selectChildren(QName.valueOf("Field"));

    if (fieldsObj.length > 0) {
      String[] fields = segment.split(((Er7Message) message).getFieldSeparator());
      if (fields.length - 1 > fieldsObj.length) {
        /* Extra fields */
        MessageFailureV2 mf = new MessageFailureV2(message.getEncoding());
        mf.setFailureType(AssertionTypeV2Constants.XTRA);
        mf.setFailureSeverity(ErrorSeverityConstants.NORMAL);
        mf.setDescription("Extra fields for segment " + segmentName);
        mf.setColumn(((Er7Message) inputMessage).getColumn(getCurrentLocation()));
        mf.setLine(lineNumber);
        mf.setPath(getCurrentLocation().toString());

        messageFailures.add(mf);
      } else {
        int fieldsIdx = 1;
        if (fields[0].equals("MSH")) {
          fieldsIdx = 0;
        }
        for (int i = 0; i < fieldsObj.length; i++, fieldsIdx++) {
          if (fieldsIdx == 0) {
            continue;
          }
          locFieldPosition = i + 1;
          locFieldInstanceNumber = 1;
          locComponentPosition = -1;
          if (fieldsIdx < fields.length) {
            checkField(fieldsObj[i], fields[fieldsIdx]);
          } else {
            /* Check Usage */
            checkUsage(fieldsObj[i], "");
          }
        }
      }
      // No Fields
      if ("R".equals(segmentUsage) && fields.length - 1 == 0) {
        locFieldPosition = -1;
        StringBuffer sb = new StringBuffer();
        MessageFailureV2 mf = new MessageFailureV2(message.getEncoding());
        sb.append("The element is missing at least one of its children");
        mf.setDescription(sb.toString());
        mf.setFailureSeverity(ErrorSeverityConstants.NORMAL);
        mf.setFailureType(AssertionTypeV2Constants.MESSAGE_STRUCTURE);
        mf.setColumn(((Er7Message) inputMessage).getColumn(getCurrentLocation()));
        mf.setLine(lineNumber);
        mf.setPath(getCurrentLocation().toString());
        messageFailures.add(mf);
        sb = null;
      }
    }
  }
Example #8
0
  /**
   * Utility method to append the contents of the child docment to the end of the parent XmlObject.
   * This is useful when dealing with elements without generated methods (like elements with xs:any)
   *
   * @param parent Parent to append contents to
   * @param childDoc Xml document containing contents to be appended
   */
  public static void append(final XmlObject parent, final XmlObject childDoc) {
    final XmlCursor parentCursor = parent.newCursor();
    parentCursor.toEndToken();

    final XmlCursor childCursor = childDoc.newCursor();
    childCursor.toFirstChild();

    childCursor.moveXml(parentCursor);
    parentCursor.dispose();
    childCursor.dispose();
  }
Example #9
0
  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;
  }
 @Override
 public OperationResult doOperation(Operation operation, ParameterContainer parameters)
     throws ExceptionReport, OXFException {
   try {
     XmlObject response = XmlFileLoader.loadXmlFileViaClassloader(file, getClass());
     return new OperationResult(response.newInputStream(), null, null);
   } catch (Exception e) {
     LOGGER.error("Could not load response file for testing: {}", file, e);
     fail("Failed to load response file.");
     return null;
   }
 }
Example #11
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()]);
  }
Example #12
0
  /**
   * 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;
  }
 /**
  * Finds schema tag and extracts the namespace prefix.
  *
  * @param wsdl
  * @return
  */
 private String extractSchemaNamespacePrefix(XmlObject wsdl) {
   String schemaNsPrefix = "";
   if (wsdl.xmlText().contains(":schema")) {
     int cursor = wsdl.xmlText().indexOf(":schema");
     for (int i = cursor; i > cursor - 100; i--) {
       schemaNsPrefix = wsdl.xmlText().substring(i, cursor);
       if (schemaNsPrefix.startsWith("<")) {
         return schemaNsPrefix.substring(1) + ":";
       }
     }
   }
   return schemaNsPrefix;
 }
 /** Sets the "DataItemStatusAbstract" element */
 public void setDataItemStatusAbstract(org.apache.xmlbeans.XmlObject dataItemStatusAbstract) {
   synchronized (monitor()) {
     check_orphaned();
     org.apache.xmlbeans.XmlObject target = null;
     target =
         (org.apache.xmlbeans.XmlObject)
             get_store().find_element_user(DATAITEMSTATUSABSTRACT$1, 0);
     if (target == null) {
       target =
           (org.apache.xmlbeans.XmlObject) get_store().add_element_user(DATAITEMSTATUSABSTRACT$0);
     }
     target.set(dataItemStatusAbstract);
   }
 }
Example #15
0
 /** Sets ith "IdentificationJurisdiction" element */
 public void setIdentificationJurisdictionArray(
     int i, org.apache.xmlbeans.XmlObject identificationJurisdiction) {
   synchronized (monitor()) {
     check_orphaned();
     org.apache.xmlbeans.XmlObject target = null;
     target =
         (org.apache.xmlbeans.XmlObject)
             get_store().find_element_user(IDENTIFICATIONJURISDICTION$11, i);
     if (target == null) {
       throw new IndexOutOfBoundsException();
     }
     target.set(identificationJurisdiction);
   }
 }
 /**
  * Returns an array of all namespace declarations, found on wsdl-level.
  *
  * @param wsdl
  * @return
  */
 private String[] extractNamespacesOnWsdlLevel(XmlObject wsdl) {
   int cursor = wsdl.xmlText().indexOf(":") + ":definitions ".length();
   String nsWsdlOrig = wsdl.xmlText().substring(cursor, wsdl.xmlText().indexOf(">", cursor));
   int noNs = StringUtils.countOccurrencesOf(nsWsdlOrig, "xmlns:");
   String[] namespacesWsdl = new String[noNs];
   cursor = 0;
   for (int i = 0; i < noNs; i++) {
     int begin = nsWsdlOrig.indexOf("xmlns:", cursor);
     int end = nsWsdlOrig.indexOf("\"", begin + 20);
     namespacesWsdl[i] = nsWsdlOrig.substring(begin, end) + "\"";
     cursor = end;
   }
   return namespacesWsdl;
 }
 /** Sets ith "PDMessageMetadataExtensionAbstract" element */
 public void setPDMessageMetadataExtensionAbstractArray(
     int i, org.apache.xmlbeans.XmlObject pdMessageMetadataExtensionAbstract) {
   synchronized (monitor()) {
     check_orphaned();
     org.apache.xmlbeans.XmlObject target = null;
     target =
         (org.apache.xmlbeans.XmlObject)
             get_store().find_element_user(PDMESSAGEMETADATAEXTENSIONABSTRACT$1, i);
     if (target == null) {
       throw new IndexOutOfBoundsException();
     }
     target.set(pdMessageMetadataExtensionAbstract);
   }
 }
  /**
   * Check the element usage
   *
   * @param usage the usage
   * @param value the value
   * @return true if there is a usage error; false otherwise
   */
  private boolean checkUsage(XmlObject obj, String value) {
    boolean usageError = false;
    MessageFailureV2 mf = null;
    String usage = obj.newCursor().getAttributeText(QName.valueOf("Usage"));

    if (usage.equals("R") && value.matches("\\s*")) {
      /* A required element is empty */
      mf = new MessageFailureV2(message.getEncoding());
      mf.setFailureType(AssertionTypeV2Constants.USAGE);
      mf.setFailureSeverity(ErrorSeverityConstants.NORMAL);
      mf.setDescription(getCurrentLocation().toString() + " is missing");
      mf.setColumn(((Er7Message) inputMessage).getColumn(getCurrentLocation()));
      mf.setLine(lineNumber);
      mf.setPath(getCurrentLocation().toString());
      messageFailures.add(mf);
      usageError = true;
    } else if (usage.equals("X") && value.matches(".+")) {
      /* A X element has a value */
      mf = new MessageFailureV2(message.getEncoding());
      mf.setFailureType(AssertionTypeV2Constants.X_USAGE);
      mf.setFailureSeverity(ErrorSeverityConstants.NORMAL);
      mf.setDescription(
          getCurrentLocation().toString() + " is present whereas it is an X-Usage element");
      mf.setColumn(((Er7Message) inputMessage).getColumn(getCurrentLocation()));
      mf.setLine(lineNumber);
      mf.setPath(getCurrentLocation().toString());
      messageFailures.add(mf);
      usageError = true;
    }
    return usageError;
  }
Example #19
0
 private static String getSchemaTypeNamespace(final XmlObject doc) {
   final QName name = doc.schemaType().getName();
   if (name != null) {
     return name.getNamespaceURI();
   }
   return null;
 }
Example #20
0
  /* (non-Javadoc)
   * @see org.n52.ses.enrichment.parser.AIXMAbstractGeometryParser#parseGeometries(org.apache.xmlbeans.XmlObject)
   */
  @Override
  protected List<Geometry> parseGeometries(XmlObject xmlO)
      throws XmlException, ParseException, GMLParseException {
    List<Geometry> geometries = new ArrayList<Geometry>();

    // parse the feature's xml-document
    NavaidDocument navaidDoc = NavaidDocument.Factory.parse(xmlO.xmlText());
    NavaidType navaid = navaidDoc.getNavaid();

    // geometry from location, defined by  a point
    for (NavaidTimeSlicePropertyType ts : navaid.getTimeSliceArray()) {
      if (ts.getNavaidTimeSlice().isSetLocation()) {
        if (ts.getNavaidTimeSlice().getLocation().getElevatedPoint().isSetPos()) {
          DirectPositionType pointPos =
              ts.getNavaidTimeSlice().getLocation().getElevatedPoint().getPos();
          geometries.add(GML32Parser.parseGeometry(pointPos));
        }
      }
    }

    // parse bounded by
    if (geometries.size() == 0 && navaid.isSetBoundedBy()) {
      geometries.add(super.parseBoundedBy(navaid.getBoundedBy()));
    }

    return geometries;
  }
Example #21
0
 /**
  * Check SOS response for xsi:schemaLocation, remove attribute and add attribute to SOAP message
  *
  * @param xmlObject
  * @param soapResponseMessage SOAP response message
  * @throws SOAPException If an error occurs
  */
 private void addAndRemoveSchemaLocationForSOAP(
     XmlObject xmlObject, SOAPMessage soapResponseMessage) throws SOAPException {
   String value = null;
   Node nodeToRemove = null;
   NamedNodeMap attributeMap = xmlObject.getDomNode().getFirstChild().getAttributes();
   for (int i = 0; i < attributeMap.getLength(); i++) {
     Node node = attributeMap.item(i);
     if (node.getLocalName().equals(W3CConstants.AN_SCHEMA_LOCATION)) {
       value = node.getNodeValue();
       nodeToRemove = node;
     }
   }
   if (nodeToRemove != null) {
     attributeMap.removeNamedItem(nodeToRemove.getNodeName());
   }
   SOAPEnvelope envelope = soapResponseMessage.getSOAPPart().getEnvelope();
   StringBuilder string = new StringBuilder();
   string.append(envelope.getNamespaceURI());
   string.append(BLANK_CHAR);
   string.append(envelope.getNamespaceURI());
   if (value != null && !value.isEmpty()) {
     string.append(BLANK_CHAR);
     string.append(value);
   }
   envelope.addAttribute(N52XmlHelper.getSchemaLocationQNameWithPrefix(), string.toString());
 }
  @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();
  }
Example #23
0
 public static Map<?, ?> getNamespaces(XmlObject xmlObject) {
   XmlCursor cursor = xmlObject.newCursor();
   Map<?, ?> nsMap = Maps.newHashMap();
   cursor.getAllNamespaces(nsMap);
   cursor.dispose();
   return nsMap;
 }
Example #24
0
 public static void fixNamespaceForXsiType(XmlObject content, Map<?, ?> namespaces) {
   final XmlCursor cursor = content.newCursor();
   while (cursor.hasNextToken()) {
     if (cursor.toNextToken().isStart()) {
       final String xsiType = cursor.getAttributeText(W3CConstants.QN_XSI_TYPE);
       if (xsiType != null) {
         final String[] toks = xsiType.split(":");
         if (toks.length > 1) {
           String prefix = toks[0];
           String localName = toks[1];
           String namespace = (String) namespaces.get(prefix);
           if (Strings.isNullOrEmpty(namespace)) {
             namespace = CodingRepository.getInstance().getNamespaceFor(prefix);
           }
           if (StringHelper.isNotEmpty(namespace)) {
             cursor.setAttributeText(
                 W3CConstants.QN_XSI_TYPE,
                 Joiner.on(Constants.COLON_CHAR)
                     .join(
                         XmlHelper.getPrefixForNamespace(content, (String) namespaces.get(prefix)),
                         localName));
           }
         }
       }
     }
   }
   cursor.dispose();
 }
Example #25
0
  public static void fixNamespaceForXsiType(final XmlObject object, final QName value) {
    final XmlCursor cursor = object.newCursor();
    while (cursor.hasNextToken()) {
      if (cursor.toNextToken().isStart()) {
        final String xsiType = cursor.getAttributeText(W3CConstants.QN_XSI_TYPE);
        if (xsiType != null) {

          final String[] toks = xsiType.split(":");
          String localName;
          String prefix;
          if (toks.length > 1) {
            prefix = toks[0];
            localName = toks[1];
          } else {
            localName = toks[0];
          }
          if (localName.equals(value.getLocalPart())) {
            cursor.setAttributeText(
                W3CConstants.QN_XSI_TYPE,
                Joiner.on(Constants.COLON_CHAR)
                    .join(
                        XmlHelper.getPrefixForNamespace(object, value.getNamespaceURI()),
                        value.getLocalPart()));
          }
        }
      }
    }
    cursor.dispose();
  }
  /**
   * Finds nested schema definitions and puts globally WSDL defined namespaces to schema level.
   *
   * @param wsdl
   * @param namespacesWsdl
   * @param schemaNsPrefix
   */
  private String[] getNestedSchemas(
      XmlObject wsdl, String[] namespacesWsdl, String schemaNsPrefix) {
    List<String> schemas = new ArrayList<String>();
    String openedStartTag = "<" + schemaNsPrefix + "schema";
    String endTag = "</" + schemaNsPrefix + "schema>";

    int cursor = 0;
    while (wsdl.xmlText().indexOf(openedStartTag, cursor) != -1) {
      int begin = wsdl.xmlText().indexOf(openedStartTag, cursor);
      int end = wsdl.xmlText().indexOf(endTag, begin) + endTag.length();
      int insertPointNamespacesWsdl = wsdl.xmlText().indexOf(" ", begin);

      StringBuffer buf = new StringBuffer();
      buf.append(wsdl.xmlText().substring(begin, insertPointNamespacesWsdl)).append(" ");

      for (String nsWsdl : namespacesWsdl) {
        String nsPrefix = nsWsdl.substring(0, nsWsdl.indexOf("="));
        if (!wsdl.xmlText().substring(begin, end).contains(nsPrefix)) {
          buf.append(nsWsdl).append(" ");
        }
      }

      buf.append(wsdl.xmlText().substring(insertPointNamespacesWsdl, end));
      schemas.add(buf.toString());
      cursor = end;
    }

    return schemas.toArray(new String[] {});
  }
Example #27
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);
 }
Example #28
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;
 }
Example #29
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;
  }
Example #30
0
 /**
  * Remove namespace declarations from an xml fragment (useful for moving all declarations to a
  * document root
  *
  * @param x The fragment to localize
  */
 public static void removeNamespaces(final XmlObject x) {
   final XmlCursor c = x.newCursor();
   while (c.hasNextToken()) {
     if (c.isNamespace()) {
       c.removeXml();
     } else {
       c.toNextToken();
     }
   }
   c.dispose();
 }