List of usage examples for org.w3c.dom Document appendChild
public Node appendChild(Node newChild) throws DOMException;
newChild
to the end of the list of children of this node. From source file:ConfigFiles.java
public static void saveXML(boolean blank, String filename) { boolean saved = true; try {/*from w w w. j av a 2 s.c o m*/ DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); DOMSource source = new DOMSource(document); Comment simpleComment = document.createComment( "\n Master config file for TSC.\n \n Logs" + " Path: Where CE and PE write their getLogs()." + " Reports Path: Where all reports are saved.\n " + "Test Suite Config: All info about the current " + "Test Suite (Test Plan).\n"); document.appendChild(simpleComment); Element root = document.createElement("Root"); document.appendChild(root); Element rootElement = document.createElement("FileType"); root.appendChild(rootElement); rootElement.appendChild(document.createTextNode("config")); try { addTag("CentralEnginePort", tceport.getText(), root, blank, document); } catch (Exception e) { addTag("CentralEnginePort", "", root, blank, document); } // try{addTag("ResourceAllocatorPort",traPort.getText(),root,blank,document);} // catch(Exception e){addTag("ResourceAllocatorPort","",root,blank,document);} // try{addTag("HttpServerPort",thttpPort.getText(),root,blank,document);} // catch(Exception e){addTag("HttpServerPort","",root,blank,document);} try { addTag("TestCaseSourcePath", ttcpath.getText(), root, blank, document); } catch (Exception e) { addTag("TestCaseSourcePath", "", root, blank, document); } try { addTag("LibsPath", libpath.getText(), root, blank, document); } catch (Exception e) { addTag("LibsPath", "", root, blank, document); } try { addTag("UsersPath", tUsers.getText(), root, blank, document); } catch (Exception e) { addTag("UsersPath", "", root, blank, document); } try { addTag("PredefinedSuitesPath", tSuites.getText(), root, blank, document); } catch (Exception e) { addTag("PredefinedSuitesPath", "", root, blank, document); } try { addTag("ArchiveLogsPath", tsecondarylog.getText(), root, blank, document); } catch (Exception e) { addTag("ArchiveLogsPath", "", root, blank, document); } try { addTag("ArchiveLogsPathActive", logsenabled.isSelected() + "", root, blank, document); } catch (Exception e) { addTag("ArchiveLogsPath", "", root, blank, document); } try { addTag("LogsPath", tlog.getText(), root, blank, document); } catch (Exception e) { addTag("LogsPath", "", root, blank, document); } rootElement = document.createElement("LogFiles"); root.appendChild(rootElement); try { addTag("logRunning", trunning.getText(), rootElement, blank, document); } catch (Exception e) { addTag("logRunning", "", rootElement, blank, document); } try { addTag("logDebug", tdebug.getText(), rootElement, blank, document); } catch (Exception e) { addTag("logDebug", "", rootElement, blank, document); } try { addTag("logSummary", tsummary.getText(), rootElement, blank, document); } catch (Exception e) { addTag("logSummary", "", rootElement, blank, document); } try { addTag("logTest", tinfo.getText(), rootElement, blank, document); } catch (Exception e) { addTag("logTest", "", rootElement, blank, document); } try { addTag("logCli", tcli.getText(), rootElement, blank, document); } catch (Exception e) { addTag("logCli", "", rootElement, blank, document); } try { addTag("DbConfigFile", tdbfile.getText(), root, blank, document); } catch (Exception e) { addTag("DbConfigFile", "", root, blank, document); } try { addTag("EpNames", tepid.getText(), root, blank, document); } catch (Exception e) { addTag("EpNames", "", root, blank, document); } try { addTag("EmailConfigFile", temailfile.getText(), root, blank, document); } catch (Exception e) { addTag("EmailConfigFile", "", root, blank, document); } try { addTag("GlobalParams", tglobalsfile.getText(), root, blank, document); } catch (Exception e) { addTag("GlobalParams", "", root, blank, document); } try { addTag("TestConfigPath", testconfigpath.getText(), root, blank, document); } catch (Exception e) { addTag("TestConfigPath", "", root, blank, document); } String temp; if (blank) temp = "fwmconfig"; else temp = filename; File file = new File(RunnerRepository.temp + RunnerRepository.getBar() + "Twister" + RunnerRepository.getBar() + temp + ".xml"); Result result = new StreamResult(file); transformer.transform(source, result); System.out.println("Saving to: " + RunnerRepository.USERHOME + "/twister/config/"); FileInputStream in = new FileInputStream(file); RunnerRepository.uploadRemoteFile(RunnerRepository.USERHOME + "/twister/config/", in, file.getName()); } catch (ParserConfigurationException e) { System.out .println("DocumentBuilder cannot be created which" + " satisfies the configuration requested"); saved = false; } catch (TransformerConfigurationException e) { System.out.println("Could not create transformer"); saved = false; } catch (Exception e) { e.printStackTrace(); saved = false; } if (saved) { CustomDialog.showInfo(JOptionPane.INFORMATION_MESSAGE, RunnerRepository.window, "Successful", "File successfully saved"); } else { CustomDialog.showInfo(JOptionPane.WARNING_MESSAGE, RunnerRepository.window.mainpanel.p4.getConfig(), "Warning", "File could not be saved "); } }
From source file:be.fedict.eid.idp.sp.protocol.ws_federation.AuthenticationResponseProcessor.java
/** * Process the incoming WS-Federation response. * /*from w w w . ja va 2 s. co m*/ * @param recipient * recipient, should match SAML v2.0 assertions's * AudienceRestriction * @param context * optional expected context * @param requiresResponseSignature * do we expect a signature on the response or not, or * <code>null</code> if to be retrieved from the * {@link AuthenticationResponseService}. * @param request * the HTTP servlet request that holds the SAML2 response. * @return the {@link be.fedict.eid.idp.common.saml2.AuthenticationResponse} * @throws AuthenticationResponseProcessorException * case something went wrong */ public AuthenticationResponse process(String recipient, String context, Boolean requiresResponseSignature, HttpServletRequest request) throws AuthenticationResponseProcessorException { DateTime now = new DateTime(); SecretKey secretKey = null; PrivateKey privateKey = null; int maxOffset = 5; boolean expectAssertionSigned = null != requiresResponseSignature ? requiresResponseSignature : false; ValidationService validationService = null; if (null != this.service) { secretKey = this.service.getAttributeSecretKey(); privateKey = this.service.getAttributePrivateKey(); maxOffset = this.service.getMaximumTimeOffset(); expectAssertionSigned = this.service.requiresResponseSignature(); validationService = this.service.getValidationService(); } // force UTF8 encoding! try { request.setCharacterEncoding("UTF8"); } catch (UnsupportedEncodingException e) { throw new AuthenticationResponseProcessorException(e); } // check wa String wa = request.getParameter("wa"); if (null == wa) { throw new AuthenticationResponseProcessorException("Missing \"wa\" param."); } if (!wa.equals("wsignin1.0")) { throw new AuthenticationResponseProcessorException("Unexpected value for \"wa\" param."); } // validate optional ctx validateContext(context, request.getParameter("wctx")); // get wresult String wresult = request.getParameter("wresult"); LOG.debug("wresult=\"" + wresult + "\""); if (null == wresult) { throw new AuthenticationResponseProcessorException("Missing \"wresult\" param."); } Document responseDocument = Saml2Util.parseDocument(wresult); RequestSecurityTokenResponseCollection rstCollections = Saml2Util .unmarshall(responseDocument.getDocumentElement()); if (rstCollections.getRequestSecurityTokenResponses().size() != 1) { throw new AuthenticationResponseProcessorException("Expected exactly 1 RequestSecurityTokenResponse"); } RequestSecurityTokenResponse rstResponse = rstCollections.getRequestSecurityTokenResponses().get(0); // context validateContext(context, rstResponse.getContext()); // tokentype validateTokenType(rstResponse); // requesttype validateRequestType(rstResponse); // keytype validateKeyType(rstResponse); // validate security token Assertion assertion = validateSecurityToken(rstResponse); // validate assertion AuthenticationResponse authenticationResponse; try { authenticationResponse = Saml2Util.validateAssertion(assertion, now, maxOffset, recipient, recipient, null, secretKey, privateKey); } catch (AssertionValidationException e) { throw new AuthenticationResponseProcessorException(e); } // check if SP expects a signature and if there is one if (null == assertion.getSignature() && expectAssertionSigned) { throw new AuthenticationResponseProcessorException("Expected a signed assertion but was not so! "); } // validate assertion's signature if any if (null != assertion.getSignature()) { try { // fix for recent versions of Apache xmlsec assertion.getDOM().setIdAttribute("ID", true); List<X509Certificate> certificateChain = Saml2Util.validateSignature(assertion.getSignature()); if (null != validationService) { // have to reparse the document here NodeList assertionNodeList = Saml2Util.parseDocument(wresult) .getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "Assertion"); LOG.debug("number of SAML2 assertions: " + assertionNodeList.getLength()); if (1 != assertionNodeList.getLength()) { throw new AuthenticationResponseProcessorException("missing SAML2 Assertion"); } Element assertionElement = (Element) assertionNodeList.item(0); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document tokenDocument = documentBuilder.newDocument(); Node assertionTokenNode = tokenDocument.importNode(assertionElement, true); tokenDocument.appendChild(assertionTokenNode); String validationServiceLocation = validationService.getLocation(); String expectedAudience = validationService.getExpectedAudience(); SecurityTokenServiceClient securityTokenServiceClient = new SecurityTokenServiceClient( validationServiceLocation); securityTokenServiceClient.validateToken(tokenDocument.getDocumentElement(), expectedAudience); } if (null != this.service) { this.service.validateServiceCertificate(authenticationResponse.getAuthenticationPolicy(), certificateChain); } } catch (CertificateException e) { throw new AuthenticationResponseProcessorException(e); } catch (ValidationException e) { throw new AuthenticationResponseProcessorException(e); } catch (Exception e) { if ("javax.ejb.EJBException".equals(e.getClass().getName())) { Exception exception; try { Method getCausedByExceptionMethod = e.getClass().getMethod("getCausedByException", new Class[] {}); exception = (Exception) getCausedByExceptionMethod.invoke(e, new Object[] {}); } catch (Exception e2) { LOG.debug("error: " + e.getMessage(), e); throw new AuthenticationResponseProcessorException( "error retrieving the root cause: " + e2.getMessage()); } throw new AuthenticationResponseProcessorException("Validation exception: " + (null != exception ? exception.getMessage() : e.getMessage())); } throw new AuthenticationResponseProcessorException(e); } } return authenticationResponse; }
From source file:de.bitzeche.video.transcoding.zencoder.ZencoderClient.java
private Document createDocumentForException(String message) { try {/*from w w w. j av a2 s . co m*/ DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document errorDocument = documentBuilder.newDocument(); Element root = errorDocument.createElement("error"); errorDocument.appendChild(root); Node input = errorDocument.createElement("reason"); input.setTextContent(message); root.appendChild(input); return errorDocument; } catch (ParserConfigurationException e) { LOGGER.error("Exception creating document for exception '" + message + "'", e); return null; } }
From source file:com.intbit.ServletModel.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from ww w. ja va 2 s .co m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.processRequest(request, response); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); File file; int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; try { look = new Looks(); // uploadXmlPath = getServletContext().getRealPath("") + "/model"; uploadPath = AppConstants.BASE_MODEL_PATH; // Verify the content type String contentType = request.getContentType(); if ((contentType.indexOf("multipart/form-data") >= 0)) { DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File(AppConstants.TMP_FOLDER)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); out.println("<html>"); out.println("<head>"); out.println("<title>JSP File upload</title>"); out.println("</head>"); out.println("<body>"); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (fi.isFormField()) { // Get the uploaded file parameters fieldName = fi.getFieldName(); if (fieldName.equals("organization")) { lookName = fi.getString(); } if (fieldName.equals("users")) { lookName = fi.getString(); } if (fieldName.equals("categories")) { lookName = fi.getString(); } if (fieldName.equals("mapper")) { lookName = fi.getString(); } if (fieldName.equals("layout")) { lookName = fi.getString(); } if (fieldName.equals("mail")) { lookName = fi.getString(); } if (fieldName.equals("socialmedia")) { lookName = fi.getString(); } if (fieldName.equals("textstyle")) { lookName = fi.getString(); } if (fieldName.equals("containerstyle")) { lookName = fi.getString(); } if (fieldName.equals("element")) { lookName = fi.getString(); } String textstyleinfo = request.getParameter("textstyle"); String containerstyle = request.getParameter("containerstyle"); String mapfiledata = request.getParameter("element"); String textstylearray[] = textstyleinfo.split(","); String containerstylearray[] = containerstyle.split(" "); String mapfiledataarray[] = mapfiledata.split(","); // String image = request.getParameter("image"); logger.log(Level.INFO, containerstyle); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("layout"); doc.appendChild(rootElement); Document doc1 = docBuilder.newDocument(); Element rootElement1 = doc1.createElement("models"); doc1.appendChild(rootElement1); Element container = doc.createElement("container"); rootElement.appendChild(container); // for (int i = 0; i <= containerstylearray.length - 1; i++) { // String v[] = containerstylearray[i].split(":"); // Attr attr = doc.createAttribute(v[0]); // attr.setValue("" + v[1]); // container.setAttributeNode(attr); // } // // // staff elements // for (int i = 0; i <= textstylearray.length - 1; i++) { // Element element = doc.createElement("element"); // rootElement.appendChild(element); // String field1[] = textstylearray[i].split(" "); // for (int j = 0; j <= field1.length - 1; j++) { // String field2[] = field1[j].split(":"); // for (int k = 0; k < field2.length - 1; k++) { // Attr attr = doc.createAttribute(field2[0]); // attr.setValue("" + field2[1]); // element.setAttributeNode(attr); // } // } // } // // // for mapper xml file // for (int i = 0; i <= mapfiledataarray.length - 1; i++) { // Element element1 = doc1.createElement("model"); // rootElement1.appendChild(element1); // String field1[] = mapfiledataarray[i].split(" "); // for (int j = 0; j <= field1.length - 1; j++) { // String field2[] = field1[j].split(":"); // for (int k = 0; k < field2.length - 1; k++) { // Attr attr = doc1.createAttribute(field2[k]); // attr.setValue("" + field2[1]); // element1.setAttributeNode(attr); // } // } // } // write the content into xml file // TransformerFactory transformerFactory = TransformerFactory.newInstance(); // Transformer transformer = transformerFactory.newTransformer(); // DOMSource source = new DOMSource(doc); // StreamResult result = new StreamResult(new File(uploadPath +File.separator + layoutfilename + ".xml")); // // TransformerFactory transformerFactory1 = TransformerFactory.newInstance(); // Transformer transformer1 = transformerFactory1.newTransformer(); // DOMSource source1 = new DOMSource(doc1); // StreamResult result1 = new StreamResult(new File(uploadPath +File.separator + mapperfilename + ".xml")); // Output to console for testing // StreamResult result = new StreamResult(System.out); // transformer.transform(source, result); // transformer1.transform(source1, result1); // layout.addLayouts(organization_id , user_id, category_id, layoutfilename, mapperfilename, type_email, type_social); } else { fieldName = fi.getFieldName(); fileName = fi.getName(); File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdirs(); } int inStr = fileName.indexOf("."); String Str = fileName.substring(0, inStr); fileName = lookName + "_" + Str + ".png"; boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); String filePath = uploadPath + File.separator + fileName; File storeFile = new File(filePath); fi.write(storeFile); out.println("Uploaded Filename: " + filePath + "<br>"); } } // look.addLooks(lookName, fileName); response.sendRedirect(request.getContextPath() + "/admin/looks.jsp"); // request_dispatcher = request.getRequestDispatcher("/admin/looks.jsp"); // request_dispatcher.forward(request, response); out.println("</body>"); out.println("</html>"); } else { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); out.println("<p>No file uploaded</p>"); out.println("</body>"); out.println("</html>"); } } catch (Exception ex) { logger.log(Level.SEVERE, util.Utility.logMessage(ex, "Exception while updating org name:", getSqlMethodsInstance().error)); out.println(getSqlMethodsInstance().error); } finally { out.close(); } }
From source file:com.esofthead.mycollab.community.ui.chart.JFreeChartWrapper.java
@Override public Resource getSource() { if (res == null) { StreamSource streamSource = new StreamResource.StreamSource() { private ByteArrayInputStream bytestream = null; ByteArrayInputStream getByteStream() { if (chart != null && bytestream == null) { int width = getGraphWidth(); int height = getGraphHeight(); if (mode == RenderingMode.SVG) { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = null; try { docBuilder = docBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e1) { throw new RuntimeException(e1); }//from w w w. j ava2s . c om Document document = docBuilder.newDocument(); Element svgelem = document.createElement("svg"); document.appendChild(svgelem); // Create an instance of the SVG Generator SVGGraphics2D svgGenerator = new SVGGraphics2D(document); // draw the chart in the SVG generator chart.draw(svgGenerator, new Rectangle(width, height)); Element el = svgGenerator.getRoot(); el.setAttributeNS(null, "viewBox", "0 0 " + width + " " + height + ""); el.setAttributeNS(null, "style", "width:100%;height:100%;"); el.setAttributeNS(null, "preserveAspectRatio", getSvgAspectRatio()); // Write svg to buffer ByteArrayOutputStream baoutputStream = new ByteArrayOutputStream(); Writer out; try { OutputStream outputStream = gzipEnabled ? new GZIPOutputStream(baoutputStream) : baoutputStream; out = new OutputStreamWriter(outputStream, "UTF-8"); /* * don't use css, FF3 can'd deal with the result * perfectly: wrong font sizes */ boolean useCSS = false; svgGenerator.stream(el, out, useCSS, false); outputStream.flush(); outputStream.close(); bytestream = new ByteArrayInputStream(baoutputStream.toByteArray()); } catch (Exception e) { log.error("Error while generating SVG chart", e); } } else { // Draw png to bytestream try { byte[] bytes = ChartUtilities.encodeAsPNG(chart.createBufferedImage(width, height)); bytestream = new ByteArrayInputStream(bytes); } catch (Exception e) { log.error("Error while generating PNG chart", e); } } } else { bytestream.reset(); } return bytestream; } @Override public InputStream getStream() { return getByteStream(); } }; res = new StreamResource(streamSource, String.format("graph%d", System.currentTimeMillis())) { @Override public int getBufferSize() { if (getStreamSource().getStream() != null) { try { return getStreamSource().getStream().available(); } catch (IOException e) { log.warn("Error while get stream info", e); return 0; } } else { return 0; } } @Override public long getCacheTime() { return 0; } @Override public String getFilename() { if (mode == RenderingMode.PNG) { return super.getFilename() + ".png"; } else { return super.getFilename() + (gzipEnabled ? ".svgz" : ".svg"); } } @Override public DownloadStream getStream() { DownloadStream downloadStream = new DownloadStream(getStreamSource().getStream(), getMIMEType(), getFilename()); if (gzipEnabled && mode == RenderingMode.SVG) { downloadStream.setParameter("Content-Encoding", "gzip"); } return downloadStream; } @Override public String getMIMEType() { if (mode == RenderingMode.PNG) { return "image/png"; } else { return "image/svg+xml"; } } }; } return res; }
From source file:at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWClient.java
private Element getSOAPBody() throws SZRGWClientException { Document doc_; try {// w w w. jav a 2 s . c om doc_ = ParepUtils.createEmptyDocument(); Element root = doc_.createElementNS(SOAPConstants.SOAP_ENV_NS, SOAPConstants.SOAP_ENV_PREFIX + SOAPConstants.ENVELOPE); doc_.appendChild(root); root.setAttribute("xmlns" + SOAPConstants.SOAP_ENV_POSTFIX, SOAPConstants.SOAP_ENV_NS); //root.setAttribute(SOAPConstants.SOAP_ENV_PREFIX + SOAPConstants.ENCODING_STYLE, SOAPConstants.SOAP_ENV_ENCODING_STYLE); root.setAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema"); root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); Element body = doc_.createElementNS(SOAPConstants.SOAP_ENV_NS, SOAPConstants.SOAP_ENV_PREFIX + SOAPConstants.BODY); root.appendChild(body); return body; } catch (SZRGWClientException e) { throw new SZRGWClientException(e); } }
From source file:com.aipo.container.gadgets.parse.AipoNekoSimplifiedHtmlParser.java
@Override protected Document parseDomImpl(String source) throws GadgetException { DocumentHandler handler;/* w w w . j av a 2 s . c o m*/ HTMLConfiguration config = newConfiguration(); try { handler = parseHtmlImpl(source, config, new NormalizingTagBalancer()); } catch (IOException ioe) { return null; } Document document = handler.getDocument(); document.appendChild(DomUtil.getFirstNamedChildNode(handler.getFragment(), "html")); fixNekoWeirdness(document); return document; }
From source file:com.limegroup.gnutella.archive.ArchiveContribution.java
/** * @throws IllegalStateException/*ww w . j ava 2 s.co m*/ * If java's xml configuration is bad * @return */ private Document getFilesDocument() { /* * Sample _files.xml file: * * <files> * <file name="MyHomeMovie.mpeg" source="original"> * <runtime>2:30</runtime> * <format>MPEG2</format> * </file> * </files> * */ final String FILES_ELEMENT = "files"; try { final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); final DocumentBuilder db = dbf.newDocumentBuilder(); final Document document = db.newDocument(); final Element filesElement = document.createElement(FILES_ELEMENT); document.appendChild(filesElement); Collection files = getFiles(); for (final Iterator i = files.iterator(); i.hasNext();) { final File file = (File) i.next(); final Element fileElement = file.getElement(document); filesElement.appendChild(fileElement); } return document; } catch (final ParserConfigurationException e) { final IllegalStateException ise = new IllegalStateException(); ise.initCause(e); throw ise; } }
From source file:com.microsoft.windowsazure.messaging.Registration.java
/** * Creates an XML representation of the Registration * @throws Exception/*from w ww . j a v a 2 s . co m*/ */ String toXml() throws Exception { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); builder.setEntityResolver(new EntityResolver() { @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { return null; } }); Document doc = builder.newDocument(); Element entry = doc.createElement("entry"); entry.setAttribute("xmlns", "http://www.w3.org/2005/Atom"); doc.appendChild(entry); appendNodeWithValue(doc, entry, "id", getURI()); appendNodeWithValue(doc, entry, "updated", getUpdatedString()); appendContentNode(doc, entry); return getXmlString(doc.getDocumentElement()); }
From source file:com.ToResultSet.java
@Path("/input") @GET//from w w w . ja v a 2s .co m @Produces(MediaType.APPLICATION_JSON) public String toResultSet(@QueryParam("budget") String x, @QueryParam("maxbudget") String y, @QueryParam("location") String location, @QueryParam("date") String minDateString) throws ParserConfigurationException, TransformerException, ParseException { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println("Fehler bei MySQL-JDBC-Bridge" + e); } //SQL Query wird hier erzeugt je nach dem Daten, die angegeben werden try { int minBudget = 0; int maxBudget = 0; try { minBudget = Integer.valueOf(x); } catch (NumberFormatException e) { if (x.length() > 0) { return "Ihre Budget soll aus Zahlen bestehen"; } } try { maxBudget = Integer.valueOf(y); } catch (NumberFormatException e) { if (y.length() > 0) { return "Ihre Budget soll aus Zahlen bestehen"; } } try { test = Integer.valueOf(location); if (test >= 0) { return "Location soll aus String bestehen"; } } catch (Exception e) { } try { if (minDateString.substring(2, 3).contains("-") && minDateString.length() > 0) { return "Date Format soll yyyy-MM-dd"; } else { java.util.Date date1 = sdf.parse(minDateString); minDate = new java.sql.Date(date1.getTime()); } } catch (Exception e) { if (minDateString.length() > 0) return "Date Format soll yyyy-MM-dd"; } //Connection mit dem SQL wird erzeugt String url = "jdbc:mysql://" + host + "/" + dbName; connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306/location?autoReconnect=true&useSSL=false", "root", "dreamhigh"); statement = connection.createStatement(); String sqlQuery = "Select * FROM " + dbTable; List<String> whereClause = new ArrayList<>(); if (minBudget > 0) { whereClause.add("Budget >= " + minBudget); } if (maxBudget > 0) { whereClause.add("Budget <= " + maxBudget); } if (minBudget > maxBudget && maxBudget > 0 && minBudget > 0) { return "Minimal Budget soll kleiner als Maximal Budget"; } if (minDate != null) { whereClause.add("Date >= '" + minDate + "'"); } if (location != null && !location.isEmpty()) { whereClause.add("Location = '" + location + "'"); } //Die Daten werden nach dem Budget absteigend sortiert if (whereClause.size() > 0) { sqlQuery += " WHERE " + StringUtils.join(whereClause, " AND ") + " ORDER BY Budget DESC"; } if (whereClause.size() == 0) { sqlQuery += " ORDER BY Budget DESC"; } resultSet = statement.executeQuery(sqlQuery); int spalten = resultSet.getMetaData().getColumnCount(); System.out.println("Anzahl Spalten: " + spalten); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); Element results = doc.createElement("Results"); doc.appendChild(results); connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306/location?autoReconnect=true&useSSL=false", "root", "dreamhigh"); ResultSetMetaData rsmd = resultSet.getMetaData(); int colCount = rsmd.getColumnCount(); while (resultSet.next()) { String[] str = new String[8]; for (int k = 1; k <= spalten; k++) { str[k - 1] = resultSet.getString(k); result.add(resultSet.getString(k)); } //Result wird hier als XML zuerst erzeugt und dann Json Element row = doc.createElement("Row"); results.appendChild(row); for (int ii = 1; ii <= colCount; ii++) { String columnName = rsmd.getColumnName(ii); Object value = resultSet.getObject(ii); Element node = doc.createElement(columnName); if (value != null) { node.appendChild(doc.createTextNode(value.toString())); row.appendChild(node); } } } System.out.println(getDocumentAsXml(doc)); try { xmlJSONObj = XML.toJSONObject(getDocumentAsXml(doc)); outPut = xmlJSONObj.toString(4); System.out.println(outPut); return outPut; } catch (JSONException je) { } } catch (SQLException e) { System.out.println("Fehler bei Tabellenabfrage: " + e); } return outPut; }