/**
   * Method that not only gets currently available text from the reader, but also checks that its
   * consistenly accessible using different (basic) StAX methods.
   */
  protected static String getAndVerifyText(XMLStreamReader sr) throws XMLStreamException {
    /* 05-Apr-2006, TSa: Although getText() is available for DTD
     *   and ENTITY_REFERENCE, getTextXxx() are not. Thus, can not
     *   do more checks for those types.
     */
    int type = sr.getEventType();
    if (type == ENTITY_REFERENCE || type == DTD) {
      return sr.getText();
    }

    int expLen = sr.getTextLength();
    /* Hmmh. It's only ok to return empty text for DTD event... well,
     * maybe also for CDATA, since empty CDATA blocks are legal?
     */
    /* !!! 01-Sep-2004, TSa:
     *  note: theoretically, in coalescing mode, it could be possible
     *  to have empty CDATA section(s) get converted to CHARACTERS,
     *  which would be empty... may need to enhance this to check that
     *  mode is not coalescing? Or something
     */
    if (type == CHARACTERS) {
      assertTrue("Stream reader should never return empty Strings.", (expLen > 0));
    }
    String text = sr.getText();
    assertNotNull("getText() should never return null.", text);
    assertEquals(
        "Expected text length of " + expLen + ", got " + text.length(), expLen, text.length());
    char[] textChars = sr.getTextCharacters();
    int start = sr.getTextStart();
    String text2 = new String(textChars, start, expLen);
    assertEquals(text, text2);
    return text;
  }
  @SuppressWarnings("unchecked")
  protected ExtensionElement parseExtensionElement(XMLStreamReader xtr) throws Exception {
    ExtensionElement extensionElement = new ExtensionElement();
    extensionElement.setName(xtr.getLocalName());
    if (StringUtils.isNotEmpty(xtr.getNamespaceURI())) {
      extensionElement.setNamespace(xtr.getNamespaceURI());
    }
    if (StringUtils.isNotEmpty(xtr.getPrefix())) {
      extensionElement.setNamespacePrefix(xtr.getPrefix());
    }

    BpmnXMLUtil.addCustomAttributes(xtr, extensionElement, defaultElementAttributes);

    boolean readyWithExtensionElement = false;
    while (readyWithExtensionElement == false && xtr.hasNext()) {
      xtr.next();
      if (xtr.isCharacters()) {
        if (StringUtils.isNotEmpty(xtr.getText().trim())) {
          extensionElement.setElementText(xtr.getText().trim());
        }
      } else if (xtr.isStartElement()) {
        ExtensionElement childExtensionElement = parseExtensionElement(xtr);
        extensionElement.addChildElement(childExtensionElement);
      } else if (xtr.isEndElement()
          && extensionElement.getName().equalsIgnoreCase(xtr.getLocalName())) {
        readyWithExtensionElement = true;
      }
    }
    return extensionElement;
  }
Beispiel #3
0
  private static void readCorner(ModalityInfoData data, CornerDisplay corner, XMLStreamReader xmler)
      throws XMLStreamException {

    TagView[] disElements = data.getCornerInfo(corner).getInfos();

    boolean state = true;
    int index = -1;
    String format = null;
    while (xmler.hasNext() && state) {
      switch (xmler.next()) {
        case XMLStreamConstants.CHARACTERS:
          if (index > 0 && index <= 7) {
            disElements[index - 1] = getTag(xmler.getText(), format);
            index = -1; // Reset current index and format
            format = null;
          }
          break;
        case XMLStreamConstants.START_ELEMENT:
          if ("p".equals(xmler.getName().getLocalPart())
              && xmler.getAttributeCount() >= 1) { // $NON-NLS-1$
            index = TagUtil.getIntegerTagAttribute(xmler, "index", -1); // $NON-NLS-1$
            format = xmler.getAttributeValue(null, "format"); // $NON-NLS-1$
          }
          break;
        case XMLStreamConstants.END_ELEMENT:
          if ("corner".equals(xmler.getName().getLocalPart())) { // $NON-NLS-1$
            state = false;
          }
          break;
        default:
          break;
      }
    }
  }
Beispiel #4
0
  /** Extract the metadata of a file system hash */
  public FileSystemHashMetadata loadFileSystemHashMetadata() throws XMLStreamException {
    String endTag = "metadata";
    HashMap<String, String> fshMetadata = new HashMap<>();
    int type;
    String currentElement;
    boolean done = false;

    while (!done && reader.hasNext()) {
      type = reader.next();
      if (type == XMLStreamReader.START_ELEMENT) {
        currentElement = reader.getLocalName();
        type = reader.next();
        if (type == XMLStreamReader.CHARACTERS) {
          fshMetadata.put(currentElement, reader.getText());
          // Look for the end of the current element and throw an exception if it cannot be found
          do {
            type = reader.next();
          } while (type != XMLStreamReader.END_ELEMENT);
          verifyClosing(currentElement);
        } else if (type == XMLStreamReader.END_ELEMENT) {
          verifyClosing(currentElement);
        }
      } else if (type == XMLStreamReader.END_ELEMENT) {
        done = reader.getLocalName().compareTo(endTag) == 0;
      }
    }
    return new FileSystemHashMetadata(fshMetadata);
  }
  public Stack<Map<String, String>> parseXml(File file) throws Exception {

    String name = "", value;

    Stack<Map<String, String>> rows = new Stack<>();

    XMLStreamReader xr =
        XMLInputFactory.newInstance().createXMLStreamReader(new FileInputStream(file));

    while (xr.hasNext()) {
      int e = xr.next();
      switch (e) {
        case XMLStreamReader.START_ELEMENT:
          {
            name = xr.getLocalName();
            break;
          }
        case XMLStreamReader.CHARACTERS:
          {
            Map<String, String> map = newHashMap();
            value = xr.getText();
            map.put(name, value);
            rows.push(map);
            break;
          }
      }
    }
    return rows;
  }
Beispiel #6
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");
 }
 public String getText() {
   if (state == STATE_START_DOCUMENT || state == STATE_END_DOCUMENT) {
     throw new IllegalStateException();
   } else {
     return parent.getText();
   }
 }
  // <security-role>
  // <role-name>admin</role-name>
  // </security-role>
  private String loadSecurityRole(XMLStreamReader xmlReader)
      throws WebXmlFormatException, XMLStreamException {
    String tagContent = null;
    String tagName;

    String roleName = null;

    while (xmlReader.hasNext()) {
      switch (xmlReader.next()) {
        case XMLStreamConstants.CHARACTERS:
          tagContent = xmlReader.getText().trim();
          break;

        case XMLStreamConstants.END_ELEMENT:
          tagName = xmlReader.getLocalName();

          if (tagName.equals("role-name")) {
            roleName = tagContent;
            continue;
          }

          if (tagName.equals("security-role")) {
            if (roleName == null) throwExceptionNotSpecifiedParameter("Security-role", "role-name");
            else return roleName;
          }
          break;

        default:
          break;
      }
    }

    throwMalformedWebXml("security-role");
    return null; // Never happens. Method above always throws exception
  }
Beispiel #9
0
 /**
  * This method will check whether the text can be optimizable using IS_BINARY flag. If that is set
  * then we try to get the data handler.
  *
  * @param omContainer
  * @param textType
  * @return omNode
  */
 private OMNode createOMText(OMContainer omContainer, int textType) {
   if (dataHandlerReader != null && dataHandlerReader.isBinary()) {
     Object dataHandlerObject;
     if (dataHandlerReader.isDeferred()) {
       dataHandlerObject = dataHandlerReader.getDataHandlerProvider();
     } else {
       try {
         dataHandlerObject = dataHandlerReader.getDataHandler();
       } catch (XMLStreamException ex) {
         throw new OMException(ex);
       }
     }
     OMText text = omfactory.createOMText(dataHandlerObject, dataHandlerReader.isOptimized());
     String contentID = dataHandlerReader.getContentID();
     if (contentID != null) {
       text.setContentID(contentID);
     }
     omContainer.addChild(text);
     return text;
   } else {
     // Some parsers (like Woodstox) parse text nodes lazily and may throw a
     // RuntimeException in getText()
     String text;
     try {
       text = parser.getText();
     } catch (RuntimeException ex) {
       parserException = ex;
       throw ex;
     }
     return omfactory.createOMText(omContainer, text, textType);
   }
 }
Beispiel #10
0
  public void testEncodingXmlStreamReader() throws Exception {
    TEST_XML_WITH_XML_HEADER_ISO_8859_1_AS_BYTE_ARRAY_STREAM.reset();

    XMLStreamReader reader = null;
    XMLStreamWriter writer = null;
    ByteArrayOutputStream output = null;
    try {
      // enter text encoded with Latin1
      reader =
          context
              .getTypeConverter()
              .mandatoryConvertTo(
                  XMLStreamReader.class, TEST_XML_WITH_XML_HEADER_ISO_8859_1_AS_BYTE_ARRAY_STREAM);

      output = new ByteArrayOutputStream();
      // ensure UTF-8 encoding
      Exchange exchange = new DefaultExchange(context);
      exchange.setProperty(Exchange.CHARSET_NAME, UTF_8.name());
      writer =
          context.getTypeConverter().mandatoryConvertTo(XMLStreamWriter.class, exchange, output);
      // copy to writer
      while (reader.hasNext()) {
        reader.next();
        switch (reader.getEventType()) {
          case XMLEvent.START_DOCUMENT:
            writer.writeStartDocument();
            break;
          case XMLEvent.END_DOCUMENT:
            writer.writeEndDocument();
            break;
          case XMLEvent.START_ELEMENT:
            writer.writeStartElement(reader.getName().getLocalPart());
            break;
          case XMLEvent.CHARACTERS:
            writer.writeCharacters(reader.getText());
            break;
          case XMLEvent.END_ELEMENT:
            writer.writeEndElement();
            break;
          default:
            break;
        }
      }
    } finally {
      if (reader != null) {
        reader.close();
      }
      if (writer != null) {
        writer.close();
      }
    }
    assertNotNull(output);

    String result = new String(output.toByteArray(), UTF_8.name());

    assertEquals(TEST_XML, result);
  }
  private ImageSeries retrieveImagesSeriesForGene(String geneSymbol, ImageSeriesPlane desiredPlane)
      throws IOException, XMLStreamException {
    ImageSeries imageSeries = null;
    URL u = new URL(ABAUtil.assembleGeneURI(geneSymbol));

    LOG.debug("Gene info URI: {}", u.toString());

    InputStream in = u.openStream();
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLStreamReader parser = factory.createXMLStreamReader(in);

    boolean inISid = false;
    boolean inPlane = false;
    String isId = null;
    String plane = null;
    for (int event = parser.next();
        event != XMLStreamConstants.END_DOCUMENT;
        event = parser.next()) {
      if (event == XMLStreamConstants.START_ELEMENT) {
        if (parser.getLocalName().equals("imageseriesid")) {
          inISid = true;
        } else if (parser.getLocalName().equals("plane")) {
          inPlane = true;
        }
      } else if (event == XMLStreamConstants.CHARACTERS) {
        if (inISid) {
          isId = parser.getText();
          inISid = false;
        } else if (inPlane) {
          plane = parser.getText();
          if (plane.equals(desiredPlane.toString())) {
            imageSeries = new ImageSeries(isId, desiredPlane);
          }
          inPlane = false;
        }
      }
    }
    try {
      parser.close();
    } catch (XMLStreamException e) {
      LOG.warn(e.getMessage(), e); // log but go on
    }
    return imageSeries;
  }
Beispiel #12
0
 /**
  * True if all the elements in the current node are blanks
  *
  * @return true if all are blanks
  * @throws javax.xml.stream.XMLStreamException
  */
 private boolean allBlanks() throws XMLStreamException {
   boolean res = true;
   if (!reader.hasText()) {
     return true;
   }
   String text = reader.getText();
   for (int i = 0, limit = text.length(); i < limit; i++) {
     res = res && Character.isWhitespace(text.charAt(i));
   }
   return res;
 }
Beispiel #13
0
    @Override
    protected void map(LongWritable key, Text value, Mapper.Context context)
        throws IOException, InterruptedException {
      String document = value.toString();
      System.out.println("'" + document + "'");
      try {
        XMLStreamReader reader =
            XMLInputFactory.newInstance()
                .createXMLStreamReader(new ByteArrayInputStream(document.getBytes()));
        String propertyName = "";
        String propertyValue = "";
        String currentElement = "";
        while (reader.hasNext()) {
          int code = reader.next();
          switch (code) {
            case XMLStreamConstants.START_ELEMENT: // START_ELEMENT:
              currentElement = reader.getLocalName();
              break;
            case XMLStreamConstants.CHARACTERS: // CHARACTERS:
              if (currentElement.equalsIgnoreCase("uid")) {
                propertyName += reader.getText().trim();
                System.out.println(propertyName);
              } else if (currentElement.equalsIgnoreCase("location")) {
                propertyValue += reader.getText().trim();
                System.out.println(propertyValue);

              } else if (currentElement.equalsIgnoreCase("age")) {
                propertyValue += ("," + reader.getText().trim());
                System.out.println(propertyValue);
              }
              break;
          }
        }
        reader.close();
        context.write(new Text(propertyName.trim()), new Text(propertyValue.trim()));

      } catch (Exception e) {
        throw new IOException(e);
      }
    }
Beispiel #14
0
 public HashedFile loadHashedFile() throws XMLStreamException {
   String endTag = "file";
   Path path = Paths.get("");
   String md5 = "";
   int type;
   String currentElement;
   boolean done = false;
   while (!done && reader.hasNext()) {
     type = reader.next();
     if (type == XMLStreamReader.END_ELEMENT) {
       done = reader.getLocalName().compareTo(endTag) == 0;
     } else if (type == XMLStreamReader.START_ELEMENT) {
       currentElement = reader.getLocalName();
       do {
         type = reader.next();
       } while (type != XMLStreamReader.CHARACTERS && type != XMLStreamReader.END_ELEMENT);
       if (type == XMLStreamReader.CHARACTERS) {
         switch (currentElement) {
           case "md5":
             md5 = reader.getText();
             break;
           case "filePath":
             path = Paths.get(reader.getText());
             break;
         }
         // Look for the end of the current element and throw an exception if it cannot be found
         do {
           type = reader.next();
         } while (type != XMLStreamReader.END_ELEMENT);
         verifyClosing(currentElement);
       } else {
         verifyClosing(currentElement);
       }
     }
   }
   HashedFile result = new HashedFile(path);
   result.setMd5(md5);
   return result;
 }
Beispiel #15
0
 /** Note: calling this method will move stream to the next non-textual event. */
 protected String collectAllText(XMLStreamReader sr) throws XMLStreamException {
   StringBuilder sb = new StringBuilder(100);
   while (true) {
     int type = sr.getEventType();
     if (type == CHARACTERS || type == SPACE || type == CDATA) {
       sb.append(sr.getText());
       sr.next();
     } else {
       break;
     }
   }
   return sb.toString();
 }
Beispiel #16
0
 @SuppressWarnings("incomplete-switch")
 public List<Weapon> parseByStAX() throws FileNotFoundException, XMLStreamException {
   List<Weapon> listWeapon = new ArrayList<Weapon>();
   Weapon weapon = null;
   WeaponTagName elementName = null;
   XMLInputFactory inputFactory = XMLInputFactory.newInstance();
   InputStream input = new FileInputStream("resources/weaponMarket.xml");
   XMLStreamReader reader = inputFactory.createXMLStreamReader(input);
   while (reader.hasNext()) {
     int type = reader.next();
     switch (type) {
       case XMLStreamConstants.START_ELEMENT:
         elementName =
             WeaponTagName.valueOf(reader.getLocalName().toUpperCase().replace("-", "_"));
         switch (elementName) {
           case WEAPON:
             weapon = new Weapon();
             weapon.setId(reader.getAttributeValue(null, "id"));
             break;
         }
         break;
       case XMLStreamConstants.CHARACTERS:
         String text = reader.getText().trim();
         if (text.isEmpty()) {
           break;
         }
         switch (elementName) {
           case WEAPON_TYPE:
             weapon.setWeaponType(text);
             break;
           case WEAPON_NAME:
             weapon.setWeaponName(text);
             break;
           case COST:
             weapon.setCost(text);
             break;
         }
         break;
       case XMLStreamConstants.END_ELEMENT:
         elementName =
             WeaponTagName.valueOf(reader.getLocalName().toUpperCase().replace("-", "_"));
         switch (elementName) {
           case WEAPON:
             listWeapon.add(weapon);
         }
     }
   }
   return listWeapon;
 }
 private void readRecord(XMLStreamReader reader) throws XMLStreamException {
   String currentKey = null;
   if (isStartElement("record")) {
     while (reader.hasNext() && !isEndElement("record")) {
       reader.next();
       if (reader.isStartElement()) {
         if (reader.getLocalName().equals("contributor_list")) {
           contributorList = readBasicRecords(reader, "person", "contributor_list");
           currentKey = null;
         } else if (reader.getLocalName().equals("tracklist")) {
           trackList = readBasicRecords(reader, "track_details", "tracklist");
           currentKey = null;
         } else {
           currentKey = reader.getLocalName();
         }
       } else if (reader.isCharacters()) {
         if (currentKey != null && !reader.getText().trim().equals("")) {
           atts.put(currentKey, reader.getText());
           currentKey = null;
         }
       }
     }
   } else throw new IllegalStateException("Reader is not at the start of a record");
 }
  // <login-config>
  // <auth-method>FORM</auth-method>
  // <form-login-config>
  // <form-login-page>/login</form-login-page>
  // <form-error-page>/loginError</form-error-page>
  // </form-login-config>
  // </login-config>
  private LoginConfig loadLoginConfig(XMLStreamReader xmlReader)
      throws WebXmlFormatException, XMLStreamException {
    String tagContent = null;
    String tagName;

    LoginConfig loginConfig = new LoginConfig();

    while (xmlReader.hasNext()) {
      switch (xmlReader.next()) {
        case XMLStreamConstants.CHARACTERS:
          tagContent = xmlReader.getText().trim();
          break;

        case XMLStreamConstants.END_ELEMENT:
          tagName = xmlReader.getLocalName();

          if (tagName.equals("auth-method")) {
            loginConfig.authMethod = tagContent;
            continue;
          }

          if (tagName.equals("form-login-page")) {
            loginConfig.formLoginPage = tagContent;
            continue;
          }

          if (tagName.equals("form-error-page")) {
            loginConfig.formErrorPage = tagContent;
            continue;
          }

          if (tagName.equals("form-login-config")) {
            if (loginConfig.formLoginPage == null || loginConfig.formErrorPage == null)
              throwMalformedWebXml("Login-config");
          }

          if (tagName.equals("login-config")) {
            return loginConfig;
          }

        default:
          break;
      }
    }

    throwMalformedWebXml("Login-config");
    return null; // Never happens. Method above always throws exception
  }
  // <env-entry>
  // <env-entry-name>HUDSON_HOME</env-entry-name>
  // <env-entry-type>java.lang.String</env-entry-type>
  // <env-entry-value></env-entry-value>
  // </env-entry>
  private EnvEntry loadEnvEntry(XMLStreamReader xmlReader)
      throws WebXmlFormatException, XMLStreamException {
    String tagContent = null;
    String tagName;

    EnvEntry envEntry = new EnvEntry();

    while (xmlReader.hasNext()) {
      switch (xmlReader.next()) {
        case XMLStreamConstants.CHARACTERS:
          tagContent = xmlReader.getText().trim();
          break;

        case XMLStreamConstants.END_ELEMENT:
          tagName = xmlReader.getLocalName();

          if (tagName.equals("env-entry-name")) {
            envEntry.entryName = tagContent;
            continue;
          }

          if (tagName.equals("env-entry-type")) {
            envEntry.entryType = tagContent;
            continue;
          }

          if (tagName.equals("env-entry-value")) {
            envEntry.entryValue = tagContent;
            continue;
          }

          if (tagName.equals("env-entry")) {
            if (envEntry.entryName == null
                || envEntry.entryValue == null
                || envEntry.entryType == null) throwMalformedWebXml("Env-entry");
            else return envEntry;
          }

        default:
          break;
      }
    }

    throwMalformedWebXml("Env-entry");
    return null; // Never happens. Method above always throws exception
  }
Beispiel #20
0
 public static Map<String, String> parse(
     XMLStreamReader streamReader, EndCondition endCondition, String... tags)
     throws XMLStreamException {
   Map<String, String> mapping = new HashMap<String, String>();
   while (streamReader.hasNext() && !endCondition.mustExit(streamReader)) {
     streamReader.next();
     if (XMLStreamReader.START_ELEMENT == streamReader.getEventType()) {
       String localPart = streamReader.getName().getLocalPart();
       for (String tag : tags) {
         if (tag.equals(localPart)) {
           streamReader.next();
           if (XMLStreamReader.CHARACTERS == streamReader.getEventType()) {
             mapping.put(tag, streamReader.getText());
           }
         }
       }
     }
   }
   return mapping;
 }
  // <servlet-mapping>
  // <servlet-name>Stapler</servlet-name>
  // <url-pattern>/*</url-pattern>
  // </servlet-mapping>
  private ServletMapping loadServletMapping(XMLStreamReader xmlReader)
      throws WebXmlFormatException, XMLStreamException {
    String tagContent = null;
    String tagName;

    ServletMapping servletMapping = new ServletMapping();

    while (xmlReader.hasNext()) {
      switch (xmlReader.next()) {
        case XMLStreamConstants.CHARACTERS:
          tagContent = xmlReader.getText().trim();
          break;

        case XMLStreamConstants.END_ELEMENT:
          tagName = xmlReader.getLocalName();

          if (tagName.equals("servlet-name")) {
            servletMapping.servletName = tagContent;
            continue;
          }

          if (tagName.equals("url-pattern")) {
            servletMapping.urlPattern = tagContent;
            continue;
          }

          if (tagName.equals("servlet-mapping")) {
            if (servletMapping.servletName == null || servletMapping.urlPattern == null)
              throwExceptionNotSpecifiedParameter("Servlet-mapping", "servlet-name", "url-pattern");
            else return servletMapping;
          }
          break;

        default:
          break;
      }
    }

    throwMalformedWebXml("servlet-mapping");
    return null; // Never happens. Method above always throws exception
  }
  // <filter>
  // <filter-name>encoding-filter</filter-name>
  // <filter-class>hudson.util.CharacterEncodingFilter</filter-class>
  // </filter>
  private Filter loadFilter(XMLStreamReader xmlReader)
      throws WebXmlFormatException, XMLStreamException {
    String tagContent = null;
    String tagName;

    Filter filter = new Filter();

    while (xmlReader.hasNext()) {
      switch (xmlReader.next()) {
        case XMLStreamConstants.CHARACTERS:
          tagContent = xmlReader.getText().trim();
          break;

        case XMLStreamConstants.END_ELEMENT:
          tagName = xmlReader.getLocalName();

          if (tagName.equals("filter-name")) {
            filter.filterName = tagContent;
            continue;
          }

          if (tagName.equals("filter-class")) {
            filter.filterClass = tagContent;
            continue;
          }

          if (tagName.equals("filter")) {
            if (filter.filterName == null || filter.filterClass == null)
              throwExceptionNotSpecifiedParameter("Filter", "filter-name", "filter-class");
            else return filter;
          }
          break;

        default:
          break;
      }
    }

    throwMalformedWebXml("filter");
    return null; // Never happens. Method above always throws exception
  }
  // <error-page>
  // <exception-type>java.lang.Throwable</exception-type>
  // <location>/oops</location>
  // </error-page>
  private ErrorPage loadErrorPage(XMLStreamReader xmlReader)
      throws WebXmlFormatException, XMLStreamException {
    String tagContent = null;
    String tagName;

    ErrorPage errorPage = new ErrorPage();

    while (xmlReader.hasNext()) {
      switch (xmlReader.next()) {
        case XMLStreamConstants.CHARACTERS:
          tagContent = xmlReader.getText().trim();
          break;

        case XMLStreamConstants.END_ELEMENT:
          tagName = xmlReader.getLocalName();

          if (tagName.equals("exception-type")) {
            errorPage.exceptionType = tagContent;
            continue;
          }

          if (tagName.equals("location")) {
            errorPage.location = tagContent;
            continue;
          }

          if (tagName.equals("error-page")) {
            if (errorPage.exceptionType == null || errorPage.location == null)
              throwMalformedWebXml("Error-page");
            else return errorPage;
          }

        default:
          break;
      }
    }

    throwMalformedWebXml("Error-page");
    return null; // Never happens. Method above always throws exception
  }
  // <mime-mapping>
  // <extension>webm</extension>
  // <mime-type>video/webm</mime-type>
  // </mime-mapping>
  private MimeMapping loadMimeMapping(XMLStreamReader xmlReader)
      throws WebXmlFormatException, XMLStreamException {
    String tagContent = null;
    String tagName;

    MimeMapping mimeMapping = new MimeMapping();

    while (xmlReader.hasNext()) {
      switch (xmlReader.next()) {
        case XMLStreamConstants.CHARACTERS:
          tagContent = xmlReader.getText().trim();
          break;

        case XMLStreamConstants.END_ELEMENT:
          tagName = xmlReader.getLocalName();

          if (tagName.equals("extension")) {
            mimeMapping.extension = tagContent;
            continue;
          }

          if (tagName.equals("mime-type")) {
            mimeMapping.mimeType = tagContent;
            continue;
          }

          if (tagName.equals("mime-mapping")) {
            if (mimeMapping.extension == null || mimeMapping.mimeType == null)
              throwMalformedWebXml("Mime-mapping");
            else return mimeMapping;
          }

        default:
          break;
      }
    }

    throwMalformedWebXml("Mime-mapping");
    return null; // Never happens. Method above always throws exception
  }
  public Map<String, String> parse(File file) throws Exception {

    Map<String, String> map = new HashMap<>();
    XMLStreamReader xr =
        XMLInputFactory.newInstance().createXMLStreamReader(new FileInputStream(file));

    while (xr.hasNext()) {
      int e = xr.next();
      if (e == XMLStreamReader.START_ELEMENT) {
        String name = xr.getLocalName();
        xr.next();
        String value = null;
        try {
          value = xr.getText();
        } catch (IllegalStateException ex) {
          logger.warn(ex);
        }
        map.put(name, value);
      }
    }
    return map;
  }
Beispiel #26
0
    private Element(XMLStreamReader stream, Element parent) throws XMLStreamException {
      // We assume that the stream points to the start of the modelled element
      if (stream.getEventType() != XMLStreamConstants.START_ELEMENT) {
        throw new AssertionError();
      }

      //
      QName name = stream.getName();
      Location location = stream.getLocation();

      //
      Map<String, String> attributes = Collections.emptyMap();
      Map<QName, String> qualifiedAttributes = Collections.emptyMap();
      int attributeCount = stream.getAttributeCount();
      for (int i = 0; i < attributeCount; i++) {
        String attributeValue = stream.getAttributeValue(i);
        QName attributeName = stream.getAttributeName(i);
        if (XMLConstants.NULL_NS_URI.equals(attributeName.getNamespaceURI())) {
          if (attributes.isEmpty()) {
            attributes = new HashMap<String, String>();
          }
          attributes.put(attributeName.getLocalPart(), attributeValue);
        } else {
          if (qualifiedAttributes.isEmpty()) {
            qualifiedAttributes = new HashMap<QName, String>();
          }
          qualifiedAttributes.put(attributeName, attributeValue);
        }
      }

      //
      Map<String, String> namespaces;
      int namespaceCount = stream.getNamespaceCount();
      if (namespaceCount > 0) {
        namespaces = new HashMap<String, String>();
        for (int i = 0; i < namespaceCount; i++) {
          String namespacePrefix = stream.getNamespacePrefix(i);
          if (namespacePrefix == null) {
            namespacePrefix = "";
          }
          String namespaceURI = stream.getNamespaceURI(i);
          namespaces.put(namespacePrefix, namespaceURI);
        }
      } else {
        namespaces = Collections.emptyMap();
      }

      // When we leave we assume that we are positionned on the next element start or the document
      // end
      StringBuilder sb = null;
      String chunk = null;
      Object content = null;
      while (true) {
        stream.next();
        int type = stream.getEventType();
        if (type == XMLStreamConstants.END_DOCUMENT || type == XMLStreamConstants.START_ELEMENT) {
          break;
        } else if (type == XMLStreamConstants.CHARACTERS) {
          if (chunk == null) {
            chunk = stream.getText();
          } else {
            if (sb == null) {
              sb = new StringBuilder(chunk);
            }
            sb.append(stream.getText());
          }
        } else if (type == XMLStreamConstants.END_ELEMENT) {
          if (sb != null) {
            content = sb;
          } else {
            content = chunk;
          }
          break;
        }
      }

      //
      int depth = 1 + (parent != null ? parent.getDepth() : 0);

      //
      this.parent = parent;
      this.name = name;
      this.depth = depth;
      this.content = content;
      this.attributes = attributes;
      this.qualifiedAttributes = qualifiedAttributes;
      this.namespaces = namespaces;
      this.location = location;
    }
 public String getText() {
   return streamReader.getText();
 }
Beispiel #28
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;
      }
    }
  }
Beispiel #29
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;
      }
    }
  }
  private void retrieveImageForPosition(String imageSeriesId, String position, Image image)
      throws IOException, XMLStreamException {
    URL u = new URL(assembleImageSeriesURI(imageSeriesId));

    LOG.debug("Meta info URI: {}", u.toString());

    InputStream in = u.openStream();
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLStreamReader parser = factory.createXMLStreamReader(in);

    boolean inImDisplayName = false;
    boolean inImId = false;
    boolean inPosition = false;
    boolean inThumbnailurl = false;
    boolean inDownloadImagePath = false;
    boolean positionMatch = false;
    for (int event = parser.next();
        event != XMLStreamConstants.END_DOCUMENT;
        event = parser.next()) {
      if (event == XMLStreamConstants.START_ELEMENT) {
        if (parser.getLocalName().equals("imagedisplayname")) {
          inImDisplayName = true;
        } else if (parser.getLocalName().equals("imageid")) {
          inImId = true;
        } else if (parser.getLocalName().equals("position")) {
          inPosition = true;
        } else if (parser.getLocalName().equals("thumbnailurl")) {
          inThumbnailurl = true;
        } else if (parser.getLocalName().equals("downloadImagePath")) {
          inDownloadImagePath = true;
        }
      } else if (event == XMLStreamConstants.CHARACTERS) {

        // element sequence is significant! imagedisplayname and
        // imageid precede position which is match value
        if (inImDisplayName) {
          image.imagedisplayname = parser.getText();
          inImDisplayName = false;
        } else if (inImId) {
          image.imageId = parser.getText();
          inImId = false;
        } else if (inPosition) {
          if (parser.getText().equals(position)) {
            positionMatch = true;
          }
          inPosition = false;
        } else if (inThumbnailurl) {
          if (positionMatch) {
            image.thumbnailurl = parser.getText();
          }
          inThumbnailurl = false;
        } else if (inDownloadImagePath) {
          if (positionMatch) {
            image.downloadImagePath = parser.getText();
            break;
          }
          inDownloadImagePath = false;
        }
      }
    }
    try {
      parser.close();
    } catch (XMLStreamException e) {
      LOG.warn(e.getMessage(), e); // log but go on
    }

    LOG.debug(
        "imageId: {}\n  thumbnailurl: {}\n  downloadImagePath: {}",
        new String[] {image.imageId, image.thumbnailurl, image.downloadImagePath});
  }