Java Code Examples for javax.xml.stream.XMLEventReader#hasNext()

The following examples show how to use javax.xml.stream.XMLEventReader#hasNext() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: IdentityTrustConfigParser.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Parse the <identity-trust> element
 * @param xmlEventReader
 * @return
 * @throws XMLStreamException
 */
public List<IdentityTrustModuleEntry> parse(XMLEventReader xmlEventReader) throws XMLStreamException
{
   List<IdentityTrustModuleEntry> entries = new ArrayList<IdentityTrustModuleEntry>();
   while(xmlEventReader.hasNext())
   {   
      XMLEvent xmlEvent = xmlEventReader.peek(); 
      
      StartElement peekedStartElement = (StartElement) xmlEvent;
      IdentityTrustModuleEntry entry = null;
      if("trust-module".equals(StaxParserUtil.getStartElementName(peekedStartElement)))
      {
         entry = this.getEntry(xmlEventReader);
      } 
      else
         break;
      entries.add(entry); 
   }
   return entries;
}
 
Example 2
Source File: AuthenticationConfigParser.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Parse the <authentication> element
 * @param xmlEventReader
 * @return
 * @throws XMLStreamException
 */
public Set<AppConfigurationEntry> parse(XMLEventReader xmlEventReader) throws XMLStreamException
{
   Set<AppConfigurationEntry> entries = new LinkedHashSet<AppConfigurationEntry>();
   while(xmlEventReader.hasNext())
   {   
      XMLEvent xmlEvent = xmlEventReader.peek(); 
      
      StartElement peekedStartElement = (StartElement) xmlEvent;
      AppConfigurationEntry entry = null;
      if("login-module".equals(StaxParserUtil.getStartElementName(peekedStartElement)))
      {
         entry = this.getEntry(xmlEventReader);
      } 
      else
         break;
      entries.add(entry); 
   }
   return entries;
}
 
Example 3
Source File: RewriteWithStAXTest.java    From versions-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasic()
    throws Exception
{
    String input = "<?xml version='1.0' encoding='utf-8'?>\n" + "<project>\n\r\n\r\n\r\n\r" + "  <parent>\r\n"
        + "    <groupId xmlns='foo'>org.codehaus.mojo</groupId>\n"
        + "    <artifactId>mojo-&amp;sandbox-parent</artifactId>\n" + "    <version>5-SNAPSHOT</version>\r"
        + "  </parent>\r" + "<build/></project>";

    byte[] rawInput = input.getBytes( "utf-8" );
    ByteArrayInputStream source = new ByteArrayInputStream( rawInput );
    ByteArrayOutputStream dest = new ByteArrayOutputStream();
    XMLInputFactory inputFactory = XMLInputFactory2.newInstance();
    inputFactory.setProperty( XMLInputFactory2.P_PRESERVE_LOCATION, Boolean.TRUE );
    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    XMLEventReader eventReader = inputFactory.createXMLEventReader( source );
    XMLEventWriter eventWriter = outputFactory.createXMLEventWriter( dest, "utf-8" );
    while ( eventReader.hasNext() )
    {
        eventWriter.add( eventReader.nextEvent() );
    }

    String output = new String( dest.toByteArray(), "utf-8" );

    assertFalse( "StAX implementation is not good enough", input.equals( output ) );
}
 
Example 4
Source File: ODataXmlDeserializer.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Override
public DeserializerResult entityReferences(final InputStream stream) throws DeserializerException {
  try {
    XMLEventReader reader = getReader(stream);
    ArrayList<URI> references = new ArrayList<URI>();

    while (reader.hasNext()) {
      final XMLEvent event = reader.nextEvent();
      if (event.isStartElement()) {
        StartElement start = event.asStartElement();
        if (entryRefQName.equals(start.getName())) {
          Attribute context = start.getAttributeByName(Constants.QNAME_ATOM_ATTR_ID);
          URI uri = URI.create(context.getValue());
          references.add(uri);
        }
      }
    }
    return DeserializerResultImpl.with().entityReferences(references).build();
  } catch (XMLStreamException e) {
    throw new DeserializerException(e.getMessage(), e, DeserializerException.MessageKeys.IO_EXCEPTION);
  }
}
 
Example 5
Source File: SearchHandle.java    From java-client-api with Apache License 2.0 6 votes vote down vote up
private void collectTop(XMLEventReader reader, StartElement element)
  throws XMLStreamException
{
  QName startName = element.getName();
  events: while (reader.hasNext()) {
    XMLEvent event = reader.nextEvent();

    int eventType = event.getEventType();
    switch (eventType) {
      case XMLStreamConstants.START_ELEMENT:
        handleTop(reader, event.asStartElement());
        break;
      case XMLStreamConstants.END_ELEMENT:
        if (startName.equals(event.asEndElement().getName())) {
          break events;
        }
        break;
    }
  }
}
 
Example 6
Source File: AtomDeserializer.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private void common(final XMLEventReader reader, final StartElement start,
    final AbstractODataObject object, final String key) throws XMLStreamException {

  boolean foundEndElement = false;
  while (reader.hasNext() && !foundEndElement) {
    final XMLEvent event = reader.nextEvent();

    if (event.isCharacters() && !event.asCharacters().isWhiteSpace()) {
      object.setCommonProperty(key, event.asCharacters().getData());
    }

    if (event.isEndElement() && start.getName().equals(event.asEndElement().getName())) {
      foundEndElement = true;
    }
  }
}
 
Example 7
Source File: XmlResourceValues.java    From bazel with Apache License 2.0 5 votes vote down vote up
public static XMLEvent peekNextTag(XMLEventReader eventReader) throws XMLStreamException {
  while (eventReader.hasNext()
      && !(eventReader.peek().isEndElement() || eventReader.peek().isStartElement())) {
    eventReader.nextEvent();
  }
  return eventReader.peek();
}
 
Example 8
Source File: ExternalAttachmentsUnmarshaller.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private Map<URI, Policy> unmarshal(final XMLEventReader reader, final StartElement parentElement) throws PolicyException {
    XMLEvent event = null;
    while (reader.hasNext()) {
        try {
            event = reader.peek();
            switch (event.getEventType()) {
                case XMLStreamConstants.START_DOCUMENT:
                case XMLStreamConstants.COMMENT:
                    reader.nextEvent();
                    break;

                case XMLStreamConstants.CHARACTERS:
                    processCharacters(event.asCharacters(), parentElement, map);
                    reader.nextEvent();
                    break;

                case XMLStreamConstants.END_ELEMENT:
                    processEndTag(event.asEndElement(), parentElement);
                    reader.nextEvent();
                    return map;

                case XMLStreamConstants.START_ELEMENT:
                    final StartElement element = event.asStartElement();
                    processStartTag(element, parentElement, reader, map);
                    break;

                case XMLStreamConstants.END_DOCUMENT:
                    return map;

                default:
                    throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0087_UNKNOWN_EVENT(event)));
            }
        } catch (XMLStreamException e) {
            final Location location = event == null ? null : event.getLocation();
            throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0088_FAILED_PARSE(location)), e);
        }
    }
    return map;
}
 
Example 9
Source File: StaxParserUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Get the next {@code StartElement }
 *
 * @param xmlEventReader
 *
 * @return
 *
 * @throws ParsingException
 */
public static StartElement getNextStartElement(XMLEventReader xmlEventReader) throws ParsingException {
    try {
        while (xmlEventReader.hasNext()) {
            XMLEvent xmlEvent = xmlEventReader.nextEvent();

            if (xmlEvent == null || xmlEvent.isStartElement())
                return (StartElement) xmlEvent;
        }
    } catch (XMLStreamException e) {
        throw logger.parserException(e);
    }
    return null;
}
 
Example 10
Source File: XmlPolicyModelUnmarshaller.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * See {@link PolicyModelUnmarshaller#unmarshalModel(Object) base method documentation}.
 */
public PolicySourceModel unmarshalModel(final Object storage) throws PolicyException {
    final XMLEventReader reader = createXMLEventReader(storage);
    PolicySourceModel model = null;

    loop:
    while (reader.hasNext()) {
        try {
            final XMLEvent event = reader.peek();
            switch (event.getEventType()) {
                case XMLStreamConstants.START_DOCUMENT:
                case XMLStreamConstants.COMMENT:
                    reader.nextEvent();
                    break; // skipping the comments and start document events
                case XMLStreamConstants.CHARACTERS:
                    processCharacters(ModelNode.Type.POLICY, event.asCharacters(), null);
                    // we advance the reader only if there is no exception thrown from
                    // the processCharacters(...) call. Otherwise we don't modify the stream
                    reader.nextEvent();
                    break;
                case XMLStreamConstants.START_ELEMENT:
                    if (NamespaceVersion.resolveAsToken(event.asStartElement().getName()) == XmlToken.Policy) {
                        StartElement rootElement = reader.nextEvent().asStartElement();

                        model = initializeNewModel(rootElement);
                        unmarshalNodeContent(model.getNamespaceVersion(), model.getRootNode(), rootElement.getName(), reader);

                        break loop;
                    } else {
                        throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0048_POLICY_ELEMENT_EXPECTED_FIRST()));
                    }
                default:
                    throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0048_POLICY_ELEMENT_EXPECTED_FIRST()));
            }
        } catch (XMLStreamException e) {
            throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0068_FAILED_TO_UNMARSHALL_POLICY_EXPRESSION(), e));
        }
    }
    return model;
}
 
Example 11
Source File: XmlPolicyModelUnmarshaller.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * See {@link PolicyModelUnmarshaller#unmarshalModel(Object) base method documentation}.
 */
public PolicySourceModel unmarshalModel(final Object storage) throws PolicyException {
    final XMLEventReader reader = createXMLEventReader(storage);
    PolicySourceModel model = null;

    loop:
    while (reader.hasNext()) {
        try {
            final XMLEvent event = reader.peek();
            switch (event.getEventType()) {
                case XMLStreamConstants.START_DOCUMENT:
                case XMLStreamConstants.COMMENT:
                    reader.nextEvent();
                    break; // skipping the comments and start document events
                case XMLStreamConstants.CHARACTERS:
                    processCharacters(ModelNode.Type.POLICY, event.asCharacters(), null);
                    // we advance the reader only if there is no exception thrown from
                    // the processCharacters(...) call. Otherwise we don't modify the stream
                    reader.nextEvent();
                    break;
                case XMLStreamConstants.START_ELEMENT:
                    if (NamespaceVersion.resolveAsToken(event.asStartElement().getName()) == XmlToken.Policy) {
                        StartElement rootElement = reader.nextEvent().asStartElement();

                        model = initializeNewModel(rootElement);
                        unmarshalNodeContent(model.getNamespaceVersion(), model.getRootNode(), rootElement.getName(), reader);

                        break loop;
                    } else {
                        throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0048_POLICY_ELEMENT_EXPECTED_FIRST()));
                    }
                default:
                    throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0048_POLICY_ELEMENT_EXPECTED_FIRST()));
            }
        } catch (XMLStreamException e) {
            throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0068_FAILED_TO_UNMARSHALL_POLICY_EXPRESSION(), e));
        }
    }
    return model;
}
 
Example 12
Source File: XmlPolicyModelUnmarshaller.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private String unmarshalNodeContent(final NamespaceVersion nsVersion, final ModelNode node, final QName nodeElementName, final XMLEventReader reader) throws PolicyException {
    StringBuilder valueBuffer = null;

    loop:
    while (reader.hasNext()) {
        try {
            final XMLEvent xmlParserEvent = reader.nextEvent();
            switch (xmlParserEvent.getEventType()) {
                case XMLStreamConstants.COMMENT:
                    break; // skipping the comments
                case XMLStreamConstants.CHARACTERS:
                    valueBuffer = processCharacters(node.getType(), xmlParserEvent.asCharacters(), valueBuffer);
                    break;
                case XMLStreamConstants.END_ELEMENT:
                    checkEndTagName(nodeElementName, xmlParserEvent.asEndElement());
                    break loop; // data exctraction for currently processed policy node is done
                case XMLStreamConstants.START_ELEMENT:
                    final StartElement childElement = xmlParserEvent.asStartElement();

                    ModelNode childNode = addNewChildNode(nsVersion, node, childElement);
                    String value = unmarshalNodeContent(nsVersion, childNode, childElement.getName(), reader);

                    if (childNode.isDomainSpecific()) {
                        parseAssertionData(nsVersion, value, childNode, childElement);
                    }
                    break;
                default:
                    throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0011_UNABLE_TO_UNMARSHALL_POLICY_XML_ELEM_EXPECTED()));
            }
        } catch (XMLStreamException e) {
            throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0068_FAILED_TO_UNMARSHALL_POLICY_EXPRESSION(), e));
        }
    }

    return (valueBuffer == null) ? null : valueBuffer.toString().trim();
}
 
Example 13
Source File: XmlResourceValues.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Nullable
static StartElement findNextStart(XMLEventReader eventReader) throws XMLStreamException {
  while (eventReader.hasNext()) {
    XMLEvent event = eventReader.nextEvent();
    if (event.isStartElement()) {
      return event.asStartElement();
    }
  }
  return null;
}
 
Example 14
Source File: SearchHandle.java    From java-client-api with Apache License 2.0 5 votes vote down vote up
private void collectSnippet(XMLEventReader reader, StartElement element)
  throws XMLStreamException
{
  QName matchName = new QName(SEARCH_NS, "match");

  QName snippetName = element.getName();
  events: while (reader.hasNext()) {
    XMLEvent event = reader.nextEvent();
    tempEvents.add(event);

    int eventType = event.getEventType();
    eventType: switch (eventType) {
      case XMLStreamConstants.START_ELEMENT:
        StartElement startElement = event.asStartElement();
        if (matchName.equals(startElement.getName())) {
          handleMatch(reader, startElement);
          break eventType;
        }
        break;
      case XMLStreamConstants.END_ELEMENT:
        if (snippetName.equals(event.asEndElement().getName())) {
          break events;
        }
        break eventType;
    }
  }
}
 
Example 15
Source File: XmlPolicyModelUnmarshaller.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * See {@link PolicyModelUnmarshaller#unmarshalModel(Object) base method documentation}.
 */
public PolicySourceModel unmarshalModel(final Object storage) throws PolicyException {
    final XMLEventReader reader = createXMLEventReader(storage);
    PolicySourceModel model = null;

    loop:
    while (reader.hasNext()) {
        try {
            final XMLEvent event = reader.peek();
            switch (event.getEventType()) {
                case XMLStreamConstants.START_DOCUMENT:
                case XMLStreamConstants.COMMENT:
                    reader.nextEvent();
                    break; // skipping the comments and start document events
                case XMLStreamConstants.CHARACTERS:
                    processCharacters(ModelNode.Type.POLICY, event.asCharacters(), null);
                    // we advance the reader only if there is no exception thrown from
                    // the processCharacters(...) call. Otherwise we don't modify the stream
                    reader.nextEvent();
                    break;
                case XMLStreamConstants.START_ELEMENT:
                    if (NamespaceVersion.resolveAsToken(event.asStartElement().getName()) == XmlToken.Policy) {
                        StartElement rootElement = reader.nextEvent().asStartElement();

                        model = initializeNewModel(rootElement);
                        unmarshalNodeContent(model.getNamespaceVersion(), model.getRootNode(), rootElement.getName(), reader);

                        break loop;
                    } else {
                        throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0048_POLICY_ELEMENT_EXPECTED_FIRST()));
                    }
                default:
                    throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0048_POLICY_ELEMENT_EXPECTED_FIRST()));
            }
        } catch (XMLStreamException e) {
            throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0068_FAILED_TO_UNMARSHALL_POLICY_EXPRESSION(), e));
        }
    }
    return model;
}
 
Example 16
Source File: StAXSchemaParser.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
public void parse(XMLEventReader input) throws XMLStreamException, XNIException {
    XMLEvent currentEvent = input.peek();
    if (currentEvent != null) {
        int eventType = currentEvent.getEventType();
        if (eventType != XMLStreamConstants.START_DOCUMENT &&
            eventType != XMLStreamConstants.START_ELEMENT) {
            throw new XMLStreamException();
        }
        fLocationWrapper.setLocation(currentEvent.getLocation());
        fSchemaDOMParser.startDocument(fLocationWrapper, null, fNamespaceContext, null);
        loop: while (input.hasNext()) {
            currentEvent = input.nextEvent();
            eventType = currentEvent.getEventType();
            switch (eventType) {
            case XMLStreamConstants.START_ELEMENT:
                ++fDepth;
                StartElement start = currentEvent.asStartElement();
                fillQName(fElementQName, start.getName());
                fLocationWrapper.setLocation(start.getLocation());
                fNamespaceContext.setNamespaceContext(start.getNamespaceContext());
                fillXMLAttributes(start);
                fillDeclaredPrefixes(start);
                addNamespaceDeclarations();
                fNamespaceContext.pushContext();
                fSchemaDOMParser.startElement(fElementQName, fAttributes, null);
                break;
            case XMLStreamConstants.END_ELEMENT:
                EndElement end = currentEvent.asEndElement();
                fillQName(fElementQName, end.getName());
                fillDeclaredPrefixes(end);
                fLocationWrapper.setLocation(end.getLocation());
                fSchemaDOMParser.endElement(fElementQName, null);
                fNamespaceContext.popContext();
                --fDepth;
                if (fDepth <= 0) {
                    break loop;
                }
                break;
            case XMLStreamConstants.CHARACTERS:
                sendCharactersToSchemaParser(currentEvent.asCharacters().getData(), false);
                break;
            case XMLStreamConstants.SPACE:
                sendCharactersToSchemaParser(currentEvent.asCharacters().getData(), true);
                break;
            case XMLStreamConstants.CDATA:
                fSchemaDOMParser.startCDATA(null);
                sendCharactersToSchemaParser(currentEvent.asCharacters().getData(), false);
                fSchemaDOMParser.endCDATA(null);
                break;
            case XMLStreamConstants.PROCESSING_INSTRUCTION:
                ProcessingInstruction pi = (ProcessingInstruction)currentEvent;
                fillProcessingInstruction(pi.getData());
                fSchemaDOMParser.processingInstruction(pi.getTarget(), fTempString, null);
                break;
            case XMLStreamConstants.DTD:
                /* There shouldn't be a DTD in the schema */
                break;
            case XMLStreamConstants.ENTITY_REFERENCE:
                /* Not needed for schemas */
                break;
            case XMLStreamConstants.COMMENT:
                /* No point in sending comments */
                break;
            case XMLStreamConstants.START_DOCUMENT:
                fDepth++;
                /* We automatically call startDocument before the loop */
                break;
            case XMLStreamConstants.END_DOCUMENT:
                /* We automatically call endDocument after the loop */
                break;
            }
        }
        fLocationWrapper.setLocation(null);
        fNamespaceContext.setNamespaceContext(null);
        fSchemaDOMParser.endDocument(null);
    }
}
 
Example 17
Source File: UsersConfigParser.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Parse the embedded xml in the module option representing
 * the {@code Users} object
 * @param xmlEventReader
 * @return
 * @throws XMLStreamException
 */
@SuppressWarnings("unchecked")
public Users parse(XMLEventReader xmlEventReader) throws XMLStreamException
{
   Users users = new Users();
   XMLEvent xmlEvent = null;
   while(xmlEventReader.hasNext())
   {   
      xmlEvent = xmlEventReader.peek(); 
      if(xmlEvent instanceof StartElement)
      {
         StartElement se = (StartElement) xmlEvent;
         if("module-option".equals(StaxParserUtil.getStartElementName(se)))
            return users;
      }
      if(xmlEvent instanceof EndElement)
      { 
         xmlEvent = xmlEventReader.nextEvent(); 
         continue;
      }
      
      xmlEvent = xmlEventReader.nextEvent();
      User user = new Users.User();
      
      StartElement peekedStartElement = (StartElement) xmlEvent;
      Iterator<Attribute> attribs = peekedStartElement.getAttributes();
      while(attribs.hasNext())
      {
         Attribute attrib  = attribs.next();
         if("name".equals(attrib.getName().getLocalPart()))
         {
            user.setName(attrib.getValue()); 
         }
         else if("password".equals(attrib.getName().getLocalPart()))
         {
            user.setPassword(attrib.getValue()); 
         }
         else if("encoding".equals(attrib.getName().getLocalPart()))
         {
            user.setEncoding(attrib.getValue()); 
         }
      }
      //Get the roles
      xmlEvent = xmlEventReader.peek();
      while(xmlEvent != null && xmlEvent.getEventType() == XMLStreamConstants.START_ELEMENT)
      {
         StartElement roleElement = (StartElement) xmlEvent;
         if("role".equals(roleElement.getName().getLocalPart()))
         {
            xmlEvent = xmlEventReader.nextEvent();
            Iterator<Attribute> roleAttribs = roleElement.getAttributes();

            String roleName = null;
            String groupName = "Roles";
            
            while(roleAttribs.hasNext())
            {
               Attribute roleAttribute = roleAttribs.next();
               String attributeValue = StaxParserUtil.getAttributeValue(roleAttribute);
               
               if("name".equals(roleAttribute.getName().getLocalPart()))
               {
                 roleName = attributeValue;  
               }
               else if("group".equals(roleAttribute.getName().getLocalPart()))
               {
                  groupName = attributeValue;  
               } 
            }
            if(roleName != null)
               user.addRole(roleName, groupName);
         } 
         else break;
         xmlEvent = xmlEventReader.peek();
      } 
      
      users.addUser(user);
   }
   return users; 
}
 
Example 18
Source File: BulkRecordCreator.java    From datacollector with Apache License 2.0 4 votes vote down vote up
public LinkedHashMap<String, Field> getFields(XMLEventReader reader) throws StageException, XMLStreamException {
  LinkedHashMap<String, Field> map = new LinkedHashMap<>();
  String type = null;
  String fieldValue;

  while (reader.hasNext()) {
    XMLEvent event = reader.nextEvent();
    if (event.isStartElement()) {
      if (event.asStartElement().getName().getLocalPart().equals(TYPE)) {
        // Move to content
        event = reader.nextEvent();
        type = event.asCharacters().getData().toLowerCase();
        // Consume closing tag
        reader.nextEvent();
      } else {
        String fieldName = event.asStartElement().getName().getLocalPart();
        Attribute attr = event.asStartElement().getAttributeByName(XSI_TYPE);
        if (attr != null && attr.getValue().equals(S_OBJECT)) {
          // Element is a nested record
          map.put(fieldName, Field.createListMap(getFields(reader)));
        } else {
          event = reader.nextEvent();
          fieldValue = null;
          switch (event.getEventType()) {
            case XMLEvent.START_ELEMENT:
              // Element is a nested list of records
              // Advance over <done>, <queryLocator> to record list
              while (!(event.isStartElement() && event.asStartElement().getName().getLocalPart().equals(RECORDS))) {
                event = reader.nextEvent();
              }

              // Read record list
              List<Field> recordList = new ArrayList<>();
              while (event.isStartElement() && event.asStartElement().getName().getLocalPart().equals(RECORDS)) {
                recordList.add(Field.createListMap(getFields(reader)));
                event = reader.nextEvent();
              }
              map.put(fieldName, Field.create(recordList));
              break;
            case XMLEvent.CHARACTERS:
              // Element is a field value
              fieldValue = event.asCharacters().getData();
              // Consume closing tag
              reader.nextEvent();
              // Intentional fall through to next case!
            case XMLEvent.END_ELEMENT:
              // Create the SDC field
              if (type == null) {
                throw new StageException(Errors.FORCE_38);
              }
              // Is this a relationship to another object?
              com.sforce.soap.partner.Field sfdcField = metadataCache.get(type).getFieldFromRelationship(fieldName);
              if (sfdcField != null) {
                // See if we already added fields from the related record
                if (map.get(fieldName) != null) {
                  // We already created this node - don't overwrite it!
                  sfdcField = null;
                }
              } else {
                sfdcField = getFieldMetadata(type, fieldName);
              }

              if (sfdcField != null) {
                Field field = createField(fieldValue, sfdcField);
                if (conf.createSalesforceNsHeaders) {
                  setHeadersOnField(field, getFieldMetadata(type, fieldName));
                }

                map.put(fieldName, field);
              }
              break;
            default:
              throw new StageException(Errors.FORCE_41, event.getEventType());
          }
        }
      }
    } else if (event.isEndElement()) {
      // Done with record
      return map;
    }
  }

  throw new StageException(Errors.FORCE_39);
}
 
Example 19
Source File: AndroidManifestProcessor.java    From bazel with Apache License 2.0 4 votes vote down vote up
/**
 * Overwrite the package attribute of {@code <manifest>} in an AndroidManifest.xml file.
 *
 * @param manifest The input manifest.
 * @param customPackage The package to write to the manifest.
 * @param output The output manifest to generate.
 * @return The output manifest if generated or the input manifest if no overwriting is required.
 */
/* TODO(apell): switch from custom xml parsing to Gradle merger with NO_PLACEHOLDER_REPLACEMENT
 * set when android common is updated to version 2.5.0.
 */
public Path writeManifestPackage(Path manifest, String customPackage, Path output) {
  if (Strings.isNullOrEmpty(customPackage)) {
    return manifest;
  }
  try {
    Files.createDirectories(output.getParent());
    XMLEventReader reader =
        XMLInputFactory.newInstance()
            .createXMLEventReader(Files.newInputStream(manifest), UTF_8.name());
    XMLEventWriter writer =
        XMLOutputFactory.newInstance()
            .createXMLEventWriter(Files.newOutputStream(output), UTF_8.name());
    XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    while (reader.hasNext()) {
      XMLEvent event = reader.nextEvent();
      if (event.isStartElement()
          && event.asStartElement().getName().toString().equalsIgnoreCase("manifest")) {
        StartElement element = event.asStartElement();
        @SuppressWarnings("unchecked")
        Iterator<Attribute> attributes = element.getAttributes();
        ImmutableList.Builder<Attribute> newAttributes = ImmutableList.builder();
        while (attributes.hasNext()) {
          Attribute attr = attributes.next();
          if (attr.getName().toString().equalsIgnoreCase("package")) {
            newAttributes.add(eventFactory.createAttribute("package", customPackage));
          } else {
            newAttributes.add(attr);
          }
        }
        writer.add(
            eventFactory.createStartElement(
                element.getName(), newAttributes.build().iterator(), element.getNamespaces()));
      } else {
        writer.add(event);
      }
    }
    writer.flush();
  } catch (XMLStreamException | FactoryConfigurationError | IOException e) {
    throw new ManifestProcessingException(e);
  }

  return output;
}
 
Example 20
Source File: CheckstyleReportsParser.java    From contribution with GNU Lesser General Public License v2.1 3 votes vote down vote up
/**
 * Parses input XML files: creates 2 parsers
 * which process their XML files in rotation and try
 * to write their results to the ParsedContent class
 * inner map, where they are eagerly compared.
 *
 * @param baseXml
 *        path to base XML file.
 * @param patchXml
 *        path to patch XML file.
 * @param portionSize
 *        single portion of XML file processed at once by any parser.
 * @return parsed content.
 * @throws FileNotFoundException
 *         if files not found.
 * @throws XMLStreamException
 *         on internal parser error.
 */
public static DiffReport parse(Path baseXml, Path patchXml, int portionSize)
                throws FileNotFoundException, XMLStreamException {
    final DiffReport content = new DiffReport();
    final XMLEventReader baseReader = StaxUtils.createReader(baseXml);
    final XMLEventReader patchReader = StaxUtils.createReader(patchXml);
    while (baseReader.hasNext() || patchReader.hasNext()) {
        parseXmlPortion(content, baseReader, portionSize, BASE_REPORT_INDEX);
        parseXmlPortion(content, patchReader, portionSize, PATCH_REPORT_INDEX);
    }
    content.getDiffStatistics();
    return content;
}