javax.servlet.http.HttpServletResponse Java Examples

The following examples show how to use javax.servlet.http.HttpServletResponse. 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: EDLControllerChain.java    From rice with Educational Community License v2.0 7 votes vote down vote up
private void transform(EDLContext edlContext, Document dom, HttpServletResponse response) throws Exception {
	if (StringUtils.isNotBlank(edlContext.getRedirectUrl())) {
		response.sendRedirect(edlContext.getRedirectUrl());
		return;
	}
    response.setContentType("text/html; charset=UTF-8");
	Transformer transformer = edlContext.getTransformer();

       transformer.setOutputProperty("indent", "yes");
       transformer.setOutputProperty(OutputKeys.INDENT, "yes");
       String user = null;
       String loggedInUser = null;
       if (edlContext.getUserSession() != null) {
           Person wu = edlContext.getUserSession().getPerson();
           if (wu != null) user = wu.getPrincipalId();
           wu = edlContext.getUserSession().getPerson();
           if (wu != null) loggedInUser = wu.getPrincipalId();
       }
       transformer.setParameter("user", user);
       transformer.setParameter("loggedInUser", loggedInUser);
       if (LOG.isDebugEnabled()) {
       	LOG.debug("Transforming dom " + XmlJotter.jotNode(dom, true));
       }
       transformer.transform(new DOMSource(dom), new StreamResult(response.getOutputStream()));
}
 
Example #2
Source File: AuthenticationMechanism.java    From javaee8-cookbook with Apache License 2.0 6 votes vote down vote up
@Override
public AuthenticationStatus validateRequest(HttpServletRequest request, HttpServletResponse response, HttpMessageContext httpMessageContext) throws AuthenticationException {

    if (httpMessageContext.isAuthenticationRequest()) {

        Credential credential = httpMessageContext.getAuthParameters().getCredential();
        if (!(credential instanceof CallerOnlyCredential)) {
            throw new IllegalStateException("Invalid mechanism");
        }

        CallerOnlyCredential callerOnlyCredential = (CallerOnlyCredential) credential;

        if ("user".equals(callerOnlyCredential.getCaller())) {
            return httpMessageContext.notifyContainerAboutLogin(callerOnlyCredential.getCaller(), new HashSet<>(Arrays.asList("role1","role2")));
        } else{
            throw new AuthenticationException();
        }

    }

    return httpMessageContext.doNothing();
}
 
Example #3
Source File: OrderController.java    From MusicStore with MIT License 6 votes vote down vote up
private String addItem(HttpServletRequest request, HttpServletResponse response) {
   // retrieve or create a cart
   HttpSession session = request.getSession();
   Cart cart = (Cart) session.getAttribute("cart");
   if (cart == null) {
      cart = new Cart();
   }

   // get the product from the database, create a line item and put it into the cart
   String productCode = request.getParameter("productCode");
   Product product = ProductDB.selectProduct(productCode);
   if (product != null) {
      LineItem lineItem = new LineItem();
      lineItem.setProduct(product);
      cart.addItem(lineItem);
   }

   session.setAttribute("cart", cart);
   return "/cart/cart.jsp";
}
 
Example #4
Source File: UploadServlet.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws IOException, ServletException {
  final Part filePart = req.getPart("file");
  final String fileName = filePart.getSubmittedFileName();

  // Modify access list to allow all users with link to read file
  List<Acl> acls = new ArrayList<>();
  acls.add(Acl.of(Acl.User.ofAllUsers(), Acl.Role.READER));
  // the inputstream is closed by default, so we don't need to close it here
  Blob blob =
      storage.create(
          BlobInfo.newBuilder(BUCKET_NAME, fileName).setAcl(acls).build(),
          filePart.getInputStream());

  // return the public download link
  resp.getWriter().print(blob.getMediaLink());
}
 
Example #5
Source File: ValidateCodeFilter.java    From blog-sample with Apache License 2.0 6 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    if(isProtectedUrl(request)) {
        String verifyCode = request.getParameter(SecurityConstants.VALIDATE_CODE_PARAMETER);
        if(!validateVerify(verifyCode)) {
            //手动设置异常
            request.getSession().setAttribute("SPRING_SECURITY_LAST_EXCEPTION",new DisabledException("验证码输入错误"));
            // 转发到错误Url
            request.getRequestDispatcher(SecurityConstants.VALIDATE_CODE_ERR_URL).forward(request,response);
        } else {
            filterChain.doFilter(request,response);
        }
    } else {
        filterChain.doFilter(request,response);
    }
}
 
Example #6
Source File: ProcessInstanceIdentityLinkResource.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
@ApiOperation(value = "Remove an involved user to from process instance", tags = { "Process Instances" },  nickname = "deleteProcessInstanceIdentityLinks")
@ApiResponses(value = {
    @ApiResponse(code = 204, message = "Indicates the process instance was found and the link has been deleted. Response body is left empty intentionally."),
    @ApiResponse(code = 404, message = "Indicates the requested process instance was not found or the link to delete doesn’t exist. The response status contains additional information about the error.")
})
@RequestMapping(value = "/runtime/process-instances/{processInstanceId}/identitylinks/users/{identityId}/{type}", method = RequestMethod.DELETE)
public void deleteIdentityLink(@ApiParam(name = "processInstanceId", value="The id of the process instance.") @PathVariable("processInstanceId") String processInstanceId,@ApiParam(name = "identityId", value="The id of the user to delete link for.") @PathVariable("identityId") String identityId,@ApiParam(name = "type", value="Type of link to delete.") @PathVariable("type") String type,
    HttpServletResponse response) {

  ProcessInstance processInstance = getProcessInstanceFromRequest(processInstanceId);

  validateIdentityLinkArguments(identityId, type);

  getIdentityLink(identityId, type, processInstance.getId());

  runtimeService.deleteUserIdentityLink(processInstance.getId(), identityId, type);

  response.setStatus(HttpStatus.NO_CONTENT.value());
}
 
Example #7
Source File: JwWebJwidController.java    From jeewx-boot with Apache License 2.0 6 votes vote down vote up
/**
 * 初始化jwid
 */
@RequestMapping(value="/initJwid",produces="text/plain;charset=UTF-8")
@ResponseBody
public String initJwid(HttpServletRequest request, HttpServletResponse response,
		@RequestParam(value = "userId", required = true) String userId) {
	log.info("初始化公众号");
	String tree = "";
    try {
        //所有可用的权限
        List<WeixinAccountDto> allJwidList = jwWebJwidService.queryJwids();
        
        //当前角色的权限
        List<WeixinAccountDto> userJwidList = jwWebJwidService.queryJwWebJwidByUserId(userId);
       
        tree = SystemUtil.list2TreeWithCheckToJwid(allJwidList,userJwidList);
        log.info("初始化公众号: " + tree);
    }catch (Exception e){
    	log.info(e.getMessage());
    }
    return tree;
}
 
Example #8
Source File: GrafanaAuthenticationTest.java    From Insights with Apache License 2.0 6 votes vote down vote up
@Test(priority = 4)
public void loginWithIncorrectHeader() throws Exception {
	this.mockMvc = getMacMvc();
	Map<String, String> headers = new HashMap();
	headers.put("Cookie", cookiesString);
	headers.put("Authorization", GrafanaAuthenticationTestData.authorization);
	headers.put("user", "<br></br>");
	headers.put(HttpHeaders.ORIGIN, ApplicationConfigProvider.getInstance().getInsightsServiceURL());
	headers.put(HttpHeaders.HOST, AuthenticationUtils.getHost(null));
	headers.put(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "GET, POST, OPTIONS, PUT, DELETE, PATCH");
	headers.put(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "*");
	MockHttpServletRequestBuilder builder = mockHttpServletRequestBuilderPostWithRequestParam("/user/authenticate",
			"", headers);

	ResultActions action = this.mockMvc.perform(builder.with(csrf().asHeader()));
	action.andExpect(status().is(HttpServletResponse.SC_BAD_REQUEST));
}
 
Example #9
Source File: JobExceptionStacktraceResource.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@ApiOperation(value = "Get the exception stacktrace for a suspended job", tags = { "Jobs" })
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Indicates the requested job was not found and the stacktrace has been returned. The response contains the raw stacktrace and always has a Content-type of text/plain."),
        @ApiResponse(code = 404, message = "Indicates the requested job was not found or the job does not have an exception stacktrace. Status-description contains additional information about the error.")
})
@GetMapping("/management/suspended-jobs/{jobId}/exception-stacktrace")
public String getSuspendedJobStacktrace(@ApiParam(name = "jobId") @PathVariable String jobId, HttpServletResponse response) {
    Job job = getSuspendedJobById(jobId);

    String stackTrace = managementService.getSuspendedJobExceptionStacktrace(job.getId());

    if (stackTrace == null) {
        throw new FlowableObjectNotFoundException("Suspended job with id '" + job.getId() + "' does not have an exception stacktrace.", String.class);
    }

    response.setContentType("text/plain");
    return stackTrace;
}
 
Example #10
Source File: AtlasApiTrustedProxyHaDispatch.java    From knox with Apache License 2.0 6 votes vote down vote up
@Override
protected void executeRequest(HttpUriRequest outboundRequest, HttpServletRequest inboundRequest, HttpServletResponse outboundResponse) throws IOException {
  HttpResponse inboundResponse = null;
  try {
    inboundResponse = executeOutboundRequest(outboundRequest);
    int statusCode = inboundResponse.getStatusLine().getStatusCode();
    Header originalLocationHeader = inboundResponse.getFirstHeader("Location");


    if ((statusCode == HttpServletResponse.SC_MOVED_TEMPORARILY || statusCode == HttpServletResponse.SC_TEMPORARY_REDIRECT) && originalLocationHeader != null) {
      inboundResponse.removeHeaders("Location");
      failoverRequest(outboundRequest, inboundRequest, outboundResponse, inboundResponse, new Exception("Atlas HA redirection"));
    }

    writeOutboundResponse(outboundRequest, inboundRequest, outboundResponse, inboundResponse);

  } catch (IOException e) {
    LOG.errorConnectingToServer(outboundRequest.getURI().toString(), e);
    failoverRequest(outboundRequest, inboundRequest, outboundResponse, inboundResponse, e);
  }
}
 
Example #11
Source File: DataSourceAction.java    From boubei-tss with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/connpool/{paramId}", method = RequestMethod.DELETE)
@ResponseBody
public Object delConnpool(HttpServletResponse response, @PathVariable("paramId") Long paramId) {
	Param param = paramService.getParam(paramId);
       paramService.delete(paramId);   
       
       // 删除“数据源列表”的下拉项
       String code = param.getCode();
       List<Param> list = ParamManager.getComboParam(PX.DATASOURCE_LIST);
	for(Param item : list) {
		if( code.equals(item.getValue()) ) {
			paramService.delete(item.getId());  
			break;
		}
	}
	
	JCache.pools.remove(code);
       
       return "成功删除数据源";
   }
 
Example #12
Source File: FlowableCookieFilter.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void redirectToLogin(HttpServletRequest request, HttpServletResponse response, String userId) {
    try {
        if (userId != null) {
            userCache.invalidate(userId);
        }
        
        String baseRedirectUrl = idmAppUrl + "#/login?redirectOnAuthSuccess=true&redirectUrl=";
        if (redirectUrlOnAuthSuccess != null) {
            response.sendRedirect(baseRedirectUrl + redirectUrlOnAuthSuccess);
            
        } else {
            response.sendRedirect(baseRedirectUrl + request.getRequestURL());
        }
        
    } catch (IOException e) {
        LOGGER.warn("Could not redirect to {}", idmAppUrl, e);
    }
}
 
Example #13
Source File: AoomsGlobalErrorController.java    From Aooms with Apache License 2.0 6 votes vote down vote up
/**
 * 覆盖默认的HTML响应
 */
@Override
public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
    //请求的状态
    HttpStatus status = getStatus(request);
    //isIncludeStackTrace(request, MediaType.TEXT_HTML)

    // message
    // status
    // trace
    // path
    // timestamp
    // error

    // 包含异常堆栈信息
    Map<String, Object> model = getErrorAttributes(request, true);
    ModelAndView modelAndView = resolveErrorView(request, response, status, model);

    //指定自定义的视图
    return new ModelAndView("/error.html", model);
}
 
Example #14
Source File: ReportController.java    From mysql_perf_analyzer with Apache License 2.0 6 votes vote down vote up
private ModelAndView list(HttpServletRequest req,
		HttpServletResponse resp) throws Exception
{
	int status = 0;
	String message = "OK";
	ResultList rList = null;
	UserReportManager urm = this.getUserReportManager(req);
	try
	{
		String appUser = WebAppUtil.findUserFromRequest(req);
		if(appUser==null||urm==null)
		{
			status = -1;
			message="Not login or session timed out";
		}else
		{
			rList = urm.listResultList();
		}
	}catch(Exception ex)
	{
		logger.log(Level.SEVERE,"Exception", ex);
	}
	ModelAndView mv = new ModelAndView(this.jsonView);
	mv.addObject("json_result", ResultListUtil.toJSONString(rList, null, status, message));
	return mv;
}
 
Example #15
Source File: WebApiFilter.java    From fess with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException,
        ServletException {
    final WebApiManagerFactory webApiManagerFactory = ComponentUtil.getWebApiManagerFactory();
    final WebApiManager webApiManager = webApiManagerFactory.get((HttpServletRequest) request);
    if (webApiManager == null) {
        chain.doFilter(request, response);
    } else {
        webApiManager.process((HttpServletRequest) request, (HttpServletResponse) response, chain);
    }
}
 
Example #16
Source File: FoodManagementApi.java    From springboot-rest-h2-swagger with GNU General Public License v3.0 5 votes vote down vote up
@GetMapping(value = "/public/getFoods/{caloriesMin}/{caloriesMax}", produces= {MediaType.APPLICATION_JSON_VALUE})
@ApiOperation(value="Return all Foods with details by calories range", notes="This is a public API", response=List.class)
@ApiResponses(value = { 
		@ApiResponse(code = HttpServletResponse.SC_OK, message = "Success"),
		@ApiResponse(code = HttpServletResponse.SC_NOT_FOUND, message = "Not found any food by calories range")
})
ResponseEntity getFoods(@PathVariable("caloriesMin") Integer caloriesMin, @PathVariable("caloriesMax") Integer caloriesMax);
 
Example #17
Source File: JettyContinuationWrapper.java    From cxf with Apache License 2.0 5 votes vote down vote up
public JettyContinuationWrapper(HttpServletRequest request,
                                HttpServletResponse resp,
                                Message m) {
    continuation = ContinuationSupport.getContinuation(request);

    message = m;
    isNew = request.getAttribute(AbstractHTTPDestination.CXF_CONTINUATION_MESSAGE) == null;
    if (isNew) {
        request.setAttribute(AbstractHTTPDestination.CXF_CONTINUATION_MESSAGE,
                             message.getExchange().getInMessage());
        continuation.addContinuationListener(this);
        callback = message.getExchange().get(ContinuationCallback.class);
    }
}
 
Example #18
Source File: ViewResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testInternalResourceViewResolverWithJstl() throws Exception {
	Locale locale = !Locale.GERMAN.equals(Locale.getDefault()) ? Locale.GERMAN : Locale.FRENCH;

	MockServletContext sc = new MockServletContext();
	StaticWebApplicationContext wac = new StaticWebApplicationContext();
	wac.setServletContext(sc);
	wac.addMessage("code1", locale, "messageX");
	wac.refresh();
	InternalResourceViewResolver vr = new InternalResourceViewResolver();
	vr.setViewClass(JstlView.class);
	vr.setApplicationContext(wac);

	View view = vr.resolveViewName("example1", Locale.getDefault());
	assertEquals("Correct view class", JstlView.class, view.getClass());
	assertEquals("Correct URL", "example1", ((JstlView) view).getUrl());

	view = vr.resolveViewName("example2", Locale.getDefault());
	assertEquals("Correct view class", JstlView.class, view.getClass());
	assertEquals("Correct URL", "example2", ((JstlView) view).getUrl());

	MockHttpServletRequest request = new MockHttpServletRequest(sc);
	HttpServletResponse response = new MockHttpServletResponse();
	request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
	request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, new FixedLocaleResolver(locale));
	Map<String, Object> model = new HashMap<>();
	TestBean tb = new TestBean();
	model.put("tb", tb);
	view.render(model, request, response);

	assertTrue("Correct tb attribute", tb.equals(request.getAttribute("tb")));
	assertTrue("Correct rc attribute", request.getAttribute("rc") == null);

	assertEquals(locale, Config.get(request, Config.FMT_LOCALE));
	LocalizationContext lc = (LocalizationContext) Config.get(request, Config.FMT_LOCALIZATION_CONTEXT);
	assertEquals("messageX", lc.getResourceBundle().getString("code1"));
}
 
Example #19
Source File: SecurityFilter.java    From logbook with MIT License 5 votes vote down vote up
@Override
public void doFilter(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain chain) throws ServletException, IOException {

    if (status == null) {
        chain.doFilter(request, response);
    } else {
        response.setStatus(status);
    }
}
 
Example #20
Source File: RestServletCollector.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
    LOGGER.debug("Karaf Decanter REST Servlet Collector request received from {}", req.getRequestURI());
    try {
        StringBuilder builder = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        }
        String payload = builder.toString();

        Map<String, Object> data = unmarshaller.unmarshal(new ByteArrayInputStream(payload.getBytes()));
        data.put("type", "restservlet");
        data.put("payload", payload);

        PropertiesPreparator.prepare(data, properties);

        Event event = new Event(baseTopic, data);
        dispatcher.postEvent(event);
        resp.setStatus(HttpServletResponse.SC_CREATED);
        LOGGER.debug("Karaf Decanter REST Servlet Collector harvesting done");
    } catch (Exception e) {
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        LOGGER.warn("Error processing event from servlet", e);
    }
    
}
 
Example #21
Source File: DesignerServletHandler.java    From uflo with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	String method=retriveMethod(req);
	if(method!=null){
		invokeMethod(method, req, resp);
	}else{
		VelocityContext context = new VelocityContext();
		context.put("contextPath", req.getContextPath());
		if(additionalInfoProvider!=null) {
			List<String> categories=additionalInfoProvider.categories();
			if(categories!=null && categories.size()>0) {
				StringBuilder sb=new StringBuilder();
				for(String category:categories) {
					if(sb.length()>0) {
						sb.append(",");
					}
					sb.append("\""+category+"\"");
				}
				context.put("categories", sb.toString());
			}
		}else {
			context.put("categories", "");
		}
		resp.setContentType("text/html");
		resp.setCharacterEncoding("utf-8");
		Template template=ve.getTemplate("uflo-html/designer.html","utf-8");
		PrintWriter writer=resp.getWriter();
		template.merge(context, writer);
		writer.close();
	}
}
 
Example #22
Source File: SiteResetHandler.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@Override
public int doGet(String[] parts, HttpServletRequest req, HttpServletResponse res,
		Session session) throws PortalHandlerException
{
	if ((parts.length > 2) && (parts[1].equals(SiteResetHandler.URL_FRAGMENT)))
	{
		try
		{
			String siteUrl = req.getContextPath() + "/site"
					+ Web.makePath(parts, 2, parts.length);
			// Make sure to add the parameters such as panel=Main
			String queryString = Validator.generateQueryString(req);
			if (queryString != null)
			{
				siteUrl = siteUrl + "?" + queryString;
			}
			portalService.setResetState("true");
			res.sendRedirect(siteUrl);
			return RESET_DONE;
		}
		catch (Exception ex)
		{
			throw new PortalHandlerException(ex);
		}
	}
	else
	{
		return NEXT;
	}
}
 
Example #23
Source File: BenchmarkTest02283.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");

		java.util.Map<String,String[]> map = request.getParameterMap();
		String param = "";
		if (!map.isEmpty()) {
			String[] values = map.get("BenchmarkTest02283");
			if (values != null) param = values[0];
		}
		

		String bar = doSomething(request, param);
		
		String sql = "SELECT * from USERS where USERNAME='foo' and PASSWORD='"+ bar +"'";
				
		try {
			java.sql.Statement statement =  org.owasp.benchmark.helpers.DatabaseHelper.getSqlStatement();
			statement.execute( sql, new int[] { 1, 2 } );
            org.owasp.benchmark.helpers.DatabaseHelper.printResults(statement, 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 #24
Source File: CacheAction.java    From boubei-tss with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/item/{code}", method = RequestMethod.DELETE)
  public void removeCachedItem(HttpServletResponse response, 
  		@PathVariable String code, 
  		@RequestParam("key") String key) {
  	
      Pool pool = cache.getPool(code);
boolean rt = pool.destroyByKey(key);
      printSuccessMessage( !rt ? "destroy succeed。" : EX.CACHE_5);
  }
 
Example #25
Source File: ToDoServlet.java    From gradle-in-action-source with MIT License 5 votes vote down vote up
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String servletPath = request.getServletPath();
    String view = processRequest(servletPath, request);

    if (view != null) {
        RequestDispatcher dispatcher = request.getRequestDispatcher(view);
        dispatcher.forward(request, response);
    }
}
 
Example #26
Source File: AddMembersControllerTest.java    From webcurator with Apache License 2.0 5 votes vote down vote up
@Test
public final void testHandleAddMembers2NoPriv() {
	try
	{
		testSetAuthorityManager();
		testSetTargetManager();
		testSetGroupsController();

		this.removeAllCurrentUserPrivileges();
		
		HttpServletRequest request = new MockHttpServletRequest();
		HttpServletResponse response = new MockHttpServletResponse();
		AddMembersCommand command = new AddMembersCommand();

		BindException errors = new BindException(command, "AddMembersCommand");

		bindEditorContext(request, 15001L);
		
		command.setActionCmd(AddMembersCommand.ACTION_ADD_MEMBERS);
		long[]  oids = {4000L};
		command.setMemberOids(oids);
		
		assertTrue(testInstance.getEditorContext(request).getTargetGroup().getNewChildren().size() == 0);
		ModelAndView mav = testInstance.handle(request, response, command, errors);
		assertNotNull(mav);
		assertEquals(mav.getViewName(), "groups");
		assertTrue(errors.getErrorCount() == 0);
		assertTrue(testInstance.getEditorContext(request).getTargetGroup().getNewChildren().size() == 0);
	}
	catch(Exception e)
	{
		fail(e.getMessage());
	}
}
 
Example #27
Source File: ThemeChangeInterceptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
		throws ServletException {

	String newTheme = request.getParameter(this.paramName);
	if (newTheme != null) {
		ThemeResolver themeResolver = RequestContextUtils.getThemeResolver(request);
		if (themeResolver == null) {
			throw new IllegalStateException("No ThemeResolver found: not in a DispatcherServlet request?");
		}
		themeResolver.setThemeName(request, response, newTheme);
	}
	// Proceed in any case.
	return true;
}
 
Example #28
Source File: BenchmarkTest02271.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");

		java.util.Map<String,String[]> map = request.getParameterMap();
		String param = "";
		if (!map.isEmpty()) {
			String[] values = map.get("BenchmarkTest02271");
			if (values != null) param = values[0];
		}
		

		String bar = doSomething(request, param);
		
		String sql = "SELECT * from USERS where USERNAME=? and PASSWORD='"+ bar +"'";
				
		try {
			java.sql.Connection connection = org.owasp.benchmark.helpers.DatabaseHelper.getSqlConnection();
			java.sql.PreparedStatement statement = connection.prepareStatement( sql, new int[] { 1, 2 } );
			statement.setString(1, "foo");
			statement.execute();
            org.owasp.benchmark.helpers.DatabaseHelper.printResults(statement, 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 #29
Source File: Prj2000Controller.java    From oslits with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Prj2001 프로젝트 권한 추가 레이어 팝업 화면 이동
 * @param 
 * @return 
 * @exception Exception
 */
@RequestMapping(value="/prj/prj2000/prj2000/selectPrj2001View.do")
   public String selectPrj2001View(HttpServletRequest request, HttpServletResponse response, ModelMap model ) throws Exception {
   	
	try{
   		// request 파라미터를 map으로 변환
       	Map<String, String> paramMap = RequestConvertor.requestParamToMapAddSelInfo(request, true);
   		
       	// 팝업 구분이 수정이 아닐경우
       	if(!"update".equals(paramMap.get("gb"))) {
   			// 세션에서 loginVO값을 가져온다.
           	HttpSession ss = request.getSession();
          		LoginVO loginVO = (LoginVO) ss.getAttribute("loginVO");
          		// 라이선스 그룹 Id Map에 세팅
              	paramMap.put("licGrpId", loginVO.getLicGrpId());
              	// 프로젝트 ID 세팅
              	paramMap.put("prjId", paramMap.get("selPrjId"));
              	
       		// 새로 추가할 역할그룹의 순번값을 가져온다. (현재 프로젝트에 등록된 역할그룹 순번의 최고값 +1)
              	int authGrpNextOrd = prj2000Service.selectPrj2000AuthGrpNextOrd(paramMap);
              	model.addAttribute("authGrpNextOrd", authGrpNextOrd);
   		}
          	
       	return "/prj/prj2000/prj2000/prj2001";
   	}
   	catch(Exception ex){
   		Log.error("selectPrj2001View()", ex);
   		throw new Exception(ex.getMessage());
   	}
   }
 
Example #30
Source File: OnlineEditorController.java    From es with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/download")
public String download(
        HttpServletRequest request, HttpServletResponse response,
        @RequestParam("path") String path) throws Exception {

    String rootPath = sc.getRealPath(ROOT_DIR);
    String filePath = rootPath + File.separator + URLDecoder.decode(path, Constants.ENCODING);
    filePath = filePath.replace("\\", "/");

    DownloadUtils.download(request, response, filePath, "");

    return null;

}