List of usage examples for javax.servlet.http HttpServletRequest getServerName
public String getServerName();
From source file:com.irets.datadownloader.SearchPropertyServlet.java
public String getUrl3(HttpServletRequest req) { String scheme = req.getScheme(); // http String serverName = req.getServerName(); // hostname.com int serverPort = req.getServerPort(); // 80 String contextPath = req.getContextPath(); // /mywebapp // String servletPath = req.getServletPath(); // /servlet/MyServlet // String pathInfo = req.getPathInfo(); // /a/b;c=123 // String queryString = req.getQueryString(); // d=789 // Reconstruct original requesting URL String url = scheme + "://" + serverName + ":" + serverPort + contextPath;//+servletPath; // if (pathInfo != null) { // url += pathInfo; // }// w w w .j a v a 2 s.c o m // if (queryString != null) { // url += "?"+queryString; // } return url; }
From source file:net.yacy.http.ProxyHandler.java
@Override public void handleRemote(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { sb.proxyLastAccess = System.currentTimeMillis(); RequestHeader proxyHeaders = ProxyHandler.convertHeaderFromJetty(request); setProxyHeaderForClient(request, proxyHeaders); final HTTPClient client = new HTTPClient(ClientIdentification.yacyProxyAgent); client.setTimout(timeout);// w ww . j a va 2 s . co m client.setHeader(proxyHeaders.entrySet()); client.setRedirecting(false); // send request try { String queryString = request.getQueryString() != null ? "?" + request.getQueryString() : ""; DigestURL digestURI = new DigestURL(request.getScheme(), request.getServerName(), request.getServerPort(), request.getRequestURI() + queryString); if (request.getMethod().equals(HeaderFramework.METHOD_GET)) { client.GET(digestURI, false); } else if (request.getMethod().equals(HeaderFramework.METHOD_POST)) { client.POST(digestURI, request.getInputStream(), request.getContentLength(), false); } else if (request.getMethod().equals(HeaderFramework.METHOD_HEAD)) { client.HEADResponse(digestURI, false); } else { throw new ServletException("Unsupported Request Method"); } HttpResponse clientresponse = client.getHttpResponse(); int statusCode = clientresponse.getStatusLine().getStatusCode(); final ResponseHeader responseHeaderLegacy = new ResponseHeader(statusCode, clientresponse.getAllHeaders()); if (responseHeaderLegacy.isEmpty()) { throw new SocketException(clientresponse.getStatusLine().toString()); } cleanResponseHeader(clientresponse); // reserver cache entry final net.yacy.crawler.retrieval.Request yacyRequest = new net.yacy.crawler.retrieval.Request(null, digestURI, null, //requestHeader.referer() == null ? null : new DigestURI(requestHeader.referer()).hash(), "", responseHeaderLegacy.lastModified(), sb.crawler.defaultProxyProfile.handle(), 0, sb.crawler.defaultProxyProfile.timezoneOffset()); //sizeBeforeDelete < 0 ? 0 : sizeBeforeDelete); final Response yacyResponse = new Response(yacyRequest, null, responseHeaderLegacy, sb.crawler.defaultProxyProfile, false, null); final String storeError = yacyResponse.shallStoreCacheForProxy(); final boolean storeHTCache = yacyResponse.profile().storeHTCache(); final String supportError = TextParser.supports(yacyResponse.url(), yacyResponse.getMimeType()); if ( /* * Now we store the response into the htcache directory if * a) the response is cacheable AND */ (storeError == null) && /* * b) the user has configured to use the htcache OR * c) the content should be indexed */ ((storeHTCache) || (supportError != null))) { // we don't write actually into a file, only to RAM, and schedule writing the file. int l = responseHeaderLegacy.size(); final ByteArrayOutputStream byteStream = new ByteArrayOutputStream((l < 32) ? 32 : l); final OutputStream toClientAndMemory = new MultiOutputStream( new OutputStream[] { response.getOutputStream(), byteStream }); convertHeaderToJetty(clientresponse, response); response.setStatus(statusCode); client.writeTo(toClientAndMemory); // cached bytes storeToCache(yacyResponse, byteStream.toByteArray()); } else { // no caching /*if (log.isFine()) log.logFine(reqID +" "+ url.toString() + " not cached." + " StoreError=" + ((storeError==null)?"None":storeError) + " StoreHTCache=" + storeHTCache + " SupportError=" + supportError);*/ convertHeaderToJetty(clientresponse, response); response.setStatus(statusCode); if (statusCode == HttpServletResponse.SC_OK) { // continue to serve header to client e.g. HttpStatus = 302 (while skiping content) client.writeTo(response.getOutputStream()); // may throw exception on httpStatus=302 while gzip encoded inputstream } } } catch (final SocketException se) { throw new ServletException("Socket Exception: " + se.getMessage()); } finally { client.finish(); } // we handled this request, break out of handler chain logProxyAccess(request); baseRequest.setHandled(true); }
From source file:jp.or.openid.eiwg.scim.servlet.ServiceProviderConfigs.java
/** * GET?//from w ww . j a v a2 s. com * * @param request * @param response ? * @throws ServletException * @throws IOException */ protected void doGet(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 { // [draft-ietf-scim-api-13 3.2.2.1. Query Endpoints] // Queries MAY be performed against a SCIM resource object, a resource // type endpoint, or a SCIM server root. // ServiceProviderConfigs ?????????? // location?URL? String location = request.getScheme() + "://" + request.getServerName(); int serverPort = request.getServerPort(); if (serverPort != 80 && serverPort != 443) { location += ":" + Integer.toString(serverPort); } location += request.getContextPath(); // ?? @SuppressWarnings("unchecked") Map<String, Object> serviceProviderConfigsObject = (Map<String, Object>) context .getAttribute("ServiceProviderConfigs"); try { ObjectMapper mapper = new ObjectMapper(); StringWriter writer = new StringWriter(); mapper.writeValue(writer, serviceProviderConfigsObject); String serviceProviderConfigs = writer.toString(); serviceProviderConfigs = String.format(serviceProviderConfigs, location); response.setContentType("application/scim+json;charset=UTF-8"); response.setHeader("Location", request.getRequestURL().toString()); PrintWriter out = response.getWriter(); out.println(serviceProviderConfigs); } catch (IOException e) { e.printStackTrace(); } } }
From source file:es.itecban.deployment.executionmanager.gui.swf.service.DeletePlanCreationManager.java
private String getXMLDependencyGraphURL(HttpServletRequest request, String unitName, String unitVersion, String selectedEnv, String containerGraphList) throws Exception { String file = request.getRequestURI(); file = file.substring(0, file.indexOf("/", file.indexOf("/") + 1)); if (request.getQueryString() != null) { // file += '?' + // request.getQueryString()+"&_eventId_getXMLGraph=true&name="+unitName+"&version="+unitVersion+"&environment="+selectedEnv; file += "/unitInverseDependencies.htm" + '?' + "name=" + unitName + "&version=" + unitVersion + "&environment=" + selectedEnv.replace(' ', '+') + "&justGraph=true" + "&containerGraphList=" + containerGraphList;/*from w ww. ja v a 2 s . c om*/ } URL reconstructedURL = new URL(request.getScheme(), request.getServerName(), request.getServerPort(), file); return (reconstructedURL.toString()).substring(request.getScheme().length(), (reconstructedURL.toString().length())); }
From source file:fr.paris.lutece.plugins.document.web.DocumentContentJspBean.java
/** * Return the view of an document before printing * @param request Http request/*from w ww .j av a2 s .c om*/ * @return the HTML page */ public String getPrintDocumentPage(HttpServletRequest request) { String strDocumentId = request.getParameter(PARAMETER_DOCUMENT_ID); int nDocumentId = IntegerUtils.convert(strDocumentId); Document document = DocumentHome.findByPrimaryKeyWithoutBinaries(nDocumentId); if (document == null) { return StringUtils.EMPTY; } DocumentType type = DocumentTypeHome.findByPrimaryKey(document.getCodeDocumentType()); XmlTransformerService xmlTransformerService = new XmlTransformerService(); String strPreview = xmlTransformerService.transformBySourceWithXslCache(document.getXmlValidatedContent(), type.getContentServiceXslSource(), XSL_UNIQUE_PREFIX + type.getContentServiceStyleSheetId(), null, null); Map<String, Object> model = new HashMap<String, Object>(); model.put(MARK_BASE_URL, AppPathService.getBaseUrl(request)); model.put(MARK_PREVIEW, strPreview); model.put(MARK_PORTAL_DOMAIN, request.getServerName()); HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_PAGE_PRINT_DOCUMENT, request.getLocale(), model); return template.getHtml(); }
From source file:com.sun.socialsite.business.DefaultURLStrategy.java
/** * Get the appropriate Gadget Server URL for the specified request. * The returned URL will not end with a trailing slash. If the * "socialsite.gadgets.server.url" property is populated and contains * any wildcards ("*"), they will be replaced with the specified * replacementValue./*from w w w . ja va 2 s . c o m*/ */ public String getGadgetServerURL(HttpServletRequest request, String replacementValue) { StringBuilder sb = new StringBuilder(); try { String propVal = Config.getProperty("socialsite.gadgets.server.url"); if (propVal != null) { String actualValue = propVal.replace("*", replacementValue); sb.append(actualValue); } else { if (Config.getBooleanProperty("socialsite.gadgets.use-cookie-jail")) { // For now, we'll use an IP-based URL to provide a cookie jail InetAddress addr = InetAddress.getByName(request.getServerName()); if (addr instanceof Inet6Address) { sb.append(request.getScheme()).append("://[").append(addr.getHostAddress()).append("]"); } else { sb.append(request.getScheme()).append("://").append(addr.getHostAddress()); } } else { sb.append(request.getScheme()).append("://").append(request.getServerName()); } switch (request.getServerPort()) { case 80: if (!(request.getScheme().equalsIgnoreCase("http"))) { sb.append(":").append(request.getServerPort()); } break; case 443: if (!(request.getScheme().equalsIgnoreCase("https"))) { sb.append(":").append(request.getServerPort()); } break; default: sb.append(":").append(request.getServerPort()); } sb.append(request.getContextPath()); sb.append("/gadgets"); } } catch (Exception e) { log.warn(e); } // We don't want our result to end with a slash while (sb.charAt(sb.length() - 1) == '/') { sb.deleteCharAt(sb.length() - 1); } return sb.toString(); }
From source file:it.jugpadova.blo.EventBo.java
@RemoteMethod public void updateBadgePanel(String continent, String country, String jugName, String pastEvents, String orderByDate, String jebShowJUGName, String jebShowCountry, String jebShowDescription, String jebShowParticipants, String badgeStyle, String locale, String maxResults) { WebContext wctx = WebContextFactory.get(); HttpServletRequest req = wctx.getHttpServletRequest(); ScriptSession session = wctx.getScriptSession(); Util util = new Util(session); java.text.DateFormat dateFormat = java.text.DateFormat.getDateInstance(java.text.DateFormat.DEFAULT, new Locale(locale)); java.lang.String baseUrl = "http://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath();//from ww w. j a va 2 s . c o m it.jugpadova.bean.EventSearch eventSearch = new it.jugpadova.bean.EventSearch(); eventSearch.setContinent(continent); eventSearch.setCountry(country); eventSearch.setJugName(jugName); eventSearch.setPastEvents(java.lang.Boolean.parseBoolean(pastEvents)); eventSearch.setOrderByDate(orderByDate); if (StringUtils.isNotBlank(maxResults)) { try { eventSearch.setMaxResults(new Integer(maxResults)); } catch (NumberFormatException numberFormatException) { /* ignore it */ } } java.util.List<it.jugpadova.po.Event> events = this.search(eventSearch); boolean showJUGName = java.lang.Boolean.parseBoolean(jebShowJUGName); boolean showCountry = java.lang.Boolean.parseBoolean(jebShowCountry); boolean showDescription = java.lang.Boolean.parseBoolean(jebShowDescription); boolean showParticipants = java.lang.Boolean.parseBoolean(jebShowParticipants); util.setValue("badgeCode", this.getBadgePageCode(baseUrl, continent, country, jugName, pastEvents, orderByDate, jebShowJUGName, jebShowCountry, jebShowDescription, jebShowParticipants, badgeStyle, locale, maxResults)); util.setValue("badgePreview", this.getBadgeHtmlCode(events, dateFormat, baseUrl, showJUGName, showCountry, showDescription, showParticipants, badgeStyle, locale)); }
From source file:io.druid.security.kerberos.DruidKerberosAuthenticationHandler.java
@Override public AuthenticationToken authenticate(HttpServletRequest request, final HttpServletResponse response) throws IOException, AuthenticationException { AuthenticationToken token = null;/* w w w .j av a2 s .c om*/ String authorization = request .getHeader(org.apache.hadoop.security.authentication.client.KerberosAuthenticator.AUTHORIZATION); if (authorization == null || !authorization .startsWith(org.apache.hadoop.security.authentication.client.KerberosAuthenticator.NEGOTIATE)) { return null; } else { authorization = authorization.substring( org.apache.hadoop.security.authentication.client.KerberosAuthenticator.NEGOTIATE.length()) .trim(); final Base64 base64 = new Base64(0); final byte[] clientToken = base64.decode(authorization); final String serverName = request.getServerName(); try { token = Subject.doAs(serverSubject, new PrivilegedExceptionAction<AuthenticationToken>() { @Override public AuthenticationToken run() throws Exception { AuthenticationToken token = null; GSSContext gssContext = null; GSSCredential gssCreds = null; try { gssCreds = gssManager.createCredential( gssManager.createName(KerberosUtil.getServicePrincipal("HTTP", serverName), KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL")), GSSCredential.INDEFINITE_LIFETIME, new Oid[] { KerberosUtil.getOidInstance("GSS_SPNEGO_MECH_OID"), KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID") }, GSSCredential.ACCEPT_ONLY); gssContext = gssManager.createContext(gssCreds); byte[] serverToken = gssContext.acceptSecContext(clientToken, 0, clientToken.length); if (serverToken != null && serverToken.length > 0) { String authenticate = base64.encodeToString(serverToken); response.setHeader( org.apache.hadoop.security.authentication.client.KerberosAuthenticator.WWW_AUTHENTICATE, org.apache.hadoop.security.authentication.client.KerberosAuthenticator.NEGOTIATE + " " + authenticate); } if (!gssContext.isEstablished()) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); log.trace("SPNEGO in progress"); } else { String clientPrincipal = gssContext.getSrcName().toString(); KerberosName kerberosName = new KerberosName(clientPrincipal); String userName = kerberosName.getShortName(); token = new AuthenticationToken(userName, clientPrincipal, getType()); response.setStatus(HttpServletResponse.SC_OK); log.trace("SPNEGO completed for principal [%s]", clientPrincipal); } } finally { if (gssContext != null) { gssContext.dispose(); } if (gssCreds != null) { gssCreds.dispose(); } } return token; } }); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } else { throw new AuthenticationException(ex.getException()); } } } return token; }
From source file:com.wordpress.metaphorm.authProxy.hook.AuthProxyServletFilter.java
private boolean serveRequest(HttpServletRequest servletReq, HttpServletResponse servletResp) throws OAuthMessageSignerException, OAuthNotAuthorizedException, OAuthExpectationFailedException, OAuthCommunicationException, IOException, MalformedURLException, UnsupportedEncodingException, ExpiredStateException, OAuthProviderConfigurationException, ProtocolNotSupportedException { _log.debug("Acting as forwarding proxy to " + servletReq.getServerName() + " !"); // Get the oAuthState linked to the userToken (by header) or HTTP session ID OAuthState oAuthState = getOAuthState(servletReq, servletResp); AuthProxyConnection uRLConn = new OAuthProxyConnectionImpl(servletReq, AuthProxyConnectionFactory.getFactory(servletReq, oAuthState)); //AuthProxyConnectionFactory.getFactory(servletReq, oAuthState).getAuthProxyConnection(); try {//from w w w. j av a 2s . c o m String transformHeader = servletReq.getHeader("transform-response-to"); if (transformHeader == null) transformHeader = servletReq.getParameter("transform-response-to"); uRLConn.connect(); servletResp.setStatus(uRLConn.getResponseCode()); Map<String, List<String>> headerMap = uRLConn.getResponseHeaders(); String acceptEncodingHeaderValue = servletReq .getHeader(HttpConstants.STRING_ACCEPT_ENCODING_HEADER_NAME); boolean supportGzip = acceptEncodingHeaderValue != null && acceptEncodingHeaderValue.contains("gzip"); boolean gzipped = false; { List<String> contentEncoding = headerMap.get(HttpConstants.STRING_CONTENT_ENCODING_HEADER_NAME); if (contentEncoding != null && contentEncoding.size() == 1 && contentEncoding.get(0).contains("gzip")) gzipped = true; } boolean proxyContentUntouched = (transformHeader == null && (!gzipped || (gzipped && supportGzip))); _log.debug("Preserve content length & encoding headers? " + proxyContentUntouched); for (String headerName : headerMap.keySet()) { // Discard content compression / encoding headers if the proxied response will be manipulated later // If so, let the Servlet container add appropriate replacement headers if (!proxyContentUntouched) { if (headerName.equalsIgnoreCase(HttpConstants.STRING_CONTENT_LENGTH_HEADER_NAME)) continue; if (headerName.equalsIgnoreCase(HttpConstants.STRING_CONTENT_TYPE_HEADER_NAME)) continue; if (headerName.equalsIgnoreCase(HttpConstants.STRING_CONTENT_ENCODING_HEADER_NAME)) continue; } for (String headerValue : headerMap.get(headerName)) { servletResp.setHeader(headerName, headerValue); _log.debug(" Set header \"" + headerName + "\" = \"" + headerValue + "\""); } } InputStream in = uRLConn.getInputStream(); if (in != null) { if (transformHeader != null) { _log.debug("Transforming JSON to XML"); String jsonContentType = uRLConn.getContentType(); String jsonCharSet = (jsonContentType.indexOf("charset=") > -1 ? jsonContentType.substring(jsonContentType.indexOf("charset=") + "charset=".length()) : ""); _log.debug("JSON response character set was " + jsonCharSet); servletResp.setContentType( "application/xml" + (jsonCharSet.length() > 0 ? "; charset=" + jsonCharSet : "")); String json = sinkInputStream(in, servletResp.getCharacterEncoding()); Utils.writeJSONAsXML(json, servletResp.getWriter()); } else { _log.debug("Serving response.."); // Proxy content type hearder servletResp.setContentType(uRLConn.getContentType()); OutputStream out; // No transformation necessary, attempt to proxy on Content-Length header int byteCount = 0; int i; if (!proxyContentUntouched) { if (gzipped) { _log.debug("Proxy endpoint content is GZipped"); in = new GZIPInputStream(in); } if (supportGzip) { _log.debug("GZipping response..."); servletResp.setHeader(HttpConstants.STRING_CONTENT_ENCODING_HEADER_NAME, "gzip"); out = servletResp.getOutputStream(); GZIPOutputStream gzipOut = new GZIPOutputStream(out); streamBytes(in, gzipOut, byteCount); } else { _log.debug("Writing an uncompressed response..."); out = servletResp.getOutputStream(); streamBytes(in, out, byteCount); } } else { _log.debug("Tunnelling proxy endpoint content untouched..."); out = servletResp.getOutputStream(); streamBytes(in, out, byteCount); } out.flush(); } } return true; } catch (RedirectRequiredException e) { if (oAuthState instanceof HttpSessionOAuthStateImpl || (oAuthState instanceof OAuthStateManager.ManagedOAuthState && ((OAuthStateManager.ManagedOAuthState) oAuthState).getManagedOAuthState() .equals(HttpSessionOAuthStateImpl.class))) { _log.debug("About to issue HTTP redirect to: " + e.getURL().toString()); servletResp.sendRedirect(e.getURL().toString()); return true; } else { String xmlResp = "<?xml version=\"1.0\"?>" + "<oauth><authorisation_needed><url>" + e.getURL().toString().replaceAll("&", "&") .replaceAll("<", "<").replaceAll(">", ">") + "</url></authorisation_needed></oauth>"; _log.debug("About to write XML: " + xmlResp); servletResp.setStatus(200); servletResp.setContentType("application/xml"); servletResp.getWriter().write(xmlResp); return true; } } }
From source file:com.bodybuilding.turbine.servlet.ClusterListServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {// www .ja v a 2 s.c o m response.setHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate"); response.setHeader("Pragma", "no-cache"); boolean preferPrivateAddress = request.getParameter("preferPrivateAddress") != null; String servletPathRegex = Pattern.quote(request.getServletPath()); Set<String> clusterNames = ClusterListUtil.getClusterNames(); Optional<String> dashboardUrl = getDashboardUrl(getServletContext(), request); String turbinePath = getTurbineMapping(getServletContext()); String turbineBaseUrl; if (preferPrivateAddress && getPrivateAddress().isPresent()) { String requestURL = request.getRequestURL().toString(); requestURL = requestURL.replace(request.getServerName(), getPrivateAddress().get()); turbineBaseUrl = requestURL.replaceFirst(servletPathRegex, turbinePath + "?cluster="); } else { turbineBaseUrl = request.getRequestURL().toString().replaceFirst(servletPathRegex, turbinePath + "?cluster="); } log.debug("Using turbine URL: {}", turbineBaseUrl); log.debug("Using dashboard URL: {}", dashboardUrl); ClusterMonitorFactory<?> clusterMonitorFactory = PluginsFactory.getClusterMonitorFactory(); List<ClusterInfo> clusters = clusterNames.stream().filter(c -> { ClusterMonitor<? extends TurbineData> m = clusterMonitorFactory.getClusterMonitor(c); if (m == null) { log.debug("Cluster {} does not have a ClusterMonitor", c); } return m != null; }).map(c -> { String turbineUrl = turbineBaseUrl + encodeUrl(c); if (dashboardUrl.isPresent()) { String link = dashboardUrl.get() + encodeUrl(turbineBaseUrl + c) + "&title=" + encodeUrl(c); return new ClusterInfo(c, turbineUrl, link); } else { return new ClusterInfo(c, turbineUrl); } }).collect(Collectors.toList()); response.setHeader("Content-Type", "application/json;charset=UTF-8"); OBJECT_MAPPER.writeValue(response.getOutputStream(), clusters); response.getOutputStream().flush(); } catch (Exception e) { log.error("Error returning list of clusters", e); } }