List of usage examples for javax.servlet.http HttpServletRequest getMethod
public String getMethod();
From source file:org.n52.iceland.service.Service.java
private MediaType getContentType(HttpServletRequest request) throws HTTPException { if (request.getContentType() == null) { // default to KVP for GET requests if (request.getMethod().equals(HTTPMethods.GET)) { return MediaTypes.APPLICATION_KVP; } else {//w w w .j av a2s.c o m throw new HTTPException(HTTPStatus.BAD_REQUEST); } } else { try { return MediaType.parse(request.getContentType()); } catch (IllegalArgumentException e) { throw new HTTPException(HTTPStatus.BAD_REQUEST, e); } } }
From source file:com.primeleaf.krystal.web.action.console.UpdateProfilePictureAction.java
@SuppressWarnings("rawtypes") public WebView execute(HttpServletRequest request, HttpServletResponse response) throws Exception { request.setCharacterEncoding(HTTPConstants.CHARACTER_ENCODING); HttpSession session = request.getSession(); User loggedInUser = (User) session.getAttribute(HTTPConstants.SESSION_KRYSTAL); if (request.getMethod().equalsIgnoreCase("POST")) { try {/*from w w w .jav a 2 s. c o m*/ String userName = loggedInUser.getUserName(); String sessionid = (String) session.getId(); String tempFilePath = System.getProperty("java.io.tmpdir"); if (!(tempFilePath.endsWith("/") || tempFilePath.endsWith("\\"))) { tempFilePath += System.getProperty("file.separator"); } tempFilePath += userName + "_" + sessionid; //variables String fileName = "", ext = ""; File file = null; // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); request.setCharacterEncoding(HTTPConstants.CHARACTER_ENCODING); upload.setHeaderEncoding(HTTPConstants.CHARACTER_ENCODING); List listItems = upload.parseRequest((HttpServletRequest) request); Iterator iter = listItems.iterator(); FileItem fileItem = null; while (iter.hasNext()) { fileItem = (FileItem) iter.next(); if (!fileItem.isFormField()) { try { fileName = fileItem.getName(); file = new File(fileName); fileName = file.getName(); ext = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase(); if (!"JPEG".equalsIgnoreCase(ext) && !"JPG".equalsIgnoreCase(ext) && !"PNG".equalsIgnoreCase(ext)) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid image. Please upload JPG or PNG file"); return (new MyProfileAction().execute(request, response)); } file = new File(tempFilePath + "." + ext); fileItem.write(file); } catch (Exception ex) { session.setAttribute("UPLOAD_ERROR", ex.getLocalizedMessage()); return (new MyProfileAction().execute(request, response)); } } } //if if (file.length() <= 0) { //code for checking minimum size of file request.setAttribute(HTTPConstants.REQUEST_ERROR, "Zero length document"); return (new MyProfileAction().execute(request, response)); } if (file.length() > (1024 * 1024 * 2)) { //code for checking minimum size of file request.setAttribute(HTTPConstants.REQUEST_ERROR, "Image size too large. Upload upto 2MB file"); return (new MyProfileAction().execute(request, response)); } User user = loggedInUser; user.setProfilePicture(file); UserDAO.getInstance().setProfilePicture(user); AuditLogManager.log(new AuditLogRecord(user.getUserId(), AuditLogRecord.OBJECT_USER, AuditLogRecord.ACTION_EDITED, loggedInUser.getUserName(), request.getRemoteAddr(), AuditLogRecord.LEVEL_INFO, "", "Profile picture update")); } catch (Exception e) { e.printStackTrace(System.out); } } request.setAttribute(HTTPConstants.REQUEST_MESSAGE, "Profile picture uploaded successfully"); return (new MyProfileAction().execute(request, response)); }
From source file:it.eng.spagobi.commons.filters.ProfileFilter.java
private String getUserIdInWebModeWithoutSSO(HttpServletRequest httpRequest) { UsernamePasswordCredentials credentials = this.findUserCredentials(httpRequest); if (credentials != null) { logger.debug("User credentials found."); if (!httpRequest.getMethod().equalsIgnoreCase("POST")) { logger.error("Request method is not POST!!!"); throw new InvalidMethodException(); }//from w ww . j a va 2 s . c o m logger.debug("Authenticating user ..."); try { this.authenticate(credentials); logger.debug("User authenticated"); } catch (Throwable t) { logger.error("Authentication failed", t); throw new SilentAuthenticationFailedException(); } } else { logger.debug("User credentials not found."); } String userId = credentials != null ? credentials.getUserName() : null; return userId; }
From source file:com.tce.oauth2.spring.api.filter.CORSFilter.java
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; HttpServletRequest request = (HttpServletRequest) req; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Authorization, Content-Type"); response.setHeader("Access-Control-Max-Age", "3600"); if (!"OPTIONS".equals(request.getMethod())) { chain.doFilter(req, res);/*from ww w .j a v a 2 s .c om*/ } else { } }
From source file:com.globalsight.everest.webapp.pagehandler.administration.permission.PermissionGroupsHandler.java
private void handleFilters(HttpServletRequest p_request, SessionManager sessionMgr, String action) { String pNameFilter = (String) p_request.getParameter("pNameFilter"); String pCompanyFilter = (String) p_request.getParameter("pCompanyFilter"); if (p_request.getMethod().equalsIgnoreCase(WebAppConstants.REQUEST_METHOD_GET)) { pNameFilter = (String) sessionMgr.getAttribute("pNameFilter"); pCompanyFilter = (String) sessionMgr.getAttribute("pCompanyFilter"); }// w w w . j a v a 2 s. com sessionMgr.setAttribute("pNameFilter", pNameFilter == null ? "" : pNameFilter); sessionMgr.setAttribute("pCompanyFilter", pCompanyFilter == null ? "" : pCompanyFilter); }
From source file:com.sybase365.mobiliser.custom.project.channels.HttpChannelEnd.java
@SuppressWarnings("unchecked") @Override//from w w w . j a v a 2 s . com public void processRequest(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { LOG.debug("Incoming {} request", request.getMethod()); checkAndPrepare(request, response, false); final MultiValueMap<String, String> result = (MultiValueMap<String, String>) this.converter.read(null, new ServletServerHttpRequest(request)); final List<String> textList = result.get("text"); final List<String> fromList = result.get("from"); final List<String> toList = result.get("to"); final List<String> typeList = result.get("type"); if (textList == null || textList.isEmpty()) { throw new MissingServletRequestParameterException("text", "string"); } if (fromList == null || fromList.isEmpty()) { throw new MissingServletRequestParameterException("from", "string"); } if (toList == null || toList.isEmpty()) { throw new MissingServletRequestParameterException("to", "string"); } final String type; if (null == typeList || typeList.isEmpty()) { type = "sms"; } else { type = typeList.get(0); } final Message req = this.messagingEngine.parseSimpleTextMessage(type, textList.get(0)); req.setSender(fromList.get(0)); req.setRecipient(toList.get(0)); if (LOG.isDebugEnabled()) { LOG.debug("{} message received for {} from {}", new Object[] { type, req.getRecipient(), req.getSender() }); } final Future<Message> responseMessage = this.receiveCallback.receiveAndRespondMessage(req, this.channelId, this.incomingChannelId); if (LOG.isDebugEnabled()) { LOG.debug("Handed off message to {} for {} awaiting response", this.receiveCallback, this.incomingChannelId); } final Message message; try { message = responseMessage.get(); if (message == null) { LOG.warn("Timed out waiting for response from {}", responseMessage); throw new NestedServletException("Timed out waiting for message"); } } catch (final InterruptedException e) { Thread.currentThread().interrupt(); // reset flag throw new NestedServletException("Interrupted during processing", e); } catch (final ExecutionException e) { if (e.getCause() instanceof InterruptedException) { throw new NestedServletException( // NOSONAR "Interrupted during processing", e.getCause()); } throw new NestedServletException("Processing message failed", // NOSONAR e.getCause()); } LOG.debug("Writing response back to client"); final LinkedMultiValueMap<String, Object> responseMap = new LinkedMultiValueMap<String, Object>(); responseMap.add("from", message.getSender().getAddress()); responseMap.add("to", message.getRecipient().getAddress()); if (message instanceof SmsMessage) { responseMap.add("text", new String(((SmsMessage) message).getText().getContent(), ((SmsMessage) message).getText().getCharset())); } else if (message instanceof UssdTextMessage) { responseMap.add("text", new String(((UssdTextMessage) message).getText().getContent(), ((UssdTextMessage) message).getText().getCharset())); } this.converter.write(responseMap, this.mediaType, new ServletServerHttpResponse(response)); }
From source file:fr.paris.lutece.plugins.rest.service.LuteceJerseySpringServlet.java
/** * Checks if the request is authenticated. Sets {@link HttpServletResponse#SC_UNAUTHORIZED} if not, * calls {@link ServletContainer#doFilter(HttpServletRequest, HttpServletResponse, FilterChain)} otherwise. * @param request the HTTP request/* w ww .ja va2 s.c o m*/ * @param response the response * @param chain the filter chain * @throws IOException exception if I/O error * @throws ServletException exception if servlet error */ @Override public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { if (checkRequestAuthentification(request)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("LuteceJerseySpringServlet processing request : " + request.getMethod() + " " + request.getContextPath() + request.getServletPath()); } super.doFilter(request, response, chain); } else { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } }
From source file:net.solarnetwork.node.setup.test.DefaultSetupServiceTest.java
@Test public void renewNetworkCertificate() throws Exception { SetupIdentityInfo info = new SetupIdentityInfo(1L, TEST_CONF_VALUE, TEST_SOLARIN_HOST, getHttpServerPort(), false, TEST_PW_VALUE);//from w w w . ja va 2 s . co m expect(setupIdentityDao.getSetupIdentityInfo()).andReturn(info).atLeastOnce(); replayAll(); keystoreService.saveCACertificate(CA_CERT); keystoreService.generateNodeSelfSignedCertificate(TEST_DN); String csr = keystoreService.generateNodePKCS10CertificateRequestString(); X509Certificate originalCert; PemReader pemReader = new PemReader(new StringReader(csr)); try { PemObject pem = pemReader.readPemObject(); PKCS10CertificationRequest req = new PKCS10CertificationRequest(pem.getContent()); originalCert = PKITestUtils.sign(req, CA_CERT, CA_KEY_PAIR.getPrivate()); String signedPem = PKITestUtils.getPKCS7Encoding(new X509Certificate[] { originalCert }); keystoreService.saveNodeSignedCertificate(signedPem); log.debug("Saved signed node certificate {}:\n{}", originalCert.getSerialNumber(), signedPem); assertThat("Generated CSR", csr, notNullValue()); } finally { pemReader.close(); } // now let's renew! AbstractTestHandler handler = new AbstractTestHandler() { @Override protected boolean handleInternal(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws Exception { assertEquals("POST", request.getMethod()); assertEquals("/solarin/api/v1/sec/cert/renew", target); String password = request.getParameter("password"); assertEquals("foobar", password); String keystoreData = request.getParameter("keystore"); assertNotNull(keystoreData); byte[] data = Base64.decodeBase64(keystoreData); KeyStore keyStore = KeyStore.getInstance("pkcs12"); keyStore.load(new ByteArrayInputStream(data), password.toCharArray()); Certificate cert = keyStore.getCertificate("node"); assertNotNull(cert); assertTrue(cert instanceof X509Certificate); X509Certificate nodeCert = (X509Certificate) cert; assertEquals(new X500Principal(TEST_DN), nodeCert.getSubjectX500Principal()); assertEquals(CA_CERT.getSubjectX500Principal(), nodeCert.getIssuerX500Principal()); response.setContentType("application/json"); PrintWriter out = response.getWriter(); out.write("{\"success\":true}"); out.flush(); response.flushBuffer(); return true; } }; httpServer.addHandler(handler); service.renewNetworkCertificate("foobar"); }