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:com.chaosinmotion.securechat.server.LoginServlet.java
/** * Handle POST commands. This uses the cookie mechanism for Java * servlets to track users for security reasons, and handles the * commands for getting a token, for verifying server status, and for * logging in and changing a password./*from w w w .j a v a2s . c o m*/ */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ReturnResult retVal = null; /* * Step 1: determine the path element after the api/1/ URL. This * determines the command */ String path = req.getPathInfo(); if (path == null) { resp.sendError(404); return; } if (path.startsWith("/")) path = path.substring(1); /* * Now handle commands that do not require the user to be logged in */ try { HttpSession session = req.getSession(); if (path.equalsIgnoreCase("status")) { // Requests server status. This simply returns success. retVal = new ReturnResult(); } else if (path.equalsIgnoreCase("token")) { // Generates a token used to hash the password sent from // the client. We use the token as a 'salt' to salt the // sha256-hashed password, in order to avoid a replay // attack on the passwords. // // We generate the random token by generating a UUID. // Unlike the client code (where we coded our own UUID // system), the server is at a known location, so there // is little point to hide the server hardware. String token = UUID.randomUUID().toString(); session.setAttribute("token", token); retVal = new SimpleReturnResult("token", token); } else if (path.equalsIgnoreCase("login")) { // Handles the login request. This pulls the request // contents as a JSON object, and calls into our // utility class to handle the login logic. We use // the same pattern throughout. JSONTokener tokener = new JSONTokener(req.getInputStream()); JSONObject requestParams = new JSONObject(tokener); String token = (String) session.getAttribute("token"); Login.UserInfo uinfo = Login.processRequest(requestParams, token); if (uinfo == null) { retVal = new ReturnResult(Errors.ERROR_LOGIN, "Login error"); } else { retVal = new ReturnResult(); session.setAttribute("userinfo", uinfo); } } else if (path.equalsIgnoreCase("forgotpassword")) { // Handle a forgot password request. This is sent when a user // is attempting to add a new device but cannot remember his // password. This pulls the username, and calls into the // forgot password logic, which then sends out a message to // the various other devices. JSONTokener tokener = new JSONTokener(req.getInputStream()); JSONObject requestParams = new JSONObject(tokener); ForgotPassword.processRequest(requestParams); retVal = new ReturnResult(); } else if (path.equalsIgnoreCase("createaccount")) { // Handle an onboarding request to create a new account. // This processes the onboarding request with a new // account. JSONTokener tokener = new JSONTokener(req.getInputStream()); JSONObject requestParams = new JSONObject(tokener); Login.UserInfo uinfo = CreateAccount.processRequest(requestParams); if (uinfo == null) { retVal = new ReturnResult(Errors.ERROR_DUPLICATEUSER, "Internal Error"); } else { retVal = new ReturnResult(); session.setAttribute("userinfo", uinfo); } } else { /* * All the commands past this point require a user account. */ Login.UserInfo userinfo = (Login.UserInfo) session.getAttribute("userinfo"); if (userinfo == null) { retVal = new ReturnResult(Errors.ERROR_UNAUTHORIZED, "Not authorized"); } else { /* * Now handle the various command requests */ if (path.equalsIgnoreCase("updateforgotpassword")) { // Handle a forgotten password. We have an interesting // irony here that the user needs to be logged in // in order to reset his password. However, this // is handled by the fact that each device stores the // password in an encrypted format as a token on // each device. // // This also implies there is no way for a user to // reset his password if he doesn't have a device // already associated with is account. This is a // deliberate design decision. // // If we were to associate each account with an e-mail // account, then the reset pathway would be different // and would involve the user arriving at a web site // URL with a random token in the URI. JSONTokener tokener = new JSONTokener(req.getInputStream()); JSONObject requestParams = new JSONObject(tokener); if (UpdateForgottenPassword.processRequest(userinfo, requestParams)) { retVal = new ReturnResult(); } else { retVal = new ReturnResult(Errors.ERROR_INTERNAL, "Internal error"); } } else if (path.equalsIgnoreCase("changepassword")) { // Handle a change password request. This requries both // the existing password and the new password. // // Yes, the user has his device, but by asking for an // existing password this assures that the phone wasn't // for example picked up by someone else while in an // unlocked state. JSONTokener tokener = new JSONTokener(req.getInputStream()); JSONObject requestParams = new JSONObject(tokener); String token = (String) session.getAttribute("token"); if (ChangePassword.processRequest(userinfo, requestParams, token)) { retVal = new ReturnResult(); } else { retVal = new ReturnResult(Errors.ERROR_LOGIN, "Internal error"); } } } } } catch (Throwable th) { retVal = new ReturnResult(th); } /* * If we get here and we still haven't initialized return value, * set to a 404 error. We assume this reaches here with a null * value because the path doesn't exist. */ if (retVal == null) { resp.sendError(404); } else { /* * We now have a return result. Formulate the response */ ServletOutputStream stream = resp.getOutputStream(); resp.setContentType("application/json"); stream.print(retVal.toString()); } }
From source file:guru.nidi.raml.doc.servlet.MirrorServlet.java
@Override protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { final int delay = req.getParameter("delay") == null ? 0 : Integer.parseInt(req.getParameter("delay")); try {/*ww w . j ava 2 s . c o m*/ Thread.sleep(delay); } catch (InterruptedException e) { //ignore } final String q = req.getParameter("q") == null ? "" : req.getParameter("q"); if (q.equals("png")) { final ServletOutputStream out = res.getOutputStream(); res.setContentType("image/png"); copy(getClass().getClassLoader().getResourceAsStream("data/google.png"), out); } else { final PrintWriter out = res.getWriter(); switch (q) { case "html": res.setContentType("text/html"); out.print("<html><body><ul>"); for (int i = 0; i < 50; i++) { out.println("<li>" + i + "</li>"); } out.print("</ul></body></html>"); break; case "json": res.setContentType("application/json"); final ObjectMapper mapper = new ObjectMapper(); final Map<String, Object> map = new HashMap<>(); map.put("method", req.getMethod()); map.put("url", req.getRequestURL().toString()); map.put("headers", headers(req)); map.put("query", query(req)); mapper.writeValue(out, map); break; case "error": res.sendError(500, "Dummy error message"); break; default: out.println(req.getMethod() + " " + req.getRequestURL()); headers(req, out); query(req, out); copy(req.getReader(), out); } } res.flushBuffer(); }
From source file:org.ejbca.ui.web.pub.AutoEnrollServlet.java
/** * Recievies the request.//from w w w .j a va2 s .c o m */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.trace(">doPost"); try { AuthenticationToken internalAdmin = new AlwaysAllowLocalAuthenticationToken( new UsernamePrincipal("AutoEnrollServlet: " + request.getRemoteAddr())); //Admin internalAdmin = Admin.getInternalAdmin(); GlobalConfiguration globalConfiguration = (GlobalConfiguration) globalConfigurationSession .getCachedConfiguration(GlobalConfiguration.GLOBAL_CONFIGURATION_ID); // Make sure we allow use of this Servlet if (!globalConfiguration.getAutoEnrollUse()) { log.info("Unauthorized access attempt from " + request.getRemoteAddr()); response.getOutputStream().println("Not allowed."); return; } int caid = globalConfiguration.getAutoEnrollCA(); if (caid == GlobalConfiguration.AUTOENROLL_DEFAULT_CA) { log.info("Configure a proper CA to use with enroll."); response.getOutputStream().println("Configure a proper CA to use with enroll."); return; } boolean debugRequest = "true".equalsIgnoreCase(request.getParameter("debug")); String debugInfo = ""; RequestHelper.setDefaultCharacterEncoding(request); if (debugRequest) { debugInfo += "getAttributeNames:\n"; Enumeration<?> enumeration = request.getAttributeNames(); while (enumeration.hasMoreElements()) { String temp = enumeration.nextElement().toString(); debugInfo += temp + " = " + request.getAttribute(temp) + "\n"; } debugInfo += "\ngetParameterNames:\n"; enumeration = request.getParameterNames(); while (enumeration.hasMoreElements()) { String temp = enumeration.nextElement().toString(); debugInfo += temp + " = " + request.getParameter(temp) + "\n"; } debugInfo += "\ngetHeaderNames:\n"; enumeration = request.getHeaderNames(); while (enumeration.hasMoreElements()) { String temp = enumeration.nextElement().toString(); debugInfo += temp + " = " + request.getHeader(temp) + "\n"; } debugInfo += "Remote address: " + request.getRemoteAddr() + "\n"; log.info(debugInfo); } byte[] result = null; String requestData = MSCertTools.extractRequestFromRawData(request.getParameter("request")); if (requestData == null) { response.getOutputStream().println("No request supplied.."); return; } log.info("Got request: " + requestData); // The next line expects apache to forward the kerberos-authenticated user as X-Remote-User" String remoteUser = request.getHeader("X-Remote-User"); String usernameShort = StringTools.stripUsername(remoteUser.substring(0, remoteUser.indexOf("@"))) .replaceAll("/", ""); if (remoteUser == null || "".equals(remoteUser) || "(null)".equals(remoteUser)) { response.getOutputStream().println("X-Remote-User was not supplied.."); return; } MSPKCS10RequestMessage req = null; String certificateTemplate = null; String command = request.getParameter("command"); if (command != null && "status".equalsIgnoreCase(command)) { response.getOutputStream().println(returnStatus(internalAdmin, "Autoenrolled-" + usernameShort + "-" + request.getParameter("template"))); return; } else { // Default command "request" } req = new MSPKCS10RequestMessage(Base64.decode(requestData.getBytes())); certificateTemplate = req.getMSRequestInfoTemplateName(); int templateIndex = MSCertTools.getTemplateIndex(certificateTemplate); /* TODO: Lookup requesting entity in AD here to verify that only Machines request Machine Certificates etc.. Also check permissions like who is allowed to enroll for what if possible. */ // Create or edit a user "Autoenrolled-Username-Templatename" String username = "Autoenrolled-" + usernameShort + "-" + certificateTemplate; log.info("Got autoenroll request from " + remoteUser + " (" + username + ") for a " + certificateTemplate + "-certificate."); String fetchedSubjectDN = null; if (MSCertTools.isRequired(templateIndex, MSCertTools.GET_SUBJECTDN_FROM_AD, 0)) { fetchedSubjectDN = ActiveDirectoryTools.getUserDNFromActiveDirectory(globalConfiguration, usernameShort); } int certProfileId = MSCertTools.getOrCreateCertificateProfile(internalAdmin, templateIndex, certificateProfileSession); int endEntityProfileId; try { endEntityProfileId = MSCertTools.getOrCreateEndEndtityProfile(internalAdmin, templateIndex, certProfileId, caid, usernameShort, fetchedSubjectDN, raAdminSession, endEntityProfileSession); } catch (EndEntityProfileNotFoundException e) { String msg = "Could not retrieve required information from AD."; log.error(msg, e); response.getOutputStream().println(msg); return; } catch (IllegalArgumentException e) { String msg = "Could not retrieve required information from AD."; log.error(msg, e); response.getOutputStream().println(msg); return; } // Create user // The CA needs to use non-LDAP order and we need to have the SAN like "CN=Users, CN=Username, DC=com, DC=company".. why?? // TODO: fix this here.. or is this an general order issue? String subjectDN = fetchedSubjectDN; if (subjectDN == null) { if (MSCertTools.isRequired(templateIndex, DnComponents.COMMONNAME, 0)) { subjectDN = "CN=" + usernameShort; } } String subjectAN = ""; if (MSCertTools.isRequired(templateIndex, DnComponents.UPN, 0)) { subjectAN += (subjectAN.length() == 0 ? "" : ",") + "UPN=" + remoteUser; } if (MSCertTools.isRequired(templateIndex, DnComponents.GUID, 0)) { String reqGUID = req.getMSRequestInfoSubjectAltnames()[0]; subjectAN += (subjectAN.length() == 0 ? "" : ",") + "GUID=" + reqGUID; } if (MSCertTools.isRequired(templateIndex, DnComponents.DNSNAME, 0)) { String reqDNS = req.getMSRequestInfoSubjectAltnames()[1]; subjectAN += (subjectAN.length() == 0 ? "" : ",") + "DNSNAME=" + reqDNS; } log.info("sdn=" + subjectDN + ", san=" + subjectAN); debugInfo += "\nsdn=" + subjectDN + ", san=" + subjectAN + "\n"; EndEntityInformation userData = new EndEntityInformation(username, subjectDN, caid, subjectAN, null, EndEntityConstants.STATUS_NEW, new EndEntityType(EndEntityTypes.ENDUSER), endEntityProfileId, certProfileId, new Date(), new Date(), SecConst.TOKEN_SOFT_BROWSERGEN, 0, null); String password = PasswordGeneratorFactory .getInstance(PasswordGeneratorFactory.PASSWORDTYPE_LETTERSANDDIGITS).getNewPassword(8, 8); userData.setPassword(password); try { if (endEntityManagementSession.existsUser(username)) { endEntityManagementSession.changeUser(internalAdmin, userData, true); } else { endEntityManagementSession.addUser(internalAdmin, userData, true); } } catch (Exception e) { log.error("Could not add user " + username, e); } Certificate cert = null; debugInfo += "Request: " + requestData + "\n"; req.setUsername(username); req.setPassword(password); ResponseMessage resp; try { resp = signSession.createCertificate(internalAdmin, req, X509ResponseMessage.class, null); cert = CertTools.getCertfromByteArray(resp.getResponseMessage()); result = signSession.createPKCS7(internalAdmin, cert, true); debugInfo += "Resulting cert: " + new String(Base64.encode(result, true)) + "\n"; } catch (Exception e) { log.error("Noooo!!! ", e); response.getOutputStream().println("An error has occurred."); return; } if (debugRequest) { response.getOutputStream().println(StringEscapeUtils.escapeJavaScript(debugInfo)); } else { // Output the certificate ServletOutputStream os = response.getOutputStream(); os.print(RequestHelper.BEGIN_PKCS7_WITH_NL); os.print(new String(Base64.encode(result, true))); os.print(RequestHelper.END_PKCS7_WITH_NL); response.flushBuffer(); log.info("Sent cert to client"); } } catch (AuthorizationDeniedException e1) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, e1.getMessage()); } log.trace("<doPost"); }
From source file:org.apache.cocoon.servlet.RequestProcessor.java
/** * Process the specified <code>HttpServletRequest</code> producing output * on the specified <code>HttpServletResponse</code>. *//*from w w w. j a v a2 s. com*/ public void service(HttpServletRequest request, HttpServletResponse res) throws ServletException, IOException { // used for timing the processing StopWatch stopWatch = new StopWatch(); stopWatch.start(); // add the cocoon version header stamp if (this.servletSettings.isShowVersion()) { res.addHeader("X-Cocoon-Version", Constants.VERSION); } // We got it... Process the request final String uri = getURI(request, res); if (uri == null) { // a redirect occured, so we are finished return; } Environment env; try { // Pass uri into environment without URLDecoding, as it is already decoded. env = getEnvironment(uri, request, res); } catch (Exception e) { if (getLogger().isErrorEnabled()) { getLogger().error("Problem with Cocoon servlet", e); } if (rethrowExceptions()) { throw new ServletException(e); } RequestUtil.manageException(request, res, null, uri, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Problem in creating the Environment", null, null, e, this.servletSettings, getLogger(), this); return; } String contentType = null; try { if (process(env)) { contentType = env.getContentType(); } else { // We reach this when there is nothing in the processing chain that matches // the request. For example, no matcher matches. getLogger().fatal("The Cocoon engine failed to process the request."); if (rethrowExceptions()) { throw new ServletException("The Cocoon engine failed to process the request."); } RequestUtil.manageException(request, res, env, uri, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Request Processing Failed", "Cocoon engine failed in processing the request", "The processing engine failed to process the request. This could be due to lack of matching or bugs in the pipeline engine.", null, this.servletSettings, getLogger(), this); return; } } catch (ResourceNotFoundException e) { if (getLogger().isDebugEnabled()) { getLogger().warn(e.getMessage(), e); } else if (getLogger().isWarnEnabled()) { getLogger().warn(e.getMessage()); } if (rethrowExceptions()) { throw new ServletException(e); } RequestUtil.manageException(request, res, env, uri, HttpServletResponse.SC_NOT_FOUND, "Resource Not Found", "Resource Not Found", "The requested resource \"" + request.getRequestURI() + "\" could not be found", e, this.servletSettings, getLogger(), this); return; } catch (ConnectionResetException e) { if (getLogger().isDebugEnabled()) { getLogger().debug(e.toString(), e); } else if (getLogger().isWarnEnabled()) { getLogger().warn(e.toString()); } } catch (IOException e) { // Tomcat5 wraps SocketException into ClientAbortException which extends IOException. if (getLogger().isDebugEnabled()) { getLogger().debug(e.toString(), e); } else if (getLogger().isWarnEnabled()) { getLogger().warn(e.toString()); } } catch (Exception e) { if (getLogger().isErrorEnabled()) { getLogger().error("Internal Cocoon Problem", e); } if (rethrowExceptions()) { throw new ServletException(e); } RequestUtil.manageException(request, res, env, uri, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error", null, null, e, this.servletSettings, getLogger(), this); return; } stopWatch.stop(); String timeString = null; if (getLogger().isInfoEnabled()) { timeString = processTime(stopWatch.getTime()); getLogger().info("'" + uri + "' " + timeString); } if (contentType != null && contentType.equals("text/html")) { String showTime = request.getParameter(Constants.SHOWTIME_PARAM); boolean show = this.servletSettings.isShowTime(); if (showTime != null) { show = !showTime.equalsIgnoreCase("no"); } if (show) { if (timeString == null) { timeString = processTime(stopWatch.getTime()); } boolean hide = this.servletSettings.isHideShowTime(); if (showTime != null) { hide = showTime.equalsIgnoreCase("hide"); } ServletOutputStream out = res.getOutputStream(); out.print((hide) ? "<!-- " : "<p>"); out.print(timeString); out.println((hide) ? " -->" : "</p>"); } } /* * Servlet Specification 2.2, 6.5 Closure of Response Object: * * A number of events can indicate that the servlet has provided all of the * content to satisfy the request and that the response object can be * considered to be closed. The events are: * o The termination of the service method of the servlet. * o When the amount of content specified in the setContentLength method * of the response has been written to the response. * o The sendError method is called. * o The sendRedirect method is called. * When a response is closed, all content in the response buffer, if any remains, * must be immediately flushed to the client. * * Due to the above, out.flush() and out.close() are not necessary, and sometimes * (if sendError or sendRedirect were used) request may be already closed. */ }
From source file:edu.cornell.mannlib.vitro.webapp.controller.grefine.JSONReconcileServlet.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 www . java 2 s . c om if (vreq.getParameter("query") != null || vreq.getParameter("queries") != null) { JSONObject qJson = getResult(vreq, req, resp); log.debug("result: " + qJson.toString()); String responseStr = (vreq.getParameter("callback") == null) ? qJson.toString() : vreq.getParameter("callback") + "(" + qJson.toString() + ")"; // System.out.println("JSONReconcileServlet result: " + responseStr); ServletOutputStream out = resp.getOutputStream(); out.print(responseStr); } else { // metadata String defaultNamespace = null; String defaultTypeList = null; String serverName = null; int serverPort = req.getServerPort(); if (vreq.getWebappDaoFactory() != null) { defaultNamespace = vreq.getWebappDaoFactory().getDefaultNamespace(); } defaultTypeList = ConfigurationProperties.getBean(req) .getProperty("Vitro.reconcile.defaultTypeList"); serverName = req.getServerName(); JSONObject metaJson = getMetadata(req, resp, defaultNamespace, defaultTypeList, serverName, serverPort); String callbackStr = (vreq.getParameter("callback") == null) ? "" : vreq.getParameter("callback"); ServletOutputStream out = resp.getOutputStream(); out.print(callbackStr + "(" + metaJson.toString() + ")"); } } catch (Exception ex) { log.warn(ex, ex); } }
From source file:org.sakaiproject.kernel.rest.me.RestMeProvider.java
/** * @param string/*from w w w. java2 s . co m*/ * @param path * @throws IOException * @throws RepositoryException */ private void sendFile(String key, String path, ServletOutputStream outputStream) throws IOException, RepositoryException { InputStream in = null; try { in = jcrNodeFactoryService.getInputStream(path); if (in == null) { outputStream.print(", \""); outputStream.print(key); outputStream.print("\" : {}"); } else { outputStream.print(", \""); outputStream.print(key); outputStream.print("\" :"); IOUtils.stream(in, outputStream); } } catch (Exception ex) { outputStream.print(", \""); outputStream.print(key); outputStream.print("\" : {}"); } finally { try { in.close(); } catch (Exception ex) { } } }
From source file:org.sigmah.server.auth.SigmahAuthDictionaryServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { /*/*w w w . j a v a2s. co m*/ * Initialize quartz scheduler here, because it needs link{EntityManager} * which can only accessed in request scope. */ injector.getInstance(GlobalExportJobActivator.class); if (req.getParameter("remove") != null) { final Cookie cookie = new Cookie("authToken", ""); cookie.setPath("/"); cookie.setMaxAge(0); resp.addCookie(cookie); } else { final HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put(SigmahAuthProvider.SHOW_MENUS, String.valueOf(false)); final String authToken = getAuthToken(req.getCookies()); if (authToken != null) { final AuthenticationDAO authDAO = injector.getInstance(AuthenticationDAO.class); final Authentication auth = authDAO.findById(authToken); final User user = auth.getUser(); if (user.getOrganization() == null) { log.error(String.format( "User with id=%d, email=%s has no organization set, cannot log into the Sigmah interface.", user.getId(), user.getEmail())); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Your account is not configured for use with Sigmah"); return; } parameters.put(SigmahAuthProvider.USER_ID, Integer.toString(user.getId())); parameters.put(SigmahAuthProvider.USER_TOKEN, '"' + authToken + '"'); parameters.put(SigmahAuthProvider.USER_EMAIL, '"' + user.getEmail() + '"'); parameters.put(SigmahAuthProvider.USER_NAME, '"' + user.getName() + '"'); parameters.put(SigmahAuthProvider.USER_FIRST_NAME, '"' + user.getFirstName() + '"'); parameters.put(SigmahAuthProvider.USER_ORG_ID, Integer.toString(user.getOrganization().getId())); parameters.put(SigmahAuthProvider.USER_ORG_UNIT_ID, Integer.toString(user.getOrgUnitWithProfiles().getOrgUnit().getId())); // Custom serialization of the profile. final ProfileDTO aggregatedProfile = aggregateProfiles(user, null, injector); final String aggregatedProfileAsString = ProfileUtils.writeProfile(aggregatedProfile); parameters.put(SigmahAuthProvider.USER_AG_PROFILE, '"' + aggregatedProfileAsString + '"'); if (log.isDebugEnabled()) { log.debug("[doGet] Writes aggregated profile: " + aggregatedProfile); log.debug("[doGet] String representation of the profile: " + aggregatedProfileAsString); } } final Properties properties = injector.getInstance(Properties.class); parameters.put(SigmahAuthProvider.VERSION_NUMBER, '"' + properties.getProperty("version.number") + '"'); final Charset utf8 = Charset.forName("UTF-8"); resp.setCharacterEncoding("UTF-8"); final ServletOutputStream output = resp.getOutputStream(); output.println("var " + SigmahAuthProvider.DICTIONARY_NAME + " = {"); boolean first = true; for (Map.Entry<String, String> entry : parameters.entrySet()) { if (first) first = false; else output.println(","); output.print(entry.getKey() + ": "); output.write(entry.getValue().getBytes(utf8)); } output.println("};"); } }
From source file:eu.earthobservatory.org.StrabonEndpoint.DescribeBean.java
/** * Processes the request made by a client of the endpoint that uses it as a service. * /* w w w . j a va 2 s. c o m*/ * @param request * @param response * @throws IOException */ private void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException { ServletOutputStream out = response.getOutputStream(); // get the RDF format (we check only the Accept header) RDFFormat format = RDFFormat.forMIMEType(request.getHeader("accept")); // get the query String query = request.getParameter("query"); // check for required parameters if (format == null || query == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); out.print(ResponseMessages.getXMLHeader()); out.print(ResponseMessages.getXMLException(PARAM_ERROR)); out.print(ResponseMessages.getXMLFooter()); } else { // decode the query query = URLDecoder.decode(request.getParameter("query"), "UTF-8"); response.setContentType(format.getDefaultMIMEType()); response.setHeader("Content-Disposition", "attachment; filename=describe." + format.getDefaultFileExtension() + "; " + format.getCharset()); try { strabonWrapper.describe(query, format.getName(), out); response.setStatus(HttpServletResponse.SC_OK); } catch (Exception e) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); out.print(ResponseMessages.getXMLHeader()); out.print(ResponseMessages.getXMLException(e.getMessage())); out.print(ResponseMessages.getXMLFooter()); } } out.flush(); }
From source file:org.jspresso.framework.util.resources.server.ResourceProviderServlet.java
/** * {@inheritDoc}/*from w w w . ja v a2 s . com*/ */ @SuppressWarnings("unchecked") @Override public void doPost(HttpServletRequest request, HttpServletResponse response) { try { HttpRequestHolder.setServletRequest(request); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); response.setContentType("text/xml"); ServletOutputStream out = response.getOutputStream(); for (FileItem item : items) { if (!item.isFormField()) { out.print("<resource"); IResourceBase uploadResource = new UploadResourceAdapter("application/octet-stream", item); String resourceId = ResourceManager.getInstance().register(uploadResource); out.print(" id=\"" + resourceId); // Sometimes prevents the browser to parse back the result // out.print("\" name=\"" + HtmlHelper.escapeForHTML(item.getName())); out.println("\" />"); } } out.flush(); out.close(); } catch (Exception ex) { LOG.error("An unexpected error occurred while uploading the content.", ex); } finally { HttpRequestHolder.setServletRequest(null); } }
From source file:org.ralasafe.servlet.QueryDesignAction.java
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String oper = req.getParameter("oper"); String tableAlias = req.getParameter("tableAlias"); String columnName = req.getParameter("columnName"); QueryDesignHandler handler = getHandler(req); req.setAttribute("handler", handler); if (log.isDebugEnabled()) { log.debug("oper=" + oper + ", query=" + handler.getQuery().getName() + ", tableAlias=" + tableAlias + ", columnName=" + columnName); }//from w w w . ja v a 2s . com if ("checkTableColumns".equals(oper)) { handler.addTableColumns(tableAlias); return; } else if ("unCheckTableColumns".equals(oper)) { handler.deleteTableColumns(tableAlias); return; } else if ("deleteTable".equals(oper)) { handler.deleteTable(tableAlias); return; } else if ("addTable".equals(oper)) { String schema = req.getParameter("schema"); String tableName = req.getParameter("tableName"); String alias = handler.addTable(schema.trim(), tableName.trim()); Gson gson = new Gson(); String json = gson.toJson(alias); resp.setContentType("application/json"); resp.getWriter().print(json); return; } else if ("setMappingClass".equals(oper)) { String mappingClass = req.getParameter("mappingClass"); handler.setMappingClass(mappingClass); return; } else if ("deleteColumn".equals(oper)) { handler.deleteColumn(tableAlias, columnName); return; } else if ("addColumn".equals(oper)) { handler.addColumn(tableAlias, columnName); return; } else if ("updateTableColumn".equals(oper)) { String function = req.getParameter("function"); String property = req.getParameter("property"); boolean readOnly = WebUtil.getBooleanParameter(req, "readOnly", false); int index = property.indexOf("<"); String javaProp = property.substring(0, index - 1).trim(); String javaType = property.substring(index + 1, property.length() - 1).trim(); handler.changeColumnMapping(tableAlias, columnName, function, javaProp, javaType, readOnly); return; } else if ("moveGroupColumn".equals(oper)) { String direct = req.getParameter("direct"); handler.moveGroupColumn(direct, tableAlias, columnName); return; } else if ("deleteGroupColumn".equals(oper)) { handler.deleteGroupColumn(tableAlias, columnName); return; } else if ("editGroupColumn".equals(oper)) { String aliasColumn = req.getParameter("aliasColumn"); int firstIndex = aliasColumn.indexOf("["); int lastIndex = aliasColumn.indexOf("]"); tableAlias = aliasColumn.substring(firstIndex + 1, lastIndex); columnName = aliasColumn.substring(lastIndex + 2); int index = WebUtil.getIntParameter(req, "index", 0); handler.editGroupColumn(index, tableAlias, columnName); return; } else if ("addGroupColumn".equals(oper)) { String aliasColumn = req.getParameter("aliasColumn"); int firstIndex = aliasColumn.indexOf("["); int lastIndex = aliasColumn.indexOf("]"); tableAlias = aliasColumn.substring(firstIndex + 1, lastIndex); columnName = aliasColumn.substring(lastIndex + 2); handler.addGroupColumn(tableAlias, columnName); return; } else if ("moveOrderColumn".equals(oper)) { String direct = req.getParameter("direct"); handler.moveOrderColumn(direct, tableAlias, columnName); return; } else if ("deleteOrderColumn".equals(oper)) { handler.deleteOrderColumn(tableAlias, columnName); return; } else if ("editOrderColumn".equals(oper)) { String aliasColumn = req.getParameter("aliasColumn"); String orderType = req.getParameter("orderType"); int firstIndex = aliasColumn.indexOf("["); int lastIndex = aliasColumn.indexOf("]"); tableAlias = aliasColumn.substring(firstIndex + 1, lastIndex); columnName = aliasColumn.substring(lastIndex + 2); int index = WebUtil.getIntParameter(req, "index", 0); handler.editOrderColumn(index, tableAlias, columnName, orderType); return; } else if ("addOrderColumn".equals(oper)) { String aliasColumn = req.getParameter("aliasColumn"); String orderType = req.getParameter("orderType"); int firstIndex = aliasColumn.indexOf("["); int lastIndex = aliasColumn.indexOf("]"); tableAlias = aliasColumn.substring(firstIndex + 1, lastIndex); columnName = aliasColumn.substring(lastIndex + 2); handler.addOrderColumn(tableAlias, columnName, orderType); return; } else if ("loadWhereExprGroup".equals(oper)) { String xml = handler.getWhere(); resp.setContentType("application/json;charset=UTF-8"); ServletOutputStream out = resp.getOutputStream(); out.print(xml); return; } else if ("addWhereChildExprGroup".equals(oper)) { String nodeId = req.getParameter("nodeId"); String type = req.getParameter("type"); handler.addWhereChildExprGroup(nodeId, type); return; } else if ("editWhereExprGroup".equals(oper)) { String nodeId = req.getParameter("nodeId"); String type = req.getParameter("type"); handler.editWhereExprGroup(nodeId, type); return; } else if ("deleteWhereExpr".equals(oper)) { String nodeId = req.getParameter("nodeId"); handler.deleteWhereExpr(nodeId); return; } else if ("addWhereExpr".equals(oper)) { String pId = req.getParameter("pId"); String exprType = req.getParameter("exprType"); if ("binary".equals(exprType)) { BinaryExpression expr = getBinaryExpression(req); handler.addBinaryExpression(expr, pId); } else if ("null".equals(exprType)) { Column column = getWhereExprInColumn(req); String operator = req.getParameter("operator"); handler.addNullExpression(column, operator, pId); } return; } else if ("editWhereExpr".equals(oper)) { String nodeId = req.getParameter("nodeId"); String exprType = req.getParameter("exprType"); if ("binary".equals(exprType)) { BinaryExpression expr = getBinaryExpression(req); handler.editBinaryExpression(expr, nodeId); } else if ("null".equals(exprType)) { Column column = getWhereExprInColumn(req); String operator = req.getParameter("operator"); handler.editNullExpression(column, operator, nodeId); } return; } else if ("save".equals(oper)) { // remove handler from session req.getSession().removeAttribute(getHandlerAttributeKey(req)); int id = WebUtil.getIntParameter(req, "id", -23); QueryManager queryManager = WebUtil.getQueryManager(req); try { handler.save(id, queryManager); } catch (EntityExistException e) { log.error("", e); throw new ServletException(e); } return; } }