public void testWithDummyExtSubset() throws Exception { final String XML = "<!DOCTYPE root PUBLIC '//some//public//id' 'no-such-thing.dtd'>\n" + "<root />"; SAXParserFactoryImpl spf = new SAXParserFactoryImpl(); spf.setNamespaceAware(true); SAXParser sp = spf.newSAXParser(); DefaultHandler h = new DefaultHandler(); /* First: let's verify that we get an exception for * unresolved reference... */ try { sp.parse(new InputSource(new StringReader(XML)), h); } catch (SAXException e) { verifyException(e, "No such file or directory"); } // And then with dummy resolver; should work ok now sp = spf.newSAXParser(); sp.getXMLReader().setEntityResolver(new MyResolver(" ")); h = new DefaultHandler(); try { sp.parse(new InputSource(new StringReader(XML)), h); } catch (SAXException e) { fail( "Should not have failed with entity resolver, got (" + e.getClass() + "): " + e.getMessage()); } }
public List<Book> getBooks(InputStream xmlStream) throws Exception { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); SaxParseService handler = new SaxParseService(); parser.parse(xmlStream, handler); return handler.getBooks(); }
@Test public void test1() throws Exception { SAXParser parser = createParser(); parser.parse( Bug4991020.class.getResource("Bug4991020.xml").toExternalForm(), new util.DraconianErrorHandler()); }
/** * Uses PackInHandler to update AD. * * @param fileName xml file to read * @return status message */ public String importXML(String fileName, Properties ctx, String trxName) throws Exception { log.info("importXML:" + fileName); File in = new File(fileName); if (!in.exists()) { String msg = "File does not exist: " + fileName; log.info("importXML:" + msg); return msg; } try { log.info("starting"); System.setProperty( "javax.xml.parsers.SAXParserFactory", "org.apache.xerces.jaxp.SAXParserFactoryImpl"); PackInHandler handler = new PackInHandler(); handler.set_TrxName(trxName); handler.setCtx(ctx); handler.setProcess(this); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); String msg = "Start Parser"; log.info(msg); parser.parse(in, handler); msg = "End Parser"; log.info(msg); return "OK."; } catch (Exception e) { log.log(Level.SEVERE, "importXML:", e); throw e; } }
private void processCommentLines(File file) throws SAXException, IOException { SAXParser parser = newSaxParser(false); XMLReader xmlReader = parser.getXMLReader(); commentHandler = new CommentHandler(); xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", commentHandler); parser.parse(FileUtils.openInputStream(file), commentHandler); }
public static boolean compareXMLContent(final InputSource content1, final InputSource content2) throws ParserConfigurationException, SAXException, IOException { final SAXParserFactory parserFactory = SAXParserFactory.newInstance(); parserFactory.setNamespaceAware(true); parserFactory.setValidating(false); final SAXParser parser = parserFactory.newSAXParser(); final IdentitySAXHandler handler1 = new IdentitySAXHandler(); parser.parse(content1, handler1); final IdentitySAXHandler handler2 = new IdentitySAXHandler(); parser.parse(content2, handler2); return (handler1.getRootElement().equals(handler2.getRootElement())); }
/** * Does the actual parsing of a devices.xml file. * * @param deviceXml the {@link File} to load/parse. This must be an existing file. * @param list the list in which to write the parsed {@link LayoutDevice}. */ private void parseLayoutDevices(File deviceXml, List<LayoutDevice> list) { // first we validate the XML try { Source source = new StreamSource(new FileReader(deviceXml)); CaptureErrorHandler errorHandler = new CaptureErrorHandler(deviceXml.getAbsolutePath()); Validator validator = LayoutDevicesXsd.getValidator(errorHandler); validator.validate(source); if (errorHandler.foundError() == false) { // do the actual parsing LayoutDeviceHandler handler = new LayoutDeviceHandler(); SAXParser parser = mParserFactory.newSAXParser(); parser.parse(new InputSource(new FileInputStream(deviceXml)), handler); // get the parsed devices list.addAll(handler.getDevices()); } } catch (SAXException e) { AdtPlugin.log(e, "Error parsing %1$s", deviceXml.getAbsoluteFile()); } catch (FileNotFoundException e) { // this shouldn't happen as we check above. } catch (IOException e) { AdtPlugin.log(e, "Error reading %1$s", deviceXml.getAbsoluteFile()); } catch (ParserConfigurationException e) { AdtPlugin.log(e, "Error parsing %1$s", deviceXml.getAbsoluteFile()); } }
/** * @param filename * @param docs */ public void parse(String filename, Collection<WikipediaDocument> docs) { // System.out.println("::Parser::parse\nFilename=" + filename+ " Docs_size=" + docs.size()); if (filename == null || filename.isEmpty()) { return; } try { InputStreamReader inReader = new InputStreamReader(new FileInputStream(filename), "UTF-8"); BufferedReader reader = new BufferedReader(inReader); InputSource is = new InputSource(reader); is.setEncoding("UTF-8"); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser saxParser = spf.newSAXParser(); DefaultHandler handler = new XMLParser(docs); saxParser.parse(is, handler); } catch (IOException x) { System.err.println(x); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block System.out.println("Parsing Terminated"); e.printStackTrace(); } finally { } }
/** Responsible for parsing the document */ public ArrayList<String> parseDocument(URL url) { snippets.clear(); // Adds a factory SAXParserFactory factory = SAXParserFactory.newInstance(); try { // adds a new instance of parser SAXParser parser = factory.newSAXParser(); // TODO SHOULD THIS BE MOVED TO MORE PROPER PLACE? // Sets user Agent System.setProperty("http.agent", "ChaosPoemSearch"); // Stream xml to parser parser.parse(new InputSource(url.openStream()), this); } catch (SAXException se) { } catch (ParserConfigurationException pce) { } catch (ConnectException e) { } catch (IOException ie) { } return snippets; }
private void chargerPresentation(ZipInputStream projectZip) throws ParserConfigurationException, SAXException, IOException, FichierException { ZipEntry zipEntry = projectZip.getNextEntry(); while (zipEntry != null && !this.presentationTrouve) { DataInputStream data = new DataInputStream(new BufferedInputStream(projectZip)); if (zipEntry.getName().equals("Presentation.xml")) { this.presentationTrouve = true; this.print(Application.getApplication().getTraduction("SAX_initialisation")); // preparation du parsing SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxparser = factory.newSAXParser(); this.print(Application.getApplication().getTraduction("presentation_parsing")); PresentationHandler handler = new PresentationHandler(); saxparser.parse(data, handler); this.print(Application.getApplication().getTraduction("Presentation_charge")); } else { zipEntry = projectZip.getNextEntry(); } } projectZip.close(); if (!this.presentationTrouve) { throw new FichierException("Presentation"); } }
public static void main(String[] args) throws IOException, TasteException, SAXException, ParserConfigurationException { String docIdsTitle = "src/main/resources/docIdsTitles.xml"; long userId = 2; // Integer neighbors = Integer.parseInt(args[2]); InputSource is = new InputSource(new FileInputStream(docIdsTitle)); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(false); SAXParser sp = factory.newSAXParser(); WikiContentHandler handler = new WikiContentHandler(); sp.parse(is, handler); MysqlConnectionPoolDataSource dataSource = new MysqlConnectionPoolDataSource(); dataSource.setDatabaseName("se"); dataSource.setUser("root"); dataSource.setPassword(""); dataSource.setCachePreparedStatements(true); dataSource.setCachePrepStmts(true); dataSource.setCacheResultSetMetadata(true); dataSource.setAlwaysSendSetIsolation(false); dataSource.setElideSetAutoCommits(true); // create the data model DataModel dataModel = new JDBCDataModelImpl(new ConnectionPoolDataSource(dataSource)); // Create an ItemSimilarity ItemSimilarity itemSimilarity = new LogLikelihoodSimilarity(dataModel); // Create an Item Based Recommender ItemBasedRecommender recommender = new GenericItemBasedRecommender(dataModel, itemSimilarity); // Get the recommendations List<RecommendedItem> recommendations = recommender.recommend(userId, 5); // TasteUtils.printRecs(recommendations, handler.map); for (RecommendedItem recommendedItem : recommendations) { System.out.println("User:"******"Movie ID : " + recommendedItem); } }
/** * Contact the remote WebDAV server and do a PROPFIND lookup, returning a {@link List} of all * scavenged resources. */ private List propfind(Location location) throws IOException { /* Create the new HttpClient instance associated with the location */ final HttpClient client = new HttpClient(location); client.addRequestHeader("Depth", "1"); client.setAcceptableStatus(207).connect("PROPFIND", true); /* Get the XML SAX Parser and parse the output of the PROPFIND */ try { final SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(false); factory.setNamespaceAware(true); final SAXParser parser = factory.newSAXParser(); final String systemId = location.toString(); final InputSource source = new InputSource(systemId); final Handler handler = new Handler(location); source.setByteStream(client.getResponseStream()); parser.parse(source, handler); return handler.list; } catch (ParserConfigurationException exception) { Exception throwable = new IOException("Error creating XML parser"); throw (IOException) throwable.initCause(exception); } catch (SAXException exception) { Exception throwable = new IOException("Error creating XML parser"); throw (IOException) throwable.initCause(exception); } finally { client.disconnect(); } }
/* (non-Javadoc) * @see org.eclipse.core.internal.jobs.InternalJob#run(org.eclipse.core.runtime.IProgressMonitor) */ protected IStatus run(IProgressMonitor monitor) { TreeNode root = new TreeNode(""); File it = new File(proj.getLocation().addTrailingSeparator() + "goblin.xml"); if (!it.canRead()) return new Status(IStatus.ERROR, "ee.ut.goblin", 97, "Can't read analysis file.", null); DefaultHandler handler = new XMLHandler(root); SAXParserFactory factory = SAXParserFactory.newInstance(); try { // Parse the input SAXParser saxParser = factory.newSAXParser(); saxParser.parse(it, handler); } catch (Throwable t) { return new Status(IStatus.ERROR, "ee.ut.goblin", 96, t.getMessage(), t); } TreeAnalysisMap tam = new TreeAnalysisMap((TreeAnalysis) root.getChildren()[0]); try { proj.setSessionProperty(GoblinPlugin.RESULT_NAME, tam); } catch (CoreException e) { return new Status(IStatus.ERROR, "ee.ut.goblin", 95, e.getMessage(), e); } monitor.done(); return Status.OK_STATUS; }
public boolean SetDoc(String strDoc) { try { SaxDoc sax = new SaxDoc(); SAXParser sp; sp = SAXParserFactory.newInstance().newSAXParser(); sp.parse(new InputSource(new StringReader(strDoc)), sax); headNode = sax.getRootNode(); rootNode = new NodeModel(true); rootNode.SetNext(headNode); headNode.SetPre(rootNode); pointer = rootNode; return true; } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { } return false; }
public static void main(String argv[]) { if (argv.length != 3) { System.err.println( "Usage: java -server TestSAXOutput <xml file> <times to parse> <output file>"); System.exit(-1); } String xmlFile = argv[0]; int times = (new Integer(argv[1])).intValue(); outFileName = argv[2]; try { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); TestSAXOutput tsp = new TestSAXOutput(); for (int i = 0; i < times; i++) { parser.parse(xmlFile, tsp); } } catch (FactoryConfigurationError e) { System.err.print("factory configuration error:\n" + e); } catch (ParserConfigurationException e) { System.err.print("parser configuration error:\n" + e); } catch (SAXException e) { System.err.print("sax configuration error:\n" + e); } catch (IOException e) { System.err.print("io error:\n" + e); } }
/** {@inheritDoc} */ public ParseResult parse(RSyntaxDocument doc, String style) { result.clearNotices(); Element root = doc.getDefaultRootElement(); result.setParsedLines(0, root.getElementCount() - 1); if (spf == null || doc.getLength() == 0) { return result; } try { SAXParser sp = spf.newSAXParser(); Handler handler = new Handler(doc); DocumentReader r = new DocumentReader(doc); InputSource input = new InputSource(r); sp.parse(input, handler); r.close(); } catch (SAXParseException spe) { // A fatal parse error - ignore; a ParserNotice was already created. } catch (Exception e) { // e.printStackTrace(); // Will print if DTD specified and can't be found result.addNotice( new DefaultParserNotice(this, "Error parsing XML: " + e.getMessage(), 0, -1, -1)); } return result; }
public ArrayList<IProject> getProjects() { final ArrayList<IProject> result = new ArrayList<IProject>(); try { IProject featureProject = getFeatureProject(); IFile featureXMLFile = featureProject.getFile("feature.xml"); SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); DefaultHandler handler = new DefaultHandler() { @Override public void startElement( String uri, String localName, String qName, Attributes attributes) throws SAXException { if ("plugin".equals(qName)) { String id = attributes.getValue("id"); IProject eachProject = ResourcesPlugin.getWorkspace().getRoot().getProject(id); if (!eachProject.exists()) { throw new BuildException( MessageFormat.format( "아이디가 {0}인 프로젝틀르 찾지 못했습니다. 프로젝트 아이디와 프로젝트 명은 동일한 것으로 간주합니다.", id)); } result.add(eachProject); } } }; parser.parse(featureXMLFile.getContents(), handler); } catch (Exception e) { throw new BuildException(e.getMessage(), e); } return result; }
public void update() throws IOException, SAXException, ParserConfigurationException { MibewResponse response = fConnection.request("operator/update.php", "since=" + fSince); SAXParser sp = SAXParserFactory.newInstance().newSAXParser(); UpdateHandler handler = new UpdateHandler(); sp.parse(new ByteArrayInputStream(response.getResponse()), handler); handleResponse(response, handler); }
public List<Customer> readDataFromXML(String filename) throws ParserConfigurationException, SAXException, IOException { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); parser.parse(new File(filename), this); return data; }
public VersionInfo getNewestVersionInfo() { VersionInfo versionInfo = new VersionInfo(); HttpClient hc = new DefaultHttpClient(); HttpGet get = new HttpGet(server_address + "/VersionInfo.xml"); try { HttpResponse response = hc.execute(get); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity he = response.getEntity(); try { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); parser.parse(he.getContent(), new VersionSaxHandler(versionInfo)); } catch (Exception e) { Log.e(tag, "xml解析错误"); return null; } he.consumeContent(); } } catch (ClientProtocolException e) { Log.e(tag, "协议错误"); return null; } catch (IOException e) { Log.e(tag, "读写错误"); return null; } return versionInfo; }
public boolean updataFeedFromServer(final int page, final int topicId, final int size) { Log.d( TAG, String.format("::updataFeedFromServer(page=%s,topicID=%s,size%s)", page, topicId, size)); try { List<JokeBean> jokeItems = new ArrayList<JokeBean>(); JokeClient client = new JokeClient(); ResponseData responseData = client.getJokes(page, size, topicId); if (responseData.getStatus()) { SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); JokeBeanHandler handler = new JokeBeanHandler(); InputSource is = new InputSource(new StringReader(responseData.toString())); parser.parse(is, handler); jokeItems.addAll(handler.getJokeItems()); /* Set topic id */ for (JokeBean item : jokeItems) { item.setTopic(topicId); } /* Now write the joke to cache */ return db.addAll(jokeItems); } } catch (Exception e) { Log.e(TAG, "" + e.getMessage()); e.printStackTrace(); } return false; }
@NotNull private MostlySingularMultiMap<String, AnnotationData> getDataFromFile( @NotNull final PsiFile file) { Pair<MostlySingularMultiMap<String, AnnotationData>, Long> cached = annotationFileToDataAndModStamp.get(file); final long fileModificationStamp = file.getModificationStamp(); if (cached != null && cached.getSecond() == fileModificationStamp) { return cached.getFirst(); } DataParsingSaxHandler handler = new DataParsingSaxHandler(file); try { SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); saxParser.parse(new InputSource(new StringReader(escapeAttributes(file.getText()))), handler); } catch (IOException e) { LOG.error(e); } catch (ParserConfigurationException e) { LOG.error(e); } catch (SAXException e) { LOG.error(e); } Pair<MostlySingularMultiMap<String, AnnotationData>, Long> pair = Pair.create(handler.getResult(), file.getModificationStamp()); annotationFileToDataAndModStamp.put(file, pair); return pair.first; }
/** Creates new form JPanelButtons */ public JPanelButtons(String sConfigKey, JPanelTicket panelticket) { initComponents(); // Load categories default thumbnail tnbmacro = new ThumbNailBuilder(24, 24, "com/openbravo/images/run_script.png"); this.panelticket = panelticket; props = new Properties(); events = new HashMap<String, String>(); String sConfigRes = panelticket.getResourceAsXML(sConfigKey); if (sConfigRes != null) { try { if (m_sp == null) { SAXParserFactory spf = SAXParserFactory.newInstance(); m_sp = spf.newSAXParser(); } m_sp.parse(new InputSource(new StringReader(sConfigRes)), new ConfigurationHandler()); } catch (ParserConfigurationException ePC) { logger.log(Level.WARNING, LocalRes.getIntString("exception.parserconfig"), ePC); } catch (SAXException eSAX) { logger.log(Level.WARNING, LocalRes.getIntString("exception.xmlfile"), eSAX); } catch (IOException eIO) { logger.log(Level.WARNING, LocalRes.getIntString("exception.iofile"), eIO); } } }
/** * 根据 xml 文件初始化配置信息,使用 AnalyzeHandler 进行 xml 解析 * * <p>{@link AnalyzeHandler} * * @param context 上下文 * @param xmlId xmlId(必须要在 res/raw 文件夹下) */ void initVirtualLightningConfig(Context context, int xmlId) { String name = context.getResources().getResourceName(xmlId); if (!name.substring(name.indexOf(":") + 1, name.indexOf("/")).equals("raw")) { throw new VLInitException("资源文件后缀名不正确!必须为\".xml\"结尾放在\"res/raw\"的XML文件"); } InputStream source = context.getResources().openRawResource(xmlId); try { SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); parser.parse(source, new AnalyzeHandler(this)); } catch (ParserConfigurationException | SAXException | IOException e) { throw new VLInitException("解析 XML 文件发生错误:" + e.getMessage()); } finally { try { source.close(); } catch (IOException ignored) { } } initDatabase(context); }
@Override public String[] parseResult(SAXParser parser, InputSource is) throws SAXException, IOException { ResultHandler handler = new ResultHandler(); parser.parse(is, handler); return handler.getResult(); }
public static ParentalControlConcern parse(File file) { try { log.info("Parsing '" + file.getCanonicalPath() + "'..."); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(true); SAXParser parser = factory.newSAXParser(); parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA); ParentalControlConcernHandler handler = new ParentalControlConcernHandler(); parser.parse(file, handler); log.info("Parsed '" + file.getCanonicalPath() + "'"); return handler.result; } catch (SAXParseException ex) { log.error( "Could not validate the parental control concern XML file! Validation error follows."); log.error(ex.getMessage()); ex.printStackTrace(); return null; } catch (Exception ex) { log.error(ex); return null; } }
// ---- main ---- public static void main(final String[] argv) { if (argv.length != 1) { System.err.println( "Usage: java " + GpxReader.class.getSimpleName() + " <file>"); //$NON-NLS-1$ //$NON-NLS-2$ System.exit(1); } final long startMillis = System.currentTimeMillis(); try { final File f = new File(argv[0]); System.out.println("File size: " + f.length() + " bytes"); // $NON-NLS-1$ //$NON-NLS-2$ // Use an instance of ourselves as the SAX event handler final DefaultHandler handler = new GpxReader(); // Parse the input with the default (non-validating) parser final SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); saxParser.parse(f, handler); } catch (final Exception t) { t.printStackTrace(); System.exit(2); } final long millis = System.currentTimeMillis() - startMillis; System.out.println("Time consumed: " + millis + " ms"); // $NON-NLS-1$ //$NON-NLS-2$ }
/** * {@link SAXParserFactoryUtil#setXIncludeAware}のテストです。 * * @throws Exception */ public void testSetXIncludeAware() throws Exception { SAXParserFactory spf = SAXParserFactoryUtil.newInstance(); SAXParserFactoryUtil.setXIncludeAware(spf, true); spf.setNamespaceAware(true); SAXParser parser = SAXParserFactoryUtil.newSAXParser(spf); InputSource is = new InputSource(ResourceUtil.getResourceAsStream("org/seasar/framework/util/include.xml")); is.setSystemId("include.xml"); parser.parse( is, new DefaultHandler() { @Override public void startElement( String uri, String localName, String qName, Attributes attributes) throws SAXException { if ("bar".equals(qName)) { included = true; } } @Override public InputSource resolveEntity(String publicId, String systemId) throws IOException, SAXException { InputSource is = new InputSource( ResourceUtil.getResourceAsStream("org/seasar/framework/util/included.xml")); is.setSystemId("included.xml"); return is; } }); assertTrue(included); }
Parser(String uri) { try { SAXParserFactory parserFactory = SAXParserFactory.newInstance(); SAXParser parser = parserFactory.newSAXParser(); ConfigHandler handler = new ConfigHandler(); parser.getXMLReader().setFeature("http://xml.org/sax/features/validation", true); parser.parse(new File(uri), handler); } catch (IOException e) { System.out.println("Error reading URI: " + e.getMessage()); } catch (SAXException e) { System.out.println("Error in parsing: " + e.getMessage()); } catch (ParserConfigurationException e) { System.out.println("Error in XML parser configuration: " + e.getMessage()); } // System.out.println("Number of Persons : " + Person.numberOfPersons()); // nameLengthStatistics(); // System.out.println("Number of Publications with authors/editors: " + // Publication.getNumberOfPublications()); // System.out.println("Maximum number of authors/editors in a publication: " + // Publication.getMaxNumberOfAuthors()); // publicationCountStatistics(); // Person.enterPublications(); // Person.printCoauthorTable(); // Person.printNamePartTable(); // Person.findSimilarNames(); }
public boolean read_config(String filename) { boolean valid = false; try { File file = new File(filename); if (file.exists()) { try { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); saxParser.parse(file, get_handler()); } catch (Exception ex) { ex.printStackTrace(); } } else { System.out.println("The file " + file.getAbsolutePath() + " does not exist."); } } catch (Exception ex) { ex.printStackTrace(); } return valid; }