List of usage examples for org.w3c.dom.ls DOMImplementationLS createLSSerializer
public LSSerializer createLSSerializer();
LSSerializer
object. From source file:ddf.security.realm.sts.StsRealm.java
/** * Transform into formatted XML.// w w w .ja va2 s . c om */ private String getFormattedXml(Node node) { Document document = node.getOwnerDocument().getImplementation().createDocument("", "fake", null); Element copy = (Element) document.importNode(node, true); document.importNode(node, false); document.removeChild(document.getDocumentElement()); document.appendChild(copy); DOMImplementation domImpl = document.getImplementation(); DOMImplementationLS domImplLs = (DOMImplementationLS) domImpl.getFeature("LS", "3.0"); LSSerializer serializer = domImplLs.createLSSerializer(); serializer.getDomConfig().setParameter("format-pretty-print", true); return serializer.writeToString(document); }
From source file:edu.harvard.i2b2.query.ui.ConceptTreePanel.java
public static String nodeToString(Node node) { DOMImplementation impl = node.getOwnerDocument().getImplementation(); DOMImplementationLS factory = (DOMImplementationLS) impl.getFeature("LS", "3.0"); LSSerializer serializer = factory.createLSSerializer(); return serializer.writeToString(node); }
From source file:com.portfolio.data.attachment.FileServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { initialize(request);//from ww w. ja v a2s . c om int userId = 0; int groupId = 0; String user = ""; String context = request.getContextPath(); String url = request.getPathInfo(); HttpSession session = request.getSession(true); if (session != null) { Integer val = (Integer) session.getAttribute("uid"); if (val != null) userId = val; val = (Integer) session.getAttribute("gid"); if (val != null) groupId = val; user = (String) session.getAttribute("user"); } Credential credential = null; try { //On initialise le dataProvider Connection c = null; if (ds == null) // Case where we can't deploy context.xml { c = getConnection(); } else { c = ds.getConnection(); } dataProvider.setConnection(c); credential = new Credential(c); } catch (Exception e) { e.printStackTrace(); } // ===================================================================================== boolean trace = false; StringBuffer outTrace = new StringBuffer(); StringBuffer outPrint = new StringBuffer(); String logFName = null; response.setCharacterEncoding("UTF-8"); System.out.println("FileServlet::doGet"); try { // ====== URI : /resources/file[/{lang}]/{context-id} // ====== PathInfo: /resources/file[/{uuid}?lang={fr|en}&size={S|L}] pathInfo // String uri = request.getRequestURI(); String[] token = url.split("/"); String uuid = token[1]; //wadbackend.WadUtilities.appendlogfile(logFName, "GETfile:"+request.getRemoteAddr()+":"+uri); /// FIXME: Passe la scurit si la source provient de localhost, il faudrait un change afin de s'assurer que n'importe quel servlet ne puisse y accder String sourceip = request.getRemoteAddr(); System.out.println("IP: " + sourceip); /// Vrification des droits d'accs // TODO: Might be something special with proxy and export/PDF, to investigate if (!ourIPs.contains(sourceip)) { if (userId == 0) throw new RestWebApplicationException(Status.FORBIDDEN, ""); if (!credential.hasNodeRight(userId, groupId, uuid, Credential.READ)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); //throw new Exception("L'utilisateur userId="+userId+" n'a pas le droit READ sur le noeud "+nodeUuid); } } else // Si la requte est locale et qu'il n'y a pas de session, on ignore la vrification { System.out.println("IP OK: bypass"); } /// On rcupre le noeud de la ressource pour retrouver le lien String data = dataProvider.getResNode(uuid, userId, groupId); // javax.servlet.http.HttpSession session = request.getSession(true); //==================================================== //String ppath = session.getServletContext().getRealPath("/"); //logFName = ppath +"logs/logNode.txt"; //==================================================== String size = request.getParameter("size"); if (size == null) size = "S"; String lang = request.getParameter("lang"); if (lang == null) { lang = "fr"; } /* String nodeUuid = uri.substring(uri.lastIndexOf("/")+1); if (uri.lastIndexOf("/")>uri.indexOf("file/")+6) { // -- file/ = 5 carac. -- lang = uri.substring(uri.indexOf("file/")+5,uri.lastIndexOf("/")); } //*/ String ref = request.getHeader("referer"); /// Parse les donnes DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader("<node>" + data + "</node>")); Document doc = documentBuilder.parse(is); DOMImplementationLS impl = (DOMImplementationLS) doc.getImplementation().getFeature("LS", "3.0"); LSSerializer serial = impl.createLSSerializer(); serial.getDomConfig().setParameter("xml-declaration", false); /// Trouve le bon noeud XPath xPath = XPathFactory.newInstance().newXPath(); /// Either we have a fileid per language String filterRes = "//fileid[@lang='" + lang + "']"; NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET); String resolve = ""; if (nodelist.getLength() != 0) { Element fileNode = (Element) nodelist.item(0); resolve = fileNode.getTextContent(); } /// Or just a single one shared if ("".equals(resolve)) { response.setStatus(404); return; } String filterName = "//filename[@lang='" + lang + "']"; NodeList textList = (NodeList) xPath.compile(filterName).evaluate(doc, XPathConstants.NODESET); String filename = ""; if (textList.getLength() != 0) { Element fileNode = (Element) textList.item(0); filename = fileNode.getTextContent(); } String filterType = "//type[@lang='" + lang + "']"; textList = (NodeList) xPath.compile(filterType).evaluate(doc, XPathConstants.NODESET); String type = ""; if (textList.getLength() != 0) { Element fileNode = (Element) textList.item(0); type = fileNode.getTextContent(); } /* String filterSize = "//size[@lang='"+lang+"']"; textList = (NodeList) xPath.compile(filterName).evaluate(doc, XPathConstants.NODESET); String filesize = ""; if( textList.getLength() != 0 ) { Element fileNode = (Element) textList.item(0); filesize = fileNode.getTextContent(); } //*/ System.out.println("!!! RESOLVE: " + resolve); /// Envoie de la requte au servlet de fichiers // http://localhost:8080/MiniRestFileServer/user/claudecoulombe/file/a8e0f07f-671c-4f6a-be6c-9dba12c519cf/ptype/sql /// TODO: Ne plus avoir besoin du switch String urlTarget = "http://" + server + "/" + resolve; // String urlTarget = "http://"+ server + "/user/" + resolve +"/"+ lang + "/ptype/fs"; HttpURLConnection connection = CreateConnection(urlTarget, request); connection.connect(); InputStream input = connection.getInputStream(); String sizeComplete = connection.getHeaderField("Content-Length"); int completeSize = Integer.parseInt(sizeComplete); response.setContentLength(completeSize); response.setContentType(type); response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); ServletOutputStream output = response.getOutputStream(); byte[] buffer = new byte[completeSize]; int totalRead = 0; int bytesRead = -1; while ((bytesRead = input.read(buffer, 0, completeSize)) != -1 || totalRead < completeSize) { output.write(buffer, 0, bytesRead); totalRead += bytesRead; } // IOUtils.copy(input, output); // IOUtils.closeQuietly(output); output.flush(); output.close(); input.close(); connection.disconnect(); } catch (RestWebApplicationException e) { logger.error(e.getMessage()); e.printStackTrace(); } catch (Exception e) { logger.error(e.toString() + " -> " + e.getLocalizedMessage()); e.printStackTrace(); //wadbackend.WadUtilities.appendlogfile(logFName, "GETfile: error"+e); } finally { try { dataProvider.disconnect(); } catch (Exception e) { ServletOutputStream out = response.getOutputStream(); out.println("Erreur dans doGet: " + e); out.close(); } } }
From source file:com.maxl.java.aips2sqlite.AllDown.java
private String getStringFromDoc(Document doc) { DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation(); LSSerializer lsSerializer = domImplementation.createLSSerializer(); return lsSerializer.writeToString(doc); }
From source file:com.portfolio.data.attachment.FileServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // ===================================================================================== initialize(request);/*from w w w .j a v a2 s. c o m*/ int userId = 0; int groupId = 0; String user = ""; HttpSession session = request.getSession(true); if (session != null) { Integer val = (Integer) session.getAttribute("uid"); if (val != null) userId = val; val = (Integer) session.getAttribute("gid"); if (val != null) groupId = val; user = (String) session.getAttribute("user"); } Credential credential = null; Connection c = null; try { //On initialise le dataProvider if (ds == null) // Case where we can't deploy context.xml { c = getConnection(); } else { c = ds.getConnection(); } dataProvider.setConnection(c); credential = new Credential(c); } catch (Exception e) { e.printStackTrace(); } /// uuid: celui de la ressource /// /resources/resource/file/{uuid}[?size=[S|L]&lang=[fr|en]] String origin = request.getRequestURL().toString(); /// Rcupration des paramtres String url = request.getPathInfo(); String[] token = url.split("/"); String uuid = token[1]; String size = request.getParameter("size"); if (size == null) size = "S"; String lang = request.getParameter("lang"); if (lang == null) { lang = "fr"; } /// Vrification des droits d'accs if (!credential.hasNodeRight(userId, groupId, uuid, Credential.WRITE)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); //throw new Exception("L'utilisateur userId="+userId+" n'a pas le droit WRITE sur le noeud "+nodeUuid); } String data; String fileid = ""; try { data = dataProvider.getResNode(uuid, userId, groupId); /// Parse les donnes DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader("<node>" + data + "</node>")); Document doc = documentBuilder.parse(is); DOMImplementationLS impl = (DOMImplementationLS) doc.getImplementation().getFeature("LS", "3.0"); LSSerializer serial = impl.createLSSerializer(); serial.getDomConfig().setParameter("xml-declaration", false); /// Cherche si on a dj envoy quelque chose XPath xPath = XPathFactory.newInstance().newXPath(); String filterRes = "//filename[@lang=\"" + lang + "\"]"; NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET); String filename = ""; if (nodelist.getLength() > 0) filename = nodelist.item(0).getTextContent(); if (!"".equals(filename)) { /// Already have one, per language String filterId = "//fileid[@lang='" + lang + "']"; NodeList idlist = (NodeList) xPath.compile(filterId).evaluate(doc, XPathConstants.NODESET); if (idlist.getLength() != 0) { Element fileNode = (Element) idlist.item(0); fileid = fileNode.getTextContent(); } } } catch (Exception e2) { e2.printStackTrace(); } int last = fileid.lastIndexOf("/") + 1; // FIXME temp patch if (last < 0) last = 0; fileid = fileid.substring(last); /// request.getHeader("REFERRER"); /// criture des donnes String urlTarget = "http://" + server + "/" + fileid; // String urlTarget = "http://"+ server + "/user/" + user +"/file/" + uuid +"/"+ lang+ "/ptype/fs"; // Unpack form, fetch binary data and send // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Configure a repository (to ensure a secure temp location is used) /* ServletContext servletContext = this.getServletConfig().getServletContext(); File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); factory.setRepository(repository); //*/ // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); String json = ""; HttpURLConnection connection = null; // Parse the request try { List<FileItem> items = upload.parseRequest(request); // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if ("uploadfile".equals(item.getFieldName())) { // Send raw data InputStream inputData = item.getInputStream(); /* URL urlConn = new URL(urlTarget); connection = (HttpURLConnection) urlConn.openConnection(); connection.setDoOutput(true); connection.setUseCaches(false); /// We don't want to cache data connection.setInstanceFollowRedirects(false); /// Let client follow any redirection String method = request.getMethod(); connection.setRequestMethod(method); String context = request.getContextPath(); connection.setRequestProperty("app", context); //*/ String fileName = item.getName(); long filesize = item.getSize(); String contentType = item.getContentType(); // /* connection = CreateConnection(urlTarget, request); connection.setRequestProperty("filename", uuid); connection.setRequestProperty("content-type", "application/octet-stream"); connection.setRequestProperty("content-length", Long.toString(filesize)); //*/ connection.connect(); OutputStream outputData = connection.getOutputStream(); IOUtils.copy(inputData, outputData); /// Those 2 lines are needed, otherwise, no request sent int code = connection.getResponseCode(); String msg = connection.getResponseMessage(); InputStream objReturn = connection.getInputStream(); StringWriter idResponse = new StringWriter(); IOUtils.copy(objReturn, idResponse); fileid = idResponse.toString(); connection.disconnect(); /// Construct Json StringWriter StringOutput = new StringWriter(); JsonWriter writer = new JsonWriter(StringOutput); writer.beginObject(); writer.name("files"); writer.beginArray(); writer.beginObject(); writer.name("name").value(fileName); writer.name("size").value(filesize); writer.name("type").value(contentType); writer.name("url").value(origin); writer.name("fileid").value(fileid); // writer.name("deleteUrl").value(ref); // writer.name("deleteType").value("DELETE"); writer.endObject(); writer.endArray(); writer.endObject(); writer.close(); json = StringOutput.toString(); /* DataOutputStream datawriter = new DataOutputStream(connection.getOutputStream()); byte[] buffer = new byte[1024]; int dataSize; while( (dataSize = inputData.read(buffer,0,buffer.length)) != -1 ) { datawriter.write(buffer, 0, dataSize); } datawriter.flush(); datawriter.close(); //*/ // outputData.close(); // inputData.close(); break; } } } catch (FileUploadException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } /* HttpURLConnection connection = CreateConnection( urlTarget, request ); connection.setRequestProperty("referer", origin); /// Send post data ServletInputStream inputData = request.getInputStream(); DataOutputStream writer = new DataOutputStream(connection.getOutputStream()); byte[] buffer = new byte[1024]; int dataSize; while( (dataSize = inputData.read(buffer,0,buffer.length)) != -1 ) { writer.write(buffer, 0, dataSize); } inputData.close(); writer.close(); /// So we can forward some Set-Cookie String ref = request.getHeader("referer"); /// Prend le JSON du fileserver InputStream in = connection.getInputStream(); InitAnswer(connection, response, ref); BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8")); StringBuilder builder = new StringBuilder(); for( String line = null; (line = reader.readLine()) != null; ) builder.append(line).append("\n"); //*/ /// Envoie la mise jour au backend /* try { PostForm.updateResource(session.getId(), backend, uuid, lang, json); } catch( Exception e ) { e.printStackTrace(); } //*/ connection.disconnect(); /// Renvoie le JSON au client response.setContentType("application/json"); PrintWriter respWriter = response.getWriter(); respWriter.write(json); // RetrieveAnswer(connection, response, ref); dataProvider.disconnect(); }
From source file:com.commander4j.thread.AutoLabellerThread.java
public void run() { logger.debug("AutoLabeller Thread running"); setSessionID(JUnique.getUniqueID()); JDBUser user = new JDBUser(getHostID(), getSessionID()); user.setUserId("interface"); user.setPassword("interface"); user.setLoginPassword("interface"); Common.userList.addUser(getSessionID(), user); Common.sd.setData(getSessionID(), "silentExceptions", "Yes", true); Boolean dbconnected = false;//from ww w . j a v a 2 s . c o m if (Common.hostList.getHost(hostID).isConnected(sessionID) == false) { dbconnected = Common.hostList.getHost(hostID).connect(sessionID, hostID); } else { dbconnected = true; } if (dbconnected) { JDBViewAutoLabellerPrinter alp = new JDBViewAutoLabellerPrinter(getHostID(), getSessionID()); LinkedList<JDBViewAutoLabellerPrinter> autolabellerList = new LinkedList<JDBViewAutoLabellerPrinter>(); int noOfMessages = 0; while (true) { JWait.milliSec(500); if (allDone) { if (dbconnected) { Common.hostList.getHost(hostID).disconnect(getSessionID()); } return; } autolabellerList.clear(); autolabellerList = alp.getModifiedPrinterLines(); noOfMessages = autolabellerList.size(); if (noOfMessages > 0) { for (int x = 0; x < noOfMessages; x++) { JWait.milliSec(100); JDBViewAutoLabellerPrinter autolabview = autolabellerList.get(x); messageProcessedOK = true; messageError = ""; if (autolabview.getPrinterObj().isEnabled()) { logger.debug("Line =" + autolabview.getAutoLabellerObj().getLine()); logger.debug("Line Description =" + autolabview.getAutoLabellerObj().getDescription()); logger.debug("Printer ID =" + autolabview.getPrinterObj().getPrinterID()); logger.debug("Printer Enabled =" + autolabview.getPrinterObj().isEnabled()); logger.debug("Export Path =" + autolabview.getPrinterObj().getExportRealPath()); logger.debug("Export Enabled =" + autolabview.getPrinterObj().isExportEnabled()); logger.debug("Export Format =" + autolabview.getPrinterObj().getExportFormat()); logger.debug("Direct Print =" + autolabview.getPrinterObj().isDirectPrintEnabled()); logger.debug("Printer Type =" + autolabview.getPrinterObj().getPrinterType()); logger.debug("Printer IP =" + autolabview.getPrinterObj().getIPAddress()); logger.debug("Printer Port =" + autolabview.getPrinterObj().getPort()); logger.debug("Process Order =" + autolabview.getLabelDataObj().getProcessOrder()); logger.debug("Material =" + autolabview.getLabelDataObj().getMaterial()); logger.debug("Module ID =" + autolabview.getModuleObj().getModuleId()); logger.debug("Module Type =" + autolabview.getModuleObj().getType()); if (autolabview.getPrinterObj().isExportEnabled()) { String exportPath = JUtility.replaceNullStringwithBlank( JUtility.formatPath(autolabview.getPrinterObj().getExportRealPath())); if (exportPath.equals("") == false) { if (exportPath.substring(exportPath.length() - 1) .equals(File.separator) == false) { exportPath = exportPath + File.separator; } } else { exportPath = Common.interface_output_path + "Auto Labeller" + File.separator; } String exportFilename = exportPath + JUtility.removePathSeparators(autolabview.getAutoLabellerObj().getLine()) + "_" + JUtility.removePathSeparators(autolabview.getPrinterObj().getPrinterID()) + "." + autolabview.getPrinterObj().getExportFormat(); String exportFilenameTemp = exportFilename + ".out"; logger.debug("Export Filename =" + exportFilename); /* ================CSV================ */ if (autolabview.getPrinterObj().getExportFormat().equals("CSV")) { try { PreparedStatement stmt = null; ResultSet rs; String labelType = autolabview.getLabelDataObj().getLabelType(); stmt = Common.hostList.getHost(getHostID()).getConnection(getSessionID()) .prepareStatement( Common.hostList.getHost(getHostID()).getSqlstatements() .getSQL("DBVIEW_AUTO_LABELLER_PRINTER.getProperties" + "_" + labelType)); stmt.setString(1, autolabview.getAutoLabellerObj().getLine()); stmt.setString(2, autolabview.getPrinterObj().getPrinterID()); stmt.setFetchSize(50); rs = stmt.executeQuery(); logger.debug("Writing CSV"); CSVWriter writer = new CSVWriter(new FileWriter(exportFilenameTemp), CSVWriter.DEFAULT_SEPARATOR, CSVWriter.DEFAULT_QUOTE_CHARACTER, CSVWriter.DEFAULT_ESCAPE_CHARACTER, CSVWriter.DEFAULT_LINE_END); writer.writeAll(rs, true); rs.close(); stmt.close(); writer.close(); File fromFile = new File(exportFilenameTemp); File toFile = new File(exportFilename); FileUtils.deleteQuietly(toFile); FileUtils.moveFile(fromFile, toFile); fromFile = null; toFile = null; } catch (Exception e) { messageProcessedOK = false; messageError = e.getMessage(); } } /* ================XML================ */ if (autolabview.getPrinterObj().getExportFormat().equals("XML")) { try { PreparedStatement stmt = null; ResultSet rs; stmt = Common.hostList.getHost(getHostID()).getConnection(getSessionID()) .prepareStatement(Common.hostList.getHost(getHostID()) .getSqlstatements() .getSQL("DBVIEW_AUTO_LABELLER_PRINTER.getProperties")); stmt.setString(1, autolabview.getAutoLabellerObj().getLine()); stmt.setString(2, autolabview.getPrinterObj().getPrinterID()); stmt.setFetchSize(50); rs = stmt.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); int colCount = rsmd.getColumnCount(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); Element message = (Element) document.createElement("message"); Element hostUniqueID = addElement(document, "hostRef", Common.hostList.getHost(getHostID()).getUniqueID()); message.appendChild(hostUniqueID); Element messageRef = addElement(document, "messageRef", autolabview.getAutoLabellerObj().getUniqueID()); message.appendChild(messageRef); Element messageType = addElement(document, "interfaceType", "Auto Labeller Data"); message.appendChild(messageType); Element messageInformation = addElement(document, "messageInformation", "Unique ID=" + autolabview.getAutoLabellerObj().getUniqueID()); message.appendChild(messageInformation); Element messageDirection = addElement(document, "interfaceDirection", "Output"); message.appendChild(messageDirection); Element messageDate = addElement(document, "messageDate", JUtility.getISOTimeStampStringFormat(JUtility.getSQLDateTime())); message.appendChild(messageDate); if (rs.first()) { Element labelData = (Element) document.createElement("LabelData"); Element row = document.createElement("Row"); labelData.appendChild(row); for (int i = 1; i <= colCount; i++) { String columnName = rsmd.getColumnName(i); Object value = rs.getObject(i); Element node = document.createElement(columnName); node.appendChild(document.createTextNode(value.toString())); row.appendChild(node); } message.appendChild(labelData); document.appendChild(message); JXMLDocument xmld = new JXMLDocument(); xmld.setDocument(document); // =============================== DOMImplementationLS DOMiLS = null; FileOutputStream FOS = null; // testing the support for DOM // Load and Save if ((document.getFeature("Core", "3.0") != null) && (document.getFeature("LS", "3.0") != null)) { DOMiLS = (DOMImplementationLS) (document.getImplementation()) .getFeature("LS", "3.0"); // get a LSOutput object LSOutput LSO = DOMiLS.createLSOutput(); FOS = new FileOutputStream(exportFilename); LSO.setByteStream((OutputStream) FOS); // get a LSSerializer object LSSerializer LSS = DOMiLS.createLSSerializer(); // do the serialization LSS.write(document, LSO); FOS.close(); } // =============================== } rs.close(); stmt.close(); } catch (Exception e) { messageError = e.getMessage(); } } if (autolabview.getPrinterObj().getExportFormat().equals("LQF")) { } } if (autolabview.getPrinterObj().isDirectPrintEnabled()) { } } if (messageProcessedOK == true) { autolabview.getAutoLabellerObj().setModified(false); autolabview.getAutoLabellerObj().update(); } else { logger.debug(messageError); } autolabview = null; } } } } }
From source file:org.apache.manifoldcf.crawler.connectors.meridio.meridiowrapper.MeridioWrapper.java
/** Given the SOAP response received by AXIS on the successful call to a Meridio * Web Service, this helper method returns a castor RMDataSet object which represents * the XML/*from www. jav a 2 s.c om*/ * * This makes it much easier to subsequently manipulate the data that has been * returned from the web service, and ensures that the Meridio wrapper implementation * is as close to native .NET code as we can get. */ protected RMDataSet getRMDataSet(MessageElement[] messageElement) throws MeridioDataSetException { if (oLog != null) oLog.debug("Meridio: Entered getRMDataSet method."); try { if (messageElement.length != 2) { if (oLog != null) oLog.warn("Meridio: SOAP Message not of expected length"); if (oLog != null) oLog.debug("Meridio: Exiting getRMDataSet method with null."); return null; } /* for (int i = 0; i < messageElement.length; i++) { oLog.debug("Meridio: Message Part: " + i + " " + messageElement[i]); } */ Document document = messageElement[1].getAsDocument(); NodeList nl = document.getElementsByTagName("RMDataSet"); NodeList errors = document.getElementsByTagName("diffgr:errors"); if (errors.getLength() != 0) { String errorXML = ""; if (oLog != null) oLog.error("Found <" + errors.getLength() + "> errors in returned data set"); for (int i = 0; i < errors.getLength(); i++) { Element e = (Element) errors.item(i); Document resultDocument = new DocumentImpl(); Node node = resultDocument.importNode(e, true); resultDocument.appendChild(node); DOMImplementation domImpl = DOMImplementationImpl.getDOMImplementation(); DOMImplementationLS implLS = (DOMImplementationLS) domImpl; LSSerializer writer = implLS.createLSSerializer(); errorXML += writer.writeToString(resultDocument) + "\n"; if (oLog != null) oLog.warn("..." + errorXML); } throw new MeridioDataSetException(errorXML); } if (nl.getLength() != 1) { if (oLog != null) oLog.warn("Meridio: Returning null - could not find RMDataSet in SOAP Message"); if (oLog != null) oLog.debug("Meridio: Exiting getRMDataSet method with null."); return null; } Element e = (Element) nl.item(0); Document resultDocument = new DocumentImpl(); Node node = resultDocument.importNode(e, true); resultDocument.appendChild(node); DOMImplementation domImpl = DOMImplementationImpl.getDOMImplementation(); DOMImplementationLS implLS = (DOMImplementationLS) domImpl; LSSerializer writer = implLS.createLSSerializer(); String documentXML = writer.writeToString(resultDocument); StringReader sr = new StringReader(documentXML); RMDataSet dsRM = new RMDataSet(); dsRM = RMDataSet.unmarshal(sr); if (oLog != null) oLog.debug("Meridio: Exiting getRMDataSet method."); return dsRM; } catch (ClassNotFoundException classNotFoundException) { throw new MeridioDataSetException( "Could not find the DOM Parser class when unmarshalling the Meridio Dataset", classNotFoundException); } catch (InstantiationException instantiationException) { throw new MeridioDataSetException( "Error instantiating the DOM Parser when unmarshalling the Meridio Dataset", instantiationException); } catch (IllegalAccessException illegalAccessException) { throw new MeridioDataSetException("DOM Parser illegal access when unmarshalling the Meridio Dataset", illegalAccessException); } catch (MarshalException marshalException) { throw new MeridioDataSetException("Castor error in marshalling the XML from the Meridio Dataset", marshalException); } catch (ValidationException validationException) { throw new MeridioDataSetException("Castor error in validating the XML from the Meridio Dataset", validationException); } catch (Exception ex) // from messageElement[1].getAsDocument(); { throw new MeridioDataSetException("Error retrieving the XML Document from the Web Service response", ex); } }
From source file:org.apache.manifoldcf.crawler.connectors.meridio.meridiowrapper.MeridioWrapper.java
/** Given the SOAP response received by AXIS on the successful call to a Meridio * Web Service, this helper method returns a castor DMDataSet object which represents * the XML/*from www . jav a 2 s.co m*/ * * This makes it much easier to subsequently manipulate the data that has been * returned from the web service, and ensures that the Meridio wrapper implementation * is as close to native .NET code as we can get. */ protected DMDataSet getDMDataSet(MessageElement[] messageElement) throws MeridioDataSetException { if (oLog != null) oLog.debug("Meridio: Entered getDMDataSet method."); try { if (messageElement.length != 2) { if (oLog != null) oLog.warn("Meridio: SOAP Message not of expected length"); if (oLog != null) oLog.debug("Meridio: Exiting getDMDataSet method with null."); return null; } /* for (int i = 0; i < messageElement.length; i++) { oLog.debug("Meridio: Message Part: " + i + " " + messageElement[i]); } */ Document document = messageElement[1].getAsDocument(); NodeList nl = document.getElementsByTagName("DMDataSet"); NodeList errors = document.getElementsByTagName("diffgr:errors"); if (errors.getLength() != 0) { String errorXML = ""; if (oLog != null) oLog.error("Found <" + errors.getLength() + "> errors in returned data set"); for (int i = 0; i < errors.getLength(); i++) { Element e = (Element) errors.item(i); Document resultDocument = new DocumentImpl(); Node node = resultDocument.importNode(e, true); resultDocument.appendChild(node); DOMImplementation domImpl = DOMImplementationImpl.getDOMImplementation(); DOMImplementationLS implLS = (DOMImplementationLS) domImpl; LSSerializer writer = implLS.createLSSerializer(); errorXML += writer.writeToString(resultDocument) + "\n"; if (oLog != null) oLog.warn("..." + errorXML); } throw new MeridioDataSetException(errorXML); } if (nl.getLength() != 1) { if (oLog != null) oLog.warn("Meridio: Returning null - could not find DMDataSet in SOAP Message"); if (oLog != null) oLog.debug("Meridio: Exiting getDMDataSet method with null."); return null; } Element e = (Element) nl.item(0); Document resultDocument = new DocumentImpl(); Node node = resultDocument.importNode(e, true); resultDocument.appendChild(node); DOMImplementation domImpl = DOMImplementationImpl.getDOMImplementation(); DOMImplementationLS implLS = (DOMImplementationLS) domImpl; LSSerializer writer = implLS.createLSSerializer(); String documentXML = writer.writeToString(resultDocument); //oLog.debug("Meridio: Result: " + documentXML); StringReader sr = new StringReader(documentXML); DMDataSet dsDM = new DMDataSet(); dsDM = DMDataSet.unmarshal(sr); if (oLog != null) oLog.debug("Meridio: Exiting getDMDataSet method."); return dsDM; } catch (ClassNotFoundException classNotFoundException) { throw new MeridioDataSetException( "Could not find the DOM Parser class when unmarshalling the Meridio Dataset", classNotFoundException); } catch (InstantiationException instantiationException) { throw new MeridioDataSetException( "Error instantiating the DOM Parser when unmarshalling the Meridio Dataset", instantiationException); } catch (IllegalAccessException illegalAccessException) { throw new MeridioDataSetException("DOM Parser illegal access when unmarshalling the Meridio Dataset", illegalAccessException); } catch (MarshalException marshalException) { throw new MeridioDataSetException("Castor error in marshalling the XML from the Meridio Dataset", marshalException); } catch (ValidationException validationException) { throw new MeridioDataSetException("Castor error in validating the XML from the Meridio Dataset", validationException); } catch (Exception ex) // from messageElement[1].getAsDocument(); { throw new MeridioDataSetException("Error retrieving the XML Document from the Web Service response", ex); } }
From source file:de.escidoc.core.test.EscidocTestBase.java
/** * Serialize the given Dom Object to a String. * //from www. jav a 2s . co m * @param xml * The Xml Node to serialize. * @param omitXMLDeclaration * Indicates if XML declaration will be omitted. * @return The String representation of the Xml Node. * @throws Exception * If anything fails. */ public static String toString(final Node xml, final boolean omitXMLDeclaration) throws Exception { String result = new String(); if (xml instanceof AttrImpl) { result = xml.getTextContent(); } else if (xml instanceof Document) { StringWriter stringOut = new StringWriter(); // format OutputFormat format = new OutputFormat((Document) xml); format.setIndenting(true); format.setPreserveSpace(true); format.setOmitXMLDeclaration(omitXMLDeclaration); format.setEncoding(DEFAULT_CHARSET); // serialize XMLSerializer serial = new XMLSerializer(stringOut, format); serial.asDOMSerializer(); serial.serialize((Document) xml); result = stringOut.toString(); } else { DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); LSOutput lsOutput = impl.createLSOutput(); lsOutput.setEncoding(DEFAULT_CHARSET); ByteArrayOutputStream os = new ByteArrayOutputStream(); lsOutput.setByteStream(os); LSSerializer writer = impl.createLSSerializer(); // result = writer.writeToString(xml); writer.write(xml, lsOutput); result = ((ByteArrayOutputStream) lsOutput.getByteStream()).toString(DEFAULT_CHARSET); if ((omitXMLDeclaration) && (result.indexOf("?>") != -1)) { result = result.substring(result.indexOf("?>") + 2); } // result = toString(getDocument(writer.writeToString(xml)), // true); } return result; }
From source file:i5.las2peer.services.mobsos.SurveyService.java
/** * Serializes a given Document to String. * //from w w w.jav a2s . c o m * @param doc * @return */ private String getStringFromDoc(org.w3c.dom.Document doc) { DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation(); LSSerializer lsSerializer = domImplementation.createLSSerializer(); return lsSerializer.writeToString(doc); }