List of usage examples for javax.xml.parsers SAXParserFactory newInstance
public static SAXParserFactory newInstance()
From source file:com.sun.faban.harness.webclient.CLIServlet.java
private void sendLogs(String[] reqC, HttpServletResponse response) throws ServletException, IOException { if (reqC.length < 2) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing RunId."); return;/* ww w . j a v a2 s . c o m*/ } RunId runId = new RunId(reqC[1]); boolean[] options = new boolean[2]; options[TAIL] = false; options[FOLLOW] = false; for (int i = 2; i < reqC.length; i++) { if ("tail".equals(reqC[i])) { options[TAIL] = true; } else if ("follow".equals(reqC[i])) { options[FOLLOW] = true; } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid option \"" + reqC[i] + "\"."); ; return; } } File logFile = new File(Config.OUT_DIR + runId, "log.xml"); String status = null; response.setContentType("text/plain"); PrintWriter out = response.getWriter(); while (!logFile.exists()) { String[] pending = RunQ.listPending(); if (pending == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND, "RunId " + runId + " not found"); return; } boolean queued = false; for (String run : pending) { if (run.equals(runId.toString())) { if (status == null) { status = "QUEUED"; out.println(status); response.flushBuffer(); } queued = true; try { Thread.sleep(1000); // Check back in one sec. } catch (InterruptedException e) { //Noop, just look it up again. } break; } } if (!queued) { // Either never queued or deleted from queue. // Check for 10x, 100ms each to allow for start time. for (int i = 0; i < 10; i++) { if (logFile.exists()) { status = "STARTED"; break; } try { Thread.sleep(100); } catch (InterruptedException e) { logger.log(Level.WARNING, "Interrupted checking existence of log file."); } } if (!"STARTED".equals(status)) { if ("QUEUED".equals(status)) { // was queued before status = "DELETED"; out.println(status); out.flush(); out.close(); return; } else { // Never queued or just removed. response.sendError(HttpServletResponse.SC_NOT_FOUND, "RunId " + runId + " not found"); return; } } } } LogOutputHandler handler = new LogOutputHandler(response, options); InputStream logInput; if (options[FOLLOW]) { // The XMLInputStream reads streaming XML and does not EOF. XMLInputStream input = new XMLInputStream(logFile); input.addEOFListener(handler); logInput = input; } else { logInput = new FileInputStream(logFile); } try { SAXParserFactory sFact = SAXParserFactory.newInstance(); sFact.setFeature("http://xml.org/sax/features/validation", false); sFact.setFeature("http://apache.org/xml/features/" + "allow-java-encodings", true); sFact.setFeature("http://apache.org/xml/features/nonvalidating/" + "load-dtd-grammar", false); sFact.setFeature("http://apache.org/xml/features/nonvalidating/" + "load-external-dtd", false); SAXParser parser = sFact.newSAXParser(); parser.parse(logInput, handler); handler.xmlComplete = true; // If we get here, the XML is good. } catch (ParserConfigurationException e) { throw new ServletException(e); } catch (SAXParseException e) { Throwable t = e.getCause(); // If it is caused by an IOException, we'll just throw it. if (t != null) { if (t instanceof IOException) throw (IOException) t; else if (options[FOLLOW]) throw new ServletException(t); } else if (options[FOLLOW]) { throw new ServletException(e); } } catch (SAXException e) { throw new ServletException(e); } finally { if (options[TAIL] && !options[FOLLOW]) // tail not yet printed handler.eof(); } }
From source file:com.magicmod.mmweather.engine.YahooWeatherProvider.java
@Override public void refreshData(String id, String localizedCityName, boolean metricUnits) { mCityId = id;/*w w w . j av a2 s. c o m*/ mLocalizedCityName = localizedCityName; mMetricUnits = metricUnits; String url = String.format(URL_WEATHER, id, metricUnits ? "c" : "f"); String response = HttpRetriever.retrieve(url); if (response == null) { mWeatherInfo = null; return; } SAXParserFactory factory = SAXParserFactory.newInstance(); try { SAXParser parser = factory.newSAXParser(); StringReader reader = new StringReader(response); WeatherHandler handler = new WeatherHandler(); parser.parse(new InputSource(reader), handler); if (handler.isComplete()) { // There are cases where the current condition is unknown, but the forecast // is not - using the (inaccurate) forecast is probably better than showing // the question mark if (handler.conditionCode.equals(3200)) { handler.condition = handler.forecasts.get(0).getCondition(); handler.conditionCode = handler.forecasts.get(0).getConditionCode(); } ArrayList<DayForecast> forecasts = new ArrayList<WeatherInfo.DayForecast>(); long time = System.currentTimeMillis(); for (DayForecast forecast : handler.forecasts) { if (forecast.getDate().equals(handler.date)) { forecast.setCondition(handler.condition); forecast.setConditionCode(handler.conditionCode); forecast.setHumidity(handler.humidity); forecast.setSunRaise(handler.sunrise); forecast.setSunSet(handler.sunset); forecast.setTemperature(handler.temperature); forecast.setTempUnit(handler.temperatureUnit); forecast.setWindSpeed(handler.windSpeed); forecast.setWindDirection(handler.windDirection); forecast.setWindSpeedUnit(handler.speedUnit); } if (localizedCityName != null) { forecast.setCity(localizedCityName); } forecast.setSynctimestamp(String.valueOf(time)); forecasts.add(forecast); } mWeatherInfo = new WeatherInfo(forecasts); Log.d(TAG, "Weather updated: " + mWeatherInfo); } else { Log.w(TAG, "Received incomplete weather XML (id=" + id + ")"); mWeatherInfo = null; } } catch (ParserConfigurationException e) { Log.e(TAG, "Could not create XML parser", e); mWeatherInfo = null; } catch (SAXException e) { Log.e(TAG, "Could not parse weather XML (id=" + id + ")", e); mWeatherInfo = null; } catch (IOException e) { Log.e(TAG, "Could not parse weather XML (id=" + id + ")", e); mWeatherInfo = null; } if (mWeatherDataChangedListener != null) mWeatherDataChangedListener.onDataChanged(); }
From source file:gov.nih.nci.ncicb.tcga.dcc.common.jaxb.JAXBUtil.java
private static SAXSource applyMetaDataNamespaceFilter(final Unmarshaller unmarshaller, final Reader xmlFileReader) throws SAXException, ParserConfigurationException, FileNotFoundException { final SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); // this should not be changed! final XMLReader reader = factory.newSAXParser().getXMLReader(); final XMLFilterImpl xmlFilter = new MetaDataXMLNamespaceFilter(reader); reader.setContentHandler(unmarshaller.getUnmarshallerHandler()); return new SAXSource(xmlFilter, new InputSource(xmlFileReader)); }
From source file:com.mbeddr.pluginmanager.com.intellij.ide.plugins.RepositoryHelper.java
private static List<IdeaPluginDescriptor> parsePluginList(@NotNull Reader reader) throws IOException { try {/* w w w . j av a 2 s. c om*/ SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); RepositoryContentHandler handler = new RepositoryContentHandler(); parser.parse(new InputSource(reader), handler); return handler.getPluginsList(); } catch (ParserConfigurationException e) { throw new IOException(e); } catch (SAXException e) { throw new IOException(e); } finally { reader.close(); } }
From source file:eionet.gdem.conversion.spreadsheet.DDXMLConverter.java
/** * Converts XML file/*from w w w . java2 s. c o m*/ * @param xmlSchema XML schema * @param outStream OutputStream * @throws Exception If an error occurs. */ protected void doConversion(String xmlSchema, OutputStream outStream) throws Exception { String instanceUrl = DataDictUtil.getInstanceUrl(xmlSchema); DD_XMLInstance instance = new DD_XMLInstance(instanceUrl); DD_XMLInstanceHandler handler = new DD_XMLInstanceHandler(instance); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); factory.setValidating(false); factory.setNamespaceAware(true); reader.setFeature("http://xml.org/sax/features/validation", false); reader.setFeature("http://apache.org/xml/features/validation/schema", false); reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); reader.setFeature("http://xml.org/sax/features/namespaces", true); reader.setContentHandler(handler); reader.parse(instanceUrl); if (Utils.isNullStr(instance.getEncoding())) { String enc_url = Utils.getEncodingFromStream(instanceUrl); if (!Utils.isNullStr(enc_url)) { instance.setEncoding(enc_url); } } importSheetSchemas(sourcefile, instance, xmlSchema); instance.startWritingXml(outStream); sourcefile.writeContentToInstance(instance); instance.flushXml(); }
From source file:dreamboxdataservice.DreamboxDataService.java
private void getEPGData(TvDataUpdateManager updateManager, Channel ch) { try {// w w w . j ava 2s. co m URL url = new URL("http://" + mProperties.getProperty("ip", "") + "/web/epgservice?sRef=" + StringUtils.replace(StringUtils.replace(ch.getId().substring(5), "_", ":"), " ", "%20")); URLConnection connection = url.openConnection(); String userpassword = mProperties.getProperty("username", "") + ":" + IOUtilities .xorEncode(mProperties.getProperty("password", ""), DreamboxSettingsPanel.PASSWORDSEED); String encoded = new String(Base64.encodeBase64(userpassword.getBytes())); connection.setRequestProperty("Authorization", "Basic " + encoded); connection.setConnectTimeout(60); InputStream stream = connection.getInputStream(); SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); DreamboxChannelHandler handler = new DreamboxChannelHandler(updateManager, ch); saxParser.parse(stream, handler); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:se.lu.nateko.edca.svc.DescribeFeatureType.java
/** * Parses an XML response from a DescribeFeatureType request and stores the layer * attribute names and their data types in a GeographyLayer object. * @param xmlResponse A reader wrapped around an InputStream containing the XML response from a DescribeFeatureType request. *///from w w w .j a v a 2 s.co m protected boolean parseXMLResponse(Reader xmlResponse) { // Log.d(TAG, "parseXMLResponse(Reader) called."); try { SAXParserFactory spfactory = SAXParserFactory.newInstance(); // Make a SAXParser factory. spfactory.setValidating(false); // Tell the factory not to make validating parsers. SAXParser saxParser = spfactory.newSAXParser(); // Use the factory to make a SAXParser. XMLReader xmlReader = saxParser.getXMLReader(); // Get an XML reader from the parser, which will send event calls to its specified event handler. XMLEventHandler xmlEventHandler = new XMLEventHandler(); xmlReader.setContentHandler(xmlEventHandler); // Set which event handler to use. xmlReader.setErrorHandler(xmlEventHandler); // Also set where to send error calls. InputSource source = new InputSource(xmlResponse); // Make an InputSource from the XML input to give to the reader. xmlReader.parse(source); // Start parsing the XML. } catch (Exception e) { Log.e(TAG, e.toString()); return false; } return true; }
From source file:info.magnolia.about.app.AboutPresenter.java
String getRepoName() { String repoConfigPath = magnoliaProperties.getProperty("magnolia.repositories.config"); File config = new File(magnoliaProperties.getProperty("magnolia.app.rootdir") + "/" + repoConfigPath); final String[] repoName = new String[1]; try {//from w w w. ja va2s . c om SAXParserFactory.newInstance().newSAXParser().parse(config, new DefaultHandler() { private boolean inRepo; @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { super.startElement(uri, localName, qName, attributes); if ("RepositoryMapping".equals(qName)) { inRepo = true; } if (inRepo && "Map".equals(qName)) { if ("config".equals(attributes.getValue("name"))) { repoName[0] = attributes.getValue("repositoryName"); } } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { super.endElement(uri, localName, qName); if ("RepositoryMapping".equals(localName)) { inRepo = false; } } }); return repoName[0]; } catch (Exception e) { log.debug("Failed to obtain repository configuration info with {}", e.getMessage(), e); } return null; }
From source file:org.semantictools.frame.api.OntologyManager.java
private void loadXsd(File file) throws SchemaParseException { try {//www .j ava 2s .com SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setFeature("http://xml.org/sax/features/namespaces", true); NamespaceReader handler = new NamespaceReader(); reader.setContentHandler(handler); parser.parse(file, handler); String namespace = handler.getTargetNamespace(); if (namespace == null) { logger.warn("Ignoring schema since targetNamespace is not declared: " + file.getPath()); } else { OntologyEntity entity = new OntologyEntity(XML_FORMAT, file, namespace); uri2OntologyEntity.put(namespace, entity); } } catch (Throwable oops) { throw new SchemaParseException(oops); } }
From source file:com.wlcg.aroundme.cc.weather.YahooWeatherProvider.java
@Override public WeatherInfo getWeatherInfo(String id, String localizedCityName, boolean metricUnits) { mCityId = id;//w w w .j av a 2 s .c om mLocalizedCityName = localizedCityName; mMetricUnits = metricUnits; String url = String.format(URL_WEATHER, id, metricUnits ? "c" : "f"); Log.d(TAG, "URL is => " + url); String response = HttpRetriever.retrieve(url); if (response == null) { //mWeatherInfo = null; return null; } WeatherInfo info = null; SAXParserFactory factory = SAXParserFactory.newInstance(); try { SAXParser parser = factory.newSAXParser(); StringReader reader = new StringReader(response); WeatherHandler handler = new WeatherHandler(); parser.parse(new InputSource(reader), handler); if (handler.isComplete()) { // There are cases where the current condition is unknown, but the forecast // is not - using the (inaccurate) forecast is probably better than showing // the question mark if (handler.conditionCode.equals(3200)) { handler.condition = handler.forecasts.get(0).getCondition(); handler.conditionCode = handler.forecasts.get(0).getConditionCode(); } ArrayList<DayForecast> forecasts = new ArrayList<WeatherInfo.DayForecast>(); String time = new SimpleDateFormat("yyyy/MM/dd HH:mm").format(new java.util.Date()); for (DayForecast forecast : handler.forecasts) { if (forecast.getDate().equals(handler.date)) { forecast.setCondition(handler.condition); forecast.setConditionCode(handler.conditionCode); forecast.setHumidity(handler.humidity); forecast.setSunRaise(handler.sunrise); forecast.setSunSet(handler.sunset); forecast.setTemperature(handler.temperature); forecast.setTempUnit(handler.temperatureUnit); forecast.setWindSpeed(handler.windSpeed); forecast.setWindDirection(handler.windDirection); forecast.setWindSpeedUnit(handler.speedUnit); } if (localizedCityName != null) { forecast.setCity(localizedCityName); } forecast.setSynctimestamp(time); forecasts.add(forecast); //Log.d(TAG, "Weather forecast is => " + forecast); } //mWeatherInfo = new WeatherInfo(forecasts); info = new WeatherInfo(forecasts); Log.d(TAG, "Weather updated: " + info); } else { Log.w(TAG, "Received incomplete weather XML (id=" + id + ")"); //mWeatherInfo = null; info = null; } } catch (ParserConfigurationException e) { Log.e(TAG, "Could not create XML parser", e); //mWeatherInfo = null; info = null; } catch (SAXException e) { Log.e(TAG, "Could not parse weather XML (id=" + id + ")", e); //mWeatherInfo = null; info = null; } catch (IOException e) { Log.e(TAG, "Could not parse weather XML (id=" + id + ")", e); //mWeatherInfo = null; info = null; } if (mWeatherDataChangedListener != null) mWeatherDataChangedListener.onDataChanged(); return info; }