List of usage examples for org.w3c.dom Document getImplementation
public DOMImplementation getImplementation();
DOMImplementation
object that handles this document. From source file:com.redhat.plugin.eap6.AbstractEAP6Mojo.java
/** * method to convert Document to String/*w w w .j a v a2 s.c o m*/ * * @param doc * @return */ protected String getStringFromDocument(final Document doc) { try { final StringWriter writer = new StringWriter(); final DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation(); final LSSerializer lsSerializer = domImplementation.createLSSerializer(); lsSerializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); final LSOutput lsOutput = domImplementation.createLSOutput(); lsOutput.setCharacterStream(writer); lsSerializer.write(doc, lsOutput); return writer.toString(); } catch (final LSException ex) { getLog().error(ex); return null; } }
From source file:com.redhat.plugin.eap6.AbstractEAP6Mojo.java
protected void writeXmlFile(final Document doc, final File workDirectory, final String fileName) throws MojoFailureException { final File destinationFile = new File(workDirectory, fileName); try {// ww w .j a v a2 s. c o m final FileOutputStream ostream = new FileOutputStream(destinationFile); final DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation(); final LSSerializer lsSerializer = domImplementation.createLSSerializer(); lsSerializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); final LSOutput lsOutput = domImplementation.createLSOutput(); lsOutput.setByteStream(ostream); lsSerializer.write(doc, lsOutput); ostream.close(); refreshEclipse(destinationFile); } catch (final Exception e) { throw new MojoFailureException("Cannot write output file", e); } }
From source file:com.portfolio.data.attachment.FileServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { initialize(request);/*w w w .ja v a 2s . c o m*/ 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:ddf.security.realm.sts.StsRealm.java
/** * Transform into formatted XML.//from w ww. j a v a 2 s .co m */ 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:com.portfolio.data.attachment.FileServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // ===================================================================================== initialize(request);/*from w w w. ja v a 2 s. co 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 w w w . jav a 2s.c om 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:i5.las2peer.services.mobsos.SurveyService.java
/** * Serializes a given Document to String. * //from w ww. j av a2 s.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); }
From source file:ddf.catalog.services.xsltlistener.XsltResponseQueueTransformer.java
@Override public ddf.catalog.data.BinaryContent transform(SourceResponse upstreamResponse, Map<String, Serializable> arguments) throws CatalogTransformerException { LOGGER.debug("Transforming ResponseQueue with XSLT tranformer"); long grandTotal = -1; try {/*from w w w . j av a 2s .c o m*/ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); Node resultsElement = doc.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "results", null)); // TODO use streaming XSLT, not DOM List<Result> results = upstreamResponse.getResults(); grandTotal = upstreamResponse.getHits(); for (Result result : results) { Metacard metacard = result.getMetacard(); String thisMetacard = metacard.getMetadata(); if (metacard != null && thisMetacard != null) { Element metacardElement = createElement(doc, XML_RESULTS_NAMESPACE, "metacard", null); if (metacard.getId() != null) { metacardElement .appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "id", metacard.getId())); } if (metacard.getMetacardType().toString() != null) { metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "type", metacard.getMetacardType().getName())); } if (metacard.getTitle() != null) { metacardElement.appendChild( createElement(doc, XML_RESULTS_NAMESPACE, "title", metacard.getTitle())); } if (result.getRelevanceScore() != null) { metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "score", result.getRelevanceScore().toString())); } if (result.getDistanceInMeters() != null) { metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "distance", result.getDistanceInMeters().toString())); } if (metacard.getSourceId() != null) { metacardElement.appendChild( createElement(doc, XML_RESULTS_NAMESPACE, "site", metacard.getSourceId())); } if (metacard.getContentTypeName() != null) { String contentType = metacard.getContentTypeName(); Element typeElement = createElement(doc, XML_RESULTS_NAMESPACE, "content-type", contentType); // TODO revisit what to put in the qualifier typeElement.setAttribute("qualifier", "content-type"); metacardElement.appendChild(typeElement); } if (metacard.getResourceURI() != null) { try { metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "product", metacard.getResourceURI().toString())); } catch (DOMException e) { LOGGER.warn(" Unable to create resource uri element", e); } } if (metacard.getThumbnail() != null) { metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "thumbnail", Base64.encodeBase64String(metacard.getThumbnail()))); try { String mimeType = URLConnection .guessContentTypeFromStream(new ByteArrayInputStream(metacard.getThumbnail())); metacardElement .appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "t_mimetype", mimeType)); } catch (IOException e) { // TODO Auto-generated catch block metacardElement.appendChild( createElement(doc, XML_RESULTS_NAMESPACE, "t_mimetype", "image/png")); } } DateTimeFormatter fmt = ISODateTimeFormat.dateTime(); if (metacard.getCreatedDate() != null) { metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "created", fmt.print(metacard.getCreatedDate().getTime()))); } // looking at the date last modified if (metacard.getModifiedDate() != null) { metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "updated", fmt.print(metacard.getModifiedDate().getTime()))); } if (metacard.getEffectiveDate() != null) { metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "effective", fmt.print(metacard.getEffectiveDate().getTime()))); } if (metacard.getLocation() != null) { metacardElement.appendChild( createElement(doc, XML_RESULTS_NAMESPACE, "location", metacard.getLocation())); } Element documentElement = doc.createElementNS(XML_RESULTS_NAMESPACE, "document"); metacardElement.appendChild(documentElement); resultsElement.appendChild(metacardElement); Node importedNode = doc.importNode(new XPathHelper(thisMetacard).getDocument().getFirstChild(), true); documentElement.appendChild(importedNode); } else { LOGGER.debug("Null content/document returned to XSLT ResponseQueueTransformer"); continue; } } if (LOGGER.isDebugEnabled()) { DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation(); LSSerializer lsSerializer = domImplementation.createLSSerializer(); LOGGER.debug("Generated XML input for transform: " + lsSerializer.writeToString(doc)); } LOGGER.debug("Starting responsequeue xslt transform."); Transformer transformer; Map<String, Object> mergedMap = new HashMap<String, Object>(); mergedMap.put(GRAND_TOTAL, grandTotal); if (arguments != null) { mergedMap.putAll(arguments); } BinaryContent resultContent; StreamResult resultOutput = null; Source source = new DOMSource(doc); ByteArrayOutputStream baos = new ByteArrayOutputStream(); resultOutput = new StreamResult(baos); try { transformer = templates.newTransformer(); } catch (TransformerConfigurationException tce) { throw new CatalogTransformerException("Could not perform Xslt transform: " + tce.getException(), tce.getCause()); } if (mergedMap != null && !mergedMap.isEmpty()) { for (Map.Entry<String, Object> entry : mergedMap.entrySet()) { if (LOGGER.isDebugEnabled()) { LOGGER.debug( "Adding parameter to transform {" + entry.getKey() + ":" + entry.getValue() + "}"); } transformer.setParameter(entry.getKey(), entry.getValue()); } } try { transformer.transform(source, resultOutput); byte[] bytes = baos.toByteArray(); LOGGER.debug("Transform complete."); resultContent = new XsltTransformedContent(bytes, mimeType); } catch (TransformerException te) { LOGGER.error("Could not perform Xslt transform: " + te.getException(), te.getCause()); throw new CatalogTransformerException("Could not perform Xslt transform: " + te.getException(), te.getCause()); } finally { // transformer.reset(); // don't need to do that unless we are putting it back into a // pool -- which we should do, but that can wait until later. } return resultContent; } catch (ParserConfigurationException e) { LOGGER.warn("Error creating new document: " + e.getMessage(), e.getCause()); throw new CatalogTransformerException("Error merging entries to xml feed.", e); } }
From source file:eumetsat.pn.common.ISO2JSON.java
private JSONObject convert(Document xmlDocument) throws XPathExpressionException, IOException { String expression = null;//from w ww .ja va2s . c o m String result = null; XPath xPath = XPathFactory.newInstance().newXPath(); JSONObject jsonObject = new JSONObject(); String xpathFileID = "//*[local-name()='fileIdentifier']/*[local-name()='CharacterString']"; String fileID = xPath.compile(xpathFileID).evaluate(xmlDocument); log.trace("{} >>> {}", xpathFileID, fileID); if (fileID != null) { jsonObject.put(FILE_IDENTIFIER_PROPERTY, fileID); } expression = "//*[local-name()='hierarchyLevelName']/*[local-name()='CharacterString']"; JSONArray list = new JSONArray(); NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { list.add(nodeList.item(i).getFirstChild().getNodeValue()); } if (list.size() > 0) { JSONObject hierarchies = parseThemeHierarchy((String) jsonObject.get(FILE_IDENTIFIER_PROPERTY), list); hierarchies.writeJSONString(writer); jsonObject.put("hierarchyNames", hierarchies); log.trace("{} >>> {}", expression, jsonObject.get("hierarchyNames")); } // Get Contact info String deliveryPoint = "//*[local-name()='address']//*[local-name()='deliveryPoint']/*[local-name()='CharacterString']"; String city = "//*[local-name()='address']//*[local-name()='city']/*[local-name()='CharacterString']"; String administrativeArea = "//*[local-name()='address']//*[local-name()='administrativeArea']/*[local-name()='CharacterString']"; String postalCode = "//*[local-name()='address']//*[local-name()='postalCode']/*[local-name()='CharacterString']"; String country = "//*[local-name()='address']//*[local-name()='country']/*[local-name()='CharacterString']"; String email = "//*[local-name()='address']//*[local-name()='electronicMailAddress']/*[local-name()='CharacterString']"; StringBuilder addressString = new StringBuilder(); StringBuilder emailString = new StringBuilder(); appendIfResultNotNull(xPath, xmlDocument, addressString, deliveryPoint); result = xPath.compile(postalCode).evaluate(xmlDocument); if (result != null) { addressString.append("\n").append(result.trim()); } result = xPath.compile(city).evaluate(xmlDocument); if (result != null) { addressString.append(" ").append(result.trim()); } result = xPath.compile(administrativeArea).evaluate(xmlDocument); if (result != null) { addressString.append("\n").append(result.trim()); } result = xPath.compile(country).evaluate(xmlDocument); if (result != null) { addressString.append("\n").append(result.trim()); } result = xPath.compile(email).evaluate(xmlDocument); if (result != null) { emailString.append(result.trim()); } HashMap<String, String> map = new HashMap<>(); map.put("address", addressString.toString()); map.put("email", emailString.toString()); jsonObject.put("contact", map); log.trace("contact: {}", Arrays.toString(map.entrySet().toArray())); // add identification info String abstractStr = "//*[local-name()='identificationInfo']//*[local-name()='abstract']/*[local-name()='CharacterString']"; String titleStr = "//*[local-name()='identificationInfo']//*[local-name()='title']/*[local-name()='CharacterString']"; String statusStr = "//*[local-name()='identificationInfo']//*[local-name()='status']/*[local-name()='MD_ProgressCode']/@codeListValue"; String keywords = "//*[local-name()='keyword']/*[local-name()='CharacterString']"; HashMap<String, Object> idMap = new HashMap<>(); result = xPath.compile(titleStr).evaluate(xmlDocument); if (result != null) { idMap.put("title", result.trim()); } result = xPath.compile(abstractStr).evaluate(xmlDocument); if (result != null) { idMap.put("abstract", result.trim()); } result = xPath.compile(statusStr).evaluate(xmlDocument); if (result != null) { idMap.put("status", result.trim()); } list = new JSONArray(); nodeList = (NodeList) xPath.compile(keywords).evaluate(xmlDocument, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { list.add(nodeList.item(i).getFirstChild().getNodeValue()); } if (list.size() > 0) { idMap.put("keywords", list); } jsonObject.put("identificationInfo", idMap); log.trace("idMap: {}", idMap); // get thumbnail product String browseThumbnailStr = "//*[local-name()='graphicOverview']//*[local-name()='MD_BrowseGraphic']//*[local-name()='fileName']//*[local-name()='CharacterString']"; result = xPath.compile(browseThumbnailStr).evaluate(xmlDocument); if (result != null) { idMap.put("thumbnail", result.trim()); log.trace("thumbnail: {}", result); } // add Geo spatial information String westBLonStr = "//*[local-name()='extent']//*[local-name()='geographicElement']//*[local-name()='westBoundLongitude']/*[local-name()='Decimal']"; String eastBLonStr = "//*[local-name()='extent']//*[local-name()='geographicElement']//*[local-name()='eastBoundLongitude']/*[local-name()='Decimal']"; String northBLatStr = "//*[local-name()='extent']//*[local-name()='geographicElement']//*[local-name()='northBoundLatitude']/*[local-name()='Decimal']"; String southBLatStr = "//*[local-name()='extent']//*[local-name()='geographicElement']//*[local-name()='southBoundLatitude']/*[local-name()='Decimal']"; // create a GeoJSON envelope object HashMap<String, Object> latlonMap = new HashMap<>(); latlonMap.put("type", "envelope"); JSONArray envelope = new JSONArray(); JSONArray leftTopPt = new JSONArray(); JSONArray rightDownPt = new JSONArray(); result = xPath.compile(westBLonStr).evaluate(xmlDocument); if (result != null) { leftTopPt.add(Double.parseDouble(result.trim())); } result = xPath.compile(northBLatStr).evaluate(xmlDocument); if (result != null) { leftTopPt.add(Double.parseDouble(result.trim())); } result = xPath.compile(eastBLonStr).evaluate(xmlDocument); if (result != null) { rightDownPt.add(Double.parseDouble(result.trim())); } result = xPath.compile(southBLatStr).evaluate(xmlDocument); if (result != null) { rightDownPt.add(Double.parseDouble(result.trim())); } envelope.add(leftTopPt); envelope.add(rightDownPt); latlonMap.put("coordinates", envelope); jsonObject.put("location", latlonMap); DOMImplementationLS domImplementation = (DOMImplementationLS) xmlDocument.getImplementation(); LSSerializer lsSerializer = domImplementation.createLSSerializer(); String xmlString = lsSerializer.writeToString(xmlDocument); jsonObject.put("xmldoc", xmlString); return jsonObject; }