List of usage examples for javax.servlet.http HttpServletRequest getServerPort
public int getServerPort();
From source file:fr.insalyon.creatis.vip.core.server.rpc.ConfigurationServiceImpl.java
private URL getBaseURL() throws MalformedURLException { URL url = null;// w w w . j av a 2 s . c o m HttpServletRequest request = this.getThreadLocalRequest(); if ((request.getServerPort() == 80) || (request.getServerPort() == 443)) { url = new URL(request.getScheme() + "://" + request.getServerName() + request.getContextPath()); } else { url = new URL(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath()); } return url; }
From source file:com.aimluck.eip.modules.actions.ALSessionValidator.java
/** * * @param data/*from www .j av a2 s . c om*/ * @throws Exception */ @Override public void doPerform(RunData data) throws Exception { try { super.doPerform(data); } catch (Throwable other) { setOrgParametersForError(data); data.setScreenTemplate(JetspeedResources.getString(TurbineConstants.TEMPLATE_ERROR)); return; } // not login and can not connect database if (checkDbError(data)) { setOrgParametersForError(data); data.setScreenTemplate(ALConstants.DB_ERROR_TEMPLATE); return; } // ? // Cookie?ID???????? if (data.getRequest().isRequestedSessionIdFromURL()) { JetspeedLink jsLink = JetspeedLinkFactory.getInstance(data); String url = jsLink.getHomePage().toString().replaceAll(";.*", ""); data.setRedirectURI(url); return; } JetspeedUser loginuser = (JetspeedUser) data.getUser(); if (isLogin(loginuser)) { try { JetspeedSecurityCache.load(loginuser.getUserName()); } catch (Exception e1) { // login and can not connect database String message = e1.getMessage(); if (message != null && message.indexOf(ALConstants.DB_ERROR_DETECT) != -1) { setOrgParametersForError(data); String template = data.getParameters().get("template"); if (template.endsWith("DBError")) { data.setScreenTemplate(ALConstants.DB_ERROR_TEMPLATE); } else { ALEipUtils.redirectDBError(data); } return; } } } if (ALSessionUtils.isImageRequest(data)) { if (isLogin(loginuser)) { return; } } if (ALSessionUtils.isJsonScreen(data)) { if (isLogin(loginuser)) { return; } } if (data.getRequest().getAttribute(ALDigestAuthenticationFilter.REQUIRE_DIGEST_AUTH) != null) { HttpServletRequest hreq = data.getRequest(); HttpServletResponse hres = data.getResponse(); if (!isLogin(loginuser)) { String auth = hreq.getHeader("Authorization"); if (auth == null) { requireAuth(hres); return; } else { try { String decoded = decodeAuthHeader(auth); int pos = decoded.indexOf(":"); String username = decoded.substring(0, pos); String password = decoded.substring(pos + 1); JetspeedUser juser = JetspeedSecurity.login(username, password); if (juser != null && "F".equals(juser.getDisabled())) { JetspeedSecurity.saveUser(juser); } else { requireAuth(hres); return; } } catch (RuntimeException ex) { // RuntimeException requireAuth(hres); return; } catch (Exception ex) { requireAuth(hres); return; } } } if (isICalRequest(data)) { data.setScreenTemplate("ScheduleiCalScreen"); return; } else { hres.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } Context context = org.apache.turbine.services.velocity.TurbineVelocity.getContext(data); // for switching theme org by org setOrgParameters(data, context); // for preventing XSS on user name context.put("utils", new ALCommonUtils()); context.put("l10n", ALLocalizationUtils.createLocalization(data)); // Cookie????????? if (!isLogin(loginuser) && !data.getParameters().get("template").equals("CookieError")) { String username = data.getParameters().getString("username", ""); String password = data.getParameters().getString("password", ""); if (username.length() > 0) { if (ALCellularUtils.isSmartPhone(data) && "admin".equals(username)) { data.setUser(JetspeedSecurity.getAnonymousUser()); data.setMessage(ALLocalizationUtils.getl10n("LOGINACTION_LOGIN_ONLY_PC")); data.getUser().setHasLoggedIn(Boolean.FALSE); } else { try { loginuser = JetspeedSecurity.login(username, password); if (loginuser != null && "F".equals(loginuser.getDisabled())) { JetspeedSecurity.saveUser(loginuser); } else { data.setUser(JetspeedSecurity.getAnonymousUser()); data.setMessage(ALLocalizationUtils.getl10n("LOGINACTION_INVALIDATION_USER")); data.getUser().setHasLoggedIn(Boolean.FALSE); } } catch (LoginException e) { } } } } String externalLoginUrl = ALConfigService.get(Property.EXTERNAL_LOGIN_URL); boolean isScreenTimeout = false; if (!isLogin(loginuser) && JetspeedResources.getBoolean("automatic.logon.enable", false)) { if (data.getRequest().getCookies() != null) { String userName = data.getCookies().getString("username", ""); String loginCookieValue = data.getCookies().getString("logincookie", ""); if (userName.length() > 0 && loginCookieValue.length() > 0) { try { loginuser = JetspeedSecurity.getUser(userName); if (loginuser.getPerm("logincookie", "").equals(loginCookieValue)) { data.setUser(loginuser); loginuser.setHasLoggedIn(Boolean.TRUE); loginuser.updateLastLogin(); data.save(); } } catch (LoginException noSuchUser) { } catch (org.apache.jetspeed.services.security.UnknownUserException unknownUser) { logger.warn("Username from the cookie was not found: " + userName); } catch (Exception other) { logger.error("ALSessionValidator.doPerform", other); } } } } else if (!isLogin(loginuser) && !JetspeedResources.getBoolean("automatic.logon.enable", false)) { // ? ????????? // ??????????? String uri = data.getRequest().getRequestURI().trim(); String template = data.getScreenTemplate(); Class<?> cls = null; try { cls = Class.forName( new StringBuffer().append("com.aimluck.eip.modules.screens.").append(template).toString()); } catch (Exception e) { cls = null; } String newTemplate = null; if (cls != null) { if (Class.forName("com.aimluck.eip.modules.screens.ALJSONScreen").isAssignableFrom(cls)) { newTemplate = "ALJSONTimeoutScreen"; } else if (Class.forName("com.aimluck.eip.modules.screens.ALVelocityScreen") .isAssignableFrom(cls)) { newTemplate = "ALVelocityTimeoutScreen"; } } if (newTemplate != null) { isScreenTimeout = true; data.setScreenTemplate(newTemplate); // ? if (data.getSession() != null) { try { data.getSession().invalidate(); } catch (IllegalStateException ex) { logger.debug("???????"); } } } else { String contextPath = ServletContextLocator.get().getContextPath(); if ("/".equals(contextPath)) { contextPath = ""; } String portalPath = contextPath + "/portal"; if (!uri.equals(portalPath + "/") && !uri.equals(portalPath)) { data.setScreenTemplate("Timeout"); if (!"".equals(externalLoginUrl)) { // ?? data.setRedirectURI(externalLoginUrl); } StringBuffer sb = new StringBuffer(uri); int count = 0; String key = null; Enumeration<?> enu = data.getRequest().getParameterNames(); if (enu.hasMoreElements()) { sb.append("?"); } while (enu.hasMoreElements()) { if (count != 0) { sb.append("&"); } key = (String) enu.nextElement(); sb.append(key).append("=").append(data.getRequest().getParameter(key)); count = count + 1; } if (data.getUser() != null) { data.getUser().setTemp("redirect", StringEscapeUtils.escapeHtml(sb.toString())); context.put("alEipUtils", new ALEipUtils()); context.put("alEipManager", ALEipManager.getInstance()); } // ? if (data.getSession() != null) { try { data.getSession().invalidate(); } catch (IllegalStateException ex) { logger.debug("???????"); } } } } } JetspeedRunData jdata = null; try { jdata = (JetspeedRunData) data; } catch (ClassCastException e) { logger.error("The RunData object does not implement the expected interface, " + "please verify the RunData factory settings", e); return; } String language = data.getRequest().getParameter("js_language"); if (null != language) { loginuser.setPerm("language", language); } CustomLocalizationService locService = (CustomLocalizationService) ServiceUtil .getServiceByName(LocalizationService.SERVICE_NAME); Locale locale = locService.getLocale(data); if (locale == null) { locale = new Locale(TurbineResources.getString("locale.default.language", "en"), TurbineResources.getString("locale.default.country", "US")); } if (loginuser != null) { loginuser.setTemp("locale", locale); } String paramPortlet = jdata.getParameters().getString("js_peid"); if (paramPortlet != null && paramPortlet.length() > 0) { jdata.setJs_peid(paramPortlet); } // Ajax???????? if (!isScreenTimeout && !"".equals(externalLoginUrl)) { HttpServletRequest request = data.getRequest(); if (!isLogin(loginuser)) { StringBuilder buf = new StringBuilder(); buf.append(request.getScheme()).append("://").append(request.getServerName()); if (request.getServerPort() == 80 || request.getServerPort() == 443) { // } else { buf.append(":").append(request.getServerPort()); } buf.append(request.getRequestURI()); String queryString = request.getQueryString(); if (queryString != null && !"".equals(queryString)) { buf.append("?").append(queryString); } String url = buf.toString(); if (!url.equals(externalLoginUrl)) { data.setRedirectURI(externalLoginUrl); } } } if (isLogin(loginuser)) { ALPreExecuteService.migratePsml(data, context); boolean hasMessage = false; Map<String, Entry> portlets = ALEipUtils.getGlobalPortlets(data); Entry entry = portlets.get("Message"); if (entry != null) { if (entry.getId().equals(jdata.getJs_peid())) { hasMessage = true; } } String client = ALEipUtils.getClient(data); boolean push = (!"IPHONE".equals(client)) || hasMessage; HttpServletRequest request = ((JetspeedRunData) data).getRequest(); String requestUrl = request.getRequestURL().toString(); String checkActivityUrl = ALConfigService.get(Property.CHECK_ACTIVITY_URL); String interval = ALConfigService.get(Property.CHECK_ACTIVITY_INTERVAL); ALEipUser eipUser = ALEipUtils.getALEipUser(data); String orgId = Database.getDomainName(); String viewer = new StringBuilder(orgId).append(":").append(eipUser.getName().getValue()).toString(); ALGadgetContext gadgetContext = new ALGadgetContext(data, viewer, "1", "/", 0); String relayUrl = ALConfigService.get(Property.CHECK_ACTIVITY_RELAY_URL); String rpctoken = String.valueOf(System.nanoTime()); String checkUrl = new StringBuilder("".equals(checkActivityUrl) ? "check.html" : checkActivityUrl) .append("?").append("st=").append(gadgetContext.getSecureToken()).append("&parent=") .append(URLEncoder.encode(requestUrl, "utf-8")).append("&interval=").append(interval) .append("&push=").append(push ? 1 : 0).append("#rpctoken=").append(rpctoken).toString(); if (data.getSession() != null && Boolean.parseBoolean((String) data.getSession().getAttribute("changeToPc"))) { // PC? context.put("client", ALEipUtils.getClient(data)); } context.put("requestUrl", requestUrl); context.put("relayUrl", relayUrl); context.put("rpctoken", rpctoken); context.put("checkUrl", checkUrl); context.put("st", gadgetContext.getSecureToken()); context.put("hasAuthorityCustomize", ALEipUtils.getHasAuthority(data, context, ALAccessControlConstants.VALUE_ACL_UPDATE)); } }
From source file:csiro.pidsvc.mappingstore.action.ActionProxy.java
@Override public void run() { HttpClient httpClient = new DefaultHttpClient(); try {// www . j av a 2s . co m HttpServletRequest originalHttpRequest = _controller.getRequest(); HttpServletResponse originalHttpResponse = _controller.getResponse(); HttpGet httpGet = new HttpGet(getExpandedActionValue()); if (isTraceMode()) trace(httpGet.getRequestLine().toString()); // Pass-through HTTP headers. HashMap<String, String> hmHeaders = _controller.getHttpHeaders(); for (String header : hmHeaders.keySet()) { httpGet.addHeader(header, hmHeaders.get(header)); if (isTraceMode()) trace("\t" + header + ": " + hmHeaders.get(header)); } // Handle X-Original-URI HTTP header. if (!hmHeaders.containsKey("X-Original-URI")) { String originalUri = originalHttpRequest.getScheme() + "://" + originalHttpRequest.getServerName(); if (originalHttpRequest.getServerPort() != 80) originalUri += ":" + originalHttpRequest.getServerPort(); originalUri += _controller.getUri().getOriginalUriAsString(); httpGet.addHeader("X-Original-URI", originalUri); if (isTraceMode()) trace("\tX-Original-URI: " + originalUri); } // Get the data. HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); if (isTraceMode()) trace(response.getStatusLine().toString()); // Pass HTTP headers through. if (!isTraceMode()) originalHttpResponse.setStatus(response.getStatusLine().getStatusCode()); if (entity.getContentType() != null) { if (isTraceMode()) { trace("\tContent-Type: " + entity.getContentType().getValue()); trace("\tContent-Length: " + EntityUtils.toString(entity).getBytes().length); } else originalHttpResponse.setContentType(entity.getContentType().getValue()); } String headerName; for (Header header : response.getAllHeaders()) { headerName = header.getName(); if (headerName.equalsIgnoreCase("Expires") || headerName.equalsIgnoreCase("Cache-Control") || headerName.equalsIgnoreCase("Content-Type") || headerName.equalsIgnoreCase("Set-Cookie") || headerName.equalsIgnoreCase("Transfer-Encoding")) continue; if (isTraceMode()) trace("\t" + header.getName() + ": " + header.getValue()); else originalHttpResponse.addHeader(header.getName(), header.getValue()); } // Pass content through. if (!isTraceMode()) originalHttpResponse.getWriter().write(EntityUtils.toString(entity)); } catch (Exception e) { _logger.trace("Exception occurred while proxying HTTP request.", e); if (isTraceMode()) { Throwable cause = e.getCause(); trace("Set response status: 500; exception: " + (cause == null ? e.getMessage() : cause.getMessage())); } else Http.returnErrorCode(_controller.getResponse(), 500, e); } finally { httpClient.getConnectionManager().shutdown(); } }
From source file:com.jspxcms.core.setup.SetupServlet.java
private void database(HttpServletRequest request, HttpServletResponse response) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { long begin = System.currentTimeMillis(); String host = request.getParameter("host"); String port = request.getParameter("port"); String name = request.getParameter("name"); String user = request.getParameter("user"); String password = request.getParameter("password"); boolean isCreateDatabase = "true".equals(request.getParameter("isCreateDatabase")); String adminUsername = request.getParameter("adminUsername"); String adminPassword = request.getParameter("adminPassword"); String version = request.getParameter("version"); int serverPort = request.getServerPort(); String webPort = serverPort == 80 ? null : String.valueOf(serverPort); String contextPath = request.getContextPath(); if (isCreateDatabase) { createDatabase(host, port, name, user, password); } else {/* ww w .j a v a2s . c o m*/ alterDatabaseCharset(host, port, name, user, password); } createDatabaseTable(host, port, name, user, password, adminUsername, adminPassword, version, webPort, contextPath); copyFile(request, host, port, name, user, password); HttpSession session = request.getSession(); session.setAttribute("step", 2); long processed = System.currentTimeMillis() - begin; System.out.println("processed in: " + processed); }
From source file:org.alfresco.web.site.servlet.CSRFFilter.java
/** * Returns the current server's scheme, name & port * * @param request The http request/*w w w . j a v a 2 s .c o m*/ * @return the current server's scheme, name & port */ private String getServerString(HttpServletRequest request) { final String scheme = request.getScheme(); final int port = request.getServerPort(); String currentServerContext; if (("http".equals(scheme) && port == 80) || ("https".equals(scheme) && port == 443)) { currentServerContext = scheme + "://" + request.getServerName(); } else { currentServerContext = scheme + "://" + request.getServerName() + ':' + port; } return currentServerContext; }
From source file:org.dspace.app.util.SyndicationFeed.java
private String resolveURL(HttpServletRequest request, DSpaceObject dso) { // If no object given then just link to the whole repository, // since no offical handle exists so we have to use local resolution. if (dso == null) { if (baseURL == null) { if (request == null) { baseURL = ConfigurationManager.getProperty("dspace.url"); } else { baseURL = (request.isSecure()) ? "https://" : "http://"; baseURL += ConfigurationManager.getProperty("dspace.hostname"); baseURL += ":" + request.getServerPort(); baseURL += request.getContextPath(); }//from w w w. java 2s. co m } return baseURL; } // return a link to handle in repository else if (ConfigurationManager.getBooleanProperty("webui.feed.localresolve")) { return resolveURL(request, null) + "/handle/" + dso.getHandle(); } // link to the Handle server or other persistent URL source else { return HandleManager.getCanonicalForm(dso.getHandle()); } }
From source file:com.netflix.genie.web.controllers.JobRestControllerUnitTests.java
/** * Make sure directory forwarding happens when all conditions are met. * * @throws IOException on error// w w w. ja va 2 s . c o m * @throws ServletException on error * @throws GenieException on error */ @Test public void canHandleForwardJobOutputRequestWithSuccess() throws IOException, ServletException, GenieException { this.jobsProperties.getForwarding().setEnabled(true); final String jobId = UUID.randomUUID().toString(); final String forwardedFrom = null; final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); final HttpServletResponse response = Mockito.mock(HttpServletResponse.class); Mockito.doNothing().when(this.genieResourceHttpRequestHandler).handleRequest(request, response); final String jobHostName = UUID.randomUUID().toString(); Mockito.when(this.jobSearchService.getJobHost(jobId)).thenReturn(jobHostName); //Mock parts of the http request final String http = "http"; Mockito.when(request.getScheme()).thenReturn(http); final int port = 8080; Mockito.when(request.getServerPort()).thenReturn(port); final String requestURI = "/" + jobId + "/" + UUID.randomUUID().toString(); Mockito.when(request.getRequestURI()).thenReturn(requestURI); final Set<String> headerNames = Sets.newHashSet(HttpHeaders.ACCEPT); Mockito.when(request.getHeaderNames()).thenReturn(Collections.enumeration(headerNames)); Mockito.when(request.getHeader(HttpHeaders.ACCEPT)).thenReturn(MediaType.APPLICATION_JSON_VALUE); final String requestUrl = UUID.randomUUID().toString(); Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer(requestUrl)); //Mock parts of forward response final HttpResponse forwardResponse = Mockito.mock(HttpResponse.class); final StatusLine statusLine = Mockito.mock(StatusLine.class); Mockito.when(forwardResponse.getStatusLine()).thenReturn(statusLine); final int successCode = 200; Mockito.when(statusLine.getStatusCode()).thenReturn(successCode); final Header contentTypeHeader = Mockito.mock(Header.class); Mockito.when(contentTypeHeader.getName()).thenReturn(HttpHeaders.CONTENT_TYPE); Mockito.when(contentTypeHeader.getValue()).thenReturn(MediaType.TEXT_PLAIN_VALUE); Mockito.when(forwardResponse.getAllHeaders()).thenReturn(new Header[] { contentTypeHeader }); final String text = UUID.randomUUID().toString() + UUID.randomUUID().toString() + UUID.randomUUID().toString(); final ByteArrayInputStream bis = new ByteArrayInputStream(text.getBytes(UTF_8)); final HttpEntity entity = Mockito.mock(HttpEntity.class); Mockito.when(entity.getContent()).thenReturn(bis); Mockito.when(forwardResponse.getEntity()).thenReturn(entity); final ByteArrayServletOutputStream bos = new ByteArrayServletOutputStream(); Mockito.when(response.getOutputStream()).thenReturn(bos); final ClientHttpRequestFactory factory = Mockito.mock(ClientHttpRequestFactory.class); final ClientHttpRequest clientHttpRequest = Mockito.mock(ClientHttpRequest.class); Mockito.when(clientHttpRequest.execute()) .thenReturn(new MockClientHttpResponse(text.getBytes(UTF_8), HttpStatus.OK)); Mockito.when(clientHttpRequest.getHeaders()).thenReturn(new HttpHeaders()); Mockito.when(factory.createRequest(Mockito.any(), Mockito.any())).thenReturn(clientHttpRequest); final RestTemplate template = new RestTemplate(factory); final Registry registry = Mockito.mock(Registry.class); final Counter counter = Mockito.mock(Counter.class); Mockito.when(registry.counter(Mockito.anyString())).thenReturn(counter); final JobRestController jobController = new JobRestController(Mockito.mock(JobCoordinatorService.class), this.jobSearchService, Mockito.mock(AttachmentService.class), Mockito.mock(ApplicationResourceAssembler.class), Mockito.mock(ClusterResourceAssembler.class), Mockito.mock(CommandResourceAssembler.class), Mockito.mock(JobResourceAssembler.class), Mockito.mock(JobRequestResourceAssembler.class), Mockito.mock(JobExecutionResourceAssembler.class), Mockito.mock(JobSearchResultResourceAssembler.class), this.hostname, template, this.genieResourceHttpRequestHandler, this.jobsProperties, registry); jobController.getJobOutput(jobId, forwardedFrom, request, response); Assert.assertThat(new String(bos.toByteArray(), UTF_8), Matchers.is(text)); Mockito.verify(request, Mockito.times(1)).getHeader(HttpHeaders.ACCEPT); Mockito.verify(this.jobSearchService, Mockito.times(1)).getJobHost(Mockito.eq(jobId)); Mockito.verify(response, Mockito.never()).sendError(Mockito.anyInt()); Mockito.verify(this.genieResourceHttpRequestHandler, Mockito.never()).handleRequest(request, response); }
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 ww w . j av a 2 s .c o m*/ } URL reconstructedURL = new URL(request.getScheme(), request.getServerName(), request.getServerPort(), file); return (reconstructedURL.toString()).substring(request.getScheme().length(), (reconstructedURL.toString().length())); }
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 w w. j a v a2 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: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; // }/*www . ja v a2 s .co m*/ // if (queryString != null) { // url += "?"+queryString; // } return url; }