List of usage examples for javax.xml.parsers SAXParserFactory newInstance
public static SAXParserFactory newInstance()
From source file:com.phonemetra.lockclock.weather.YahooWeatherProvider.java
@Override public WeatherInfo getWeatherInfo(String id, String localizedCityName, boolean metric) { String url = String.format(URL_WEATHER, id, metric ? "c" : "f"); String response = HttpRetriever.retrieve(url); if (response == null) { return null; }//from w ww . ja v a 2 s. c o m 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 == 3200) { handler.condition = handler.forecasts.get(0).condition; handler.conditionCode = handler.forecasts.get(0).conditionCode; } WeatherInfo w = new WeatherInfo(mContext, id, localizedCityName != null ? localizedCityName : handler.city, handler.condition, handler.conditionCode, handler.temperature, handler.temperatureUnit, handler.humidity, handler.windSpeed, handler.windDirection, handler.speedUnit, handler.forecasts, System.currentTimeMillis()); Log.d(TAG, "Weather updated: " + w); return w; } else { Log.w(TAG, "Received incomplete weather XML (id=" + id + ")"); } } catch (ParserConfigurationException e) { Log.e(TAG, "Could not create XML parser", e); } catch (SAXException e) { Log.e(TAG, "Could not parse weather XML (id=" + id + ")", e); } catch (IOException e) { Log.e(TAG, "Could not parse weather XML (id=" + id + ")", e); } return null; }
From source file:egat.cli.strategyregret.StrategyRegretCommandHandler.java
protected void processSymmetricGame(MutableSymmetricGame game) throws CommandProcessingException { try {/* ww w . ja v a2s . c o m*/ Profile profile = null; if (uniform) { Player[] players = game.players().toArray(new Player[0]); Strategy[] strategies = new Strategy[players.length]; Action[] actions = ((Set<Action>) game.getActions()).toArray(new Action[0]); Number[] distribution = new Number[actions.length]; Arrays.fill(distribution, 1.0 / distribution.length); Strategy strategy = Games.createStrategy(actions, distribution); Arrays.fill(strategies, strategy); profile = Games.createProfile(players, strategies); } else { InputStream inputStream = null; inputStream = new FileInputStream(profilePath); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); ProfileHandler handler = new ProfileHandler(); parser.parse(inputStream, handler); profile = handler.getProfile(); } findRegret(profile, game); } catch (NonexistentPayoffException e) { System.err.println(String.format("Could not calculate regret. %s", e.getMessage())); } catch (FileNotFoundException e) { throw new CommandProcessingException(e); } catch (ParserConfigurationException e) { throw new CommandProcessingException(e); } catch (SAXException e) { throw new CommandProcessingException(e); } catch (IOException e) { throw new CommandProcessingException(e); } }
From source file:net.sf.ehcache.config.Configurator.java
/** * Configures a bean from an XML file in the classpath. */// w w w. java 2s .c o m public void configure(final Object bean) throws Exception { final SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); final BeanHandler handler = new BeanHandler(bean); URL url = getClass().getResource(DEFAULT_CLASSPATH_CONFIGURATION_FILE); if (url != null) { if (LOG.isDebugEnabled()) { LOG.debug("Configuring ehcache from ehcache.xml found in the classpath: " + url); } } else { url = getClass().getResource(FAILSAFE_CLASSPATH_CONFIGURATION_FILE); if (LOG.isWarnEnabled()) { LOG.warn("No configuration found. Configuring ehcache from ehcache-failsafe.xml" + " found in the classpath: " + url); } } parser.parse(url.toExternalForm(), handler); }
From source file:com.openbravo.pos.sales.JTicketLines.java
/** Creates new form JLinesTicket */ public JTicketLines(AppView app, String propertyRowHeight, String propertyFontsize, String ticketline) { this.m_App = app; initComponents();/*w ww . j ava 2 s. com*/ m_jTicketTable.m_App = app; m_jTicketTable.propertyRowHeight = propertyRowHeight; ColumnTicket[] acolumns = new ColumnTicket[0]; if (ticketline != null) { try { if (m_sp == null) { SAXParserFactory spf = SAXParserFactory.newInstance(); m_sp = spf.newSAXParser(); } ColumnsHandler columnshandler = new ColumnsHandler(); m_sp.parse(new InputSource(new StringReader(ticketline)), columnshandler); acolumns = columnshandler.getColumns(); } 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); } } Map<String, Integer> widths = PropertyUtil.getTicketLineWidths(m_App); for (ColumnTicket acolumn : acolumns) { Integer width = widths.get(acolumn.name); if (width == null) { continue; } acolumn.width = width; } m_jTableModel = new TicketTableModel(acolumns); m_jTicketTable.setModel(m_jTableModel); m_jTicketTable.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN); TableColumnModel jColumns = m_jTicketTable.getColumnModel(); for (int i = 0; i < acolumns.length; i++) { jColumns.getColumn(i).setPreferredWidth(acolumns[i].width); jColumns.getColumn(i).setResizable(true); } PropertyUtil.ScaleScrollbar(m_App, m_jScrollTableTicket); m_jTicketTable.getTableHeader().setReorderingAllowed(false); // m_jTicketTable.setDefaultRenderer(Object.class, new // TicketCellRenderer(app, acolumns, propertyFontsize)); m_jTicketTable.setDefaultRenderer(Object.class, new RowHeightCellRenderer(app, acolumns, propertyFontsize, propertyRowHeight)); PropertyUtil.ScaleTableColumnFontsize(m_App, m_jTicketTable, "sales-tablecolumn-fontsize", "14"); m_jTicketTable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION); m_jTicketTable.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { JTable table = (JTable) me.getSource(); Point p = me.getPoint(); int row = table.rowAtPoint(p); if (me.getClickCount() == 2) { // your valueChanged overridden method listDoubleClickListener.valueChanged(new ListSelectionEvent(m_jTicketTable, row, row, false)); } } }); // reseteo la tabla... m_jTableModel.clear(); }
From source file:com.sshtools.common.hosts.AbstractHostKeyVerification.java
/** * Creates a new AbstractHostKeyVerification object. * * @param hostFileName//from www . j a v a 2s. co m * * @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) { } } } }
From source file:io.lightlink.excel.StreamingExcelTransformer.java
private List<String> processSharedStrings(byte[] bytes) throws ParserConfigurationException, SAXException, IOException { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); SharedStringsHandler handler = new SharedStringsHandler(); saxParser.parse(new ByteArrayInputStream(bytes), handler); return handler.getSharedStings(); }
From source file:com.esri.geoevent.solutions.adapter.cot.CoTAdapter.java
public CoTAdapter(AdapterDefinition adapterDefinition, String guid) throws ConfigurationException, ComponentException { super(adapterDefinition); this.guid = guid; messageParser = new MessageParser(null); saxFactory = SAXParserFactory.newInstance(); try {/*from w ww . ja v a 2 s . com*/ saxParser = saxFactory.newSAXParser(); } catch (ParserConfigurationException e) { e.printStackTrace(); saxParser = null; } catch (SAXException e) { e.printStackTrace(); saxParser = null; } }
From source file:com.cloudhopper.sxmp.SxmpParser.java
/** public Node parse(InputSource source) throws IOException, SAXException { // _dtd=null;/*from w w w. j a v a 2s . com*/ Handler handler = new Handler(); XMLReader reader = _parser.getXMLReader(); reader.setContentHandler(handler); reader.setErrorHandler(handler); reader.setEntityResolver(handler); if (logger.isDebugEnabled()) logger.debug("parsing: sid=" + source.getSystemId() + ",pid=" + source.getPublicId()); _parser.parse(source, handler); if (handler.error != null) throw handler.error; Node root = (Node)handler.root; handler.reset(); return root; } public synchronized Node parse(String xml) throws IOException, SAXException { ByteArrayInputStream is = new ByteArrayInputStream(xml.getBytes()); return parse(is); } public synchronized Node parse(File file) throws IOException, SAXException { return parse(new InputSource(file.toURI().toURL().toString())); } public synchronized Node parse(InputStream in) throws IOException, SAXException { //_dtd=null; Handler handler = new Handler(); XMLReader reader = _parser.getXMLReader(); reader.setContentHandler(handler); reader.setErrorHandler(handler); reader.setEntityResolver(handler); _parser.parse(new InputSource(in), handler); if (handler.error != null) throw handler.error; Node root = (Node)handler.root; handler.reset(); return root; } */ public Operation parse(InputStream in) throws SxmpParsingException, IOException, SAXException, ParserConfigurationException { // create a new SAX parser SAXParserFactory factory = SAXParserFactory.newInstance(); //factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); SAXParser parser = factory.newSAXParser(); //_parser.getXMLReader().setFeature("http://xml.org/sax/features/validation", validating); parser.getXMLReader().setFeature("http://xml.org/sax/features/namespaces", true); parser.getXMLReader().setFeature("http://xml.org/sax/features/namespace-prefixes", true); parser.getXMLReader().setFeature("http://javax.xml.XMLConstants/feature/secure-processing", true); //_dtd=null; Handler handler = new Handler(); XMLReader reader = parser.getXMLReader(); reader.setContentHandler(handler); reader.setErrorHandler(handler); reader.setEntityResolver(handler); // try parsing (may throw an SxmpParsingException in the handler) try { parser.parse(new InputSource(in), handler); } catch (com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException e) { throw new SxmpParsingException(SxmpErrorCode.INVALID_XML, "XML encoding mismatch", null); } // check if there was an error if (handler.error != null) { throw handler.error; } // check to see if an operation was actually parsed if (handler.getOperation() == null) { throw new SxmpParsingException(SxmpErrorCode.MISSING_REQUIRED_ELEMENT, "The operation type [" + handler.operationType.getValue() + "] requires a request element", new PartialOperation(handler.operationType)); } // if we got here, an operation was parsed -- now we need to validate it // to make sure that it has all required elements try { handler.getOperation().validate(); } catch (SxmpErrorException e) { throw new SxmpParsingException(e.getErrorCode(), e.getErrorMessage(), handler.getOperation()); } return handler.getOperation(); }
From source file:edu.uci.ics.jung.io.GraphMLReader.java
/** * Creates a <code>GraphMLReader</code> instance with the specified * vertex and edge factories.//from w w w .ja va 2 s . c o m * * @param vertex_factory the vertex factory to use to create vertex objects * @param edge_factory the edge factory to use to create edge objects * @throws ParserConfigurationException * @throws SAXException */ public GraphMLReader(Factory<V> vertex_factory, Factory<E> edge_factory) throws ParserConfigurationException, SAXException { current_vertex = null; current_edge = null; SAXParserFactory factory = SAXParserFactory.newInstance(); saxp = factory.newSAXParser(); current_states = new LinkedList<TagState>(); tag_state = new DualHashBidiMap<String, TagState>(); tag_state.put("node", TagState.VERTEX); tag_state.put("edge", TagState.EDGE); tag_state.put("hyperedge", TagState.HYPEREDGE); tag_state.put("endpoint", TagState.ENDPOINT); tag_state.put("graph", TagState.GRAPH); tag_state.put("data", TagState.DATA); tag_state.put("key", TagState.KEY); tag_state.put("desc", TagState.DESC); tag_state.put("default", TagState.DEFAULT_KEY); tag_state.put("graphml", TagState.GRAPHML); this.key_type = KeyType.NONE; this.vertex_factory = vertex_factory; this.edge_factory = edge_factory; }
From source file:com.mirth.connect.plugins.datatypes.dicom.DICOMSerializer.java
@Override public String fromXML(String source) throws MessageSerializerException { if (source == null || source.length() == 0) { return org.apache.commons.lang3.StringUtils.EMPTY; }/*from www .j a v a 2s . c o m*/ try { // re-parse the xml to Mirth format Document document = documentSerializer.fromXML(source); Element element = document.getDocumentElement(); Node node = element.getChildNodes().item(0); // change back to <attr> tag for all tags under <dicom> tag while (node != null) { renameTagToAttr(document, node); node = node.getNextSibling(); } NodeList items = document.getElementsByTagName("item"); // change back to <attr> tag for all tags under <item> tags if (items != null) { for (int i = 0; i < items.getLength(); i++) { Node itemNode = items.item(i); if (itemNode.getChildNodes() != null) { NodeList itemNodes = itemNode.getChildNodes(); for (int j = 0; j < itemNodes.getLength(); j++) { Node nodeItem = itemNodes.item(j); renameTagToAttr(document, nodeItem); } } } } // find the charset String charset = null; Element charsetElement = (Element) document.getElementsByTagName("tag00080005").item(0); if (charsetElement != null) { charset = charsetElement.getNodeValue(); } else { charset = "utf-8"; } // parse the Document into a DicomObject SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); DicomObject dicomObject = new BasicDicomObject(); ContentHandlerAdapter contentHandler = new ContentHandlerAdapter(dicomObject); byte[] documentBytes = documentSerializer.toXML(document).trim().getBytes(charset); parser.parse(new InputSource(new ByteArrayInputStream(documentBytes)), contentHandler); return StringUtils .newStringUsAscii(Base64Util.encodeBase64(DICOMConverter.dicomObjectToByteArray(dicomObject))); } catch (Exception e) { throw new MessageSerializerException("Error converting XML to DICOM", e, ErrorMessageBuilder .buildErrorMessage(this.getClass().getSimpleName(), "Error converting XML to DICOM", e)); } }