Пример #1
0
  /** parse the text into a named list... */
  private NamedList<Object> processResponse(XMLStreamReader parser) {
    try {
      NamedList<Object> response = null;
      for (int event = parser.next();
          event != XMLStreamConstants.END_DOCUMENT;
          event = parser.next()) {
        switch (event) {
          case XMLStreamConstants.START_ELEMENT:
            if (response != null) {
              throw new Exception("already read the response!");
            }

            // only top-level element is "response
            String name = parser.getLocalName();
            if (name.equals("response") || name.equals("result")) {
              response = readNamedList(parser);
            } else if (name.equals("solr")) {
              return new SimpleOrderedMap<Object>();
            } else {
              throw new Exception(
                  "really needs to be response or result.  " + "not:" + parser.getLocalName());
            }
            break;
        }
      }
      return response;
    } catch (Exception ex) {
      throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "parsing error", ex);
    } finally {
      try {
        parser.close();
      } catch (Exception ex) {
      }
    }
  }
Пример #2
0
  /**
   * Compile dictionary to letter transducers
   *
   * @param file the address of the XML dictionnary to be read
   * @param dir the direction of the compilation, 'lr' (leftSide-to-right) or 'rl'
   *     (right-to-leftSide)
   */
  public void parse(String file, String dir) {
    try {
      direction = dir;
      XMLInputFactory factory = XMLInputFactory.newInstance();
      if (file.equals("-")) {
        reader = factory.createXMLStreamReader(System.in);
      } else {
        reader = factory.createXMLStreamReader(new FileInputStream(file));
      }
      while (reader.hasNext()) {
        procNode();
        reader.next();
      }
      reader.close();
      // Minimize transducers
      for (TransducerComp transducer : sections.values()) {
        transducer.minimize();
      }

    } catch (FileNotFoundException e) {
      throw new RuntimeException("Error: Cannot open '" + file + "'.");
    } catch (RuntimeException e) {
      System.err.println("Error (" + e + ") at line " + reader.getLocation().getLineNumber());
      throw e;
    } catch (Throwable ex) {
      System.err.println("Error (" + ex + ") at line " + reader.getLocation().getLineNumber());
      throw new RuntimeException("Error t " + reader.getLocation().getLineNumber(), ex);
    }
  }
Пример #3
0
  public static void main(String[] args) throws Exception {

    XMLInputFactory xif = XMLInputFactory.newFactory();
    StreamSource xml = new StreamSource("src/main/resources/PClientCreate_001_Request.xml");
    XMLStreamReader xsr = xif.createXMLStreamReader(xml);
    xsr.nextTag();

    /* System.out.println(xsr.getElementText()); */

    int event = 0;
    // here we advance to next tag untill we find node called "kitchen"
    for (event = xsr.next(); event != XMLStreamReader.END_DOCUMENT; event = xsr.next()) {

      if (event == XMLStreamReader.START_ELEMENT) {
        System.out.println(xsr.getLocalName());
        if (xsr.getLocalName() == "s2465") {
          break;
        }
      }
    }

    JAXBContext jc = JAXBContext.newInstance(S2465.class);
    Unmarshaller unmarshaller = jc.createUnmarshaller();

    JAXBElement<S2465> jb = unmarshaller.unmarshal(xsr, S2465.class);
    xsr.close();

    S2465 s2465 = jb.getValue();
    System.out.println(s2465.getLgivname());
    System.out.println(s2465.getLsurname());
  }
  public void writePayloadTo(XMLStreamWriter writer) throws XMLStreamException {
    if (payloadLocalName == null) {
      return;
    } // no body
    assert unconsumed();
    XMLStreamReaderToXMLStreamWriter conv = new XMLStreamReaderToXMLStreamWriter();
    while (reader.getEventType() != XMLStreamConstants.END_DOCUMENT) {
      String name = reader.getLocalName();
      String nsUri = reader.getNamespaceURI();

      // after previous conv.bridge() call the cursor will be at
      // END_ELEMENT. Check if its not soapenv:Body then move to next
      // ELEMENT
      if (reader.getEventType() == XMLStreamConstants.END_ELEMENT) {
        if (!name.equals("Body") || !nsUri.equals(soapVersion.nsUri)) {
          XMLStreamReaderUtil.nextElementContent(reader);
          if (reader.getEventType() == XMLStreamConstants.END_DOCUMENT) {
            break;
          }
          name = reader.getLocalName();
          nsUri = reader.getNamespaceURI();
        }
      }
      if (name.equals("Body") && nsUri.equals(soapVersion.nsUri)
          || (reader.getEventType() == XMLStreamConstants.END_DOCUMENT)) {
        break;
      }
      conv.bridge(reader, writer);
    }
    reader.close();
    XMLStreamReaderFactory.recycle(reader);
  }
Пример #5
0
 public void terminate() {
   try {
     reader.close();
   } catch (XMLStreamException e) {
     e.printStackTrace();
   }
 }
    public void run() {
      try {
        FileOutputStream fos = new FileOutputStream("" + no);
        XMLStreamWriter w = getWriter(fos);
        // System.out.println("Writer="+w+" Thread="+Thread.currentThread());
        w.writeStartDocument();
        w.writeStartElement("hello");
        for (int j = 0; j < 50; j++) {
          w.writeStartElement("a" + j);
          w.writeEndElement();
        }
        w.writeEndElement();
        w.writeEndDocument();
        w.close();
        fos.close();

        FileInputStream fis = new FileInputStream("" + no);
        XMLStreamReader r = getReader(fis);
        while (r.hasNext()) {
          r.next();
        }
        r.close();
        fis.close();
      } catch (Exception e) {
        Assert.fail(e.getMessage());
      }
    }
Пример #7
0
 /**
  * Do parse.
  *
  * @param context
  * @param rs
  */
 public List<Country> parseCountries(Operator context, Resource rs) {
   List<Country> countryList = new ArrayList<>();
   logger.debug("About to read country list from {}.", rs);
   try {
     XMLInputFactory factory = XMLInputFactory.newInstance();
     XMLStreamReader parser = factory.createXMLStreamReader(rs.getInputStream());
     while (true) {
       int event = parser.next();
       if (event == XMLStreamConstants.END_DOCUMENT) {
         parser.close();
         break;
       }
       if (event == XMLStreamConstants.START_ELEMENT && parser.getLocalName().equals("country")) {
         String countryCode = parser.getAttributeValue("", "countryCode");
         String name =
             parser
                 .getAttributeValue("", "countryName")
                 .concat("                                ")
                 .substring(0, 32)
                 .trim();
         Country country = new Country(context, countryCode, name);
         countryList.add(country);
         logger.debug("Added {} to country list.", country);
       }
     }
   } catch (XMLStreamException e) {
     throw new IllegalArgumentException("Unable to parse country data file", e);
   } catch (IOException e) {
     throw new IllegalArgumentException("Unable to read from country data file", e);
   }
   return countryList;
 }
  @Override
  public ISORecord inspect(ISORecord record, Connection conn, SQLDialect dialect)
      throws MetadataInspectorException {

    ISORecord result = record;

    try {
      // create temporary sink for normalized XML
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(bos);
      writer = new NamespaceNormalizingXMLStreamWriter(writer, nsBindings);

      // create normalized copy
      XMLStreamReader reader = record.getAsXMLStream();
      XMLAdapter.writeElement(writer, reader);
      reader.close();
      writer.close();

      InputStream is = new ByteArrayInputStream(bos.toByteArray());
      XMLStreamReader xmlStream = XMLInputFactory.newInstance().createXMLStreamReader(is);
      result = new ISORecord(xmlStream);
    } catch (Throwable t) {
      LOG.error(
          "Namespace normalization failed. Proceeding with unnormalized record. Error: "
              + t.getMessage());
    }

    return result;
  }
 public void close() throws IOException {
   try {
     reader.close();
   } catch (XMLStreamException e) {
     throw new IOException(e.getMessage());
   }
 }
 private void safeClose() {
   try {
     streamReader.close();
   } catch (Exception e) {
     // ignore
   }
 }
 protected Document wbxmlStream2Doc(InputStream in, boolean event) throws Exception {
   XMLStreamReader xmlStreamReader = null;
   XMLEventReader xmlEventReader = null;
   try {
     if (event) {
       xmlEventReader = inFact.createXMLEventReader(in);
     } else {
       xmlStreamReader = inFact.createXMLStreamReader(in);
     }
     Transformer xformer = TransformerFactory.newInstance().newTransformer();
     StAXSource staxSource =
         event ? new StAXSource(xmlEventReader) : new StAXSource(xmlStreamReader);
     DOMResult domResult = new DOMResult();
     xformer.transform(staxSource, domResult);
     Document doc = (Document) domResult.getNode();
     doc.normalize();
     return doc;
   } finally {
     if (xmlStreamReader != null) {
       try {
         xmlStreamReader.close();
       } catch (Exception e) {
       }
     }
     if (xmlEventReader != null) {
       try {
         xmlEventReader.close();
       } catch (Exception e) {
       }
     }
   }
 }
  private void parseCoordElements(final File pom) {
    Reader reader = null;
    XMLStreamReader xml = null;
    try {
      reader = new FileReader(pom);
      xml = XMLInputFactory.newFactory().createXMLStreamReader(reader);

      final Stack<String> path = new Stack<String>();
      while (xml.hasNext()) {
        final int evt = xml.next();
        switch (evt) {
          case START_ELEMENT:
            {
              path.push(xml.getLocalName());
              if (captureValue(path, xml)) {
                // seems like xml.getElementText() traverses the END_ELEMENT event...
                path.pop();
              }

              if (foundPreferredValues()) {
                return;
              }
              break;
            }
          case END_ELEMENT:
            {
              path.pop();
              break;
            }
          default:
            {
            }
        }
      }
    } catch (final IOException e) {
      logger.warn(
          "Failed to peek at POM coordinate for: %s. Reason: %s\n"
              + "This POM will NOT be available as an ancestor to other models during effective-model building.",
          e, pom, e.getMessage());
    } catch (final XMLStreamException e) {
      logger.warn(
          "Failed to peek at POM coordinate for: %s. Reason: %s\n"
              + "This POM will NOT be available as an ancestor to other models during effective-model building.",
          e, pom, e.getMessage());
    } catch (final FactoryConfigurationError e) {
      logger.warn(
          "Failed to peek at POM coordinate for: %s. Reason: %s\n"
              + "This POM will NOT be available as an ancestor to other models during effective-model building.",
          e, pom, e.getMessage());
    } finally {
      if (xml != null) {
        try {
          xml.close();
        } catch (final XMLStreamException e) {
        }
      }

      closeQuietly(reader);
    }
  }
  public static OMElement read(String filePath) throws FileNotFoundException, XMLStreamException {
    OMElement documentElement = null;
    XMLStreamReader parser = null;
    InputStreamReader in = null;

    try {

      in = new InputStreamReader(new FileInputStream(filePath), Charset.defaultCharset());
      parser = XMLInputFactory.newInstance().createXMLStreamReader(in);
      // create the builder
      StAXOMBuilder builder = new StAXOMBuilder(parser);
      // get the root element
      documentElement = builder.getDocumentElement();
      documentElement.build();
    } finally {
      if (parser != null) {
        parser.close();
      }

      try {
        if (in != null) in.close();
      } catch (IOException e) {
        // ignore
      }
    }
    return documentElement;
  }
 protected Object wbxmlStream2Object(InputStream in, boolean event) throws Exception {
   XMLStreamReader xmlStreamReader = null;
   XMLEventReader xmlEventReader = null;
   try {
     if (event) {
       xmlEventReader = inFact.createXMLEventReader(in);
     } else {
       xmlStreamReader = inFact.createXMLStreamReader(in);
     }
     if (jc == null) {
       jc = JAXBContext.newInstance(Class.forName(this.def.getClazz()));
     }
     Unmarshaller unmarshaller = jc.createUnmarshaller();
     if (event) {
       return unmarshaller.unmarshal(xmlEventReader);
     } else {
       return unmarshaller.unmarshal(xmlStreamReader);
     }
   } finally {
     if (xmlStreamReader != null) {
       try {
         xmlStreamReader.close();
       } catch (Exception e) {
       }
     }
     if (xmlEventReader != null) {
       try {
         xmlEventReader.close();
       } catch (Exception e) {
       }
     }
   }
 }
Пример #15
0
 private static void safeClose(final XMLStreamReader streamReader) {
   if (streamReader != null)
     try {
       streamReader.close();
     } catch (XMLStreamException e) {
       // ignore
     }
 }
Пример #16
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 void tryClose(XMLStreamReader reader) {
   if (reader != null) {
     try {
       reader.close();
     } catch (XMLStreamException e) {
       // whatever
     }
   }
 }
Пример #18
0
 /**
  * Unconditionally close a {@link XMLStreamReader}.
  *
  * <p>Equivalent to XMLStreamReader.close(), except any exceptions will be ignored. This is
  * typically used in finally blocks.
  *
  * @param xmlReader to close, may be null or already closed
  */
 public static void closeQuietly(XMLStreamReader xmlReader) {
   if (xmlReader != null) {
     try {
       xmlReader.close();
     } catch (Exception e) {
       LOG.info("XMLStreamReader could not be closed: {}", e.getMessage());
     }
   }
 }
 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();
 }
  public void writePayloadTo(
      ContentHandler contentHandler, ErrorHandler errorHandler, boolean fragment)
      throws SAXException {
    assert unconsumed();
    try {
      if (payloadLocalName == null) {
        return;
      } // no body

      XMLStreamReaderToContentHandler conv =
          new XMLStreamReaderToContentHandler(reader, contentHandler, true, fragment);

      while (reader.getEventType() != XMLStreamConstants.END_DOCUMENT) {
        String name = reader.getLocalName();
        String nsUri = reader.getNamespaceURI();

        // after previous conv.bridge() call the cursor will be at
        // END_ELEMENT. Check if its not soapenv:Body then move to next
        // ELEMENT
        if (reader.getEventType() == XMLStreamConstants.END_ELEMENT) {
          if (!name.equals("Body") || !nsUri.equals(soapVersion.nsUri)) {
            XMLStreamReaderUtil.nextElementContent(reader);
            if (reader.getEventType() == XMLStreamConstants.END_DOCUMENT) {
              break;
            }
            name = reader.getLocalName();
            nsUri = reader.getNamespaceURI();
          }
        }
        if (name.equals("Body") && nsUri.equals(soapVersion.nsUri)
            || (reader.getEventType() == XMLStreamConstants.END_DOCUMENT)) {
          break;
        }

        conv.bridge();
      }
      reader.close();
      XMLStreamReaderFactory.recycle(reader);
    } catch (XMLStreamException e) {
      Location loc = e.getLocation();
      if (loc == null) {
        loc = DummyLocation.INSTANCE;
      }

      SAXParseException x =
          new SAXParseException(
              e.getMessage(),
              loc.getPublicId(),
              loc.getSystemId(),
              loc.getLineNumber(),
              loc.getColumnNumber(),
              e);
      errorHandler.error(x);
    }
  }
Пример #21
0
 /**
  * Parses XMI document accessible via the specified stream.
  *
  * @param stream Input stream which streams the XMI document.
  * @return
  * @throws XMLStreamException
  */
 public static RawRoot parse(InputStream stream) throws XMLStreamException {
   XMLInputFactory factory = XMLInputFactory.newInstance();
   XMLStreamReader reader = factory.createXMLStreamReader(stream);
   try {
     return parse(reader);
   } finally {
     try {
       reader.close();
     } catch (XMLStreamException exc) {
     }
   }
 }
Пример #22
0
  private void process(Mode mode, Set<String> xmlRootElements, Map<String, Class<?>> entityClasses)
      throws Exception {
    LOGGER.info("Start {}: {}", mode, fiasRarFile);
    try (final Archive archive = new Archive(fiasRarFile)) {
      if (!archive.isEncrypted()) {
        final XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
        Collection<Object> batch = new ArrayList<>(batchSize);
        FileHeader fileHeader;

        while ((fileHeader = archive.nextFileHeader()) != null) {
          final String fileName = fileHeader.getFileNameString();

          if (!fileHeader.isEncrypted()) {
            if (fileHeader.isFileHeader()) {
              if ((!fileName.startsWith("AS_DEL_") && mode == Mode.SAVE)
                  || (fileName.startsWith("AS_DEL_") && mode == Mode.DELETE)) {
                LOGGER.info("Start Reading: {}", fileName);

                try (final InputStream inputStream = archive.getInputStream(fileHeader)) {
                  final XMLStreamReader xmlStreamReader =
                      xmlInputFactory.createXMLStreamReader(inputStream);

                  try {
                    batch =
                        processFile(mode, xmlRootElements, entityClasses, xmlStreamReader, batch);
                  } finally {
                    xmlStreamReader.close();
                  }
                } catch (Throwable e) {
                  LOGGER.error("{} Error: {}", mode, fileName, e);
                } finally {
                  LOGGER.info("Finish Reading: {}", fileName);
                }
              }
            } else {
              LOGGER.error("Not File: {}", fileName);
            }
          } else {
            LOGGER.error("File is encrypted: {}", fileName);
          }
        }

        if (batch.size() > 0) {
          processBatch(mode, batch);
        }
      } else {
        LOGGER.error("Archive is encrypted: {}", fiasRarFile);
      }
    } finally {
      LOGGER.info("Finish {}: {}", mode, fiasRarFile);
    }
  }
Пример #23
0
 /**
  * Parses a job xml file, which defines a batch job.
  *
  * @param inputStream the source of the job xml definition
  * @return a Job object
  * @throws XMLStreamException
  */
 public static Job parseJob(final InputStream inputStream) throws XMLStreamException {
   final XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
   Job job = null;
   try {
     while (reader.hasNext()) {
       final int eventType = reader.next();
       if (eventType != START_ELEMENT && eventType != END_ELEMENT) {
         continue;
       }
       final XmlElement element = XmlElement.forName(reader.getLocalName());
       switch (eventType) {
         case START_ELEMENT:
           switch (element) {
             case JOB:
               job = new Job(getAttributeValue(reader, XmlAttribute.ID, true));
               job.setRestartable(getAttributeValue(reader, XmlAttribute.RESTARTABLE, false));
               break;
             case STEP:
               job.addJobElement(parseStep(reader));
               break;
             case FLOW:
               job.addJobElement(parseFlow(reader));
               break;
             case SPLIT:
               job.addJobElement(parseSplit(reader));
               break;
             case DECISION:
               job.addJobElement(parseDecision(reader));
               break;
             case PROPERTIES:
               job.setProperties(parseProperties(reader));
               break;
             case LISTENERS:
               job.addListeners(parseListeners(reader));
               break;
             default:
               throw BatchLogger.LOGGER.unexpectedXmlElement(
                   reader.getLocalName(), reader.getLocation());
           }
           break;
         case END_ELEMENT:
           if (element != XmlElement.JOB) {
             throw BatchLogger.LOGGER.unexpectedXmlElement(
                 reader.getLocalName(), reader.getLocation());
           }
       }
     }
   } finally {
     reader.close();
   }
   return job;
 }
Пример #24
0
 protected void parse() throws XMLStreamException {
   int event = parser.getEventType();
   while (true) {
     if (event == XMLStreamConstants.START_ELEMENT) {
       parseRoot();
     } else if (event == XMLStreamConstants.END_ELEMENT) return;
     if (parser.hasNext()) {
       event = parser.next();
     } else {
       break;
     }
   }
   parser.close();
 }
Пример #25
0
  public void testSimpleValidExternalSubset() throws XMLStreamException {
    String XML = "<!DOCTYPE root SYSTEM 'myurl' >" + "<root>text</root>";
    String EXT_ENTITY_VALUE = "just testing";
    String EXT_SUBSET = "<!ELEMENT root (#PCDATA)>\n" + "<!-- comments are ok!!! -->";

    XMLStreamReader sr = getReader(XML, true, new SimpleResolver(EXT_SUBSET));
    assertTokenType(DTD, sr.next());
    assertTokenType(START_ELEMENT, sr.next());
    assertEquals("root", sr.getLocalName());
    assertTokenType(CHARACTERS, sr.next());
    assertEquals("text", getAndVerifyText(sr));
    assertTokenType(END_ELEMENT, sr.next());
    sr.close();
  }
Пример #26
0
    protected void init(InputStream input) throws XMLStreamException {

      try {
        read(input);
      } finally {
        if (parser != null) {
          try {
            parser.close();
          } catch (Exception ex) {
            // ignore
          }
        }
      }
    }
  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;
  }
Пример #28
0
  /** @return the parsed document */
  public static Document buildDocument(InputStream is) throws PublicException, IOException {
    Document doc = null;
    try {
      XMLInputFactory inputFactory = StaxUtils.getXmlInputFactory();
      XMLStreamReader xmlReader = inputFactory.createXMLStreamReader(is);

      try {
        doc = buildDocument(xmlReader);
      } finally {
        xmlReader.close();
      }
    } catch (XMLStreamException e) {
      throw new PublicException(BpmRuntimeError.SDT_FAILED_PARSING_XML_DOCUMENT.raise(), e);
    }

    return doc;
  }
Пример #29
0
    public void run() {
      try {
        final XMLStreamReader reader =
            STAXUtils.createXMLStreamReader(stream, message.getEncoding(), context);
        final InMessage inMessage = new InMessage(reader, uri);
        inMessage.setEncoding(message.getEncoding());

        channel.receive(context, inMessage);

        reader.close();
        stream.close();
      } catch (Exception e) {
        throw new XFireRuntimeException("Couldn't read stream.", e);
      } finally {
        semaphore.release();
      }
    }
Пример #30
0
  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;
  }