List of usage examples for org.dom4j DocumentHelper parseText
public static Document parseText(String text) throws DocumentException
parseText
parses the given text as an XML document and returns the newly created Document.
From source file:de.tu_berlin.cit.rwx4j.component.ResourceContainerComponent.java
License:Apache License
/** * Override this method to handle the IQ stanzas of type <tt>get</tt> that * could not be processed by the {@link AbstractComponent} implementation. * //w ww.jav a 2 s. co m * Note that, as any IQ stanza of type <tt>get</tt> must be replied to, * returning <tt>null</tt> from this method equals returning an IQ error * stanza of type 'feature-not-implemented' (this behavior can be disabled * by setting the <tt>enforceIQResult</tt> argument in the constructor to * <tt>false</tt>). * * Note that if this method throws an Exception, an IQ stanza of type * <tt>error</tt>, condition 'internal-server-error' will be returned to the * sender of the original request. * * The default implementation of this method returns <tt>null</tt>. It is * expected that most child classes will override this method. * * @param iq * The IQ request stanza of type <tt>get</tt> that was received * by this component. * @return the response the to request stanza, or <tt>null</tt> to indicate * 'feature-not-available'. */ @Override protected IQ handleIQGet(IQ iq) throws Exception { logger.info("the following iq get stanza has been received:" + iq.toString()); Element child = iq.getChildElement(); String path = child.attribute("path").getValue(); XwadlDocument xwadl = this.container.getXWADL(path); Document doc = DocumentHelper.parseText(xwadl.toString()); IQ response = IQ.createResultIQ(iq); response.setChildElement(doc.getRootElement()); logger.info("the following iq result stanza will be send:" + response.toString()); return response; }
From source file:de.tu_berlin.cit.rwx4j.component.ResourceContainerComponent.java
License:Apache License
/** * Override this method to handle the IQ stanzas of type <tt>set</tt> that * could not be processed by the {@link AbstractComponent} implementation. * /* www . j ava 2 s. c om*/ * Note that, as any IQ stanza of type <tt>set</tt> must be replied to, * returning <tt>null</tt> from this method equals returning an IQ error * stanza of type 'feature-not-implemented' {this behavior can be disabled * by setting the <tt>enforceIQResult</tt> argument in the constructor to * <tt>false</tt>). * * Note that if this method throws an Exception, an IQ stanza of type * <tt>error</tt>, condition 'internal-server-error' will be returned to the * sender of the original request. * * The default implementation of this method returns <tt>null</tt>. It is * expected that most child classes will override this method. * * @param iq * The IQ request stanza of type <tt>set</tt> that was received * by this component. * @return the response the to request stanza, or <tt>null</tt> to indicate * 'feature-not-available'. */ @Override protected IQ handleIQSet(IQ iq) throws Exception { logger.info("the following iq set stanza has been received:" + iq.toString()); Element child = iq.getChildElement(); RestDocument xmlRequest = RestDocument.Factory.parse(child.asXML()); RestDocument xmlResponse = this.container.execute(xmlRequest); Document doc = DocumentHelper.parseText(xmlResponse.toString()); IQ response = IQ.createResultIQ(iq); response.setChildElement(doc.getRootElement()); logger.info("the following iq result stanza will be send:" + response.toString()); return response; }
From source file:de.tu_berlin.cit.rwx4j.component.ResourceContainerSocket.java
License:Apache License
public XwadlDocument requestXWADL(String path) throws InterruptedException { IQ iq = new IQ(Type.get); iq.setTo(jid);/* w w w .j ava 2 s .c o m*/ // create request XwadlDocument request = XwadlDocument.Factory.newInstance(); request.addNewXwadl().setPath(path); try { Document doc; doc = DocumentHelper.parseText(request.toString()); // set request iq.setChildElement(doc.getRootElement()); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } this.socketManager.sendIQ(iq, this); // wait for response XwadlDocument response; response = this.xwadlExchanger.exchange(request); return response; }
From source file:de.tu_berlin.cit.rwx4j.component.ResourceContainerSocket.java
License:Apache License
public RestDocument invokeRestXML(RestDocument request) throws InterruptedException { IQ iq = new IQ(Type.set); iq.setTo(jid);/*from www . j a v a 2s . c om*/ // create request try { Document doc; doc = DocumentHelper.parseText(request.toString()); // set request iq.setChildElement(doc.getRootElement()); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } this.socketManager.sendIQ(iq, this); // wait for response RestDocument response; response = this.restXmlExchanger.exchange(request); return response; }
From source file:de.tu_berlin.cit.rwx4j.component.ResourceContainerSocket.java
License:Apache License
public void invokeAsyncRestXML(RestDocument request, AsynchronousResultListener listener) { IQ iq = new IQ(Type.set); iq.setTo(jid);/* w w w .jav a 2s . c om*/ // create request try { Document doc; doc = DocumentHelper.parseText(request.toString()); // set request iq.setChildElement(doc.getRootElement()); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } this.socketManager.sendIQ(iq, this); // process the result in a separate thread new Thread(new Runnable() { @Override public void run() { // wait for response RestDocument response; try { response = restXmlExchanger.exchange(request); listener.processResult(response); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); }
From source file:ec.ControlYahoo.java
itemDataBeans search(String word) { //URL?//from w w w . j ava2 s. c om String sendPalam = "?appid=" + APP_ID + "&query=" + word; itemDataBeans listIDB = new itemDataBeans(); //String sendPalam = "&query=" + word; try { //XML Document doc = null; // AhX??Awb_?[?? URL url = new URL(SEARCH_URL + sendPalam); //URL url = new URL(SEARCH_URL + "?appid=" + APP_ID); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); // POSTGET con.setDoOutput(true); // POSTf?[^t con.setInstanceFollowRedirects(false);// ?_CNg con.setRequestProperty("Accept-Language", "jp"); con.setRequestProperty("Content-Type", "text/xml;charset=utf-8"); //con.setRequestProperty("User-Agent","Mozilla/5.0"); OutputStream os = con.getOutputStream();//POSTpOutputStream // URLANZX?AXMLhL?g //doc = new SAXBuilder().build(con.getInputStream()); //XML ?ol //?i //i //TlC //N //=========================================== InputStream is = con.getInputStream();//POST BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String xml = ""; String s = ""; while ((s = reader.readLine()) != null) { System.out.println(s); xml += s; } doc = DocumentHelper.parseText(xml); String strMsg = ""; //?[gvf Element root = doc.getRootElement(); //?i?Ei?ETlC for (Iterator i = root.elementIterator(); i.hasNext();) { Element elem = (Element) i.next(); for (Iterator ii = elem.elementIterator(); ii.hasNext();) { Element elemHit = (Element) ii.next(); String sHit = elemHit.getName(); if (elemHit.getName().equals("Hit")) { Element elemTmp = elemHit.element("Name"); listIDB.setName(elemTmp.getText()); elemTmp.detach(); elemTmp = elemHit.element("Price"); String price = elemTmp.getText(); listIDB.setPrice(Integer.parseInt(price)); elemTmp.detach(); elemTmp = elemHit.element("Image").element("Medium"); listIDB.setImageURL(elemTmp.getText()); elemTmp.detach(); elemTmp = elemHit.element("ProductId"); listIDB.setProductID(elemTmp.getText()); } } } // DoucmnetW??o??o // BufferedWriter bout = new BufferedWriter(new OutputStreamWriter(System.out)); // XMLOutputter out = new XMLOutputter(); // out.output(doc, bout); //ps.close(); reader.close(); con.connect(); } catch (MalformedURLException e) { String str = e.getMessage(); } catch (Exception e) { String str = e.getMessage(); } return listIDB; }
From source file:edu.gmu.csiss.automation.pacs.utils.BaseTool.java
License:Open Source License
/** * Read document from string//from w w w . j a v a2 s.c om * @param xmlstring * @return */ public Document readDocumentFromString(String xmlstring) { Document doc = null; try { doc = DocumentHelper.parseText(xmlstring.trim()); } catch (Exception e) { // e.printStackTrace(); throw new RuntimeException("Fail to read document from string:" + xmlstring); } return doc; }
From source file:edu.gmu.csiss.automation.pacs.utils.BaseTool.java
License:Open Source License
/** * Read element from string/* w ww .j a v a2 s.c o m*/ * @param xmlstring * @return */ public Element readElementFromString(String xmlstring) { Element ele = null; try { Document doc = DocumentHelper.parseText(xmlstring.trim()); ele = doc.getRootElement(); } catch (Exception e) { // e.printStackTrace(); throw new RuntimeException("Fail to read element from string:" + xmlstring); } return ele; }
From source file:edu.pitt.sis.FetchNE.java
/** * @param args/*from ww w.ja v a 2 s .c o m*/ */ public static void getNameEntity(long col_id) { //public static void main(String args[]){ //long col_id = 19; try { URL url = new URL("http://api.opencalais.com/enlighten/rest/"); String license = "t32k95r9k8n9ftdp256e8esw"; String paramsXML = "<c:params xmlns:c=\"http://s.opencalais.com/1/pred/\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">" + "<c:processingDirectives c:contentType=\"text/txt\" c:enableMetadataType=\"GenericRelations\" c:outputFormat=\"text/simple\">" + "</c:processingDirectives>" + "<c:userDirectives c:allowDistribution=\"true\" c:allowSearch=\"true\" c:externalID=\"17cabs901\" c:submitter=\"jahn\">" + "</c:userDirectives>" + "<c:externalMetadata>" + "</c:externalMetadata>" + "</c:params>"; try { String sql = "SELECT c.col_id,c.title,s.name,h.host,c.location,c.detail " + "FROM colloquium c,speaker s,host h " + "WHERE c.speaker_id = s.speaker_id AND " + "c.host_id = h.host_id AND " + "c.col_id = " + col_id; connectDB conn = new connectDB(); ResultSet rs = conn.getResultSet(sql); try { if (rs.next()) { col_id = rs.getLong("col_id"); String content = rs.getString("title") + "\n" + rs.getString("name") + "\n" + rs.getString("host") + "\n" + rs.getString("location") + "\n" + rs.getString("detail"); if (content.length() > 100000) { content = content.substring(0, 99999); } String query = "licenseID=" + URLEncoder.encode(license, "UTF-8") + "&" + "content=" + URLEncoder.encode(content, "UTF-8") + "&" + "paramsXML=" + URLEncoder.encode(paramsXML, "UTF-8"); //make connection URLConnection urlc = url.openConnection(); //use post mode urlc.setDoOutput(true); urlc.setAllowUserInteraction(false); //send query PrintStream ps = new PrintStream(urlc.getOutputStream()); ps.print(query); ps.close(); //get result BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream())); String line = null; String result = ""; while ((line = br.readLine()) != null) { System.out.println(line); result += line; } br.close(); //save opencalais response sql = "INSERT INTO opencalais (col_id,content,output,_date) VALUES (?,?,?,NOW())"; PreparedStatement pstmt = conn.conn.prepareStatement(sql); pstmt.setLong(1, col_id); pstmt.setString(2, content); pstmt.setString(3, result); pstmt.executeUpdate(); try { Document document = DocumentHelper.parseText(result); Element root = document.getRootElement(); //topics and topic tables were merged into entities and entity tables //sql = "DELETE FROM topics WHERE col_id = " + col_id; //conn.executeUpdate(sql); sql = "DELETE FROM entities WHERE col_id = " + col_id; conn.executeUpdate(sql); // iterate through child elements of root with element name "CalaisSimpleOutputFormat" for (Iterator i = root.elementIterator("CalaisSimpleOutputFormat"); i.hasNext();) { Element element = (Element) i.next(); for (Iterator j = element.elementIterator(); j.hasNext();) { Element e = (Element) j.next(); System.out.println(e.getName() + " : " + e.getText()); if (e.getName().trim().equalsIgnoreCase("topics")) {//Insert topics => entities for (Iterator l = e.elementIterator(); l.hasNext();) { Element ee = (Element) l.next(); System.out.println(ee.getName() + " : " + ee.getText()); sql = "SELECT entity_id FROM entity WHERE entity = ?"; pstmt = conn.conn.prepareStatement(sql); pstmt.setString(1, ee.getText().replaceAll("_", " ")); ResultSet rst = pstmt.executeQuery(); long entity_id = -1; if (rst.next()) { entity_id = rst.getLong("entity_id"); } else { sql = "INSERT INTO entity (entity,_type,_date) VALUES (?,'Topic',NOW())"; pstmt = conn.conn.prepareStatement(sql); pstmt.setString(1, ee.getText()); pstmt.executeUpdate(); sql = "SELECT LAST_INSERT_ID()"; ResultSet rsst = conn.getResultSet(sql); if (rsst.next()) { entity_id = rsst.getLong(1); } } sql = "INSERT INTO entities (entity_id,col_id) VALUES (?,?)"; pstmt = conn.conn.prepareStatement(sql); pstmt.setLong(1, entity_id); pstmt.setLong(2, col_id); pstmt.executeUpdate(); //for(Iterator m = e.attributeIterator();m.hasNext();){ // Attribute aa = (Attribute)m.next(); // System.out.println(aa.getName() + " : " + aa.getText()); //} } } else { String entity = e.getText(); String _type = e.getName(); String normalized = ""; String other = ""; int count = -1; double relevance = 0.0; for (Iterator k = e.attributeIterator(); k.hasNext();) { Attribute a = (Attribute) k.next(); System.out.println(a.getName() + " : " + a.getText()); if (a.getName().equalsIgnoreCase("count")) { count = Integer.parseInt(a.getText()); } else if (a.getName().equalsIgnoreCase("relevance")) { relevance = Double.parseDouble(a.getText()); } else if (a.getName().equalsIgnoreCase("normalized")) { normalized = a.getText(); } else { other += a.getText(); } } //Find an entity in db sql = "SELECT entity_id FROM entity WHERE entity = ?"; pstmt = conn.conn.prepareStatement(sql); pstmt.setString(1, entity); ResultSet rsEntity = pstmt.executeQuery(); long entity_id = -1; if (rsEntity.next()) { entity_id = rsEntity.getLong("entity_id"); } else { sql = "INSERT INTO entity (entity,_type,normalized,other,_date) VALUES (?,?,?,?,NOW())"; pstmt = conn.conn.prepareStatement(sql); pstmt.setString(1, entity); pstmt.setString(2, _type); pstmt.setString(3, normalized); pstmt.setString(4, other); pstmt.executeUpdate(); sql = "SELECT LAST_INSERT_ID()"; rsEntity = conn.getResultSet(sql); if (rsEntity.next()) { entity_id = rsEntity.getLong(1); } } sql = "INSERT INTO entities (entity_id,relevance,occur,col_id) VALUES (?,?,?,?)"; pstmt = conn.conn.prepareStatement(sql); pstmt.setLong(1, entity_id); pstmt.setDouble(2, relevance); pstmt.setInt(3, count); pstmt.setLong(4, col_id); pstmt.executeUpdate(); } } } } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } } conn.conn.close(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } finally { conn = null; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } //return 1; }
From source file:edu.ucsd.library.dams.api.DAMSAPIServlet.java
public String objectBatch(List<String> objids, TripleStore ts, TripleStore es) throws Exception { ArrayList<String> docs = new ArrayList<String>(); ArrayList<String> errors = new ArrayList<String>(); // retrieve rdf/xml for each record for (int i = 0; i < objids.size(); i++) { try {// w ww.j a va 2 s .c o m Identifier id = createID(objids.get(i), null, null); if (ts.exists(id)) { DAMSObject obj = new DAMSObject(ts, es, objids.get(i), nsmap); docs.add(obj.getRDFXML(true)); } else if (es != null && es.exists(id)) { DAMSObject obj = new DAMSObject(es, null, objids.get(i), nsmap); docs.add(obj.getRDFXML(true)); } else { errors.add(objids.get(i) + ": not found"); } } catch (Exception ex) { errors.add(objids.get(i) + ": " + ex.toString()); } } // combine xml documents String xml = null; if (docs.size() == 1) { xml = docs.get(0); } else if (docs.size() > 1) { try { Document doc = DocumentHelper.parseText(docs.get(0)); Element rdf = doc.getRootElement(); for (int i = 1; i < docs.size(); i++) { Document doc2 = DocumentHelper.parseText(docs.get(i)); Iterator it = doc2.getRootElement().elementIterator(); if (it.hasNext()) { Element e = (Element) it.next(); rdf.add(e.detach()); } } xml = doc.asXML(); } catch (Exception ex) { errors.add("Error combining records into a batch: " + ex.toString()); } } // check errors if (errors.size() > 0) { String msg = errors.get(0); for (int i = 1; i < errors.size(); i++) { msg += "; " + errors.get(i); } throw new Exception(msg); } return xml; }