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

The following examples show how to use javax.xml.stream.XMLInputFactory#newFactory() . 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: JAXBHelper.java    From entando-components with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Unmarshal the entity given its representation
 * @param source streamSource object describing the entity
 * @param expected the expected result class
 * @param hasRoot
 * @param isJson
 * @return
 * @throws Throwable
 */
public static Object unmarshall(StreamSource source, Class<?> expected, boolean hasRoot, boolean isJson) throws Throwable {
  Object obj = null;
  JAXBContext jaxbContext = JAXBContext.newInstance(expected);
  Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

  if (null != source && null != expected) {
    // JSON
    if (isJson) {
      jaxbUnmarshaller.setProperty(JAXBContextProperties.JSON_INCLUDE_ROOT,
              hasRoot);
      jaxbUnmarshaller.setProperty(JAXBContextProperties.MEDIA_TYPE,
              "application/json");
      obj = jaxbUnmarshaller.unmarshal(source, expected).getValue();
    } else {
      // XML
      XMLInputFactory xif = XMLInputFactory.newFactory();
      xif.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false);
      XMLStreamReader xsr = xif.createXMLStreamReader(source);

       obj = jaxbUnmarshaller.unmarshal(xsr);
    }
  }
  return obj;
}
 
Example 2
Source File: XmlProcessBase.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 默认转换将指定的xml转化为
* 方法描述
* @param inputStream
* @param fileName
* @return
* @throws JAXBException
* @throws XMLStreamException
* @创建日期 2016年9月16日
*/
public Object baseParseXmlToBean(String fileName) throws JAXBException, XMLStreamException {
    // 搜索当前转化的文件
    InputStream inputStream = XmlProcessBase.class.getResourceAsStream(fileName);

    // 如果能够搜索到文件
    if (inputStream != null) {
        // 进行文件反序列化信息
        XMLInputFactory xif = XMLInputFactory.newFactory();
        xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
        XMLStreamReader xmlRead = xif.createXMLStreamReader(new StreamSource(inputStream));

        return unmarshaller.unmarshal(xmlRead);
    }

    return null;
}
 
Example 3
Source File: MetaMapConceptProvider.java    From bioasq with Apache License 2.0 5 votes vote down vote up
MetaMapConceptProvider(String version, String username, String password, String email,
        boolean silentOnError, int priority) throws ResourceInitializationException {
  conf = createConf(version, username, password, email, silentOnError, priority);
  xmlInputFactory = XMLInputFactory.newFactory();
  try {
    transformer = new TransformerFactoryImpl().newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "no");
    unmarshaller = JAXBContext.newInstance(MetaMapObject.class).createUnmarshaller();
  } catch (TransformerConfigurationException | JAXBException e) {
    throw new ResourceInitializationException();
  }
}
 
Example 4
Source File: XmlUtils.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
public static XMLStreamReader createSafeReader(StreamSource source) throws XMLStreamException {
    if (source == null) {
        throw new IllegalArgumentException("The provided source cannot be null");
    }

    XMLInputFactory xif = XMLInputFactory.newFactory();
    xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
    xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
    return xif.createXMLStreamReader(source);
}
 
Example 5
Source File: XmlProcessBase.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
/**
 * baseParseXmlToBean
 *
 * @param fileName
 * @return
 * @throws JAXBException
 * @throws XMLStreamException
 * @Created 2016/9/16
 */
public Object baseParseXmlToBean(String fileName) throws JAXBException, XMLStreamException {
    InputStream inputStream = ResourceUtil.getResourceAsStreamFromRoot(fileName);
    if (inputStream != null) {
        XMLInputFactory xif = XMLInputFactory.newFactory();
        xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
        XMLStreamReader xmlRead = xif.createXMLStreamReader(new StreamSource(inputStream));
        return unmarshaller.unmarshal(xmlRead);
    }

    return null;
}
 
Example 6
Source File: NodeConverter.java    From java-client-api with Apache License 2.0 5 votes vote down vote up
static private XMLInputFactory getXMLInputFactory() {
   // okay if one thread overwrites another during lazy initialization
   if (xmlInputFactory == null) {
      xmlInputFactory = XMLInputFactory.newFactory();
   }
   return xmlInputFactory;
}
 
Example 7
Source File: XmlUtils.java    From nifi with Apache License 2.0 5 votes vote down vote up
public static XMLStreamReader createSafeReader(StreamSource source) throws XMLStreamException {
    if (source == null) {
        throw new IllegalArgumentException("The provided source cannot be null");
    }

    XMLInputFactory xif = XMLInputFactory.newFactory();
    xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
    xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
    return xif.createXMLStreamReader(source);
}
 
Example 8
Source File: XACMLResponse.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
public XACMLResponse(String response, ValueFactory vf, JAXBContext jaxbContext) {
    this.jaxbContext = jaxbContext;
    try {
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        final XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
        final Reader reader = new StringReader(response);
        final XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(reader);
        this.responseType = unmarshaller.unmarshal(xmlStreamReader, ResponseType.class).getValue();
    } catch (JAXBException | XMLStreamException e) {
        throw new MobiException(e);
    }
    of = new ObjectFactory();

    ResultType resultType = this.responseType.getResult().get(0);
    setDecision(resultType.getDecision());
    StatusType statusType = resultType.getStatus();
    setStatus(statusType.getStatusCode().getValue());
    this.statusMessage = statusType.getStatusMessage() == null ? "" : statusType.getStatusMessage();
    PolicyIdentifierListType policyIdentifierListType = resultType.getPolicyIdentifierList();
    if (policyIdentifierListType != null) {
        this.policyIds = policyIdentifierListType.getPolicyIdReferenceOrPolicySetIdReference().stream()
                .map(idReferenceTypeJAXBElement -> vf.createIRI(idReferenceTypeJAXBElement.getValue().getValue()))
                .collect(Collectors.toList());
    } else {
        this.policyIds = new ArrayList<>();
    }
}
 
Example 9
Source File: XmlTransformer.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private static XMLInputFactory createInputFactory() throws FactoryConfigurationError {
  // Prevent XXE attacks.
  XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
  xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
  xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
  return xmlInputFactory;
}
 
Example 10
Source File: TopologyMarshaller.java    From knox with Apache License 2.0 5 votes vote down vote up
@Override
public Topology readFrom(Class<Topology>                type,
                         Type                           genericType,
                         Annotation[]                   annotations,
                         MediaType                      mediaType,
                         MultivaluedMap<String, String> httpHeaders,
                         InputStream                    entityStream) throws IOException, WebApplicationException {
  Topology topology = null;

  try {
    if (isReadable(type, genericType, annotations, mediaType)) {
      Map<String, Object> properties = Collections.emptyMap();
      JAXBContext context = JAXBContext.newInstance(new Class[]{Topology.class}, properties);

      Unmarshaller u = context.createUnmarshaller();
      u.setProperty(UnmarshallerProperties.MEDIA_TYPE, mediaType.getType() + "/" + mediaType.getSubtype());

      if (mediaType.isCompatible(MediaType.APPLICATION_XML_TYPE)) {
        // Safeguard against entity injection (KNOX-1308)
        XMLInputFactory xif = XMLInputFactory.newFactory();
        xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
        xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
        xif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false);
        XMLStreamReader xsr = xif.createXMLStreamReader(new StreamSource(entityStream));
        topology = (Topology) u.unmarshal(xsr);
      } else {
        topology = (Topology) u.unmarshal(entityStream);
      }
    }
  } catch (XMLStreamException | JAXBException e) {
    throw new IOException(e);
  }

  return topology;
}
 
Example 11
Source File: XMLInputFactoryNewInstanceTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Test if newDefaultFactory() method returns an instance
 * of the expected factory.
 * @throws Exception If any errors occur.
 */
@Test
public void testDefaultInstance() throws Exception {
    XMLInputFactory if1 = XMLInputFactory.newDefaultFactory();
    XMLInputFactory if2 = XMLInputFactory.newFactory();
    assertNotSame(if1, if2, "same instance returned:");
    assertSame(if1.getClass(), if2.getClass(),
              "unexpected class mismatch for newDefaultFactory():");
    assertEquals(if1.getClass().getName(), DEFAULT_IMPL_CLASS);
}
 
Example 12
Source File: EppXmlSanitizer.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private static XMLInputFactory createXmlInputFactory() {
  XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
  // Coalesce adjacent data, so that all chars in a string will be grouped as one item.
  xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, true);
  // Preserve Name Space information.
  xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true);
  return xmlInputFactory;
}
 
Example 13
Source File: BugTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Verifies that the initial event of an XMLStreamReader instance is
 * START_DOCUMENT.
 *
 * @param xml the xml input
 * @param type1 the type of the 1st event
 * @param type2 the type of the 2nd event
 * @throws Exception if the test fails to run properly
 */
@Test(dataProvider = "xmls")
public static void test1(String xml, int type1, int type2) throws Exception {
   XMLInputFactory factory = XMLInputFactory.newFactory();

   XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(xml));
   int type1stEvent = reader.getEventType();
   int type2ndEvent = reader.next();
   System.out.println("First event: " + type1stEvent);
   System.out.println("2nd event: " + type2ndEvent);
   Assert.assertEquals(type1, type1stEvent);
   Assert.assertEquals(type2, type2ndEvent);
}
 
Example 14
Source File: XMLInputFactoryProvider.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("deprecation")
public XMLInputFactory get() {
    //ugly, but must be done
    System.setProperty(INPUT_FACTORY_INTERFACE, FACTORY_CLASS);

    // NOTE: In case the newFactory(String, ClassLoader) is used,
    //       the given class loader is ignored if the system property is set!
    return XMLInputFactory.newFactory();
}
 
Example 15
Source File: StaxHelper.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a new StAX XMLInputFactory, with sensible defaults
 */
public static XMLInputFactory newXMLInputFactory() {
    XMLInputFactory factory = XMLInputFactory.newFactory();
    trySetProperty(factory, XMLInputFactory.IS_NAMESPACE_AWARE, true);
    trySetProperty(factory, XMLInputFactory.IS_VALIDATING, false);
    trySetProperty(factory, XMLInputFactory.SUPPORT_DTD, false);
    trySetProperty(factory, XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
    return factory;
}
 
Example 16
Source File: JaxbEngine.java    From pippo with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new instance of the factory with some configurations.
 *
 * @return the factory implementation
 *
 * @see XMLInputFactory#newFactory()
 */
protected XMLInputFactory buildXMLInputFactory() {
    XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();

    xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
    xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);

    return xmlInputFactory;
}
 
Example 17
Source File: XMLInputFactoryNewInstanceTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions = NullPointerException.class, dataProvider = "new-instance-neg", dataProviderClass = JAXPDataProvider.class)
public void testNewFactoryNeg(String factoryId, ClassLoader classLoader) {
    XMLInputFactory.newFactory(factoryId, classLoader);
}
 
Example 18
Source File: ServerConfigurationManagerImpl.java    From java-client-api with Apache License 2.0 4 votes vote down vote up
@Override
public void readConfiguration()
  throws ForbiddenUserException, FailedRequestException {
  try {
    if (logger.isInfoEnabled())
      logger.info("Reading server configuration");

    InputStream stream = services.getValues(null, "config/properties", "application/xml", InputStream.class);
    if (stream == null)
      return;

    XMLInputFactory factory = XMLInputFactory.newFactory();
    factory.setProperty("javax.xml.stream.isNamespaceAware", true);
    factory.setProperty("javax.xml.stream.isValidating",     false);

    XMLStreamReader reader = factory.createXMLStreamReader(stream);

    validatingQueries               = null;
    validatingQueryOptions          = null;
    defaultDocumentReadTransform    = null;
    defaultDocumentReadTransformAll = null;
    serverRequestLogging            = null;
    contentVersions                 = null;
    updatePolicy                    = null;

    while (reader.hasNext()) {
      if (reader.next() != XMLStreamReader.START_ELEMENT)
        continue;

      String localName = reader.getLocalName();
      if ("validate-queries".equals(localName)) {
        validatingQueries = Boolean.valueOf(reader.getElementText());
      } else if ("validate-options".equals(localName)) {
        validatingQueryOptions = Boolean.valueOf(reader.getElementText());
      } else if ("document-transform-out".equals(localName)) {
        defaultDocumentReadTransform = reader.getElementText();
      } else if ("document-transform-all".equals(localName)) {
        defaultDocumentReadTransformAll = Boolean.valueOf(reader.getElementText());
      } else if ("debug".equals(localName)) {
        serverRequestLogging = Boolean.valueOf(reader.getElementText());
      } else if ("content-versions".equals(localName)) {
        contentVersions = Enum.valueOf(Policy.class, reader.getElementText().toUpperCase());
      } else if ("update-policy".equals(localName)) {
        updatePolicy = Enum.valueOf(UpdatePolicy.class,
          reader.getElementText().toUpperCase().replace("-", "_"));
      }
    }

    reader.close();

    if (contentVersions == null) {
      updatePolicyToContentVersion();
    } else if (updatePolicy == null) {
      contentVersionToUpdatePolicy();
    }
  } catch (XMLStreamException e) {
    logger.error("Failed to read server configuration stream",e);
    throw new MarkLogicInternalException(e);
  }
}
 
Example 19
Source File: AbstractJaxbFacade.java    From dss with GNU Lesser General Public License v2.1 4 votes vote down vote up
private XMLStreamReader avoidXXE(Source source) throws XMLStreamException {
	XMLInputFactory xif = XMLInputFactory.newFactory();
	xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
	xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
	return xif.createXMLStreamReader(source);
}
 
Example 20
Source File: RuleToXmlConverter.java    From yare with MIT License 4 votes vote down vote up
private XMLInputFactory getXmlInputFactory() {
    XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
    xmlInputFactory.setProperty(IS_SUPPORTING_EXTERNAL_ENTITIES, FALSE);
    xmlInputFactory.setProperty(SUPPORT_DTD, FALSE);
    return xmlInputFactory;
}