javax.xml.parsers.ParserConfigurationException Java Examples

The following examples show how to use javax.xml.parsers.ParserConfigurationException. 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: XercesParser.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a <code>SAXParser</code> based on the underlying
 * <code>Xerces</code> version.
 * @param properties parser specific properties/features
 * @return an XML Schema/DTD enabled <code>SAXParser</code>
 */
public static SAXParser newSAXParser(Properties properties) 
        throws ParserConfigurationException, 
               SAXException,
               SAXNotSupportedException {

    SAXParserFactory factory =  
                    (SAXParserFactory)properties.get("SAXParserFactory");

    if (versionNumber == null){
        versionNumber = getXercesVersion();
        version = new Float( versionNumber ).floatValue();
    }

    // Note: 2.2 is completely broken (with XML Schema). 
    if (version > 2.1) {

        configureXerces(factory);
        return factory.newSAXParser();
    } else {
        SAXParser parser = factory.newSAXParser();
        configureOldXerces(parser,properties);
        return parser;
    }
}
 
Example #2
Source File: XPathImplUtil.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Parse the input source and return a Document.
 * @param source The {@code InputSource} of the document
 * @return a DOM Document
 * @throws XPathExpressionException if there is an error parsing the source.
 */
Document getDocument(InputSource source)
    throws XPathExpressionException {
    requireNonNull(source, "Source");
    try {
        // we'd really like to cache those DocumentBuilders, but we can't because:
        // 1. thread safety. parsers are not thread-safe, so at least
        //    we need one instance per a thread.
        // 2. parsers are non-reentrant, so now we are looking at having a
        // pool of parsers.
        // 3. then the class loading issue. The look-up procedure of
        //    DocumentBuilderFactory.newInstance() depends on context class loader
        //    and system properties, which may change during the execution of JVM.
        //
        // so we really have to create a fresh DocumentBuilder every time we need one
        // - KK
        DocumentBuilderFactory dbf = JdkXmlUtils.getDOMFactory(overrideDefaultParser);
        return dbf.newDocumentBuilder().parse(source);
    } catch (ParserConfigurationException | SAXException | IOException e) {
        throw new XPathExpressionException (e);
    }
}
 
Example #3
Source File: DataUtils.java    From BuildmLearn-Toolkit-Android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static String[] readTitleAuthor() {
    String result[] = new String[2];
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setValidating(false);

    DocumentBuilder db;
    Document doc;
    try {
        File fXmlFile = new File(org.buildmlearn.toolkit.flashcardtemplate.Constants.XMLFileName);
        db = dbf.newDocumentBuilder();
        doc = db.parse(fXmlFile);
        doc.normalize();

        result[0] = doc.getElementsByTagName("title").item(0).getChildNodes()
                .item(0).getNodeValue();

        result[1] = doc.getElementsByTagName("name").item(0).getChildNodes()
                .item(0).getNodeValue();

    } catch (ParserConfigurationException | SAXException | IOException e) {
        e.printStackTrace();
    }
    return result;
}
 
Example #4
Source File: XMLSignatureInput.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the node set from input which was specified as the parameter of
 * {@link XMLSignatureInput} constructor
 * @param circumvent
 *
 * @return the node set
 * @throws SAXException
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws CanonicalizationException
 */
public Set<Node> getNodeSet(boolean circumvent) throws ParserConfigurationException,
    IOException, SAXException, CanonicalizationException {
    if (inputNodeSet != null) {
        return inputNodeSet;
    }
    if (inputOctetStreamProxy == null && subNode != null) {
        if (circumvent) {
            XMLUtils.circumventBug2650(XMLUtils.getOwnerDocument(subNode));
        }
        inputNodeSet = new LinkedHashSet<Node>();
        XMLUtils.getSet(subNode, inputNodeSet, excludeNode, excludeComments);
        return inputNodeSet;
    } else if (isOctetStream()) {
        convertToNodes();
        Set<Node> result = new LinkedHashSet<Node>();
        XMLUtils.getSet(subNode, result, null, false);
        return result;
    }

    throw new RuntimeException("getNodeSet() called but no input data present");
}
 
Example #5
Source File: MapSettings.java    From megamek with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates and returns a new instance of MapSettings with default values
 * loaded from the given input stream.
 * 
 * @param is
 *            the input stream that contains an XML representation of the
 *            map settings
 * @return a MapSettings with the values from XML
 */
public static MapSettings getInstance(final InputStream is) {
    MapSettings ms = null;

    try {
        JAXBContext jc = JAXBContext.newInstance(MapSettings.class);

        Unmarshaller um = jc.createUnmarshaller();
        ms = (MapSettings) um.unmarshal(MegaMekXmlUtil.createSafeXmlSource(is));
    } catch (JAXBException | SAXException | ParserConfigurationException ex) {
        System.err.println("Error loading XML for map settings: " + ex.getMessage()); //$NON-NLS-1$
        ex.printStackTrace();
    }

    return ms;
}
 
Example #6
Source File: EntryParserImplTest.java    From google-sites-liberation with Apache License 2.0 6 votes vote down vote up
@Before
public void before() {
  context = new JUnit4Mockery() {{
    setImposteriser(ClassImposteriser.INSTANCE);
  }};
  authorParser = context.mock(AuthorParser.class);
  contentParser = context.mock(ContentParser.class);
  dataParser = context.mock(DataParser.class);
  fieldParser = context.mock(FieldParser.class);
  summaryParser = context.mock(SummaryParser.class);
  titleParser = context.mock(TitleParser.class);
  updatedParser = context.mock(UpdatedParser.class);
  entryParser = new EntryParserImpl(authorParser, contentParser, dataParser,
      fieldParser, summaryParser, titleParser, 
      updatedParser);
  try {
    document = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder().newDocument();
  } catch (ParserConfigurationException e) {
    fail("Failure to create test document");
  }
}
 
Example #7
Source File: InflatableData.java    From InflatableDonkey with MIT License 6 votes vote down vote up
public static Optional<InflatableData> from(byte[] bs) {
    InflatableData data;
    try {
        NSDictionary parse = (NSDictionary) PropertyListParser.parse(bs);
        byte[] escrowedKeys = ((NSData) parse.get("escrowedKeys")).bytes();
        UUID deviceUuid = UUID.fromString(((NSString) parse.get("deviceUuid")).getContent());
        String deviceHardWareId = ((NSString) parse.get("deviceHardWareId")).getContent();
        data = new InflatableData(escrowedKeys, deviceUuid, deviceHardWareId);

    } catch (ClassCastException | IllegalArgumentException | IOException | NullPointerException
            | PropertyListFormatException | ParseException | ParserConfigurationException | SAXException ex) {
        logger.warn("-- from() - exception: ", ex);
        data = null;
    }
    return Optional.ofNullable(data);
}
 
Example #8
Source File: JUnitXMLParser.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public JUnitResultData parseXmlFile(File xmlFile){
  this.xmlFile = xmlFile;
  //get the factory
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  JUnitResultData returnResultsForFile = null;
  try {

    //Using factory get an instance of document builder
    DocumentBuilder db = dbf.newDocumentBuilder();

    //parse using builder to get DOM representation of the XML file
    dom = db.parse(xmlFile);
    returnResultsForFile = parseDocument();
    returnResultsForFile.setJunitResultfile(xmlFile);

  }catch(ParserConfigurationException pce) {
    pce.printStackTrace();
  }catch(SAXException se) {
    se.printStackTrace();
  }catch(IOException ioe) {
    ioe.printStackTrace();
  }
  return returnResultsForFile;
}
 
Example #9
Source File: Prd3431IT.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void testAsXmlOutput() throws ResourceException, ReportProcessingException, IOException, SAXException,
  ParserConfigurationException {
  final URL url = getClass().getResource( "Prd-3431.prpt" );
  assertNotNull( url );
  final ResourceManager resourceManager = new ResourceManager();
  resourceManager.registerDefaults();
  final Resource directly = resourceManager.createDirectly( url, MasterReport.class );
  final MasterReport report = (MasterReport) directly.getResource();
  final MemoryByteArrayOutputStream mbos = new MemoryByteArrayOutputStream();
  XmlTableReportUtil.createFlowXML( report, new NoCloseOutputStream( mbos ) );

  final ByteArrayInputStream bin = new ByteArrayInputStream( mbos.getRaw(), 0, mbos.getLength() );
  final DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
  final Document document = documentBuilder.parse( bin );
  final NodeList table = document.getDocumentElement().getElementsByTagName( "table" );
  assertSheetName( (Element) table.item( 0 ), "Summary" );
  assertSheetName( (Element) table.item( 1 ), "AuthorPublisher A" );
  assertSheetName( (Element) table.item( 2 ), "AuthorPublisher B" );
  assertSheetName( (Element) table.item( 3 ), "AuthorPublisher C" );
}
 
Example #10
Source File: ConfigurationRequestConverter.java    From c2mon with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Create an XML string representation of the ProcessConnectionRequest object.
 * @throws ParserConfigurationException if exception occurs in XML parser
 * @throws TransformerException if exception occurs in XML parser
 * @param configurationRequest the request object to convert to XML
 * @return XML as String
 */
public synchronized String toXML(final ConfigurationRequest configurationRequest) throws ParserConfigurationException, TransformerException {
  DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
  DocumentBuilder builder = builderFactory.newDocumentBuilder();
  Document dom = builder.newDocument();
  Element rootElt = dom.createElement(CONFIGURATION_XML_ROOT);
  rootElt.setAttribute(CONFIGURATION_ID_ATTRIBUTE, Integer.toString(configurationRequest.getConfigId()));
  dom.appendChild(rootElt);

  TransformerFactory transformerFactory = TransformerFactory.newInstance();
  Transformer transformer = transformerFactory.newTransformer();
  StringWriter writer = new StringWriter();
  Result result = new StreamResult(writer);
  Source source = new DOMSource(dom);
  transformer.transform(source, result);
  return writer.getBuffer().toString();

}
 
Example #11
Source File: JAXBConfigImpl.java    From rice with Educational Community License v2.0 6 votes vote down vote up
protected org.kuali.rice.core.impl.config.property.Config unmarshal(Unmarshaller unmarshaller, InputStream in)
        throws SAXException, ParserConfigurationException, IOException,
        IllegalStateException, JAXBException {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);

    XMLFilter filter = new ConfigNamespaceURIFilter();
    filter.setParent(spf.newSAXParser().getXMLReader());

    UnmarshallerHandler handler = unmarshaller.getUnmarshallerHandler();
    filter.setContentHandler(handler);

    filter.parse(new InputSource(in));

    return (org.kuali.rice.core.impl.config.property.Config) handler.getResult();
}
 
Example #12
Source File: JaxRsStackSupportImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private DocumentBuilder getDocumentBuilder() {
    DocumentBuilder builder = null;

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(false);
    factory.setIgnoringComments(false);
    factory.setIgnoringElementContentWhitespace(false);
    factory.setCoalescing(false);
    factory.setExpandEntityReferences(false);
    factory.setValidating(false);

    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
        Exceptions.printStackTrace(ex);
    }

    return builder;
}
 
Example #13
Source File: DocumentBuilderFactoryImpl.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a new instance of a {@link javax.xml.parsers.DocumentBuilder}
 * using the currently configured parameters.
 */
public DocumentBuilder newDocumentBuilder()
    throws ParserConfigurationException
{
    /** Check that if a Schema has been specified that neither of the schema properties have been set. */
    if (grammar != null && attributes != null) {
        if (attributes.containsKey(JAXPConstants.JAXP_SCHEMA_LANGUAGE)) {
            throw new ParserConfigurationException(
                    SAXMessageFormatter.formatMessage(null,
                    "schema-already-specified", new Object[] {JAXPConstants.JAXP_SCHEMA_LANGUAGE}));
        }
        else if (attributes.containsKey(JAXPConstants.JAXP_SCHEMA_SOURCE)) {
            throw new ParserConfigurationException(
                    SAXMessageFormatter.formatMessage(null,
                    "schema-already-specified", new Object[] {JAXPConstants.JAXP_SCHEMA_SOURCE}));
        }
    }

    try {
        return new DocumentBuilderImpl(this, attributes, features, fSecureProcess);
    } catch (SAXException se) {
        // Handles both SAXNotSupportedException, SAXNotRecognizedException
        throw new ParserConfigurationException(se.getMessage());
    }
}
 
Example #14
Source File: DOMHelper.java    From xades4j with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static Element createElementInTempDocument(
        String name,
        String prefix,
        String namespaceURI)
{
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    try
    {
        Document doc = dbf.newDocumentBuilder().newDocument();
        return createElement(doc, name, prefix, namespaceURI);
    } catch (ParserConfigurationException ex)
    {
        return null;
    }
}
 
Example #15
Source File: DependencyServiceImpl.java    From score with Apache License 2.0 6 votes vote down vote up
private void removeByXpathExpression(String pomFilePath, String expression) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException, TransformerException {
    File xmlFile = new File(pomFilePath);
    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);
    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList nl = (NodeList) xpath.compile(expression).
            evaluate(doc, XPathConstants.NODESET);

    if (nl != null && nl.getLength() > 0) {
        for (int i = 0; i < nl.getLength(); i++) {
            Node node = nl.item(i);
            node.getParentNode().removeChild(node);
        }

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        // need to convert to file and then to path to override a problem with spaces
        Result output = new StreamResult(new File(pomFilePath).getPath());
        Source input = new DOMSource(doc);
        transformer.transform(input, output);
    }
}
 
Example #16
Source File: PDFDomTree.java    From Pdf2Dom with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Creates a new PDF DOM parser.
 * @throws IOException
 * @throws ParserConfigurationException
 */
public PDFDomTree(PDFDomTreeConfig config) throws IOException, ParserConfigurationException
{
    this();
    if (config != null)
        this.config = config;
}
 
Example #17
Source File: DocViewFormat.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
/** internally formats the given file and computes their checksum
 * 
 * @param file the file
 * @param original checksum of the original file
 * @param formatted checksum of the formatted file
 * @return the formatted bytes
 * @throws IOException if an error occurs */
private byte[] format(File file, Checksum original, Checksum formatted) throws IOException {
    try (InputStream in = new CheckedInputStream(new BufferedInputStream(new FileInputStream(file)), original)) {
        @SuppressWarnings("resource")
        ByteArrayOutputStream buffer = formattingBuffer != null ? formattingBuffer.get() : null;
        if (buffer == null) {
            buffer = new ByteArrayOutputStream();
            formattingBuffer = new WeakReference<>(buffer);
        } else {
            buffer.reset();
        }

        try (OutputStream out = new CheckedOutputStream(buffer, formatted);
             FormattingXmlStreamWriter writer = FormattingXmlStreamWriter.create(out, format)) {
            // cannot use XMlStreamReader due to comment handling:
            // https://stackoverflow.com/questions/15792007/why-does-xmlstreamreader-staxsource-strip-comments-from-xml
            TransformerFactory tf = TransformerFactory.newInstance();
            tf.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
            SAXSource saxSource = new SAXSource(new InputSource(in));
            SAXParserFactory sf = SAXParserFactory.newInstance();
            sf.setNamespaceAware(true);
            sf.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
            sf.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
            saxSource.setXMLReader(new NormalizingSaxFilter(sf.newSAXParser().getXMLReader()));
            Transformer t = tf.newTransformer();
            StAXResult result = new StAXResult(writer);
            t.transform(saxSource, result);
        }
        return buffer.toByteArray();
    } catch (TransformerException | XMLStreamException | FactoryConfigurationError | ParserConfigurationException | SAXException ex) {
        throw new IOException(ex);
    }
}
 
Example #18
Source File: MarkLogicNode.java    From marklogic-contentpump with Apache License 2.0 5 votes vote down vote up
@Override protected DocumentBuilder initialValue() {
    try {
        return 
        DocumentBuilderFactory.newInstance().newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        LOG.error(e);
        return null;
    } 
}
 
Example #19
Source File: DocumentBuilderProvider.java    From sawmill with Apache License 2.0 5 votes vote down vote up
public DocumentBuilderProvider() {
    localDocumentBuilder = ThreadLocal.withInitial(() -> {
        try {
            return DocumentBuilderFactory.newInstance().newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            throw new ProcessorConfigurationException("failed to create document builder", e);
        }
    });
}
 
Example #20
Source File: JarPackageReader.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public JarPackageData readXML(JarPackageData jarPackage) throws IOException, SAXException {
  	DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
   	factory.setValidating(false);
	DocumentBuilder parser= null;

	try {
		parser= factory.newDocumentBuilder();
	} catch (ParserConfigurationException ex) {
		throw new IOException(ex.getLocalizedMessage());
	} finally {
		// Note: Above code is OK since clients are responsible to close the stream
	}
	parser.setErrorHandler(new DefaultHandler());
	Element xmlJarDesc= parser.parse(new InputSource(fInputStream)).getDocumentElement();
	if (!xmlJarDesc.getNodeName().equals(JarPackagerUtil.DESCRIPTION_EXTENSION)) {
		throw new IOException(JarPackagerMessages.JarPackageReader_error_badFormat);
	}
	NodeList topLevelElements= xmlJarDesc.getChildNodes();
	for (int i= 0; i < topLevelElements.getLength(); i++) {
		Node node= topLevelElements.item(i);
		if (node.getNodeType() != Node.ELEMENT_NODE)
			continue;
		Element element= (Element)node;
		xmlReadJarLocation(jarPackage, element);
		xmlReadOptions(jarPackage, element);
		xmlReadRefactoring(jarPackage, element);
		xmlReadSelectedProjects(jarPackage, element);
		if (jarPackage.areGeneratedFilesExported())
			xmlReadManifest(jarPackage, element);
		xmlReadSelectedElements(jarPackage, element);
	}
	return jarPackage;
}
 
Example #21
Source File: BaseXMLSerializer.java    From mq-http-java-sdk with MIT License 5 votes vote down vote up
protected DocumentBuilder getDocmentBuilder() throws ParserConfigurationException {
    DocumentBuilder db = sps.get();
    if (db == null) {
        db = factory.newDocumentBuilder();
        sps.set(db);
    }
    return db;
}
 
Example #22
Source File: XmlUtil.java    From cerberus-source with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns a new {@link Document} instance from the default
 * {@link DocumentBuilder}
 *
 * @return a new {@link Document} instance from the default
 * {@link DocumentBuilder}
 * @throws XmlUtilException if an error occurred
 */
public static Document newDocument() throws XmlUtilException {
    try {
        DocumentBuilderFactory resultDocFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder resultDocBuilder = resultDocFactory.newDocumentBuilder();
        return resultDocBuilder.newDocument();
    } catch (ParserConfigurationException e) {
        throw new XmlUtilException(e);
    }
}
 
Example #23
Source File: EmbeddedSolrServerFactory.java    From dubbox with Apache License 2.0 5 votes vote down vote up
/**
 * @param path
 *            Any Path expression valid for use with
 *            {@link org.springframework.util.ResourceUtils}
 * @return new instance of
 *         {@link org.apache.solr.client.solrj.embedded.EmbeddedSolrServer}
 * @throws javax.xml.parsers.ParserConfigurationException
 * @throws java.io.IOException
 * @throws org.xml.sax.SAXException
 */
public final EmbeddedSolrServer createPathConfiguredSolrServer(String path)
		throws ParserConfigurationException, IOException, SAXException {
	String solrHomeDirectory = System.getProperty(SOLR_HOME_SYSTEM_PROPERTY);

	if (StringUtils.isBlank(solrHomeDirectory)) {
		solrHomeDirectory = ResourceUtils.getURL(path).getPath();
	}

	solrHomeDirectory = URLDecoder.decode(solrHomeDirectory, "utf-8");
	return new EmbeddedSolrServer(createCoreContainer(solrHomeDirectory), "collection1");
}
 
Example #24
Source File: AbstractTranslet.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public Document newDocument(String uri, String qname)
    throws ParserConfigurationException
{
    if (_domImplementation == null) {
        DocumentBuilderFactory dbf = FactoryImpl.getDOMFactory(_useServicesMechanism);
        _domImplementation = dbf.newDocumentBuilder().getDOMImplementation();
    }
    return _domImplementation.createDocument(uri, qname, null);
}
 
Example #25
Source File: Licenseinfo.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static Licenseinfo parse(File licenseinfo) throws IOException {
    try {
        Document doc = documentBuilderFactory.newDocumentBuilder().parse(licenseinfo);
        
        if(! "licenseinfo".equals(doc.getDocumentElement().getTagName())) {
            throw new IOException("Document Element is not licenseinfo");
        }
        return parse(licenseinfo, doc.getDocumentElement());
                    
    } catch (SAXException | ParserConfigurationException | RuntimeException ex) {
        throw new IOException(ex);
    }
}
 
Example #26
Source File: SecurityVerificationOutTest.java    From steady with Apache License 2.0 5 votes vote down vote up
private SoapMessage coachMessage(String policyName) 
    throws IOException, ParserConfigurationException, SAXException {
    Policy policy = policyBuilder.getPolicy(this.getResourceAsStream(policyName)); 
    AssertionInfoMap aim = new AssertionInfoMap(policy);
    SoapMessage message = control.createMock(SoapMessage.class);        
    EasyMock.expect(message.get(Message.REQUESTOR_ROLE)).andReturn(Boolean.TRUE);
    EasyMock.expect(message.get(AssertionInfoMap.class)).andReturn(aim);
    return message;
}
 
Example #27
Source File: FlickrPhotoGrabber.java    From liresolr with GNU General Public License v2.0 5 votes vote down vote up
public static List<FlickrPhoto> getRecentPhotos() throws IOException, SAXException, ParserConfigurationException {
    LinkedList<FlickrPhoto> photos = new LinkedList<FlickrPhoto>();
    URL u = new URL(BASE_URL);
    FlickrPhotoGrabber handler = new FlickrPhotoGrabber();
    SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
    saxParser.parse(u.openStream(), handler);
    return handler.photos;
}
 
Example #28
Source File: ConvertUserFavoriteSitesSakai11.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public PreferenceMigrator() {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

    try {
        documentBuilder = dbFactory.newDocumentBuilder();
        xpath = XPathFactory.newInstance().newXPath();
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
}
 
Example #29
Source File: Canonicalizer11.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
protected void circumventBugIfNeeded(XMLSignatureInput input)
    throws CanonicalizationException, ParserConfigurationException,
    IOException, SAXException {
    if (!input.isNeedsToBeExpanded()) {
        return;
    }
    Document doc = null;
    if (input.getSubNode() != null) {
        doc = XMLUtils.getOwnerDocument(input.getSubNode());
    } else {
        doc = XMLUtils.getOwnerDocument(input.getNodeSet());
    }
    XMLUtils.circumventBug2650(doc);
}
 
Example #30
Source File: ResXmlPatcher.java    From ratel with Apache License 2.0 5 votes vote down vote up
/**
 * Finds key in strings.xml file and returns text value
 *
 * @param directory Root directory of apk
 * @param key String reference (ie @string/foo)
 * @return String|null
 * @throws AndrolibException
 */
public static String pullValueFromStrings(File directory, String key) throws AndrolibException {
    if (key == null || ! key.contains("@")) {
        return null;
    }

    File file = new File(directory, "/res/values/strings.xml");
    key = key.replace("@string/", "");

    if (file.exists()) {
        try {
            Document doc = loadDocument(file);
            XPath xPath = XPathFactory.newInstance().newXPath();
            XPathExpression expression = xPath.compile("/resources/string[@name=" + '"' + key + "\"]/text()");

            Object result = expression.evaluate(doc, XPathConstants.STRING);

            if (result != null) {
                return (String) result;
            }

        }  catch (SAXException | ParserConfigurationException | IOException | XPathExpressionException ignored) {
        }
    }

    return null;
}