List of usage examples for javax.servlet.http HttpServletRequest getServerName
public String getServerName();
From source file:be.fedict.eid.idp.sp.protocol.saml2.AuthenticationRequestServlet.java
/** * {@inheritDoc}//from w ww.jav a2 s .c o m */ @SuppressWarnings("unchecked") @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LOG.debug("doGet"); String idpDestination; String relayState; KeyStore.PrivateKeyEntry spIdentity = null; String language; AuthenticationRequestService service = this.authenticationRequestServiceLocator.locateService(); if (null != service) { idpDestination = service.getIdPDestination(); relayState = service.getRelayState(request.getParameterMap()); spIdentity = service.getSPIdentity(); language = service.getLanguage(); } else { idpDestination = this.idpDestination; relayState = null; language = this.language; } // sp-destination String spDestination = null; if (null != service) { spDestination = service.getSPDestination(); } if (null == spDestination) { // not provided by the service, check web.xml... if (null != this.spDestination) { spDestination = this.spDestination; } else { spDestination = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + this.spDestinationPage; } } // issuer String issuer = null; if (null != service) { issuer = service.getIssuer(); } if (null == issuer) { issuer = spDestination; } // generate and send an authentication request AuthnRequest authnRequest = AuthenticationRequestUtil.sendRequest(issuer, idpDestination, spDestination, relayState, spIdentity, response, language); // save state on session setRequestIssuer(authnRequest.getIssuer().getValue(), request.getSession()); setRequestId(authnRequest.getID(), request.getSession()); setRecipient(authnRequest.getAssertionConsumerServiceURL(), request.getSession()); setRelayState(relayState, request.getSession()); }
From source file:com.flexive.shared.FxContext.java
/** * Constructor//from w w w . j a va 2s . com * * @param request the request * @param divisionId the division * @param isWebdav true if this is an webdav request * @param forceSession */ private FxContext(HttpServletRequest request, int divisionId, boolean isWebdav, boolean forceSession) { final HttpSession session = request.getSession(forceSession); this.sessionID = session != null ? session.getId() : null; this.requestURI = request.getRequestURI(); this.contextPath = request.getContextPath(); this.serverName = request.getServerName(); this.serverPort = request.getServerPort(); this.requestUriNoContext = request.getRequestURI().substring(request.getContextPath().length()); this.webDAV = isWebdav; if (this.webDAV) { // Cut away servlet path, eg. "/webdav/" this.requestUriNoContext = this.requestUriNoContext.substring(request.getServletPath().length()); } this.globalAuthenticated = session != null && session.getAttribute(ADMIN_AUTHENTICATED) != null; //get the real remote host incase a proxy server is used String forwardedFor = request.getHeader("x-forwarded-for"); if (forwardedFor != null && !StringUtils.isBlank(String.valueOf(forwardedFor))) { final int clientSplit = forwardedFor.indexOf(','); final String clientIp = clientSplit == -1 ? forwardedFor : forwardedFor.substring(0, clientSplit); this.remoteHost = clientIp.replace("[", "").replace("]", ""); } else { this.remoteHost = request.getRemoteAddr(); } this.division = divisionId; initFormatters(); }
From source file:es.itecban.deployment.executionmanager.gui.swf.service.CommonCreationManager.java
public 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 a2s. 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:net.daw.control.upload.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// ww w . j a va2 s . c om * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { String name = ""; String strMessage = ""; HashMap<String, String> hash = new HashMap<>(); if (ServletFileUpload.isMultipartContent(request)) { try { List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()) .parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { name = new File(item.getName()).getName(); item.write(new File(".//..//webapps//images//" + name)); } else { hash.put(item.getFieldName(), item.getString()); } } Gson oGson = new Gson(); Map<String, String> data = new HashMap<>(); Iterator it = hash.entrySet().iterator(); while (it.hasNext()) { Map.Entry e = (Map.Entry) it.next(); data.put(e.getKey().toString(), e.getValue().toString()); } data.put("imglink", "http://" + request.getServerName() + ":" + request.getServerPort() + "/images/" + name); out.print("{\"status\":200,\"message\":" + oGson.toJson(data) + "}"); } catch (Exception ex) { strMessage += "File Upload Failed: " + ex; out.print("{\"status\":500,\"message\":\"" + strMessage + "\"}"); } } else { strMessage += "Only serve file upload requests"; out.print("{\"status\":500,\"message\":\"" + strMessage + "\"}"); } } }
From source file:org.frontcache.FrontCacheEngine.java
/** * Works for Servlets and ServletFilters * /*from w ww. ja v a 2 s . c o m*/ * @param servletRequest * @param servletResponse * @param filterChain */ private RequestContext init(HttpServletRequest servletRequest, HttpServletResponse servletResponse, FilterChain filterChain) { RequestContext context = new RequestContext(); context.setFrontCacheId(fcHostId); context.setRequest(servletRequest); context.setResponse(servletResponse); String uri = FCUtils.buildRequestURI(servletRequest); if (-1 < uri.indexOf(";jsessionid=")) // remove JSESSIONID from URI uri = uri.replaceAll(";jsessionid=.*?(?=\\?|$)", ""); context.setRequestURI(uri); String queryString = servletRequest.getQueryString(); // FCUtils.getQueryString(servletRequest, context); queryString = (null == queryString) ? "" : "?" + queryString; context.setRequestQueryString(queryString); context.setFrontCacheHost(servletRequest.getServerName()); context.setFrontCacheHttpPort(frontcacheHttpPort); context.setFrontCacheHttpsPort(frontcacheHttpsPort); DomainContext domainContex = getDomainContext(context.getRequest().getServerName()); context.setDomainContext(domainContex); String protocol = "https".equalsIgnoreCase(servletRequest.getScheme()) ? "https" : "http"; context.setFrontCacheProtocol(protocol); context.setOriginURL(getOriginUrl(context)); if (logToHeadersConfig || "true".equalsIgnoreCase(servletRequest.getHeader(FCHeaders.X_FRONTCACHE_TRACE))) { context.setLogToHTTPHeaders(); } String requestId = servletRequest.getHeader(FCHeaders.X_FRONTCACHE_REQUEST_ID); String requestType = FCHeaders.COMPONENT_INCLUDE; String includeLevelStr = servletRequest.getHeader(FCHeaders.X_FRONTCACHE_INCLUDE_LEVEL); if (null == requestId) { requestId = UUID.randomUUID().toString(); requestType = FCHeaders.COMPONENT_TOPLEVEL; } else { // can be include // or top_level (e.g. FC1 in scenario browser -> FC2 -> FC1 -> app ) if ("0".equals(includeLevelStr)) // it's second level FC (e.g. FC1 in scenario browser -> FC2 -> FC1 -> app ) { requestType = FCHeaders.COMPONENT_TOPLEVEL; } else { if (null != servletRequest.getHeader(FCHeaders.X_FRONTCACHE_ASYNC_INCLUDE)) requestType = FCHeaders.COMPONENT_ASYNC_INCLUDE; else requestType = FCHeaders.COMPONENT_INCLUDE; } context.setRequestFromFrontcache(); } if (null == includeLevelStr) includeLevelStr = INCLUDE_LEVEL_TOP_LEVEL; // default (top level) context.setIncludeLevel(includeLevelStr); // top level context.setRequestId(requestId); context.setRequestType(requestType); context.setClientType(getClientType(servletRequest, domainContex.getDomain())); // client type = bot | browser based on User-Agent Header and bots.conf if (null != filterChain) context.setFilterChain(filterChain); return context; }
From source file:org.jasig.cas.web.report.StatisticsController.java
/** * Handles the request.//from w w w . j a v a 2s . c o m * * @param httpServletRequest the http servlet request * @param httpServletResponse the http servlet response * @return the model and view * @throws Exception the exception */ @RequestMapping(method = RequestMethod.GET) protected ModelAndView handleRequestInternal(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) throws Exception { final ModelAndView modelAndView = new ModelAndView(MONITORING_VIEW_STATISTICS); modelAndView.addObject("startTime", this.upTimeStartDate); final double difference = System.currentTimeMillis() - this.upTimeStartDate.getTime(); modelAndView .addObject("upTime", calculateUptime(difference, new LinkedList<Integer>(Arrays.asList(NUMBER_OF_MILLISECONDS_IN_A_DAY, NUMBER_OF_MILLISECONDS_IN_AN_HOUR, NUMBER_OF_MILLISECONDS_IN_A_MINUTE, NUMBER_OF_MILLISECONDS_IN_A_SECOND, 1)), new LinkedList<String>( Arrays.asList("day", "hour", "minute", "second", "millisecond")))); modelAndView.addObject("totalMemory", convertToMegaBytes(Runtime.getRuntime().totalMemory())); modelAndView.addObject("maxMemory", convertToMegaBytes(Runtime.getRuntime().maxMemory())); modelAndView.addObject("freeMemory", convertToMegaBytes(Runtime.getRuntime().freeMemory())); modelAndView.addObject("availableProcessors", Runtime.getRuntime().availableProcessors()); modelAndView.addObject("serverHostName", httpServletRequest.getServerName()); modelAndView.addObject("serverIpAddress", httpServletRequest.getLocalAddr()); modelAndView.addObject("casTicketSuffix", this.casTicketSuffix); int unexpiredTgts = 0; int unexpiredSts = 0; int expiredTgts = 0; int expiredSts = 0; try { final Collection<Ticket> tickets = this.centralAuthenticationService.getTickets(TruePredicate.INSTANCE); for (final Ticket ticket : tickets) { if (ticket instanceof ServiceTicket) { if (ticket.isExpired()) { expiredSts++; } else { unexpiredSts++; } } else { if (ticket.isExpired()) { expiredTgts++; } else { unexpiredTgts++; } } } } catch (final UnsupportedOperationException e) { logger.trace("The ticket registry doesn't support this information."); } modelAndView.addObject("unexpiredTgts", unexpiredTgts); modelAndView.addObject("unexpiredSts", unexpiredSts); modelAndView.addObject("expiredTgts", expiredTgts); modelAndView.addObject("expiredSts", expiredSts); modelAndView.addObject("pageTitle", modelAndView.getViewName()); return modelAndView; }
From source file:com.viewer.controller.ViewerController.java
@RequestMapping(value = "/GetImageUrls", method = RequestMethod.POST, headers = { "Content-type=application/json" }) @ResponseBody// w w w .jav a 2 s . co m public GetImageUrlsResponse GetImageUrls(@RequestBody GetImageUrlsParameters parameters, HttpServletRequest request) throws Exception { try { if (com.viewer.model.helper.DotNetToJavaStringHelper.isNullOrEmpty(parameters.getPath())) { GetImageUrlsResponse empty = new GetImageUrlsResponse(); empty.imageUrls = new String[0]; return empty; } DocumentInfoOptions documentInfoOptions = new DocumentInfoOptions(parameters.getPath()); DocumentInfoContainer documentInfoContainer = _imageHandler.getDocumentInfo(documentInfoOptions); int[] pageNumbers = new int[documentInfoContainer.getPages().size()]; int count = 0; for (PageData page : documentInfoContainer.getPages()) { pageNumbers[count] = page.getNumber(); count++; } String applicationHost = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort(); String[] imageUrls = ImageUrlHelper.GetImageUrls(applicationHost, pageNumbers, parameters); GetImageUrlsResponse result = new GetImageUrlsResponse(); result.imageUrls = imageUrls; return result; } catch (Exception e) { e.printStackTrace(); } GetImageUrlsResponse test = null; return test; }
From source file:org.jahia.modules.formbuilder.flow.CustomFormFlowHandler.java
public ActionResult callAction(final HttpServletRequest request, String actionName) { try {// w w w .ja va2 s . c om final Action action = ServicesRegistry.getInstance().getJahiaTemplateManagerService().getActions() .get(actionName); final RenderContext renderContext = (RenderContext) request.getAttribute("renderContext"); final Map<String, List<String>> formDatas = (Map<String, List<String>>) request.getSession() .getAttribute("formDatas"); Resource mainResource = (Resource) request.getAttribute("currentResource"); final Resource resource = new Resource(mainResource.getNode().getNode("responses"), mainResource.getTemplateType(), actionName, Resource.CONFIGURATION_PAGE); URLResolver mainResolver = (URLResolver) request.getAttribute("urlResolver"); String urlPathInfo = StringUtils.substringBefore(mainResolver.getUrlPathInfo(), mainResolver.getPath()) + resource.getNode().getPath(); if (!actionName.equals("default")) { urlPathInfo += "." + actionName + ".do"; } else { urlPathInfo += "/*"; } URLResolverFactory f = (URLResolverFactory) SpringContextSingleton.getBean("urlResolverFactory"); final URLResolver resolver = f.createURLResolver(urlPathInfo, request.getServerName(), request); JCRSessionWrapper sessionWrapper = JCRSessionFactory.getInstance().getCurrentUserSession(workspace, locale); return JCRTemplate.getInstance().doExecuteWithSystemSession(sessionWrapper.getUser().getUsername(), workspace, locale, new JCRCallback<ActionResult>() { public ActionResult doInJCR(JCRSessionWrapper session) throws RepositoryException { try { return action.doExecute(request, renderContext, resource, session, formDatas, resolver); } catch (Exception e) { logger.error("Error executing action", e); } return null; } }); } catch (Exception e) { logger.error("Error in action", e); } return null; }
From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.alumni.AlumniPublicAccessDA.java
public ActionForward sendEmailReportingError(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { final AlumniErrorSendingMailBean alumniBean = getRenderedObject(); StringBuilder mailBody = new StringBuilder(); mailBody.append(BundleUtil.getString(Bundle.ALUMNI, "message.alumni.mail.body.header")); mailBody.append("'").append(BundleUtil.getString(Bundle.ALUMNI, alumniBean.getErrorMessage())) .append("'\n\n"); String[] mailArgs = new String[8]; mailArgs[0] = alumniBean.getFullName(); mailArgs[1] = alumniBean.getStudentNumber().toString(); mailArgs[2] = alumniBean.getContactEmail(); mailArgs[3] = alumniBean.getDocumentIdNumber(); mailArgs[4] = alumniBean.getDateOfBirthYearMonthDay().toString(); mailArgs[5] = alumniBean.getSocialSecurityNumber(); mailArgs[6] = alumniBean.getNameOfFather(); mailArgs[7] = alumniBean.getNameOfMother(); String messageBody = RenderUtils.getFormatedResourceString("ALUMNI_RESOURCES", "message.alumni.mail.person.data", mailArgs); mailBody.append(messageBody);/*from w w w . ja v a 2s . c o m*/ mailBody.append("\n\n").append(BundleUtil.getString(Bundle.ALUMNI, "message.alumni.mail.body.footer")); EMail email = null; try { if (!request.getServerName().equals("localhost")) { email = new EMail("mail.adm", "erro@dot.ist.utl.pt"); String aluminiEmailAddress = Installation.getInstance().getInstituitionalEmailAddress("alumni"); email.send(aluminiEmailAddress, "Erro Registo Alumni", mailBody.toString()); } } catch (Throwable t) { logger.error(t.getMessage(), t); throw new Error(t); } request.setAttribute("alumniPublicAccessTitle", "title.report.error"); request.setAttribute("alumniPublicAccessMessage", "message.public.error.mail.success"); return mapping.findForward("alumniPublicAccessMessage"); }
From source file:jp.aegif.alfresco.online_webdav.WebDAVHelper.java
/** * Check that the destination path is on this server and is a valid WebDAV * path for this server// w w w . jav a 2s. co m * * @param request The request made against the WebDAV server. * @param urlStr String * @exception WebDAVServerException */ public void checkDestinationURL(HttpServletRequest request, String urlStr) throws WebDAVServerException { try { // Parse the URL URL url = new URL(urlStr); // Check if the path is on this WebDAV server boolean localPath = true; if (url.getPort() != -1 && url.getPort() != request.getServerPort()) { // Debug if (logger.isDebugEnabled()) logger.debug("Destination path, different server port"); localPath = false; } else if (url.getHost().equalsIgnoreCase(request.getServerName()) == false && url.getHost().equals(request.getLocalAddr()) == false) { // The target host may contain a domain or be specified as a numeric IP address String targetHost = url.getHost(); if (IPAddress.isNumericAddress(targetHost) == false) { String localHost = request.getServerName(); int pos = targetHost.indexOf("."); if (pos != -1) targetHost = targetHost.substring(0, pos); pos = localHost.indexOf("."); if (pos != -1) localHost = localHost.substring(0, pos); // compare the host names if (targetHost.equalsIgnoreCase(localHost) == false) localPath = false; } else { try { // Check if the target IP address is a local address InetAddress targetAddr = InetAddress.getByName(targetHost); if (NetworkInterface.getByInetAddress(targetAddr) == null) localPath = false; } catch (Exception ex) { // DEBUG if (logger.isDebugEnabled()) logger.debug("Failed to check target IP address, " + targetHost); localPath = false; } } // Debug if (localPath == false && logger.isDebugEnabled()) { logger.debug("Destination path, different server name/address"); logger.debug(" URL host=" + url.getHost() + ", ServerName=" + request.getServerName() + ", localAddr=" + request.getLocalAddr()); } } else if (!url.getPath().startsWith(getUrlPathPrefix(request))) { // Debug if (logger.isDebugEnabled()) logger.debug("Destination path, different serlet path"); localPath = false; } // If the URL does not refer to this WebDAV server throw an // exception if (localPath != true) throw new WebDAVServerException(HttpServletResponse.SC_BAD_GATEWAY); } catch (MalformedURLException ex) { // Debug if (logger.isDebugEnabled()) logger.debug("Bad destination path, " + urlStr); throw new WebDAVServerException(HttpServletResponse.SC_BAD_GATEWAY); } }