List of usage examples for javax.xml.parsers SAXParser parse
public void parse(InputSource is, DefaultHandler dh) throws SAXException, IOException
From source file:com.abstratt.mdd.core.util.MDDUtil.java
public static boolean isGenerated(java.net.URI uri) { if (cachedParserFactory == null) { cachedParserFactory = SAXParserFactory.newInstance(); }//from w ww. j av a 2 s . c o m SAXParser xmlParser; try { xmlParser = cachedParserFactory.newSAXParser(); } catch (ParserConfigurationException e) { if (Platform.inDebugMode()) LogUtils.logError(MDDCore.PLUGIN_ID, "Error creating XML parser", e); return false; } catch (SAXException e) { if (Platform.inDebugMode()) LogUtils.logError(MDDCore.PLUGIN_ID, "Error creating XML parser", e); return false; } final boolean[] generated = { false }; final boolean[] aborted = { false }; InputStream stream = null; try { stream = new BufferedInputStream(uri.toURL().openStream()); xmlParser.parse(stream, new DefaultHandler() { private boolean skipping = true; @Override public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException { if (name.equalsIgnoreCase("eAnnotations")) if (GENERATED.equals(attributes.getValue("source"))) { generated[0] = true; aborted[0] = true; throw new SAXParseException("", null); } else return; if (!skipping) { // should have seen the annotation by now aborted[0] = true; throw new SAXParseException("", null); } if (name.startsWith("uml")) skipping = false; } }); } catch (SAXException e) { if (!aborted[0] && Platform.inDebugMode()) LogUtils.logError(MDDCore.PLUGIN_ID, "Error parsing " + uri, e); } catch (IOException e) { if (Platform.inDebugMode()) LogUtils.logError(MDDCore.PLUGIN_ID, "Error parsing " + uri, e); } finally { if (stream != null) try { stream.close(); } catch (IOException e) { // no biggie } } return generated[0]; }
From source file:ensen.controler.DBpediaLookupClient.java
public String getOneResource(String query, String classes, int numberOfRes) throws Exception { HttpClient client = new HttpClient(); // client.getHttpConnectionManager().getParams().setConnectionTimeout(10000); String query2 = URLEncoder.encode(query, "utf-8"); HttpMethod method = new GetMethod( gatway + "QueryString=" + query2 + "&QueryClass=" + classes + "&MaxHits=" + numberOfRes); // method.setFollowRedirects(true); try {/*w ww .j ava 2 s . c o m*/ client.executeMethod(method); InputStream ins = method.getResponseBodyAsStream(); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser sax = factory.newSAXParser(); sax.parse(ins, this); } catch (HttpException he) { System.out.println("Http error connecting to lookup.dbpedia.org"); } catch (IOException ioe) { System.out.println("Unable to connect to lookup.dbpedia.org"); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } method.releaseConnection(); String resource = ""; int num_results = Results.size(); if (num_results > 0) { for (DBpediaLookupResModel res : Results) { resource = URLDecoder.decode(res.uri); /* * if (res.uri.contains("http://")) { Resource O = * model.createResource(res.uri); Property P = * model.createProperty("http://ensen.org/data#has-a"); Literal * O1 = model.createLiteral(res.label + ""); Literal O2 = * model.createLiteral(res.desc + ""); Property P1 = * model.createProperty * ("http://www.w3.org/2000/01/rdf-schema#label"); Property P2 = * model.createProperty( * "http://www.w3.org/1999/02/22-rdf-syntax-ns#description"); * O.addProperty(P1, O1); O.addProperty(P2, O2); * * for (String cat : res.cats) { Resource OO = * model.createResource(cat); Property PP = * model.createProperty("http://purl.org/dc/terms/subject"); * O.addProperty(PP, OO); } for (String c : res.classes) { * Resource OO = model.createResource(c); Property PP = * model.createProperty * ("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"); * O.addProperty(PP, OO); } core.addProperty(P, O); * * } */ } } return resource; }
From source file:ensen.controler.DBpediaLookupClient.java
public Model qetEntities(String query, String classes, int numberOfRes) throws Exception { HttpClient client = new HttpClient(); // client.getHttpConnectionManager().getParams().setConnectionTimeout(10000); String query2 = URLEncoder.encode(query, "utf-8"); HttpMethod method = new GetMethod( gatway + "QueryString=" + query2 + "&QueryClass=" + classes + "&MaxHits=" + numberOfRes); // method.setFollowRedirects(true); try {/*from w ww .jav a2 s . com*/ client.executeMethod(method); InputStream ins = method.getResponseBodyAsStream(); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser sax = factory.newSAXParser(); sax.parse(ins, this); } catch (HttpException he) { System.out.println("Http error connecting to lookup.dbpedia.org"); } catch (IOException ioe) { System.out.println("Unable to connect to lookup.dbpedia.org"); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } method.releaseConnection(); Model model = ModelFactory.createDefaultModel(); Resource core = model.createResource("http://ensen.org/data#q-" + query2); int num_results = Results.size(); if (num_results > 0) { for (DBpediaLookupResModel res : Results) { // System.out.println("URI: " + res.uri); if (res.uri.contains("http://")) { Resource O = model.createResource(res.uri); Property P = model.createProperty("http://ensen.org/data#has-a"); Literal O1 = model.createLiteral(res.label + ""); Literal O2 = model.createLiteral(res.desc + ""); Property P1 = model.createProperty("http://www.w3.org/2000/01/rdf-schema#label"); Property P2 = model.createProperty("http://www.w3.org/1999/02/22-rdf-syntax-ns#description"); O.addProperty(P1, O1); O.addProperty(P2, O2); for (String cat : res.cats) { Resource OO = model.createResource(cat); Property PP = model.createProperty("http://purl.org/dc/terms/subject"); O.addProperty(PP, OO); } for (String c : res.classes) { Resource OO = model.createResource(c); Property PP = model.createProperty("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"); O.addProperty(PP, OO); } core.addProperty(P, O); } } } return model; }
From source file:de.uni_freiburg.informatik.ultimate.licence_manager.authors.SvnAuthorProvider.java
private SvnBlameSAXHandler parseSvnBlameOutput(InputStream input) throws ParserConfigurationException, SAXException, IOException { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); SvnBlameSAXHandler handler = new SvnBlameSAXHandler(); saxParser.parse(input, handler); return handler; }
From source file:org.xwiki.contrib.repository.pypi.internal.searching.PypiPackageListIndexUpdateTask.java
protected List<String> parseHtmlPageToPackagenames(InputStream is) throws ParserConfigurationException, SAXException, IOException { SAXParserFactory parserFactor = SAXParserFactory.newInstance(); SAXParser parser = parserFactor.newSAXParser(); PypiPackageListSAXHandler handler = new PypiPackageListSAXHandler(); parser.parse(is, handler); return handler.getPackageNames(); }
From source file:io.lightlink.excel.StreamingExcelTransformer.java
public void doExport(InputStream template, OutputStream out, ExcelStreamVisitor visitor) throws IOException { try {//from w w w .j av a 2 s.c o m ZipInputStream zipIn = new ZipInputStream(template); ZipOutputStream zipOut = new ZipOutputStream(out); ZipEntry entry; Map<String, byte[]> sheets = new HashMap<String, byte[]>(); while ((entry = zipIn.getNextEntry()) != null) { String name = entry.getName(); if (name.startsWith("xl/sharedStrings.xml")) { byte[] bytes = IOUtils.toByteArray(zipIn); zipOut.putNextEntry(new ZipEntry(name)); zipOut.write(bytes); sharedStrings = processSharedStrings(bytes); } else if (name.startsWith("xl/worksheets/sheet")) { byte[] bytes = IOUtils.toByteArray(zipIn); sheets.put(name, bytes); } else if (name.equals("xl/calcChain.xml")) { // skip this file, let excel recreate it } else if (name.equals("xl/workbook.xml")) { zipOut.putNextEntry(new ZipEntry(name)); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); Writer writer = new OutputStreamWriter(zipOut, "UTF-8"); byte[] bytes = IOUtils.toByteArray(zipIn); saxParser.parse(new ByteArrayInputStream(bytes), new WorkbookTemplateHandler(writer)); writer.flush(); } else { zipOut.putNextEntry(new ZipEntry(name)); IOUtils.copy(zipIn, zipOut); } } for (Map.Entry<String, byte[]> sheetEntry : sheets.entrySet()) { String name = sheetEntry.getKey(); byte[] bytes = sheetEntry.getValue(); zipOut.putNextEntry(new ZipEntry(name)); processSheet(bytes, zipOut, visitor); } zipIn.close(); template.close(); zipOut.close(); out.close(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e.toString(), e); } }
From source file:net.sf.jabref.importer.fileformat.BibTeXMLImporter.java
@Override public ParserResult importDatabase(BufferedReader reader) throws IOException { Objects.requireNonNull(reader); List<BibEntry> bibItems = new ArrayList<>(); // Obtain a factory object for creating SAX parsers SAXParserFactory parserFactory = SAXParserFactory.newInstance(); // Configure the factory object to specify attributes of the parsers it // creates//from w w w .j av a2 s .c o m // parserFactory.setValidating(true); parserFactory.setNamespaceAware(true); // Now create a SAXParser object try { SAXParser parser = parserFactory.newSAXParser(); //May throw exceptions BibTeXMLHandler handler = new BibTeXMLHandler(); // Start the parser. It reads the file and calls methods of the handler. parser.parse(new InputSource(reader), handler); // When you're done, report the results stored by your handler object bibItems.addAll(handler.getItems()); } catch (javax.xml.parsers.ParserConfigurationException e) { LOGGER.error("Error with XML parser configuration", e); return ParserResult.fromErrorMessage(e.getLocalizedMessage()); } catch (org.xml.sax.SAXException e) { LOGGER.error("Error during XML parsing", e); return ParserResult.fromErrorMessage(e.getLocalizedMessage()); } catch (IOException e) { LOGGER.error("Error during file import", e); return ParserResult.fromErrorMessage(e.getLocalizedMessage()); } return new ParserResult(bibItems); }
From source file:net.sbbi.upnp.messages.StateVariableMessage.java
/** * Executes the state variable query and retuns the UPNP device response, according to the UPNP specs, * this method could take up to 30 secs to process ( time allowed for a device to respond to a request ) * @return a state variable response object containing the variable value * @throws IOException if some IOException occurs during message send and reception process * @throws UPNPResponseException if an UPNP error message is returned from the server * or if some parsing exception occurs ( detailErrorCode = 899, detailErrorDescription = SAXException message ) *//*from ww w. j a v a 2 s . c o m*/ public StateVariableResponse service() throws IOException, UPNPResponseException { StateVariableResponse rtrVal = null; UPNPResponseException upnpEx = null; IOException ioEx = null; StringBuffer body = new StringBuffer(256); body.append("<?xml version=\"1.0\"?>\r\n"); body.append("<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\""); body.append(" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"); body.append("<s:Body>"); body.append("<u:QueryStateVariable xmlns:u=\"urn:schemas-upnp-org:control-1-0\">"); body.append("<u:varName>").append(serviceStateVar.getName()).append("</u:varName>"); body.append("</u:QueryStateVariable>"); body.append("</s:Body>"); body.append("</s:Envelope>"); if (log.isDebugEnabled()) log.debug("POST prepared for URL " + service.getControlURL()); URL url = new URL(service.getControlURL().toString()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); HttpURLConnection.setFollowRedirects(false); //conn.setConnectTimeout( 30000 ); conn.setRequestProperty("HOST", url.getHost() + ":" + url.getPort()); conn.setRequestProperty("SOAPACTION", "\"urn:schemas-upnp-org:control-1-0#QueryStateVariable\""); conn.setRequestProperty("CONTENT-TYPE", "text/xml; charset=\"utf-8\""); conn.setRequestProperty("CONTENT-LENGTH", Integer.toString(body.length())); OutputStream out = conn.getOutputStream(); out.write(body.toString().getBytes()); out.flush(); conn.connect(); InputStream input = null; if (log.isDebugEnabled()) log.debug("executing query :\n" + body); try { input = conn.getInputStream(); } catch (IOException ex) { // java can throw an exception if he error code is 500 or 404 or something else than 200 // but the device sends 500 error message with content that is required // this content is accessible with the getErrorStream input = conn.getErrorStream(); } if (input != null) { int response = conn.getResponseCode(); String responseBody = getResponseBody(input); if (log.isDebugEnabled()) log.debug("received response :\n" + responseBody); SAXParserFactory saxParFact = SAXParserFactory.newInstance(); saxParFact.setValidating(false); saxParFact.setNamespaceAware(true); StateVariableResponseParser msgParser = new StateVariableResponseParser(serviceStateVar); StringReader stringReader = new StringReader(responseBody); InputSource src = new InputSource(stringReader); try { SAXParser parser = saxParFact.newSAXParser(); parser.parse(src, msgParser); } catch (ParserConfigurationException confEx) { // should never happen // we throw a runtimeException to notify the env problem throw new RuntimeException( "ParserConfigurationException during SAX parser creation, please check your env settings:" + confEx.getMessage()); } catch (SAXException saxEx) { // kind of tricky but better than nothing.. upnpEx = new UPNPResponseException(899, saxEx.getMessage()); } finally { try { input.close(); } catch (IOException ex) { // ignoring } } if (upnpEx == null) { if (response == HttpURLConnection.HTTP_OK) { rtrVal = msgParser.getStateVariableResponse(); } else if (response == HttpURLConnection.HTTP_INTERNAL_ERROR) { upnpEx = msgParser.getUPNPResponseException(); } else { ioEx = new IOException("Unexpected server HTTP response:" + response); } } } try { out.close(); } catch (IOException ex) { // ignore } conn.disconnect(); if (upnpEx != null) { throw upnpEx; } if (rtrVal == null && ioEx == null) { ioEx = new IOException("Unable to receive a response from the UPNP device"); } if (ioEx != null) { throw ioEx; } return rtrVal; }
From source file:egat.cli.AbstractGameCommandHandler.java
protected void processCommand(InputStream inputStream, boolean symmetric) throws CommandProcessingException { try {//from w w w . j a va 2 s. c o m if (symmetric) { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); SymmetricGameHandler handler = new SymmetricGameHandler(); parser.parse(inputStream, handler); MutableSymmetricGame game = handler.getGame(); processSymmetricGame(game); } else { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); StrategicGameHandler handler = new StrategicGameHandler(); parser.parse(inputStream, handler); MutableStrategicGame game = handler.getGame(); processStrategicGame(game); } } catch (ParserConfigurationException e) { throw new CommandProcessingException(e); } catch (SAXException e) { throw new CommandProcessingException(e); } catch (IOException e) { throw new CommandProcessingException(e); } }
From source file:de.tudarmstadt.ukp.dkpro.core.io.xml.XmlReaderText.java
@Override public void getNext(CAS aCAS) throws IOException, CollectionException { Resource res = nextFile();/*from www . j av a2 s . c o m*/ initCas(aCAS, res); InputStream is = null; try { JCas jcas = aCAS.getJCas(); is = res.getInputStream(); // Create handler Handler handler = newSaxHandler(); handler.setJCas(jcas); handler.setLogger(getLogger()); // Parser XML SAXParserFactory pf = SAXParserFactory.newInstance(); SAXParser parser = pf.newSAXParser(); InputSource source = new InputSource(is); source.setPublicId(res.getLocation()); source.setSystemId(res.getLocation()); parser.parse(source, handler); // Set up language if (getConfigParameterValue(PARAM_LANGUAGE) != null) { aCAS.setDocumentLanguage((String) getConfigParameterValue(PARAM_LANGUAGE)); } } catch (CASException e) { throw new CollectionException(e); } catch (ParserConfigurationException e) { throw new CollectionException(e); } catch (SAXException e) { throw new IOException(e); } finally { closeQuietly(is); } }