List of usage examples for javax.servlet.http HttpServletRequest getQueryString
public String getQueryString();
From source file:net.hillsdon.reviki.web.dispatching.impl.DispatcherImpl.java
private void handleException(final HttpServletRequest request, final HttpServletResponse response, final Exception ex, final boolean logTrace, final String customMessage, final int statusCode) throws ServletException, IOException { response.setStatus(statusCode);/*from w w w . j av a 2s. c om*/ String user = (String) request.getAttribute(RequestAttributes.USERNAME); if (user == null) { user = "[none]"; } String queryString = request.getQueryString(); String uri = request.getRequestURI() + (queryString == null ? "" : "?" + queryString); String message = format("%s for user '%s' accessing '%s'.", ex.getClass().getSimpleName(), user, uri); if (logTrace) { LOG.error(message, ex); } else { LOG.warn(message, null); } request.setAttribute("exception", ex); request.setAttribute("customMessage", customMessage); request.getRequestDispatcher("/WEB-INF/templates/Error.jsp").forward(request, response); }
From source file:nl.surfnet.mujina.controllers.OpenSocialAPI.java
@RequestMapping(value = "/parseAnchor.shtml", method = RequestMethod.GET) @ResponseBody/*from ww w .jav a 2 s.c o m*/ public String parseAnchor(HttpServletRequest request, HttpServletResponse response) throws IOException { String token = request.getParameter("access_token"); Token accessToken = new Token(token, ""); request.getSession().setAttribute("accessToken", accessToken); return request.getQueryString(); }
From source file:io.seldon.api.interceptor.GenericScopedInterceptor.java
private ScopedConsumerBean authorise(HttpServletRequest request) { final ScopedConsumerBean scopedConsumerBean = authorizationServer.getConsumer(request); if (scopedConsumerBean != null) MDCKeys.addKeysConsumer(scopedConsumerBean); final TokenScope.Scope tokenScope = TokenScope.fromString(scopedConsumerBean.getScope()); final String requestURI = request.getRequestURI(); final String queryString = request.getQueryString(); final String requestInfo = requestURI + ", " + queryString; if (tokenScope == getScope() && validReferrer(request, scopedConsumerBean)) { if (logger.isDebugEnabled()) logger.debug("Scope and referrer valid for request: " + requestInfo); return scopedConsumerBean; } else {/*w w w. ja v a 2 s . co m*/ logger.warn("Incorrect scope of invalid referrer in request for: " + requestInfo); throw new APIException(APIException.METHOD_NOT_AUTHORIZED); // create additional error code? } }
From source file:nl.mineleni.cbsviewer.servlet.ReverseProxyServlet.java
/** * Process the HTTP Get request. Voor een Openlayers proxy wordt de url dan * iets van: <br>//from www. ja v a2s. co m * <code>WMSproxy/proxy?</code> <br> * waarin WMSproxy de naam van de webapp is en proxy de servlet mapping. * * @param request * the request * @param response * the response * @throws ServletException * the servlet exception */ @Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException { try { String serverUrl = request.getQueryString(); serverUrl = URLDecoder.decode(serverUrl, "UTF-8"); if (serverUrl.startsWith("http://") || serverUrl.startsWith("https://")) { // check if allowed if (!this.checkUrlAllowed(serverUrl)) { LOGGER.warn(serverUrl + ERR_MSG_FORBIDDEN); response.sendError(SC_FORBIDDEN, serverUrl + ERR_MSG_FORBIDDEN); response.flushBuffer(); } else { // intercept and modify request if (serverUrl.contains("GetFeatureInfo")) { serverUrl = serverUrl.replace("text%2Fhtml", URLEncoder.encode(type.toString(), "UTF-8")); serverUrl = serverUrl.replace("text/html", URLEncoder.encode(type.toString(), "UTF-8")); if (LOGGER.isDebugEnabled()) { LOGGER.debug("proxy GetFeatureInfo GET param: " + serverUrl); } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Execute proxy GET param:" + serverUrl); } final HttpGet httpget = new HttpGet(serverUrl); httpget.setConfig(this.requestConfig); final HttpResponse get = this.client.execute(httpget); if (get.getStatusLine().getStatusCode() == SC_OK) { String responseBody; if (serverUrl.contains("GetFeatureInfo")) { String lName = ""; String styles = ""; // uitzoeken querylayers final String[] params = serverUrl.split("&"); for (final String s : params) { if (s.contains("QUERY_LAYERS=")) { lName = EncodingUtil .decodeURIComponent(s.substring("QUERY_LAYERS=".length(), s.length())); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Query layers = " + lName); } } if (s.contains("STYLES=")) { styles = EncodingUtil .decodeURIComponent(s.substring("STYLES=".length(), s.length())); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Layer styles = " + styles); } } } final String wmsUrl = serverUrl.substring(0, serverUrl.indexOf('?')); if (LOGGER.isDebugEnabled()) { LOGGER.debug("WMS url = " + wmsUrl); } responseBody = FeatureInfoResponseConverter.convertToHTMLTable( get.getEntity().getContent(), type, this.layers.getLayerByLayers(lName, wmsUrl, styles)); response.setContentType("text/html; charset=UTF-8"); } else { // force the response to have XML content type (WMS // servers generally don't) if (this.forceXmlResponse) { response.setContentType("text/xml"); } responseBody = EntityUtils.toString(get.getEntity()).trim(); } response.setCharacterEncoding("UTF-8"); // in het geval van multi byte chars, bijv 'Skarsterln' // is de lengte incorrect, laat voorlopig maar aan de // container over.. // response.setContentLength(responseBody.length()); final PrintWriter out = response.getWriter(); out.print(responseBody); response.flushBuffer(); } else { LOGGER.warn("Onverwachte fout(server url=" + serverUrl + "): " + get.getStatusLine().toString()); response.sendError(get.getStatusLine().getStatusCode(), get.getStatusLine().toString()); } httpget.reset(); } } else { throw new ServletException("Only HTTP(S) protocol is supported"); } } catch (final UnsupportedEncodingException e) { LOGGER.error("Proxy fout.", e); throw new ServletException(e); } catch (final IOException e) { LOGGER.error("Proxy IO fout.", e); throw new ServletException(e); } }
From source file:com.microsoft.aad.adal4jsample.BasicFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; try {// w w w .jav a 2 s .c o m String currentUri = httpRequest.getRequestURL().toString(); String queryStr = httpRequest.getQueryString(); String fullUrl = currentUri + (queryStr != null ? "?" + queryStr : ""); // check if user has a AuthData in the session if (!AuthHelper.isAuthenticated(httpRequest)) { if (AuthHelper.containsAuthenticationData(httpRequest)) { processAuthenticationData(httpRequest, currentUri, fullUrl); } else { // not authenticated sendAuthRedirect(httpRequest, httpResponse); return; } } if (isAuthDataExpired(httpRequest)) { updateAuthDataUsingRefreshToken(httpRequest); } } catch (AuthenticationException authException) { // something went wrong (like expiration or revocation of token) // we should invalidate AuthData stored in session and redirect to Authorization server removePrincipalFromSession(httpRequest); sendAuthRedirect(httpRequest, httpResponse); return; } catch (Throwable exc) { httpResponse.setStatus(500); request.setAttribute("error", exc.getMessage()); request.getRequestDispatcher("/error.jsp").forward(request, response); } } chain.doFilter(request, response); }
From source file:com.envision.envservice.filter.AccessLogFilter.java
private void logAccessAPI(HttpServletRequest request) { try {//from w w w.j a v a 2s . c o m UserBo user = (UserBo) request.getSession().getAttribute(Constants.SESSION_USER); String userId = user != null ? user.getUser_id() : "NOT_LOGIN"; String remoteAddr = IPUtil.getRemoteAddr(request); String method = request.getMethod(); String requestURI = request.getRequestURI(); String userAgent = StringUtils.defaultString(request.getHeader("User-Agent")); String queryString = request.getQueryString(); if (queryString != null) { queryString = URLDecoder.decode(request.getQueryString(), Constants.CHARSET); } requestURI = requestURI + (StringUtils.isNotEmpty(queryString) ? ("?" + queryString) : StringUtils.EMPTY); EnvLog.getAccessAPILogger().info( String.format("[%s] [%s] [%s] %s [%s]", userId, remoteAddr, method, requestURI, userAgent)); } catch (Exception e) { EnvLog.getAccessAPILogger().warn("AccessAPI logger error: " + e.getMessage(), e); } }
From source file:se.skltp.cooperation.web.rest.exception.DefaultExceptionHandler.java
private void buildErrorMessage(HttpServletRequest request, Exception e, HttpStatus status, ProblemDetail error) {/*from w ww . j av a 2s. com*/ try { error.setType(new URI("http://httpstatus.es/" + status.value())); } catch (URISyntaxException e1) { log.error("Unable to set error type", e); } error.setTitle(status.getReasonPhrase()); error.setStatus(status.value()); error.setDetail(e.getMessage()); String url = request.getRequestURL().toString(); if (request.getQueryString() != null) { url = url + "?" + request.getQueryString(); } error.setInstance(url); }
From source file:de.jaxenter.eesummit.caroline.gui.filter.LogFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { String remoteAddress = null;/*from ww w. ja v a 2 s . c o m*/ String sessionId = null; String uid = "0"; long start = 0; String url = ""; String method = ""; Throwable throwable = null; boolean dropped = false; String agent = null; try { Validate.isTrue(request instanceof HttpServletRequest, "filter oops?"); HttpServletRequest req = (HttpServletRequest) request; if (req.getCharacterEncoding() == null || forceRequestEncoding) { req.setCharacterEncoding(requestEncoding); } url = req.getRequestURI(); method = req.getMethod(); String qs = req.getQueryString(); agent = req.getHeader("User-Agent"); if (qs != null) { url += "?" + qs; } for (String stopUrl : dropUrls) { // does any stopUrl match url if (url.indexOf(stopUrl) != -1) { dropped = true; break; // stop searching } } if (!dropped) { if (ndcEnabled) { if (ndcAddress) { String forwarded = req.getHeader("X-Forwarded-For"); if (forwarded != null) { remoteAddress = forwarded; } else { remoteAddress = request.getRemoteAddr(); } } if (ndcSession) { HttpSession session = req.getSession(false); // do not create if (session != null) { sessionId = session.getId(); String sessOID = (String) session.getAttribute("USER_ID_LOG"); uid = sessOID == null ? "0" : sessOID; } } } StringBuilder msg = simulateNDC(remoteAddress, sessionId, uid); msg.append("request start ").append(method).append(" ").append(url).append(" UA=").append(agent); logger.info(msg.toString()); start = System.currentTimeMillis(); } filterChain.doFilter(request, response); } catch (IOException e) { throwable = e; throw e; } catch (ServletException e) { if (e.getRootCause() != null) { throwable = e.getRootCause(); } else { throwable = e; } throw e; } catch (Throwable e) { // be sure to get all errors throwable = e; throw new ServletException(e); } finally { if (!dropped) { long time = System.currentTimeMillis() - start; StringBuilder msg = simulateNDC(remoteAddress, sessionId, uid); msg.append("request done ").append(method).append(" "); msg.append(url).append(" time=").append(time).append("ms"); if (throwable == null) { logger.info(msg.toString()); } else { String name = throwable.getClass().getSimpleName(); msg.append(" ex=").append(name); msg.append(" msg=").append(throwable.getMessage()); if (name.equals("ViewExpiredException") || name.equals("ClientAbortException")) { logger.warn(msg.toString()); } else { msg.append(" UA=").append(agent); // also log agent in error case logger.error(msg.toString()); } } } } }
From source file:com.ibm.jaggr.core.impl.transport.AbstractHttpTransport.java
/** * Returns the value of the requested parameter from the request, or null * * @param request//from w w w.j av a 2s.c o m * the request object * @param aliases * array of query arg names by which the request may be specified * @return the value of the param, or null if it is not specified under the * specified names */ protected static String getParameter(HttpServletRequest request, String[] aliases) { final String sourceMethod = "getParameter"; //$NON-NLS-1$ boolean isTraceLogging = log.isLoggable(Level.FINER); if (isTraceLogging) { log.entering(AbstractHttpTransport.class.getName(), sourceMethod, new Object[] { request.getQueryString(), Arrays.asList(aliases) }); } Map<String, String[]> params = request.getParameterMap(); String result = null; for (Map.Entry<String, String[]> entry : params.entrySet()) { String name = entry.getKey(); for (String alias : aliases) { if (alias.equalsIgnoreCase(name)) { String[] values = entry.getValue(); result = values[values.length - 1]; // return last value in array } } } if (isTraceLogging) { log.exiting(AbstractHttpTransport.class.getName(), sourceMethod, result); } return result; }