List of usage examples for javax.servlet.http HttpServletRequest getLocalName
public String getLocalName();
From source file:eu.planets_project.tb.impl.data.util.DataHandlerImpl.java
@Deprecated public URI getHttpFileRef(File localFileRef, boolean input) throws URISyntaxException, FileNotFoundException { if (!localFileRef.canRead()) { throw new FileNotFoundException(localFileRef + " not found"); }/*w ww . j a v a 2 s . c om*/ HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext() .getRequest(); String authority = req.getLocalName() + ":" + Integer.toString(req.getLocalPort()); //distinguish between inputdata and outputdata if (input) { //URI input file ref to be created //URI(scheme,authority,path,query,fragement) return new URI("http", authority, "/planets-testbed/inputdata/" + localFileRef.getName(), null, null); } else { //URI output file ref to be created return new URI("http", authority, "/planets-testbed/outputdata/" + localFileRef.getName(), null, null); } }
From source file:jp.go.nict.langrid.servicesupervisor.StreamingServiceSupervisor.java
protected void doFilterProcess(HttpServletRequest request, HttpServletResponse response, FilterChain chain, ServiceContext serviceContext, String userGridId, String userId, String serviceGridId, String serviceId) throws ConnectException, DaoException, IOException, ServletException { // prepare// w ww . j a va2 s. c o m String protocol = getProtocol(request); FaultResponder responder = protocol.equals(Protocols.PROTOBUF_RPC) ? new HttpFaultResponder(request.getLocalName(), serviceGridId, serviceId) : new SoapFaultResponder(request.getLocalName(), serviceGridId, serviceId); ProcessContext c = null; FrontEnd fe = FrontEnd.getInstance(); // preprocess Throwable expInPreprocess = null; daoContext.beginTransaction(); try { c = prepareContextAndSetServiceInfoHeader(response, serviceContext, userGridId, userId, serviceGridId, serviceId); fe.preprocess(c, serviceContext.getRequestMimeHeaders()); } catch (Throwable e) { expInPreprocess = e; } finally { daoContext.commitTransaction(); } if (expInPreprocess != null) { ByteArrayOutputHttpServletResponseWrapper expResponse = new ByteArrayOutputHttpServletResponseWrapper( response); responder.setResponse(expResponse); responder.respond(expInPreprocess); byte[] res = expResponse.getOutput(); response.getOutputStream().write(res); if (c != null && c.getTargetService() != null) { daoContext.beginTransaction(); try { if (res.length > 4000) { res = Arrays.copyOf(res, 4000); } fe.logProcess(c, FrontEnd.createLogInfo(request, new ByteArrayInputStream(res), -1, expResponse.getStatus(), res.length, protocol), "Server.serverException", ExceptionUtil.getMessageWithStackTrace(expInPreprocess)); } catch (SystemErrorException e) { logger.log(Level.SEVERE, "unexpected exception occurred in log process(commit fase).", e); } finally { daoContext.commitTransaction(); } } else { logger.log(Level.WARNING, "exception for unknown service.", expInPreprocess); } return; } // invoke, reply and postprocess boolean isStreaming = c.getTargetService().getStreaming(); if (!isStreaming) { String v = request.getHeader(LangridConstants.HTTPHEADER_STREAMING); if (v != null && !v.equalsIgnoreCase("false")) { isStreaming = true; } } long millis = -1; int len = -1; int code = -1; byte[] responseHead = null; Throwable expInProcess = null; if (!isStreaming) { ByteArrayOutputHttpServletResponseWrapper wresponse = new ByteArrayOutputHttpServletResponseWrapper( response); wresponse.setStatus(200); try { long s = System.currentTimeMillis(); chain.doFilter(request, wresponse); millis = System.currentTimeMillis() - s; } catch (Throwable e) { expInProcess = e; } byte[] responseBytes = wresponse.getOutput(); // postprocess if (expInProcess == null && serviceContext.getSelfGridId().equals(c.getTargetGrid().getGridId())) { daoContext.beginTransaction(); try { fe.postprocess(c, responseBytes.length); } catch (Throwable t) { expInProcess = t; } finally { daoContext.commitTransaction(); } } if (expInProcess == null) { code = wresponse.getStatus(); } else { ByteArrayOutputHttpServletResponseWrapper wresponse2 = new ByteArrayOutputHttpServletResponseWrapper( response); responder.setResponse(wresponse2); responder.respond(expInProcess); responseBytes = wresponse2.getOutput(); code = wresponse2.getStatus(); } response.setStatus(code); response.getOutputStream().write(responseBytes); len = responseBytes.length; responseHead = Arrays.copyOf(responseBytes, Math.min(responseBytes.length, 4000)); } else { PostprocessingHttpServletResponseWrapper wresponse = new PostprocessingHttpServletResponseWrapper( response, c, fe, serviceContext.getSelfGridId().equals(c.getTargetGrid().getGridId())); try { long s = System.currentTimeMillis(); // invoke chain.doFilter(request, wresponse); wresponse.getOutputStream().flush(); wresponse.getOutputStream().close(); millis = System.currentTimeMillis() - s; } catch (Throwable e) { expInProcess = e; } if (wresponse.getWrittenBytes() == 0) { responder.setResponse(wresponse); Exception exp = wresponse.getExceptionInProcessing(); if (exp != null) { responder.respond(exp); expInProcess = exp; } else if (expInProcess != null) { responder.respond(expInProcess); } } len = wresponse.getWrittenBytes(); code = wresponse.getStatus(); responseHead = wresponse.getResponseHead(); } // logProcess daoContext.beginTransaction(); try { Pair<String, String> soapFault = Pair.create((String) null, (String) null); if (code != 200) { soapFault = SOAPBodyUtil.extractSoapFaultString(new ByteArrayInputStream(responseHead)); if (soapFault.getFirst() == null && soapFault.getSecond() == null) { // protobuf error? soapFault = Pair.create("Server.unknownError", StringEscapeUtils.escapeHtml( new String(responseHead, 0, Math.min(700, responseHead.length), CharsetUtil.UTF_8))); } } else if (expInProcess != null) { soapFault = Pair.create("Server.processError", expInProcess.toString()); } fe.logProcess(c, FrontEnd.createLogInfo(request, new ByteArrayInputStream(responseHead), millis, code, len, protocol), soapFault.getFirst(), soapFault.getSecond()); } catch (SystemErrorException e) { logger.log(Level.SEVERE, "unexpected exception occurred in log process(commit fase).", e); } finally { daoContext.commitTransaction(); } }
From source file:com.commsen.apropos.web.servlet.DownloadPropertiesServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String name = req.getParameter("name"); if (StringUtils.isBlank(name)) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing package name!"); return;/* w w w. j av a 2 s . co m*/ } PropertyPackage propertyPackage = PropertiesManager.getPropertyPackage(name.trim()); StringEscapeUtils.escapeHtml(name); if (propertyPackage == null) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Property package called " + StringEscapeUtils.escapeHtml(name) + " was not found!"); return; } String type = req.getParameter("type"); if (StringUtils.isBlank(type)) { type = "properties"; } if (type.toLowerCase().equals("properties")) { resp.setContentType("text/plain; charset=ASCI"); propertyPackage.asProperties().store(resp.getOutputStream(), "Property file obtained from " + req.getLocalName()); } else if (type.toLowerCase().equals("xml")) { resp.setContentType("text/xml; charset=UTF-8"); propertyPackage.asProperties().storeToXML(resp.getOutputStream(), "Property file obtained from " + req.getRequestURI()); } else { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unsupported type: " + StringEscapeUtils.escapeHtml(type) + " !"); return; } }
From source file:se.vgregion.portal.requestlogger.RequestLoggerController.java
private Map<String, String> getRequestInfo(PortletRequest request) { Map<String, String> requestResult = new TreeMap<String, String>(); HttpServletRequest httpRequest = PortalUtil.getHttpServletRequest(request); requestResult.put("RemoteUser", httpRequest.getRemoteUser()); requestResult.put("P3P.USER_LOGIN_ID", getRemoteUserId(request)); requestResult.put("RemoteAddr", httpRequest.getRemoteAddr()); requestResult.put("RemoteHost", httpRequest.getRemoteHost()); requestResult.put("RemotePort", String.valueOf(httpRequest.getRemotePort())); requestResult.put("AuthType", httpRequest.getAuthType()); requestResult.put("CharacterEncoding", httpRequest.getCharacterEncoding()); requestResult.put("ContentLength", String.valueOf(httpRequest.getContentLength())); requestResult.put("ContentType", httpRequest.getContentType()); requestResult.put("ContextPath", httpRequest.getContextPath()); requestResult.put("LocalAddr", httpRequest.getLocalAddr()); requestResult.put("Locale", httpRequest.getLocale().toString()); requestResult.put("LocalName", httpRequest.getLocalName()); requestResult.put("LocalPort", String.valueOf(httpRequest.getLocalPort())); requestResult.put("Method", httpRequest.getMethod()); requestResult.put("PathInfo", httpRequest.getPathInfo()); requestResult.put("PathTranslated", httpRequest.getPathTranslated()); requestResult.put("Protocol", httpRequest.getProtocol()); requestResult.put("QueryString", httpRequest.getQueryString()); requestResult.put("RequestedSessionId", httpRequest.getRequestedSessionId()); requestResult.put("RequestURI", httpRequest.getRequestURI()); requestResult.put("Scheme", httpRequest.getScheme()); requestResult.put("ServerName", httpRequest.getServerName()); requestResult.put("ServerPort", String.valueOf(httpRequest.getServerPort())); requestResult.put("ServletPath", httpRequest.getServletPath()); return requestResult; }
From source file:cn.bc.web.util.DebugUtils.java
public static StringBuffer getDebugInfo(HttpServletRequest request, HttpServletResponse response) { @SuppressWarnings("rawtypes") Enumeration e;/* www. j a v a2s. co m*/ String name; StringBuffer html = new StringBuffer(); //session HttpSession session = request.getSession(); html.append("<div><b>session:</b></div><ul>"); html.append(createLI("Id", session.getId())); html.append(createLI("CreationTime", new Date(session.getCreationTime()).toString())); html.append(createLI("LastAccessedTime", new Date(session.getLastAccessedTime()).toString())); //session:attributes e = session.getAttributeNames(); html.append("<li>attributes:<ul>\r\n"); while (e.hasMoreElements()) { name = (String) e.nextElement(); html.append(createLI(name, String.valueOf(session.getAttribute(name)))); } html.append("</ul></li>\r\n"); html.append("</ul>\r\n"); //request html.append("<div><b>request:</b></div><ul>"); html.append(createLI("URL", request.getRequestURL().toString())); html.append(createLI("QueryString", request.getQueryString())); html.append(createLI("Method", request.getMethod())); html.append(createLI("CharacterEncoding", request.getCharacterEncoding())); html.append(createLI("ContentType", request.getContentType())); html.append(createLI("Protocol", request.getProtocol())); html.append(createLI("RemoteAddr", request.getRemoteAddr())); html.append(createLI("RemoteHost", request.getRemoteHost())); html.append(createLI("RemotePort", request.getRemotePort() + "")); html.append(createLI("RemoteUser", request.getRemoteUser())); html.append(createLI("ServerName", request.getServerName())); html.append(createLI("ServletPath", request.getServletPath())); html.append(createLI("ServerPort", request.getServerPort() + "")); html.append(createLI("Scheme", request.getScheme())); html.append(createLI("LocalAddr", request.getLocalAddr())); html.append(createLI("LocalName", request.getLocalName())); html.append(createLI("LocalPort", request.getLocalPort() + "")); html.append(createLI("Locale", request.getLocale().toString())); //request:headers e = request.getHeaderNames(); html.append("<li>Headers:<ul>\r\n"); while (e.hasMoreElements()) { name = (String) e.nextElement(); html.append(createLI(name, request.getHeader(name))); } html.append("</ul></li>\r\n"); //request:parameters e = request.getParameterNames(); html.append("<li>Parameters:<ul>\r\n"); while (e.hasMoreElements()) { name = (String) e.nextElement(); html.append(createLI(name, request.getParameter(name))); } html.append("</ul></li>\r\n"); html.append("</ul>\r\n"); //response html.append("<div><b>response:</b></div><ul>"); html.append(createLI("CharacterEncoding", response.getCharacterEncoding())); html.append(createLI("ContentType", response.getContentType())); html.append(createLI("BufferSize", response.getBufferSize() + "")); html.append(createLI("Locale", response.getLocale().toString())); html.append("<ul>\r\n"); return html; }
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 www. j av a2s . c o m*/ 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); }
From source file:org.iwethey.forums.web.HeaderInterceptor.java
/** * Load the request attributes with the User object (if authenticated) * and start time for the page for audit purposes. * <p>/*from w w w . ja v a2 s.c o m*/ * @param request The servlet request object. * @param response The servlet response object. * @param handler The request handler processing this request. */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Date now = new Date(); request.setAttribute("now", now); long start = now.getTime(); request.setAttribute("start", new Long(start)); Integer id = (Integer) WebUtils.getSessionAttribute(request, USER_ID_ATTRIBUTE); User user = null; if (id == null) { user = (User) WebUtils.getSessionAttribute(request, USER_ATTRIBUTE); if (user == null) { user = new User("Anonymous"); WebUtils.setSessionAttribute(request, USER_ATTRIBUTE, user); } } else { user = mUserManager.getUserById(id.intValue()); user.setLastPresent(new Date()); mUserManager.saveUserAttributes(user); } request.setAttribute("username", user.getNickname()); request.setAttribute(USER_ATTRIBUTE, user); System.out.println("Local Address = [" + request.getLocalAddr() + "]"); System.out.println("Local Name = [" + request.getLocalName() + "]"); System.out.println("Remote Address = [" + request.getRemoteAddr() + "]"); System.out.println("Remote Host = [" + request.getRemoteHost() + "]"); System.out.println("Remote Port = [" + request.getRemotePort() + "]"); System.out.println("Remote User = [" + request.getRemoteUser() + "]"); System.out.println("Context Path = [" + request.getContextPath() + "]"); System.out.println("===================="); Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; System.out.println("Cookie Domain = [" + cookie.getDomain() + "]"); System.out.println("Cookie Name = [" + cookie.getName() + "]"); System.out.println("Cookie Value = [" + cookie.getValue() + "]"); System.out.println("Cookie Expire = [" + cookie.getMaxAge() + "]"); System.out.println("===================="); if ("iwt_cookie".equals(cookie.getName())) { cookie.setMaxAge(1000 * 60 * 60 * 24 * 30 * 6); response.addCookie(cookie); } } } else { System.out.println("No cookies were found in the request"); } Cookie newCookie = new Cookie("iwt_cookie", "harrr2!"); newCookie.setPath(request.getContextPath()); newCookie.setDomain(request.getLocalName()); newCookie.setMaxAge(1000 * 60 * 60 * 24 * 30 * 6); response.addCookie(newCookie); request.setAttribute(HEADER_IMAGE_ATTRIBUTE, "/images/iwethey-lrpd-small.png"); return true; }
From source file:org.openmrs.module.sdmxhddataexport.web.controller.report.ReportDataElementController.java
@RequestMapping(value = "/module/sdmxhddataexport/downloadExecutedReport.form", method = RequestMethod.GET) public String downloadExecutedReport(@RequestParam(value = "reportId", required = false) Integer reportId, @RequestParam(value = "startDate", required = false) String startDate, @RequestParam(value = "endDate", required = false) String endDate, @RequestParam(value = "outputType", required = false) String outputType, HttpServletRequest request, HttpServletResponse response, Model model) throws ParseException, IOException { String u = request.getParameter("url"); System.out.print("i think it is a url - " + u); //String s=(u.split("/")[2]).split(":")[0]; String urlToRead = "http://" + u + request.getContextPath() + "/module/sdmxhddataexport/resultExecuteReport.form?reportId=" + reportId + "&startDate=" + startDate + "&endDate=" + endDate; // String urlToRead = "http://" + "127.0.0.1" + ":" // + request.getLocalPort() + request.getContextPath() // + "/module/sdmxhddataexport/resultExecuteReport.form?reportId=" // + reportId + "&startDate=" + startDate + "&endDate=" + endDate; URL url;// ww w .ja v a 2 s.c om System.out.println("http servlet request" + u + request.getLocalAddr() + "," + request.getLocalName()); HttpURLConnection conn; InputStream rd = null; String contents = ""; try { url = new URL(urlToRead); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); rd = conn.getInputStream(); byte[] bytes = new byte[1024]; int bytesRead; boolean firstRead = true; while ((bytesRead = rd.read(bytes)) != -1) { String str = new String(bytes); str = str.substring(0, bytesRead); //if(firstRead){ firstRead = false; str = str.replaceAll("^\\s+", ""); System.out.print(str); //} contents = contents.concat(str); } //rd.close(); } catch (Exception e) { e.printStackTrace(); } if (outputType.contentEquals("download")) { // File fil1=new File("/sdmx-temp-sdmx.xml"); // FileOutputStream fos = new FileOutputStream("sdmx-temp-sdmx.xml"); File file = File.createTempFile("sdmx", "report"); Writer output = new BufferedWriter(new FileWriter(file)); output.write(contents); output.flush(); // output = new BufferedWriter(new FileWriter(fil1)); // output.write(contents); // output.flush(); output.close(); System.out.println("these are contents ------------------------"); System.out.println(contents); System.out.println("these wre contents ------------------------"); response.setContentType("application/download"); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss"); response.setHeader("Content-Disposition", "attachment; filename=\"" + "sdmxhd-" + formatter.format(new Date()) + ".xml" + "\""); FileCopyUtils.copy(new FileInputStream(file), response.getOutputStream()); file.delete(); } if (outputType.equals("view")) { try { contents = transform(contents); } catch (Exception e) { System.out.println("some error" + contents); e.printStackTrace(); } model.addAttribute("contents", contents); System.out.println("Now contents---------------------------" + contents + ":"); return "/module/sdmxhddataexport/report/resultView"; } else if (outputType.equals("send")) { HttpSession httpSession = request.getSession(); String urlStr = Context.getAdministrationService().getGlobalProperty("sdmxhddataexport.reportUrl"); String[] paramName = { "report1" }; String[] paramVal = new String[10]; paramVal[0] = contents; try { String Response = HttpRestUtil.httpRestPost(urlStr, paramName, paramVal); System.out.println("Response:" + Response); String temp = "Report Sent Successfully"; httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, StringUtils.isBlank(temp) ? "sdmxhddataexport.dataElement.deleted" : temp); } catch (Exception e) { e.printStackTrace(); } } return "/module/sdmxhddataexport/report/list"; }
From source file:edu.harvard.iq.dvn.core.web.admin.OptionsPage.java
public String saveNetworkPrivilegedUsersPage() { HttpServletRequest request = (HttpServletRequest) this.getExternalContext().getRequest(); String hostName = request.getLocalName(); int port = request.getLocalPort(); String portStr = ""; if (port != 80) { portStr = ":" + port; }// w w w. ja va 2 s. com // Needed to send an approval email to approved creators String creatorUrl = "http://" + hostName + portStr + request.getContextPath() + "/faces/site/AddSitePage.xhtml"; privileges.save(creatorUrl); getVDCRenderBean().getFlash().put("successMessage", "Successfully updated network permissions."); tab2 = ""; return "/networkAdmin/NetworkOptionsPage.xhtml?faces-redirect=true&tab=permissions"; }