Java Code Examples for javax.servlet.http.HttpServletRequest#getQueryString()

The following examples show how to use javax.servlet.http.HttpServletRequest#getQueryString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestJobEndNotifier.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Override
public void doGet(HttpServletRequest request, 
                  HttpServletResponse response
                  ) throws ServletException, IOException {
  InputStreamReader in = new InputStreamReader(request.getInputStream());
  PrintStream out = new PrintStream(response.getOutputStream());

  calledTimes++;
  try {
    requestUri = new URI(null, null,
        request.getRequestURI(), request.getQueryString(), null);
  } catch (URISyntaxException e) {
  }

  in.close();
  out.close();
}
 
Example 2
Source File: ActiveServerFilter.java    From incubator-atlas with Apache License 2.0 6 votes vote down vote up
private void handleRedirect(HttpServletRequest servletRequest, HttpServletResponse httpServletResponse,
                            String activeServerAddress) throws IOException {
    String requestURI = servletRequest.getRequestURI();
    String queryString = servletRequest.getQueryString();
    if ((queryString != null) && (!queryString.isEmpty())) {
        requestURI += "?" + queryString;
    }
    String quotedUri = HtmlQuoting.quoteHtmlChars(requestURI);
    if (quotedUri == null) {
        quotedUri = "/";
    }
    String redirectLocation = activeServerAddress + quotedUri;
    LOG.info("Not active. Redirecting to {}", redirectLocation);
    // A POST/PUT/DELETE require special handling by sending HTTP 307 instead of the regular 301/302.
    // Reference: http://stackoverflow.com/questions/2068418/whats-the-difference-between-a-302-and-a-307-redirect
    if (isUnsafeHttpMethod(servletRequest)) {
        httpServletResponse.setHeader(HttpHeaders.LOCATION, redirectLocation);
        httpServletResponse.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
    } else {
        httpServletResponse.sendRedirect(redirectLocation);
    }
}
 
Example 3
Source File: SecureBaseAction.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
  AccountActionForm acctForm = (AccountActionForm) request.getSession().getAttribute("accountForm");
  if (acctForm == null || acctForm.getAccount() == null) {
    String url = request.getServletPath();
    String query = request.getQueryString();
    if (query != null) {
      request.setAttribute("signonForwardAction", url+"?"+query);
    }
	else {
      request.setAttribute("signonForwardAction", url);
    }
    return mapping.findForward("global-signon");
  }
else {
    return doExecute(mapping, form, request, response);
  }
}
 
Example 4
Source File: PeopleController.java    From scoold with Apache License 2.0 6 votes vote down vote up
@PostMapping("/bulk-edit")
public String bulkEdit(@RequestParam(required = false) String[] selectedUsers,
		@RequestParam(required = false) String[] selectedSpaces, HttpServletRequest req) {
	Profile authUser = utils.getAuthUser(req);
	boolean isAdmin = utils.isAdmin(authUser);
	if (isAdmin && selectedUsers != null) {
		ArrayList<Map<String, Object>> toUpdate = new ArrayList<>();
		for (String selectedUser : selectedUsers) {
			if (!StringUtils.isBlank(selectedUser)) {
				Map<String, Object> profile = new HashMap<>();
				profile.put(Config._ID, selectedUser);
				if (selectedSpaces == null) {
					selectedSpaces = new String[]{};
				}
				profile.put("spaces", Arrays.asList(selectedSpaces));
				toUpdate.add(profile);
			}
		}
		if (!toUpdate.isEmpty()) {
			// partial batch update
			utils.getParaClient().invokePatch("_batch", Entity.json(toUpdate));
		}
	}
	return "redirect:" + PEOPLELINK + (isAdmin ? "?" + req.getQueryString() : "");
}
 
Example 5
Source File: ScipioUserLoginAuthPlugin.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
/**
 * Custom request param extraction code that extracts UTF-8-ENCODED parameter values
 * from the query string manually, avoiding ServletRequest.getParameter.
 * <p>
 * For externalLoginKey there's no need to unencode, but other parameters need
 * UTF-8 decoder.
 * <p>
 * IMPORTANT: This "filter" must not call the method ServletRequest.getParameter.
 * It causes a state change which breaks SolrDispatchFilter. Therefore we must parse
 * the query string manually.
 */
protected static String getRawRequestParameter(HttpServletRequest request, String name) {
    String queryString = request.getQueryString();
    if (queryString == null) return null;
    int paramValIdx;
    if (queryString.startsWith(name + "=")) {
        paramValIdx = name.length() + 1;
    } else {
        int idx = queryString.indexOf("&" + name + "=");
        if (idx < 0) return null;
        paramValIdx = idx + name.length() + 2;
    }
    // TODO: optimize this
    int termIdx = queryString.indexOf('&', paramValIdx);
    if (termIdx < 0) {
        queryString.indexOf(USERID_TENANTID_SEP, paramValIdx);
    }
    if (termIdx >= 0) {
        return queryString.substring(paramValIdx, termIdx);
    } else {
        return queryString.substring(paramValIdx);
    }
}
 
Example 6
Source File: OLATSessionTrackingFilter.java    From olat with Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    final HttpServletRequest httpRequest = (HttpServletRequest) request;
    MDC.put(LOGGING_KEY_SESSIONID, httpRequest.getSession().getId());

    if (log.isDebugEnabled()) {
        final StringBuilder requestedUrl = new StringBuilder();
        requestedUrl.append(httpRequest.getRequestURL());
        if (httpRequest.getQueryString() != null) {
            requestedUrl.append(httpRequest.getQueryString());
        }
        log.debug("request: " + requestedUrl + " for session: " + httpRequest.getRequestedSessionId());
    }

    chain.doFilter(request, response);

    MDC.remove(LOGGING_KEY_SESSIONID);
}
 
Example 7
Source File: BenchmarkTest02580.java    From Benchmark with GNU General Public License v2.0 5 votes vote down vote up
@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");

		String queryString = request.getQueryString();
		String paramval = "BenchmarkTest02580"+"=";
		int paramLoc = -1;
		if (queryString != null) paramLoc = queryString.indexOf(paramval);
		if (paramLoc == -1) {
			response.getWriter().println("getQueryString() couldn't find expected parameter '" + "BenchmarkTest02580" + "' in query string.");
			return;
		}
		
		String param = queryString.substring(paramLoc + paramval.length()); // 1st assume "BenchmarkTest02580" param is last parameter in query string.
		// And then check to see if its in the middle of the query string and if so, trim off what comes after.
		int ampersandLoc = queryString.indexOf("&", paramLoc);
		if (ampersandLoc != -1) {
			param = queryString.substring(paramLoc + paramval.length(), ampersandLoc);
		}
		param = java.net.URLDecoder.decode(param, "UTF-8");

		String bar = doSomething(request, param);
		
response.setHeader("X-XSS-Protection", "0");
		Object[] obj = { "a", "b" };
		response.getWriter().format(bar,obj);
	}
 
Example 8
Source File: BenchmarkTest00802.java    From Benchmark with GNU General Public License v2.0 5 votes vote down vote up
@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
	
		String queryString = request.getQueryString();
		String paramval = "BenchmarkTest00802"+"=";
		int paramLoc = -1;
		if (queryString != null) paramLoc = queryString.indexOf(paramval);
		if (paramLoc == -1) {
			response.getWriter().println("getQueryString() couldn't find expected parameter '" + "BenchmarkTest00802" + "' in query string.");
			return;
		}
		
		String param = queryString.substring(paramLoc + paramval.length()); // 1st assume "BenchmarkTest00802" param is last parameter in query string.
		// And then check to see if its in the middle of the query string and if so, trim off what comes after.
		int ampersandLoc = queryString.indexOf("&", paramLoc);
		if (ampersandLoc != -1) {
			param = queryString.substring(paramLoc + paramval.length(), ampersandLoc);
		}
		param = java.net.URLDecoder.decode(param, "UTF-8");
		
		
		String bar = "";
		if (param != null) {
			bar = new String( org.apache.commons.codec.binary.Base64.decodeBase64(
			org.apache.commons.codec.binary.Base64.encodeBase64( param.getBytes() ) ));
		}
		
		
response.setHeader("X-XSS-Protection", "0");
		response.getWriter().print(bar.toCharArray());
	}
 
Example 9
Source File: OpendapServlet.java    From tds with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected long getLastModified(HttpServletRequest req) {
  String query = req.getQueryString();
  if (query != null) {
    return -1;
  }

  String path = req.getPathInfo();
  if (path == null) {
    return -1;
  }

  if (path.endsWith(".asc")) {
    path = path.substring(0, path.length() - 4);
  } else if (path.endsWith(".ascii")) {
    path = path.substring(0, path.length() - 6);
  } else if (path.endsWith(".das")) {
    path = path.substring(0, path.length() - 4);
  } else if (path.endsWith(".dds")) {
    path = path.substring(0, path.length() - 4);
  } else if (path.endsWith(".ddx")) {
    path = path.substring(0, path.length() - 4);
  } else if (path.endsWith(".dods")) {
    path = path.substring(0, path.length() - 5);
  } else if (path.endsWith(".html")) {
    path = path.substring(0, path.length() - 5);
  } else if (path.endsWith(".info")) {
    path = path.substring(0, path.length() - 5);
  } else if (path.endsWith(".opendap")) {
    path = path.substring(0, path.length() - 5);
  } else {
    return -1;
  }

  // if (null != DatasetHandler.findResourceControl( path)) return -1; // LOOK weird Firefox behaviour?

  return TdsRequestedDataset.getLastModified(path);
}
 
Example 10
Source File: WebUtil.java    From blade-tool with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 获取 request 请求内容
 *
 * @param request request
 * @return String
 * @throws IOException IOException
 */
public static String getRequestStr(HttpServletRequest request) throws IOException {
	String queryString = request.getQueryString();
	if (StringUtil.isNotBlank(queryString)) {
		return new String(queryString.getBytes(Charsets.ISO_8859_1), Charsets.UTF_8).replaceAll("&amp;", "&").replaceAll("%22", "\"");
	}
	return getRequestStr(request, getRequestBytes(request));
}
 
Example 11
Source File: CallbackPolyvController.java    From roncoo-education with MIT License 5 votes vote down vote up
/**
 * 保利威视,视频授权播放回调接口
 */
@ApiOperation(value = "保利威视,视频授权播放回调接口", notes = "保利威视,视频授权播放回调接口")
@RequestMapping(value = "/auth", method = {RequestMethod.POST, RequestMethod.GET})
public String callbackPolyvAuth(PolyvAuth polyvAuth, HttpServletRequest request) {
    if (StringUtils.isEmpty(polyvAuth.getCallback())) {
        String sourceParam = request.getQueryString();
        sourceParam = sourceParam.replaceAll("vid=" + polyvAuth.getVid(), "");
        sourceParam = sourceParam.replaceAll("&t=" + polyvAuth.getT(), "");
        sourceParam = sourceParam.replaceAll("&code=", "").replace("+", "%2B");
        polyvAuth.setCode(sourceParam);
    }
    return biz.auth(polyvAuth);
}
 
Example 12
Source File: PerformanceMonitorInterceptor.java    From maven-framework-project with MIT License 4 votes vote down vote up
private String getURLPath(HttpServletRequest request) {
	String currentPath = request.getRequestURI();
	String queryString = request.getQueryString();
	queryString = queryString == null ? "" : "?" + queryString;
	return currentPath+queryString;
}
 
Example 13
Source File: FederationAuthenticator.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
private Authentication handleCachedAuthentication(HttpServletRequest request, HttpServletResponse response,
                                                  HttpSession session, FedizContext fedConfig) throws IOException {
    Authentication authentication =
        (Authentication) session.getAttribute(SessionAuthentication.__J_AUTHENTICATED);
    if (authentication != null) {
        // Has authentication been revoked?
        if (authentication instanceof Authentication.User
            && isTokenExpired(fedConfig, ((Authentication.User)authentication).getUserIdentity())) {
            session.removeAttribute(SessionAuthentication.__J_AUTHENTICATED);
        } else {
            //logout
            String action = request.getParameter(FederationConstants.PARAM_ACTION);
            boolean logout = FederationConstants.ACTION_SIGNOUT.equals(action);
            String logoutUrl = fedConfig.getLogoutURL();

            String uri = request.getRequestURI();
            if (uri == null) {
                uri = URIUtil.SLASH;
            }

            String contextName = request.getSession().getServletContext().getContextPath();
            if (contextName == null || contextName.isEmpty()) {
                contextName = "/";
            }

            if (logout || logoutUrl != null && !logoutUrl.isEmpty() && uri.equals(contextName + logoutUrl)) {
                session.invalidate();

                FedizProcessor wfProc =
                    FedizProcessorFactory.newFedizProcessor(fedConfig.getProtocol());
                signOutRedirectToIssuer(request, response, wfProc);

                return Authentication.SEND_CONTINUE;
            }

            String jUri = (String)session.getAttribute(J_URI);
            @SuppressWarnings("unchecked")
            MultiMap<String> jPost = (MultiMap<String>)session.getAttribute(J_POST);
            if (jUri != null && jPost != null) {
                StringBuffer buf = request.getRequestURL();
                if (request.getQueryString() != null) {
                    buf.append('?').append(request.getQueryString());
                }

                if (jUri.equals(buf.toString())) {
                    // This is a retry of an original POST request
                    // so restore method and parameters

                    session.removeAttribute(J_POST);
                    Request baseRequest = (Request)request;
                    // (req instanceof Request)?(Request)
                    // req:HttpConnection.getCurrentConnection().getRequest();
                    baseRequest.setMethod(HttpMethod.POST.asString());
                    baseRequest.setQueryParameters(jPost);
                }
            } else if (jUri != null) {
                session.removeAttribute(J_URI);
            }

            return authentication;
        }
    }
    return null;
}
 
Example 14
Source File: CasDefaultFlowUrlHandler.java    From springboot-shiro-cas-mybatis with MIT License 4 votes vote down vote up
@Override
public String createFlowDefinitionUrl(final String flowId, final AttributeMap input, final HttpServletRequest request) {
    return request.getRequestURI()
        + (request.getQueryString() != null ? '?'
        + request.getQueryString() : "");
}
 
Example 15
Source File: BenchmarkTest00850.java    From Benchmark with GNU General Public License v2.0 4 votes vote down vote up
@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
	
		String queryString = request.getQueryString();
		String paramval = "BenchmarkTest00850"+"=";
		int paramLoc = -1;
		if (queryString != null) paramLoc = queryString.indexOf(paramval);
		if (paramLoc == -1) {
			response.getWriter().println("getQueryString() couldn't find expected parameter '" + "BenchmarkTest00850" + "' in query string.");
			return;
		}
		
		String param = queryString.substring(paramLoc + paramval.length()); // 1st assume "BenchmarkTest00850" param is last parameter in query string.
		// And then check to see if its in the middle of the query string and if so, trim off what comes after.
		int ampersandLoc = queryString.indexOf("&", paramLoc);
		if (ampersandLoc != -1) {
			param = queryString.substring(paramLoc + paramval.length(), ampersandLoc);
		}
		param = java.net.URLDecoder.decode(param, "UTF-8");
		
		
		String bar = "";
		if (param != null) {
			java.util.List<String> valuesList = new java.util.ArrayList<String>( );
			valuesList.add("safe");
			valuesList.add( param );
			valuesList.add( "moresafe" );
			
			valuesList.remove(0); // remove the 1st safe value
			
			bar = valuesList.get(0); // get the param value
		}
		
		
		String sql = "SELECT * from USERS where USERNAME='foo' and PASSWORD='"+ bar +"'";
				
		try {
			java.sql.Statement statement = org.owasp.benchmark.helpers.DatabaseHelper.getSqlStatement();
			java.sql.ResultSet rs = statement.executeQuery( sql );
            org.owasp.benchmark.helpers.DatabaseHelper.printResults(rs, sql, response);
		} catch (java.sql.SQLException e) {
			if (org.owasp.benchmark.helpers.DatabaseHelper.hideSQLErrors) {
        		response.getWriter().println(
"Error processing request."
);
        		return;
        	}
			else throw new ServletException(e);
		}
	}
 
Example 16
Source File: AtlasKnoxSSOAuthenticationFilter.java    From atlas with Apache License 2.0 4 votes vote down vote up
private String getOriginalQueryString(HttpServletRequest request) {
    String originalQueryString = request.getQueryString();
    return (originalQueryString == null) ? "" : "?" + originalQueryString;
}
 
Example 17
Source File: UrlUtil.java    From heimdall with Apache License 2.0 4 votes vote down vote up
/**
* Returns the current URL from a {@link HttpServletRequest}.
* 
* @param 	request			The {@link HttpServletRequest}
* @return					The current URL as a {@link String}
*/
  public static String getCurrentUrl(HttpServletRequest request) {

       try {

            URL url = new URL(request.getRequestURL().toString());

            String query = request.getQueryString();
            if (query != null) {

                 return url.toString() + "?" + query;
            } else {

                 return url.toString();
            }

       } catch (Exception e) {
            log.error(e.getMessage(), e);
       }

       return null;
  }
 
Example 18
Source File: RequestServlet.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 4 votes vote down vote up
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	logger.info("访问 doGet");

	request.setCharacterEncoding("UTF-8");
	response.setCharacterEncoding("UTF-8");

	response.setContentType("text/html");

	String authType = request.getAuthType();
	String localAddr = request.getLocalAddr();
	Locale locale = request.getLocale();
	String localName = request.getLocalName();
	String contextPath = request.getContextPath();
	int localPort = request.getLocalPort();
	String method = request.getMethod();
	String pathInfo = request.getPathInfo();
	String pathTranslated = request.getPathTranslated();
	String protocol = request.getProtocol();
	String queryString = request.getQueryString();
	String remoteAddr = request.getRemoteAddr();
	int port = request.getRemotePort();
	String remoteUser = request.getRemoteUser();
	String requestedSessionId = request.getRequestedSessionId();
	String requestURI = request.getRequestURI();
	StringBuffer requestURL = request.getRequestURL();
	String scheme = request.getScheme();
	String serverName = request.getServerName();
	int serverPort = request.getServerPort();
	String servletPath = request.getServletPath();
	Principal userPrincipal = request.getUserPrincipal();

	String accept = request.getHeader("accept");
	String referer = request.getHeader("referer");
	String userAgent = request.getHeader("user-agent");

	String serverInfo = this.getServletContext().getServerInfo();

	PrintWriter out = response.getWriter();
	out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
	out.println("<HTML>");

	// 这里<title></title>之间的信息在浏览器中显示为标题
	out.println("  <HEAD><TITLE>Request Servlet</TITLE></HEAD>");
	out.println("  <style>body, font, td, div {font-size:12px; line-height:18px; }</style>");
	out.println("  <BODY>");

	out.println("<b>您的IP为</b> " + remoteAddr + "<b>;您使用</b> " + getOS(userAgent) + " <b>操作系统</b>,"
		+ getNavigator(userAgent) + " <b>。您使用</b> " + getLocale(locale) + "。<br/>");
	out.println("<b>服务器IP为</b> " + localAddr + localAddr + "<b>;服务器使用</b> " + serverPort + " <b>端口,您的浏览器使用了</b> "
		+ port + " <b>端口访问本网页。</b><br/>");
	out.println("<b>服务器软件为</b>:" + serverInfo + "。<b>服务器名称为</b> " + localName + "。<br/>");
	out.println("<b>您的浏览器接受</b> " + getAccept(accept) + "。<br/>");
	out.println("<b>您从</b> " + referer + " <b>访问到该页面。</b><br/>");
	out.println("<b>使用的协议为</b> " + protocol + "。<b>URL协议头</b> " + scheme + ",<b>服务器名称</b> " + serverName
		+ ",<b>您访问的URI为</b> " + requestURI + "。<br/>");
	out.println("<b>该 Servlet 路径为</b> " + servletPath + ",<b>该 Servlet 类名为</b> " + this.getClass().getName()
		+ "。<br/>");
	out.println("<b>本应用程序在硬盘的根目录为</b> " + this.getServletContext().getRealPath("") + ",<b>网络相对路径为</b> "
		+ contextPath + "。 <br/>");

	out.println("<br/>");

	out.println("<br/><br/><a href=" + requestURI + "> 点击刷新本页面 </a>");

	out.println("  </BODY>");
	out.println("</HTML>");
	out.flush();
	out.close();
}
 
Example 19
Source File: BenchmarkTest02617.java    From Benchmark with GNU General Public License v2.0 4 votes vote down vote up
@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");

		String queryString = request.getQueryString();
		String paramval = "BenchmarkTest02617"+"=";
		int paramLoc = -1;
		if (queryString != null) paramLoc = queryString.indexOf(paramval);
		if (paramLoc == -1) {
			response.getWriter().println("getQueryString() couldn't find expected parameter '" + "BenchmarkTest02617" + "' in query string.");
			return;
		}
		
		String param = queryString.substring(paramLoc + paramval.length()); // 1st assume "BenchmarkTest02617" param is last parameter in query string.
		// And then check to see if its in the middle of the query string and if so, trim off what comes after.
		int ampersandLoc = queryString.indexOf("&", paramLoc);
		if (ampersandLoc != -1) {
			param = queryString.substring(paramLoc + paramval.length(), ampersandLoc);
		}
		param = java.net.URLDecoder.decode(param, "UTF-8");

		String bar = doSomething(request, param);
		
	    try {
		    java.security.SecureRandom secureRandomGenerator = java.security.SecureRandom.getInstance("SHA1PRNG");
		
		    // Get 40 random bytes
		    byte[] randomBytes = new byte[40];
		    secureRandomGenerator.nextBytes(randomBytes);
		    
	        String rememberMeKey = org.owasp.esapi.ESAPI.encoder().encodeForBase64(randomBytes, true);
	
			String user = "SafeByron";
			String fullClassName = this.getClass().getName();
			String testCaseNumber = fullClassName.substring(fullClassName.lastIndexOf('.')+1+"BenchmarkTest".length());
			user+= testCaseNumber;
			
			String cookieName = "rememberMe" + testCaseNumber;
			
			boolean foundUser = false;
			javax.servlet.http.Cookie[] cookies = request.getCookies();
			if (cookies != null) {
				for (int i = 0; !foundUser && i < cookies.length; i++) {
					javax.servlet.http.Cookie cookie = cookies[i];
					if (cookieName.equals(cookie.getName())) {
						if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) {
							foundUser = true;
						}
					}
				}
			}
			
			if (foundUser) {
				response.getWriter().println(
"Welcome back: " + user + "<br/>"
);
			
			} else {			
				javax.servlet.http.Cookie rememberMe = new javax.servlet.http.Cookie(cookieName, rememberMeKey);
				rememberMe.setSecure(true);
	//			rememberMe.setPath("/benchmark/" + this.getClass().getSimpleName());
				rememberMe.setPath(request.getRequestURI()); // i.e., set path to JUST this servlet 
															 // e.g., /benchmark/sql-01/BenchmarkTest01001
				request.getSession().setAttribute(cookieName, rememberMeKey);
response.addCookie(rememberMe);
response.getWriter().println(
user + " has been remembered with cookie: " + rememberMe.getName() 
						+ " whose value is: " + rememberMe.getValue() + "<br/>"
);
			}  
	    } catch (java.security.NoSuchAlgorithmException e) {
			System.out.println("Problem executing SecureRandom.nextBytes() - TestCase");
			throw new ServletException(e);
	    } finally {
			response.getWriter().println(
"Randomness Test java.security.SecureRandom.nextBytes(byte[]) executed"
);
	    }
	}
 
Example 20
Source File: UsageLog.java    From tds with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Gather context information for the given HTTP request and return
 * a log message appropriate for logging at the start of the request.
 * <p/>
 * <p>
 * The following context information is gathered:
 * <ul>
 * <li>"ID" - an identifier for the current thread;</li>
 * <li>"host" - the remote host (IP address or host name);</li>
 * <li>"userid" - the id of the remote user;</li>
 * <li>"startTime" - the system time in millis when this request is started (i.e., when this method is called);
 * and</li>
 * <li>"request" - The HTTP request, e.g., "GET /index.html HTTP/1.1".</li>
 * </ul>
 * <p/>
 * <p>
 * Call this method at the start of each HttpServlet doXXX() method
 * (e.g., doGet(), doPut()) or Spring MVC Controller handle() method.
 *
 * @param req the current request
 * @return a log message appropriate for the start of the request.
 */
public static String setupRequestContext(HttpServletRequest req) {

  // Setup context.
  // HttpSession session = req.getSession(false);
  /*
   * MDC.put("host", req.getRemoteHost());
   * MDC.put("ident", (session == null) ? "-" : session.getId());
   * MDC.put("userid", req.getRemoteUser() != null ? req.getRemoteUser() : "-");
   */

  MDC.put("ID", Long.toString(logServerAccessId.incrementAndGet()));
  MDC.put("startTime", Long.toString(System.currentTimeMillis()));

  String query = req.getQueryString();
  query = (query != null) ? "?" + query : "";
  Formatter request = new Formatter();
  request.format("\"%s %s%s %s\"", req.getMethod(), req.getRequestURI(), query, req.getProtocol());

  MDC.put("request", request.toString());
  return "Remote host: " + req.getRemoteHost() + " - Request: " + request.toString();
}