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

The following examples show how to use javax.servlet.http.HttpServletRequest#getHeaderNames() . 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: ServletCallback.java    From bugsnag-java with MIT License 7 votes vote down vote up
private Map<String, String> getHeaderMap(HttpServletRequest request) {
    Map<String, String> headers = new HashMap<String, String>();
    Enumeration<String> headerNames = request.getHeaderNames();

    while (headerNames != null && headerNames.hasMoreElements()) {
        String key = headerNames.nextElement();
        Enumeration<String> headerValues = request.getHeaders(key);
        StringBuilder value = new StringBuilder();

        if (headerValues != null && headerValues.hasMoreElements()) {
            value.append(headerValues.nextElement());

            // If there are multiple values for the header, do comma-separated concat
            // as per RFC 2616:
            // https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
            while (headerValues.hasMoreElements()) {
                value.append(",").append(headerValues.nextElement());
            }
        }

        headers.put(key, value.toString());
    }

    return headers;
}
 
Example 2
Source File: JWTUtil.java    From NutzSite with Apache License 2.0 6 votes vote down vote up
/**
 *  获取ID
 * @return
 */
public static String getId() {
    HttpServletRequest request = Mvcs.getReq();
    Map<String, String> map = new HashMap<String, String>();
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String key = (String) headerNames.nextElement();
        String value = request.getHeader(key);
        map.put(key, value);
    }
    try{
        String token=map.get("authorization");
       if(verifyToken(token)){
           Claims claims = Jwts.parser()
                   .setSigningKey(key)
                   .parseClaimsJws(token).getBody();
           return  claims.getId();
       }
    }catch (Exception e){
        log.debug(e.getMessage());
        e.printStackTrace();

    }
    return null;
}
 
Example 3
Source File: DebugRequest.java    From s2g-zuul with MIT License 6 votes vote down vote up
@Override
    public Object run() {
        HttpServletRequest req = RequestContext.getCurrentContext().getRequest();

        Debug.addRequestDebug("REQUEST:: " + req.getScheme() + " " + req.getRemoteAddr() + ":" + req.getRemotePort());
        Debug.addRequestDebug("REQUEST:: > " + req.getMethod() + " " + req.getRequestURI() + " " + req.getProtocol());

        Enumeration<String> headerIt = req.getHeaderNames();
        while (headerIt.hasMoreElements()) {
            String name = (String) headerIt.nextElement();
            String value = req.getHeader(name);
            Debug.addRequestDebug("REQUEST:: > " + name + ":" + value);
        }

//        final RequestContext ctx = RequestContext.getCurrentContext();
//        if (!ctx.isChunkedRequestBody() && !BODY_DEBUG_DISABLED.get()) {
//            InputStream inp = ctx.getRequest().getInputStream();
//            String body = null;
//            if (inp != null) {
//                body = inp.getText();
//                Debug.addRequestDebug("REQUEST:: > " + body);
//            }
//        }
        return null;
    }
 
Example 4
Source File: FeignHttpInterceptorConfig.java    From microservices-platform with Apache License 2.0 5 votes vote down vote up
/**
 * 使用feign client访问别的微服务时,将上游传过来的access_token、username、roles等信息放入header传递给下一个服务
 */
@Bean
public RequestInterceptor httpFeignInterceptor() {
    return template -> {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            Enumeration<String> headerNames = request.getHeaderNames();
            if (headerNames != null) {
                String headerName;
                String headerValue;
                while(headerNames.hasMoreElements()) {
                    headerName = headerNames.nextElement();
                    if (requestHeaders.contains(headerName)) {
                        headerValue = request.getHeader(headerName);
                        template.header(headerName, headerValue);
                    }
                }
            }
            //传递access_token,无网络隔离时需要传递
            /*
            String token = extractHeaderToken(request);
            if (StrUtil.isEmpty(token)) {
                token = request.getParameter(CommonConstant.ACCESS_TOKEN);
            }
            if (StrUtil.isNotEmpty(token)) {
                template.header(CommonConstant.TOKEN_HEADER, CommonConstant.BEARER_TYPE + " " + token);
            }
            */
        }
    };
}
 
Example 5
Source File: ServletInfo.java    From Tutorials with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException {
	PrintWriter pr = response.getWriter();
	
	pr.println("=== Paths ===\n");
	pr.println("Request URL : " + request.getRequestURL());
	pr.println("Request URI : " + request.getRequestURI());
	pr.println("Servlet path : " + request.getServletPath());
	
	pr.println("\n=== Headers ===\n");
	Enumeration<String> e = request.getHeaderNames();
	while(e.hasMoreElements()){
		String param = (String) e.nextElement();
		pr.println(param + " : " + request.getHeader(param));
	}
	
	pr.println("\n=== Parameters ===\n");
	Map<String, String[]> paramsMap = request.getParameterMap();
	for (String key : paramsMap.keySet()) {
		pr.println(key + " : " + request.getParameter(key));
	}
	
	pr.println("\n=== Session ===\n");
	// returns 0:0:0:0:0:0:0:1 if executed from localhost
	pr.println("Client IP address : " + request.getRemoteAddr());
	pr.println("Session ID : " + request.getRequestedSessionId());
	// Cookie objects the client sent with this request
	Cookie[] cookies = request.getCookies();
	if (cookies != null) {
		for (Cookie cookie : cookies) {
			pr.print(cookie.getName() + ";");
		}
	}
}
 
Example 6
Source File: SessionRequestHolder.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public SessionRequestHolder(HttpServletRequest request, String marker,
		String replacement)
{
	headers = new HashMap<String, List>();
	Enumeration e = request.getHeaderNames();
	while (e.hasMoreElements())
	{
		String s = (String) e.nextElement();
		List v = new ArrayList();
		Enumeration e1 = request.getHeaders(s);
		while (e1.hasMoreElements())
		{
			v.add(e1.nextElement());
		}
		headers.put(s, v);
	}
	Map m = request.getParameterMap();
	parameterMap = new HashMap();
	for (Iterator<Entry<Object, Object>> i = m.entrySet().iterator(); i.hasNext();)
	{
		Entry<Object, Object> entry = i.next();
		parameterMap.put(entry.getKey(), entry.getValue());
	}
	contextPath = PortalStringUtil.replaceFirst(request.getContextPath(), marker,
			replacement);
	method = request.getMethod();
	queryString = request.getQueryString();
}
 
Example 7
Source File: BasicHttpSolrClientTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private void setHeaders(HttpServletRequest req) {
  Enumeration<String> headerNames = req.getHeaderNames();
  headers = new HashMap<>();
  while (headerNames.hasMoreElements()) {
    final String name = headerNames.nextElement();
    headers.put(name, req.getHeader(name));
  }
}
 
Example 8
Source File: CustomFeignConfig.java    From spring-microservice-exam with MIT License 5 votes vote down vote up
private Map<String, String> getHeaders(HttpServletRequest request) {
    Map<String, String> map = new LinkedHashMap<>();
    Enumeration<String> enumeration = request.getHeaderNames();
    while (enumeration.hasMoreElements()) {
        String key = enumeration.nextElement();
        String value = request.getHeader(key);
        map.put(key, value);
    }
    return map;
}
 
Example 9
Source File: ForwardedHeaderFilter.java    From java-technology-stack with MIT License 5 votes vote down vote up
private static Map<String, List<String>> initHeaders(HttpServletRequest request) {
	Map<String, List<String>> headers = new LinkedCaseInsensitiveMap<>(Locale.ENGLISH);
	Enumeration<String> names = request.getHeaderNames();
	while (names.hasMoreElements()) {
		String name = names.nextElement();
		if (!FORWARDED_HEADER_NAMES.contains(name)) {
			headers.put(name, Collections.list(request.getHeaders(name)));
		}
	}
	return headers;
}
 
Example 10
Source File: FeignRequestInterceptorConfig.java    From sophia_scaffolding with Apache License 2.0 5 votes vote down vote up
@Override
    public void apply(RequestTemplate requestTemplate) {

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        if (request != null) {
            log.error("调用feign传递header携带token");

//        只携带token
//            String authorization = request.getHeader(AUTHORIZATION_HEADER);
//            requestTemplate.header("Authorization", authorization);
//             System.err.println("Authorization :\t\t"+ authorization);

//        携带全部
            Enumeration<String> headerNames = request.getHeaderNames();
            if (headerNames != null) {
                while (headerNames.hasMoreElements()) {
                    String name = headerNames.nextElement();
                    String values = request.getHeader(name);
                    requestTemplate.header(name, values);
                    log.debug("name :\t\t" + name);
                    log.debug("values : \t\t" + values);

                }
            }

        }

    }
 
Example 11
Source File: StatusResource.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * Service実行.
 * @param path リソース名
 * @param req Requestオブジェクト
 * @param res Responseオブジェクト
 * @param is リクエストストリームオブジェクト
 * @return Response
 */
public final Response run(final String path,
        final HttpServletRequest req,
        final HttpServletResponse res,
        final InputStream is) {
    StringBuilder msg = new StringBuilder();
    msg.append(">>> Request Started ");
    msg.append(" method:");
    msg.append(req.getMethod());
    msg.append(" method:");
    msg.append(req.getRequestURL());
    msg.append(" url:");
    log.info(msg);

    // デバッグ用 すべてのヘッダをログ出力
    Enumeration<String> multiheaders = req.getHeaderNames();
    for (String headerName : Collections.list(multiheaders)) {
        Enumeration<String> headers = req.getHeaders(headerName);
        for (String header : Collections.list(headers)) {
            log.debug("RequestHeader['" + headerName + "'] = " + header);
        }
    }
    try {
        DcEngineConfig.reload();
    } catch (Exception e) {
        log.warn(" unknown Exception(" + e.getMessage() + ")");
        return errorResponse(new DcEngineException("500 Internal Server Error (Unknown Error)",
                DcEngineException.STATUSCODE_SERVER_ERROR));
    }
    return Response.status(HttpStatus.SC_NO_CONTENT).build();
}
 
Example 12
Source File: BenchmarkTest01109.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 param = "";
		java.util.Enumeration<String> names = request.getHeaderNames();
		while (names.hasMoreElements()) {
			String name = (String) names.nextElement();
			
			if(org.owasp.benchmark.helpers.Utils.commonHeaders.contains(name)){
				continue;
			}
			
			java.util.Enumeration<String> values = request.getHeaders(name);
			if (values != null && values.hasMoreElements()) {
				param = name;
				break;
			}
		}
		// Note: We don't URL decode header names because people don't normally do that

		String bar = new Test().doSomething(request, param);
		
		java.io.File fileTarget = new java.io.File(bar, "/Test.txt");
		response.getWriter().println(
"Access to file: '" + org.owasp.esapi.ESAPI.encoder().encodeForHTML(fileTarget.toString()) + "' created." 
);
		if (fileTarget.exists()) {
			response.getWriter().println(
" And file already exists."
);
		} else { response.getWriter().println(
" But file doesn't exist yet."
); }
	}
 
Example 13
Source File: TraceServlet.java    From rest-client with Apache License 2.0 4 votes vote down vote up
private void process(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
    response.setContentType("text/plain; charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.println("**RESTClient TraceServlet**");
    
    out.println("\n*Method*");
    out.println("\t" + request.getMethod());
    
    out.println("\n*Path Info*");
    out.println("\t" + request.getPathInfo());
    
    out.println("\n*Headers*");
    Enumeration eHeaders = request.getHeaderNames();
    while(eHeaders.hasMoreElements()){
        final String headerName = (String)eHeaders.nextElement();
        Enumeration eValues = request.getHeaders(headerName);
        while(eValues.hasMoreElements()) {
            String headerValue = (String) eValues.nextElement();
            headerValue = headerValue.replaceAll("\n", "\n\t");
            out.println("\t" + headerName + ": " + headerValue);
        }
    }
    
    out.println("\n*Query String*");
    out.println("\t" + request.getQueryString());
    
    out.println("\n*Parameters*");
    Enumeration eParams = request.getParameterNames();
    while(eParams.hasMoreElements()){
        String paramName = (String)eParams.nextElement();
        String[] paramValues = request.getParameterValues(paramName);

        for(String paramValue: paramValues) {
            paramValue = paramValue.replaceAll("\n", "\n\t");

            out.println("\t~Parameter Name: " + paramName);
            out.println("\t~Parameter Value:");
            out.println("\t" + paramValue);
        }
    }
    
    out.println("\n*Body (First 100 characters only)*");
    String body = Util.inputStreamToString(request.getInputStream());
    String[] arr = body.split("\n");
    for(String s: arr) {
        out.print("\t");
        out.println(s);
    }
    
    out.println();
    
    out.flush();
    out.close();
}
 
Example 14
Source File: BenchmarkTest01987.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 param = "";
		java.util.Enumeration<String> names = request.getHeaderNames();
		while (names.hasMoreElements()) {
			String name = (String) names.nextElement();
			
			if(org.owasp.benchmark.helpers.Utils.commonHeaders.contains(name)){
				continue;
			}
			
			java.util.Enumeration<String> values = request.getHeaders(name);
			if (values != null && values.hasMoreElements()) {
				param = name;
				break;
			}
		}
		// Note: We don't URL decode header names because people don't normally do that

		String bar = doSomething(request, param);
		
		// FILE URIs are tricky because they are different between Mac and Windows because of lack of standardization.
		// Mac requires an extra slash for some reason.
		String startURIslashes = "";
        if (System.getProperty("os.name").indexOf("Windows") != -1)
	        if (System.getProperty("os.name").indexOf("Windows") != -1)
	        	startURIslashes = "/";
	        else startURIslashes = "//";

		try {
			java.net.URI fileURI = new java.net.URI("file", null, startURIslashes 
				+ org.owasp.benchmark.helpers.Utils.testfileDir.replace('\\', java.io.File.separatorChar).replace(' ', '_') + bar, null, null);
			java.io.File fileTarget = new java.io.File(fileURI);
            response.getWriter().println(
"Access to file: '" + org.owasp.esapi.ESAPI.encoder().encodeForHTML(fileTarget.toString()) + "' created." 
);
            if (fileTarget.exists()) {
            response.getWriter().println(
" And file already exists."
);
            } else { response.getWriter().println(
" But file doesn't exist yet."
); }
		} catch (java.net.URISyntaxException e) {
			throw new ServletException(e);
		}
	}
 
Example 15
Source File: BenchmarkTest01996.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 param = "";
		java.util.Enumeration<String> names = request.getHeaderNames();
		while (names.hasMoreElements()) {
			String name = (String) names.nextElement();
			
			if(org.owasp.benchmark.helpers.Utils.commonHeaders.contains(name)){
				continue;
			}
			
			java.util.Enumeration<String> values = request.getHeaders(name);
			if (values != null && values.hasMoreElements()) {
				param = name;
				break;
			}
		}
		// Note: We don't URL decode header names because people don't normally do that

		String bar = doSomething(request, param);
		
		try {
		    java.util.Properties benchmarkprops = new java.util.Properties();
		    benchmarkprops.load(this.getClass().getClassLoader().getResourceAsStream("benchmark.properties"));
			String algorithm = benchmarkprops.getProperty("hashAlg1", "SHA512");
			java.security.MessageDigest md = java.security.MessageDigest.getInstance(algorithm);
			byte[] input = { (byte)'?' };
			Object inputParam = bar;
			if (inputParam instanceof String) input = ((String) inputParam).getBytes();
			if (inputParam instanceof java.io.InputStream) {
				byte[] strInput = new byte[1000];
				int i = ((java.io.InputStream) inputParam).read(strInput);
				if (i == -1) {
					response.getWriter().println(
"This input source requires a POST, not a GET. Incompatible UI for the InputStream source."
);
					return;
				}
				input = java.util.Arrays.copyOf(strInput, i);
			}			
			md.update(input);
			
			byte[] result = md.digest();
			java.io.File fileTarget = new java.io.File(
					new java.io.File(org.owasp.benchmark.helpers.Utils.testfileDir),"passwordFile.txt");
			java.io.FileWriter fw = new java.io.FileWriter(fileTarget,true); //the true will append the new data
			    fw.write("hash_value=" + org.owasp.esapi.ESAPI.encoder().encodeForBase64(result, true) + "\n");
			fw.close();
			response.getWriter().println(
"Sensitive value '" + org.owasp.esapi.ESAPI.encoder().encodeForHTML(new String(input)) + "' hashed and stored<br/>"
);

		} catch (java.security.NoSuchAlgorithmException e) {
			System.out.println("Problem executing hash - TestCase");
			throw new ServletException(e);
		}
		
		response.getWriter().println(
"Hash Test java.security.MessageDigest.getInstance(java.lang.String) executed"
);
	}
 
Example 16
Source File: RestAuthFilter.java    From opencps-v2 with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
		throws IOException, ServletException {
	HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;

	String pAuth = httpRequest.getHeader(P_AUTH);
	String path = httpRequest.getRequestURI();
	boolean exclude = false;
	for (String pattern : IGNORE_PATTERN) {
		if (path.matches(pattern)) {
			exclude = true;
			break;
		}
	}
	if (Validator.isNotNull(httpRequest.getParameter("Token"))) {
		pAuth = httpRequest.getParameter("Token");
	}
	String ipAddress = HttpUtil.getIpAddress(httpRequest);
	boolean checkLocal = ("localhost".equals(ipAddress) || "127.0.0.1".equals(ipAddress));
	
	if (checkLocal || exclude || AuthTokenUtil.getToken(httpRequest).equals(pAuth) || (Validator.isNotNull(httpRequest.getHeader("localaccess")) ? httpRequest.getHeader("localaccess").equals(pAuth) : false) ) {
		Object userObj = httpRequest.getSession(true).getAttribute(USER_ID);
		if (Validator.isNotNull(userObj) || exclude) {
			httpRequest.setAttribute(USER_ID, userObj);
			if (!exclude) {
				authOK(servletRequest, servletResponse, filterChain, (Long) userObj);
			}
			else {
				authOK(servletRequest, servletResponse, filterChain, 0);
			}
		} else {
			long sockId = Validator.isNotNull(httpRequest.getHeader("userid")) ? Long.valueOf(httpRequest.getHeader("userid")) : 0;
			httpRequest.setAttribute(USER_ID, sockId);
			authOK(servletRequest, servletResponse, filterChain, sockId);
		}
	
	} else {
		
		Enumeration<String> headerNames = httpRequest.getHeaderNames();
		
		boolean isBasic = false;
		String strBasic = StringPool.BLANK;
		
		if (headerNames != null) {
			while (headerNames.hasMoreElements()) {
	            String key = (String) headerNames.nextElement();
	            String value = httpRequest.getHeader(key);
	            if (key.trim().equalsIgnoreCase(AUTHORIZATION)) {
	            	strBasic = value;
	            	isBasic = true;
	            	break;
	            }
	        }
		}
		if (isBasic) {

			try {
				// Get encoded user and password, comes after "BASIC "  
		        String userpassEncoded = strBasic.substring(6);  
		        String decodetoken = new String(Base64.decode(userpassEncoded),
		                StringPool.UTF8);
		        String account[] = decodetoken.split(":");
		        
		        String email = account[0];
		        String password = account[1];
	        
				long userId = AuthenticatedSessionManagerUtil.getAuthenticatedUserId(httpRequest, email, password, CompanyConstants.AUTH_TYPE_EA);
			
				authOK(servletRequest, servletResponse, filterChain, userId);
				
			} catch (PortalException e) {
				_log.debug(e);
				authFailure(servletResponse);
			}

		} else {
			authFailure(servletResponse);
		}
		
	}

}
 
Example 17
Source File: LoginToContinueMechanism.java    From tomee with Apache License 2.0 4 votes vote down vote up
static void saveRequest(final HttpServletRequest request) throws IOException {
    SavedRequest saved = new SavedRequest();
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            saved.addCookie(cookies[i]);
        }
    }
    Enumeration<String> names = request.getHeaderNames();
    while (names.hasMoreElements()) {
        String name = names.nextElement();
        Enumeration<String> values = request.getHeaders(name);
        while (values.hasMoreElements()) {
            String value = values.nextElement();
            saved.addHeader(name, value);
        }
    }
    Enumeration<Locale> locales = request.getLocales();
    while (locales.hasMoreElements()) {
        Locale locale = locales.nextElement();
        saved.addLocale(locale);
    }

    int maxSavePostSize = MAX_SAVE_POST_SIZE;
    if (maxSavePostSize != 0) {
        ByteChunk body = new ByteChunk();
        body.setLimit(maxSavePostSize);

        byte[] buffer = new byte[4096];
        int bytesRead;
        InputStream is = request.getInputStream();

        while ( (bytesRead = is.read(buffer) ) >= 0) {
            body.append(buffer, 0, bytesRead);
        }

        // Only save the request body if there is something to save
        if (body.getLength() > 0) {
            saved.setContentType(request.getContentType());
            saved.setBody(body);
        }
    }

    saved.setMethod(request.getMethod());
    saved.setQueryString(request.getQueryString());
    saved.setRequestURI(request.getRequestURI());
    saved.setRequestURL(request.getRequestURL().toString());

    // Stash the SavedRequest in our session for later use
    request.getSession().setAttribute(ORIGINAL_REQUEST, saved);
}
 
Example 18
Source File: EchoRequestInfoAction.java    From aws-serverless-java-container with Apache License 2.0 4 votes vote down vote up
public String execute() {

        HttpServletRequest request = ServletActionContext.getRequest();
        AwsProxyRequestContext awsProxyRequestContext =
                (AwsProxyRequestContext) request
                        .getAttribute(RequestReader.API_GATEWAY_CONTEXT_PROPERTY);

        switch (mode) {
            case "principal":
                result = awsProxyRequestContext.getAuthorizer().getPrincipalId();
                break;
            case "scheme":
                result = request.getScheme();
                break;
            case "content-type":
                if (request.getContentType().contains("application/octet-stream")) {
                    ServletActionContext.getResponse().setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
                }
                result = request.getContentType();
                break;
            case "not-allowed":
                ServletActionContext.getResponse().setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                break;
            case "custom-status-code":
                ServletActionContext.getResponse().setStatus(HttpServletResponse.SC_CREATED);
                break;
            case "not-implemented":
                ServletActionContext.getResponse().setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
                break;
            case "headers":
                Map<String, String> headers = new HashMap<>();

                Enumeration<String> headerNames = request.getHeaderNames();
                while (headerNames.hasMoreElements()) {
                    String headerName = headerNames.nextElement();
                    headers.put(headerName, request.getHeader(headerName));
                }

                result = headers;
                break;
            case "query-string":
                Map<String, String> params = new HashMap<>();

                Enumeration<String> parameterNames = request.getParameterNames();
                while (parameterNames.hasMoreElements()) {
                    String parameterName = parameterNames.nextElement();
                    params.put(parameterName, request.getParameter(parameterName));
                }

                result = params;
                break;
            default:
                throw new IllegalArgumentException("Invalid mode requested: " + mode);
        }

        return SUCCESS;
    }
 
Example 19
Source File: BenchmarkTest01132.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 param = "";
		java.util.Enumeration<String> names = request.getHeaderNames();
		while (names.hasMoreElements()) {
			String name = (String) names.nextElement();
			
			if(org.owasp.benchmark.helpers.Utils.commonHeaders.contains(name)){
				continue;
			}
			
			java.util.Enumeration<String> values = request.getHeaders(name);
			if (values != null && values.hasMoreElements()) {
				param = name;
				break;
			}
		}
		// Note: We don't URL decode header names because people don't normally do that

		String bar = new Test().doSomething(request, param);
		
		int r = new java.util.Random().nextInt();
		String rememberMeKey = Integer.toString(r);
		
		String user = "Ingrid";
		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/>"
			);
		}
				
		response.getWriter().println(
"Weak Randomness Test java.util.Random.nextInt() executed"
);

	}
 
Example 20
Source File: RequestHeaderExample.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Override
public void doGet(HttpServletRequest request,
                  HttpServletResponse response)
    throws IOException, ServletException
{
    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");

    PrintWriter out = response.getWriter();
    out.println("<!DOCTYPE html><html>");
    out.println("<head>");
    out.println("<meta charset=\"UTF-8\" />");

    String title = RB.getString("requestheader.title");
    out.println("<title>" + title + "</title>");
    out.println("</head>");
    out.println("<body bgcolor=\"white\">");

    // all links relative

    // XXX
    // making these absolute till we work out the
    // addition of a PathInfo issue

    out.println("<a href=\"../reqheaders.html\">");
    out.println("<img src=\"../images/code.gif\" height=24 " +
                "width=24 align=right border=0 alt=\"view code\"></a>");
    out.println("<a href=\"../index.html\">");
    out.println("<img src=\"../images/return.gif\" height=24 " +
                "width=24 align=right border=0 alt=\"return\"></a>");

    out.println("<h3>" + title + "</h3>");
    out.println("<table border=0>");
    Enumeration<String> e = request.getHeaderNames();
    while (e.hasMoreElements()) {
        String headerName = e.nextElement();
        String headerValue = request.getHeader(headerName);
        out.println("<tr><td bgcolor=\"#CCCCCC\">");
        out.println(HTMLFilter.filter(headerName));
        out.println("</td><td>");
        if (headerName.toLowerCase(Locale.ENGLISH).contains("cookie")) {
            HttpSession session = request.getSession(false);
            String sessionId = null;
            if (session != null) {
                sessionId = session.getId();
            }
            out.println(HTMLFilter.filter(CookieFilter.filter(headerValue, sessionId)));
        } else {
            out.println(HTMLFilter.filter(headerValue));
        }
        out.println("</td></tr>");
    }
    out.println("</table>");
}