List of usage examples for javax.servlet.http HttpServletRequest getCharacterEncoding
public String getCharacterEncoding();
From source file:net.triptech.metahive.web.RecordController.java
/** * List the records./*from w ww .j av a 2 s. c o m*/ * * @param id the id * @param vid the vid * @param orderId the order id * @param recordId the record id * @param page the page * @param size the size * @param uiModel the ui model * @param request the http servlet request * @return the string */ @RequestMapping(method = RequestMethod.GET) public String list(@RequestParam(value = "id", required = false) String id, @RequestParam(value = "vid", required = false) Integer vid, @RequestParam(value = "order", required = false) Long orderId, @RequestParam(value = "recordId", required = false) String recordId, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel, HttpServletRequest request) { Person user = loadUser(request); List<Definition> definitions = new ArrayList<Definition>(); if (user == null) { // Load the default definition list MetahivePreferences preferences = MetahivePreferences.load(); definitions = preferences.getDefaultDefinitions(); } else { if (user.getSearchDefinitions().size() == 0) { // Set the default definitions for the user MetahivePreferences preferences = MetahivePreferences.load(); for (Definition def : preferences.getDefaultDefinitions()) { definitions.add(def); } user.setSearchDefinitions(definitions); user.persist(); } else { definitions = user.getSearchDefinitions(); } } UserRole userRole = UserRole.ANONYMOUS; if (user != null && user.getUserRole() != null) { userRole = user.getUserRole(); } RecordFilter filter = new RecordFilter(); filter.setEncoding(request.getCharacterEncoding()); Map<String, RecordFilter> searches = getSearches(request); if (StringUtils.isNotBlank(id) && searches.containsKey(id)) { filter = searches.get(id); } if (orderId != null) { filter.setOrderId(orderId); } if (filter.getFilterVectors() == null || filter.getFilterVectors().size() == 0) { List<FilterVector> defaultVector = new ArrayList<FilterVector>(); defaultVector.add(new FilterVector()); filter.setFilterVectors(defaultVector); } if (vid != null && vid > 1 && filter.getFilterVectors().size() >= vid) { List<FilterVector> vectors = filter.getFilterVectors(); vectors.remove(vid - 1); filter.setFilterVectors(vectors); } String defaultRecordFilter = getMessage("metahive_records_filter_id"); if (StringUtils.isNotBlank(recordId) && !StringUtils.equalsIgnoreCase(recordId, defaultRecordFilter)) { filter.setRecordId(recordId); } else { filter.setRecordId(""); } searches.put(filter.getId(), filter); request.getSession().setAttribute("searches", searches); int sizeNo = size == null ? DEFAULT_PAGE_SIZE : size.intValue(); int pageNo = page == null ? 0 : page.intValue() - 1; uiModel.addAttribute("definitions", definitions); uiModel.addAttribute("records", Record.findRecordEntries(filter, definitions, userRole, this.getContext(), pageNo * sizeNo, sizeNo)); float nrOfPages = (float) Record.countRecords(filter) / sizeNo; uiModel.addAttribute("resultCounts", resultCounts()); uiModel.addAttribute("page", pageNo + 1); uiModel.addAttribute("size", sizeNo); uiModel.addAttribute("filter", filter); uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages)); return "records/list"; }
From source file:org.j2eeframework.commons.struts2.multipart.JakartaMultiPartRequest.java
/** * Creates a new request wrapper to handle multi-part data using methods adapted from Jason Pell's * multipart classes (see class description). * * @param saveDir the directory to save off the file * @param servletRequest the request containing the multipart * @throws java.io.IOException is thrown if encoding fails. *//*w ww . j av a2 s . c o m*/ public void parse(HttpServletRequest servletRequest, String saveDir) throws IOException { DiskFileItemFactory fac = new DiskFileItemFactory(); // Make sure that the data is written to file fac.setSizeThreshold(0); if (saveDir != null) { fac.setRepository(new File(saveDir)); } // Parse the request try { ServletFileUpload upload = new ServletFileUpload(fac); upload.setSizeMax(maxSize); @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(createRequestContext(servletRequest)); for (Object item1 : items) { FileItem item = (FileItem) item1; if (LOG.isDebugEnabled()) LOG.debug("Found item " + item.getFieldName()); if (item.isFormField()) { LOG.debug("Item is a normal form field"); List<String> values; if (params.get(item.getFieldName()) != null) { values = params.get(item.getFieldName()); } else { values = new ArrayList<String>(); } // note: see http://jira.opensymphony.com/browse/WW-633 // basically, in some cases the charset may be null, so // we're just going to try to "other" method (no idea if this // will work) String charset = servletRequest.getCharacterEncoding(); if (charset != null) { values.add(item.getString(charset)); } else { values.add(item.getString()); } params.put(item.getFieldName(), values); } else { LOG.debug("Item is a file upload"); // Skip file uploads that don't have a file name - meaning that no file was selected. if (item.getName() == null || item.getName().trim().length() < 1) { LOG.debug("No file has been uploaded for the field: " + item.getFieldName()); continue; } List<FileItem> values; if (files.get(item.getFieldName()) != null) { values = files.get(item.getFieldName()); } else { values = new ArrayList<FileItem>(); } values.add(item); files.put(item.getFieldName(), values); } } } catch (SizeLimitExceededException e) { ArrayList<String> values = new ArrayList<String>(); values.add("SizeLimitExceededException"); params.put("exception", values);//? } catch (FileUploadException e) { LOG.error("Unable to parse request", e); ArrayList<String> values = new ArrayList<String>(); values.add("FileUploadException"); params.put("exception", values); errors.add(e.getMessage()); } }
From source file:axiom.servlet.AbstractServletClient.java
/** * Handle a request.//from w w w . j av a 2s .c om * * @param request ... * @param response ... * * @throws ServletException ... * @throws IOException ... */ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final String httpMethod = request.getMethod(); if (!"POST".equalsIgnoreCase(httpMethod) && !"GET".equalsIgnoreCase(httpMethod)) { sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "HTTP Method " + httpMethod + " not supported."); return; } RequestTrans reqtrans = new RequestTrans(request, response, getPathInfo(request)); try { // get the character encoding String encoding = request.getCharacterEncoding(); if (encoding == null) { // no encoding from request, use the application's charset encoding = getApplication().getCharset(); } // read and set http parameters parseParameters(request, reqtrans, encoding); List uploads = null; ServletRequestContext reqcx = new ServletRequestContext(request); if (ServletFileUpload.isMultipartContent(reqcx)) { // get session for upload progress monitoring UploadStatus uploadStatus = getApplication().getUploadStatus(reqtrans); try { uploads = parseUploads(reqcx, reqtrans, uploadStatus, encoding); } catch (Exception upx) { System.err.println("Error in file upload: " + upx); if (uploadSoftfail) { String msg = upx.getMessage(); if (msg == null || msg.length() == 0) { msg = upx.toString(); } reqtrans.set("axiom_upload_error", msg); } else if (upx instanceof FileUploadBase.SizeLimitExceededException) { sendError(response, HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, "File upload size exceeds limit of " + uploadLimit + "kB"); return; } else { sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error in file upload: " + upx); return; } } } parseCookies(request, reqtrans, encoding); // do standard HTTP variables String host = request.getHeader("Host"); if (host != null) { host = host.toLowerCase(); reqtrans.set("http_host", host); } String referer = request.getHeader("Referer"); if (referer != null) { reqtrans.set("http_referer", referer); } try { long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifModifiedSince > -1) { reqtrans.setIfModifiedSince(ifModifiedSince); } } catch (IllegalArgumentException ignore) { } String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null) { reqtrans.setETags(ifNoneMatch); } String remotehost = request.getRemoteAddr(); if (remotehost != null) { reqtrans.set("http_remotehost", remotehost); } // get the cookie domain to use for this response, if any. String resCookieDomain = cookieDomain; if (resCookieDomain != null) { // check if cookieDomain is valid for this response. // (note: cookieDomain is guaranteed to be lower case) // check for x-forwarded-for header, fix for bug 443 String proxiedHost = request.getHeader("x-forwarded-host"); if (proxiedHost != null) { if (proxiedHost.toLowerCase().indexOf(cookieDomain) == -1) { resCookieDomain = null; } } else if ((host != null) && host.toLowerCase().indexOf(cookieDomain) == -1) { resCookieDomain = null; } } // check if session cookie is present and valid, creating it if not. checkSessionCookie(request, response, reqtrans, resCookieDomain); String browser = request.getHeader("User-Agent"); if (browser != null) { reqtrans.set("http_browser", browser); } String language = request.getHeader("Accept-Language"); if (language != null) { reqtrans.set("http_language", language); } String authorization = request.getHeader("authorization"); if (authorization != null) { reqtrans.set("authorization", authorization); } ResponseTrans restrans = getApplication().execute(reqtrans); // if the response was already written and committed by the application // we can skip this part and return if (response.isCommitted()) { return; } // set cookies if (restrans.countCookies() > 0) { CookieTrans[] resCookies = restrans.getCookies(); for (int i = 0; i < resCookies.length; i++) try { Cookie c = resCookies[i].getCookie("/", resCookieDomain); response.addCookie(c); } catch (Exception ignore) { ignore.printStackTrace(); } } // write response writeResponse(request, response, reqtrans, restrans); } catch (Exception x) { try { if (debug) { sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Server error: " + x); x.printStackTrace(); } else { sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "The server encountered an error while processing your request. " + "Please check back later."); } log("Exception in execute: " + x); } catch (IOException io_e) { log("Exception in sendError: " + io_e); } } }
From source file:org.gatherdata.camel.http.internal.ServletProxyProducerImpl.java
private Map<String, Object> extractHeaders(HttpServletRequest request) { Map<String, Object> headers = new HashMap<String, Object>(); String contentType = ""; //apply the headerFilterStrategy Enumeration names = request.getHeaderNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); Object value = request.getHeader(name); // mapping the content-type if (name.toLowerCase().equals("content-type")) { name = Exchange.CONTENT_TYPE; contentType = (String) value; }/*from w w w . j a v a2 s . c o m*/ headers.put(name, value); } //we populate the http request parameters for GET and POST String method = request.getMethod(); if (method.equalsIgnoreCase("GET") || (method.equalsIgnoreCase("POST") && contentType.equalsIgnoreCase("application/x-www-form-urlencoded"))) { names = request.getParameterNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); Object value = request.getParameter(name); headers.put(name, value); } } // store the method and query and other info in headers headers.put(Exchange.HTTP_METHOD, request.getMethod()); headers.put(Exchange.HTTP_QUERY, request.getQueryString()); //headers.put(Exchange.HTTP_URL, request.getRequestURL()); headers.put(Exchange.HTTP_URI, request.getRequestURI()); headers.put(Exchange.HTTP_PATH, request.getPathInfo()); headers.put(Exchange.CONTENT_TYPE, request.getContentType()); headers.put(Exchange.HTTP_CHARACTER_ENCODING, request.getCharacterEncoding()); return headers; }
From source file:com.globalsight.everest.util.ajax.AjaxService.java
public void service(HttpServletRequest request, HttpServletResponse response) { this.request = request; this.response = response; boolean check = setCompanyId(); HttpSession session = request.getSession(false); m_userId = (String) session.getAttribute(WebAppConstants.USER_NAME); response.setCharacterEncoding(request.getCharacterEncoding()); String method = request.getParameter("action"); try {//from ww w.j a va 2 s.c om writer = response.getWriter(); if (!check) { writer.write("failed"); } else { AjaxService.class.getMethod(method, null).invoke(AjaxService.this); } } catch (Exception e) { CATEGORY.error("Can not invoke the method:" + method); } }
From source file:net.openkoncept.vroom.VroomController.java
private void processRequestJSFile(HttpServletRequest request, HttpServletResponse response, String contextPath, String servletPath, String sessionId, String requestPath) throws IOException { String src = request.getParameter(FILE_SRC); if (src != null) { String realPath = getServletContext().getRealPath(src); BufferedReader reader = new BufferedReader(new FileReader(realPath)); StringBuffer sbOutput = new StringBuffer(); String line = reader.readLine(); while (line != null) { sbOutput.append(line);// w ww. ja va 2s . c om sbOutput.append("\n"); line = reader.readLine(); } reader.close(); VroomHtmlProcessor.replace(sbOutput, $CONTEXT_PATH$, contextPath); VroomHtmlProcessor.replace(sbOutput, $SERVLET_PATH$, servletPath); VroomHtmlProcessor.replace(sbOutput, $SESSION_ID$, sessionId); VroomHtmlProcessor.replace(sbOutput, $REQUEST_PATH$, requestPath); String encoding = request.getHeader("response-encoding"); if (encoding == null || encoding.trim().length() == 0) { encoding = request.getCharacterEncoding(); } response.setContentType(JS_MIME_TYPE); if (encoding != null) { VroomUtilities.safeCall(response, "setCharacterEncoding", new Class[] { String.class }, new Object[] { encoding }); // response.setCharacterEncoding(encoding); } PrintWriter out = null; try { out = response.getWriter(); out.write(sbOutput.toString()); } finally { if (out != null) { out.close(); } } } }
From source file:com.github.vatbub.vatbubgitreports.Main.java
public void doPost(HttpServletRequest request, HttpServletResponse response) { response.setContentType("application/json"); PrintWriter writer;//from w w w . jav a 2s . co m Gson gson = new GsonBuilder().setPrettyPrinting().create(); StringBuilder requestBody = new StringBuilder(); String line; try { writer = response.getWriter(); } catch (IOException e) { Internet.sendErrorMail("getWriter", "Unable not read request", e, gMailUsername, gMailPassword); e.printStackTrace(); response.setStatus(500); return; } try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { requestBody.append(line); } } catch (IOException e) { Error error = new Error(e.getClass().getName() + " occurred while reading the request", ExceptionUtils.getFullStackTrace(e)); writer.write(gson.toJson(error)); response.setStatus(500); Internet.sendErrorMail("ReadRequestBody", requestBody.toString(), e, gMailUsername, gMailPassword); return; } // parse the request if (!request.getContentType().equals("application/json")) { // bad content type Error error = new Error("content type must be application/json"); writer.write(gson.toJson(error)); } GitHubIssue gitHubIssue; try { System.out.println("Received request:"); System.out.println(requestBody.toString()); System.out.println("Request encoding is: " + request.getCharacterEncoding()); gitHubIssue = gson.fromJson(requestBody.toString(), GitHubIssue.class); } catch (Exception e) { Internet.sendErrorMail("ParseJSON", requestBody.toString(), e, gMailUsername, gMailPassword); Error error = new Error(e.getClass().getName() + " occurred while parsing the request", ExceptionUtils.getFullStackTrace(e)); writer.write(gson.toJson(error)); response.setStatus(500); return; } // Authenticate on GitHub GitHubClient client = new GitHubClient(); client.setOAuth2Token(System.getenv("GITHUB_ACCESS_TOKEN")); // Convert the issue object Issue issue = new Issue(); issue.setTitle(gitHubIssue.getTitle()); String body = ""; boolean metadataGiven = false; if (!gitHubIssue.getReporterName().equals("")) { body = "Reporter name: " + gitHubIssue.getReporterName() + "\n"; metadataGiven = true; } if (!gitHubIssue.getReporterEmail().equals("")) { body = body + "Reporter email: " + gitHubIssue.getReporterEmail() + "\n"; metadataGiven = true; } if (gitHubIssue.getLogLocation() != null) { body = body + "Log location: " + gitHubIssue.getLogLocation() + "\n"; metadataGiven = true; } if (gitHubIssue.getScreenshotLocation() != null) { body = body + "Screenshot location: " + gitHubIssue.getScreenshotLocation() + "\n"; metadataGiven = true; } if (gitHubIssue.getThrowable() != null) { body = body + "Exception stacktrace:\n" + ExceptionUtils.getFullStackTrace(gitHubIssue.getThrowable()) + "\n"; metadataGiven = true; } if (metadataGiven) { body = body + "----------------------------------" + "\n\nDESCRIPTION:\n"; } body = body + gitHubIssue.getBody(); issue.setBody(body); // send the issue to GitHub try { new IssueService(client).createIssue(gitHubIssue.getToRepo_Owner(), gitHubIssue.getToRepo_RepoName(), issue); } catch (IOException e) { e.printStackTrace(); Error error = new Error(e.getClass().getName() + " occurred while parsing the request", ExceptionUtils.getFullStackTrace(e)); writer.write(gson.toJson(error)); response.setStatus(500); Internet.sendErrorMail("ForwardToGitHub", requestBody.toString(), e, gMailUsername, gMailPassword); return; } writer.write(gson.toJson(issue)); }
From source file:org.geoserver.ows.Dispatcher.java
protected void preprocessRequest(HttpServletRequest request) throws Exception { //set the charset Charset charSet = null;//from w w w . ja v a2 s.co m //TODO: make this server settable charSet = UTF8; if (request.getCharacterEncoding() != null) try { charSet = Charset.forName(request.getCharacterEncoding()); } catch (Exception e) { // ok, we tried... } request.setCharacterEncoding(charSet.name()); }
From source file:com.qlkh.client.server.proxy.ProxyServlet.java
/** * Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same content POST * data (JSON, XML, etc.) as was sent in the given {@link javax.servlet.http.HttpServletRequest} * * @param postMethodProxyRequest The {@link org.apache.commons.httpclient.methods.PostMethod} that we are * configuring to send a standard POST request * @param httpServletRequest The {@link javax.servlet.http.HttpServletRequest} that contains * the POST data to be sent via the {@link org.apache.commons.httpclient.methods.PostMethod} *///from ww w . jav a 2 s .com private void handleContentPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest) throws IOException, ServletException { StringBuilder content = new StringBuilder(); BufferedReader reader = httpServletRequest.getReader(); for (;;) { String line = reader.readLine(); if (line == null) break; content.append(line); } String contentType = httpServletRequest.getContentType(); String postContent = content.toString(); if (contentType.startsWith("text/x-gwt-rpc")) { String clientHost = httpServletRequest.getLocalName(); if (clientHost.equals("127.0.0.1")) { clientHost = "localhost"; } int clientPort = httpServletRequest.getLocalPort(); String clientUrl = clientHost + ((clientPort != 80) ? ":" + clientPort : ""); String serverUrl = stringProxyHost + ((intProxyPort != 80) ? ":" + intProxyPort : "") + httpServletRequest.getServletPath(); //debug("Replacing client (" + clientUrl + ") with server (" + serverUrl + ")"); postContent = postContent.replace(clientUrl, serverUrl); } String encoding = httpServletRequest.getCharacterEncoding(); debug("POST Content Type: " + contentType + " Encoding: " + encoding, "Content: " + postContent); StringRequestEntity entity; try { entity = new StringRequestEntity(postContent, contentType, encoding); } catch (UnsupportedEncodingException e) { throw new ServletException(e); } // Set the proxy request POST data postMethodProxyRequest.setRequestEntity(entity); }