List of usage examples for javax.servlet.http HttpServletRequest getMethod
public String getMethod();
From source file:com.primeleaf.krystal.web.action.cpanel.NewUserAction.java
public WebView execute(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); User loggedInUser = (User) session.getAttribute(HTTPConstants.SESSION_KRYSTAL); if (request.getMethod().equalsIgnoreCase("POST")) { String realName = request.getParameter("txtRealName") != null ? request.getParameter("txtRealName") : ""; String userName = request.getParameter("txtUserName") != null ? request.getParameter("txtUserName") : ""; String password = request.getParameter("txtPassWord") != null ? request.getParameter("txtPassWord") : ""; String confirmPassword = request.getParameter("txtConfirmPassWord") != null ? request.getParameter("txtConfirmPassWord") : ""; String userEmail = request.getParameter("txtUserEmail") != null ? request.getParameter("txtUserEmail") : ""; String userDescription = request.getParameter("txtDescription") != null ? request.getParameter("txtDescription") : ""; String userType = request.getParameter("radUserType") != null ? request.getParameter("radUserType") : "A"; userName = userName.replace(' ', '_'); try {/*from w ww . jav a 2 s . c o m*/ if (!GenericValidator.matchRegexp(userName, HTTPConstants.ALPHA_REGEXP)) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input for User Name"); return (new UsersAction().execute(request, response)); } if (!GenericValidator.maxLength(userName, 15)) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Value too large for User Name"); return (new UsersAction().execute(request, response)); } if (!GenericValidator.maxLength(realName, 50)) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Value too large for Real Name"); return (new UsersAction().execute(request, response)); } if (!GenericValidator.maxLength(password, 50)) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Value too large for Password"); return (new UsersAction().execute(request, response)); } if (!GenericValidator.minLength(password, 8)) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid Password"); return (new UsersAction().execute(request, response)); } if (!GenericValidator.matchRegexp(password, HTTPConstants.PASSWORD_PATTERN_REGEXP)) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid Password"); return (new UsersAction().execute(request, response)); } if (!GenericValidator.minLength(confirmPassword, 8)) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid Password"); return (new UsersAction().execute(request, response)); } if (!GenericValidator.matchRegexp(confirmPassword, HTTPConstants.PASSWORD_PATTERN_REGEXP)) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input for Password"); return (new UsersAction().execute(request, response)); } if (!password.equals(confirmPassword)) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Password do not match"); return (new UsersAction().execute(request, response)); } if (!GenericValidator.isEmail(userEmail)) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid Email ID"); return (new UsersAction().execute(request, response)); } if (!GenericValidator.maxLength(userEmail, 50)) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Value too large for Email ID"); return (new UsersAction().execute(request, response)); } if (!GenericValidator.maxLength(userDescription, 50)) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Value too large for User Description"); return (new UsersAction().execute(request, response)); } if (!User.USER_TYPE_ADMIN.equalsIgnoreCase(userType)) { userType = User.USER_TYPE_USER; } boolean userExist = UserDAO.getInstance().validateUser(userName); boolean emailExist = UserDAO.getInstance().validateUserEmail(userEmail); if (userExist) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "User with this username already exist"); return (new UsersAction().execute(request, response)); } if (emailExist) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "User with this email Id already exist"); return (new UsersAction().execute(request, response)); } User user = new User(); user.setUserName(userName); user.setPassword(password); user.setUserDescription(userDescription); user.setUserEmail(userEmail); user.setRealName(realName); user.setActive(true); user.setUserType(userType); UserDAO.getInstance().addUser(user); user = UserDAO.getInstance().readUserByName(userName); PasswordHistory passwordHistory = new PasswordHistory(); passwordHistory.setUserId(user.getUserId()); passwordHistory.setPassword(password); PasswordHistoryDAO.getInstance().create(passwordHistory); AuditLogManager.log(new AuditLogRecord(user.getUserId(), AuditLogRecord.OBJECT_USER, AuditLogRecord.ACTION_CREATED, loggedInUser.getUserName(), request.getRemoteAddr(), AuditLogRecord.LEVEL_INFO, "ID :" + user.getUserId(), "Name : " + user.getUserName())); request.setAttribute(HTTPConstants.REQUEST_MESSAGE, "User " + userName.toUpperCase() + " added successfully"); return (new UsersAction().execute(request, response)); } catch (Exception ex) { ex.printStackTrace(); } } return (new NewUserView(request, response)); }
From source file:io.lavagna.web.security.login.OAuthLogin.java
@Override public boolean doAction(HttpServletRequest req, HttpServletResponse resp) throws IOException { OAuthConfiguration conf = Json.GSON.fromJson(configurationRepository.getValue(Key.OAUTH_CONFIGURATION), OAuthConfiguration.class); String requestURI = req.getRequestURI(); if ("POST".equals(req.getMethod())) { OAuthProvider authHandler = conf.matchAuthorization(requestURI); if (authHandler != null) { handler.from(authHandler, conf.baseUrl, userRepository, errorPage).handleAuthorizationUrl(req, resp);/* w ww . j a v a2s. co m*/ return true; } } OAuthProvider callbackHandler = conf.matchCallback(requestURI); if (callbackHandler != null) { handler.from(callbackHandler, conf.baseUrl, userRepository, errorPage).handleCallback(req, resp); return true; } return false; }
From source file:com.primeleaf.krystal.web.action.cpanel.EditUserAction.java
public WebView execute(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); User loggedInUser = (User) session.getAttribute(HTTPConstants.SESSION_KRYSTAL); if (request.getMethod().equalsIgnoreCase("POST")) { short userId = 0; try {//from www. java2 s. c o m userId = Short .parseShort(request.getParameter("userid") != null ? request.getParameter("userid") : "0"); } catch (Exception e) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input"); return (new UsersAction().execute(request, response)); } UserDAO.getInstance().setReadCompleteObject(true); User user = UserDAO.getInstance().readUserById(userId); if (user == null) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid User"); return (new UsersAction().execute(request, response)); } String userName = request.getParameter("txtUserName") != null ? request.getParameter("txtUserName") : ""; String realName = request.getParameter("txtRealName") != null ? request.getParameter("txtRealName") : ""; String userEmail = request.getParameter("txtUserEmail") != null ? request.getParameter("txtUserEmail") : ""; String userDescription = request.getParameter("txtDescription") != null ? request.getParameter("txtDescription") : ""; String active = request.getParameter("radActive") != null ? request.getParameter("radActive") : "Y"; String userType = request.getParameter("radUserType") != null ? request.getParameter("radUserType") : "A"; if (!GenericValidator.maxLength(userName, 15)) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Value too large for User Name"); return (new UsersAction().execute(request, response)); } if (!GenericValidator.maxLength(realName, 50)) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Value too large for Real Name"); return (new UsersAction().execute(request, response)); } if (!GenericValidator.isEmail(userEmail)) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input"); return (new UsersAction().execute(request, response)); } if (!GenericValidator.maxLength(userEmail, 50)) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Value too large for User Email"); return (new UsersAction().execute(request, response)); } if (!GenericValidator.maxLength(userDescription, 50)) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Value too large for User Description"); return (new UsersAction().execute(request, response)); } if (!"Y".equalsIgnoreCase(active)) { active = "N"; } if (!User.USER_TYPE_ADMIN.equalsIgnoreCase(userType)) { userType = User.USER_TYPE_USER; } //check if new email address is different then existing one if (!user.getUserEmail().equalsIgnoreCase(userEmail)) { //it is different so validate if (UserDAO.getInstance().validateUserEmail(userEmail)) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "User with " + userEmail + " already exist"); return (new UsersAction().execute(request, response)); } } if (user.getUserName().equalsIgnoreCase(ServerConstants.SYSTEM_ADMIN_USER)) { active = "Y"; //Administrator user can never be in activated. userType = User.USER_TYPE_ADMIN; } try { user.setUserId(userId); user.setRealName(realName); user.setUserName(userName); user.setUserDescription(userDescription); user.setUserEmail(userEmail); if ("Y".equalsIgnoreCase(active)) { user.setActive(true); } else { user.setActive(false); } user.setUserType(userType); UserDAO.getInstance().updateUser(user, false); AuditLogManager.log(new AuditLogRecord(user.getUserId(), AuditLogRecord.OBJECT_USER, AuditLogRecord.ACTION_EDITED, loggedInUser.getUserName(), request.getRemoteAddr(), AuditLogRecord.LEVEL_INFO, "ID :" + user.getUserId(), "Name : " + user.getUserName())); request.setAttribute(HTTPConstants.REQUEST_MESSAGE, "User " + userName.toUpperCase() + " updated successfully"); return (new UsersAction().execute(request, response)); } catch (Exception e) { e.printStackTrace(); } } else { int userId = 0; try { userId = Integer .parseInt(request.getParameter("userid") != null ? request.getParameter("userid") : "0"); } catch (Exception e) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input"); return (new UsersAction().execute(request, response)); } UserDAO.getInstance().setReadCompleteObject(true); User user = UserDAO.getInstance().readUserById(userId); UserDAO.getInstance().setReadCompleteObject(false); if (user == null) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid User"); return (new UsersAction().execute(request, response)); } request.setAttribute("USER", user); } return (new EditUserView(request, response)); }
From source file:com.epam.cme.storefront.interceptors.beforeview.SeoRobotsFollowBeforeViewHandler.java
@Override public void beforeView(final HttpServletRequest request, final HttpServletResponse response, final ModelAndView modelAndView) { // Check to see if the controller has specified a Index/Follow directive for robots if (modelAndView != null && !modelAndView.getModel().containsKey("metaRobots")) { // Build a default directive String robotsValue = "no-index,no-follow"; if (RequestMethod.GET.name().equalsIgnoreCase(request.getMethod())) { if (request.isSecure()) { robotsValue = "no-index,follow"; } else { robotsValue = "index,follow"; }/*w w w.jav a 2 s . c o m*/ } else if (RequestMethod.POST.name().equalsIgnoreCase(request.getMethod())) { robotsValue = "no-index,no-follow"; } modelAndView.addObject("metaRobots", robotsValue); } }
From source file:com.cisco.oss.foundation.http.server.MonitoringFilter.java
@Override public void doFilterImpl(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { regiterMonitoring();// w ww . j a v a 2s.co m final long startTime = System.currentTimeMillis(); HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; String tempMethodName = httpServletRequest.getMethod(); if (uniqueUriMonitoringEnabled) { tempMethodName += ":" + httpServletRequest.getRequestURI(); } boolean reportToMonitoring = true; try { LOGGER.trace("Monitoring filter: Request processing started at: {}", startTime); // methodName = httpServletRequest.getMethod() + ":" + httpServletRequest.getRequestURI().toString(); tempMethodName = updateMethodName(httpServletRequest, tempMethodName); LOGGER.trace("transaction method name is: {}", tempMethodName); CommunicationInfo.getCommunicationInfo().transactionStarted(serviceDetails, tempMethodName, threadPool != null ? threadPool.getThreads() : -1); } catch (Exception e) { LOGGER.error("can't report monitoring data as it has failed on:" + e); reportToMonitoring = false; } final String methodName = tempMethodName; try { chain.doFilter(httpServletRequest, httpServletResponse); if (request.isAsyncStarted()) { AsyncContext async = request.getAsyncContext(); async.addListener(new AsyncListener() { @Override public void onComplete(AsyncEvent event) throws IOException { final long endTime = System.currentTimeMillis(); final int processingTime = (int) (endTime - startTime); LOGGER.debug("Processing time: {} milliseconds", processingTime); } @Override public void onTimeout(AsyncEvent event) throws IOException { } @Override public void onError(AsyncEvent event) throws IOException { Throwable throwable = event.getThrowable(); if (throwable != null) { CommunicationInfo.getCommunicationInfo().transactionFinished(serviceDetails, methodName, true, throwable.toString()); } } @Override public void onStartAsync(AsyncEvent event) throws IOException { } }); } else { final long endTime = System.currentTimeMillis(); final int processingTime = (int) (endTime - startTime); LOGGER.debug("Processing time: {} milliseconds", processingTime); } } catch (Exception e) { CommunicationInfo.getCommunicationInfo().transactionFinished(serviceDetails, methodName, true, e.toString()); throw e; } if (reportToMonitoring) { try { int status = httpServletResponse.getStatus(); if (status >= 400) { CommunicationInfo.getCommunicationInfo().transactionFinished(serviceDetails, methodName, true, httpServletResponse.getStatus() + ""); } else { CommunicationInfo.getCommunicationInfo().transactionFinished(serviceDetails, methodName, false, ""); } } catch (Exception e) { LOGGER.error("can't report monitoring data as it has failed on:" + e); } } }
From source file:com.gst.infrastructure.security.filter.TenantAwareBasicAuthenticationFilter.java
@Override public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException { final HttpServletRequest request = (HttpServletRequest) req; final HttpServletResponse response = (HttpServletResponse) res; final StopWatch task = new StopWatch(); task.start();//from w w w .ja v a 2 s . c o m try { if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { // ignore to allow 'preflight' requests from AJAX applications // in different origin (domain name) } else { String tenantIdentifier = request.getHeader(this.tenantRequestHeader); if (org.apache.commons.lang.StringUtils.isBlank(tenantIdentifier)) { tenantIdentifier = request.getParameter("tenantIdentifier"); } if (tenantIdentifier == null && this.exceptionIfHeaderMissing) { throw new InvalidTenantIdentiferException( "No tenant identifier found: Add request header of '" + this.tenantRequestHeader + "' or add the parameter 'tenantIdentifier' to query string of request URL."); } String pathInfo = request.getRequestURI(); boolean isReportRequest = false; if (pathInfo != null && pathInfo.contains("report")) { isReportRequest = true; } final FineractPlatformTenant tenant = this.basicAuthTenantDetailsService .loadTenantById(tenantIdentifier, isReportRequest); ThreadLocalContextUtil.setTenant(tenant); String authToken = request.getHeader("Authorization"); if (authToken != null && authToken.startsWith("Basic ")) { ThreadLocalContextUtil.setAuthToken(authToken.replaceFirst("Basic ", "")); } if (!firstRequestProcessed) { final String baseUrl = request.getRequestURL().toString().replace(request.getPathInfo(), "/"); System.setProperty("baseUrl", baseUrl); final boolean ehcacheEnabled = this.configurationDomainService.isEhcacheEnabled(); if (ehcacheEnabled) { this.cacheWritePlatformService.switchToCache(CacheType.SINGLE_NODE); } else { this.cacheWritePlatformService.switchToCache(CacheType.NO_CACHE); } TenantAwareBasicAuthenticationFilter.firstRequestProcessed = true; } } super.doFilter(req, res, chain); } catch (final InvalidTenantIdentiferException e) { // deal with exception at low level SecurityContextHolder.getContext().setAuthentication(null); response.addHeader("WWW-Authenticate", "Basic realm=\"" + "Fineract Platform API" + "\""); response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } finally { task.stop(); final PlatformRequestLog log = PlatformRequestLog.from(task, request); logger.info(this.toApiJsonSerializer.serialize(log)); } }
From source file:com.atlassian.jira.web.dispatcher.JiraWebworkActionDispatcher.java
private boolean needsMultipartWrapper(final HttpServletRequest httpServletRequest, final boolean disableMultipartGet) { return MultiPartRequest.isMultiPart(httpServletRequest) && ("POST".equals(httpServletRequest.getMethod()) || ("GET".equals(httpServletRequest.getMethod()) && !disableMultipartGet)); }
From source file:io.ericwittmann.corsproxy.ProxyServlet.java
/** * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *//* w ww . ja va 2 s . c om*/ @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String url = "https://issues.jboss.org" + req.getPathInfo(); if (req.getQueryString() != null) { url += "?" + req.getQueryString(); } System.out.println("Proxying to: " + url); boolean isWrite = req.getMethod().equalsIgnoreCase("post") || req.getMethod().equalsIgnoreCase("put"); URL remoteUrl = new URL(url); HttpURLConnection remoteConn = (HttpURLConnection) remoteUrl.openConnection(); if (isWrite) { remoteConn.setDoOutput(true); } String auth = req.getHeader("Authorization"); if (auth != null) { remoteConn.setRequestProperty("Authorization", auth); } if (isWrite) { InputStream requestIS = null; OutputStream remoteOS = null; try { requestIS = req.getInputStream(); remoteOS = remoteConn.getOutputStream(); IOUtils.copy(requestIS, remoteOS); remoteOS.flush(); } catch (Exception e) { e.printStackTrace(); resp.sendError(500, e.getMessage()); return; } finally { IOUtils.closeQuietly(requestIS); IOUtils.closeQuietly(remoteOS); } } InputStream remoteIS = null; OutputStream responseOS = null; try { Map<String, List<String>> headerFields = remoteConn.getHeaderFields(); for (String headerName : headerFields.keySet()) { if (headerName == null) { continue; } if (EXCLUDE_HEADERS.contains(headerName)) { continue; } String headerValue = remoteConn.getHeaderField(headerName); resp.setHeader(headerName, headerValue); } resp.setHeader("Cache-control", "no-cache, no-store, must-revalidate"); //$NON-NLS-2$ remoteIS = remoteConn.getInputStream(); responseOS = resp.getOutputStream(); IOUtils.copy(remoteIS, responseOS); resp.flushBuffer(); } catch (Exception e) { e.printStackTrace(); resp.sendError(500, e.getMessage()); } finally { IOUtils.closeQuietly(responseOS); IOUtils.closeQuietly(remoteIS); } }
From source file:com.tasktop.c2c.server.web.proxy.HttpProxy.java
private HttpMethod createProxyRequest(String targetUrl, HttpServletRequest request) throws IOException { URI targetUri;//from w w w . j a v a 2 s . c o m try { targetUri = new URI(uriEncode(targetUrl)); } catch (URISyntaxException e) { throw new RuntimeException(e); } HttpMethod commonsHttpMethod = httpMethodProvider.getMethod(request.getMethod(), targetUri.toString()); commonsHttpMethod.setFollowRedirects(false); Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); Enumeration<String> headerVals = request.getHeaders(headerName); while (headerVals.hasMoreElements()) { String headerValue = headerVals.nextElement(); headerValue = headerFilter.processRequestHeader(headerName, headerValue); if (headerValue != null) { commonsHttpMethod.addRequestHeader(new Header(headerName, headerValue)); } } } return commonsHttpMethod; }
From source file:com.tc.webshell.servlets.RestSimple.java
/** * Processes requests for both HTTP//from www. ja v a 2 s. co m * <code>GET</code> and * <code>POST</code> methods. * * @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 { Database db = ContextInfo.getUserDatabase(); String json = null; if ("POST".equals(request.getMethod())) { json = IOUtils.toString(request.getInputStream()); } else if ("GET".equals(request.getMethod())) { json = request.getParameter(WebshellConstants.PARAM_JSON); } else { json = IOUtils.toString(request.getInputStream()); } if (StrUtils.isNull(json)) { Prompt error = new Prompt(); error.setMessage("No json data found"); error.setTitle("ERROR"); json = MapperFactory.mapper().writeValueAsString(error); this.compressResponse(request, response, json); return; } Document doc = new DocFactory().buildDocument(request, db, json); String message = doc.getItemValueString("Form") + " created successfully"; Prompt prompt = new Prompt(); prompt.setMessage(message); prompt.setTitle("info"); prompt.addProperty(WebshellConstants.PARAM_NOTEID, doc.getNoteID()); prompt.addProperty(WebshellConstants.PARAM_UNID, doc.getUniversalID()); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd G 'at' HH:mm:ss z"); String strdate = formatter.format(doc.getCreated().toJavaDate()); prompt.addProperty(WebshellConstants.PARAM_CREATED, strdate); //lets add all the fields from the doc as a property for (Object o : doc.getItems()) { Item item = (Item) o; prompt.addProperty(item.getName(), item.getText()); } json = MapperFactory.mapper().writeValueAsString(prompt); this.compressResponse(request, response, json); doc.recycle(); } catch (NotesException e) { logger.log(Level.SEVERE, null, e); } }