List of usage examples for javax.servlet.http HttpServletRequestWrapper HttpServletRequestWrapper
public HttpServletRequestWrapper(HttpServletRequest request)
From source file:org.structr.web.datasource.RestDataSource.java
public List<GraphObject> getData(final RenderContext renderContext, final String restQuery) throws FrameworkException { final Map<Pattern, Class<? extends Resource>> resourceMap = new LinkedHashMap<>(); final SecurityContext securityContext = renderContext.getSecurityContext(); ResourceProvider resourceProvider = renderContext.getResourceProvider(); if (resourceProvider == null) { try {//from w w w. j a v a 2 s.c o m resourceProvider = UiResourceProvider.class.newInstance(); } catch (Throwable t) { logger.log(Level.SEVERE, "Couldn't establish a resource provider", t); return Collections.EMPTY_LIST; } } // inject resources resourceMap.putAll(resourceProvider.getResources()); Value<String> propertyView = new ThreadLocalPropertyView(); propertyView.set(securityContext, PropertyView.Ui); HttpServletRequest request = securityContext.getRequest(); if (request == null) { request = renderContext.getRequest(); } // initialize variables // mimic HTTP request final HttpServletRequest wrappedRequest = new HttpServletRequestWrapper(request) { @Override public Enumeration<String> getParameterNames() { return new IteratorEnumeration(getParameterMap().keySet().iterator()); } @Override public String getParameter(final String key) { String[] p = getParameterMap().get(key); return p != null ? p[0] : null; } @Override public String[] getParameterValues(final String key) { return getParameterMap().get(key); } @Override public Map<String, String[]> getParameterMap() { String[] parts = StringUtils.split(getQueryString(), "&"); Map<String, String[]> parameterMap = new HashMap(); for (String p : parts) { String[] kv = StringUtils.split(p, "="); if (kv.length > 1) { parameterMap.put(kv[0], new String[] { kv[1] }); } } return parameterMap; } @Override public String getQueryString() { return StringUtils.substringAfter(restQuery, "?"); } @Override public String getPathInfo() { return StringUtils.substringBefore(restQuery, "?"); } @Override public StringBuffer getRequestURL() { return new StringBuffer(restQuery); } }; // store original request final HttpServletRequest origRequest = securityContext.getRequest(); // update request in security context securityContext.setRequest(wrappedRequest); //HttpServletResponse response = renderContext.getResponse(); Resource resource = null; try { resource = ResourceHelper.applyViewTransformation(wrappedRequest, securityContext, ResourceHelper.optimizeNestedResourceChain( ResourceHelper.parsePath(securityContext, wrappedRequest, resourceMap, propertyView)), propertyView); } catch (IllegalPathException | NotFoundException e) { logger.log(Level.WARNING, "Illegal path for REST query: {0}", restQuery); } // reset request to old context securityContext.setRequest(origRequest); if (resource == null) { return Collections.EMPTY_LIST; } // TODO: decide if we need to rest the REST request here //securityContext.checkResourceAccess(request, resource.getResourceSignature(), resource.getGrant(request, response), PropertyView.Ui); // add sorting & paging String pageSizeParameter = wrappedRequest.getParameter(JsonRestServlet.REQUEST_PARAMETER_PAGE_SIZE); String pageParameter = wrappedRequest.getParameter(JsonRestServlet.REQUEST_PARAMETER_PAGE_NUMBER); String offsetId = wrappedRequest.getParameter(JsonRestServlet.REQUEST_PARAMETER_OFFSET_ID); String sortOrder = wrappedRequest.getParameter(JsonRestServlet.REQUEST_PARAMETER_SORT_ORDER); String sortKeyName = wrappedRequest.getParameter(JsonRestServlet.REQUEST_PARAMETER_SORT_KEY); boolean sortDescending = (sortOrder != null && "desc".equals(sortOrder.toLowerCase())); int pageSize = parseInt(pageSizeParameter, NodeFactory.DEFAULT_PAGE_SIZE); int page = parseInt(pageParameter, NodeFactory.DEFAULT_PAGE); PropertyKey sortKey = null; // set sort key if (sortKeyName != null) { Class<? extends GraphObject> type = resource.getEntityClass(); if (type == null) { // fallback to default implementation // if no type can be determined type = AbstractNode.class; } sortKey = StructrApp.getConfiguration().getPropertyKeyForDatabaseName(type, sortKeyName, false); } // do action Result result = Result.EMPTY_RESULT; try { result = resource.doGet(sortKey, sortDescending, pageSize, page, offsetId); } catch (NotFoundException nfe) { logger.log(Level.WARNING, "No result from internal REST query: {0}", restQuery); } result.setIsCollection(resource.isCollectionResource()); result.setIsPrimitiveArray(resource.isPrimitiveArray()); //Integer rawResultCount = (Integer) Services.getAttribute(NodeFactory.RAW_RESULT_COUNT + Thread.currentThread().getId()); PagingHelper.addPagingParameter(result, pageSize, page); List<GraphObject> res = result.getResults(); if (renderContext != null) { renderContext.setResult(result); } return res != null ? res : Collections.EMPTY_LIST; }
From source file:org.structr.websocket.command.WrappedRestCommand.java
@Override public void processMessage(WebSocketMessage webSocketData) throws FrameworkException { final Map<String, Object> nodeData = webSocketData.getNodeData(); final String method = (String) nodeData.get("method"); if (method == null || !(method.equals("POST") || method.equals("PUT"))) { logger.log(Level.WARNING, "Method not supported: {0}", method); getWebSocket().send(/*w w w.j a v a 2s. c o m*/ MessageBuilder.wrappedRest().code(422).message("Method not supported: " + method).build(), true); return; } ResourceProvider resourceProvider; try { resourceProvider = UiResourceProvider.class.newInstance(); } catch (Throwable t) { logger.log(Level.SEVERE, "Couldn't establish a resource provider", t); getWebSocket().send(MessageBuilder.wrappedRest().code(422) .message("Couldn't establish a resource provider").build(), true); return; } final Map<Pattern, Class<? extends Resource>> resourceMap = new LinkedHashMap<>(); resourceMap.putAll(resourceProvider.getResources()); final StructrWebSocket socket = this.getWebSocket(); final String url = (String) nodeData.get("url"); // mimic HTTP request final HttpServletRequest wrappedRequest = new HttpServletRequestWrapper(socket.getRequest()) { @Override public Enumeration<String> getParameterNames() { return new IteratorEnumeration(getParameterMap().keySet().iterator()); } @Override public String getParameter(String key) { String[] p = getParameterMap().get(key); return p != null ? p[0] : null; } @Override public Map<String, String[]> getParameterMap() { String[] parts = StringUtils.split(getQueryString(), "&"); Map<String, String[]> parameterMap = new HashMap(); for (String p : parts) { String[] kv = StringUtils.split(p, "="); if (kv.length > 1) { parameterMap.put(kv[0], new String[] { kv[1] }); } } return parameterMap; } @Override public String getQueryString() { return StringUtils.substringAfter(url, "?"); } @Override public String getPathInfo() { return StringUtils.substringBefore(url, "?"); } @Override public StringBuffer getRequestURL() { return new StringBuffer(url); } }; Resource resource; final StaticValue fakePropertyView = new StaticValue(PropertyView.Public); try { resource = ResourceHelper .applyViewTransformation(wrappedRequest, socket.getSecurityContext(), ResourceHelper.optimizeNestedResourceChain(ResourceHelper.parsePath( socket.getSecurityContext(), wrappedRequest, resourceMap, fakePropertyView)), fakePropertyView); } catch (IllegalPathException | NotFoundException e) { logger.log(Level.WARNING, "Illegal path for REST query"); getWebSocket().send( MessageBuilder.wrappedRest().code(422).message("Illegal path for REST query").build(), true); return; } final String data = (String) nodeData.get("data"); final Gson gson = new GsonBuilder().create(); final Map<String, Object> jsonData = gson.fromJson(data, Map.class); RestMethodResult result = null; switch (method) { case "PUT": // we want to update data result = resource.doPut(jsonData); break; case "POST": // we either want to create data or call a method on an object result = resource.doPost(jsonData); break; } // right now we do not send messages if (result != null) { // getWebSocket().send(MessageBuilder.wrappedRest().code(result.getResponseCode()).message(result.jsonMessage()).build(), true); } }
From source file:org.wso2.carbon.identity.core.filter.AuthorizationHeaderFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final HttpServletRequest req = (HttpServletRequest) request; final String authHeader = req.getHeader(HTTPConstants.HEADER_AUTHORIZATION); if (StringUtils.isEmpty(authHeader)) { chain.doFilter(request, response); return;//from w w w . j a v a 2 s .c om } String authType = null; if (authHeader.length() >= AUTH_TYPE_BASIC_LENGTH) { authType = authHeader.trim().substring(0, AUTH_TYPE_BASIC_LENGTH); } if (AUTH_TYPE_BASIC.equals(authType)) { final String authCredentials = (authHeader.trim().substring(AUTH_TYPE_BASIC_LENGTH)).trim(); //if auth header comes in invalid format send error in response if (StringUtils.isBlank(authCredentials) || authCredentials.indexOf(' ') >= 0 || authCredentials.length() < MINIMUM_CREDENTIAL_SIZE) { String errorMsg = "Internal Server Error"; handleErrorResponse((HttpServletResponse) response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, errorMsg); } else if (authHeader.substring((AUTH_TYPE_BASIC + " ").length()).startsWith(" ")) { //if there is more than single space between auth_type and credentials modify the request header HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(req) { @Override public Enumeration<String> getHeaders(String name) { if (StringUtils.equalsIgnoreCase(name, HTTPConstants.HEADER_AUTHORIZATION)) { Enumeration<String> headerValues = req.getHeaders(name); ArrayList<String> newHeaderValues = new ArrayList<>(); while (headerValues.hasMoreElements()) { String value = headerValues.nextElement(); if (StringUtils.equals(value, authHeader)) { value = AUTH_TYPE_BASIC + " " + authCredentials; newHeaderValues.add(value); } else { newHeaderValues.add(value); } } return Collections.enumeration(newHeaderValues); } return super.getHeaders(name); } }; // pass the request along the filter chain chain.doFilter(wrapper, response); } //if auth header comes in correct format, forward else { chain.doFilter(request, response); } } else { chain.doFilter(request, response); } }
From source file:servletunit.struts.MockStrutsTestCase.java
/** * Returns a HttpServletRequestWrapper object that can be used * in this test. Note that if {@link #setRequestWrapper} has not been * called, this method will return an instance of * javax.servlet.http.HttpServletRequestWrapper. *///from w w w .ja va 2 s .c o m public HttpServletRequestWrapper getRequestWrapper() { if (logger.isDebugEnabled()) logger.debug("Entering"); init(); if (requestWrapper == null) { if (logger.isDebugEnabled()) logger.debug("Exiting"); return new HttpServletRequestWrapper(this.request); } else { if (logger.isDebugEnabled()) { logger.debug("wrapper class is '" + requestWrapper.getClass() + "'"); } if (logger.isDebugEnabled()) logger.debug("Exiting"); return requestWrapper; } }
From source file:uk.ac.lancs.e_science.fileUpload.UploadFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { chain.doFilter(request, response); return;//from w w w .ja v a2 s . c om } HttpServletRequest httpRequest = (HttpServletRequest) request; String contentLength = httpRequest.getHeader("Content-Length"); try { if (sizeMax != -1 && contentLength != null && Long.parseLong(contentLength) > sizeMax) { ServletException servletEx = new ServletException("Uploaded file size excess maximun legal"); throw servletEx; } } catch (NumberFormatException e) { e.printStackTrace(); //nothing } boolean isMultipartContent = FileUpload.isMultipartContent(httpRequest); if (!isMultipartContent) { chain.doFilter(request, response); return; } DiskFileUpload upload = new DiskFileUpload(); if (repositoryPath != null) upload.setRepositoryPath(repositoryPath); try { // SAK-13408 - Websphere cannot properly read the request if it has already been parsed and // marked by the Apache Commons FileUpload library. The request needs to be buffered so that // it can be reset for subsequent processing if ("websphere".equals(ServerConfigurationService.getString("servlet.container"))) { HttpServletRequest bufferedInputRequest = new BufferedHttpServletRequestWrapper(httpRequest); httpRequest = bufferedInputRequest; } List list = upload.parseRequest(httpRequest); if ("websphere".equals(ServerConfigurationService.getString("servlet.container"))) { httpRequest.getInputStream().reset(); } final Map map = new HashMap(); for (int i = 0; i < list.size(); i++) { FileItem item = (FileItem) list.get(i); String str = item.getString("UTF-8"); if (item.isFormField()) map.put(item.getFieldName(), new String[] { str }); else httpRequest.setAttribute(item.getFieldName(), item); } chain.doFilter(new HttpServletRequestWrapper(httpRequest) { public Map getParameterMap() { return map; } public String[] getParameterValues(String name) { Map map = getParameterMap(); return (String[]) map.get(name); } public String getParameter(String name) { String[] params = getParameterValues(name); if (params == null) return null; return params[0]; } public Enumeration getParameterNames() { Map map = getParameterMap(); return Collections.enumeration(map.keySet()); } }, response); } catch (FileUploadException ex) { ServletException servletEx = new ServletException(); servletEx.initCause(ex); throw servletEx; } }