List of usage examples for org.xml.sax.helpers DefaultHandler DefaultHandler
DefaultHandler
From source file:io.dataapps.chlorine.finder.DefaultFinderProvider.java
DefaultFinderProvider(InputStream in, final boolean ignoreEnabledFlag) { try {// w w w . j av a 2 s. c o m SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); DefaultHandler handler = new DefaultHandler() { boolean bName = false; boolean bPattern = false; boolean bClass = false; boolean bEnabled = false; boolean bFlags = false; String name = ""; String pattern = ""; String className = ""; String strFlags = ""; int flags = RegexFinder.DEFAULT_FLAGS; String strEnabled = ""; boolean enabled = true; public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase("NAME")) { bName = true; } else if (qName.equalsIgnoreCase("PATTERN")) { bPattern = true; } else if (qName.equalsIgnoreCase("CLASS")) { bClass = true; } else if (qName.equalsIgnoreCase("FLAGS")) { bFlags = true; } else if (qName.equalsIgnoreCase("ENABLED")) { bEnabled = true; } } public void endElement(String uri, String localName, String qName) throws SAXException { if (qName.equalsIgnoreCase("NAME")) { bName = false; name = name.trim(); } else if (qName.equalsIgnoreCase("PATTERN")) { bPattern = false; pattern = pattern.trim(); } else if (qName.equalsIgnoreCase("CLASS")) { bClass = false; className = className.trim(); } else if (qName.equalsIgnoreCase("FLAGS")) { bFlags = false; flags = Integer.parseInt(strFlags.trim()); } else if (qName.equalsIgnoreCase("ENABLED")) { bEnabled = false; enabled = Boolean.parseBoolean(strEnabled.trim()); } else if (qName.equalsIgnoreCase("FINDER")) { if (ignoreEnabledFlag || enabled) { if (!className.isEmpty()) { try { Class<?> klass = Thread.currentThread().getContextClassLoader() .loadClass(className); finders.add((Finder) klass.newInstance()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { LOG.error(e); } } else if (flags != RegexFinder.DEFAULT_FLAGS) { finders.add(new RegexFinder(name, pattern, flags)); } else { finders.add(new RegexFinder(name, pattern)); } } name = ""; pattern = ""; className = ""; flags = RegexFinder.DEFAULT_FLAGS; strFlags = ""; enabled = true; strEnabled = ""; } } public void characters(char ch[], int start, int length) throws SAXException { if (bName) { name += new String(ch, start, length); } else if (bPattern) { pattern += new String(ch, start, length); } else if (bClass) { className += new String(ch, start, length); } else if (bEnabled) { strEnabled += new String(ch, start, length); } else if (bFlags) { strFlags += new String(ch, start, length); } } }; saxParser.parse(in, handler); } catch (Exception e) { LOG.error(e); } }
From source file:manchester.synbiochem.datacapture.SeekConnector.java
private DocumentBuilder parser() throws ParserConfigurationException { DocumentBuilder builder = dbf.newDocumentBuilder(); builder.setErrorHandler(new DefaultHandler() { @Override// w w w .j av a 2s. c o m public void warning(SAXParseException exception) throws SAXException { log.warn(exception.getMessage()); } @Override public void error(SAXParseException exception) throws SAXException { log.error(exception.getMessage(), exception); } }); return builder; }
From source file:com.badugi.game.logic.model.utils.common.XmlUtils.java
/** * Retrieve the text for a specific element (when we know there is only * one).//w w w.ja va 2s . co m * * @param xmlAsString the xml response * @param element the element to look for * @return the text value of the element. */ public static String getTextForElement(final String xmlAsString, final String element) { final XMLReader reader = getXmlReader(); final StringBuilder builder = new StringBuilder(); final DefaultHandler handler = new DefaultHandler() { private boolean foundElement = false; public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) throws SAXException { if (localName.equals(element)) { this.foundElement = true; } } public void endElement(final String uri, final String localName, final String qName) throws SAXException { if (localName.equals(element)) { this.foundElement = false; } } public void characters(char[] ch, int start, int length) throws SAXException { if (this.foundElement) { builder.append(ch, start, length); } } }; reader.setContentHandler(handler); reader.setErrorHandler(handler); try { reader.parse(new InputSource(new StringReader(xmlAsString))); } catch (final Exception e) { LOG.error(e, e); return null; } return builder.toString(); }
From source file:com.wart.magister.SelectSchoolActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_select_school); // Display the Actionbar arrow getActionBar().setDisplayHomeAsUpEnabled(false); ((EditText) findViewById(R.id.select_school_edittext)).addTextChangedListener(new TextWatcher() { @Override/*from w w w. j a va2 s . co m*/ public void afterTextChanged(Editable e) { if (e.length() > 0) { showProgress(true); if (mRetrieveSchoolsRequest != null && !mRetrieveSchoolsRequest.isFinished()) mRetrieveSchoolsRequest.cancel(true); mRetrieveSchoolsRequest = Global.AsyncHttpClient.get( "http://app.schoolmaster.nl/schoolLicentieService.asmx/Search?term=" + e.toString().replace(" ", "%20").toLowerCase().trim(), new TextHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, String responseBody) { try { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); mRetrievedSchools.clear(); DefaultHandler handler = new DefaultHandler() { private String currentValue; private School currentSchool; @Override public void characters(char ch[], int start, int length) throws SAXException { currentValue = new String(ch, start, length); } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (qName.equalsIgnoreCase("medius")) currentSchool.URL = currentValue; else if (qName.equalsIgnoreCase("licentie")) currentSchool.License = currentValue; } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase("school")) { currentSchool = new School(); mRetrievedSchools.add(currentSchool); } } }; saxParser.parse(new InputSource(new StringReader(responseBody)), handler); String[] names = new String[mRetrievedSchools.size()]; for (int i = 0; i < mRetrievedSchools.size(); i++) names[i] = mRetrievedSchools.get(i).License; mSchoolsList.setAdapter(new ArrayAdapter<String>(SelectSchoolActivity.this, android.R.layout.simple_list_item_1, names)); } catch (Exception e) { Log.e(TAG, "Error in onSuccess", e); } } @Override public void onFailure(String responseBody, Throwable error) { mSchoolsList.setAdapter(null); Log.e(TAG, "Retrieving schools failed", error); } @Override public void onFinish() { showProgress(false); } }); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } }); mSchoolsList = (ListView) findViewById(R.id.select_school_listview); mSchoolsList.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (mTestMediusRequest != null && !mTestMediusRequest.isFinished()) mTestMediusRequest.cancel(true); ((TextView) findViewById(R.id.select_school_status_message)).setText("Testing school..."); showProgress(true); Data.set(Data.MEDIUSURL, Data.buildMediusUrl(mRetrievedSchools.get(position).URL)); Log.v(TAG, "posting to " + Data.getString(Data.MEDIUSURL)); byte[] request = new byte[54]; request[0] = 0x52; request[1] = 0x4f; request[2] = 49; request[3] = 48; request[4] = 55; request[12] = 95; request[13] = -38; request[14] = -109; request[15] = 13; request[16] = -14; request[17] = 92; request[18] = 7; request[19] = 86; request[20] = -77; request[21] = -23; request[22] = 9; request[23] = 22; request[24] = 71; request[25] = -53; request[26] = -81; request[27] = 45; request[28] = 5; request[32] = 76; request[33] = 111; request[34] = 103; request[35] = 105; request[36] = 110; request[37] = 13; request[41] = 71; request[42] = 101; request[43] = 116; request[44] = 83; request[45] = 99; request[46] = 104; request[47] = 111; request[48] = 111; request[49] = 108; request[50] = 78; request[51] = 97; request[52] = 109; request[53] = 101; Log.i(TAG, "Testing the url..."); mTestMediusRequest = Global.AsyncHttpClient.post(SelectSchoolActivity.this, Data.getString(Data.MEDIUSURL), new ByteArrayEntity(request), "text/html", new BinaryHttpResponseHandler(new String[] { "text/html" }) { @Override public void onSuccess(byte[] binaryData) { if (binaryData != null) { Log.i(TAG, "Received " + binaryData.length + " bytes of data"); Serializer s = new Serializer(binaryData); try { if (s.readROHeader(null, "login", "getschoolname")) { Data.set(Data.LICENSE, s.readString()); MediusCall.setLicense(Data.getString(Data.LICENSE)); } else Log.e(TAG, "Geblokkeerd door webserver"); } catch (Exception e) { Log.e(TAG, "Error in TestMedius.onSuccess", e); } Log.i(TAG, "Succesfully tested the medius"); SelectSchoolActivity.this.startActivity( new Intent(SelectSchoolActivity.this, LoginActivity.class)); } else Log.e(TAG, "TestMedius timed out"); } @Override public void onFailure(int statusCode, Header[] headers, byte[] binaryData, Throwable error) { Log.e(TAG, "Error in TestMedius.onFaillure", error); } @Override public void onFinish() { showProgress(false); } }); } }); mSearchLayout = (LinearLayout) findViewById(R.id.select_school_status_layout); }
From source file:com.connectsdk.core.upnp.Device.java
public static Device createInstanceFromXML(String url, String searchTarget) { Device newDevice = null;//from www. ja v a 2s.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:org.openbmap.soapclient.CheckServerTask.java
@Override protected Object[] doInBackground(final String... params) { try {/*from w ww . j ava 2s . com*/ final Object[] result = new Object[2]; result[0] = ServerAnswer.UNKNOWN_ERROR; result[1] = "Uninitialized"; //check whether we have a connection to openbmap.org if (!isOnline()) { // if not, check whether connecting, if so wait Log.i(TAG, "No reply from server! Device might just been switched on, so wait a bit"); waitForConnect(); if (!isOnline()) { Log.i(TAG, "Waiting didn't help. Still no connection"); result[0] = ServerAnswer.NO_REPLY; result[1] = "No online connection!"; return result; } } final SAXParserFactory factory = SAXParserFactory.newInstance(); final DefaultHandler handler = new DefaultHandler() { private boolean versionElement = false; public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase("ALLOWED")) { versionElement = true; } } public void endElement(final String uri, final String localName, final String qName) throws SAXException { // Log.d(TAG, "End Element :" + qName); } public void characters(final char[] ch, final int start, final int length) throws SAXException { if (versionElement) { serverVersion = new String(ch, start, length); versionElement = false; } } }; Log.i(TAG, "Verifying client version at" + Preferences.VERSION_CHECK_URL); // version file is opened as stream, thus preventing immediate timeout issues final URL url = new URL(Preferences.VERSION_CHECK_URL); final InputStream stream = url.openStream(); final SAXParser saxParser = factory.newSAXParser(); saxParser.parse(stream, handler); stream.close(); if (serverVersion.equals(params[0])) { Log.i(TAG, "Client version is up-to-date: " + params[0]); final boolean anonymousUpload = PreferenceManager.getDefaultSharedPreferences(mContext) .getBoolean(Preferences.KEY_ANONYMOUS_UPLOAD, false); if (!anonymousUpload && credentialsAccepted(params[1], params[2])) { result[0] = ServerAnswer.OK; result[1] = "Everything fine! You're using the most up-to-date version!"; } else if (!anonymousUpload && !credentialsAccepted(params[1], params[2])) { result[0] = ServerAnswer.BAD_PASSWORD; result[1] = "Server reports bad user or password!"; } else { result[0] = ServerAnswer.OK; result[1] = "Password validation skipped, anonymous upload!"; } return result; } else { Log.i(TAG, "Client version is outdated: server " + serverVersion + " client " + params[0]); result[0] = ServerAnswer.OUTDATED; result[1] = "New version available:" + serverVersion; return result; } } catch (final IOException e) { Log.e(TAG, "Error while checking version. Are you online?"); return new Object[] { ServerAnswer.NO_REPLY, "Couldn't contact server" }; } catch (final Exception e) { Log.e(TAG, "Error while checking version: " + e.toString(), e); return new Object[] { ServerAnswer.UNKNOWN_ERROR, "Error: " + e.toString() }; } }
From source file:iarnrodProducer.java
public static DefaultFeatureCollection parseXML(final SimpleFeatureBuilder builder) { // sft schema = "trainStatus:String,trainCode:String,publicMessage:String,direction:String,dtg:Date,*geom:Point:srid=4326" final DefaultFeatureCollection featureCollection = new DefaultFeatureCollection(); try {/*from w ww. ja v a 2 s . c o m*/ SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); DefaultHandler handler = new DefaultHandler() { StringBuilder textContent = new StringBuilder(); String tagName; double lat; double lon; String trainCode; public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { tagName = qName; textContent.setLength(0); } public void endElement(String uri, String localName, String qName) throws SAXException { tagName = qName; String text = textContent.toString(); if (tagName == TRAIN_LAT) { lat = Double.parseDouble(text); } else if (tagName == TRAIN_LON) { lon = Double.parseDouble(text); } else if (tagName == TRAIN_STATUS) { builder.add(text); } else if (tagName == TRAIN_CODE) { trainCode = text; // use this as feature ID builder.add(text); } else if (tagName == PUBLIC_MESSAGE) { builder.add(text); } else if (tagName == DIRECTION) { builder.add(text); // add direction // this is the last field, so finish up builder.add(DateTime.now().toDate()); builder.add(WKTUtils$.MODULE$.read("POINT(" + (lon) + " " + (lat) + ")")); SimpleFeature feature = builder.buildFeature(trainCode); featureCollection.add(feature); } } public void characters(char ch[], int start, int length) throws SAXException { textContent.append(ch, start, length); } public void startDocument() throws SAXException { // System.out.println("document started"); } public void endDocument() throws SAXException { // System.out.println("document ended"); } }; //handler saxParser.parse(API_PATH, handler); return featureCollection; } catch (Exception e) { System.out.println("Parsing exception: " + e); System.out.println("exception"); return null; } }
From source file:edu.scripps.fl.pubchem.web.entrez.ELinkWebSession.java
@SuppressWarnings("unchecked") protected Collection<ELinkResult> getELinkResultsSAX(final Collection<ELinkResult> relations) throws Exception { log.info("Memory in use before inputstream: " + memUsage()); InputStream is = EUtilsWebSession.getInstance() .getInputStream("http://eutils.ncbi.nlm.nih.gov/entrez/eutils/elink.fcgi", getParams()).call(); log.info("Memory in use after inputstream: " + memUsage()); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); DefaultHandler handler = new DefaultHandler() { private ELinkResult result; private List<Long> idList; private StringBuffer buf; private int depth; private String linkName; private String dbTo; public void characters(char ch[], int start, int length) throws SAXException { buf.append(ch, start, length); }/*w w w.java 2 s .c o m*/ public void endElement(String uri, String localName, String qName) throws SAXException { if (qName.equalsIgnoreCase("LinkSet")) relations.add(result); else if (qName.equalsIgnoreCase("LinkSetDb")) { if (idList.size() > 0) result.setIds(dbTo, linkName, idList); } else if (qName.equalsIgnoreCase("LinkName")) linkName = buf.toString(); else if (qName.equalsIgnoreCase("dbTo")) dbTo = buf.toString(); else if (qName.equalsIgnoreCase("DbFrom")) result.setDbFrom(buf.toString()); else if (qName.equalsIgnoreCase("Id")) { Long id = Long.parseLong(buf.toString()); if (depth == 4) result.setId(id); else if (depth == 5) idList.add(id); } depth--; } public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { depth++; buf = new StringBuffer(); if (qName.equalsIgnoreCase("LinkSet")) result = new ELinkResult(); else if (qName.equalsIgnoreCase("LinkSetDb")) idList = new ArrayList(); } }; log.info("Memory in use before parsing: " + memUsage()); log.info("Parsing elink results using SAX."); try { saxParser.parse(is, handler); } catch (SAXParseException ex) { throw new Exception("Error parsing ELink output: " + ex.getMessage()); } log.info("Finished parsing elink results."); log.info("Memory in use after parsing: " + memUsage()); return relations; }
From source file:mj.ocraptor.extraction.tika.parser.epub.EpubParser.java
public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { // Because an EPub file is often made up of multiple XHTML files, // we need explicit control over the start and end of the document XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata); xhtml.startDocument();/*from w w w . ja v a2 s. co m*/ ContentHandler childHandler = new EmbeddedContentHandler(new BodyContentHandler(xhtml)); ZipInputStream zip = new ZipInputStream(stream); ZipEntry entry = zip.getNextEntry(); TikaImageHelper helper = new TikaImageHelper(metadata); try { while (entry != null) { // TODO: images String entryExtension = null; try { entryExtension = FilenameUtils.getExtension(new File(entry.getName()).getName()); } catch (Exception e) { e.printStackTrace(); } if (entryExtension != null && FileType.isValidImageFileExtension(entryExtension) && Config.inst().getProp(ConfigBool.ENABLE_IMAGE_OCR)) { File imageFile = null; try { imageFile = TikaImageHelper.saveZipEntryToTemp(zip, entry); helper.addImage(imageFile); } catch (Exception e) { e.printStackTrace(); } finally { if (imageFile != null) { imageFile.delete(); } } } else if (entry.getName().equals("mimetype")) { String type = IOUtils.toString(zip, "UTF-8"); metadata.set(Metadata.CONTENT_TYPE, type); } else if (entry.getName().equals("metadata.xml")) { meta.parse(zip, new DefaultHandler(), metadata, context); } else if (entry.getName().endsWith(".opf")) { meta.parse(zip, new DefaultHandler(), metadata, context); } else if (entry.getName().endsWith(".html") || entry.getName().endsWith(".xhtml")) { content.parse(zip, childHandler, metadata, context); } entry = zip.getNextEntry(); } helper.addTextToHandler(xhtml); } catch (Exception e) { e.printStackTrace(); } finally { if (helper != null) { helper.close(); } } // Finish everything xhtml.endDocument(); }
From source file:fr.ortolang.diffusion.store.binary.BinaryStoreServiceBean.java
@PostConstruct public void init() { this.base = Paths.get(OrtolangConfig.getInstance().getHomePath().toString(), DEFAULT_BINARY_HOME); this.working = Paths.get(base.toString(), WORK); this.collide = Paths.get(base.toString(), COLLIDE); this.factory = new SHA1FilterInputStreamFactory(); LOGGER.log(Level.FINEST, "Initializing service with base folder: " + base); try {/*from w w w . ja va 2 s .com*/ Files.createDirectories(base); Files.createDirectories(working); Files.createDirectories(collide); } catch (Exception e) { LOGGER.log(Level.SEVERE, "unable to initialize binary store", e); } this.handler = new DefaultHandler(); this.autoDetectParser = new AutoDetectParser(); }