List of usage examples for javax.servlet.http HttpServletRequest getServletPath
public String getServletPath();
From source file:cn.vlabs.duckling.vwb.VWBContext.java
private String getRequestURL(HttpServletRequest request) { String url = getBaseURL() + request.getServletPath(); if (request.getPathInfo() != null) url += request.getPathInfo();/*from w ww . j a v a2 s .com*/ if (request.getQueryString() != null) url = url + "?" + request.getQueryString(); return url; }
From source file:io.lightlink.servlet.JsMethodsDefinitionServlet.java
String getDeclarationScript(String debugMethods, HttpServletRequest req) throws IOException { Set<String> services = getServicesNames(); InputStream definitionScript = Thread.currentThread().getContextClassLoader() .getResourceAsStream("io/lightlink/core/jsApiDefinition.js"); StringBuilder sb = new StringBuilder(IOUtils.toString(definitionScript)); definitionScript.close();/*from w w w. j av a2s . co m*/ String lightLinkUrl = req.getServletPath().split("-api/")[0]; sb.append("\n\nLL.JsApi.contextPath='").append(req.getContextPath()).append("';\n"); sb.append("\n\nLL.JsApi.url='").append(req.getContextPath()).append(lightLinkUrl).append("';\n"); sb.append("\n\nLL.JsApi.appContext='").append(req.getContextPath()).append("';\n\n"); String[] debugExpressions = debugMethods.split("/"); for (String service : services) { boolean debug = false; if (debugMethods != null) { for (String debugExpression : debugExpressions) { if (service.matches(debugExpression.replaceAll("\\*", ".*"))) { debug = true; break; } } } sb.append("LL.JsApi.").append(debug ? "debugDefine" : "define").append("('").append(service) .append("');\n"); } Map<String, String> customServices = getCustomServices(); for (Map.Entry<String, String> entry : customServices.entrySet()) { sb.append("LL.JsApi.").append("defineCustomUrl").append("('").append(entry.getKey()).append("','") .append(entry.getValue()).append("');\n"); } return sb.toString(); }
From source file:eionet.util.Util.java
/** * * *///from www .ja va 2 s . co m public static String getServletPathWithQueryString(HttpServletRequest request) { StringBuffer result = new StringBuffer(); String servletPath = request.getServletPath(); if (servletPath != null && servletPath.length() > 0) { if (servletPath.startsWith("/") && servletPath.length() > 1) { result.append(servletPath.substring(1)); } String queryString = request.getQueryString(); if (queryString != null && queryString.length() > 0) { result.append("?").append(queryString); } } return result.toString(); }
From source file:com.credit.common.web.servlet.filter.csrf.CsrfPreventionFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { ServletResponse wResponse = null;//from w w w .j a v a 2s . c o m if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; boolean skipNonceCheck = false; String path = req.getServletPath(); if (req.getPathInfo() != null) { path = path + req.getPathInfo(); } for (String entr : entryPoints) { if (entr.equalsIgnoreCase(path) || path.endsWith("jsp") || path.endsWith("list") || path.endsWith("List")) // TODO { skipNonceCheck = true; break; } if (entr.indexOf("*") > 0) { entr = entr.replace("*", ""); if (path.startsWith(entr)) { skipNonceCheck = true; break; } } } HttpSession session = getSession(req); @SuppressWarnings("unchecked") LruCache<String> nonceCache = (session == null) ? null : (LruCache<String>) session.getAttribute(Constants.CSRF_NONCE_SESSION_ATTR_NAME); if (!skipNonceCheck) { String previousNonce = req.getParameter(Constants.CSRF_NONCE_REQUEST_PARAM); if (nonceCache == null || previousNonce == null || !nonceCache.contains(previousNonce)) { res.sendError(denyStatus); return; } } if (nonceCache == null) { nonceCache = new LruCache<String>(nonceCacheSize); if (session == null) { session = req.getSession(true); } session.setAttribute(Constants.CSRF_NONCE_SESSION_ATTR_NAME, nonceCache); } String newNonce = generateNonce(); nonceCache.add(newNonce); request.setAttribute(Constants.CSRF_NONCE_REQUEST_PARAM, newNonce); wResponse = new CsrfResponseWrapper(res, newNonce); } else { wResponse = response; } chain.doFilter(request, wResponse); }
From source file:de.berlios.jedi.presentation.admin.PrepareAdminSessionFilter.java
/** * Checks if the session has the needed attributes for the admin actions.<br> * If the session hasn't those attributes, it forwards to the * PrepareAdminSessionAction, using the name of the intercepted Action as * the value of the NEXT_FORWARD_NAME key.<br> * If the session already has those attributes, the next element in the * chain is invoked./*from w ww .j a v a 2s .c o m*/ * * @throws IOException * If an IOException occurs when filtering. * @throws ServletException * If a ServletException occurs when filtering. * * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, * javax.servlet.ServletResponse, javax.servlet.FilterChain) */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { LogFactory.getLog(LoginFilter.class) .error("Unexpected error: request in PrepareAdminSessionFilter" + "isn't a HttpServletRequest"); throw new ServletException( "Unexpected error: request in PrepareAdminSessionFilter" + "isn't a HttpServletRequest"); } HttpServletRequest httpRequest = (HttpServletRequest) request; JispPackagesList jispPackagesList = (JispPackagesList) httpRequest.getSession() .getAttribute(AdminKeys.JISP_PACKAGES_LIST_KEY); JispIdManager jispIdManager = (JispIdManager) httpRequest.getSession() .getAttribute(AdminKeys.JISP_ID_MANAGER_KEY); try { if (jispPackagesList == null || jispIdManager == null) { httpRequest.setAttribute(Keys.NEXT_FORWARD_NAME, httpRequest.getServletPath()); httpRequest.getSession().getServletContext().getRequestDispatcher("/Admin/PrepareAdminSession.do") .forward(request, response); return; } chain.doFilter(request, response); } catch (IOException e) { LogFactory.getLog(LoginFilter.class).error("IOException in PrepareAdminSessionFilter", e); throw e; } catch (ServletException e) { LogFactory.getLog(LoginFilter.class).error("ServletException in PrepareAdminSessionFilter", e); throw e; } }
From source file:org.cagrid.identifiers.namingauthority.impl.NamingAuthorityService.java
/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response)// w ww.j a va 2 s. com */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LOG.debug("getPathInfo[" + request.getPathInfo() + "]"); LOG.debug("getQueryString[" + request.getQueryString() + "]"); LOG.debug("getRequestURI[" + request.getRequestURI() + "]"); LOG.debug("getRequestURL[" + request.getRequestURL() + "]"); LOG.debug("getServerName[" + request.getServerName() + "]"); LOG.debug("getServerPort[" + request.getServerPort() + "]"); LOG.debug("getServletPath[" + request.getServletPath() + "]"); LOG.debug("User Identity[" + request.getAttribute(GSIConstants.GSI_USER_DN)); processor.process(request, response); }
From source file:edu.harvard.hul.ois.drs.pdfaconvert.service.servlets.PdfaConverterServlet.java
/** * Handles the HTTP <code>GET</code> method. There are currently two end * point for GET://from w w w . jav a 2 s . com * <ol> * <li>/examine -- to have PdfaConverter examine a file and return a PDF/A. Use this when uploading a file locally.</li> * <li>/version -- to receive "text/plain" output of the version of PdfaConverter * being used to process files.</li> * </ol> * "/examine" requires the path to the file to be analyzed with the request * parameter "file" set to location of the file. E.g.: http:// * <host>[:port]/pdfa-converter/examine?file=<path/to/file/filename Note: "pdfa-converter" in * the above URL needs to be adjusted to the final name of the WAR file. * * @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 doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String servletPath = request.getServletPath(); // gives servlet mapping logger.info("Entering doGet(): " + servletPath); // See if path is just requesting version number. If so, just return it. // Outputs version of PdfaConverter, not the version of web application. if (RESOURCE_PATH_VERSION.equals(servletPath)) { sendPdfaConverterVersionResponse(request, response); return; } String filePath = request.getParameter(FILE_PARAM); if (StringUtils.isEmpty(filePath)) { ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_BAD_REQUEST, " Missing parameter: [" + FILE_PARAM + "] ", request.getRequestURL().toString()); sendErrorMessageResponse(errorMessage, response); return; } String fileName = null; int index = filePath.lastIndexOf(File.separatorChar); if (index > 0 && index <= filePath.length()) { fileName = filePath.substring(index + 1); } else { fileName = filePath; } File inputFile = new File(filePath); // Send it to the PdfaConverter processor... sendPdfaConverterExamineResponse(inputFile, fileName, request, response); }
From source file:ke.co.tawi.babblesms.server.servlet.contacts.AddContacts.java
/** * * @param request/*w w w .j av a 2s .co m*/ * @param response * @throws ServletException * @throws IOException */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userPath = request.getServletPath(); HttpSession session = request.getSession(false); // if add contacts is called if (userPath.equals("/account/addcontact")) { String[] emailArray = request.getParameterValues("email[]"); String[] phonenumArray = request.getParameterValues("phonenum[]"); String[] networkArray = request.getParameterValues("network[]"); String contactname = request.getParameter("contname"); String groupid = request.getParameter("groupid"); String statusuuid = request.getParameter("statusuuid"); String accountuuid = request.getParameter("accountuuid"); Set<String> mySet = new HashSet<String>(Arrays.asList(emailArray)); Set<String> mySet2 = new HashSet<String>(Arrays.asList(phonenumArray)); int duplicateemail = emailArray.length - mySet.size(); int duplicatephone = phonenumArray.length - mySet2.size(); // No First Name provided if ((StringUtils.isBlank(contactname)) || (emailArray.length == 0) || (phonenumArray.length == 0) || (networkArray.length == 0)) { session.setAttribute(SessionConstants.ADD_ERROR, ERROR_NO_NAME); } else if (!validemails(emailArray)) { session.setAttribute(SessionConstants.ADD_ERROR, ERROR_INVALID_EMAIL); } else if (existsEmail(emailArray)) { session.setAttribute(SessionConstants.ADD_ERROR, ERROR_EMAIL_EXISTS); } else if (duplicateemail >= 1) { session.setAttribute(SessionConstants.ADD_ERROR, ERROR_DUPLICATE_EMAIL); } else if (duplicatephone >= 1) { session.setAttribute(SessionConstants.ADD_ERROR, ERROR_PUBLICATE_PHONE); } /*else if (existsPhone(phonenumArray)) { session.setAttribute(SessionConstants.ADD_ERROR, ERROR_PHONE_EXISTS); }*/ else { session.setAttribute(SessionConstants.ADD_SUCCESS, ADD_SUCCESS); ct = new Contact(); ct.setName(contactname); ct.setStatusUuid(statusuuid); ct.setAccountUuid(accountuuid); if (ctDAO.putContact(ct)) { } else { session.setAttribute(SessionConstants.ADD_ERROR, "Contact creation Failed."); } //get contact bean to update cache String uuid = ct.getUuid(); //ct = ctDAO.getContactByName(contactname); ct = ctDAO.getContact(uuid); //logger.info(ct + " added sucessfully"); // mgr.getCache(CacheVariables.CACHE_CONTACTS_BY_UUID).put(new Element(ct.getUuid(), ct)); //loop emails for (String email2 : emailArray) { mail = new Email(); mail.setAddress(email2); mail.setContactuuid(ct.getUuid()); //mail.setStatusuuid(statusuuid); emailDAO.putEmail(mail); //get uuid to update cache mail = emailDAO.getEmail(email2); //logger.info(mail + " added sucessfully"); mgr.getCache(CacheVariables.CACHE_EMAIL_BY_UUID).put(new Element(mail.getUuid(), mail)); } //loop phonenumbers int count = 0; for (String phonenum : phonenumArray) { phn = new Phone(); phn.setPhonenumber(phonenum); phn.setContactUuid(ct.getUuid()); phn.setNetworkuuid(networkArray[count]); //phn.setStatusuuid(statusuuid); phoneDAO.putPhone(phn); //updatecache with correct uuid phn = phoneDAO.getPhone(phonenum); //logger.info(phn + " added sucessfully"); mgr.getCache(CacheVariables.CACHE_PHONE_BY_UUID).put(new Element(phn.getUuid(), phn)); count++; } // ContactGroup cg = new ContactGroup(); // cg.setAccountsuuid(accountuuid); // cg.setCgroupuuid(groupid); //cg.setContactuuid(ct.getUuid()); //cgDAO.putContactGroup(cg); //logger.info(cg + " added sucessfully"); //mgr.getCache(CacheVariables.CACHE_CONTACT_GROUP_BY_UUID).put(new Element(cg.getUuid(), cg)); //response.sendRedirect("account/contact.jsp"); } response.sendRedirect("addcontact.jsp"); //userPath = "addcontact"; } else if (userPath.equals("/account/editEmail")) { String email = request.getParameter("email"); String emailuuid = request.getParameter("emailuuid"); String contactname = request.getParameter("contname"); String contactuuid = request.getParameter("contactuuid"); //ctDAO.updateContact(contactuuid, contactname); /*if (emailDAO.updateEmail(emailuuid, email)) { session.setAttribute(SessionConstants.UPDATE_SUCCESS, "Update was successful."); } else { session.setAttribute(SessionConstants.UPDATE_ERROR, "Update Failed."); }*/ response.sendRedirect("contactemail.jsp"); //userPath = "contactemail"; } else if (userPath.equals("/account/editcontact")) { String phone = request.getParameter("phonenum"); String phoneuuid = request.getParameter("phoneuuid"); String contactname = request.getParameter("contname"); String contactuuid = request.getParameter("contactuuid"); /* ctDAO.updateContact(contactuuid, contactname); emailDAO.updateEmail(emailuuid, email); if (phoneDAO.updatePhone(phoneuuid, phone)) { session.setAttribute(SessionConstants.UPDATE_SUCCESS, "Update successful."); } else { session.setAttribute(SessionConstants.UPDATE_ERROR, "Update failed."); }*/ response.sendRedirect("contact.jsp"); //userPath = "contact"; } else if (userPath.equals("/account/deletecontact")) { String contactuuid = request.getParameter("contactuuid"); //String emailuuid = request.getParameter("emailuuid"); //String phone = request.getParameter("phonenum"); String phoneuuid = request.getParameter("phoneuuid"); /* if(phoneDAO.deletePhone(phoneuuid)){ ctDAO.deleteContact(contactuuid); session.setAttribute(SessionConstants.DELETE_SUCCESS, "Deletion successful."); } else{ session.setAttribute(SessionConstants.DELETE_ERROR, "Deletion failed."); }*/ response.sendRedirect("contact.jsp"); //userPath = "contact"; } else if (userPath.equals("/account/deleteemail")) { String contactuuid = request.getParameter("contactuuid"); String emailuuid = request.getParameter("emailuuid"); /* if(emailDAO.deleteEmail(emailuuid)){ // ctDAO.deleteContact(contactuuid); session.setAttribute(SessionConstants.DELETE_SUCCESS, "Deletion successful."); } else{ session.setAttribute(SessionConstants.DELETE_ERROR, "Deletion failed."); }*/ response.sendRedirect("contactemail.jsp"); //userPath = "contactemail"; } // use RequestDispatcher to forward request internally /* String url = userPath + ".jsp"; try { request.getRequestDispatcher(url).forward(request, response); } catch (ServletException | IOException ex) { } */ }
From source file:com.bodybuilding.turbine.servlet.ClusterListServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {/*from w w w . jav a 2s .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); } }
From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.Invoker.java
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the requested path and info boolean included = false; String servlet_path = (String) request.getAttribute(Dispatcher.__INCLUDE_SERVLET_PATH); if (servlet_path == null) servlet_path = request.getServletPath(); else/* w ww . j av a 2 s.co m*/ included = true; String path_info = (String) request.getAttribute(Dispatcher.__INCLUDE_PATH_INFO); if (path_info == null) path_info = request.getPathInfo(); // Get the servlet class String servlet = path_info; if (servlet == null || servlet.length() <= 1) { response.sendError(404); return; } int i0 = servlet.charAt(0) == '/' ? 1 : 0; int i1 = servlet.indexOf('/', i0); servlet = i1 < 0 ? servlet.substring(i0) : servlet.substring(i0, i1); // look for a named holder ServletHolder holder = _servletHandler.getServletHolder(servlet); if (holder != null) { // Add named servlet mapping _servletHandler.addServletHolder(holder); _servletHandler.mapPathToServlet(URI.addPaths(servlet_path, servlet) + "/*", holder.getName()); } else { // look for a class mapping if (servlet.endsWith(".class")) servlet = servlet.substring(0, servlet.length() - 6); if (servlet == null || servlet.length() == 0) { response.sendError(404); return; } synchronized (_servletHandler) { // find the entry for the invoker if (_invokerEntry == null) _invokerEntry = _servletHandler.getHolderEntry(servlet_path); // Check for existing mapping (avoid threaded race). String path = URI.addPaths(servlet_path, servlet); Map.Entry entry = _servletHandler.getHolderEntry(path); if (entry != null && entry != _invokerEntry) { // Use the holder holder = (ServletHolder) entry.getValue(); } else { // Make a holder holder = new ServletHolder(_servletHandler, servlet, servlet); if (_parameters != null) holder.putAll(_parameters); try { holder.start(); } catch (Exception e) { log.debug(LogSupport.EXCEPTION, e); throw new UnavailableException(e.toString()); } // Check it is from an allowable classloader if (!_nonContextServlets) { Object s = holder.getServlet(); if (_servletHandler.getClassLoader() != s.getClass().getClassLoader()) { holder.stop(); log.warn("Dynamic servlet " + s + " not loaded from context " + request.getContextPath()); throw new UnavailableException("Not in context"); } } // Add the holder for all the possible paths if (_verbose) log("Dynamic load '" + servlet + "' at " + path); _servletHandler.addServletHolder(holder); _servletHandler.mapPathToServlet(path + "/*", holder.getName()); _servletHandler.mapPathToServlet(path + ".class/*", holder.getName()); } } } if (holder != null) holder.handle(new Request(request, included, servlet, servlet_path, path_info), response); else response.sendError(404); }