List of usage examples for javax.servlet.http HttpServletRequest getLocalAddr
public String getLocalAddr();
From source file:com.jd.survey.web.reports.ReportController.java
/** * Exports survey data to a comma delimited values file * @param surveyDefinitionId//from w w w . j a va 2s. c o m * @param principal * @param response */ @Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" }) @RequestMapping(value = "/{id}", params = "csv", produces = "text/html") public void surveyCSVExport(@PathVariable("id") Long surveyDefinitionId, Principal principal, HttpServletRequest httpServletRequest, HttpServletResponse response) { try { User user = userService.user_findByLogin(principal.getName()); if (!securityService.userIsAuthorizedToManageSurvey(surveyDefinitionId, user)) { log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo() + " attempted by user login:" + principal.getName() + "from IP:" + httpServletRequest.getLocalAddr()); response.sendRedirect("../accessDenied"); //throw new AccessDeniedException("Unauthorized access attempt"); } String columnName; SurveyDefinition surveyDefinition = surveySettingsService.surveyDefinition_findById(surveyDefinitionId); List<Map<String, Object>> surveys = reportDAO.getSurveyData(surveyDefinitionId); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append( "\"id\",\"Survey Name\",\"User Login\",\"Submission Date\",\"Creation Date\",\"Last Update Date\","); for (SurveyDefinitionPage page : surveyDefinition.getPages()) { for (Question question : page.getQuestions()) { if (question.getType().getIsMatrix()) { for (QuestionRowLabel questionRowLabel : question.getRowLabels()) { for (QuestionColumnLabel questionColumnLabel : question.getColumnLabels()) { stringBuilder.append("\" p" + page.getOrder() + "q" + question.getOrder() + "r" + questionRowLabel.getOrder() + "c" + questionColumnLabel.getOrder() + "\","); } } continue; } if (question.getType().getIsMultipleValue()) { for (QuestionOption questionOption : question.getOptions()) { stringBuilder.append("\" p" + page.getOrder() + "q" + question.getOrder() + "o" + questionOption.getOrder() + "\","); } continue; } stringBuilder.append("\"p" + page.getOrder() + "q" + question.getOrder() + "\","); } } stringBuilder.deleteCharAt(stringBuilder.length() - 1); //delete the last comma stringBuilder.append("\n"); for (Map<String, Object> record : surveys) { stringBuilder.append(record.get("survey_id") == null ? "" : "\"" + record.get("survey_id").toString().replace("\"", "\"\"") + "\","); stringBuilder.append(record.get("type_name") == null ? "" : "\"" + record.get("type_name").toString().replace("\"", "\"\"") + "\","); stringBuilder.append(record.get("login") == null ? "" : "\"" + record.get("login").toString().replace("\"", "\"\"") + "\","); stringBuilder.append(record.get("submission_date") == null ? "" : "\"" + record.get("creation_date").toString().replace("\"", "\"\"") + "\","); stringBuilder.append(record.get("creation_date") == null ? "" : "\"" + record.get("last_update_date").toString().replace("\"", "\"\"") + "\","); stringBuilder.append(record.get("last_update_date") == null ? "" : "\"" + record.get("last_update_date").toString().replace("\"", "\"\"") + "\","); for (SurveyDefinitionPage page : surveyDefinition.getPages()) { for (Question question : page.getQuestions()) { if (question.getType().getIsMatrix()) { for (QuestionRowLabel questionRowLabel : question.getRowLabels()) { for (QuestionColumnLabel questionColumnLabel : question.getColumnLabels()) { columnName = "p" + page.getOrder() + "q" + question.getOrder() + "r" + questionRowLabel.getOrder() + "c" + questionColumnLabel.getOrder(); stringBuilder.append(record.get(columnName) == null ? "," : "\"" + record.get(columnName).toString().replace("\"", "\"\"") + "\","); } } continue; } if (question.getType().getIsMultipleValue()) { for (QuestionOption questionOption : question.getOptions()) { columnName = "p" + page.getOrder() + "q" + question.getOrder() + "o" + questionOption.getOrder(); stringBuilder.append(record.get(columnName) == null ? "," : "\"" + record.get(columnName).toString().replace("\"", "\"\"") + "\","); } continue; } columnName = "p" + page.getOrder() + "q" + question.getOrder(); stringBuilder.append(record.get(columnName) == null ? "," : "\"" + record.get(columnName).toString().replace("\"", "\"\"") + "\","); } } stringBuilder.deleteCharAt(stringBuilder.length() - 1); //delete the last comma stringBuilder.append("\n"); } //Zip file manipulations Code ByteArrayOutputStream bos = new ByteArrayOutputStream(); ZipEntry zipentry; ZipOutputStream zipfile = new ZipOutputStream(bos); zipentry = new ZipEntry("survey" + surveyDefinition.getId() + ".csv"); zipfile.putNextEntry(zipentry); zipfile.write(stringBuilder.toString().getBytes("UTF-8")); zipfile.close(); //response.setContentType("text/html; charset=utf-8"); response.setContentType("application/octet-stream"); // Set standard HTTP/1.1 no-cache headers. response.setHeader("Cache-Control", "no-store, no-cache,must-revalidate"); // Set IE extended HTTP/1.1 no-cache headers (use addHeader). response.addHeader("Cache-Control", "post-check=0, pre-check=0"); // Set standard HTTP/1.0 no-cache header. response.setHeader("Pragma", "no-cache"); response.setHeader("Content-Disposition", "inline;filename=survey" + surveyDefinition.getId() + ".zip"); ServletOutputStream servletOutputStream = response.getOutputStream(); //servletOutputStream.write(stringBuilder.toString().getBytes("UTF-8")); servletOutputStream.write(bos.toByteArray()); servletOutputStream.flush(); } catch (Exception e) { log.error(e.getMessage(), e); throw new RuntimeException(e); } }
From source file:com.jd.survey.web.settings.DataSetController.java
@Secured({ "ROLE_ADMIN" }) @RequestMapping(method = RequestMethod.PUT, produces = "text/html") public String update(@RequestParam(value = "_proceed", required = false) String proceed, @Valid DataSet dataSet, BindingResult bindingResult, Principal principal, Model uiModel, HttpServletRequest httpServletRequest) { log.info("update(): handles PUT"); try {/*from ww w. j a v a 2 s .c om*/ User user = userService.user_findByLogin(principal.getName()); if (!user.isAdmin()) { log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo() + " attempted by user login:" + principal.getName() + "from IP:" + httpServletRequest.getLocalAddr()); return "accessDenied"; } if (proceed != null) { if (bindingResult.hasErrors()) { populateEditForm(uiModel, dataSet, user); return "settings/datasets/update"; } if (surveySettingsService.dataset_findByName(dataSet.getName()) != null && !surveySettingsService .dataset_findByName(dataSet.getName()).getId().equals(dataSet.getId())) { bindingResult.rejectValue("name", "field_unique"); populateEditForm(uiModel, dataSet, user); return "settings/datasets/update"; } uiModel.asMap().clear(); dataSet = surveySettingsService.dataSet_merge(dataSet); return "redirect:/settings/datasets/" + encodeUrlPathSegment(dataSet.getId().toString(), httpServletRequest); } else { return "redirect:/settings/datasets"; } } catch (Exception e) { log.error(e.getMessage(), e); throw (new RuntimeException(e)); } }
From source file:com.jd.survey.web.settings.DataSetController.java
@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" }) @RequestMapping(value = "/upload", method = RequestMethod.POST, produces = "text/html") public String importDatasetItems(@RequestParam("file") MultipartFile file, @RequestParam("id") Long dataSetId, @RequestParam("ignoreFirstRow") Boolean ignoreFirstRow, @RequestParam(value = "_proceed", required = false) String proceed, Principal principal, Model uiModel, HttpServletRequest httpServletRequest) { try {//from ww w .ja v a 2s . co m String login = principal.getName(); User user = userService.user_findByLogin(login); if (!user.isAdmin()) { log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo() + " attempted by user login:" + principal.getName() + "from IP:" + httpServletRequest.getLocalAddr()); return "accessDenied"; } if (proceed != null) { log.info(file.getContentType()); //if file is empty OR the file type is incorrect the upload page is returned with an error message. if (file.isEmpty() || !((file.getContentType().equalsIgnoreCase("text/csv")) || (file.getContentType().equals("application/vnd.ms-excel")) || (file.getContentType().equals("text/plain")))) { uiModel.addAttribute("dataSet", surveySettingsService.dataSet_findById(dataSetId)); uiModel.addAttribute("emptyFileError", true); return "settings/datasets/upload"; } try { CSVReader csvReader; csvReader = new CSVReader(new InputStreamReader(file.getInputStream())); surveySettingsService.importDatasetItems(csvReader, dataSetId, ignoreFirstRow); //done Redirect to the set view page return "redirect:/settings/datasets/" + encodeUrlPathSegment(dataSetId.toString(), httpServletRequest) + "?page=1&size=15"; } catch (Exception e) { log.error(e.getMessage(), e); uiModel.addAttribute("dataSet", surveySettingsService.dataSet_findById(dataSetId)); uiModel.addAttribute("emptyFileError", true); return "settings/datasets/upload"; } } else { return "redirect:/settings/datasets/" + encodeUrlPathSegment(dataSetId.toString(), httpServletRequest); } } catch (Exception e) { log.error(e.getMessage(), e); throw new RuntimeException(e); } }
From source file:unUtils.ActionError.java
@Override public Object doAction(WikittyPublicationContext context) { error.printStackTrace();//w w w .ja v a 2s . com HttpServletRequest req = context.getRequest(); String result = "<html><body>Error: " + "<br>context: " + context + "<br>" + "<br>getContextPath: " + req.getContextPath() + "<br>getMethod: " + req.getMethod() + "<br>getPathInfo: " + req.getPathInfo() + "<br>getPathTranslated: " + req.getPathTranslated() + "<br>getQueryString: " + req.getQueryString() + "<br>getRemoteUser: " + req.getRemoteUser() + "<br>getRequestURI: " + req.getRequestURI() + "<br>getRequestURI: " + req.getRequestURI() + "<br>getRequestedSessionId: " + req.getRequestedSessionId() + "<br>getServletPath: " + req.getServletPath() + "<br>getCharacterEncoding: " + req.getCharacterEncoding() + "<br>getContentType: " + req.getContentType() + "<br>getLocalAddr: " + req.getLocalAddr() + "<br>getLocalName: " + req.getLocalName() + "<br>getProtocol: " + req.getProtocol() + "<br>getRemoteAddr: " + req.getRemoteAddr() + "<br>getRemoteHost: " + req.getRemoteHost() + "<br>getScheme: " + req.getScheme() + "<br>getServerName: " + req.getServerName() + "<br>" + "<br>error:<pre>" + StringEscapeUtils.escapeHtml(ExceptionUtil.stackTrace(error)) + "</pre>" + "</body></html>"; return result; }
From source file:com.jd.survey.web.settings.DataSetController.java
@Secured({ "ROLE_ADMIN" }) @RequestMapping(method = RequestMethod.POST, produces = "text/html") public String createPost(@RequestParam(value = "_proceed", required = false) String proceed, @Valid DataSet dataSet, BindingResult bindingResult, Principal principal, Model uiModel, HttpServletRequest httpServletRequest) { log.info("create(): handles " + RequestMethod.POST.toString()); try {/*from w w w . j a va2 s .c o m*/ User user = userService.user_findByLogin(principal.getName()); if (!user.isAdmin()) { log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo() + " attempted by user login:" + principal.getName() + "from IP:" + httpServletRequest.getLocalAddr()); return "accessDenied"; } if (proceed != null) { if (bindingResult.hasErrors()) { populateEditForm(uiModel, dataSet, user); return "settings/datasets/create"; } if (surveySettingsService.dataset_findByName(dataSet.getName()) != null && !surveySettingsService .dataset_findByName(dataSet.getName()).getId().equals(dataSet.getId())) { bindingResult.rejectValue("name", "field_unique"); populateEditForm(uiModel, dataSet, user); return "settings/datasets/update"; } uiModel.asMap().clear(); dataSet = surveySettingsService.dataSet_merge(dataSet); return "redirect:/settings/datasets/" + encodeUrlPathSegment(dataSet.getId().toString(), httpServletRequest); } else { return "redirect:/settings/datasets"; } } catch (Exception e) { log.error(e.getMessage(), e); throw (new RuntimeException(e)); } }
From source file:nz.co.fortytwo.signalk.processor.RestApiProcessor.java
@Override public void process(Exchange exchange) throws Exception { // the Restlet request should be available if needed HttpServletRequest request = exchange.getIn(HttpMessage.class).getRequest(); HttpSession session = request.getSession(); if (logger.isDebugEnabled()) { logger.debug("Request = " + exchange.getIn().getHeader(Exchange.HTTP_SERVLET_REQUEST).getClass()); logger.debug("Session = " + session.getId()); }//ww w . j a v a2 s . c om if (session.getId() != null) { exchange.getIn().setHeader(REST_REQUEST, "true"); String remoteAddress = request.getRemoteAddr(); String localAddress = request.getLocalAddr(); if (Util.sameNetwork(localAddress, remoteAddress)) { exchange.getIn().setHeader(SignalKConstants.MSG_TYPE, SignalKConstants.INTERNAL_IP); } else { exchange.getIn().setHeader(SignalKConstants.MSG_TYPE, SignalKConstants.EXTERNAL_IP); } exchange.getIn().setHeader(SignalKConstants.MSG_SRC_IP, remoteAddress); exchange.getIn().setHeader(SignalKConstants.MSG_SRC_IP_PORT, request.getRemotePort()); exchange.getIn().setHeader(SignalKConstants.MSG_SRC_BUS, "rest." + remoteAddress.replace('.', '_')); exchange.getIn().setHeader(WebsocketConstants.CONNECTION_KEY, session.getId()); String path = (String) exchange.getIn().getHeader(Exchange.HTTP_URI); if (logger.isDebugEnabled()) { logger.debug(exchange.getIn().getHeaders()); logger.debug(path); } if (logger.isDebugEnabled()) logger.debug("Processing the path = " + path); if (!isValidPath(path)) { exchange.getIn().setBody("Bad Request"); exchange.getIn().setHeader(Exchange.CONTENT_TYPE, "text/plain"); exchange.getIn().setHeader(Exchange.HTTP_RESPONSE_CODE, HttpServletResponse.SC_BAD_REQUEST); // response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } if (exchange.getIn().getHeader(Exchange.HTTP_METHOD).equals("GET")) { processGet(exchange, path); } if (exchange.getIn().getHeader(Exchange.HTTP_METHOD).equals("PUT")) { processPut(exchange, path); } if (exchange.getIn().getHeader(Exchange.HTTP_METHOD).equals("POST")) { if (exchange.getIn().getBody() instanceof StreamCache) { StreamCache cache = exchange.getIn().getBody(StreamCache.class); ByteArrayOutputStream writer = new ByteArrayOutputStream(); cache.writeTo(writer); if (logger.isDebugEnabled()) logger.debug("Reading the POST request:" + writer.toString()); exchange.getIn().setBody(writer.toString()); // POST here if (logger.isDebugEnabled()) logger.debug("Processing the POST request:" + exchange.getIn().getBody()); } else { if (logger.isDebugEnabled()) logger.debug( "Skipping processing the POST request:" + exchange.getIn().getBody().getClass()); } } } else { // HttpServletResponse response = // exchange.getIn(HttpMessage.class).getResponse(); exchange.getIn().setHeader(Exchange.HTTP_RESPONSE_CODE, HttpServletResponse.SC_MOVED_TEMPORARILY); // constant("http://somewhere.com")) exchange.getIn().setHeader("Location", SignalKConstants.SIGNALK_AUTH); exchange.getIn().setBody("Authentication Required"); } }
From source file:com.jd.survey.web.surveys.SurveyController.java
/** * Shows a single Survey /*from www . j a va 2s . c o m*/ * @param surveyId * @param principal * @param uiModel * @param httpServletRequest * @return */ @Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" }) @RequestMapping(value = "/{id}", params = "show", produces = "text/html") public String showSurvey(@PathVariable("id") Long surveyId, Principal principal, Model uiModel, HttpServletRequest httpServletRequest) { log.info("showSurvey surveyId=" + surveyId + " no pageOrder"); try { //Survey survey =surveyService.Survey_findById(surveyId); User user = userService.user_findByLogin(principal.getName()); SurveyEntry surveyEntry = surveyService.surveyEntry_get(surveyId); if (!securityService.userIsAuthorizedToManageSurvey(surveyEntry.getSurveyDefinitionId(), user)) { log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo() + " attempted by user login:" + principal.getName() + "from IP:" + httpServletRequest.getLocalAddr()); return "accessDenied"; } List<SurveyPage> surveyPages = surveyService.surveyPage_getAll(surveyId, messageSource.getMessage(DATE_FORMAT, null, LocaleContextHolder.getLocale())); uiModel.addAttribute("surveyEntry", surveyEntry); uiModel.addAttribute("surveyPages", surveyPages); return "surveys/survey"; } catch (Exception e) { log.error(e.getMessage(), e); throw (new RuntimeException(e)); } }
From source file:org.ambraproject.action.FeedbackAction.java
@SuppressWarnings("unchecked") public Map<String, String> getUserSessionAttributes() { final Map<String, String> headers = new LinkedHashMap<String, String>(); final HttpServletRequest request = ServletActionContext.getRequest(); {/*from w w w .jav a 2s. c om*/ final Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { final String headerName = (String) headerNames.nextElement(); final List<String> headerValues = EnumerationUtils.toList(request.getHeaders(headerName)); headers.put(headerName, StringUtils.join(headerValues.iterator(), ",")); } } headers.put("server-name", request.getServerName() + ":" + request.getServerPort()); headers.put("remote-addr", request.getRemoteAddr()); headers.put("local-addr", request.getLocalAddr() + ":" + request.getLocalPort()); /* * Keeping this in case more values get passed from the client other than just the visible form * fields */ { final Enumeration parameterNames = request.getParameterNames(); while (parameterNames.hasMoreElements()) { final String paramName = (String) parameterNames.nextElement(); final String[] paramValues = request.getParameterValues(paramName); headers.put(paramName, StringUtils.join(paramValues, ",")); } } return headers; }
From source file:com.jd.survey.web.settings.QuestionRowLabelController.java
@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" }) @RequestMapping(value = "/{id}", params = "form", produces = "text/html") public String updateForm(@PathVariable("id") Long questionId, Principal principal, Model uiModel, HttpServletRequest httpServletRequest) { try {/*w w w . ja va 2 s . com*/ String login = principal.getName(); User user = userService.user_findByLogin(login); Question question = surveySettingsService.question_findById(questionId); //Check if the user is authorized if (!securityService.userIsAuthorizedToManageSurvey(question.getPage().getSurveyDefinition().getId(), user) && !securityService.userBelongsToDepartment( question.getPage().getSurveyDefinition().getDepartment().getId(), user)) { log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo() + " attempted by user login:" + principal.getName() + "from IP:" + httpServletRequest.getLocalAddr()); return "accessDenied"; } SortedSet<QuestionRowLabel> RowLabels = question.getRowLabels(); log.info("initial set size" + RowLabels.size()); for (int i = 1; i <= EMPTY_OPTIONS_COUNT; i++) { log.info("adding to set" + i); RowLabels.add(new QuestionRowLabel(question, (short) (question.getRowLabels().size() + i))); } question.setRowLabels(RowLabels); uiModel.addAttribute("question", question); return "settings/questionRows/update"; } catch (Exception e) { log.error(e.getMessage(), e); throw (new RuntimeException(e)); } }