Java Code Examples for javax.servlet.http.httpservletrequest#getParameterValues()

The following examples show how to use javax.servlet.http.httpservletrequest#getParameterValues() . 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: BenchmarkTest02485.java    From Benchmark with GNU General Public License v2.0 6 votes vote down vote up
@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");

		String[] values = request.getParameterValues("BenchmarkTest02485");
		String param;
		if (values != null && values.length > 0)
		  param = values[0];
		else param = "";

		String bar = doSomething(request, param);
		
response.setHeader("X-XSS-Protection", "0");
		Object[] obj = { "a", bar};
		response.getWriter().printf(java.util.Locale.US,"Formatted like: %1$s and %2$s.",obj);
	}
 
Example 2
Source File: KualiTransactionalDocumentFormBase.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * Uses the "checkboxToReset" parameter to find checkboxes which had not been
 * populated in the request and attempts to populate them
 * 
 * @param request the request to populate
 */
protected void populateFalseCheckboxes(HttpServletRequest request) {
	Map<String, String[]> parameterMap = request.getParameterMap();
	if (parameterMap.get("checkboxToReset") != null) {
		final String[] checkboxesToReset = request.getParameterValues("checkboxToReset");
        if(checkboxesToReset != null && checkboxesToReset.length > 0) {
            for (int i = 0; i < checkboxesToReset.length; i++) {
                String propertyName = (String) checkboxesToReset[i];
                if ( !StringUtils.isBlank(propertyName) && parameterMap.get(propertyName) == null ) {
                	populateForProperty(propertyName, KimConstants.KIM_ATTRIBUTE_BOOLEAN_FALSE_STR_VALUE_DISPLAY, parameterMap);
                }  
                else if ( !StringUtils.isBlank(propertyName) && parameterMap.get(propertyName) != null && parameterMap.get(propertyName).length >= 1 && parameterMap.get(propertyName)[0].equalsIgnoreCase("on") ) {
                	populateForProperty(propertyName, KimConstants.KIM_ATTRIBUTE_BOOLEAN_TRUE_STR_VALUE_DISPLAY, parameterMap);
                }
            }
        }
	}
}
 
Example 3
Source File: FessFunctions.java    From fess with Apache License 2.0 6 votes vote down vote up
private static String createQuery(final String key, final String prefix) {
    final HttpServletRequest request = LaRequestUtil.getRequest();
    String query = (String) request.getAttribute(key);
    if (query == null) {
        final StringBuilder buf = new StringBuilder(100);
        final Enumeration<String> names = request.getParameterNames();
        while (names.hasMoreElements()) {
            final String name = names.nextElement();
            if (name.startsWith(prefix)) {
                final String[] values = request.getParameterValues(name);
                if (values != null) {
                    for (final String value : values) {
                        buf.append('&');
                        buf.append(LdiURLUtil.encode(name, Constants.UTF_8));
                        buf.append('=');
                        buf.append(LdiURLUtil.encode(value, Constants.UTF_8));
                    }
                }
            }
        }
        query = buf.toString();
        request.setAttribute(key, query);
    }
    return query;
}
 
Example 4
Source File: BenchmarkTest02319.java    From Benchmark with GNU General Public License v2.0 6 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 = "";
		boolean flag = true;
		java.util.Enumeration<String> names = request.getParameterNames();
		while (names.hasMoreElements() && flag) {
			String name = (String) names.nextElement();		    	
			String[] values = request.getParameterValues(name);
			if (values != null) {
				for(int i=0;i<values.length && flag; i++){
					String value = values[i];
					if (value.equals("BenchmarkTest02319")) {
						param = name;
					    flag = false;
					}
				}
			}
		}

		String bar = doSomething(request, param);
		
response.setHeader("X-XSS-Protection", "0");
		response.getWriter().print(bar);
	}
 
Example 5
Source File: DocumentAction.java    From OA with GNU General Public License v3.0 6 votes vote down vote up
public String deleteDocument() {
	HttpServletRequest request = ServletActionContext.getRequest();
	String ids[] = request.getParameterValues("delid");
	Document docs = null;
	String key;
	for (String a : ids) {
		docs = documentService.findDocument(Integer.valueOf(a));
		if (docs.getTypePersist() != null) {
			key = docs.getTypePersist().replaceAll("(.*)\\|.*", "$1");
			Persistence.removeVariable(key);
		}
	}
	returns = "DocumentAction!listMyDocument";
	documentService.deleteDocuments(ids);
	return null;
}
 
Example 6
Source File: BatchRefineTransformer.java    From p3-batchrefine with Apache License 2.0 6 votes vote down vote up
private String getSingleParameter(String parameter, String defaultValue,
                                  HttpServletRequest request) throws IOException {
    String[] values = request.getParameterValues(parameter);
    if (values == null) {
        if (defaultValue != null) {
            return defaultValue;
        }
        // TODO appropriate error reporting/handling
        throw new IOException("BatchRefine requires a " + parameter
                + " request parameter.");
    }

    if (values.length > 1) {
        fLogger.warn("More than one " + parameter
                + " specified in request URL, using the first one ("
                + values[0] + ")");
    }

    return values[0];
}
 
Example 7
Source File: BenchmarkTest02529.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[] values = request.getParameterValues("BenchmarkTest02529");
		String param;
		if (values != null && values.length > 0)
		  param = values[0];
		else param = "";

		String bar = doSomething(request, param);
		
		String sql = "{call " + bar + "}";
				
		try {
			java.sql.Connection connection = org.owasp.benchmark.helpers.DatabaseHelper.getSqlConnection();
			java.sql.CallableStatement statement = connection.prepareCall( sql );
		    java.sql.ResultSet rs = statement.executeQuery();
            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 8
Source File: BenchmarkTest01608.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[] values = request.getParameterValues("BenchmarkTest01608");
	String param;
	if (values != null && values.length > 0)
	  param = values[0];
	else param = "";

	String bar = new Test().doSomething(request, param);
	
	String cmd = org.owasp.benchmark.helpers.Utils.getInsecureOSCommandString(this.getClass().getClassLoader());
	String[] args = {cmd};
       String[] argsEnv = { bar };
       
	Runtime r = Runtime.getRuntime();

	try {
		Process p = r.exec(args, argsEnv, new java.io.File(System.getProperty("user.dir")));
		org.owasp.benchmark.helpers.Utils.printOSCommandResults(p, response);
	} catch (IOException e) {
		System.out.println("Problem executing cmdi - TestCase");
		response.getWriter().println(
		  org.owasp.esapi.ESAPI.encoder().encodeForHTML(e.getMessage())
		);
		return;
	}
}
 
Example 9
Source File: PromoCodeInterceptor.java    From maven-framework-project with MIT License 5 votes vote down vote up
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
	String givenPromoCode = request.getParameterValues("promo")==null ? "":request.getParameterValues("promo")[0];
	
	if(request.getRequestURI().endsWith("products/specialOffer")){
		if(givenPromoCode.equals(promoCode)){
			response.sendRedirect(request.getContextPath()+"/"+offerRedirect);
		} else{
			response.sendRedirect(errorRedirect);
		}
		return false;
	}
	
	return true;
}
 
Example 10
Source File: XSLTEntityHandler.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public void addRequestParameters(ContentHandler ch, HttpServletRequest request)
		throws Exception
{
	if (!isAvailable()) return;

	AttributesImpl dummyAttributes = new AttributesImpl();

	// add the request parameters
	ch.startElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_REQUEST_PARAMS,
			SchemaNames.EL_NSREQUEST_PARAMS, dummyAttributes);
	for (Enumeration e = request.getParameterNames(); e.hasMoreElements();)
	{
		String name = (String) e.nextElement();
		String[] attr = request.getParameterValues(name);
		AttributesImpl propA = new AttributesImpl();
		propA.addAttribute("", SchemaNames.ATTR_NAME, //$NON-NLS-1$
				SchemaNames.ATTR_NAME, "string", name); //$NON-NLS-1$
		ch.startElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_REQUEST_PARAM,
				SchemaNames.EL_NSREQUEST_PARAM, propA);
		for (int i = 0; i < attr.length; i++)
		{
			addElement(ch, SchemaNames.NS_CONTAINER, SchemaNames.EL_VALUE,
					SchemaNames.EL_NSVALUE, dummyAttributes, attr[i]);
		}
		ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_REQUEST_PARAM,
				SchemaNames.EL_NSREQUEST_PARAM);
	}

	ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_REQUEST_PARAMS,
			SchemaNames.EL_REQUEST_PARAMS);
}
 
Example 11
Source File: BenchmarkTest00742.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[] values = request.getParameterValues("BenchmarkTest00742");
	String param;
	if (values != null && values.length > 0)
	  param = values[0];
	else param = "";
	
	
	String bar = "safe!";
	java.util.HashMap<String,Object> map62435 = new java.util.HashMap<String,Object>();
	map62435.put("keyA-62435", "a_Value"); // put some stuff in the collection
	map62435.put("keyB-62435", param); // put it in a collection
	map62435.put("keyC", "another_Value"); // put some stuff in the collection
	bar = (String)map62435.get("keyB-62435"); // get it back out
	bar = (String)map62435.get("keyA-62435"); // get safe value back out
	
	
	String cmd = "";
       String osName = System.getProperty("os.name");
       if (osName.indexOf("Windows") != -1) {
       	cmd = org.owasp.benchmark.helpers.Utils.getOSCommandString("echo");
       }
       
	String[] argsEnv = { "Foo=bar" };
	Runtime r = Runtime.getRuntime();

	try {
		Process p = r.exec(cmd + bar, argsEnv, new java.io.File(System.getProperty("user.dir")));
		org.owasp.benchmark.helpers.Utils.printOSCommandResults(p, response);
	} catch (IOException e) {
		System.out.println("Problem executing cmdi - TestCase");
        response.getWriter().println(
          org.owasp.esapi.ESAPI.encoder().encodeForHTML(e.getMessage())
        );
        return;
	}
}
 
Example 12
Source File: LsCommandExecutor.java    From elfinder-2.x-servlet with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void execute(FsService fsService, HttpServletRequest request,
		ServletContext servletContext, JSONObject json) throws Exception
{
	String target = request.getParameter("target");
	String[] onlyMimes = request.getParameterValues("mimes[]");

	Map<String, FsItemEx> files = new HashMap<String, FsItemEx>();
	FsItemEx fsi = super.findItem(fsService, target);
	super.addChildren(files, fsi, onlyMimes);

	json.put("list", files2JsonArray(request, files.values()));
}
 
Example 13
Source File: BenchmarkTest01443.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 = "";
	boolean flag = true;
	java.util.Enumeration<String> names = request.getParameterNames();
	while (names.hasMoreElements() && flag) {
		String name = (String) names.nextElement();		    	
		String[] values = request.getParameterValues(name);
		if (values != null) {
			for(int i=0;i<values.length && flag; i++){
				String value = values[i];
				if (value.equals("BenchmarkTest01443")) {
					param = name;
				    flag = false;
				}
			}
		}
	}

	String bar = new Test().doSomething(request, param);
	
	String cmd = "";
       String osName = System.getProperty("os.name");
       if (osName.indexOf("Windows") != -1) {
       	cmd = org.owasp.benchmark.helpers.Utils.getOSCommandString("echo");
       }
       
	String[] argsEnv = { "Foo=bar" };
	Runtime r = Runtime.getRuntime();

	try {
		Process p = r.exec(cmd + bar, argsEnv);
		org.owasp.benchmark.helpers.Utils.printOSCommandResults(p, response);
	} catch (IOException e) {
		System.out.println("Problem executing cmdi - TestCase");
		response.getWriter().println(
		  org.owasp.esapi.ESAPI.encoder().encodeForHTML(e.getMessage())
		);
		return;
	}
}
 
Example 14
Source File: BenchmarkTest01614.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[] values = request.getParameterValues("BenchmarkTest01614");
		String param;
		if (values != null && values.length > 0)
		  param = values[0];
		else param = "";

		String bar = new Test().doSomething(request, param);
		
		try {
			long l = java.security.SecureRandom.getInstance("SHA1PRNG").nextLong();
			String rememberMeKey = Long.toString(l);
			
			String user = "SafeLogan";
			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.nextLong() - TestCase");
			throw new ServletException(e);
	    }		
		response.getWriter().println(
"Weak Randomness Test java.security.SecureRandom.nextLong() executed"
);

	}
 
Example 15
Source File: Adm8100Controller.java    From oslits with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 
 * 보고서 저장 및 작성 처리
 * 
 * @param request
 * @param response
 * @param model
 * @return
 * @throws Exception
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
@RequestMapping(value="/adm/adm8000/adm8100/updateAdm8100ReportInfo.do")
public ModelAndView updateAdm8100ReportInfo(HttpServletRequest request, HttpServletResponse response, ModelMap model ) throws Exception {

	try{
		//리퀘스트에서 넘어온 파라미터를 맵으로 세팅
		Map paramMap = RequestConvertor.requestParamToMapAddSelInfo(request, true);
		HttpSession ss = request.getSession();

		LoginVO loginVO = (LoginVO) ss.getAttribute("loginVO");
		paramMap.put("prjId", ss.getAttribute("selPrjId").toString());
		paramMap.put("licGrpId", loginVO.getLicGrpId());	
		// 신규 조직 등록
		
		String itemCds[] =request.getParameterValues("itemCd");
		String meaVals[] =request.getParameterValues("meaVal");
		String apprVals[] =request.getParameterValues("apprVal");
		String optVals[] =request.getParameterValues("optVal");
		String modifyApprVals[] =request.getParameterValues("modifyApprVal");
		String modifyOptVals[] =request.getParameterValues("modifyOptVal");
		Adm8100VO adm8100VO = null;
		List<Adm8100VO> adm8100VOList = new ArrayList<Adm8100VO>();
		
		if(itemCds!=null){
			for (int i = 0; i < itemCds.length; i++) {
				adm8100VO = new Adm8100VO();
				adm8100VO.setLicGrpId(loginVO.getLicGrpId());
				adm8100VO.setPrjId(ss.getAttribute("selPrjId").toString());
				adm8100VO.setMeaDtm( (String)paramMap.get("meaDtm") );
				adm8100VO.setReportCd( (String)paramMap.get("reportCd") );
				adm8100VO.setItemCd(itemCds[i]);
				
				adm8100VO.setItemCd(itemCds[i]);
				adm8100VO.setMeaVal(meaVals[i]);
				adm8100VO.setApprVal(apprVals[i]);
				adm8100VO.setOptVal(optVals[i]);
				adm8100VO.setModifyApprVal(modifyApprVals[i]);
				adm8100VO.setModifyOptVal(modifyOptVals[i]);
				
				adm8100VO.setModifyUsrId(loginVO.getUsrId());
				adm8100VO.setModifyUsrIp(request.getRemoteAddr());
				
				
				adm8100VOList.add(adm8100VO);
			}
		}
		
		int iResult =adm8100Service.updateAdm8100ReportInfo(paramMap,adm8100VOList);

		//등록 성공 메시지 세팅
		model.addAttribute("message", egovMessageSource.getMessage("success.common.update"));

		return new ModelAndView("jsonView");

	}catch(Exception ex){
		Log.error("updateAdm8100ReportInfo()", ex);

		//등록실패 메시지 세팅
		model.addAttribute("message", egovMessageSource.getMessage("fail.common.update"));
		return new ModelAndView("jsonView");
	}
}
 
Example 16
Source File: BenchmarkTest00745.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[] values = request.getParameterValues("BenchmarkTest00745");
		String param;
		if (values != null && values.length > 0)
		  param = values[0];
		else param = "";
		
		
		String bar = org.apache.commons.lang.StringEscapeUtils.escapeHtml(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 17
Source File: BenchmarkTest02336.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 = "";
	boolean flag = true;
	java.util.Enumeration<String> names = request.getParameterNames();
	while (names.hasMoreElements() && flag) {
		String name = (String) names.nextElement();		    	
		String[] values = request.getParameterValues(name);
		if (values != null) {
			for(int i=0;i<values.length && flag; i++){
				String value = values[i];
				if (value.equals("BenchmarkTest02336")) {
					param = name;
				    flag = false;
				}
			}
		}
	}

	String bar = doSomething(request, param);
	
	String a1 = "";
	String a2 = "";
	String osName = System.getProperty("os.name");
       if (osName.indexOf("Windows") != -1) {
       	a1 = "cmd.exe";
       	a2 = "/c";
       } else {
       	a1 = "sh";
       	a2 = "-c";
       }
       String[] args = {a1, a2, "echo " + bar};

	ProcessBuilder pb = new ProcessBuilder();

	pb.command(args);
	
	try {
		Process p = pb.start();
		org.owasp.benchmark.helpers.Utils.printOSCommandResults(p, response);
	} catch (IOException e) {
		System.out.println("Problem executing cmdi - java.lang.ProcessBuilder(java.util.List) Test Case");
           throw new ServletException(e);
	}
}
 
Example 18
Source File: SaveTestCaseLabel.java    From cerberus-source with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, CerberusException, JSONException {
    JSONObject jsonResponse = new JSONObject();
    Answer ans = new Answer();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    ans.setResultMessage(msg);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    String charset = request.getCharacterEncoding() == null ? "UTF-8" : request.getCharacterEncoding();
    String usr = request.getUserPrincipal().getName();

    testCaseLabelService = appContext.getBean(ITestCaseLabelService.class);
    testCaseLabelFactory = appContext.getBean(IFactoryTestCaseLabel.class);
    
    response.setContentType("application/json");

    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);

    /**
     * Parsing and securing all required parameters.
     */
    // Parameter that are already controled by GUI (no need to decode) --> We SECURE them
    String test = policy.sanitize(request.getParameter("test"));
    String testcase = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("testcase"), "", charset);
    
    
    String[] labelIdList = request.getParameterValues("labelid");
    /**
     * Checking all constrains before calling the services.
     */
    if (test.isEmpty() || testcase.isEmpty()) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "TestCaseLabel")
                .replace("%OPERATION%", "Save")
                .replace("%REASON%", "Mandatory parameter is missing. [test|testcase]"));
        ans.setResultMessage(msg);
    } else {
        /**
         * All data seems cleans so we can call the services.
         */
        List<TestCaseLabel> toSave = new ArrayList<>();
        if (null!= labelIdList && labelIdList.length!=0) {
            Timestamp creationDate = new Timestamp(new Date().getTime());
            for (String lableId : labelIdList){
            toSave.add(testCaseLabelFactory.create(0, test, testcase, Integer.valueOf(lableId), usr, creationDate, usr, creationDate, null));
            }
        }
        
        List<TestCaseLabel> existingList = testCaseLabelService.readByTestTestCase(test, testcase, null).getDataList();
        testCaseLabelService.compareListAndUpdateInsertDeleteElements(test, testcase, toSave);
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "TestCaseLabel")
                .replace("%OPERATION%", "Save")); 
        ans.setResultMessage(msg);
        
        }
    

    /**
     * Formating and returning the json result.
     */
    jsonResponse.put("messageType", ans.getResultMessage().getMessage().getCodeString());
    jsonResponse.put("message", ans.getResultMessage().getDescription());

    response.getWriter().print(jsonResponse);
    response.getWriter().flush();
}
 
Example 19
Source File: BenchmarkTest00751.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[] values = request.getParameterValues("BenchmarkTest00751");
		String param;
		if (values != null && values.length > 0)
		  param = values[0];
		else param = "";
		
		
		String bar;
		
		// Simple if statement that assigns param to bar on true condition
		int num = 196;
		if ( (500/42) + num > 200 )
		   bar = param;
		else bar = "This should never happen"; 
		
		
		try {
			double rand = java.security.SecureRandom.getInstance("SHA1PRNG").nextDouble();
			
			String rememberMeKey = Double.toString(rand).substring(2); // Trim off the 0. at the front.
			
			String user = "SafeDonna";
			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.nextDouble() - TestCase");
			throw new ServletException(e);
	    }
		response.getWriter().println(
"Weak Randomness Test java.security.SecureRandom.nextDouble() executed"
);
	}
 
Example 20
Source File: PreferenceServlet.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
public void doGet( HttpServletRequest request, HttpServletResponse response )
		throws ServletException, IOException
{
	HttpSession session = request.getSession( false );
	if ( session == null )
	{
		response.sendRedirect( "http://localhost:8080/error.html" ); //$NON-NLS-1$
	}

	cm = ChartModels.createBarChart( );
	
	Enumeration en = request.getParameterNames( );
	while ( en.hasMoreElements( ) )
	{
		String name = (String) en.nextElement( );
		String value = request.getParameterValues( name )[0];

		if ( name.equals( "fonts" ) )//$NON-NLS-1$
		{
			fontName = value;
		}
		else if ( name.equals( "style" ) )//$NON-NLS-1$
		{
			if ( value.equals( "Bold" ) )//$NON-NLS-1$
			{
				bBold = true;
				bItalic = false;
			}
			else if ( value.equals( "Italic" ) )//$NON-NLS-1$
			{
				bBold = false;
				bItalic = true;
			}
		}
		else if ( name.equals( "size" ) )//$NON-NLS-1$
		{
			size = Float.parseFloat( value );				
		}
		else if ( name.equals( "color" ) )//$NON-NLS-1$
		{
			if ( value.equals( "Black" ) ) //$NON-NLS-1$
			{
				cd = ColorDefinitionImpl.BLACK( );
			}
			else if ( value.equals( "Red" ) ) //$NON-NLS-1$
			{
				cd = ColorDefinitionImpl.RED( );
			}
			else if ( value.equals( "Blue" ) ) //$NON-NLS-1$
			{
				cd = ColorDefinitionImpl.BLUE( );
			}
		}

	}

	response.setHeader( "Cache-Control", "no-store" ); //$NON-NLS-1$//$NON-NLS-2$
	response.setDateHeader( "Expires", 0 ); //$NON-NLS-1$

	// Set the Content-Type header for the image output
	response.setContentType( "image/jpeg" ); //$NON-NLS-1$
	createImage( (OutputStream) response.getOutputStream( ) );
}