List of usage examples for javax.servlet.http HttpServletRequest getServerName
public String getServerName();
From source file:io.fabric8.gateway.servlet.ProxyServlet.java
/** * Executes the {@link HttpMethod} passed in and sends the proxy response * back to the client via the given {@link javax.servlet.http.HttpServletResponse} * * @param proxyDetails//from www . j a va 2 s. c om * @param httpMethodProxyRequest An object representing the proxy request to be made * @param httpServletResponse An object by which we can send the proxied * response back to the client * @throws java.io.IOException Can be thrown by the {@link HttpClient}.executeMethod * @throws javax.servlet.ServletException Can be thrown to indicate that another error has occurred */ private void executeProxyRequest(ProxyDetails proxyDetails, HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { httpMethodProxyRequest.setDoAuthentication(false); httpMethodProxyRequest.setFollowRedirects(false); // Create a default HttpClient HttpClient httpClient = proxyDetails.createHttpClient(httpMethodProxyRequest); // Execute the request int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest); // Check if the proxy response is a redirect // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect // Hooray for open source software if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) { String stringStatusCode = Integer.toString(intProxyResponseCode); String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue(); if (stringLocation == null) { throw new ServletException("Received status code: " + stringStatusCode + " but no " + STRING_LOCATION_HEADER + " header was found in the response"); } // Modify the redirect to go to this proxy servlet rather that the proxied host String stringMyHostName = httpServletRequest.getServerName(); if (httpServletRequest.getServerPort() != 80) { stringMyHostName += ":" + httpServletRequest.getServerPort(); } stringMyHostName += httpServletRequest.getContextPath(); httpServletResponse.sendRedirect(stringLocation .replace(proxyDetails.getProxyHostAndPort() + proxyDetails.getProxyPath(), stringMyHostName)); return; } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) { // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0); httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } // Pass the response code back to the client httpServletResponse.setStatus(intProxyResponseCode); // Pass response headers back to the client Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); for (Header header : headerArrayResponse) { if (!ProxySupport.isHopByHopHeader(header.getName())) { if (ProxySupport.isSetCookieHeader(header)) { HttpProxyRule proxyRule = proxyDetails.getProxyRule(); String setCookie = ProxySupport.replaceCookieAttributes(header.getValue(), proxyRule.getCookiePath(), proxyRule.getCookieDomain()); httpServletResponse.setHeader(header.getName(), setCookie); } else { httpServletResponse.setHeader(header.getName(), header.getValue()); } } } // check if we got data, that is either the Content-Length > 0 // or the response code != 204 int code = httpMethodProxyRequest.getStatusCode(); boolean noData = code == HttpStatus.SC_NO_CONTENT; if (!noData) { String length = httpServletRequest.getHeader(STRING_CONTENT_LENGTH_HEADER_NAME); if (length != null && "0".equals(length.trim())) { noData = true; } } LOG.trace("Response has data? {}", !noData); if (!noData) { // Send the content to the client InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream(); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse); OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream(); int intNextByte; while ((intNextByte = bufferedInputStream.read()) != -1) { outputStreamClientResponse.write(intNextByte); } } }
From source file:com.ba.forms.receipt.BAReceiptAction.java
public ActionForward baPrint(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { Connection con = null;//from w w w . ja va2 s. co m com.fins.org.json.JSONObject json = new com.fins.org.json.JSONObject(); try { logger.info("hotel_booking"); // title is the title of the report.Here we are passing dynamically.So that this class is useful to remaining reports also. String jrept = "hotel_receipt.jrxml"; String pdfFileName = "hotel_receipt"; String receipt = request.getParameter("receipt"); con = BADatabaseUtil.getConnection(); String reportFileName = JasperCompileManager .compileReportToFile(request.getRealPath("/reports") + "/" + jrept); java.util.Map parameters = new java.util.HashMap(); parameters.put("receipt", receipt); File reportFile = new File(reportFileName); if (!reportFile.exists()) { throw new JRRuntimeException( "File WebappReport.jasper not found. The report design must be compiled first."); } JasperPrint jasperPrint = JasperFillManager.fillReport(reportFileName, parameters, con); JasperExportManager.exportReportToPdfFile(jasperPrint, request.getRealPath("/PDF") + "/" + pdfFileName + "_" + receipt + ".pdf"); File f = new File(request.getRealPath("/PDF") + "/" + pdfFileName + "_" + receipt + ".pdf"); FileInputStream fin = new FileInputStream(f); // String path = "http://" + request.getServerName() + ":" + request.getServerPort() + "/" + request.getContextPath() + "/PDF" + "/" + pdfFileName + "_" + receipt + ".pdf"; request.setAttribute("path", path); // outStream.flush(); fin.close(); // outStream.close(); logger.info("print feed dc"); json.put("exception", ""); json.put("bookingDets", path); json.put("bookingExit", 1); } catch (Exception ex) { ex.printStackTrace(); json.put("exception", BAHandleAllException.exceptionHandler(ex)); } finally { BADatabaseUtil.closeConnection(con); } logger.info("CmsReasonMasterDaoImpl In CmsReasonMasterAction :: cmsGet() ends Here "); response.getWriter().write(json.toString()); return null; }
From source file:es.pode.visualizador.presentacion.descargas.DescargasControllerImpl.java
/** * @see es.pode.visualizador.presentacion.descargas.DescargasController#listadoDescargas(org.apache.struts.action.ActionMapping, es.pode.visualizador.presentacion.descargas.ListadoDescargasForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *///from w w w . j a v a 2 s.c o m public final void listadoDescargas(ActionMapping mapping, es.pode.visualizador.presentacion.descargas.ListadoDescargasForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { try { Locale locale = (Locale) request.getSession().getAttribute(ConstantesAgrega.DEFAULT_LOCALE); String idioma = locale.getLanguage(); logger.debug("Recuperado idioma :" + idioma); DescargaVO descargas[] = getSrvDescargas().obtenerDescargasActivas(); logger.debug("Recuperadas " + descargas.length != null ? descargas.length : 0 + " descargas"); ArrayList<DescargaInfo> listaDescargas = new ArrayList<DescargaInfo>(); if (descargas != null && descargas.length > 0) { DescDescargaVO[] descs = getSrvDescargas().obtenerDescDescargasIdioma(descargas, idioma); logger.debug("Recuperadas " + descs.length + " descripciones de descargas"); for (int i = 0; i < descargas.length; i++) { DescargaInfo info = new DescargaInfo(); info.setTitulo(descs[i] != null && descs[i].getTitulo() != null ? descs[i].getTitulo() : VACIA); info.setDescripcion( descs[i] != null && descs[i].getDescripcion() != null ? descs[i].getDescripcion() : VACIA); info.setIdentificador(descargas[i] != null && descargas[i].getIdentificador() != null ? descargas[i].getIdentificador().toString() : VACIA); info.setPeso( descargas[i] != null && descargas[i].getPeso() != null ? descargas[i].getPeso() : 0L, locale); info.setRuta(descargas[i] != null && descargas[i].getPath() != null ? request.getServerName() + "/" + descargas[i].getPath() : VACIA); listaDescargas.add(info); } } logger.debug("Lista de descargas construida"); form.setDescargas(listaDescargas); } catch (Exception e) { logger.debug("Error al recuperar descargas.", e); throw new ValidatorException("{listaDescargas.error}"); } }
From source file:PrintCGI.java
/** * Prints CGI Environment Variables in a table * //from w ww. j av a2 s.c o m * @param request * @param response * @throws IOException */ public void printCGIValues(HttpServletRequest request, HttpServletResponse response) throws IOException { String headers = null; String htmlHeader = "<HTML><HEAD><TITLE> CGI Environment Variables </TITLE></HEAD><BODY>"; String htmlFooter = "</BODY></HTML>"; response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(htmlHeader); out.println("<TABLE ALIGN=CENTER BORDER=1>"); out.println("<tr><th> CGI Variable </th><th> Value </th>"); out.println("<tr><td align=center>Authentication Type</td>"); out.println("<td align=center>" + request.getAuthType() + "</td></tr>"); out.println("<tr><td align=center>Content Type</td>"); out.println("<td align=center>" + request.getContentType() + "</td></tr>"); out.println("<tr><td align=center>Content Type Length</td>"); out.println("<td align=center>" + request.getContentLength() + "</td></tr>"); out.println("<tr><td align=center>Query String</td>"); out.println("<td align=center>" + request.getMethod() + "</td></tr>"); out.println("<tr><td align=center>IP Address</td>"); out.println("<td align=center>" + request.getRemoteAddr() + "</td></tr>"); out.println("<tr><td align=center>Host Name</td>"); out.println("<td align=center>" + request.getRemoteHost() + "</td></tr>"); out.println("<tr><td align=center>Request URL</td>"); out.println("<td align=center>" + request.getRequestURI() + "</td></tr>"); out.println("<tr><td align=center>Servlet Path</td>"); out.println("<td align=center>" + request.getServletPath() + "</td></tr>"); out.println("<tr><td align=center>Server's Name</td>"); out.println("<td align=center>" + request.getServerName() + "</td></tr>"); out.println("<tr><td align=center>Server's Port</td>"); out.println("<td align=center>" + request.getServerPort() + "</td></tr>"); out.println("</TABLE><BR>"); out.println(htmlFooter); }
From source file:org.ngrinder.script.controller.DavSvnController.java
private void logRequest(HttpServletRequest request) { StringBuilder logBuffer = new StringBuilder(); logBuffer.append('\n'); logBuffer.append("request.getAuthType(): " + request.getAuthType()); logBuffer.append('\n'); logBuffer.append("request.getCharacterEncoding(): " + request.getCharacterEncoding()); logBuffer.append('\n'); logBuffer.append("request.getContentType(): " + request.getContentType()); logBuffer.append('\n'); logBuffer.append("request.getContextPath(): " + request.getContextPath()); logBuffer.append('\n'); logBuffer.append("request.getContentLength(): " + request.getContentLength()); logBuffer.append('\n'); logBuffer.append("request.getMethod(): " + request.getMethod()); logBuffer.append('\n'); logBuffer.append("request.getPathInfo(): " + request.getPathInfo()); logBuffer.append('\n'); logBuffer.append("request.getPathTranslated(): " + request.getPathTranslated()); logBuffer.append('\n'); logBuffer.append("request.getQueryString(): " + request.getQueryString()); logBuffer.append('\n'); logBuffer.append("request.getRemoteAddr(): " + request.getRemoteAddr()); logBuffer.append('\n'); logBuffer.append("request.getRemoteHost(): " + request.getRemoteHost()); logBuffer.append('\n'); logBuffer.append("request.getRemoteUser(): " + request.getRemoteUser()); logBuffer.append('\n'); logBuffer.append("request.getRequestURI(): " + request.getRequestURI()); logBuffer.append('\n'); logBuffer.append("request.getServerName(): " + request.getServerName()); logBuffer.append('\n'); logBuffer.append("request.getServerPort(): " + request.getServerPort()); logBuffer.append('\n'); logBuffer.append("request.getServletPath(): " + request.getServletPath()); logBuffer.append('\n'); logBuffer.append("request.getRequestURL(): " + request.getRequestURL()); LOGGER.trace(logBuffer.toString());/*w w w . jav a 2 s. com*/ }
From source file:de.appsolve.padelcampus.admin.controller.events.AdminEventsController.java
@RequestMapping(method = POST, value = "/{eventId}/addguests") public ModelAndView postAddGuests(@PathVariable("eventId") Long eventId, @ModelAttribute("Player") Player player, @RequestParam("NumberOfGuests") Long numberOfGuests, HttpServletRequest request, BindingResult result) { Event event = eventDAO.findByIdFetchWithParticipants(eventId); try {//from www.j a v a2s . c om Player primaryPlayer; if (StringUtils.isEmpty(player.getUUID())) { validator.validate(player, result); if (result.hasErrors()) { return getAddGuestsView(event, player, numberOfGuests); } if (playerDAO.findByEmail(player.getEmail()) != null) { throw new Exception(msg.get("EmailAlreadyRegistered")); } player.setAllowEmailContact(false); primaryPlayer = playerDAO.saveOrUpdate(player); } else { primaryPlayer = playerDAO.findByUUID(player.getUUID()); } if (event.getParticipants().contains(primaryPlayer)) { throw new Exception(msg.get("AlreadyParticipatesInThisEvent", new Object[] { primaryPlayer })); } for (long guestNumber = 1L; guestNumber <= numberOfGuests; guestNumber++) { String domain = request.getServerName().equals("localhost") ? "localhost.local" : request.getServerName(); String guestEmail = String.format("%s-%s-Gast-%s@%s", primaryPlayer.getFirstName(), primaryPlayer.getLastName(), guestNumber, domain).replace(" ", "-"); Player guest = playerDAO.findByEmail(guestEmail); if (guest == null) { guest = new Player(); guest.setFirstName(primaryPlayer.getFirstName()); guest.setLastName(String.format("%s Gast %s", primaryPlayer.getLastName(), guestNumber)); guest.setAllowEmailContact(false); guest.setEmail(guestEmail); guest.setPhone(primaryPlayer.getPhone()); guest.setGender(primaryPlayer.getGender()); guest = playerDAO.saveOrUpdate(guest); } event.getParticipants().add(guest); } event.getParticipants().add(primaryPlayer); eventDAO.saveOrUpdate(event); return new ModelAndView("redirect:/admin/events/edit/" + eventId); } catch (Exception e) { LOG.error(e.getMessage(), e); result.addError(new ObjectError("id", e.getMessage())); return getAddGuestsView(event, player, numberOfGuests); } }
From source file:com.ba.forms.bookingForm.BABookingAction.java
public ActionForward baPrint(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { Connection con = null;/* ww w .j av a 2 s . c o m*/ com.fins.org.json.JSONObject json = new com.fins.org.json.JSONObject(); try { logger.info("hotel_booking"); // title is the title of the report.Here we are passing dynamically.So that this class is useful to remaining reports also. String jrept = "hotel_booking.jrxml"; String pdfFileName = "hotel_booking"; String bookingId = request.getParameter("bookingId"); con = BADatabaseUtil.getConnection(); String reportFileName = JasperCompileManager .compileReportToFile(request.getRealPath("/reports") + "/" + jrept); java.util.Map parameters = new java.util.HashMap(); parameters.put("bookingId", bookingId); File reportFile = new File(reportFileName); if (!reportFile.exists()) { throw new JRRuntimeException( "File WebappReport.jasper not found. The report design must be compiled first."); } JasperPrint jasperPrint = JasperFillManager.fillReport(reportFileName, parameters, con); JasperExportManager.exportReportToPdfFile(jasperPrint, request.getRealPath("/PDF") + "/" + pdfFileName + "_" + bookingId + ".pdf"); File f = new File(request.getRealPath("/PDF") + "/" + pdfFileName + "_" + bookingId + ".pdf"); FileInputStream fin = new FileInputStream(f); // String path = "http://" + request.getServerName() + ":" + request.getServerPort() + "/" + request.getContextPath() + "/PDF" + "/" + pdfFileName + "_" + bookingId + ".pdf"; request.setAttribute("path", path); // outStream.flush(); fin.close(); // outStream.close(); logger.info("print feed dc"); json.put("exception", ""); json.put("bookingDets", path); json.put("bookingExit", 1); } catch (Exception ex) { ex.printStackTrace(); json.put("exception", BAHandleAllException.exceptionHandler(ex)); } finally { BADatabaseUtil.closeConnection(con); } logger.info("CmsReasonMasterDaoImpl In CmsReasonMasterAction :: cmsGet() ends Here "); response.getWriter().write(json.toString()); return null; }
From source file:com.reachcall.pretty.http.ProxyServlet.java
private void execute(Match match, HttpRequestBase method, HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { LOG.log(Level.FINE, "Requesting {0}", method.getURI()); HttpClient client = this.getClient(); HttpResponse response = client.execute(method); for (Header h : response.getHeaders("Set-Cookie")) { String line = parseCookie(h.getValue()); LOG.log(Level.FINER, method.getURI() + "{0}", new Object[] { line }); if (line != null) { LOG.log(Level.INFO, "Bonding session {0} to host {1}", new Object[] { line, match.destination.hostAndPort() }); try { resolver.bond(line, match); } catch (ExecutionException ex) { Logger.getLogger(ProxyServlet.class.getName()).log(Level.SEVERE, null, ex); this.releaseClient(client); throw new ServletException(ex); }//from w w w . j a va2s . c o m } } int rc = response.getStatusLine().getStatusCode(); if ((rc >= HttpServletResponse.SC_MULTIPLE_CHOICES) && (rc < HttpServletResponse.SC_NOT_MODIFIED)) { String location = response.getFirstHeader(HEADER_LOCATION).getValue(); if (location == null) { throw new ServletException("Recieved status code: " + rc + " but no " + HEADER_LOCATION + " header was found in the response"); } String hostname = req.getServerName(); if ((req.getServerPort() != 80) && (req.getServerPort() != 443)) { hostname += (":" + req.getServerPort()); } hostname += req.getContextPath(); String replaced = location.replace(match.destination.hostAndPort() + match.path.getDestination(), hostname); if (replaced.startsWith("http://")) { replaced = replaced.replace("http:", req.getScheme() + ":"); } resp.sendRedirect(replaced); this.releaseClient(client); return; } else if (rc == HttpServletResponse.SC_NOT_MODIFIED) { resp.setIntHeader(HEADER_CONTENT_LENTH, 0); resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); this.releaseClient(client); return; } resp.setStatus(rc); Header[] headerArrayResponse = response.getAllHeaders(); for (Header header : headerArrayResponse) { resp.setHeader(header.getName(), header.getValue()); } if (response.getEntity() != null) { resp.setContentLength((int) response.getEntity().getContentLength()); response.getEntity().writeTo(resp.getOutputStream()); } this.releaseClient(client); LOG.finer("Done."); }
From source file:jp.or.openid.eiwg.scim.servlet.Users.java
/** * POST?//w w w. jav a2 s .c om * * @param request * @param response ? * @throws ServletException * @throws IOException */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // ? ServletContext context = getServletContext(); // ?? Operation op = new Operation(); boolean result = op.Authentication(context, request); if (!result) { // errorResponse(response, op.getErrorCode(), op.getErrorType(), op.getErrorMessage()); } else { // ? String targetId = request.getPathInfo(); String attributes = request.getParameter("attributes"); if (targetId != null && !targetId.isEmpty()) { // ?'/'??? targetId = targetId.substring(1); } if (targetId == null || targetId.isEmpty()) { // POST(JSON)? request.setCharacterEncoding("UTF-8"); String body = IOUtils.toString(request.getReader()); // ? LinkedHashMap<String, Object> resultObject = op.createUserInfo(context, request, attributes, body); if (resultObject != null) { // javaJSON?? ObjectMapper mapper = new ObjectMapper(); StringWriter writer = new StringWriter(); mapper.writeValue(writer, resultObject); // Location?URL? String location = request.getScheme() + "://" + request.getServerName(); int serverPort = request.getServerPort(); if (serverPort != 80 && serverPort != 443) { location += ":" + Integer.toString(serverPort); } location += request.getContextPath(); location += "/scim/Users/"; if (resultObject.get("id") != null) { location += resultObject.get("id").toString(); } // ?? response.setStatus(HttpServletResponse.SC_CREATED); response.setContentType("application/scim+json;charset=UTF-8"); response.setHeader("Location", location); PrintWriter out = response.getWriter(); out.println(writer.toString()); } else { // errorResponse(response, op.getErrorCode(), op.getErrorType(), op.getErrorMessage()); } } else { errorResponse(response, HttpServletResponse.SC_BAD_REQUEST, null, MessageConstants.ERROR_NOT_SUPPORT_OPERATION); } } }
From source file:com.ba.forms.foodBill.BAFoodBillAction.java
public ActionForward baPrint(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { Connection con = null;// w w w. j a v a2 s. co m com.fins.org.json.JSONObject json = new com.fins.org.json.JSONObject(); try { logger.info("hotel_booking"); // title is the title of the report.Here we are passing dynamically.So that this class is useful to remaining reports also. String jrept = "hotel_food.jrxml"; String pdfFileName = "hotel_food"; String foodBill = request.getParameter("foodBill"); con = BADatabaseUtil.getConnection(); String reportFileName = JasperCompileManager .compileReportToFile(request.getRealPath("/reports") + "/" + jrept); java.util.Map parameters = new java.util.HashMap(); parameters.put("foodBill", foodBill); File reportFile = new File(reportFileName); if (!reportFile.exists()) { throw new JRRuntimeException( "File WebappReport.jasper not found. The report design must be compiled first."); } JasperPrint jasperPrint = JasperFillManager.fillReport(reportFileName, parameters, con); JasperExportManager.exportReportToPdfFile(jasperPrint, request.getRealPath("/PDF") + "/" + pdfFileName + "_" + foodBill + ".pdf"); File f = new File(request.getRealPath("/PDF") + "/" + pdfFileName + "_" + foodBill + ".pdf"); FileInputStream fin = new FileInputStream(f); // String path = "http://" + request.getServerName() + ":" + request.getServerPort() + "/" + request.getContextPath() + "/PDF" + "/" + pdfFileName + "_" + foodBill + ".pdf"; request.setAttribute("path", path); // outStream.flush(); fin.close(); // outStream.close(); logger.info("print feed dc"); json.put("exception", ""); json.put("bookingDets", path); json.put("bookingExit", 1); } catch (Exception ex) { ex.printStackTrace(); json.put("exception", BAHandleAllException.exceptionHandler(ex)); } finally { BADatabaseUtil.closeConnection(con); } logger.info("CmsReasonMasterDaoImpl In CmsReasonMasterAction :: cmsGet() ends Here "); response.getWriter().write(json.toString()); return null; }