List of usage examples for javax.servlet ServletOutputStream print
public void print(double d) throws IOException
double
value to the client, with no carriage return-line feed (CRLF) at the end. From source file:org.my.eaptest.UploadServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;charset=UTF-8"); ServletOutputStream out = resp.getOutputStream(); // Check that we have a file upload request. if (!ServletFileUpload.isMultipartContent(req)) { out.println(//from w w w .j a v a2s .com "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">"); 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>"); return; } // 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); // Maximum size that will be stored in memory. factory.setSizeThreshold(MAX_FILE_SIZE); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request to get file items. try { List<FileItem> items = upload.parseRequest(req); out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); out.println("<div style=\"text-align: left;\">"); // we look for a filename item and/or file item with file content Iterator<FileItem> iter = items.iterator(); String filename = null; String contents = null; boolean delete = false; while (iter.hasNext()) { FileItem item = iter.next(); boolean isFormField = item.isFormField(); String fieldName = item.getFieldName(); if (isFormField && fieldName.equals("filename")) { String name = item.getString(); if (name.length() > 0 || filename == null) { filename = name; } } else if (isFormField && fieldName.equals("readonly")) { // means no filename or file provided } else if (isFormField && fieldName.equals("delete")) { // delete one or all fiels depending on whether filename is provided delete = true; } else if (!isFormField && fieldName.equals("file")) { contents = fromStream(item.getInputStream()); contents = StringEscapeUtils.escapeHtml(contents); if (filename == null || filename.length() == 0) { filename = item.getName(); } } else { if (isFormField) { out.print("<p><pre>Unexpected field name : "); out.print(fieldName); out.println("</pre>"); } else { String name = item.getName(); out.print("<p><pre>Unexpected file item : "); out.print(name); out.print(" for field "); out.print(fieldName); out.println("</pre>"); } out.println("</body>"); out.println("</html>"); return; } } // if we don't have a filename then either list or delete all files in the hashtable if (filename == null) { if (delete) { filedata.clear(); out.println("All files deleted!<br/>"); } else { Set<String> keys = filedata.keySet(); out.println("All files:<br/>"); out.println("<pre>"); if (keys.isEmpty()) { out.println("No files found!"); } else { for (String key : keys) { out.print(key); FileSet set = filedata.get(key); if (set != null) { out.print(" "); out.println(set.size()); } else { out.println(" 0"); } } } out.println("</pre>"); } out.println("</body>"); out.println("</html>"); return; } // if we have a filename and no contents then we // retrieve the file contents from the hashmap // and maybe delete the file // if we have a filename and contents then we update // the hashmap -- delete should not be supplied in // this case boolean noUpdate = (contents == null); if (noUpdate) { if (delete) { FileSet set = filedata.remove(filename); contents = (set != null ? set.get() : null); } else { FileSet set = filedata.get(filename); contents = (set != null ? set.get() : null); } } else { FileSet set = new FileSet(); FileSet old = filedata.putIfAbsent(filename, set); if (old != null) { set = old; } set.add(contents); } // now hand the contents back out.print("<pre>File: "); out.print(filename); boolean printContents = true; if (noUpdate) { if (contents == null) { out.println(" not found"); printContents = false; } else if (delete) { out.print(" deleted"); } } else { if (contents == null) { out.print(" added"); } else { out.print(" updated"); } } out.println("</pre><br/>"); if (printContents) { out.println("<pre>"); out.println(contents); out.println("</pre>"); } out.println("</body>"); out.println("</html>"); } catch (FileUploadException fuEx) { log.error("Problem with process file upload:", fuEx); } }
From source file:org.apache.catalina.servlets.DefaultServlet.java
/** * Copy the contents of the specified input stream to the specified * output stream, and ensure that both streams are closed before returning * (even in the face of an exception)./*from www . j a v a 2 s .co m*/ * * @param resourceInfo The ResourceInfo object * @param ostream The output stream to write to * @param ranges Enumeration of the ranges the client wanted to retrieve * @param contentType Content type of the resource * @throws IOException if an input/output error occurs */ private void copy(ResourceInfo resourceInfo, ServletOutputStream ostream, Enumeration ranges, String contentType) throws IOException { IOException exception = null; while ((exception == null) && (ranges.hasMoreElements())) { InputStream resourceInputStream = resourceInfo.getStream(); InputStream istream = // FIXME: internationalization??????? new BufferedInputStream(resourceInputStream, input); Range currentRange = (Range) ranges.nextElement(); // Writing MIME header. ostream.println(); ostream.println("--" + mimeSeparation); if (contentType != null) { ostream.println("Content-Type: " + contentType); } ostream.println("Content-Range: bytes " + currentRange.start + "-" + currentRange.end + "/" + currentRange.length); ostream.println(); // Printing content exception = copyRange(istream, ostream, currentRange.start, currentRange.end); try { istream.close(); } catch (Throwable t) { ; } } ostream.println(); ostream.print("--" + mimeSeparation + "--"); // Rethrow any exception that has occurred if (exception != null) { throw exception; } }
From source file:hu.sztaki.lpds.storage.service.carmen.server.upload.UploadServlet.java
/** * Processes requests for <code>GET</code> methods. * * @param request//from w w w . j a va2s .c o m * servlet request * @param response * servlet response * @throws IOException channel handling error * @throws ServletException Servlet error */ protected void getProcessRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // System.out.println(""); // System.out.println("UploadServlet getProcessRequest begin..."); ServletOutputStream out = response.getOutputStream(); String getSID = null; String getendSID = null; String retStr = new String(""); try { getSID = request.getParameter("sid"); // System.out.println("getSID: " + getSID); } catch (Exception e) { e.printStackTrace(); } try { getendSID = request.getParameter("endsid"); // System.out.println("getendSID: " + getendSID); } catch (Exception e) { e.printStackTrace(); } // if ((getSID != null) && (getendSID == null)) { // get type "sid" // System.out.println("get type SID : " + getSID); if (!getSID.trim().equals("")) { retStr = UploadUtils.getInstance().getGenerateRetHTMLString(getSID); } else { retStr = new String("Error in parameter: sid"); } } else if ((getSID == null) && (getendSID != null)) { // get type "endsid" // System.out.println("get type endSID : " + getendSID); if (!getendSID.trim().equals("")) { // check error uploads boolean haveError = false; // get file list (fileHash) Hashtable fileHash = UploadItemsList.getInstance().getFileHash(getendSID); // parse if ((fileHash != null) && (!fileHash.isEmpty())) { Enumeration enumeration = fileHash.keys(); StringBuffer sb = new StringBuffer(); while (enumeration.hasMoreElements()) { String fileName = (String) enumeration.nextElement(); if ((fileName != null) && (!fileName.equals(""))) { UploadItemBean uploadItemBean = (UploadItemBean) fileHash.get(fileName); Integer filePerCent = uploadItemBean.getPerCent(); String fileErrorStr = uploadItemBean.getErrorStr(); // System.out.println("fileName - fileErrorStr : " + fileName + " - " + fileErrorStr); if (fileErrorStr.startsWith("Error")) { haveError = true; // System.out.println("have error in : "); // retStr = new String(fileErrorStr + "</ br>"); sb.append(new String(fileErrorStr + "</ br>")); // System.out.println("fileName : " + fileName); } } } retStr = sb.toString(); // System.out.println("Storage Upload Servlet haveError : " + haveError); if (haveError) { retStr = new String("Error in upload process ! </ br>\n" + retStr); } else { // System.out.println("no have error in : "); retStr = new String("Upload is succesfull !" + "</ br>"); } } else { retStr = new String("Error getFileHash is null !"); } } else { retStr = new String("Error in parameter: endsid"); } } else if ((getSID == null) && (getendSID == null)) { // getSID == null and getendSID == null // System.out.println("getSID : " + getSID + " - getendSID : " + getendSID); retStr = new String("Error in parameter: sid and endsid !"); } else { retStr = new String("Error in parameters !"); } out.print(retStr); // System.out.println("UploadServlet getProcessRequest retString: " + retStr); // System.out.println("UploadServlet getProcessRequest end..."); }
From source file:de.innovationgate.wgpublisher.WGPDispatcher.java
private void writeRangesData(DataSource data, List<AcceptRange> ranges, HttpServletResponse response, String dbHint, long size) throws IOException, HttpErrorException, UnsupportedEncodingException { ServletOutputStream out = response.getOutputStream(); for (AcceptRange range : ranges) { InputStream in = data.getInputStream(); if (in == null) { throw new HttpErrorException(404, "File not found: " + data.getName(), dbHint); }//w w w .j av a2 s . c om if (ranges.size() != 1) { out.println(); out.println("--" + BYTERANGE_BOUNDARY); out.println("Content-Type: " + data.getContentType()); out.println("Content-Range: bytes " + range.from + "-" + range.to + "/" + size); out.println(); } if (range.from > 0) { in.skip(range.from); } try { WGUtils.inToOutLimited(in, out, (new Long(range.to - range.from + 1)).intValue(), 2048); out.flush(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } } if (ranges.size() != 1) { out.println(); out.print("--" + BYTERANGE_BOUNDARY + "--"); out.flush(); } }
From source file:org.gss_project.gss.server.rest.Webdav.java
/** * Copy the contents of the specified input stream to the specified output * stream, and ensure that both streams are closed before returning (even in * the face of an exception)./* w w w . java2 s. com*/ * * @param file * @param ostream The output stream to write to * @param ranges Enumeration of the ranges the client wanted to retrieve * @param contentType Content type of the resource * @param req the HTTP request * @param oldBody the old version of the file, if requested * @exception IOException if an input/output error occurs * @throws RpcException * @throws InsufficientPermissionsException * @throws ObjectNotFoundException */ protected void copy(FileHeader file, ServletOutputStream ostream, Iterator ranges, String contentType, HttpServletRequest req, FileBody oldBody) throws IOException, ObjectNotFoundException, InsufficientPermissionsException, RpcException { IOException exception = null; User user = getUser(req); while (exception == null && ranges.hasNext()) { InputStream resourceInputStream = oldBody == null ? getService().getFileContents(user.getId(), file.getId()) : getService().getFileContents(user.getId(), file.getId(), oldBody.getId()); InputStream istream = new BufferedInputStream(resourceInputStream, input); Range currentRange = (Range) ranges.next(); // Writing MIME header. ostream.println(); ostream.println("--" + mimeSeparation); if (contentType != null) ostream.println("Content-Type: " + contentType); ostream.println("Content-Range: bytes " + currentRange.start + "-" + currentRange.end + "/" + currentRange.length); ostream.println(); // Printing content exception = copyRange(istream, ostream, currentRange.start, currentRange.end); istream.close(); } ostream.println(); ostream.print("--" + mimeSeparation + "--"); // Rethrow any exception that has occurred if (exception != null) throw exception; }
From source file:org.opencms.webdav.CmsWebdavServlet.java
/** * Copy the contents of the specified input stream to the specified * output stream, and ensure that both streams are closed before returning * (even in the face of an exception).<p> * * @param item the RepositoryItem// w w w .j a v a 2 s .com * @param ostream the output stream to write to * @param ranges iterator of the ranges the client wants to retrieve * @param contentType the content type of the resource * * @throws IOException if an input/output error occurs */ protected void copy(I_CmsRepositoryItem item, ServletOutputStream ostream, Iterator<CmsWebdavRange> ranges, String contentType) throws IOException { IOException exception = null; while ((exception == null) && (ranges.hasNext())) { InputStream resourceInputStream = new ByteArrayInputStream(item.getContent()); InputStream istream = new BufferedInputStream(resourceInputStream, m_input); CmsWebdavRange currentRange = ranges.next(); // Writing MIME header. ostream.println(); ostream.println("--" + MIME_SEPARATION); if (contentType != null) { ostream.println("Content-Type: " + contentType); } ostream.println("Content-Range: bytes " + currentRange.getStart() + "-" + currentRange.getEnd() + "/" + currentRange.getLength()); ostream.println(); // Printing content exception = copyRange(istream, ostream, currentRange.getStart(), currentRange.getEnd()); try { istream.close(); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key(Messages.ERR_CLOSE_INPUT_STREAM_0), e); } } } ostream.println(); ostream.print("--" + MIME_SEPARATION + "--"); // Rethrow any exception that has occurred if (exception != null) { throw exception; } }
From source file:org.structr.web.servlet.HtmlServlet.java
@Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) { final Authenticator auth = getConfig().getAuthenticator(); List<Page> pages = null; boolean requestUriContainsUuids = false; SecurityContext securityContext;/*from w w w .j a va2 s .c o m*/ final App app; try { final String path = request.getPathInfo(); // check for registration (has its own tx because of write access if (checkRegistration(auth, request, response, path)) { return; } // check for registration (has its own tx because of write access if (checkResetPassword(auth, request, response, path)) { return; } // isolate request authentication in a transaction try (final Tx tx = StructrApp.getInstance().tx()) { securityContext = auth.initializeAndExamineRequest(request, response); tx.success(); } app = StructrApp.getInstance(securityContext); try (final Tx tx = app.tx()) { // Ensure access mode is frontend securityContext.setAccessMode(AccessMode.Frontend); request.setCharacterEncoding("UTF-8"); // Important: Set character encoding before calling response.getWriter() !!, see Servlet Spec 5.4 response.setCharacterEncoding("UTF-8"); boolean dontCache = false; logger.log(Level.FINE, "Path info {0}", path); // don't continue on redirects if (response.getStatus() == 302) { tx.success(); return; } final Principal user = securityContext.getUser(false); if (user != null) { // Don't cache if a user is logged in dontCache = true; } final RenderContext renderContext = RenderContext.getInstance(securityContext, request, response); renderContext.setResourceProvider(config.getResourceProvider()); final EditMode edit = renderContext.getEditMode(user); DOMNode rootElement = null; AbstractNode dataNode = null; final String[] uriParts = PathHelper.getParts(path); if ((uriParts == null) || (uriParts.length == 0)) { // find a visible page rootElement = findIndexPage(securityContext, pages, edit); logger.log(Level.FINE, "No path supplied, trying to find index page"); } else { if (rootElement == null) { rootElement = findPage(securityContext, pages, path, edit); } else { dontCache = true; } } if (rootElement == null) { // No page found // Look for a file final File file = findFile(securityContext, request, path); if (file != null) { streamFile(securityContext, file, request, response, edit); tx.success(); return; } // store remaining path parts in request final Matcher matcher = threadLocalUUIDMatcher.get(); for (int i = 0; i < uriParts.length; i++) { request.setAttribute(uriParts[i], i); matcher.reset(uriParts[i]); // set to "true" if part matches UUID pattern requestUriContainsUuids |= matcher.matches(); } if (!requestUriContainsUuids) { // Try to find a data node by name dataNode = findFirstNodeByName(securityContext, request, path); } else { dataNode = findNodeByUuid(securityContext, PathHelper.getName(path)); } //if (dataNode != null && !(dataNode instanceof Linkable)) { if (dataNode != null) { // Last path part matches a data node // Remove last path part and try again searching for a page // clear possible entry points request.removeAttribute(POSSIBLE_ENTRY_POINTS_KEY); rootElement = findPage(securityContext, pages, StringUtils.substringBeforeLast(path, PathHelper.PATH_SEP), edit); renderContext.setDetailsDataObject(dataNode); // Start rendering on data node if (rootElement == null && dataNode instanceof DOMNode) { rootElement = ((DOMNode) dataNode); } } } // look for pages with HTTP Basic Authentication (must be done as superuser) if (rootElement == null) { final HttpBasicAuthResult authResult = checkHttpBasicAuth(request, response, path); switch (authResult.authState()) { // Element with Basic Auth found and authentication succeeded case Authenticated: final Linkable result = authResult.getRootElement(); if (result instanceof Page) { rootElement = (DOMNode) result; securityContext = authResult.getSecurityContext(); renderContext.pushSecurityContext(securityContext); } else if (result instanceof File) { streamFile(authResult.getSecurityContext(), (File) result, request, response, EditMode.NONE); tx.success(); return; } break; // Page with Basic Auth found but not yet authenticated case MustAuthenticate: tx.success(); return; // no Basic Auth for given path, go on case NoBasicAuth: break; } } // Still nothing found, do error handling if (rootElement == null) { rootElement = notFound(response, securityContext); } if (rootElement == null) { tx.success(); return; } // check dont cache flag on page (if root element is a page) // but don't modify true to false dontCache |= rootElement.getProperty(Page.dontCache); if (EditMode.WIDGET.equals(edit) || dontCache) { setNoCacheHeaders(response); } if (!securityContext.isVisible(rootElement)) { rootElement = notFound(response, securityContext); if (rootElement == null) { tx.success(); return; } } else { if (!EditMode.WIDGET.equals(edit) && !dontCache && notModifiedSince(request, response, rootElement, dontCache)) { ServletOutputStream out = response.getOutputStream(); out.flush(); //response.flushBuffer(); out.close(); } else { // prepare response response.setCharacterEncoding("UTF-8"); String contentType = rootElement.getProperty(Page.contentType); if (contentType == null) { // Default contentType = "text/html;charset=UTF-8"; } if (contentType.equals("text/html")) { contentType = contentType.concat(";charset=UTF-8"); } response.setContentType(contentType); setCustomResponseHeaders(response); final boolean createsRawData = rootElement.getProperty(Page.pageCreatesRawData); // async or not? if (isAsync && !createsRawData) { final AsyncContext async = request.startAsync(); final ServletOutputStream out = async.getResponse().getOutputStream(); final AtomicBoolean finished = new AtomicBoolean(false); final DOMNode rootNode = rootElement; threadPool.submit(new Runnable() { @Override public void run() { try (final Tx tx = app.tx()) { //final long start = System.currentTimeMillis(); // render rootNode.render(renderContext, 0); finished.set(true); //final long end = System.currentTimeMillis(); //System.out.println("Done in " + (end-start) + " ms"); tx.success(); } catch (Throwable t) { t.printStackTrace(); final String errorMsg = t.getMessage(); try { //response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, errorMsg); finished.set(true); } catch (IOException ex) { ex.printStackTrace(); } } } }); // start output write listener out.setWriteListener(new WriteListener() { @Override public void onWritePossible() throws IOException { try { final Queue<String> queue = renderContext.getBuffer().getQueue(); while (out.isReady()) { String buffer = null; synchronized (queue) { buffer = queue.poll(); } if (buffer != null) { out.print(buffer); } else { if (finished.get()) { async.complete(); response.setStatus(HttpServletResponse.SC_OK); // prevent this block from being called again break; } Thread.sleep(1); } } } catch (Throwable t) { t.printStackTrace(); } } @Override public void onError(Throwable t) { t.printStackTrace(); } }); } else { final StringRenderBuffer buffer = new StringRenderBuffer(); renderContext.setBuffer(buffer); // render rootElement.render(renderContext, 0); try { response.getOutputStream().write(buffer.getBuffer().toString().getBytes("utf-8")); response.getOutputStream().flush(); response.getOutputStream().close(); } catch (IOException ioex) { ioex.printStackTrace(); } } } } tx.success(); } catch (FrameworkException fex) { fex.printStackTrace(); logger.log(Level.SEVERE, "Exception while processing request", fex); } } catch (IOException | FrameworkException t) { t.printStackTrace(); logger.log(Level.SEVERE, "Exception while processing request", t); UiAuthenticator.writeInternalServerError(response); } }
From source file:com.occamlab.te.web.TestServlet.java
public void processFormData(HttpServletRequest request, HttpServletResponse response) throws ServletException { try {// w ww . ja v a 2 s . c o m FileItemFactory ffactory; ServletFileUpload upload; List /* FileItem */ items = null; HashMap<String, String> params = new HashMap<String, String>(); boolean multipart = ServletFileUpload.isMultipartContent(request); if (multipart) { ffactory = new DiskFileItemFactory(); upload = new ServletFileUpload(ffactory); items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { params.put(item.getFieldName(), item.getString()); } } } else { Enumeration paramNames = request.getParameterNames(); while (paramNames.hasMoreElements()) { String name = (String) paramNames.nextElement(); params.put(name, request.getParameter(name)); } } HttpSession session = request.getSession(); ServletOutputStream out = response.getOutputStream(); String operation = params.get("te-operation"); if (operation.equals("Test")) { TestSession s = new TestSession(); String user = request.getRemoteUser(); File logdir = new File(conf.getUsersDir(), user); String mode = params.get("mode"); RuntimeOptions opts = new RuntimeOptions(); opts.setWorkDir(conf.getWorkDir()); opts.setLogDir(logdir); if (mode.equals("retest")) { opts.setMode(Test.RETEST_MODE); String sessionid = params.get("session"); String test = params.get("test"); if (sessionid == null) { int i = test.indexOf("/"); sessionid = i > 0 ? test.substring(0, i) : test; } opts.setSessionId(sessionid); if (test == null) { opts.addTestPath(sessionid); } else { opts.addTestPath(test); } for (Entry<String, String> entry : params.entrySet()) { if (entry.getKey().startsWith("profile_")) { String profileId = entry.getValue(); int i = profileId.indexOf("}"); opts.addTestPath(sessionid + "/" + profileId.substring(i + 1)); } } s.load(logdir, sessionid); opts.setSourcesName(s.getSourcesName()); } else if (mode.equals("resume")) { opts.setMode(Test.RESUME_MODE); String sessionid = params.get("session"); opts.setSessionId(sessionid); s.load(logdir, sessionid); opts.setSourcesName(s.getSourcesName()); } else { opts.setMode(Test.TEST_MODE); String sessionid = LogUtils.generateSessionId(logdir); s.setSessionId(sessionid); String sources = params.get("sources"); s.setSourcesName(sources); SuiteEntry suite = conf.getSuites().get(sources); s.setSuiteName(suite.getId()); // String suite = params.get("suite"); // s.setSuiteName(suite); String description = params.get("description"); s.setDescription(description); opts.setSessionId(sessionid); opts.setSourcesName(sources); opts.setSuiteName(suite.getId()); ArrayList<String> profiles = new ArrayList<String>(); for (Entry<String, String> entry : params.entrySet()) { if (entry.getKey().startsWith("profile_")) { profiles.add(entry.getValue()); opts.addProfile(entry.getValue()); } } s.setProfiles(profiles); s.save(logdir); } String webdir = conf.getWebDirs().get(s.getSourcesName()); // String requestURI = request.getRequestURI(); // String contextPath = requestURI.substring(0, requestURI.indexOf(request.getServletPath()) + 1); // URI contextURI = new URI(request.getScheme(), null, request.getServerName(), request.getServerPort(), contextPath, null, null); URI contextURI = new URI(request.getScheme(), null, request.getServerName(), request.getServerPort(), request.getRequestURI(), null, null); opts.setBaseURI(new URL(contextURI.toURL(), webdir + "/").toString()); // URI baseURI = new URL(contextURI.toURL(), webdir).toURI(); // String base = baseURI.toString() + URLEncoder.encode(webdir, "UTF-8") + "/"; // opts.setBaseURI(base); //System.out.println(opts.getSourcesName()); TECore core = new TECore(engine, indexes.get(opts.getSourcesName()), opts); //System.out.println(indexes.get(opts.getSourcesName()).toString()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); core.setOut(ps); core.setWeb(true); Thread thread = new Thread(core); session.setAttribute("testsession", core); thread.start(); response.setContentType("text/xml"); out.println("<thread id=\"" + thread.getId() + "\" sessionId=\"" + s.getSessionId() + "\"/>"); } else if (operation.equals("Stop")) { response.setContentType("text/xml"); TECore core = (TECore) session.getAttribute("testsession"); if (core != null) { core.stopThread(); session.removeAttribute("testsession"); out.println("<stopped/>"); } else { out.println("<message>Could not retrieve core object</message>"); } } else if (operation.equals("GetStatus")) { TECore core = (TECore) session.getAttribute("testsession"); response.setContentType("text/xml"); out.print("<status"); if (core.getFormHtml() != null) { out.print(" form=\"true\""); } if (core.isThreadComplete()) { out.print(" complete=\"true\""); session.removeAttribute("testsession"); } out.println(">"); out.print("<![CDATA["); // out.print(core.getOutput()); out.print(URLEncoder.encode(core.getOutput(), "UTF-8").replace('+', ' ')); out.println("]]>"); out.println("</status>"); } else if (operation.equals("GetForm")) { TECore core = (TECore) session.getAttribute("testsession"); String html = core.getFormHtml(); core.setFormHtml(null); response.setContentType("text/html"); out.print(html); } else if (operation.equals("SubmitForm")) { TECore core = (TECore) session.getAttribute("testsession"); Document doc = DB.newDocument(); Element root = doc.createElement("values"); doc.appendChild(root); for (String key : params.keySet()) { if (!key.startsWith("te-")) { Element valueElement = doc.createElement("value"); valueElement.setAttribute("key", key); valueElement.appendChild(doc.createTextNode(params.get(key))); root.appendChild(valueElement); } } if (multipart) { Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField() && !item.getName().equals("")) { File uploadedFile = new File(core.getLogDir(), StringUtils.getFilenameFromString(item.getName())); item.write(uploadedFile); Element valueElement = doc.createElement("value"); String key = item.getFieldName(); valueElement.setAttribute("key", key); if (core.getFormParsers().containsKey(key)) { Element parser = core.getFormParsers().get(key); URL url = uploadedFile.toURI().toURL(); Element resp = core.parse(url.openConnection(), parser, doc); Element content = DomUtils.getElementByTagName(resp, "content"); if (content != null) { Element child = DomUtils.getChildElement(content); if (child != null) { valueElement.appendChild(child); } } } else { Element fileEntry = doc.createElementNS(CTL_NS, "file-entry"); fileEntry.setAttribute("full-path", uploadedFile.getAbsolutePath().replace('\\', '/')); fileEntry.setAttribute("media-type", item.getContentType()); fileEntry.setAttribute("size", String.valueOf(item.getSize())); valueElement.appendChild(fileEntry); } root.appendChild(valueElement); } } } core.setFormResults(doc); response.setContentType("text/html"); out.println("<html>"); out.println("<head><title>Form Submitted</title></head>"); out.print("<body onload=\"window.parent.update()\"></body>"); out.println("</html>"); } } catch (Throwable t) { throw new ServletException(t); } }
From source file:edu.cornell.mannlib.vitro.webapp.controller.grefine.GrefinePropertyListServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doGet(req, resp); resp.setContentType("application/json"); VitroRequest vreq = new VitroRequest(req); try {//from w ww . ja va 2 s . com String callbackStr = (vreq.getParameter("callback") == null) ? "" : vreq.getParameter("callback"); ServletOutputStream out = resp.getOutputStream(); VClassDao vcDao = vreq.getUnfilteredWebappDaoFactory().getVClassDao(); DataPropertyDao dao = vreq.getUnfilteredWebappDaoFactory().getDataPropertyDao(); String topUri = vreq.getParameter("type"); VClass topClass = vcDao.getVClassByURI(topUri); HashSet<String> propURIs = new HashSet<String>(); HashMap<VClass, List<DataProperty>> classPropertiesMap = populateClassPropertiesMap(vcDao, dao, topUri, propURIs); // Construct json String JSONObject completeJson = new JSONObject(); JSONArray propertiesJsonArr = new JSONArray(); if (classPropertiesMap.size() > 0) { for (Iterator<VClass> iter = classPropertiesMap.keySet().iterator(); iter.hasNext();) { // add results to schema VClass vc = (VClass) iter.next(); //System.out.println("vc uri: " + vc.getURI()); //System.out.println("vc name: " + vc.getName()); ArrayList<DataProperty> vcProps = (ArrayList<DataProperty>) classPropertiesMap.get(vc); for (DataProperty prop : vcProps) { String nameStr = prop.getPublicName() == null ? prop.getName() == null ? null : prop.getName() : prop.getPublicName(); //System.out.println("--- uri: " + prop.getURI()); //System.out.println("--- name: " + nameStr); // top level JSONObject propertiesItemJson = new JSONObject(); JSONObject rootSchemaJson = new JSONObject(); rootSchemaJson.put("id", vc.getURI()); rootSchemaJson.put("name", vc.getName()); rootSchemaJson.put("alias", new JSONArray()); propertiesItemJson.put("schema", rootSchemaJson); // second level propertiesItemJson.put("id", prop.getURI()); propertiesItemJson.put("name", nameStr); propertiesItemJson.put("alias", new JSONArray()); JSONObject expectsJson = new JSONObject(); expectsJson.put("id", prop.getURI()); expectsJson.put("name", nameStr); expectsJson.put("alias", new JSONArray()); propertiesItemJson.put("expects", expectsJson); propertiesJsonArr.put(propertiesItemJson); } } } // get data properties from subclasses List<VClass> lvl2Classes = new ArrayList<VClass>(); List roots = null; String requestType = vreq.getParameter("type"); if (requestType != null) { roots = new LinkedList<VClass>(); roots.add(vcDao.getVClassByURI(requestType)); } if (roots != null) { String ontologyUri = null; Collections.sort(roots); Iterator rootIt = roots.iterator(); if (rootIt.hasNext()) { while (rootIt.hasNext()) { VClass root = (VClass) rootIt.next(); if (root != null) { List<VClass> lvl2ChildClasses = new ArrayList<VClass>(); addChildren(vcDao, vreq.getUnfilteredWebappDaoFactory(), root, lvl2ChildClasses, 0, ontologyUri); lvl2Classes.addAll(lvl2ChildClasses); } } } } for (VClass lvl2Class : lvl2Classes) { HashMap<VClass, List<DataProperty>> lvl2ClassPropertiesMap = populateClassPropertiesMap(vcDao, dao, lvl2Class.getURI(), propURIs); if (lvl2ClassPropertiesMap.size() > 0) { for (Iterator<VClass> iter = lvl2ClassPropertiesMap.keySet().iterator(); iter.hasNext();) { // add results to schema VClass vc = (VClass) iter.next(); ArrayList<DataProperty> vcProps = (ArrayList<DataProperty>) lvl2ClassPropertiesMap.get(vc); for (DataProperty prop : vcProps) { String nameStr = prop.getPublicName() == null ? prop.getName() == null ? null : prop.getName() : prop.getPublicName(); // top level JSONObject propertiesItemJson = new JSONObject(); JSONObject rootSchemaJson = new JSONObject(); rootSchemaJson.put("id", topClass.getURI()); rootSchemaJson.put("name", topClass.getName()); rootSchemaJson.put("alias", new JSONArray()); propertiesItemJson.put("schema", rootSchemaJson); // second level propertiesItemJson.put("id", vc.getURI()); propertiesItemJson.put("name", vc.getName()); propertiesItemJson.put("alias", new JSONArray()); propertiesItemJson.put("id2", prop.getURI()); propertiesItemJson.put("name2", nameStr); propertiesItemJson.put("alias2", new JSONArray()); JSONObject expectsJson = new JSONObject(); expectsJson.put("id", prop.getURI()); expectsJson.put("name", nameStr); expectsJson.put("alias", new JSONArray()); propertiesItemJson.put("expects", expectsJson); propertiesJsonArr.put(propertiesItemJson); } } } } completeJson.put("properties", propertiesJsonArr); out.print(callbackStr + "(" + completeJson.toString() + ")"); } catch (Exception ex) { log.warn(ex, ex); } }