List of usage examples for javax.xml.parsers SAXParser parse
public void parse(InputSource is, DefaultHandler dh) throws SAXException, IOException
From source file:com.aurel.track.exchange.docx.importer.HTMLParser.java
private void parse(ByteArrayOutputStream byteArrayOutputStream, Locale locale) { localizedHeading = "berschrift";//LocalizeUtil.getLocalizedTextFromApplicationResources(HEADING_KEY, locale); SAXParserFactory spf = SAXParserFactory.newInstance(); Reader fileReader = null;/* w w w .j a va 2 s . c om*/ try { fileReader = new FileReader(new File("d:/docx/PN164_SC_Track.docx.html")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block LOGGER.error(ExceptionUtils.getStackTrace(e)); } try { //get a new instance of parser SAXParser sp = spf.newSAXParser(); //InputSource is=new InputSource(new ByteArrayInputStream(byteArrayOutputStream.toByteArray())); InputSource is = new InputSource(fileReader); sp.parse(is, this); } catch (SAXException se) { LOGGER.error("Parsing failed with " + se.getMessage()); if (LOGGER.isDebugEnabled()) { LOGGER.error(ExceptionUtils.getStackTrace(se)); } } catch (ParserConfigurationException pce) { LOGGER.error("Parsing failed with " + pce.getMessage()); if (LOGGER.isDebugEnabled()) { LOGGER.error(ExceptionUtils.getStackTrace(pce)); } } catch (IOException ie) { LOGGER.error("Reading failed with " + ie.getMessage()); LOGGER.error(ExceptionUtils.getStackTrace(ie)); } }
From source file:crawlercommons.sitemaps.SiteMapParserSAX.java
/** * Parse the given XML content.//from w ww.j a v a 2 s . c om * * @param sitemapUrl * a sitemap {@link java.net.URL} * @param is * an {@link org.xml.sax.InputSource} backing the sitemap * @return the site map * @throws UnknownFormatException * if there is an error parsing the * {@link org.xml.sax.InputSource} */ protected AbstractSiteMap processXml(URL sitemapUrl, InputSource is) throws UnknownFormatException { SAXParserFactory factory = SAXParserFactory.newInstance(); DelegatorHandler handler = new DelegatorHandler(sitemapUrl, strict); try { SAXParser saxParser = factory.newSAXParser(); saxParser.parse(is, handler); AbstractSiteMap sitemap = handler.getSiteMap(); if (sitemap == null) { throw new UnknownFormatException("Unknown XML format for: " + sitemapUrl); } return sitemap; } catch (IOException e) { LOG.warn("Error parsing sitemap {}: {}", sitemapUrl, e.getMessage()); UnknownFormatException ufe = new UnknownFormatException("Failed to parse " + sitemapUrl); ufe.initCause(e); throw ufe; } catch (SAXException e) { LOG.warn("Error parsing sitemap {}: {}", sitemapUrl, e.getMessage()); AbstractSiteMap sitemap = handler.getSiteMap(); if (allowPartial && sitemap != null) { LOG.warn("Processed broken/partial sitemap for '" + sitemapUrl + "'"); sitemap.setProcessed(true); return sitemap; } else { UnknownFormatException ufe = new UnknownFormatException("Failed to parse " + sitemapUrl); ufe.initCause(e); throw ufe; } } catch (ParserConfigurationException e) { throw new IllegalStateException(e); } }
From source file:Validate.java
void parse(String dir, String filename) throws FileNotFoundException, IOException, ParserConfigurationException, SAXException { try {/*from ww w .j a v a 2 s .com*/ File f = new File(dir, filename); StringBuffer errorBuff = new StringBuffer(); InputSource input = new InputSource(new FileInputStream(f)); // Set systemID so parser can find the dtd with a relative URL in the source document. input.setSystemId(f.toString()); SAXParserFactory spfact = SAXParserFactory.newInstance(); spfact.setValidating(true); spfact.setNamespaceAware(true); SAXParser parser = spfact.newSAXParser(); XMLReader reader = parser.getXMLReader(); //Instantiate inner-class error and lexical handler. Handler handler = new Handler(filename, errorBuff); reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler); parser.parse(input, handler); if (handler.containsDTD && !handler.errorOrWarning) // valid { buff.append("VALID " + filename + "\n"); numValidFiles++; } else if (handler.containsDTD) // not valid { buff.append("NOT VALID " + filename + "\n"); buff.append(errorBuff.toString()); numInvalidFiles++; } else // no DOCTYPE to use for validation { buff.append("NO DOCTYPE DECLARATION " + filename + "\n"); numFilesMissingDoctype++; } } catch (Exception e) // Serious problem! { buff.append("NOT WELL-FORMED " + filename + ". " + e.getMessage() + "\n"); numMalformedFiles++; } finally { numXMLFiles++; } }
From source file:com.git.original.common.config.XMLFileConfigDocument.java
protected ConfigNode doLoad(String configFilePath) throws Exception { InputStream in = null;/*from w ww . ja v a 2 s.c om*/ try { File confFile = new File(configFilePath); if (!confFile.isAbsolute()) { confFile = new File(this.getHmailHome(), configFilePath); } if (!confFile.exists()) { throw new FileNotFoundException("path:" + confFile); } String currentDigest = confFile.lastModified() + ";" + confFile.length(); if (currentDigest.equals(this.configFileDigest)) { // ??, ? return null; } in = new FileInputStream(confFile); SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); NodeBuilder nb = new NodeBuilder(); parser.parse(in, nb); ConfigNode result = nb.getRootNode(); if (result != null) { try { this.dbVersion = result.getAttribute(CONF_DOC_ATTRIBUTE_DB_VERSION); } catch (Exception ex) { this.dbVersion = null; } try { String str = result.getAttribute(CONF_DOC_ATTRIBUTE_IGNORE_DB); if (StringUtils.isEmpty(str)) { this.ignoreDb = false; } else { this.ignoreDb = Boolean.parseBoolean(str); } } catch (Exception ex) { this.ignoreDb = false; } try { String tmp = result.getAttribute(CONF_DOC_ATTRIBUTE_SCAN_PERIOD); if (StringUtils.isEmpty(tmp)) { this.scanMillis = null; } else { this.scanMillis = ConfigNode.textToNumericMillis(tmp.trim()); } } catch (Exception ex) { this.scanMillis = null; } } LOG.debug("Load config from local dir success, file:{}", configFilePath); return result; } finally { if (in != null) { try { in.close(); } catch (IOException e) { // ignore exception } } } }
From source file:com.wadpam.ricotta.web.IndexController.java
protected void importXML(InputStream in, String projName, String branchName) throws ParserConfigurationException, SAXException, IOException { SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); final UserService userService = UserServiceFactory.getUserService(); final User user = userService.getCurrentUser(); final String updatedBy = null != user ? user.getEmail() : "[ANONYMOUS]"; DefaultHandler dh = new TokensImportHandler(uberDao, projName, branchName, updatedBy); parser.parse(in, dh); }
From source file:com.wooki.test.unit.ConversionsTest.java
@Test(enabled = true) public void testAptConversion() { String result = " ------\n Title\n ------\n Author\n ------\n Date\n\n Paragraph 1, line 1.\n Paragraph 1, line 2.\n\n Paragraph 2, line 1.\n Paragraph 2, line 2.\n\nSection title\n\n* Sub-section title\n\n** Sub-sub-section title\n\n*** Sub-sub-sub-section title\n\n**** Sub-sub-sub-sub-section title\n\n * List item 1.\n\n * List item 2.\n\n Paragraph contained in list item 2.\n\n * Sub-list item 1.\n\n * Sub-list item 2.\n\n * List item 3.\n Force end of list:\n\n []\n\n+------------------------------------------+\nVerbatim text not contained in list item 3\n+------------------------------------------+\n\n [[1]] Numbered item 1.\n\n [[A]] Numbered item A.\n\n [[B]] Numbered item B.\n\n [[2]] Numbered item 2.\n\n List numbering schemes: [[1]], [[a]], [[A]], [[i]], [[I]].\n\n [Defined term 1] of definition list.\n\n [Defined term 2] of definition list.\n\n+-------------------------------+\nVerbatim text\n in a box\n+-------------------------------+\n\n --- instead of +-- suppresses the box around verbatim text.\n\n[Figure name] Figure caption\n\n*----------*--------------+----------------:\n| Centered | Left-aligned | Right-aligned |\n| cell 1,1 | cell 1,2 | cell 1,3 |\n*----------*--------------+----------------:\n| cell 2,1 | cell 2,2 | cell 2,3 |\n*----------*--------------+----------------:\nTable caption\n\n No grid, no caption:\n\n*-----*------*\n cell | cell\n*-----*------*\n cell | cell\n*-----*------*\n\n Horizontal line:\n\n=======================================================================\n\n^L\n New page.\n\n <Italic> font. <<Bold>> font. <<<Monospaced>>> font.\n\n {Anchor}. Link to {{anchor}}. Link to {{http://www.pixware.fr}}.\n Link to {{{anchor}showing alternate text}}.\n Link to {{{http://www.pixware.fr}Pixware home page}}.\n\n Force line\\\n break.\n\n Non\\ breaking\\ space.\n\n Escaped special characters: \\~, \\=, \\-, \\+, \\*, \\[, \\], \\<, \\>, \\{, \\}, \\\\.\n\n Copyright symbol: \\251, \\xA9, \\u00a9.\n\n~~Commented out."; File aptFile = null;//from ww w . j ava 2 s . c o m String from = "apt"; File out = null; try { out = File.createTempFile("fromAptToXHTML", ".html"); InputStream apt = new ByteArrayInputStream(result.getBytes()); try { aptFile = File.createTempFile("wooki", ".apt"); FileOutputStream fos = new FileOutputStream(aptFile); logger.debug("APT File is " + aptFile.getAbsolutePath()); byte[] content = null; int available = 0; while ((available = apt.available()) > 0) { content = new byte[available]; apt.read(content); fos.write(content); } fos.flush(); fos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } String to = "xhtml"; Converter converter = new DefaultConverter(); InputFileWrapper input = InputFileWrapper.valueOf(aptFile.getAbsolutePath(), from, "ISO-8859-1", converter.getInputFormats()); OutputFileWrapper output = OutputFileWrapper.valueOf(out.getAbsolutePath(), to, "UTF-8", converter.getOutputFormats()); converter.convert(input, output); } catch (UnsupportedFormatException e) { e.printStackTrace(); } catch (ConverterException e) { e.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } InputStream newHTML = fromAptToDocbook.performTransformation(new FileSystemResource(out)); SAXParserFactory factory = SAXParserFactory.newInstance(); // cration d'un parseur SAX SAXParser parser; try { parser = factory.newSAXParser(); parser.parse(new InputSource(newHTML), htmlParser); } catch (ParserConfigurationException e) { e.printStackTrace(); logger.error(e.getLocalizedMessage()); } catch (SAXException e) { e.printStackTrace(); logger.error(e.getLocalizedMessage()); } catch (IOException e) { e.printStackTrace(); logger.error(e.getLocalizedMessage()); } Book book = htmlParser.getBook(); logger.debug("The book title is " + book.getTitle()); }
From source file:ch.entwine.weblounge.common.impl.content.image.ImageContentReader.java
/** * This method is called to parse the serialized XML of a * {@link ch.entwine.weblounge.common.content.ResourceContent}. * //from w w w. j av a 2 s.co m * @param is * the content data * @throws ParserConfigurationException * if the SAX parser setup failed * @throws IOException * if reading the input stream fails * @throws SAXException * if an error occurs while parsing */ public ImageContent createFromXml(InputStream is) throws SAXException, IOException, ParserConfigurationException { SAXParser parser = parserRef.get(); if (parser == null) { parser = parserFactory.newSAXParser(); parserRef = new WeakReference<SAXParser>(parser); } parser.parse(is, this); return content; }
From source file:com.connectsdk.service.netcast.NetcastHttpServer.java
public void start() { //TODO: this method is too complex and should be refactored if (running)/*from w ww .j a v a 2s . c o m*/ return; running = true; try { welcomeSocket = new ServerSocket(this.port); } catch (IOException ex) { ex.printStackTrace(); } while (running) { if (welcomeSocket == null || welcomeSocket.isClosed()) { stop(); break; } Socket connectionSocket = null; BufferedReader inFromClient = null; DataOutputStream outToClient = null; try { connectionSocket = welcomeSocket.accept(); } catch (IOException ex) { ex.printStackTrace(); // this socket may have been closed, so we'll stop stop(); return; } String str = null; int c; StringBuilder sb = new StringBuilder(); try { inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); while ((str = inFromClient.readLine()) != null) { if (str.equals("")) { break; } } while ((c = inFromClient.read()) != -1) { sb.append((char) c); String temp = sb.toString(); if (temp.endsWith("</envelope>")) break; } } catch (IOException ex) { ex.printStackTrace(); } String body = sb.toString(); Log.d(Util.T, "got message body: " + body); Calendar calendar = Calendar.getInstance(); SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); String date = dateFormat.format(calendar.getTime()); String androidOSVersion = android.os.Build.VERSION.RELEASE; PrintWriter out = null; try { outToClient = new DataOutputStream(connectionSocket.getOutputStream()); out = new PrintWriter(outToClient); out.println("HTTP/1.1 200 OK"); out.println("Server: Android/" + androidOSVersion + " UDAP/2.0 ConnectSDK/1.2.1"); out.println("Cache-Control: no-store, no-cache, must-revalidate"); out.println("Date: " + date); out.println("Connection: Close"); out.println("Content-Length: 0"); out.println(); out.flush(); } catch (IOException ex) { ex.printStackTrace(); } finally { try { inFromClient.close(); out.close(); outToClient.close(); connectionSocket.close(); } catch (IOException ex) { ex.printStackTrace(); } } SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); InputStream stream = null; try { stream = new ByteArrayInputStream(body.getBytes("UTF-8")); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } NetcastPOSTRequestParser handler = new NetcastPOSTRequestParser(); SAXParser saxParser; try { saxParser = saxParserFactory.newSAXParser(); saxParser.parse(stream, handler); } catch (IOException ex) { ex.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } if (body.contains("ChannelChanged")) { ChannelInfo channel = NetcastChannelParser.parseRawChannelData(handler.getJSONObject()); Log.d(Util.T, "Channel Changed: " + channel.getNumber()); for (URLServiceSubscription<?> sub : subscriptions) { if (sub.getTarget().equalsIgnoreCase("ChannelChanged")) { for (int i = 0; i < sub.getListeners().size(); i++) { @SuppressWarnings("unchecked") ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners() .get(i); Util.postSuccess(listener, channel); } } } } else if (body.contains("KeyboardVisible")) { boolean focused = false; TextInputStatusInfo keyboard = new TextInputStatusInfo(); keyboard.setRawData(handler.getJSONObject()); try { JSONObject currentWidget = (JSONObject) handler.getJSONObject().get("currentWidget"); focused = (Boolean) currentWidget.get("focus"); keyboard.setFocused(focused); } catch (JSONException e) { e.printStackTrace(); } Log.d(Util.T, "KeyboardFocused?: " + focused); for (URLServiceSubscription<?> sub : subscriptions) { if (sub.getTarget().equalsIgnoreCase("KeyboardVisible")) { for (int i = 0; i < sub.getListeners().size(); i++) { @SuppressWarnings("unchecked") ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners() .get(i); Util.postSuccess(listener, keyboard); } } } } else if (body.contains("TextEdited")) { System.out.println("TextEdited"); String newValue = ""; try { newValue = handler.getJSONObject().getString("value"); } catch (JSONException ex) { ex.printStackTrace(); } Util.postSuccess(textChangedListener, newValue); } else if (body.contains("3DMode")) { try { String enabled = (String) handler.getJSONObject().get("value"); boolean bEnabled; bEnabled = enabled.equalsIgnoreCase("true"); for (URLServiceSubscription<?> sub : subscriptions) { if (sub.getTarget().equalsIgnoreCase("3DMode")) { for (int i = 0; i < sub.getListeners().size(); i++) { @SuppressWarnings("unchecked") ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners() .get(i); Util.postSuccess(listener, bEnabled); } } } } catch (JSONException e) { e.printStackTrace(); } } } }
From source file:com.connectsdk.device.netcast.NetcastHttpServer.java
public void start() { if (running)//from w ww . j a v a 2s. c om return; running = true; try { welcomeSocket = new ServerSocket(this.port); } catch (IOException ex) { ex.printStackTrace(); } while (running) { if (welcomeSocket == null || welcomeSocket.isClosed()) { stop(); break; } Socket connectionSocket = null; BufferedReader inFromClient = null; DataOutputStream outToClient = null; try { connectionSocket = welcomeSocket.accept(); } catch (IOException ex) { ex.printStackTrace(); // this socket may have been closed, so we'll stop stop(); return; } String str = null; int c; StringBuilder sb = new StringBuilder(); try { inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); while ((str = inFromClient.readLine()) != null) { if (str.equals("")) { break; } } while ((c = inFromClient.read()) != -1) { sb.append((char) c); String temp = sb.toString(); if (temp.endsWith("</envelope>")) break; } } catch (IOException ex) { ex.printStackTrace(); } String body = sb.toString(); Log.d("Connect SDK", "got message body: " + body); Calendar calendar = Calendar.getInstance(); SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); String date = dateFormat.format(calendar.getTime()); String androidOSVersion = android.os.Build.VERSION.RELEASE; PrintWriter out = null; try { outToClient = new DataOutputStream(connectionSocket.getOutputStream()); out = new PrintWriter(outToClient); out.println("HTTP/1.1 200 OK"); out.println("Server: Android/" + androidOSVersion + " UDAP/2.0 ConnectSDK/1.2.1"); out.println("Cache-Control: no-store, no-cache, must-revalidate"); out.println("Date: " + date); out.println("Connection: Close"); out.println("Content-Length: 0"); out.flush(); } catch (IOException ex) { ex.printStackTrace(); } finally { try { inFromClient.close(); out.close(); outToClient.close(); connectionSocket.close(); } catch (IOException ex) { ex.printStackTrace(); } } SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); InputStream stream = null; try { stream = new ByteArrayInputStream(body.getBytes("UTF-8")); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } NetcastPOSTRequestParser handler = new NetcastPOSTRequestParser(); SAXParser saxParser; try { saxParser = saxParserFactory.newSAXParser(); saxParser.parse(stream, handler); } catch (IOException ex) { ex.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } if (body.contains("ChannelChanged")) { ChannelInfo channel = NetcastChannelParser.parseRawChannelData(handler.getJSONObject()); Log.d("Connect SDK", "Channel Changed: " + channel.getNumber()); for (URLServiceSubscription<?> sub : subscriptions) { if (sub.getTarget().equalsIgnoreCase("ChannelChanged")) { for (int i = 0; i < sub.getListeners().size(); i++) { @SuppressWarnings("unchecked") ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners() .get(i); Util.postSuccess(listener, channel); } } } } else if (body.contains("KeyboardVisible")) { boolean focused = false; TextInputStatusInfo keyboard = new TextInputStatusInfo(); keyboard.setRawData(handler.getJSONObject()); try { JSONObject currentWidget = (JSONObject) handler.getJSONObject().get("currentWidget"); focused = (Boolean) currentWidget.get("focus"); keyboard.setFocused(focused); } catch (JSONException e) { e.printStackTrace(); } Log.d("Connect SDK", "KeyboardFocused?: " + focused); for (URLServiceSubscription<?> sub : subscriptions) { if (sub.getTarget().equalsIgnoreCase("KeyboardVisible")) { for (int i = 0; i < sub.getListeners().size(); i++) { @SuppressWarnings("unchecked") ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners() .get(i); Util.postSuccess(listener, keyboard); } } } } else if (body.contains("TextEdited")) { System.out.println("TextEdited"); String newValue = ""; try { newValue = handler.getJSONObject().getString("value"); } catch (JSONException ex) { ex.printStackTrace(); } Util.postSuccess(textChangedListener, newValue); } else if (body.contains("3DMode")) { try { String enabled = (String) handler.getJSONObject().get("value"); boolean bEnabled; if (enabled.equalsIgnoreCase("true")) bEnabled = true; else bEnabled = false; for (URLServiceSubscription<?> sub : subscriptions) { if (sub.getTarget().equalsIgnoreCase("3DMode")) { for (int i = 0; i < sub.getListeners().size(); i++) { @SuppressWarnings("unchecked") ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners() .get(i); Util.postSuccess(listener, bEnabled); } } } } catch (JSONException e) { e.printStackTrace(); } } } }
From source file:com.sshtools.common.hosts.AbstractHostKeyVerification.java
/** * Creates a new AbstractHostKeyVerification object. * * @param hostFileName// w w w . j a va2 s . c om * * @throws InvalidHostFileException */ public AbstractHostKeyVerification(String hostFileName) throws InvalidHostFileException { InputStream in = null; try { // If no host file is supplied, or there is not enough permission to load // the file, then just create an empty list. if (hostFileName != null) { if (System.getSecurityManager() != null) { AccessController.checkPermission(new FilePermission(hostFileName, "read")); } // Load the hosts file. Do not worry if fle doesnt exist, just disable // save of File f = new File(hostFileName); if (f.exists()) { in = new FileInputStream(f); hostFile = hostFileName; SAXParserFactory saxFactory = SAXParserFactory.newInstance(); SAXParser saxParser = saxFactory.newSAXParser(); saxParser.parse(in, this); hostFileWriteable = f.canWrite(); } else { // Try to create the file if (f.createNewFile()) { FileOutputStream out = new FileOutputStream(f); out.write(toString().getBytes()); out.close(); hostFileWriteable = true; } else { hostFileWriteable = false; } } if (!hostFileWriteable) { log.warn("Host file is not writeable."); } } } catch (AccessControlException ace) { log.warn("Not enough permission to load a hosts file, so just creating an empty list"); } catch (IOException ioe) { throw new InvalidHostFileException("Could not open or read " + hostFileName); } catch (SAXException sax) { throw new InvalidHostFileException("Failed XML parsing: " + sax.getMessage()); } catch (ParserConfigurationException pce) { throw new InvalidHostFileException("Failed to initialize xml parser: " + pce.getMessage()); } finally { if (in != null) { try { in.close(); } catch (IOException ioe) { } } } }