List of usage examples for javax.servlet.http HttpServletRequest getServerPort
public int getServerPort();
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 ww w. j a v a2 s.com 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:com.ah.be.common.NmsUtil.java
/** * The function will return the web application url String with http (not https) * * @param request -//w w w.j a va 2s . c om * @return - */ public static String getWebAppHttpUrl(HttpServletRequest request) { String httpUrl; if (useHttpProxy) { // with proxy setting, the url will be hard coded httpUrl = "http://" + request.getServerName() + ":8080" + request.getContextPath() + "/"; } else { // rewrite by the request information if ("https".equals(request.getScheme())) { if (request.getServerPort() == 8443) { httpUrl = "http://" + request.getServerName() + ":8080" + request.getContextPath() + "/"; } else { httpUrl = "http://" + request.getServerName() + request.getContextPath() + "/"; } } else { httpUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/"; } } log.info("getWebAppHttpUrl", httpUrl); return httpUrl; }
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 w w w . j a v a 2 s .co m * @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.bookingForm.BABookingAction.java
public ActionForward baPrint(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { Connection con = null;/*from ww w.j a v 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 v a2 s . co 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:crds.pub.FCKeditor.connector.ConnectorServlet.java
/** * Manage the Get requests (GetFolders, GetFoldersAndFiles, CreateFolder).<br> * * The servlet accepts commands sent in the following format:<br> * connector?Command=CommandName&Type=ResourceType&CurrentFolder=FolderPath<br><br> * It execute the command and then return the results to the client in XML format. * *//*from ww w .j a v a 2s . c o m*/ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); FormUserOperation formUser = Constant.getFormUserOperation(request); String fck_task_id = (String) session.getAttribute("fck_task_id"); if (fck_task_id == null) { fck_task_id = "temp_task_id"; } response.setContentType("text/xml; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); String currentPath = baseDir + formUser.getCompany_code() + currentFolderStr + fck_task_id + currentFolderStr + typeStr + currentFolderStr; String currentDirPath = getServletContext().getRealPath(currentPath); File currentDir = new File(currentDirPath); if (!currentDir.exists()) { currentDir.mkdirs(); } Document document = null; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.newDocument(); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } //???IP String server_ip = (String) session.getAttribute("server_ip"); if (server_ip == null) { server_ip = CommonMethod.getServerIP(request) + ":" + request.getServerPort();//???IP? } String url = "http://" + server_ip + currentPath.substring(2, currentPath.length()); Node root = CreateCommonXml(document, commandStr, typeStr, currentFolderStr, url); if (commandStr.equals("GetFolders")) { getFolders(currentDir, root, document); } else if (commandStr.equals("GetFoldersAndFiles")) { getFolders(currentDir, root, document); getFiles(currentDir, root, document); } else if (commandStr.equals("CreateFolder")) { String newFolderStr = request.getParameter("NewFolderName"); File newFolder = new File(currentDir, newFolderStr); String retValue = "110"; if (newFolder.exists()) { retValue = "101"; } else { try { boolean dirCreated = newFolder.mkdir(); if (dirCreated) retValue = "0"; else retValue = "102"; } catch (SecurityException sex) { retValue = "103"; } } setCreateFolderResponse(retValue, root, document); } document.getDocumentElement().normalize(); try { TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(out); transformer.transform(source, result); if (debug) { StreamResult dbgResult = new StreamResult(System.out); transformer.transform(source, dbgResult); } } catch (Exception ex) { ex.printStackTrace(); } out.flush(); out.close(); }
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;/*from w w w . j a v a 2 s.com*/ 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; }
From source file:org.ngrinder.script.controller.SvnDavController.java
@SuppressWarnings("StringConcatenationInsideStringBufferAppend") 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());/* ww w . j ava 2 s .com*/ }
From source file:jp.or.openid.eiwg.scim.servlet.Users.java
/** * POST?// w w w . ja va2 s. c o m * * @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: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());/*from w ww.j a va 2 s .co m*/ }