Java Code Examples for javax.xml.stream.XMLInputFactory#setProperty()

The following examples show how to use javax.xml.stream.XMLInputFactory#setProperty() . 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: SchemaInfo.java    From elastic-db-tools-for-java with MIT License 6 votes vote down vote up
/**
 * Initializes a new instance of the <see cref="SchemaInfo"/> class.
 */
public SchemaInfo(ResultSet reader,
        int offset) {
    try (StringReader sr = new StringReader(reader.getSQLXML(offset).getString())) {
        JAXBContext jc = JAXBContext.newInstance(SchemaInfo.class);

        XMLInputFactory xif = XMLInputFactory.newFactory();
        xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
        xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
        XMLStreamReader xsr = xif.createXMLStreamReader(sr);

        SchemaInfo schemaInfo = (SchemaInfo) jc.createUnmarshaller().unmarshal(xsr);

        this.referenceTables = new ReferenceTableSet(schemaInfo.getReferenceTables());
        this.shardedTables = new ShardedTableSet(schemaInfo.getShardedTables());
    }
    catch (SQLException | JAXBException | XMLStreamException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
 
Example 2
Source File: Jaxb2CollectionHttpMessageConverterTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void readXmlRootElementExternalEntityEnabled() throws Exception {
	Resource external = new ClassPathResource("external.txt", getClass());
	String content =  "<!DOCTYPE root [" +
			"  <!ELEMENT external ANY >\n" +
			"  <!ENTITY ext SYSTEM \"" + external.getURI() + "\" >]>" +
			"  <list><rootElement><type s=\"1\"/><external>&ext;</external></rootElement></list>";
	MockHttpInputMessage inputMessage = new MockHttpInputMessage(content.getBytes("UTF-8"));

	Jaxb2CollectionHttpMessageConverter<?> c = new Jaxb2CollectionHttpMessageConverter<Collection<Object>>() {
		@Override
		protected XMLInputFactory createXmlInputFactory() {
			XMLInputFactory inputFactory = XMLInputFactory.newInstance();
			inputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, true);
			return inputFactory;
		}
	};

	Collection<RootElement> result = c.read(rootElementListType, null, inputMessage);
	assertEquals(1, result.size());
	assertEquals("Foo Bar", result.iterator().next().external);
}
 
Example 3
Source File: XMLEventReaderWrapper.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public XMLEventReaderWrapper(final InputStream stream)
    throws IOException, XMLStreamException {
  final StringBuilder startBuilder = new StringBuilder();
  startBuilder.append("<").append(CONTENT).
  append(" xmlns:m").append("=\"").append(Constants.get(ConstantKey.METADATA_NS)).append("\"").
  append(" xmlns:d").append("=\"").append(Constants.get(ConstantKey.DATASERVICES_NS)).append("\"").
  append(" xmlns:georss").append("=\"").append(Constants.get(ConstantKey.GEORSS_NS)).append("\"").
  append(" xmlns:gml").append("=\"").append(Constants.get(ConstantKey.GML_NS)).append("\"").
  append(">");

  CONTENT_STAG = startBuilder.toString();

  final XMLInputFactory factory = XMLInputFactory.newInstance();
  factory.setProperty(SUPPORT_DTD, false);
  factory.setProperty(IS_SUPPORTING_EXTERNAL_ENTITIES, false);

  final InputStreamReader reader = new InputStreamReader(
      new ByteArrayInputStream((CONTENT_STAG
          + IOUtils.toString(stream, ENCODING).replaceAll("^<\\?xml.*\\?>", "")
          + XMLEventReaderWrapper.CONTENT_ETAG).getBytes(ENCODING)),
          Constants.DECODER);

  wrapped = factory.createXMLEventReader(reader);

  init();
}
 
Example 4
Source File: IgnoreExternalDTDTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testFeatureNegative() throws Exception {
    XMLInputFactory xif = XMLInputFactory.newInstance();
    xif.setProperty(ZEPHYR_PROPERTY_PREFIX + IGNORE_EXTERNAL_DTD, Boolean.FALSE);
    try {
        parse(xif);
        // refer to 6440324, absent of that change, an exception would be
        // thrown;
        // due to the change made for 6440324, parsing will continue without
        // exception
        // fail();
    } catch (XMLStreamException e) {
        // the error is expected that no DTD was found
    }
}
 
Example 5
Source File: Jackson2ObjectMapperBuilder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private static XMLInputFactory xmlInputFactory() {
	XMLInputFactory inputFactory = XMLInputFactory.newInstance();
	inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
	inputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
	inputFactory.setXMLResolver(NO_OP_XML_RESOLVER);
	return inputFactory;
}
 
Example 6
Source File: XMLStreamReaderFactory.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public Zephyr(XMLInputFactory xif, Class clazz) throws NoSuchMethodException {
    zephyrClass = clazz;
    setInputSourceMethod = clazz.getMethod("setInputSource", InputSource.class);
    resetMethod = clazz.getMethod("reset");

    try {
        // Turn OFF internal factory caching in Zephyr.
        // Santiago told me that this makes it thread-safe.
        xif.setProperty("reuse-instance", false);
    } catch (IllegalArgumentException e) {
        // falls through
    }
    this.xif = xif;
}
 
Example 7
Source File: XMLStreamUtil.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Build a new XMLInputFactory.
 *
 * @return XML input factory
 */
public static XMLInputFactory getXmlInputFactory() {
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    inputFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
    inputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE);
    inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE);
    // Woodstox 5.2.0
    //if (inputFactory.isPropertySupported("com.ctc.wstx.allowXml11EscapedCharsInXml10")) {
    //    inputFactory.setProperty("com.ctc.wstx.allowXml11EscapedCharsInXml10", Boolean.TRUE);
    //}
    return inputFactory;
}
 
Example 8
Source File: FileBasedTaskRepository.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
private static XMLStreamReader getXMLStreamReader(InputStream input) throws XMLStreamException {
    XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
    xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
    xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
    XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(new StreamSource(input));
    return xmlStreamReader;
}
 
Example 9
Source File: DatabaseIO.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new, initialized XML input factory object.
 * 
 * @return The factory object
 */
private XMLInputFactory getXMLInputFactory()
{
    XMLInputFactory factory = XMLInputFactory.newInstance();

    factory.setProperty("javax.xml.stream.isCoalescing",     Boolean.TRUE);
    factory.setProperty("javax.xml.stream.isNamespaceAware", Boolean.TRUE);
    return factory;
}
 
Example 10
Source File: AbstractConsumerTest.java    From cloud-odata-java with Apache License 2.0 5 votes vote down vote up
protected XMLStreamReader createReaderForTest(final String input, final boolean namespaceAware) throws XMLStreamException {
  XMLInputFactory factory = XMLInputFactory.newInstance();
  factory.setProperty(XMLInputFactory.IS_VALIDATING, false);
  factory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, namespaceAware);

  XMLStreamReader streamReader = factory.createXMLStreamReader(new StringReader(input));

  return streamReader;
}
 
Example 11
Source File: XMLResolverTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testXMLResolver() {
    try {
        XMLInputFactory xifactory = XMLInputFactory.newInstance();
        xifactory.setProperty(XMLInputFactory.RESOLVER, new MyStaxResolver());
        File file = new File(getClass().getResource("XMLResolverTest.xml").getFile());
        String systemId = file.toURI().toString();
        InputStream entityxml = new FileInputStream(file);
        XMLStreamReader streamReader = xifactory.createXMLStreamReader(systemId, entityxml);
        while (streamReader.hasNext()) {
            int eventType = streamReader.next();
            if (eventType == XMLStreamConstants.START_ELEMENT) {
                eventType = streamReader.next();
                if (eventType == XMLStreamConstants.CHARACTERS) {
                    String text = streamReader.getText();
                    Assert.assertTrue(text.contains("replace2"));
                }
            }
        }
    } catch (XMLStreamException ex) {

        if (ex.getNestedException() != null) {
            ex.getNestedException().printStackTrace();
        }
        // ex.printStackTrace() ;
    } catch (Exception io) {
        io.printStackTrace();
    }
}
 
Example 12
Source File: TestCharacterLimits.java    From woodstox with Apache License 2.0 5 votes vote down vote up
public void testLongWhitespaceCoalescing() throws Exception {
    try {
        Reader reader = createLongReader("", "", true);
        XMLInputFactory factory = getNewInputFactory();
        factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
        factory.setProperty(WstxInputProperties.P_MAX_TEXT_LENGTH, Integer.valueOf(1000));
        XMLStreamReader xmlreader = factory.createXMLStreamReader(reader);
        while (xmlreader.next() != XMLStreamReader.START_ELEMENT) {
        }
        xmlreader.nextTag();
        fail("Should have failed");
    } catch (XMLStreamException ex) {
        _verifyTextLimitException(ex);
    }
}
 
Example 13
Source File: SecureXmlParserFactory.java    From analysis-model with MIT License 5 votes vote down vote up
/**
 * Creates a new instance of a {@link XMLStreamReader} that does not resolve external entities.
 *
 * @param reader
 *         the reader to wrap
 *
 * @return a new instance of a {@link XMLStreamReader}
 */
public XMLStreamReader createXmlStreamReader(final Reader reader) {
    try {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        factory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
        factory.setProperty("javax.xml.stream.isSupportingExternalEntities", false);
        return factory.createXMLStreamReader(reader);
    }
    catch (XMLStreamException exception) {
        throw new IllegalArgumentException("Can't create instance of XMLStreamReader", exception);
    }
}
 
Example 14
Source File: XmlUtil.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public static XMLInputFactory newXMLInputFactory(boolean secureXmlProcessingEnabled)  {
    XMLInputFactory factory = XMLInputFactory.newInstance();
    if (isXMLSecurityDisabled(secureXmlProcessingEnabled)) {
        // TODO-Miran: are those apppropriate defaults?
        factory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
        factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
    }
    return factory;
}
 
Example 15
Source File: ArtifactsXmlAbsoluteUrlRemover.java    From nexus-repository-p2 with Eclipse Public License 1.0 4 votes vote down vote up
private TempBlob transformXmlMetadata(final TempBlob artifact,
                                      final Repository repository,
                                      final String file,
                                      final String extension,
                                      final XmlStreamTransformer transformer) throws IOException {

  Path tempFile = createTempFile("", ".xml");
  // This is required in the case that the input stream is a jar to allow us to extract a single file
  Path artifactsTempFile = createTempFile("", ".xml");
  try {
    try (InputStream xmlIn = xmlInputStream(artifact, file + "." + "xml", extension, artifactsTempFile);
         OutputStream xmlOut = xmlOutputStream(file + "." + "xml", extension, tempFile)) {
      XMLInputFactory inputFactory = XMLInputFactory.newInstance();
      inputFactory.setProperty(SUPPORT_DTD, false);
      inputFactory.setProperty(IS_SUPPORTING_EXTERNAL_ENTITIES, false);

      XMLOutputFactory outputFactory = XMLOutputFactory.newFactory();
      XMLEventReader reader = null;
      XMLEventWriter writer = null;
      //try-with-resources will be better here, but XMLEventReader and XMLEventWriter are not AutoCloseable
      try {
        reader = inputFactory.createXMLEventReader(xmlIn);
        writer = outputFactory.createXMLEventWriter(xmlOut);
        transformer.transform(reader, writer);
        writer.flush();
      }
      finally {
        if (reader != null) {
          reader.close();
        }
        if (writer != null) {
          writer.close();
        }
      }
    }
    catch (XMLStreamException ex) {
      log.error("Failed to rewrite metadata for file with extension {} and blob {} with reason: {} ",
          ex, artifact.getBlob().getId(), ex);
      return artifact;
    }
    return convertFileToTempBlob(tempFile, repository);
  }
  finally {
    delete(tempFile);
    delete(artifactsTempFile);
  }
}
 
Example 16
Source File: Library.java    From MusicPlayer with MIT License 4 votes vote down vote up
public static ObservableList<Playlist> getPlaylists() {
    if (playlists == null) {

        playlists = new ArrayList<>();
        int id = 0;

        try {
            XMLInputFactory factory = XMLInputFactory.newInstance();
            factory.setProperty("javax.xml.stream.isCoalescing", true);
            FileInputStream is = new FileInputStream(new File(Resources.JAR + "library.xml"));
            XMLStreamReader reader = factory.createXMLStreamReader(is, "UTF-8");

            String element;
            boolean isPlaylist = false;
            String title = null;
            ArrayList<Song> songs = new ArrayList<>();

            while(reader.hasNext()) {
                reader.next();
                if (reader.isWhiteSpace()) {
                    continue;
                } else if (reader.isStartElement()) {
                    element = reader.getName().getLocalPart();

                    // If the element is a play list, reads the element attributes to retrieve
                    // the play list id and title.
                    if (element.equals("playlist")) {
                        isPlaylist = true;

                        id = Integer.parseInt(reader.getAttributeValue(0));
                        title = reader.getAttributeValue(1);
                    }
                } else if (reader.isCharacters() && isPlaylist) {
                    // Retrieves the reader value (song ID), gets the song and adds it to the songs list.
                    String value = reader.getText();
                    songs.add(getSong(Integer.parseInt(value)));
                } else if (reader.isEndElement() && reader.getName().getLocalPart().equals("playlist")) {
                    // If the play list id, title, and songs have been retrieved, a new play list is created
                    // and the values reset.
                    playlists.add(new Playlist(id, title, songs));
                    id = -1;
                    title = null;
                    songs = new ArrayList<>();
                } else if (reader.isEndElement() && reader.getName().getLocalPart().equals("playlists")) {
                    reader.close();
                    break;
                }
            }
            reader.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        playlists.sort((x, y) -> {
            if (x.getId() < y.getId()) {
                return 1;
            } else if (x.getId() > y.getId()) {
                return -1;
            } else {
                return 0;
            }
        });

        playlists.add(new MostPlayedPlaylist(-2));
        playlists.add(new RecentlyPlayedPlaylist(-1));
    } else {
        playlists.sort((x, y) -> {
            if (x.getId() < y.getId()) {
                return 1;
            } else if (x.getId() > y.getId()) {
                return -1;
            } else {
                return 0;
            }
        });
    }
    return FXCollections.observableArrayList(playlists);
}
 
Example 17
Source File: XMLStreamReaderFactory.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
public Woodstox(XMLInputFactory xif) {
    super(xif);

    if (xif.isPropertySupported(P_INTERN_NSURIS)) {
        xif.setProperty(P_INTERN_NSURIS, true);
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, P_INTERN_NSURIS + " is {0}", true);
        }
    }

    if (xif.isPropertySupported(P_MAX_ATTRIBUTES_PER_ELEMENT)) {
        maxAttributesPerElement = Integer.valueOf(buildIntegerValue(
            PROPERTY_MAX_ATTRIBUTES_PER_ELEMENT, DEFAULT_MAX_ATTRIBUTES_PER_ELEMENT)
        );
        xif.setProperty(P_MAX_ATTRIBUTES_PER_ELEMENT, maxAttributesPerElement);
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, P_MAX_ATTRIBUTES_PER_ELEMENT + " is {0}", maxAttributesPerElement);
        }
    }

    if (xif.isPropertySupported(P_MAX_ATTRIBUTE_SIZE)) {
        maxAttributeSize = Integer.valueOf(buildIntegerValue(
            PROPERTY_MAX_ATTRIBUTE_SIZE, DEFAULT_MAX_ATTRIBUTE_SIZE)
        );
        xif.setProperty(P_MAX_ATTRIBUTE_SIZE, maxAttributeSize);
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, P_MAX_ATTRIBUTE_SIZE + " is {0}", maxAttributeSize);
        }
    }

    if (xif.isPropertySupported(P_MAX_CHILDREN_PER_ELEMENT)) {
        maxChildrenPerElement = Integer.valueOf(buildIntegerValue(
            PROPERTY_MAX_CHILDREN_PER_ELEMENT, DEFAULT_MAX_CHILDREN_PER_ELEMENT)
        );
        xif.setProperty(P_MAX_CHILDREN_PER_ELEMENT, maxChildrenPerElement);
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, P_MAX_CHILDREN_PER_ELEMENT + " is {0}", maxChildrenPerElement);
        }
    }

    if (xif.isPropertySupported(P_MAX_ELEMENT_DEPTH)) {
        maxElementDepth = Integer.valueOf(buildIntegerValue(
            PROPERTY_MAX_ELEMENT_DEPTH, DEFAULT_MAX_ELEMENT_DEPTH)
        );
        xif.setProperty(P_MAX_ELEMENT_DEPTH, maxElementDepth);
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, P_MAX_ELEMENT_DEPTH + " is {0}", maxElementDepth);
        }
    }

    if (xif.isPropertySupported(P_MAX_ELEMENT_COUNT)) {
        maxElementCount = Long.valueOf(buildLongValue(
            PROPERTY_MAX_ELEMENT_COUNT, DEFAULT_MAX_ELEMENT_COUNT)
        );
        xif.setProperty(P_MAX_ELEMENT_COUNT, maxElementCount);
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, P_MAX_ELEMENT_COUNT + " is {0}", maxElementCount);
        }
    }

    if (xif.isPropertySupported(P_MAX_CHARACTERS)) {
        maxCharacters = Long.valueOf(buildLongValue(
            PROPERTY_MAX_CHARACTERS, DEFAULT_MAX_CHARACTERS)
        );
        xif.setProperty(P_MAX_CHARACTERS, maxCharacters);
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, P_MAX_CHARACTERS + " is {0}", maxCharacters);
        }
    }
}
 
Example 18
Source File: XMLStreamReaderFactory.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public Woodstox(XMLInputFactory xif) {
    super(xif);

    if (xif.isPropertySupported(P_INTERN_NSURIS)) {
        xif.setProperty(P_INTERN_NSURIS, true);
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, P_INTERN_NSURIS + " is {0}", true);
        }
    }

    if (xif.isPropertySupported(P_MAX_ATTRIBUTES_PER_ELEMENT)) {
        maxAttributesPerElement = Integer.valueOf(buildIntegerValue(
            PROPERTY_MAX_ATTRIBUTES_PER_ELEMENT, DEFAULT_MAX_ATTRIBUTES_PER_ELEMENT)
        );
        xif.setProperty(P_MAX_ATTRIBUTES_PER_ELEMENT, maxAttributesPerElement);
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, P_MAX_ATTRIBUTES_PER_ELEMENT + " is {0}", maxAttributesPerElement);
        }
    }

    if (xif.isPropertySupported(P_MAX_ATTRIBUTE_SIZE)) {
        maxAttributeSize = Integer.valueOf(buildIntegerValue(
            PROPERTY_MAX_ATTRIBUTE_SIZE, DEFAULT_MAX_ATTRIBUTE_SIZE)
        );
        xif.setProperty(P_MAX_ATTRIBUTE_SIZE, maxAttributeSize);
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, P_MAX_ATTRIBUTE_SIZE + " is {0}", maxAttributeSize);
        }
    }

    if (xif.isPropertySupported(P_MAX_CHILDREN_PER_ELEMENT)) {
        maxChildrenPerElement = Integer.valueOf(buildIntegerValue(
            PROPERTY_MAX_CHILDREN_PER_ELEMENT, DEFAULT_MAX_CHILDREN_PER_ELEMENT)
        );
        xif.setProperty(P_MAX_CHILDREN_PER_ELEMENT, maxChildrenPerElement);
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, P_MAX_CHILDREN_PER_ELEMENT + " is {0}", maxChildrenPerElement);
        }
    }

    if (xif.isPropertySupported(P_MAX_ELEMENT_DEPTH)) {
        maxElementDepth = Integer.valueOf(buildIntegerValue(
            PROPERTY_MAX_ELEMENT_DEPTH, DEFAULT_MAX_ELEMENT_DEPTH)
        );
        xif.setProperty(P_MAX_ELEMENT_DEPTH, maxElementDepth);
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, P_MAX_ELEMENT_DEPTH + " is {0}", maxElementDepth);
        }
    }

    if (xif.isPropertySupported(P_MAX_ELEMENT_COUNT)) {
        maxElementCount = Long.valueOf(buildLongValue(
            PROPERTY_MAX_ELEMENT_COUNT, DEFAULT_MAX_ELEMENT_COUNT)
        );
        xif.setProperty(P_MAX_ELEMENT_COUNT, maxElementCount);
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, P_MAX_ELEMENT_COUNT + " is {0}", maxElementCount);
        }
    }

    if (xif.isPropertySupported(P_MAX_CHARACTERS)) {
        maxCharacters = Long.valueOf(buildLongValue(
            PROPERTY_MAX_CHARACTERS, DEFAULT_MAX_CHARACTERS)
        );
        xif.setProperty(P_MAX_CHARACTERS, maxCharacters);
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, P_MAX_CHARACTERS + " is {0}", maxCharacters);
        }
    }
}
 
Example 19
Source File: XMLEditor.java    From MusicPlayer with MIT License 4 votes vote down vote up
private static int xmlNewLastIdAssignedFinder() {
try {
	// Creates reader for xml file.
	XMLInputFactory factory = XMLInputFactory.newInstance();
	factory.setProperty("javax.xml.stream.isCoalescing", true);
	FileInputStream is = new FileInputStream(new File(Resources.JAR + "library.xml"));
	XMLStreamReader reader = factory.createXMLStreamReader(is, "UTF-8");
	
	String element = null;
	String location;
	
	String currentSongId = null;
	String xmlNewLastIdAssigned = null;
	
	// Loops through xml file looking for the music directory file path.
	while(reader.hasNext()) {
	    reader.next();
	    if (reader.isWhiteSpace()) {
	        continue;
	    } else if (reader.isStartElement()) {
	    	element = reader.getName().getLocalPart();
	    } else if (reader.isCharacters() && element.equals("id")) {
	    	currentSongId = reader.getText();
	    } else if (reader.isCharacters() && element.equals("location")) {
	    	location = reader.getText();
	    	// If the current location is does not correspond to one of the files to be deleted,
	    	// then the current id is assigned as the newLastIdAssigned.
	    	if (!songPathsToDelete.contains(location)) {
	    		xmlNewLastIdAssigned = currentSongId;
	    	}
	    } else if (reader.isEndElement() && reader.getName().getLocalPart().equals("songs")) {
	    	break;
	    }
	}
	// Closes xml reader.
	reader.close();
	
	// Converts the file number to an int and returns the value. 
	return Integer.parseInt(xmlNewLastIdAssigned);
} catch (Exception e) {
	e.printStackTrace();
	return 0;
}
  }
 
Example 20
Source File: Bug6509774.java    From openjdk-jdk9 with GNU General Public License v2.0 2 votes vote down vote up
@Test
public void test2() {

    try {

        XMLInputFactory xif = XMLInputFactory.newInstance();

        xif.setProperty("javax.xml.stream.supportDTD", Boolean.FALSE);

        XMLStreamReader xsr = xif.createXMLStreamReader(

        getClass().getResource("sgml-bad-systemId.xml").toString(),

        getClass().getResourceAsStream("sgml-bad-systemId.xml"));

        Assert.assertTrue(xsr.getEventType() == XMLStreamConstants.START_DOCUMENT);

        int event = xsr.next();

        // Should not be a DTD event since they are ignored

        Assert.assertTrue(event == XMLStreamConstants.DTD);

        while (xsr.hasNext()) {

            event = xsr.next();

        }

        Assert.assertTrue(event == XMLStreamConstants.END_DOCUMENT);

        xsr.close();

    }

    catch (Exception e) {

        // Bogus systemId in XML document should not result in exception

        Assert.fail(e.getMessage());

    }

}