Exemplo n.º 1
0
  static String getNextElement(
      XMLStreamReader reader, String name, Map<String, String> attributes, boolean getElementText)
      throws XMLStreamException {
    if (!reader.hasNext()) {
      throw new XMLStreamException("Expected more elements", reader.getLocation());
    }
    int type = reader.next();
    while (reader.hasNext() && type != START_ELEMENT) {
      type = reader.next();
    }
    if (reader.getEventType() != START_ELEMENT) {
      throw new XMLStreamException("No <" + name + "> found");
    }
    if (!reader.getLocalName().equals("" + name + "")) {
      throw new XMLStreamException("<" + name + "> expected", reader.getLocation());
    }

    if (attributes != null) {
      for (int i = 0; i < reader.getAttributeCount(); i++) {
        String attr = reader.getAttributeLocalName(i);
        if (!attributes.containsKey(attr)) {
          throw new XMLStreamException("Unexpected attribute " + attr, reader.getLocation());
        }
        attributes.put(attr, reader.getAttributeValue(i));
      }
    }

    return getElementText ? reader.getElementText() : null;
  }
  /**
   * Reads the "version" attribute of ejb-jar element and returns the corresponding {@link
   * org.jboss.metadata.ejb.spec.EjbJarVersion}.
   *
   * <p>Returns null, if either the "version" attribute is not specified or if the value of the
   * "version" attribute doesn't belong to the known values from {@link
   * org.jboss.metadata.ejb.spec.EjbJarVersion}.
   *
   * @param reader
   * @return
   * @throws XMLStreamException
   */
  protected static EjbJarVersion readVersionAttribute(XMLStreamReader reader)
      throws XMLStreamException {
    EjbJarVersion ejbJarVersion = null;

    // Look at the version attribute
    String versionString = null;
    final int count = reader.getAttributeCount();
    for (int i = 0; i < count; i++) {
      if (attributeHasNamespace(reader, i)) {
        continue;
      }
      final EjbJarAttribute ejbJarVersionAttribute =
          EjbJarAttribute.forName(reader.getAttributeLocalName(i));
      if (ejbJarVersionAttribute == EjbJarAttribute.VERSION) {
        versionString = reader.getAttributeValue(i);
      }
    }
    if ("1.1".equals(versionString)) {
      ejbJarVersion = EjbJarVersion.EJB_1_1;
    } else if ("2.0".equals(versionString)) {
      ejbJarVersion = EjbJarVersion.EJB_2_0;
    } else if ("2.1".equals(versionString)) {
      ejbJarVersion = EjbJarVersion.EJB_2_1;
    } else if ("3.0".equals(versionString)) {
      ejbJarVersion = EjbJarVersion.EJB_3_0;
    } else if ("3.1".equals(versionString)) {
      ejbJarVersion = EjbJarVersion.EJB_3_1;
    }

    return ejbJarVersion;
  }
Exemplo n.º 3
0
 private static Element parseElement(XMLStreamReader xsr) throws XMLStreamException {
   // xsr points to a START_ELEMENT event. Create the element and read all its attributes
   // Then read all its children events
   Element element = new Element(xsr.getLocalName());
   // text that will be added to the element. Text can come in different events, so we add it here
   // and add it to the element at the end
   StringBuilder elementText = new StringBuilder();
   int attributeCount = xsr.getAttributeCount();
   for (int i = 0; i < attributeCount; i++) {
     element.putAttribute(xsr.getAttributeLocalName(i), xsr.getAttributeValue(i));
   }
   while (xsr.hasNext()) {
     xsr.next();
     if (xsr.getEventType() == XMLStreamConstants.END_ELEMENT) {
       // element is closed. Move the cursor and return it
       // check if there is some text to add before (empty text is not added, but added text is not
       // trimmed)
       // we set empty text also if the element has no children
       if (!elementText.toString().trim().isEmpty() || !element.hasChildren()) {
         element.setText(elementText.toString());
       }
       //                xsr.next();
       return element;
     } else if (xsr.getEventType() == XMLStreamConstants.CHARACTERS) {
       // an attribute of the current element
       elementText.append(xsr.getText());
     } else if (xsr.getEventType() == XMLStreamConstants.START_ELEMENT) {
       // new element begins -> read it recursively and add it to the current element
       element.addChild(parseElement(xsr));
     }
   }
   // we reached the end of the document without the tag end -> error parsing
   throw new XMLStreamException(
       "End of the document unexpectedly reached. Element " + element.getName() + " not closed");
 }
Exemplo n.º 4
0
  /**
   * Get the attributes associated with the given START_ELEMENT or ATTRIBUTE StAXevent.
   *
   * @return the StAX attributes converted to an org.xml.sax.Attributes
   */
  private Attributes getAttributes() {
    AttributesImpl attrs = new AttributesImpl();

    int eventType = staxStreamReader.getEventType();
    if (eventType != XMLStreamConstants.ATTRIBUTE
        && eventType != XMLStreamConstants.START_ELEMENT) {
      throw new InternalError("getAttributes() attempting to process: " + eventType);
    }

    // in SAX, namespace declarations are not part of attributes by default.
    // (there's a property to control that, but as far as we are concerned
    // we don't use it.) So don't add xmlns:* to attributes.

    // gather non-namespace attrs
    for (int i = 0; i < staxStreamReader.getAttributeCount(); i++) {
      String uri = staxStreamReader.getAttributeNamespace(i);
      if (uri == null) uri = "";
      String localName = staxStreamReader.getAttributeLocalName(i);
      String prefix = staxStreamReader.getAttributePrefix(i);
      String qName;
      if (prefix == null || prefix.length() == 0) qName = localName;
      else qName = prefix + ':' + localName;
      String type = staxStreamReader.getAttributeType(i);
      String value = staxStreamReader.getAttributeValue(i);

      attrs.addAttribute(uri, localName, qName, type, value);
    }

    return attrs;
  }
Exemplo n.º 5
0
 public String getAttributeLocalName(int index) {
   if (state == STATE_START_DOCUMENT || state == STATE_END_DOCUMENT) {
     throw new IllegalStateException();
   } else {
     return parent.getAttributeLocalName(index);
   }
 }
Exemplo n.º 6
0
  /**
   * Method processAttributes.
   *
   * @param node
   */
  protected void processAttributes(OMElement node) {
    int attribCount = parser.getAttributeCount();
    for (int i = 0; i < attribCount; i++) {
      String uri = parser.getAttributeNamespace(i);
      String prefix = parser.getAttributePrefix(i);

      OMNamespace namespace = null;
      if (uri != null && uri.length() > 0) {

        // prefix being null means this elements has a default namespace or it has inherited
        // a default namespace from its parent
        namespace = node.findNamespace(uri, prefix);
        if (namespace == null) {
          if (prefix == null || "".equals(prefix)) {
            prefix = OMSerializerUtil.getNextNSPrefix();
          }
          namespace = node.declareNamespace(uri, prefix);
        }
      }

      // todo if the attributes are supposed to namespace qualified all the time
      // todo then this should throw an exception here

      OMAttribute attr =
          node.addAttribute(
              parser.getAttributeLocalName(i), parser.getAttributeValue(i), namespace);
      attr.setAttributeType(parser.getAttributeType(i));
    }
  }
  public static FilterMappingMetaData parse(XMLStreamReader reader) throws XMLStreamException {
    FilterMappingMetaData filterMapping = new FilterMappingMetaData();

    // Handle attributes
    final int count = reader.getAttributeCount();
    for (int i = 0; i < count; i++) {
      final String value = reader.getAttributeValue(i);
      if (reader.getAttributeNamespace(i) != null) {
        continue;
      }
      final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
      switch (attribute) {
        case ID:
          {
            filterMapping.setId(value);
            break;
          }
        default:
          throw unexpectedAttribute(reader, i);
      }
    }

    // Handle elements
    while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
      final Element element = Element.forName(reader.getLocalName());
      switch (element) {
        case FILTER_NAME:
          filterMapping.setFilterName(getElementText(reader));
          break;
        case URL_PATTERN:
          List<String> urlPatterns = filterMapping.getUrlPatterns();
          if (urlPatterns == null) {
            urlPatterns = new ArrayList<String>();
            filterMapping.setUrlPatterns(urlPatterns);
          }
          urlPatterns.add(getElementText(reader));
          break;
        case SERVLET_NAME:
          List<String> servletNames = filterMapping.getServletNames();
          if (servletNames == null) {
            servletNames = new ArrayList<String>();
            filterMapping.setServletNames(servletNames);
          }
          servletNames.add(getElementText(reader));
          break;
        case DISPATCHER:
          List<DispatcherType> dispatchers = filterMapping.getDispatchers();
          if (dispatchers == null) {
            dispatchers = new ArrayList<DispatcherType>();
            filterMapping.setDispatchers(dispatchers);
          }
          dispatchers.add(DispatcherType.valueOf(getElementText(reader)));
          break;
        default:
          throw unexpectedElement(reader);
      }
    }

    return filterMapping;
  }
 protected void processAttribute(EjbJarMetaData ejbJarMetaData, XMLStreamReader reader, int i)
     throws XMLStreamException {
   final String value = reader.getAttributeValue(i);
   if (attributeHasNamespace(reader, i)) {
     return;
   }
   final EjbJarAttribute ejbJarAttribute =
       EjbJarAttribute.forName(reader.getAttributeLocalName(i));
   switch (ejbJarAttribute) {
     case ID:
       {
         ejbJarMetaData.setId(value);
         break;
       }
     case VERSION:
       {
         ejbJarMetaData.setVersion(value);
         break;
       }
     case METADATA_COMPLETE:
       {
         // metadata-complete applies only to EJB 3.x
         if (ejbJarMetaData.isEJB3x()) {
           if (Boolean.TRUE.equals(Boolean.valueOf(value))) {
             ejbJarMetaData.setMetadataComplete(true);
           }
         } else {
           throw unexpectedAttribute(reader, i);
         }
         break;
       }
     default:
       throw unexpectedAttribute(reader, i);
   }
 }
 private void processContentXml(InputStream in, String sitePath, Session session, ZipFile zip)
     throws XMLStreamException {
   Map<String, Resource> resources = new HashMap<String, Resource>();
   String currentResourceId = null;
   XMLStreamReader reader = xmlInputFactory.createXMLStreamReader(in);
   for (int event = reader.next(); event != XMLStreamReader.END_DOCUMENT; event = reader.next()) {
     String localName = null;
     switch (event) {
       case XMLStreamReader.START_ELEMENT:
         localName = reader.getLocalName();
         if ("archive".equalsIgnoreCase(localName)) {
           final String system = reader.getAttributeValue(null, "system");
           boolean supportedVersion = false;
           for (String version : supportedVersions) {
             if (version.equalsIgnoreCase(system)) {
               supportedVersion = true;
             }
           }
           if (!supportedVersion) {
             throw new Error("Not a supported version: " + system);
           }
           break;
         }
         if ("collection".equalsIgnoreCase(localName) || "resource".equalsIgnoreCase(localName)) {
           // grab the resource's attributes
           Resource resource = new Resource();
           for (int i = 0; i < reader.getAttributeCount(); i++) {
             resource.attributes.put(
                 reader.getAttributeLocalName(i).toLowerCase(), reader.getAttributeValue(i));
           }
           currentResourceId = resource.getId();
           resources.put(currentResourceId, resource);
           break;
         }
         if ("property".equalsIgnoreCase(localName)) {
           Resource resource = resources.get(currentResourceId);
           final String name = reader.getAttributeValue(null, "name");
           String value = reader.getAttributeValue(null, "value");
           if (value != null && !"".equals(value)) {
             if (reader.getAttributeValue(null, "enc").equalsIgnoreCase("BASE64")) {
               value = new String(base64.decode(value));
             }
             resource.properties.put(name, value);
           }
           break;
         }
         break;
       case XMLStreamReader.END_ELEMENT:
         localName = reader.getLocalName();
         if ("collection".equalsIgnoreCase(localName) || "resource".equalsIgnoreCase(localName)) {
           makeResource(resources.get(currentResourceId), sitePath, session, zip);
         }
         break;
     } // end switch
   } // end for
   reader.close();
 }
Exemplo n.º 10
0
 /*package*/ void fillAttributes(XMLStreamReader in) {
   for (int i = in.getAttributeCount() - 1; i >= 0; i--) {
     String n = in.getAttributeLocalName(i);
     if (model.attributes.containsKey(n)) {
       if (attributes == null) attributes = new HashMap<String, String>();
       attributes.put(n, in.getAttributeValue(i));
     }
   }
   if (attributes == null) attributes = Collections.emptyMap();
 }
Exemplo n.º 11
0
 private void ensureIsUpdated() {
   if (updateRequired) {
     updateRequired = false;
     attC = reader.getAttributeCount();
     ensureIndexMapSize(attC);
     for (int i = 0; i < attC; i++) {
       indexToIDMap[i] =
           idResolver.getEID(reader.getAttributeNamespace(i), reader.getAttributeLocalName(i));
     }
   }
 }
Exemplo n.º 12
0
 private static Properties getAttributes(XMLStreamReader reader) {
   Properties props = new Properties();
   if (reader.getAttributeCount() > 0) {
     for (int i = 0; i < reader.getAttributeCount(); i++) {
       String attrName = reader.getAttributeLocalName(i);
       String attrValue = reader.getAttributeValue(i);
       props.setProperty(attrName, attrValue);
     }
   }
   return props;
 }
Exemplo n.º 13
0
  public static PortComponentRef parse(XMLStreamReader reader) throws XMLStreamException {
    PortComponentRef portComponentRef = new PortComponentRef();

    // Handle attributes
    final int count = reader.getAttributeCount();
    for (int i = 0; i < count; i++) {
      final String value = reader.getAttributeValue(i);
      if (reader.getAttributeNamespace(i) != null) {
        continue;
      }
      final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
      switch (attribute) {
        case ID:
          {
            portComponentRef.setId(value);
            break;
          }
        default:
          throw unexpectedAttribute(reader, i);
      }
    }

    // Handle elements
    while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
      final Element element = Element.forName(reader.getLocalName());
      switch (element) {
        case SERVICE_ENDPOINT_INTERFACE:
          portComponentRef.setServiceEndpointInterface(getElementText(reader));
          break;
        case ENABLE_MTOM:
          portComponentRef.setEnableMtom(Boolean.valueOf(getElementText(reader)));
          break;
        case MTOM_THRESHOLD:
          portComponentRef.setMtomThreshold(Integer.valueOf(getElementText(reader)));
          break;
        case ADDRESSING:
          portComponentRef.setAddressing(AddressingParser.parse(reader));
          break;
        case RESPECT_BINDING:
          portComponentRef.setRespectBinding(RespectBindingParser.parse(reader));
          break;
        case PORT_COMPONENT_LINK:
          portComponentRef.setPortComponentLink(getElementText(reader));
          break;
        default:
          throw unexpectedElement(reader);
      }
    }

    return portComponentRef;
  }
Exemplo n.º 14
0
 private void fillXMLAttributes(XMLStreamReader input) {
   fAttributes.removeAllAttributes();
   final int len = input.getAttributeCount();
   for (int i = 0; i < len; ++i) {
     fillQName(
         fAttributeQName,
         input.getAttributeNamespace(i),
         input.getAttributeLocalName(i),
         input.getAttributePrefix(i));
     String type = input.getAttributeType(i);
     fAttributes.addAttributeNS(
         fAttributeQName,
         (type != null) ? type : XMLSymbols.fCDATASymbol,
         input.getAttributeValue(i));
     fAttributes.setSpecified(i, input.isAttributeSpecified(i));
   }
 }
  private static List<BindVariable> parseBinds(String binds, XMLInputFactory inputFactory) {
    if (binds == null) return null;
    List<BindVariable> vars = new java.util.ArrayList<BindVariable>();
    // <binds><bind name=":1" pos="1" dty="1" dtystr="VARCHAR2(2000)" maxlen="2000" csid="873"
    // len="15">Billing Contact</bind></binds>

    java.io.CharArrayReader in = new java.io.CharArrayReader(binds.toCharArray());
    XMLStreamReader reader = null;
    try {
      reader = inputFactory.createXMLStreamReader(in);
      while (reader.hasNext()) {
        // loop till one sql tag is found
        int evtType = reader.next();
        if (evtType != XMLStreamConstants.START_ELEMENT) continue;
        String tagName = reader.getLocalName();
        if (!"bind".equals(tagName)) continue;
        BindVariable var = new BindVariable();
        int attrCount = reader.getAttributeCount();
        for (int i = 0; i < attrCount; i++) {
          String attrName = reader.getAttributeLocalName(i);
          String attrValue = reader.getAttributeValue(i);
          if ("name".equals(attrName)) var.name = attrValue;
          else if ("pos".equals(attrName)) var.pos = attrValue;
          else if ("dtystr".equalsIgnoreCase(attrName)) var.dtystr = attrValue;
          else if ("maxlen".equalsIgnoreCase(attrName)) {
            var.maxLen = attrValue;
          } else if ("len".equalsIgnoreCase(attrName)) {
            var.len = attrValue;
          }
        }
        var.value = reader.getElementText();
        vars.add(var);
      }
    } catch (Exception ex) {

    } finally {
      if (reader != null)
        try {
          reader.close();
          reader = null;
        } catch (Exception iex) {
        }
    }

    return vars;
  }
  public static ServletMappingMetaData parse(
      XMLStreamReader reader, PropertyReplacer propertyReplacer) throws XMLStreamException {
    ServletMappingMetaData servletMapping = new ServletMappingMetaData();

    // Handle attributes
    final int count = reader.getAttributeCount();
    for (int i = 0; i < count; i++) {
      final String value = reader.getAttributeValue(i);
      if (attributeHasNamespace(reader, i)) {
        continue;
      }
      final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
      switch (attribute) {
        case ID:
          {
            servletMapping.setId(value);
            break;
          }
        default:
          throw unexpectedAttribute(reader, i);
      }
    }

    // Handle elements
    while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
      final Element element = Element.forName(reader.getLocalName());
      switch (element) {
        case SERVLET_NAME:
          servletMapping.setServletName(getElementText(reader, propertyReplacer));
          break;
        case URL_PATTERN:
          List<String> urlPatterns = servletMapping.getUrlPatterns();
          if (urlPatterns == null) {
            urlPatterns = new ArrayList<String>();
            servletMapping.setUrlPatterns(urlPatterns);
          }
          urlPatterns.add(getElementText(reader, propertyReplacer));
          break;
        default:
          throw unexpectedElement(reader);
      }
    }

    return servletMapping;
  }
Exemplo n.º 17
0
 private static void parseProperty(XMLStreamReader reader, AdminObjectImpl anObj)
     throws XMLStreamException {
   if (reader.getAttributeCount() > 0) {
     String key = null;
     String value = null;
     for (int i = 0; i < reader.getAttributeCount(); i++) {
       String attrName = reader.getAttributeLocalName(i);
       String attrValue = reader.getAttributeValue(i);
       if (attrName.equals(Element.NAME.getLocalName())) {
         key = attrValue;
       }
       if (attrName.equals(Element.VALUE.getLocalName())) {
         value = attrValue;
       }
     }
     anObj.addProperty(key, value);
   }
   ignoreTillEnd(reader);
 }
Exemplo n.º 18
0
  private static void parseProperties(XMLStreamReader reader, Properties properties)
      throws XMLStreamException {

    while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
      final Element element = Element.forName(reader.getLocalName());
      switch (element) {
        case PROPERTY:
          final int count = reader.getAttributeCount();
          String name = null, value = null;
          for (int i = 0; i < count; i++) {
            final String attributeValue = reader.getAttributeValue(i);
            final String attributeNamespace = reader.getAttributeNamespace(i);
            if (attributeNamespace != null && !attributeNamespace.isEmpty()) {
              continue;
            }
            final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
            switch (attribute) {
              case NAME:
                name = attributeValue;
                break;
              case VALUE:
                value = attributeValue;
                if (name != null && value != null) {
                  properties.put(name, value);
                }
                name = value = null;
                break;
              default:
                throw unexpectedAttribute(reader, i);
            }
          }
          if (reader.hasNext() && (reader.nextTag() != END_ELEMENT))
            throw unexpectedElement(reader);

          break;
        default:
          throw unexpectedElement(reader);
      }
    }
  }
Exemplo n.º 19
0
  protected SolrDocumentList readDocuments(XMLStreamReader parser) throws XMLStreamException {
    SolrDocumentList docs = new SolrDocumentList();

    // Parse the attributes
    for (int i = 0; i < parser.getAttributeCount(); i++) {
      String n = parser.getAttributeLocalName(i);
      String v = parser.getAttributeValue(i);
      if ("numFound".equals(n)) {
        docs.setNumFound(Long.parseLong(v));
      } else if ("start".equals(n)) {
        docs.setStart(Long.parseLong(v));
      } else if ("maxScore".equals(n)) {
        docs.setMaxScore(Float.parseFloat(v));
      } else if ("sum".equals(n)) {
        docs.setSum(Double.parseDouble(v));
      } else if ("max".equals(n)) {
        docs.setMax(Double.parseDouble(v));
      } else if ("min".equals(n)) {
        docs.setMin(Double.parseDouble(v));
      }
    }

    // Read through each document
    int event;
    while (true) {
      event = parser.next();
      if (XMLStreamConstants.START_ELEMENT == event) {
        if (!"doc".equals(parser.getLocalName())) {
          throw new RuntimeException(
              "shoudl be doc! " + parser.getLocalName() + " :: " + parser.getLocation());
        }
        docs.add(readDocument(parser));
      } else if (XMLStreamConstants.END_ELEMENT == event) {
        return docs; // only happens once
      }
    }
  }
Exemplo n.º 20
0
  /** @since solr 1.3 */
  void processDelete(UpdateRequestProcessor processor, XMLStreamReader parser, SolrParams params)
      throws XMLStreamException, IOException {
    // Parse the command
    DeleteUpdateCommand deleteCmd = new DeleteUpdateCommand();
    deleteCmd.fromPending = true;
    deleteCmd.fromCommitted = true;

    Boolean updateStore = params.getBool(UpdateParams.UPDATE_STORE);
    if (updateStore != null) {
      deleteCmd.setUpdateStore(updateStore.booleanValue());
    }

    for (int i = 0; i < parser.getAttributeCount(); i++) {
      String attrName = parser.getAttributeLocalName(i);
      String attrVal = parser.getAttributeValue(i);
      if ("fromPending".equals(attrName)) {
        deleteCmd.fromPending = StrUtils.parseBoolean(attrVal);
      } else if ("fromCommitted".equals(attrName)) {
        deleteCmd.fromCommitted = StrUtils.parseBoolean(attrVal);
      } else {
        XmlUpdateRequestHandler.log.warn("unexpected attribute delete/@" + attrName);
      }
    }

    StringBuilder text = new StringBuilder();
    while (true) {
      int event = parser.next();
      switch (event) {
        case XMLStreamConstants.START_ELEMENT:
          String mode = parser.getLocalName();
          if (!("id".equals(mode) || "query".equals(mode))) {
            XmlUpdateRequestHandler.log.warn("unexpected XML tag /delete/" + mode);
            throw new SolrException(
                SolrException.ErrorCode.BAD_REQUEST, "unexpected XML tag /delete/" + mode);
          }
          text.setLength(0);
          break;

        case XMLStreamConstants.END_ELEMENT:
          String currTag = parser.getLocalName();
          if ("id".equals(currTag)) {
            deleteCmd.id = text.toString();
          } else if ("query".equals(currTag)) {
            deleteCmd.query = text.toString();
          } else if ("delete".equals(currTag)) {
            return;
          } else {
            XmlUpdateRequestHandler.log.warn("unexpected XML tag /delete/" + currTag);
            throw new SolrException(
                SolrException.ErrorCode.BAD_REQUEST, "unexpected XML tag /delete/" + currTag);
          }
          processor.processDelete(deleteCmd);
          deleteCmd.id = null;
          deleteCmd.query = null;
          break;

          // Add everything to the text
        case XMLStreamConstants.SPACE:
        case XMLStreamConstants.CDATA:
        case XMLStreamConstants.CHARACTERS:
          text.append(parser.getText());
          break;
      }
    }
  }
Exemplo n.º 21
0
      public static NfeCabecMsg parse(final javax.xml.stream.XMLStreamReader reader)
          throws java.lang.Exception {
        final NfeCabecMsg object = new NfeCabecMsg();

        java.lang.String nillableValue = null;
        try {

          while (!reader.isStartElement() && !reader.isEndElement()) {
            reader.next();
          }

          if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type")
              != null) {
            final java.lang.String fullTypeName =
                reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type");
            if (fullTypeName != null) {
              java.lang.String nsPrefix = null;
              if (fullTypeName.contains(":")) {
                nsPrefix = fullTypeName.substring(0, fullTypeName.indexOf(":"));
              }
              nsPrefix = nsPrefix == null ? "" : nsPrefix;

              final java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":") + 1);

              if (!"nfeCabecMsg".equals(type)) {
                // find namespace for the prefix
                final java.lang.String nsUri =
                    reader.getNamespaceContext().getNamespaceURI(nsPrefix);
                return (NfeCabecMsg) ExtensionMapper.getTypeObject(nsUri, type, reader);
              }
            }
          }

          // Note all attributes that were handled. Used to differ normal attributes
          // from anyAttributes.
          final java.util.Vector<String> handledAttributes = new java.util.Vector<>();

          // now run through all any or extra attributes
          // which were not reflected until now
          for (int i = 0; i < reader.getAttributeCount(); i++) {
            if (!handledAttributes.contains(reader.getAttributeLocalName(i))) {
              // this is an anyAttribute and we create
              // an OMAttribute for this
              final org.apache.axiom.om.OMFactory factory =
                  org.apache.axiom.om.OMAbstractFactory.getOMFactory();
              final org.apache.axiom.om.OMAttribute attr =
                  factory.createOMAttribute(
                      reader.getAttributeLocalName(i),
                      factory.createOMNamespace(
                          reader.getAttributeNamespace(i), reader.getAttributePrefix(i)),
                      reader.getAttributeValue(i));

              // and add it to the extra attributes

              object.addExtraAttributes(attr);
            }
          }

          reader.next();

          while (!reader.isStartElement() && !reader.isEndElement()) {
            reader.next();
          }

          if (reader.isStartElement()
              && new javax.xml.namespace.QName(
                      "http://www.portalfiscal.inf.br/nfe/wsdl/CadConsultaCadastro2", "versaoDados")
                  .equals(reader.getName())) {

            nillableValue =
                reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "nil");
            if ("true".equals(nillableValue) || "1".equals(nillableValue)) {
              throw new org.apache.axis2.databinding.ADBException(
                  "The element: " + "versaoDados" + "  cannot be null");
            }

            final java.lang.String content = reader.getElementText();

            object.setVersaoDados(
                org.apache.axis2.databinding.utils.ConverterUtil.convertToString(content));

            reader.next();

          } // End of if for expected property start element
          else {

          }

          while (!reader.isStartElement() && !reader.isEndElement()) {
            reader.next();
          }

          if (reader.isStartElement()
              && new javax.xml.namespace.QName(
                      "http://www.portalfiscal.inf.br/nfe/wsdl/CadConsultaCadastro2", "cUF")
                  .equals(reader.getName())) {

            nillableValue =
                reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "nil");
            if ("true".equals(nillableValue) || "1".equals(nillableValue)) {
              throw new org.apache.axis2.databinding.ADBException(
                  "The element: " + "cUF" + "  cannot be null");
            }

            final java.lang.String content = reader.getElementText();

            object.setCUF(
                org.apache.axis2.databinding.utils.ConverterUtil.convertToString(content));

            reader.next();

          } // End of if for expected property start element
          else {

          }

          while (!reader.isStartElement() && !reader.isEndElement()) {
            reader.next();
          }

          if (reader.isStartElement()) {
            // A start element we are not expecting indicates a trailing invalid property
            throw new org.apache.axis2.databinding.ADBException(
                "Unexpected subelement " + reader.getName());
          }

        } catch (final javax.xml.stream.XMLStreamException e) {
          throw new java.lang.Exception(e);
        }

        return object;
      }
  public static PersistenceContextReferenceMetaData parse(
      XMLStreamReader reader, final PropertyReplacer propertyReplacer) throws XMLStreamException {
    PersistenceContextReferenceMetaData pcReference = new PersistenceContextReferenceMetaData();

    // Handle attributes
    final int count = reader.getAttributeCount();
    for (int i = 0; i < count; i++) {
      final String value = reader.getAttributeValue(i);
      if (attributeHasNamespace(reader, i)) {
        continue;
      }
      final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
      switch (attribute) {
        case ID:
          {
            pcReference.setId(value);
            break;
          }
        default:
          throw unexpectedAttribute(reader, i);
      }
    }

    DescriptionsImpl descriptions = new DescriptionsImpl();
    // Handle elements
    while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
      if (DescriptionsMetaDataParser.parse(reader, descriptions, propertyReplacer)) {
        if (pcReference.getDescriptions() == null) {
          pcReference.setDescriptions(descriptions);
        }
        continue;
      }
      if (ResourceInjectionMetaDataParser.parse(reader, pcReference, propertyReplacer)) {
        continue;
      }
      final Element element = Element.forName(reader.getLocalName());
      switch (element) {
        case PERSISTENCE_CONTEXT_REF_NAME:
          pcReference.setPersistenceContextRefName(getElementText(reader, propertyReplacer));
          break;
        case PERSISTENCE_CONTEXT_TYPE:
          pcReference.setPersistenceContextType(
              PersistenceContextTypeDescription.valueOf(
                  propertyReplacer.replaceProperties(
                      getElementText(reader, propertyReplacer).toUpperCase())));
          break;
        case PERSISTENCE_CONTEXT_SYNCHRONIZATION:
          pcReference.setPersistenceContextSynchronization(
              PersistenceContextSynchronizationType.valueOf(
                  getElementText(reader, propertyReplacer)));
          break;
        case PERSISTENCE_UNIT_NAME:
          pcReference.setPersistenceUnitName(getElementText(reader, propertyReplacer));
          break;
        case PERSISTENCE_PROPERTY:
          PropertiesMetaData properties = pcReference.getProperties();
          if (properties == null) {
            properties = new PropertiesMetaData();
            pcReference.setProperties(properties);
          }
          properties.add(PropertyMetaDataParser.parse(reader, propertyReplacer));
          break;
        default:
          throw unexpectedElement(reader);
      }
    }

    return pcReference;
  }
Exemplo n.º 23
0
  public static PersistenceUnitMetadataHolder parse(final XMLStreamReader reader)
      throws XMLStreamException {

    reader.require(START_DOCUMENT, null, null); // check for a bogus document and throw error

    // Read until the first start element
    Version version = null;
    while (reader.hasNext() && reader.next() != START_ELEMENT) {
      if (reader.getEventType() == DTD) {
        final String dtdLocation = readDTDLocation(reader);
        if (dtdLocation != null) {
          version = Version.forLocation(dtdLocation);
        }
      }
    }
    final String schemaLocation = readSchemaLocation(reader);
    if (schemaLocation != null) {
      version = Version.forLocation(schemaLocation);
    }
    if (version == null || Version.UNKNOWN.equals(version)) {
      // Look at the version attribute
      String versionString = null;
      final int count = reader.getAttributeCount();
      for (int i = 0; i < count; i++) {
        final String attributeNamespace = reader.getAttributeNamespace(i);
        if (attributeNamespace != null && !attributeNamespace.isEmpty()) {
          continue;
        }
        final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
        if (attribute == Attribute.VERSION) {
          versionString = reader.getAttributeValue(i);
        }
      }
      if ("1.0".equals(versionString)) {
        version = Version.JPA_1_0;
      } else if ("1".equals(versionString)) {
        version = Version.JPA_1_0;
      } else if ("2.0".equals(versionString)) {
        version = Version.JPA_2_0;
      } else if ("2".equals(versionString)) {
        version = Version.JPA_2_0;
      } else {
        version = Version.JPA_2_0;
      }
    }

    final int count = reader.getAttributeCount();
    for (int i = 0; i < count; i++) {
      final String value = reader.getAttributeValue(i);
      final String attributeNamespace = reader.getAttributeNamespace(i);
      if (attributeNamespace != null && !attributeNamespace.isEmpty()) {
        continue;
      }
      final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
      switch (attribute) {
        case VERSION:
          // log.info("version = " + value);
          // TODO:  handle version
          break;
        default:
          throw unexpectedAttribute(reader, i);
      }
    }
    final List<PersistenceUnitMetadata> PUs = new ArrayList<PersistenceUnitMetadata>();
    // until the ending PERSISTENCE tag
    while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
      final Element element = Element.forName(reader.getLocalName());
      switch (element) {
        case PERSISTENCEUNIT:
          PersistenceUnitMetadata pu = parsePU(reader, version);
          PUs.add(pu);
          JPA_LOGGER.readingPersistenceXml(pu.getPersistenceUnitName());
          break;

        default:
          throw unexpectedElement(reader);
      }
    }
    PersistenceUnitMetadataHolder result =
        new PersistenceUnitMetadataHolder().setPersistenceUnits(PUs);
    if (JPA_LOGGER.isTraceEnabled()) JPA_LOGGER.trace(result.toString());

    return result;
  }
Exemplo n.º 24
0
  /**
   * Parse the persistence unit definitions based on persistence_2_0.xsd.
   *
   * @param reader
   * @return
   * @throws XMLStreamException
   */
  private static PersistenceUnitMetadata parsePU(XMLStreamReader reader, Version version)
      throws XMLStreamException {
    PersistenceUnitMetadata pu = new PersistenceUnitMetadataImpl();
    List<String> classes = new ArrayList<String>(1);
    List<String> jarfiles = new ArrayList<String>(1);
    List<String> mappingFiles = new ArrayList<String>(1);
    Properties properties = new Properties();

    // set defaults
    pu.setTransactionType(PersistenceUnitTransactionType.JTA);
    pu.setValidationMode(ValidationMode.AUTO);
    pu.setSharedCacheMode(SharedCacheMode.UNSPECIFIED);
    pu.setPersistenceProviderClassName(
        "org.hibernate.ejb.HibernatePersistence"); // TODO: move to domain.xml?
    if (version.equals(Version.JPA_1_0)) {
      pu.setPersistenceXMLSchemaVersion("1.0");
    } else {
      pu.setPersistenceXMLSchemaVersion("2.0");
    }

    final int count = reader.getAttributeCount();
    for (int i = 0; i < count; i++) {
      final String value = reader.getAttributeValue(i);
      if (traceEnabled) {
        JPA_LOGGER.tracef("parse persistence.xml: attribute value(%d) = %s", i, value);
      }
      final String attributeNamespace = reader.getAttributeNamespace(i);
      if (attributeNamespace != null && !attributeNamespace.isEmpty()) {
        continue;
      }
      final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
      switch (attribute) {
        case NAME:
          pu.setPersistenceUnitName(value);
          break;
        case TRANSACTIONTYPE:
          if (value.equalsIgnoreCase("RESOURCE_LOCAL"))
            pu.setTransactionType(PersistenceUnitTransactionType.RESOURCE_LOCAL);
          break;
        default:
          throw unexpectedAttribute(reader, i);
      }
    }

    // until the ending PERSISTENCEUNIT tag
    while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
      final Element element = Element.forName(reader.getLocalName());
      if (traceEnabled) {
        JPA_LOGGER.tracef("parse persistence.xml: element=%s", element.getLocalName());
      }
      switch (element) {
        case CLASS:
          classes.add(Util.resolveSystemProperty(reader.getElementText()));
          break;

        case DESCRIPTION:
          final String description = Util.resolveSystemProperty(reader.getElementText());
          break;

        case EXCLUDEUNLISTEDCLASSES:
          String text = Util.resolveSystemProperty(reader.getElementText());
          if (text == null || text.isEmpty()) {
            // the spec has examples where an empty
            // exclude-unlisted-classes element has the same
            // effect as setting it to true
            pu.setExcludeUnlistedClasses(true);
          } else {
            pu.setExcludeUnlistedClasses(Boolean.valueOf(text));
          }
          break;

        case JARFILE:
          String file = Util.resolveSystemProperty(reader.getElementText());
          jarfiles.add(file);
          break;

        case JTADATASOURCE:
          pu.setJtaDataSourceName(Util.resolveSystemProperty(reader.getElementText()));
          break;

        case NONJTADATASOURCE:
          pu.setNonJtaDataSourceName(Util.resolveSystemProperty(reader.getElementText()));
          break;

        case MAPPINGFILE:
          mappingFiles.add(Util.resolveSystemProperty(reader.getElementText()));
          break;

        case PROPERTIES:
          parseProperties(reader, properties);
          break;

        case PROVIDER:
          pu.setPersistenceProviderClassName(Util.resolveSystemProperty(reader.getElementText()));
          break;

        case SHAREDCACHEMODE:
          String cm = Util.resolveSystemProperty(reader.getElementText());
          pu.setSharedCacheMode(SharedCacheMode.valueOf(cm));
          break;

        case VALIDATIONMODE:
          String validationMode = Util.resolveSystemProperty(reader.getElementText());
          pu.setValidationMode(ValidationMode.valueOf(validationMode));
          break;

        default:
          throw unexpectedElement(reader);
      }
    }
    if (traceEnabled) {
      JPA_LOGGER.trace("parse persistence.xml: reached ending persistence-unit tag");
    }
    pu.setManagedClassNames(classes);
    pu.setJarFiles(jarfiles);
    pu.setMappingFiles(mappingFiles);
    pu.setProperties(properties);
    return pu;
  }
Exemplo n.º 25
0
  /**
   * Given the input stream, read a document
   *
   * @since solr 1.3
   */
  SolrInputDocument readDoc(XMLStreamReader parser) throws XMLStreamException {
    SolrInputDocument doc = new SolrInputDocument();

    String attrName = "";
    for (int i = 0; i < parser.getAttributeCount(); i++) {
      attrName = parser.getAttributeLocalName(i);
      if ("boost".equals(attrName)) {
        doc.setDocumentBoost(Float.parseFloat(parser.getAttributeValue(i)));
      } else {
        XmlUpdateRequestHandler.log.warn("Unknown attribute doc/@" + attrName);
      }
    }

    StringBuilder text = new StringBuilder();
    String name = null;
    float boost = 1.0f;
    boolean isNull = false;
    while (true) {
      int event = parser.next();
      switch (event) {
          // Add everything to the text
        case XMLStreamConstants.SPACE:
        case XMLStreamConstants.CDATA:
        case XMLStreamConstants.CHARACTERS:
          text.append(parser.getText());
          break;

        case XMLStreamConstants.END_ELEMENT:
          if ("doc".equals(parser.getLocalName())) {
            return doc;
          } else if ("field".equals(parser.getLocalName())) {
            if (!isNull) {
              doc.addField(name, text.toString(), boost);
              boost = 1.0f;
            }
          }
          break;

        case XMLStreamConstants.START_ELEMENT:
          text.setLength(0);
          String localName = parser.getLocalName();
          if (!"field".equals(localName)) {
            XmlUpdateRequestHandler.log.warn("unexpected XML tag doc/" + localName);
            throw new SolrException(
                SolrException.ErrorCode.BAD_REQUEST, "unexpected XML tag doc/" + localName);
          }
          boost = 1.0f;
          String attrVal = "";
          for (int i = 0; i < parser.getAttributeCount(); i++) {
            attrName = parser.getAttributeLocalName(i);
            attrVal = parser.getAttributeValue(i);
            if ("name".equals(attrName)) {
              name = attrVal;
            } else if ("boost".equals(attrName)) {
              boost = Float.parseFloat(attrVal);
            } else if ("null".equals(attrName)) {
              isNull = StrUtils.parseBoolean(attrVal);
            } else {
              XmlUpdateRequestHandler.log.warn("Unknown attribute doc/field/@" + attrName);
            }
          }
          break;
      }
    }
  }
Exemplo n.º 26
0
  /**
   * Parses the SecurityToken by wrapping within an AssertionWrapper.
   *
   * @param securityToken SecurityToken
   */
  private void parseToken(SecurityToken securityToken) {
    XMLStreamReader xmlStreamReader = StaxUtils.createXMLStreamReader(securityToken.getToken());

    try {
      AttrStatement attributeStatement = null;
      AuthenticationStatement authenticationStatement = null;
      Attr attribute = null;
      int attrs = 0;
      while (xmlStreamReader.hasNext()) {
        int event = xmlStreamReader.next();
        switch (event) {
          case XMLStreamConstants.START_ELEMENT:
            {
              String localName = xmlStreamReader.getLocalName();
              switch (localName) {
                case NameID.DEFAULT_ELEMENT_LOCAL_NAME:
                  name = xmlStreamReader.getElementText();
                  for (int i = 0; i < xmlStreamReader.getAttributeCount(); i++) {
                    if (xmlStreamReader
                        .getAttributeLocalName(i)
                        .equals(NameID.FORMAT_ATTRIB_NAME)) {
                      nameIDFormat = xmlStreamReader.getAttributeValue(i);
                      break;
                    }
                  }
                  break;
                case AttributeStatement.DEFAULT_ELEMENT_LOCAL_NAME:
                  attributeStatement = new AttrStatement();
                  attributeStatements.add(attributeStatement);
                  break;
                case AuthnStatement.DEFAULT_ELEMENT_LOCAL_NAME:
                  authenticationStatement = new AuthenticationStatement();
                  authenticationStatements.add(authenticationStatement);
                  attrs = xmlStreamReader.getAttributeCount();
                  for (int i = 0; i < attrs; i++) {
                    String name = xmlStreamReader.getAttributeLocalName(i);
                    String value = xmlStreamReader.getAttributeValue(i);
                    if (AuthnStatement.AUTHN_INSTANT_ATTRIB_NAME.equals(name)) {
                      authenticationStatement.setAuthnInstant(DateTime.parse(value));
                    }
                  }
                  break;
                case AuthnContextClassRef.DEFAULT_ELEMENT_LOCAL_NAME:
                  if (authenticationStatement != null) {
                    String classValue = xmlStreamReader.getText();
                    classValue = classValue.trim();
                    AuthenticationContextClassRef authenticationContextClassRef =
                        new AuthenticationContextClassRef();
                    authenticationContextClassRef.setAuthnContextClassRef(classValue);
                    AuthenticationContext authenticationContext = new AuthenticationContext();
                    authenticationContext.setAuthnContextClassRef(authenticationContextClassRef);
                    authenticationStatement.setAuthnContext(authenticationContext);
                  }
                  break;
                case Attribute.DEFAULT_ELEMENT_LOCAL_NAME:
                  attribute = new Attr();
                  if (attributeStatement != null) {
                    attributeStatement.addAttribute(attribute);
                  }
                  attrs = xmlStreamReader.getAttributeCount();
                  for (int i = 0; i < attrs; i++) {
                    String name = xmlStreamReader.getAttributeLocalName(i);
                    String value = xmlStreamReader.getAttributeValue(i);
                    if (Attribute.NAME_ATTTRIB_NAME.equals(name)) {
                      attribute.setName(value);
                    } else if (Attribute.NAME_FORMAT_ATTRIB_NAME.equals(name)) {
                      attribute.setNameFormat(value);
                    }
                  }
                  break;
                case AttributeValue.DEFAULT_ELEMENT_LOCAL_NAME:
                  XSString xsString = new XMLString();
                  xsString.setValue(xmlStreamReader.getElementText());
                  if (attribute != null) {
                    attribute.addAttributeValue(xsString);
                  }
                  break;
                case Issuer.DEFAULT_ELEMENT_LOCAL_NAME:
                  issuer = xmlStreamReader.getElementText();
                  break;
                case Conditions.DEFAULT_ELEMENT_LOCAL_NAME:
                  attrs = xmlStreamReader.getAttributeCount();
                  for (int i = 0; i < attrs; i++) {
                    String name = xmlStreamReader.getAttributeLocalName(i);
                    String value = xmlStreamReader.getAttributeValue(i);
                    if (Conditions.NOT_BEFORE_ATTRIB_NAME.equals(name)) {
                      notBefore = DatatypeConverter.parseDateTime(value).getTime();
                    } else if (Conditions.NOT_ON_OR_AFTER_ATTRIB_NAME.equals(name)) {
                      notOnOrAfter = DatatypeConverter.parseDateTime(value).getTime();
                    }
                  }
                  break;
              }
              break;
            }
          case XMLStreamConstants.END_ELEMENT:
            {
              String localName = xmlStreamReader.getLocalName();
              switch (localName) {
                case AttributeStatement.DEFAULT_ELEMENT_LOCAL_NAME:
                  attributeStatement = null;
                  break;
                case Attribute.DEFAULT_ELEMENT_LOCAL_NAME:
                  attribute = null;
                  break;
              }
              break;
            }
        }
      }
    } catch (XMLStreamException e) {
      LOGGER.error("Unable to parse security token.", e);
    } finally {
      try {
        xmlStreamReader.close();
      } catch (XMLStreamException ignore) {
        // ignore
      }
    }
  }
Exemplo n.º 27
0
  /** @since solr 1.2 */
  void processUpdate(
      UpdateRequestProcessor processor, XMLStreamReader parser, SolrParams solrParams)
      throws XMLStreamException, IOException, FactoryConfigurationError, InstantiationException,
          IllegalAccessException, TransformerConfigurationException {
    AddUpdateCommand addCmd = null;
    while (true) {
      int event = parser.next();
      switch (event) {
        case XMLStreamConstants.END_DOCUMENT:
          parser.close();
          return;

        case XMLStreamConstants.START_ELEMENT:
          String currTag = parser.getLocalName();
          if (currTag.equals(XmlUpdateRequestHandler.ADD)) {
            XmlUpdateRequestHandler.log.trace("SolrCore.update(add)");

            addCmd = new AddUpdateCommand();
            boolean overwrite = true; // the default

            Boolean overwritePending = null;
            Boolean overwriteCommitted = null;
            for (int i = 0; i < parser.getAttributeCount(); i++) {
              String attrName = parser.getAttributeLocalName(i);
              String attrVal = parser.getAttributeValue(i);
              if (XmlUpdateRequestHandler.OVERWRITE.equals(attrName)) {
                overwrite = StrUtils.parseBoolean(attrVal);
              } else if (XmlUpdateRequestHandler.ALLOW_DUPS.equals(attrName)) {
                overwrite = !StrUtils.parseBoolean(attrVal);
              } else if (XmlUpdateRequestHandler.COMMIT_WITHIN.equals(attrName)) {
                addCmd.commitWithin = Integer.parseInt(attrVal);
              } else if (XmlUpdateRequestHandler.OVERWRITE_PENDING.equals(attrName)) {
                overwritePending = StrUtils.parseBoolean(attrVal);
              } else if (XmlUpdateRequestHandler.OVERWRITE_COMMITTED.equals(attrName)) {
                overwriteCommitted = StrUtils.parseBoolean(attrVal);
              } else {
                XmlUpdateRequestHandler.log.warn("Unknown attribute id in add:" + attrName);
              }
            }

            // check if these flags are set
            if (overwritePending != null && overwriteCommitted != null) {
              if (overwritePending != overwriteCommitted) {
                throw new SolrException(
                    SolrException.ErrorCode.BAD_REQUEST,
                    "can't have different values for 'overwritePending' and 'overwriteCommitted'");
              }
              overwrite = overwritePending;
            }
            addCmd.overwriteCommitted = overwrite;
            addCmd.overwritePending = overwrite;
            addCmd.allowDups = !overwrite;
          } else if ("doc".equals(currTag)) {
            XmlUpdateRequestHandler.log.trace("adding doc...");
            addCmd.clear();
            addCmd.solrDoc = readDoc(parser);
            processor.processAdd(addCmd);
          } else if (XmlUpdateRequestHandler.COMMIT.equals(currTag)
              || XmlUpdateRequestHandler.OPTIMIZE.equals(currTag)) {
            XmlUpdateRequestHandler.log.trace("parsing " + currTag);

            CommitUpdateCommand cmd =
                new CommitUpdateCommand(XmlUpdateRequestHandler.OPTIMIZE.equals(currTag));

            boolean sawWaitSearcher = false, sawWaitFlush = false;
            for (int i = 0; i < parser.getAttributeCount(); i++) {
              String attrName = parser.getAttributeLocalName(i);
              String attrVal = parser.getAttributeValue(i);
              if (XmlUpdateRequestHandler.WAIT_FLUSH.equals(attrName)) {
                cmd.waitFlush = StrUtils.parseBoolean(attrVal);
                sawWaitFlush = true;
              } else if (XmlUpdateRequestHandler.WAIT_SEARCHER.equals(attrName)) {
                cmd.waitSearcher = StrUtils.parseBoolean(attrVal);
                sawWaitSearcher = true;
              } else if (UpdateParams.MAX_OPTIMIZE_SEGMENTS.equals(attrName)) {
                cmd.maxOptimizeSegments = Integer.parseInt(attrVal);
              } else if (UpdateParams.EXPUNGE_DELETES.equals(attrName)) {
                cmd.expungeDeletes = StrUtils.parseBoolean(attrVal);
              } else {
                XmlUpdateRequestHandler.log.warn("unexpected attribute commit/@" + attrName);
              }
            }

            // If waitFlush is specified and waitSearcher wasn't, then
            // clear waitSearcher.
            if (sawWaitFlush && !sawWaitSearcher) {
              cmd.waitSearcher = false;
            }
            processor.processCommit(cmd);
          } // end commit
          else if (XmlUpdateRequestHandler.ROLLBACK.equals(currTag)) {
            XmlUpdateRequestHandler.log.trace("parsing " + currTag);

            RollbackUpdateCommand cmd = new RollbackUpdateCommand();

            processor.processRollback(cmd);
          } // end rollback
          else if (XmlUpdateRequestHandler.DELETE.equals(currTag)) {
            XmlUpdateRequestHandler.log.trace("parsing delete");
            processDelete(processor, parser, solrParams);
          } // end delete
          break;
      }
    }
  }
Exemplo n.º 28
0
  /**
   * Given the input stream, read a document
   *
   * @since solr 1.3
   */
  public SolrInputDocument readDoc(XMLStreamReader parser) throws XMLStreamException {
    SolrInputDocument doc = new SolrInputDocument();

    String attrName = "";
    for (int i = 0; i < parser.getAttributeCount(); i++) {
      attrName = parser.getAttributeLocalName(i);
      if ("boost".equals(attrName)) {
        doc.setDocumentBoost(Float.parseFloat(parser.getAttributeValue(i)));
      } else {
        log.warn("XML element <doc> has invalid XML attr:" + attrName);
      }
    }

    StringBuilder text = new StringBuilder();
    String name = null;
    float boost = 1.0f;
    boolean isNull = false;
    String update = null;
    Collection<SolrInputDocument> subDocs = null;
    Map<String, Map<String, Object>> updateMap = null;
    boolean complete = false;
    while (!complete) {
      int event = parser.next();
      switch (event) {
          // Add everything to the text
        case XMLStreamConstants.SPACE:
        case XMLStreamConstants.CDATA:
        case XMLStreamConstants.CHARACTERS:
          text.append(parser.getText());
          break;

        case XMLStreamConstants.END_ELEMENT:
          if ("doc".equals(parser.getLocalName())) {
            if (subDocs != null && !subDocs.isEmpty()) {
              doc.addChildDocuments(subDocs);
              subDocs = null;
            }
            complete = true;
            break;
          } else if ("field".equals(parser.getLocalName())) {
            // should I warn in some text has been found too
            Object v = isNull ? null : text.toString();
            if (update != null) {
              if (updateMap == null) updateMap = new HashMap<>();
              Map<String, Object> extendedValues = updateMap.get(name);
              if (extendedValues == null) {
                extendedValues = new HashMap<>(1);
                updateMap.put(name, extendedValues);
              }
              Object val = extendedValues.get(update);
              if (val == null) {
                extendedValues.put(update, v);
              } else {
                // multiple val are present
                if (val instanceof List) {
                  List list = (List) val;
                  list.add(v);
                } else {
                  List<Object> values = new ArrayList<>();
                  values.add(val);
                  values.add(v);
                  extendedValues.put(update, values);
                }
              }
              break;
            }
            doc.addField(name, v, boost);
            boost = 1.0f;
            // field is over
            name = null;
          }
          break;

        case XMLStreamConstants.START_ELEMENT:
          text.setLength(0);
          String localName = parser.getLocalName();
          if ("doc".equals(localName)) {
            if (subDocs == null) subDocs = Lists.newArrayList();
            subDocs.add(readDoc(parser));
          } else {
            if (!"field".equals(localName)) {
              String msg = "XML element <doc> has invalid XML child element: " + localName;
              log.warn(msg);
              throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, msg);
            }
            boost = 1.0f;
            update = null;
            isNull = false;
            String attrVal = "";
            for (int i = 0; i < parser.getAttributeCount(); i++) {
              attrName = parser.getAttributeLocalName(i);
              attrVal = parser.getAttributeValue(i);
              if (NAME.equals(attrName)) {
                name = attrVal;
              } else if ("boost".equals(attrName)) {
                boost = Float.parseFloat(attrVal);
              } else if ("null".equals(attrName)) {
                isNull = StrUtils.parseBoolean(attrVal);
              } else if ("update".equals(attrName)) {
                update = attrVal;
              } else {
                log.warn("XML element <field> has invalid XML attr: " + attrName);
              }
            }
          }
          break;
      }
    }

    if (updateMap != null) {
      for (Map.Entry<String, Map<String, Object>> entry : updateMap.entrySet()) {
        name = entry.getKey();
        Map<String, Object> value = entry.getValue();
        doc.addField(name, value, 1.0f);
      }
    }

    return doc;
  }
 public String getAttributeLocalName(final int index) {
   return streamReader.getAttributeLocalName(index);
 }
Exemplo n.º 30
0
  public static WebMetaData parse(
      XMLStreamReader reader, DTDInfo info, boolean validation, PropertyReplacer propertyReplacer)
      throws XMLStreamException {
    if (reader == null) throw new IllegalArgumentException("Null reader");
    if (info == null) throw new IllegalArgumentException("Null info");

    reader.require(START_DOCUMENT, null, null);

    // Read until the first start element
    while (reader.hasNext() && reader.next() != START_ELEMENT) ;

    String schemaLocation = readSchemaLocation(reader);

    Version version = null;
    if (info.getPublicID() != null) {
      version = Version.fromPublicID(info.getPublicID());
    }
    if (version == null && info.getSystemID() != null) {
      version = Version.fromSystemID(info.getSystemID());
    }
    if (version == null && schemaLocation != null) {
      version = Version.fromSystemID(schemaLocation);
    }
    if (version == null) {
      // Look at the version attribute
      String versionString = null;
      final int count = reader.getAttributeCount();
      for (int i = 0; i < count; i++) {
        if (attributeHasNamespace(reader, i)) {
          continue;
        }
        final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
        if (attribute == Attribute.VERSION) {
          versionString = reader.getAttributeValue(i);
        }
      }
      if ("2.4".equals(versionString)) {
        version = Version.SERVLET_2_4;
      } else if ("2.5".equals(versionString)) {
        version = Version.SERVLET_2_5;
      } else if ("3.0".equals(versionString)) {
        version = Version.SERVLET_3_0;
      }
    }

    if (version == null) version = Version.SERVLET_3_0;
    // throw new IllegalStateException("Cannot obtain servlet version");

    WebMetaData wmd = null;
    switch (version) {
      case SERVLET_2_2:
        wmd = new Web22MetaData();
        break;
      case SERVLET_2_3:
        wmd = new Web23MetaData();
        break;
      case SERVLET_2_4:
        wmd = new Web24MetaData();
        break;
      case SERVLET_2_5:
        wmd = new Web25MetaData();
        break;
      case SERVLET_3_0:
        wmd = new Web30MetaData();
        break;
    }

    // Set the publicId / systemId
    if (info != null) wmd.setDTD(info.getBaseURI(), info.getPublicID(), info.getSystemID());

    // Set the schema location if we have one
    if (schemaLocation != null) wmd.setSchemaLocation(schemaLocation);

    // Handle attributes
    final int count = reader.getAttributeCount();
    for (int i = 0; i < count; i++) {
      final String value = reader.getAttributeValue(i);
      if (attributeHasNamespace(reader, i)) {
        continue;
      }
      final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
      switch (attribute) {
        case ID:
          {
            wmd.setId(value);
            break;
          }
        case VERSION:
          {
            wmd.setVersion(value);
            break;
          }
        case METADATA_COMPLETE:
          {
            if (wmd instanceof Web25MetaData || wmd instanceof Web30MetaData) {
              if (Boolean.TRUE.equals(Boolean.valueOf(value))) {
                if (wmd instanceof Web25MetaData) {
                  ((Web25MetaData) wmd).setMetadataComplete(true);
                }
                if (wmd instanceof Web30MetaData) {
                  ((Web30MetaData) wmd).setMetadataComplete(true);
                }
              }
            } else {
              throw unexpectedAttribute(reader, i);
            }
            break;
          }
        default:
          throw unexpectedAttribute(reader, i);
      }
    }

    DescriptionGroupMetaData descriptionGroup = new DescriptionGroupMetaData();
    EnvironmentRefsGroupMetaData env = new EnvironmentRefsGroupMetaData();
    // Handle elements
    while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
      if (WebCommonMetaDataParser.parse(reader, wmd, propertyReplacer)) {
        continue;
      }
      if (EnvironmentRefsGroupMetaDataParser.parse(reader, env, propertyReplacer)) {
        if (wmd.getJndiEnvironmentRefsGroup() == null) {
          wmd.setJndiEnvironmentRefsGroup(env);
        }
        continue;
      }
      if (DescriptionGroupMetaDataParser.parse(reader, descriptionGroup)) {
        if (wmd.getDescriptionGroup() == null) {
          wmd.setDescriptionGroup(descriptionGroup);
        }
        continue;
      }
      final Element element = Element.forName(reader.getLocalName());
      switch (element) {
        case ABSOLUTE_ORDERING:
          if (wmd instanceof Web30MetaData) {
            ((Web30MetaData) wmd)
                .setAbsoluteOrdering(
                    AbsoluteOrderingMetaDataParser.parse(reader, propertyReplacer));
          } else {
            throw unexpectedElement(reader);
          }
          break;
        case MODULE_NAME:
          if (wmd instanceof Web30MetaData) {
            ((Web30MetaData) wmd).setModuleName(getElementText(reader, propertyReplacer));
          } else {
            throw unexpectedElement(reader);
          }
          break;
        case TAGLIB:
          if (wmd instanceof Web22MetaData || wmd instanceof Web23MetaData) {
            JspConfigMetaData jspConfig = wmd.getJspConfig();
            if (jspConfig == null) {
              jspConfig = new JspConfigMetaData();
              wmd.setJspConfig(jspConfig);
            }
            List<TaglibMetaData> taglibs = jspConfig.getTaglibs();
            if (taglibs == null) {
              taglibs = new ArrayList<TaglibMetaData>();
              jspConfig.setTaglibs(taglibs);
            }
            taglibs.add(TaglibMetaDataParser.parse(reader, propertyReplacer));
          } else {
            throw unexpectedElement(reader);
          }
          break;
        default:
          throw unexpectedElement(reader);
      }
    }

    return wmd;
  }