List of usage examples for javax.xml.parsers DocumentBuilder newDocument
public abstract Document newDocument();
From source file:de.mpg.escidoc.services.transformation.Util.java
public static Node getSize(String url) { DocumentBuilder documentBuilder; HttpClient httpClient = new HttpClient(); HeadMethod headMethod = new HeadMethod(url); try {/*ww w . java 2 s. c o m*/ logger.info("Getting size of " + url); ProxyHelper.executeMethod(httpClient, headMethod); if (headMethod.getStatusCode() != 200) { logger.warn("Wrong status code " + headMethod.getStatusCode() + " at " + url); } documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element element = document.createElement("size"); document.appendChild(element); Header header = headMethod.getResponseHeader("Content-Length"); logger.info("HEAD Request to " + url + " returned Content-Length: " + (header != null ? header.getValue() : null)); if (header != null) { element.setTextContent(header.getValue()); return document; } else { //did not get length via HEAD request, try to do a GET request //workaround for biomed central, where HEAD requests sometimes return Content-Length, sometimes not logger.info("GET request to " + url + " did not return any Content-Length. Trying GET request."); httpClient = new HttpClient(); GetMethod getMethod = new GetMethod(url); ProxyHelper.executeMethod(httpClient, getMethod); if (getMethod.getStatusCode() != 200) { logger.warn("Wrong status code " + getMethod.getStatusCode() + " at " + url); } InputStream is = getMethod.getResponseBodyAsStream(); long size = 0; while (is.read() != -1) { size++; } is.close(); logger.info("GET request to " + url + " returned a file with length: " + size); element.setTextContent(String.valueOf(size)); return document; } } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.limegroup.gnutella.archive.ArchiveContribution.java
/** * @throws IllegalStateException//from w ww . j a v a 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:de.bitzeche.video.transcoding.zencoder.ZencoderClient.java
private Document createDocumentForException(String message) { try {//from w w w . j a va 2s. c om 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.ibm.dbwkl.request.internal.LoggingHandler.java
/** * @return xml output//from w ww . ja va 2s. co m */ @Override public Document getXML() { if (hasRequestOption(Options.LOG_LIST)) { try { List<LoggerEntry> logEntries = Logger.getLogEntries(); int entriesToShow = Integer.parseInt(getRequestOption(Options.LOG_LIST)); if (entriesToShow < logEntries.size()) logEntries = logEntries.subList(logEntries.size() - entriesToShow, logEntries.size()); // create the document DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); // create the document root node Element root = document.createElement("db2wklresult"); document.appendChild(root); // create the result information Element rc = document.createElement("rc"); rc.setTextContent(Integer.toString(this.getResult().rc)); root.appendChild(rc); Element object = document.createElement("resultObject"); object.setTextContent( this.getResult().resultObj == null ? "" : this.getResult().resultObj.toString()); Element entries = null; for (LoggerEntry logEntry : logEntries) { entries = document.createElement("logEntry"); entries.setAttribute("formattedTime", logEntry.getFormatedTime()); entries.setAttribute("requestName", logEntry.getRequestName()); entries.setAttribute("loglevel", logEntry.getLevel()); entries.setAttribute("message", logEntry.getMessage().replaceAll(String.valueOf('"'), "'")); entries.setAttribute("class", logEntry.getClasse()); entries.setAttribute("method", logEntry.getMethod()); entries.setAttribute("line", String.valueOf(logEntry.getLineNumber())); entries.setAttribute("thread", logEntry.getThread()); entries.setAttribute("threadGroup", logEntry.getThreadGroup()); object.appendChild(entries); } root.appendChild(object); // return the resulting document return document; } catch (ParserConfigurationException e) { Logger.log(e.getMessage(), LogLevel.Error); } } return null; }
From source file:com.photon.phresco.impl.ConfigManagerImpl.java
private void createNewDoc() throws ConfigurationException { try {//from w w w.j a va2 s. c om DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(false); DocumentBuilder builder = domFactory.newDocumentBuilder(); document = builder.newDocument(); rootElement = document.createElement("environments"); document.appendChild(rootElement); } catch (ParserConfigurationException e) { throw new ConfigurationException(e); } }
From source file:com.microsoft.windowsazure.management.sql.RecoverDatabaseOperationsImpl.java
/** * Issues a recovery request for an Azure SQL Database. * * @param sourceServerName Required. The name of the Azure SQL Database * Server on which the database was hosted. * @param parameters Required. Additional parameters for the Create Recover * Database Operation request.// ww w . j a v a2 s . c o m * @throws ParserConfigurationException Thrown if there was an error * configuring the parser for the response body. * @throws SAXException Thrown if there was an error parsing the response * body. * @throws TransformerException Thrown if there was an error creating the * DOM transformer. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @return Contains the response to the Create Recover Database Operation * request. */ @Override public RecoverDatabaseOperationCreateResponse create(String sourceServerName, RecoverDatabaseOperationCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { // Validate if (sourceServerName == null) { throw new NullPointerException("sourceServerName"); } if (parameters == null) { throw new NullPointerException("parameters"); } if (parameters.getSourceDatabaseName() == null) { throw new NullPointerException("parameters.SourceDatabaseName"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("sourceServerName", sourceServerName); tracingParameters.put("parameters", parameters); CloudTracing.enter(invocationId, this, "createAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/sqlservers/servers/"; url = url + URLEncoder.encode(sourceServerName, "UTF-8"); url = url + "/recoverdatabaseoperations"; String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpPost httpRequest = new HttpPost(url); // Set Headers httpRequest.setHeader("Content-Type", "application/xml"); httpRequest.setHeader("x-ms-version", "2012-03-01"); // Serialize Request String requestContent = null; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document requestDoc = documentBuilder.newDocument(); Element serviceResourceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ServiceResource"); requestDoc.appendChild(serviceResourceElement); Element sourceDatabaseNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SourceDatabaseName"); sourceDatabaseNameElement.appendChild(requestDoc.createTextNode(parameters.getSourceDatabaseName())); serviceResourceElement.appendChild(sourceDatabaseNameElement); if (parameters.getTargetServerName() != null) { Element targetServerNameElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "TargetServerName"); targetServerNameElement.appendChild(requestDoc.createTextNode(parameters.getTargetServerName())); serviceResourceElement.appendChild(targetServerNameElement); } if (parameters.getTargetDatabaseName() != null) { Element targetDatabaseNameElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "TargetDatabaseName"); targetDatabaseNameElement.appendChild(requestDoc.createTextNode(parameters.getTargetDatabaseName())); serviceResourceElement.appendChild(targetDatabaseNameElement); } DOMSource domSource = new DOMSource(requestDoc); StringWriter stringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(domSource, streamResult); requestContent = stringWriter.toString(); StringEntity entity = new StringEntity(requestContent); httpRequest.setEntity(entity); httpRequest.setHeader("Content-Type", "application/xml"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_CREATED) { ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result RecoverDatabaseOperationCreateResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_CREATED) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new RecoverDatabaseOperationCreateResponse(); DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); documentBuilderFactory2.setNamespaceAware(true); DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); Element serviceResourceElement2 = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ServiceResource"); if (serviceResourceElement2 != null) { RecoverDatabaseOperation serviceResourceInstance = new RecoverDatabaseOperation(); result.setOperation(serviceResourceInstance); Element requestIDElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "RequestID"); if (requestIDElement != null) { String requestIDInstance; requestIDInstance = requestIDElement.getTextContent(); serviceResourceInstance.setId(requestIDInstance); } Element sourceDatabaseNameElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "SourceDatabaseName"); if (sourceDatabaseNameElement2 != null) { String sourceDatabaseNameInstance; sourceDatabaseNameInstance = sourceDatabaseNameElement2.getTextContent(); serviceResourceInstance.setSourceDatabaseName(sourceDatabaseNameInstance); } Element targetServerNameElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "TargetServerName"); if (targetServerNameElement2 != null) { String targetServerNameInstance; targetServerNameInstance = targetServerNameElement2.getTextContent(); serviceResourceInstance.setTargetServerName(targetServerNameInstance); } Element targetDatabaseNameElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "TargetDatabaseName"); if (targetDatabaseNameElement2 != null) { String targetDatabaseNameInstance; targetDatabaseNameInstance = targetDatabaseNameElement2.getTextContent(); serviceResourceInstance.setTargetDatabaseName(targetDatabaseNameInstance); } Element nameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "Name"); if (nameElement != null) { String nameInstance; nameInstance = nameElement.getTextContent(); serviceResourceInstance.setName(nameInstance); } Element typeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "Type"); if (typeElement != null) { String typeInstance; typeInstance = typeElement.getTextContent(); serviceResourceInstance.setType(typeInstance); } Element stateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "State"); if (stateElement != null) { String stateInstance; stateInstance = stateElement.getTextContent(); serviceResourceInstance.setState(stateInstance); } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:com.ToResultSet.java
@Path("/input") @GET//from w w w . j a v a 2s. c o 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; }
From source file:com.ToResultSet.java
@Path("/tabelle") @GET// w w w . j a v a2 s . c o m public String toResultSetTabelle(@QueryParam("budget") String x, @QueryParam("maxbudget") String y, @QueryParam("location") String location, @QueryParam("date") String minDateString) throws ParserConfigurationException, TransformerException, ParseException { ArrayList<String[]> result1 = new ArrayList<String[]>(); 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(); 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[6]; for (int k = 1; k <= spalten; k++) { str[k - 1] = resultSet.getString(k); if (result1.contains(str) == false) { result1.add(str); } } } //HTML Datei wird mit Hilfe von String Builder erzeugt sb.append("<html><body>"); for (Iterator iter = result1.iterator(); iter.hasNext();) { String[] str = (String[]) iter.next(); sb.append("<br>"); sb.append("<br>"); for (int i = 0; i < str.length; i++) { sb.append(System.lineSeparator()); if (i == 0) { sb.append("Link : <a href=" + str[i] + ">" + str[i] + "</a><br>"); } if (i == 1) { sb.append("Budget : " + str[i] + "<br>"); } if (i == 2) { sb.append("Location : " + str[i] + "<br>"); } if (i == 3) { sb.append("Qm : " + str[i] + "<br>"); } if (i == 4) { sb.append("Room : " + str[i] + "<br>"); } if (i == 5) { sb.append("Date : " + str[i] + "<br>"); } } } sb.append("</body>"); sb.append("</html>"); outPut = sb.toString(); } catch (SQLException e) { System.out.println("Fehler bei Tabellenabfrage: " + e); } return outPut = sb.toString(); }
From source file:com.intbit.ServletModel.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w.j ava 2 s. com*/ * * @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.meikai.common.web.servlet.FCKeditorConnectorServlet.java
/** * Manage the Get requests (GetFolders, GetFoldersAndFiles, CreateFolder).<br> * /*from w w w.j av a2 s .c o m*/ * The servlet accepts commands sent in the following format:<br> * connector?Command=CommandName&Type=ResourceType&CurrentFolder=FolderPath<br> * <br> * It execute the command and then return the results to the client in XML * format. * */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (debug) System.out.println("--- BEGIN DOGET (list files) ---"); response.setContentType("text/xml; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); // edit begin +++++++++++++++++ /* * User user = (User) HttpUtil.getAttribute(request.getSession(), * Symbols.SESSION_USER); String userId = ""; if (debug) * System.out.println("user is null : " + (user == null)); if (user == * null) { userId = HttpUtil.getCookieValue(request, * Symbols.COOKIE_FCKEDITOR); } else { userId = user.getId().toString(); } * if (debug) System.out.println("get user id from cookie and userId * value is : " + userId); */ /* * String currentPath=baseDir+typeStr+currentFolderStr; String * currentDirPath=getServletContext().getRealPath(currentPath); */ if (debug) System.out.println("? " + dateCreated); String currentPath = baseDir + typeStr + "/" + dateCreated.substring(0, 4) + "/" + dateCreated.substring(5) + currentFolderStr; if (debug) System.out.println("?Path : " + currentPath); // create user dir makeDirectory(getServletContext().getRealPath("/"), currentPath); // String currentPath = ""; String currentDirPath = getServletContext().getRealPath(currentPath); // edit end ++++++++++++++++ File currentDir = new File(currentDirPath); /* * if(!currentDir.exists()){ currentDir.mkdir(); } */ Document document = null; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.newDocument(); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } Node root = CreateCommonXml(document, commandStr, typeStr, currentFolderStr, request.getContextPath() + currentPath); if (debug) System.out.println("Command = " + commandStr); if (commandStr.equals("GetFolders")) { getFolders(currentDir, root, document); } else if (commandStr.equals("GetFoldersAndFiles")) { getFolders(currentDir, root, document); getFiles(currentDir, root, document); } else if (commandStr.equals("CreateFolder")) { String newFolderStr = request.getParameter("NewFolderName"); File newFolder = new File(currentDir, newFolderStr); String retValue = "110"; if (newFolder.exists()) { retValue = "101"; } else { try { boolean dirCreated = newFolder.mkdir(); if (dirCreated) retValue = "0"; else retValue = "102"; } catch (SecurityException sex) { retValue = "103"; } } setCreateFolderResponse(retValue, root, document); } document.getDocumentElement().normalize(); try { TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(out); transformer.transform(source, result); if (debug) { StreamResult dbgResult = new StreamResult(System.out); transformer.transform(source, dbgResult); System.out.println(""); System.out.println("--- END DOGET ---"); } } catch (Exception ex) { ex.printStackTrace(); } out.flush(); out.close(); }