List of usage examples for javax.xml.parsers SAXParser parse
public void parse(InputSource is, DefaultHandler dh) throws SAXException, IOException
From source file:elaborate.util.XmlUtil.java
public static boolean isWellFormed(String body) { try {/*ww w. j av a2s . c o m*/ SAXParser parser; parser = SAXParserFactory.newInstance().newSAXParser(); DefaultHandler dh = new DefaultHandler(); parser.parse(new InputSource(new StringReader(body)), dh); } catch (ParserConfigurationException e1) { e1.printStackTrace(); return false; } catch (SAXException e1) { e1.printStackTrace(); Log.error("body={}", body); return false; } catch (IOException e) { e.printStackTrace(); return false; } return true; }
From source file:com.mbeddr.pluginmanager.com.intellij.ide.plugins.RepositoryHelper.java
private static List<IdeaPluginDescriptor> parsePluginList(@NotNull Reader reader) throws IOException { try {//from ww w . j av a 2s . co m 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:com.microsoft.tfs.core.externaltools.ExternalTool.java
/** * <p>//from www . j a v a 2 s . c om * Given a path to an application bundle (ie, Mac ".app" directory), * determine the path to the bundled executable. For example, given * /Applications/Camino.app, return * /Applications/Camino.app/Contents/MacOS/Camino. * </p> * * @param appBundle * path to the Mac .app bundle (must not be <code>null</code>) * @return the fully-qualified executable suitable for exec(), or null if * the path is not a valid mac application bundle */ private static String getMacCommand(final String appBundle) { Check.notNull(appBundle, "appBundle"); //$NON-NLS-1$ Map plistDict; final String plistPath = appBundle + "/Contents/Info.plist"; //$NON-NLS-1$ final File plistFile = new File(plistPath); if (!plistFile.exists() || !plistFile.canRead()) { return null; } try { final FileInputStream plistStream = new FileInputStream(plistFile); final SAXParser plistParser = SAXUtils.newSAXParser(); final PlistHandler plistHandler = new PlistHandler(); plistParser.parse(plistStream, plistHandler); final Object plist = plistHandler.getPlist(); if (!(plist instanceof Map)) { log.error(MessageFormat.format("Plist {0} does not contain dict", plistPath)); //$NON-NLS-1$ return null; } plistDict = (Map) plist; } catch (final IOException e) { log.error(MessageFormat.format("Could not read plist {0}", plistPath), e); //$NON-NLS-1$ return null; } catch (final ParserConfigurationException e) { log.error(MessageFormat.format("Could not parse plist {0}", plistPath), e); //$NON-NLS-1$ return null; } catch (final SAXException e) { log.error(MessageFormat.format("Could not parse plist {0}", plistPath), e); //$NON-NLS-1$ return null; } final Object executable = plistDict.get("CFBundleExecutable"); //$NON-NLS-1$ if (executable == null || !(executable instanceof String)) { log.error(MessageFormat.format("Plist {0} contains no string entry for CFBundleExecutable", plistPath)); //$NON-NLS-1$ return null; } return appBundle + "/Contents/MacOS/" + (String) executable; //$NON-NLS-1$ }
From source file:mcp.tools.nmap.parser.NmapXmlParser.java
public static void parse(File xmlResultsFile, String scanDescription, String commandLine) { Pattern endTimePattern = Pattern.compile("<runstats><finished time=\"(\\d+)"); String xmlResults;/*from www. ja v a 2 s . c o m*/ try { xmlResults = FileUtils.readFileToString(xmlResultsFile); } catch (IOException e) { logger.error("Failed to parse nmap results file '" + xmlResultsFile.toString() + "': " + e.getLocalizedMessage(), e); return; } Matcher m = endTimePattern.matcher(xmlResults); Instant scanTime = null; if (m.find()) { int t; try { t = Integer.parseInt(m.group(1)); scanTime = Instant.ofEpochSecond(t); } catch (NumberFormatException e) { } } if (scanTime == null) { logger.debug("Failed to find scan completion time in nmap results. Using current time."); scanTime = Instant.now(); } String path; try { path = xmlResultsFile.getCanonicalPath(); } catch (IOException e1) { logger.debug("Why did the canonical path fail?"); path = xmlResultsFile.getAbsolutePath(); } NmapScanSource source = new NmapScanSourceImpl(path, scanDescription, commandLine); NMapXmlHandler nmxh = new NMapXmlHandler(scanTime, source); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp; try { sp = spf.newSAXParser(); } catch (ParserConfigurationException e) { throw new UnexpectedException("This shouldn't have happened: " + e.getLocalizedMessage(), e); } catch (SAXException e) { throw new UnexpectedException("This shouldn't have happened: " + e.getLocalizedMessage(), e); } try { sp.parse(xmlResultsFile, nmxh); } catch (SAXException e) { logger.error("Failed to parse nmap results file '" + xmlResultsFile.toString() + "': " + e.getLocalizedMessage(), e); return; } catch (IOException e) { logger.error("Failed to parse nmap results file '" + xmlResultsFile.toString() + "': " + e.getLocalizedMessage(), e); return; } }
From source file:applab.search.client.ImageManager.java
public static void updateLocalImages() { // Get remote list InputStream xmlStream = getImageXml(); // Get local list HashMap<String, File> localImageList = getLocalImageList(); // Init Sax Parser & XML Handler SAXParser xmlParser; ImageXmlParseHandler xmlHandler = new ImageXmlParseHandler(); xmlHandler.setLocalImageList(localImageList); if (xmlStream == null) { return;//w w w . java 2 s . c o m } try { if (xmlStream != null) { xmlParser = SAXParserFactory.newInstance().newSAXParser(); // This line was causing problems on android 2.2 (IDEOS) // xmlParser.reset(); xmlParser.parse(xmlStream, xmlHandler); // Delete local files not on remote list for (Entry<String, File> localImage : localImageList.entrySet()) { File file = localImage.getValue(); String sha1Hash = localImage.getKey(); // Confirm this is the file we intend to delete (a new file with the same name may have been downloaded) if (ImageFilesUtility.getSHA1Hash(file).equalsIgnoreCase(sha1Hash)) { ImageFilesUtility.deleteFile(file); } } } } catch (SAXException e) { Log.e("ImageManager", "Error while parsing XML: " + e); } catch (IOException e) { Log.e("ImageManager", "Error while parsing XML: " + e); } catch (ParserConfigurationException e) { Log.e("ImageManager", "Error while parsing XML: " + e); } }
From source file:com.jkoolcloud.tnt4j.streams.configure.sax.StreamsConfigSAXParser.java
/** * Reads the configuration and invokes the (SAX-based) parser to parse the configuration file contents. * * @param config/*from w w w. jav a 2 s . c o m*/ * input stream to get configuration data from * @param validate * flag indicating whether to validate configuration XML against XSD schema * @return streams configuration data * @throws ParserConfigurationException * if there is an inconsistency in the configuration * @throws SAXException * if there was an error parsing the configuration * @throws IOException * if there is an error reading the configuration data */ public static StreamsConfigData parse(InputStream config, boolean validate) throws ParserConfigurationException, SAXException, IOException { if (validate) { config = config.markSupported() ? config : new ByteArrayInputStream(IOUtils.toByteArray(config)); Map<OpLevel, List<SAXParseException>> validationErrors = validate(config); if (MapUtils.isNotEmpty(validationErrors)) { for (Map.Entry<OpLevel, List<SAXParseException>> vee : validationErrors.entrySet()) { for (SAXParseException ve : vee.getValue()) { LOGGER.log(OpLevel.WARNING, StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME, "StreamsConfigSAXParser.xml.validation.error"), ve.getLineNumber(), ve.getColumnNumber(), vee.getKey(), ve.getLocalizedMessage()); } } } } Properties p = Utils.loadPropertiesResource("sax.properties"); // NON-NLS SAXParserFactory parserFactory = SAXParserFactory.newInstance(); SAXParser parser = parserFactory.newSAXParser(); ConfigParserHandler hndlr = null; try { String handlerClassName = p.getProperty(HANDLER_PROP_KEY, ConfigParserHandler.class.getName()); if (StringUtils.isNotEmpty(handlerClassName)) { hndlr = (ConfigParserHandler) Utils.createInstance(handlerClassName); } } catch (Exception exc) { } if (hndlr == null) { hndlr = new ConfigParserHandler(); } parser.parse(config, hndlr); return hndlr.getStreamsConfigData(); }
From source file:com.connectsdk.core.upnp.Device.java
public static Device createInstanceFromXML(String url, String searchTarget) { Device newDevice = null;// www . java2 s. com try { newDevice = new Device(url, searchTarget); } catch (IOException e) { return null; } final Device device = newDevice; DefaultHandler dh = new DefaultHandler() { String currentValue = null; Icon currentIcon; Service currentService; @Override public void characters(char[] ch, int start, int length) throws SAXException { currentValue = new String(ch, start, length); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (Icon.TAG.equals(qName)) { currentIcon = new Icon(); } else if (Service.TAG.equals(qName)) { currentService = new Service(); currentService.baseURL = device.baseURL; } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { // System.out.println("[DEBUG] qName: " + qName + ", currentValue: " + currentValue); /* Parse device-specific information */ if (TAG_DEVICE_TYPE.equals(qName)) { device.deviceType = currentValue; } else if (TAG_FRIENDLY_NAME.equals(qName)) { device.friendlyName = currentValue; } else if (TAG_MANUFACTURER.equals(qName)) { device.manufacturer = currentValue; } else if (TAG_MANUFACTURER_URL.equals(qName)) { device.manufacturerURL = currentValue; } else if (TAG_MODEL_DESCRIPTION.equals(qName)) { device.modelDescription = currentValue; } else if (TAG_MODEL_NAME.equals(qName)) { device.modelName = currentValue; } else if (TAG_MODEL_NUMBER.equals(qName)) { device.modelNumber = currentValue; } else if (TAG_MODEL_URL.equals(qName)) { device.modelURL = currentValue; } else if (TAG_SERIAL_NUMBER.equals(qName)) { device.serialNumber = currentValue; } else if (TAG_UDN.equals(qName)) { device.UDN = currentValue; // device.UUID = Device.parseUUID(currentValue); } else if (TAG_UPC.equals(qName)) { device.UPC = currentValue; } /* Parse icon-list information */ else if (Icon.TAG_MIME_TYPE.equals(qName)) { currentIcon.mimetype = currentValue; } else if (Icon.TAG_WIDTH.equals(qName)) { currentIcon.width = currentValue; } else if (Icon.TAG_HEIGHT.equals(qName)) { currentIcon.height = currentValue; } else if (Icon.TAG_DEPTH.equals(qName)) { currentIcon.depth = currentValue; } else if (Icon.TAG_URL.equals(qName)) { currentIcon.url = currentValue; } else if (Icon.TAG.equals(qName)) { device.iconList.add(currentIcon); } /* Parse service-list information */ else if (Service.TAG_SERVICE_TYPE.equals(qName)) { currentService.serviceType = currentValue; } else if (Service.TAG_SERVICE_ID.equals(qName)) { currentService.serviceId = currentValue; } else if (Service.TAG_SCPD_URL.equals(qName)) { currentService.SCPDURL = currentValue; } else if (Service.TAG_CONTROL_URL.equals(qName)) { currentService.controlURL = currentValue; } else if (Service.TAG_EVENTSUB_URL.equals(qName)) { currentService.eventSubURL = currentValue; } else if (Service.TAG.equals(qName)) { device.serviceList.add(currentService); } } }; SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser; try { URL mURL = new URL(url); URLConnection urlConnection = mURL.openConnection(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); try { parser = factory.newSAXParser(); parser.parse(in, dh); } finally { in.close(); } device.headers = urlConnection.getHeaderFields(); return device; } catch (MalformedURLException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:com.vinexs.tool.XML.java
/** * Parse standard XML to element structure, allow access with css selector. * * @param inputStream InputStream point to a XML document. * @return JSONObject// w ww. j a v a 2 s. c o m */ public static Element toElement(InputStream inputStream) throws ParserConfigurationException, SAXException, IOException { SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); SAXParser parser = saxParserFactory.newSAXParser(); parseHandler handler = new parseHandler(); parser.parse(inputStream, handler); return handler.datas; }
From source file:com.opensymphony.xwork.util.DomHelper.java
/** * Creates a W3C Document that remembers the location of each element in * the source file. The location of element nodes can then be retrieved * using the {@link #getLocationObject(Element)} method. * * @param inputSource the inputSource to read the document from * @param dtdMappings a map of DTD names and public ids */// w w w . j a v a 2 s . c o m public static Document parse(InputSource inputSource, Map dtdMappings) { SAXParserFactory factory = null; String parserProp = System.getProperty("xwork.saxParserFactory"); if (parserProp != null) { try { Class clazz = ObjectFactory.getObjectFactory().getClassInstance(parserProp); factory = (SAXParserFactory) clazz.newInstance(); } catch (ClassNotFoundException e) { LOG.error("Unable to load saxParserFactory set by system property 'xwork.saxParserFactory': " + parserProp, e); } catch (Exception e) { LOG.error("Unable to load saxParserFactory set by system property 'xwork.saxParserFactory': " + parserProp, e); } } if (factory == null) { factory = SAXParserFactory.newInstance(); } factory.setValidating((dtdMappings != null)); factory.setNamespaceAware(true); SAXParser parser = null; try { parser = factory.newSAXParser(); } catch (Exception ex) { throw new XworkException("Unable to create SAX parser", ex); } DOMBuilder builder = new DOMBuilder(); // Enhance the sax stream with location information ContentHandler locationHandler = new LocationAttributes.Pipe(builder); try { parser.parse(inputSource, new StartHandler(locationHandler, dtdMappings)); } catch (Exception ex) { throw new XworkException(ex); } return builder.getDocument(); }
From source file:com.taobao.android.tpatch.utils.SmaliUtils.java
/** * dex?smali// w w w .j a v a 2s.c o m * @param dex * @param outputDir * @param includeClasses ?? */ public static boolean disassembleDexFile(File dex, File outputDir, final Set<String> includeClasses) throws IOException { final baksmaliOptions options = createBaksmaliOptions(); if (!outputDir.exists()) { outputDir.mkdirs(); } DexFile dexFile = DexFileFactory.loadDexFile(dex, DEFAULT_API_LEVEL, true); options.outputDirectory = outputDir.getAbsolutePath(); //1. options.jobs = 3; if (options.registerInfo != 0 || options.deodex) { try { Iterable<String> extraClassPathEntries; if (options.extraClassPathEntries != null) { extraClassPathEntries = options.extraClassPathEntries; } else { extraClassPathEntries = ImmutableList.of(); } options.classPath = ClassPath.fromClassPath(options.bootClassPathDirs, Iterables.concat(options.bootClassPathEntries, extraClassPathEntries), dexFile, options.apiLevel, options.checkPackagePrivateAccess, options.experimental); if (options.customInlineDefinitions != null) { options.inlineResolver = new CustomInlineMethodResolver(options.classPath, options.customInlineDefinitions); } } catch (Exception ex) { System.err.println("\n\nError occurred while loading boot class path files. Aborting."); ex.printStackTrace(System.err); return false; } } if (options.resourceIdFileEntries != null) { class PublicHandler extends DefaultHandler { String prefix = null; public PublicHandler(String prefix) { super(); this.prefix = prefix; } public void startElement(String uri, String localName, String qName, Attributes attr) throws SAXException { if (qName.equals("public")) { String type = attr.getValue("type"); String name = attr.getValue("name").replace('.', '_'); Integer public_key = Integer.decode(attr.getValue("id")); String public_val = new StringBuffer().append(prefix).append(".").append(type).append(".") .append(name).toString(); options.resourceIds.put(public_key, public_val); } } } ; for (Map.Entry<String, String> entry : options.resourceIdFileEntries.entrySet()) { try { SAXParser saxp = SAXParserFactory.newInstance().newSAXParser(); String prefix = entry.getValue(); saxp.parse(entry.getKey(), new PublicHandler(prefix)); } catch (ParserConfigurationException e) { continue; } catch (SAXException e) { continue; } catch (IOException e) { continue; } } } File outputDirectoryFile = new File(options.outputDirectory); if (!outputDirectoryFile.exists()) { if (!outputDirectoryFile.mkdirs()) { System.err.println("Can't create the output directory " + options.outputDirectory); return false; } } // sort the classes, so that if we're on a case-insensitive file system and need to handle classes with file // name collisions, then we'll use the same name for each class, if the dex file goes through multiple // baksmali/smali cycles for some reason. If a class with a colliding name is added or removed, the filenames // may still change of course List<? extends ClassDef> classDefs = Ordering.natural().sortedCopy(dexFile.getClasses()); if (!options.noAccessorComments) { options.syntheticAccessorResolver = new SyntheticAccessorResolver(classDefs); } final ClassFileNameHandler fileNameHandler = new ClassFileNameHandler(outputDirectoryFile, ".smali"); ExecutorService executor = Executors.newFixedThreadPool(options.jobs); List<Future<Boolean>> tasks = Lists.newArrayList(); for (final ClassDef classDef : classDefs) { tasks.add(executor.submit(new Callable<Boolean>() { @Override public Boolean call() throws Exception { String className = getDalvikClassName(classDef.getType()); if (null != includeClasses) { if (includeClasses.contains(className)) { BakSmali.disassembleClass(classDef, fileNameHandler, options); } return true; } else { return BakSmali.disassembleClass(classDef, fileNameHandler, options); } } })); } boolean errorOccurred = false; try { for (Future<Boolean> task : tasks) { while (true) { try { if (!task.get()) { errorOccurred = true; } } catch (InterruptedException ex) { continue; } catch (ExecutionException ex) { throw new RuntimeException(ex); } break; } } } finally { executor.shutdown(); } return !errorOccurred; }