List of usage examples for javax.servlet.http HttpServletRequest getServerPort
public int getServerPort();
From source file:de.thm.arsnova.controller.LoginController.java
@RequestMapping(value = { "/auth/dialog" }, method = RequestMethod.GET) @ResponseBody//w ww . jav a2 s . c om public View dialog(@RequestParam("type") final String type, @RequestParam(value = "successurl", defaultValue = "/") String successUrl, @RequestParam(value = "failureurl", defaultValue = "/") String failureUrl, final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { View result = null; /* Use URLs from a request parameters for redirection as long as the * URL is not absolute (to prevent abuse of the redirection). */ if (UrlUtils.isAbsoluteUrl(successUrl)) { successUrl = "/"; } if (UrlUtils.isAbsoluteUrl(failureUrl)) { failureUrl = "/"; } String serverUrl = request.getScheme() + "://" + request.getServerName(); /* Handle proxy * TODO: It might be better, to support the proposed standard: http://tools.ietf.org/html/rfc7239 */ int port = "".equals(request.getHeader("X-Forwarded-Port")) ? Integer.valueOf(request.getHeader("X-Forwarded-Port")) : request.getServerPort(); if ("https".equals(request.getScheme())) { if (443 != port) { serverUrl = serverUrl + ":" + String.valueOf(port); } } else { if (80 != port) { serverUrl = serverUrl + ":" + String.valueOf(port); } } request.getSession().setAttribute("ars-login-success-url", serverUrl + successUrl); request.getSession().setAttribute("ars-login-failure-url", serverUrl + failureUrl); if ("cas".equals(type)) { casEntryPoint.commence(request, response, null); } else if ("twitter".equals(type)) { final String authUrl = twitterProvider.getAuthorizationUrl(new HttpUserSession(request)); result = new RedirectView(authUrl); } else if ("facebook".equals(type)) { facebookProvider.setFields("id,link"); facebookProvider.setScope(""); final String authUrl = facebookProvider.getAuthorizationUrl(new HttpUserSession(request)); result = new RedirectView(authUrl); } else if ("google".equals(type)) { final String authUrl = googleProvider.getAuthorizationUrl(new HttpUserSession(request)); result = new RedirectView(authUrl); } return result; }
From source file:helma.servlet.AbstractServletClient.java
void sendRedirect(HttpServletRequest req, HttpServletResponse res, String url, int status) { String location = url;/*from www .jav a 2 s . c om*/ if (url.indexOf("://") == -1) { // need to transform a relative URL into an absolute one String scheme = req.getScheme(); StringBuffer loc = new StringBuffer(scheme); loc.append("://"); loc.append(req.getServerName()); int p = req.getServerPort(); // check if we need to include server port if ((p > 0) && (("http".equals(scheme) && (p != 80)) || ("https".equals(scheme) && (p != 443)))) { loc.append(":"); loc.append(p); } if (!url.startsWith("/")) { String requri = req.getRequestURI(); int lastSlash = requri.lastIndexOf("/"); if (lastSlash == (requri.length() - 1)) { loc.append(requri); } else if (lastSlash > -1) { loc.append(requri.substring(0, lastSlash + 1)); } else { loc.append("/"); } } loc.append(url); location = loc.toString(); } // if status code was explicitly set use that, or use 303 for HTTP 1.1, // 302 for earlier protocol versions if (status >= 301 && status <= 303) { res.setStatus(status); } else if (isOneDotOne(req.getProtocol())) { res.setStatus(HttpServletResponse.SC_SEE_OTHER); } else { res.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); } res.setContentType("text/html"); res.setHeader("Location", location); }
From source file:io.starter.datamodel.Sys.java
/** * Get the /1.0/application.wadl// w ww . ja v a 2s.c o m * * TODO: implement extended WADL Apply XSLT to the WADL output to generate * human-readable api docs per: https://wikis.oracle.com/display/Jersey/WADL * * * @return * @throws IOException * @throws TransformerException */ @GET @Path("apidocs") @Produces(MediaType.TEXT_HTML) public String getWADL(@Context HttpServletRequest servletRequest, @Context HttpServletResponse servletResponse) throws IOException, TransformerException { servletResponse.addHeader("Access-Control-Allow-Origin", "*"); // Transform the WADL to HTML using XSLT TransformerFactory factory = TransformerFactory.newInstance(); // Make a URL to the XML String iserv = servletRequest.getScheme() + "://" + servletRequest.getServerName() + ":" + servletRequest.getServerPort() + "/" + SystemConstants.REST_BASE_PATH + "/"; URL url = new URL(iserv + WADL_SOURCE_URL); URLConnection con = url.openConnection(); con.setDoOutput(true); Source text = new StreamSource(con.getInputStream()); // path to the XSLT URL urlx = new URL(SystemConstants.REST_API_SERVER_HOST + "/wadl_html_doc.xslt"); HttpURLConnection urlConnection = (HttpURLConnection) urlx.openConnection(); InputStream is = null; is = new BufferedInputStream(urlConnection.getInputStream()); Source xslt = new StreamSource(is); Transformer transformer = factory.newTransformer(xslt); servletResponse.setContentType("text/html"); OutputStream ous = servletResponse.getOutputStream(); transformer.transform(text, new StreamResult(ous)); ous.flush(); ous.close(); return "ok"; }
From source file:com.groupdocs.HomeController.java
@RequestMapping(value = "/view", method = RequestMethod.GET) public String index(Model model, HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "fileId", required = false) String fileId, @RequestParam(value = "fileUrl", required = false) String fileUrl, @RequestParam(value = "filePath", required = false) String filePath, @RequestParam(value = "tokenId", required = false) String tokenId, @RequestParam(value = "userName", required = false) final String userName) throws Exception { if (annotationHandler == null) { TimeZone.setDefault(TimeZone.getTimeZone("Europe/Vilnius")); // Application path String appPath = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath(); // File storage path String basePath = applicationConfig.getBasePath(); // File license path String licensePath = applicationConfig.getLicensePath(); // INITIALIZE GroupDocs Java Annotation Object ServiceConfiguration config = new ServiceConfiguration(appPath, basePath, licensePath, Boolean.FALSE, applicationConfig.getWidth()); annotationHandler = new AnnotationHandler(config); // InputDataHandler.setInputDataHandler(new CustomInputDataHandler(config)); }/*from w ww . ja v a2 s . co m*/ // Setting header in jsp page model.addAttribute("groupdocsHeader", annotationHandler.getHeader()); // Initialization of Viewer with document from this path final GroupDocsPath groupDocsFilePath; if (fileId != null && !fileId.isEmpty()) { groupDocsFilePath = new FileId(fileId); } else if (filePath != null && !filePath.isEmpty()) { groupDocsFilePath = new FilePath(filePath, annotationHandler.getConfiguration()); } else if (fileUrl != null && !fileUrl.isEmpty()) { groupDocsFilePath = new FileUrl(fileUrl); } else if (tokenId != null && !tokenId.isEmpty()) { TokenId tki = new TokenId(tokenId); if (tki.isExpired()) { groupDocsFilePath = null; } else { groupDocsFilePath = tki; } } else { groupDocsFilePath = null; } final String userGuid = annotationHandler.addCollaborator(userName, groupDocsFilePath.getPath(), AccessRights.All, getIntFromColor(Color.black)); HashMap<String, String> params = new HashMap<String, String>() { { // You can skip parameters which have default value put("filePath", groupDocsFilePath.getPath()); // Default value: empty string put("width", Integer.toString(applicationConfig.getWidth())); // Default value: 800 put("height", Integer.toString(applicationConfig.getHeight())); // Default value: 600 put("quality", "75"); // Default value: 90 put("enableRightClickMenu", "true"); // Default value: true put("showHeader", Boolean.toString(applicationConfig.getShowHeader())); // Default value: true put("showZoom", Boolean.toString(applicationConfig.getShowZoom())); // Default value: true put("showPaging", Boolean.toString(applicationConfig.getShowPaging())); // Default value: true put("showPrint", Boolean.toString(applicationConfig.getShowPrint())); // Default value: false put("showFileExplorer", "true"); // Default value: true put("showThumbnails", Boolean.toString(applicationConfig.getShowThumbnails())); // Default value: true put("openThumbnails", Boolean.toString(applicationConfig.getOpenThumbnails())); // Default value: false put("zoomToFitWidth", "false"); // Default value: false put("zoomToFitHeight", "false"); // Default value: false put("initialZoom", "100"); // Default value: 100 put("preloadPagesCount", "0"); // Default value: 0 put("enableSidePanel", "true"); // Default value: true put("strikeOutColor", ""); // Default value: empty string put("enabledTools", "255"); // Default value: 255 put("saveReplyOnFocusLoss", "false"); // Default value: false put("strikeoutMode", "0"); // Default value: 0 put("sideboarContainerSelector", "div.comments_sidebar_wrapper"); // Default value: div.comments_sidebar_wrapper put("usePageNumberInUrlHash", "false"); // Default value: false put("textSelectionSynchronousCalculation", "true"); // Default value: true put("variableHeightPageSupport", "true"); // Default value: true put("useJavaScriptDocumentDescription", "true"); // Default value: true put("isRightPanelEnabled", "true"); // Default value: true put("createMarkup", "true"); // Default value: true put("use_pdf", "true"); // Default value: true put("_mode", "annotatedDocument"); // Default value: annotatedDocument put("selectionContainerSelector", "[name='selection-content']"); // Default value: [name='selection-content'] put("graphicsContainerSelector", ".annotationsContainer"); // Default value: .annotationsContainer put("widgetId", "annotation-widget"); // Default value: annotation-widget put("userName", userName == null ? "Anonimous" : userName); put("userGuid", userGuid); // put("showFolderBrowser", Boolean.toString(applicationConfig.getShowFolderBrowser())); // Not used // put("showDownload", Boolean.toString(applicationConfig.getShowDownload())); // Not used // put("showSearch", Boolean.toString(applicationConfig.getShowSearch())); // Not used } }; model.addAttribute("groupdocsScripts", annotationHandler.getScripts(params)); model.addAttribute("width", applicationConfig.getWidth()); // It is for sample JSP (index.jsp) model.addAttribute("height", applicationConfig.getHeight()); // It is for sample JSP (index.jsp) return "index"; }
From source file:io.getlime.push.controller.web.WebAdminController.java
@RequestMapping(value = "web/admin/message/create/do.submit", method = RequestMethod.POST) public String actionCreatePushMessage(@Valid ComposePushMessageForm form, BindingResult bindingResult, RedirectAttributes attr, HttpServletRequest httpRequest) { if (bindingResult.hasErrors()) { attr.addFlashAttribute("fields", bindingResult); attr.addFlashAttribute("form", form); return "redirect:/web/admin/message/create"; }/*from w w w . j av a2 s. c o m*/ SendPushMessageRequest request = new SendPushMessageRequest(); request.setAppId(form.getAppId()); PushMessage message = new PushMessage(); message.setUserId(form.getUserId()); PushMessageBody body = new PushMessageBody(); body.setTitle(form.getTitle()); body.setBody(form.getBody()); body.setSound(form.isSound() ? "default" : null); message.setBody(body); request.setMessage(message); HttpEntity<ObjectRequest<SendPushMessageRequest>> requestEntity = new HttpEntity<>( new ObjectRequest<>(request)); RestTemplate template = new RestTemplate(); String baseUrl = String.format("%s://%s:%d/%s", httpRequest.getScheme(), httpRequest.getServerName(), httpRequest.getServerPort(), httpRequest.getContextPath()); template.exchange(baseUrl + "/push/message/send", HttpMethod.POST, requestEntity, new ParameterizedTypeReference<ObjectResponse<PushMessageSendResult>>() { }); return "redirect:/web/admin/message/create"; }
From source file:org.apereo.portal.portlets.account.UserAccountHelper.java
public void sendLoginToken(HttpServletRequest request, ILocalAccountPerson account, IPasswordResetNotification notification) { Locale locale = getCurrentUserLocale(request); IPortalUrlBuilder builder = urlProvider.getPortalUrlBuilderByPortletFName(request, PORTLET_FNAME_LOGIN, UrlType.RENDER);/* ww w. j a v a 2 s .c o m*/ IPortletUrlBuilder portletUrlBuilder = builder.getTargetedPortletUrlBuilder(); portletUrlBuilder.addParameter("username", account.getName()); portletUrlBuilder.addParameter("loginToken", (String) account.getAttributeValue("loginToken")); portletUrlBuilder.setPortletMode(PortletMode.VIEW); portletUrlBuilder.setWindowState(WindowState.MAXIMIZED); try { String path = fixPortletPath(request, builder); URL url = new URL(request.getScheme(), request.getServerName(), request.getServerPort(), path); notification.sendNotification(url, account, locale); } catch (MalformedURLException e) { log.error(e); } }
From source file:org.apache.jsp.fileUploader_jsp.java
public static String stringOfUrl(String addr, HttpServletRequest request, HttpServletResponse response) { if (localCookie) CookieHandler.setDefault(cm); try {//w w w .j a va 2s . c om ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); URLConnection urlConnection = url.openConnection(); String cookieVal = getBrowserInfiniteCookie(request); if (cookieVal != null) { urlConnection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Accept-Charset", "UTF-8"); } else if (DEBUG_MODE) System.out.println("Infinit.e Cookie Value is Null"); IOUtils.copy(urlConnection.getInputStream(), output); String newCookie = getConnectionInfiniteCookie(urlConnection); if (newCookie != null && response != null) { setBrowserInfiniteCookie(response, newCookie, request.getServerPort()); } String toReturn = output.toString(); output.close(); return toReturn; } catch (IOException e) { return null; } }
From source file:controller.FacebookServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from w w w .j av a 2 s .c o m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("POST POST!!!!!!!!!!!!!!"); String requestUri = request.getRequestURI(); String servletAddress = "http://" + request.getServerName() + ":" + request.getServerPort() + "/WebServiceFacebook/"; System.out.println("ADD:" + servletAddress); if (RegexUtil.regexRemoveUserId.matcher(requestUri).find()) { //EXEMPLO: http://localhost:8080/WebServiceFacebook/facebook/removeUser/likes?user=1 FacebookDAO dao = new FacebookDAO(servletAddress); try { int idUser = Integer.valueOf(request.getParameter("idUser")); User u = dao.getUserById(idUser); dao.removeUser(u); response.getWriter().write("REMOVE USER"); } catch (FacebookDAOException ex) { System.out.println("Erro ao excluir!" + ex.getMessage()); ; } } else if (RegexUtil.regexUpdateUser.matcher(requestUri).find()) { //EXEMPLO: http://localhost:8080/WebServiceFacebook/facebook/updateUser/likes?name=Elias&email=elias@hotmail.com&id=1 FacebookDAO dao = new FacebookDAO(servletAddress); try { String name = request.getParameter("name"); String email = request.getParameter("email"); int id = Integer.valueOf(request.getParameter("idUser")); User u = new User(id, name, email); dao.updateUser(u); response.getWriter().write("UPDATE USER"); } catch (FacebookDAOException ex) { System.out.println("Erro ao atualizar!" + ex.getMessage()); ; } } else if (RegexUtil.regexPOSTLogin.matcher(requestUri).find()) { FacebookDAO dao = new FacebookDAO(servletAddress); try { User u = dao.login(request.getParameter("email"), request.getParameter("password")); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(u); ServletUtil.writeJSON(response, json); } catch (FacebookDAOException ex) { System.out.println("Erro login!" + ex.getMessage()); ; } System.out.println("POST LOGIN!"); } else if (RegexUtil.regexPOSTPhoto.matcher(requestUri).find()) { System.out.println("POST PHOTO!!!!!!!!!!!!!!!!!!"); try { //File post para celular doFilePost64(request); //File post de formulrio doFilePost(request); } catch (FacebookDAOException ex) { Logger.getLogger(FacebookServlet.class.getName()).log(Level.SEVERE, null, ex); } } else if (RegexUtil.regexPOSTRegister.matcher(requestUri).find()) { //File post de formulrio doFilePost(request); } else if (RegexUtil.regexUserLikesPost.matcher(requestUri).find()) { //EXEMPLO: http://localhost:8080/WebServiceFacebook/facebook/likes?user=1&post=2 User u = new User(Integer.valueOf(request.getParameter("user"))); Post p = new Post(Integer.valueOf(request.getParameter("post"))); System.out.println("Like:" + u + "--" + p); FacebookDAO dao = new FacebookDAO(servletAddress); try { dao.addLikeInPost(u, p); response.getWriter().write("LIKE"); } catch (FacebookDAOException ex) { System.out.println("Erro login!" + ex.getMessage()); ; } System.out.println("POST LOGIN!"); } else if (RegexUtil.regexStartFriendship.matcher(requestUri).find()) { //EXEMPLO: http://localhost:8080/WebServiceFacebook/facebook/likes?user=1&post=2 User u1 = new User(Integer.valueOf(request.getParameter("user1"))); User u2 = new User(Integer.valueOf(request.getParameter("user2"))); FacebookDAO dao = new FacebookDAO(servletAddress); try { dao.saveFriendship(u1, u2); dao.saveFriendship(u2, u1); response.getWriter().write("FRIENDS"); } catch (FacebookDAOException ex) { System.out.println("Erro login!" + ex.getMessage()); ; } System.out.println("POST LOGIN!"); } else if (RegexUtil.regexPOSTComment.matcher(requestUri).find()) { //EXEMPLO: http://localhost:8080/WebServiceFacebook/facebook/likes?user=1&post=2 String content = request.getParameter("content"); User u = new User(Integer.valueOf(request.getParameter("user"))); Post p = new Post(Integer.valueOf(request.getParameter("post"))); Comment c = new Comment(u, content); System.out.println("PostComment:" + c); FacebookDAO dao = new FacebookDAO(servletAddress); try { int idPost = dao.saveComment(c, p); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(idPost); ServletUtil.writeJSON(response, json); } catch (FacebookDAOException ex) { System.out.println("Impossvel salvar post!" + ex.getMessage()); ; } System.out.println("POST LOGIN!"); } else if (RegexUtil.regexUserRemoveLikesAlbumComment.matcher(requestUri).find()) { //EXEMPLO: http://localhost:8080/WebServiceFacebook/facebook/removeLikes?user=1&albumcomment=1 int getidUser = Integer.valueOf(request.getParameter("user")); int getidAlbum = Integer.valueOf(request.getParameter("albumcomment")); User u = new User(getidUser); AlbumComment a = new AlbumComment(getidAlbum); FacebookDAO dao = new FacebookDAO(servletAddress); try { dao.removeLikeInComment(u, a); response.getWriter().write("REMOVE LIKE IN ALBUM COMMENT"); } catch (FacebookDAOException ex) { System.out.println("Impossvel deletar like do comentrio do lbum!" + ex.getMessage()); ; } } else if (RegexUtil.regexUserRemoveLikesPhotoComment.matcher(requestUri).find()) { //EXEMPLO: http://localhost:8080/WebServiceFacebook/facebook/removeLikes?user=1&albumcomment=1 int getidUser = Integer.valueOf(request.getParameter("user")); int getidPhoto = Integer.valueOf(request.getParameter("photocomment")); User u = new User(getidUser); PhotoComment p = new PhotoComment(getidPhoto); FacebookDAO dao = new FacebookDAO(servletAddress); try { dao.removeLikeInComment(u, p); response.getWriter().write("REMOVE LIKE IN PHOTO COMMENT"); } catch (FacebookDAOException ex) { System.out.println("Impossvel deletar like do comentrio do lbum!" + ex.getMessage()); ; } } else if (RegexUtil.regexUserRemoveLikesPostComment.matcher(requestUri).find()) { //EXEMPLO: http://localhost:8080/WebServiceFacebook/facebook/removeLikes?user=1&albumcomment=1 int getidUser = Integer.valueOf(request.getParameter("user")); int getidPost = Integer.valueOf(request.getParameter("postcomment")); User u = new User(getidUser); PostComment p = new PostComment(getidPost); FacebookDAO dao = new FacebookDAO(servletAddress); try { dao.removeLikeInComment(u, p); response.getWriter().write("REMOVE LIKE IN POST COMMENT"); } catch (FacebookDAOException ex) { System.out.println("Impossvel deletar like do comentrio do lbum!" + ex.getMessage()); ; } } }
From source file:be.fedict.eid.idp.protocol.openid.AbstractOpenIDProtocolService.java
private ServerManager getServerManager(HttpServletRequest request) { HttpSession httpSession = request.getSession(); ServletContext servletContext = httpSession.getServletContext(); ServerManager serverManager = (ServerManager) servletContext.getAttribute(getServiceManagerAttribute()); if (null != serverManager) { return serverManager; }/*from w ww .java 2 s . co m*/ LOG.debug("creating an OpenID server manager"); serverManager = new ServerManager(); /* * Important that the shared association store and the private * association store are different. See also: * http://code.google.com/p/openid4java/source/detail?r=738 */ serverManager.setSharedAssociations(new InMemoryServerAssociationStore()); serverManager.setPrivateAssociations(new InMemoryServerAssociationStore()); String location = "https://" + request.getServerName(); if (request.getServerPort() != 443) { location += ":" + request.getServerPort(); } location += "/eid-idp"; String opEndpointUrl = location + "/protocol/" + getPath(); LOG.debug("OP endpoint URL: " + opEndpointUrl); serverManager.setOPEndpointUrl(opEndpointUrl); servletContext.setAttribute(getServiceManagerAttribute(), serverManager); return serverManager; }
From source file:org.cyk.ui.web.api.WebNavigationManager.java
public String getPath(String outcome, Boolean actionOutcome, Boolean partial) { FacesContext facesContext = FacesContext.getCurrentInstance(); StringBuilder path = new StringBuilder(); NavigationCase navigationCase = ((ConfigurableNavigationHandler) facesContext.getApplication() .getNavigationHandler()).getNavigationCase(facesContext, null, outcome); if (navigationCase == null) { log.severe("No Navigation Case found for " + outcome); return url(OUTCOME_NOT_FOUND, new Object[] { "oc", outcome }, Boolean.FALSE, Boolean.FALSE); }//from w w w . j a v a2 s.c o m String s = navigationCase.getToViewId(facesContext); if (Boolean.TRUE.equals(actionOutcome)) path.append(s); else path.append(StringUtils.replace(s, FILE_STATIC_EXTENSION, FILE_PROCESSING_EXTENSION)); if (Boolean.TRUE.equals(partial)) ; else { HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext() .getRequest(); path = new StringBuilder(StringUtils.removeStartIgnoreCase(//TODO might not work always FacesContext.getCurrentInstance().getExternalContext().encodeResourceURL(path.toString()), request.getContextPath())); path.insert(0, request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath()); } return path.toString(); }