Java Code Examples for javax.servlet.http.HttpServletRequest

The following are top voted examples for showing how to use javax.servlet.http.HttpServletRequest. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: shoucang   File: GZipResponseUtil.java   View source code 11 votes vote down vote up
/**
 * Performs a number of checks to ensure response saneness according to the rules of RFC2616:
 * <ol>
 * <li>If the response code is {@link javax.servlet.http.HttpServletResponse#SC_NO_CONTENT} then it is illegal for the body
 * to contain anything. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.5
 * <li>If the response code is {@link javax.servlet.http.HttpServletResponse#SC_NOT_MODIFIED} then it is illegal for the body
 * to contain anything. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
 * </ol>
 *
 * @param request        the client HTTP request
 * @param responseStatus the responseStatus
 * @return true if the response should be 0, even if it is isn't.
 */
public static boolean shouldBodyBeZero(HttpServletRequest request, int responseStatus) {

    //Check for NO_CONTENT
    if (responseStatus == HttpServletResponse.SC_NO_CONTENT) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("{} resulted in a {} response. Removing message body in accordance with RFC2616.",
                    request.getRequestURL(), HttpServletResponse.SC_NO_CONTENT);
        }
        return true;
    }

    //Check for NOT_MODIFIED
    if (responseStatus == HttpServletResponse.SC_NOT_MODIFIED) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("{} resulted in a {} response. Removing message body in accordance with RFC2616.",
                    request.getRequestURL(), HttpServletResponse.SC_NOT_MODIFIED);
        }
        return true;
    }
    return false;
}
 
Example 2
Project: tomcat7   File: ImplicitObjectELResolver.java   View source code 9 votes vote down vote up
public Map<String,Cookie> getCookie() {
    if (this.cookie == null) {
        this.cookie = new ScopeMap<Cookie>() {
            @Override
            protected Enumeration<String> getAttributeNames() {
                Cookie[] c = ((HttpServletRequest) page.getRequest())
                        .getCookies();
                if (c != null) {
                    Vector<String> v = new Vector<String>();
                    for (int i = 0; i < c.length; i++) {
                        v.add(c[i].getName());
                    }
                    return v.elements();
                }
                return null;
            }

            @Override
            protected Cookie getAttribute(String name) {
                Cookie[] c = ((HttpServletRequest) page.getRequest())
                        .getCookies();
                if (c != null) {
                    for (int i = 0; i < c.length; i++) {
                        if (name.equals(c[i].getName())) {
                            return c[i];
                        }
                    }
                }
                return null;
            }

        };
    }
    return this.cookie;
}
 
Example 3
Project: shoucang   File: CsrfCookieGeneratorFilter.java   View source code 8 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    // Spring put the CSRF token in session attribute "_csrf"
    CsrfToken csrfToken = (CsrfToken) request.getAttribute("_csrf");

    // Send the cookie only if the token has changed
    String actualToken = request.getHeader("X-CSRF-TOKEN");
    if (actualToken == null || !actualToken.equals(csrfToken.getToken())) {
        // Session cookie that will be used by AngularJS
        String pCookieName = "CSRF-TOKEN";
        Cookie cookie = new Cookie(pCookieName, csrfToken.getToken());
        cookie.setMaxAge(-1);
        cookie.setHttpOnly(false);
        cookie.setPath("/");
        response.addCookie(cookie);
    }
    filterChain.doFilter(request, response);
}
 
Example 4
Project: lams   File: WebUtil.java   View source code 7 votes vote down vote up
/**
    * TODO default proper exception at lams level to replace RuntimeException TODO isTesting should be removed when
    * login is done properly.
    *
    * @param req
    *            -
    * @return username from principal object
    */
   public static String getUsername(HttpServletRequest req, boolean isTesting) throws RuntimeException {
if (isTesting) {
    return "test";
}

Principal prin = req.getUserPrincipal();
if (prin == null) {
    throw new RuntimeException(
	    "Trying to get username but principal object missing. Request is " + req.toString());
}

String username = prin.getName();
if (username == null) {
    throw new RuntimeException("Name missing from principal object. Request is " + req.toString()
	    + " Principal object is " + prin.toString());
}

return username;
   }
 
Example 5
Project: pay-xxpay-master   File: Notify4AliPayController.java   View source code 6 votes vote down vote up
public String doAliPayRes(HttpServletRequest request) throws ServletException, IOException {
	String logPrefix = "【支付宝支付回调通知】";
	//获取支付宝POST过来反馈信息
	Map<String,String> params = new HashMap<String,String>();
	Map requestParams = request.getParameterMap();
	for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
		String name = (String) iter.next();
		String[] values = (String[]) requestParams.get(name);
		String valueStr = "";
		for (int i = 0; i < values.length; i++) {
			valueStr = (i == values.length - 1) ? valueStr + values[i]
					: valueStr + values[i] + ",";
		}
		//乱码解决,这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
		//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
		params.put(name, valueStr);
	}
	_log.info("{}通知请求数据:reqStr={}", logPrefix, params);
	if(params.isEmpty()) {
		_log.error("{}请求参数为空", logPrefix);
		return PayConstant.RETURN_ALIPAY_VALUE_FAIL;
	}
	return notifyPayService.doAliPayNotify(params);
}
 
Example 6
Project: validator-web   File: RedirectView.java   View source code 6 votes vote down vote up
/**
 * Creates the target URL by checking if the redirect string is a URI template first,
 * expanding it with the given model, and then optionally appending simple type model
 * attributes as query String parameters.
 */
protected final String createTargetUrl(Map<String, Object> model, HttpServletRequest request)
        throws UnsupportedEncodingException {
    // Prepare target URL.
    StringBuilder targetUrl = new StringBuilder();
    if (this.contextRelative && getUrl().startsWith("/")) {
        // Do not apply context path to relative URLs.
        targetUrl.append(request.getContextPath());
    }
    targetUrl.append(getUrl());
    
    String enc = this.encodingScheme;
    if (enc == null) {
        enc = request.getCharacterEncoding();
    }
    if (enc == null) {
        enc = DEFAULT_CHARACTER_ENCODING;
    }
    
    if (this.expandUriTemplateVariables && StringUtils.hasText(targetUrl)) {
        Map<String, String> variables = Collections.<String, String> emptyMap();
        targetUrl = replaceUriTemplateVariables(targetUrl.toString(), model, variables, enc);
    }
    if (this.exposeModelAttributes) {
        appendQueryProperties(targetUrl, model, enc);
    }
    return targetUrl.toString();
}
 
Example 7
Project: product   File: ProductlevelAction.java   View source code 6 votes vote down vote up
@At("/")
@Ok("beetl:/WEB-INF/base/productlevel_list.html")
public void index(@Param("..")Page p,
                  @Param("..")Productlevel productlevel,
                  HttpServletRequest request){

    Cnd c = new ParseObj(productlevel).getCnd();
    if (c == null || c.equals(""))
    {
        p.setRecordCount(productlevelService.listCount(c));
        request.setAttribute("list_obj", productlevelService.queryCache(c,p));
    }else{
        p.setRecordCount(productlevelService.count(c));
        request.setAttribute("list_obj", productlevelService.query(c,p));
    }

    request.setAttribute("page", p);
    request.setAttribute("productlevel", productlevel);
}
 
Example 8
Project: solo-spring   File: InitProcessor.java   View source code 6 votes vote down vote up
/**
 * Shows initialization page.
 *
 * @param context
 *            the specified http request context
 * @param request
 *            the specified http servlet request
 * @param response
 *            the specified http servlet response
 * @throws Exception
 *             exception
 */
@RequestMapping(value = "/init", method = RequestMethod.GET)
public void showInit(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
	if (initService.isInited()) {
		response.sendRedirect("/");
		return;
	}

	final AbstractFreeMarkerRenderer renderer = new ConsoleRenderer();
	renderer.setTemplateName("init.ftl");

	final Map<String, Object> dataModel = renderer.getDataModel();

	final Map<String, String> langs = langPropsService.getAll(Locales.getLocale(request));

	dataModel.putAll(langs);

	dataModel.put(Common.VERSION, SoloConstant.VERSION);
	dataModel.put(Common.STATIC_RESOURCE_VERSION, Latkes.getStaticResourceVersion());
	dataModel.put(Common.YEAR, String.valueOf(Calendar.getInstance().get(Calendar.YEAR)));

	Keys.fillRuntime(dataModel);
	filler.fillMinified(dataModel);
	renderer.render(request, response);
}
 
Example 9
Project: uflo   File: DesignerServletHandler.java   View source code 6 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());
		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 10
Project: dubbo-mock   File: MockOperDefineController.java   View source code 6 votes vote down vote up
@ResponseBody
@RequestMapping(value = "/selectMockRuleScript")
public String selectMockRuleScript(HttpServletRequest arg0, Boolean selectFlag) throws Exception {
    String serviceId = arg0.getParameter("serviceId");
    String mockTestIds = arg0.getParameter("mockTestIds");
    String[] mocks = mockTestIds.split(",");
    Integer[] integers = new Integer[mocks.length];
    for (int i = 0; i < mocks.length; i++) {
        integers[i] = Integer.valueOf(mocks[i]);
    }
    MockGenericService service = dubboMockServer.buildMockGenericService(Integer.valueOf(serviceId), integers);
    Map<String, String> map = Maps.newConcurrentMap();
    Set<String> set = service.getRules().keySet();
    for (String key : set) {
        MethodRule rule = service.getRules().get(key);
        map.put(key, rule.getTemplate().getRaw());
    }
    return JSON.toJSONString(map);
}
 
Example 11
Project: NGB-master   File: UrlTestingUtils.java   View source code 6 votes vote down vote up
public static Server getFileServer(ApplicationContext context) {
    Resource resource = context.getResource("classpath:templates");

    Server server = new Server(UrlTestingUtils.TEST_FILE_SERVER_PORT);
    server.setHandler(new AbstractHandler() {
            @Override
            public void handle(String target, Request baseRequest, HttpServletRequest request,
                               HttpServletResponse response) throws IOException, ServletException {
            String uri = baseRequest.getRequestURI();
            LOGGER.info(uri);
            File file = new File(resource.getFile().getAbsolutePath() + uri);
            MultipartFileSender fileSender = MultipartFileSender.fromFile(file);
            try {
                fileSender.with(request).with(response).serveResource();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

    return server;
}
 
Example 12
Project: doctorkafka   File: DoctorKafkaWebServer.java   View source code 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest request,
                     HttpServletResponse response) throws ServletException,
                                                          IOException {
  response.setContentType("text/html");
  try {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    URL resource = classLoader.getResource(indexPagePath);
    URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{resource});

    InputStream input = urlClassLoader.getResourceAsStream(indexPagePath);
    String result = CharStreams.toString(new InputStreamReader(input, Charsets.UTF_8));
    response.setStatus(HttpServletResponse.SC_OK);
    response.getWriter().print(result);
  } catch (Exception e) {
    response.getWriter().print(e);
    LOG.error("error : ", e);
  }
}
 
Example 13
Project: lemon   File: BpmCategoryController.java   View source code 6 votes vote down vote up
@RequestMapping("bpm-category-export")
public void export(@ModelAttribute Page page,
        @RequestParam Map<String, Object> parameterMap,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    List<PropertyFilter> propertyFilters = PropertyFilter
            .buildFromMap(parameterMap);
    page = bpmCategoryManager.pagedQuery(page, propertyFilters);

    List<BpmCategory> bpmCategories = (List<BpmCategory>) page.getResult();
    TableModel tableModel = new TableModel();
    tableModel.setName("bpm-category");
    tableModel.addHeaders("id", "name");
    tableModel.setData(bpmCategories);
    exportor.export(request, response, tableModel);
}
 
Example 14
Project: unitimes   File: StudentSolverForm.java   View source code 6 votes vote down vote up
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
       ActionErrors errors = new ActionErrors();

       if(iSetting==null || iSetting.intValue()<0)
           errors.add("setting", new ActionMessage("errors.lookup.config.required", ""));
       
       Set<Long> emptyIds = new HashSet<Long>(SolverPredefinedSettingDAO.getInstance().getSession().createQuery(
       		"select s.uniqueId from SolverParameterDef s where s.group.name = :group and s.visible = true and s.type = :type")
       		.setString("group", "StudentSctBasic")
       		.setString("type", "text").setCacheable(true).list());
       
       for (Iterator i=iParamValues.entrySet().iterator();i.hasNext();) {
       	Map.Entry entry = (Map.Entry)i.next();
        	Long parm = (Long)entry.getKey();
        	if (emptyIds.contains(parm)) continue;
       	String val = (String)entry.getValue();
       	if (val==null || val.trim().length()==0)
       		errors.add("parameterValue["+parm+"]", new ActionMessage("errors.required", ""));
       }
       
       return errors;
}
 
Example 15
Project: bibliometrics   File: AskOrcidServlet.java   View source code 6 votes vote down vote up
public void doGetPost(MCRServletJob job) throws Exception {
  //prepare request
    HttpServletRequest req = job.getRequest();
    
    //prepare Connection
    OrcidConnector connection = new OrcidConnector();
    
    //get parameter from URL
    String orcid = getParameter(req, "id");
    
    //send request to API
    MCRContent orcidExport = connection.getPublicationsByOrcid(orcid);
    
   //transform in MODS
    MCRXSL2XMLTransformer transformer = new MCRXSL2XMLTransformer("xsl/Orcid2mods.xsl");
    MCRContent mods = transformer.transform(orcidExport);
    
    //save results
    mods.sendTo(new File(resultsDir,"OrcidProfile_mods_OrcID" + orcid + ".xml"));
    
    connection.close();
}
 
Example 16
Project: lemon   File: DictSchemaController.java   View source code 6 votes vote down vote up
@RequestMapping("dict-schema-export")
public void export(@ModelAttribute Page page,
        @RequestParam Map<String, Object> parameterMap,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    String tenantId = tenantHolder.getTenantId();
    List<PropertyFilter> propertyFilters = PropertyFilter
            .buildFromMap(parameterMap);
    propertyFilters.add(new PropertyFilter("EQS_tenantId", tenantId));
    page = dictSchemaManager.pagedQuery(page, propertyFilters);

    List<DictSchema> dictSchemas = (List<DictSchema>) page.getResult();

    TableModel tableModel = new TableModel();
    tableModel.setName("dict info");
    tableModel.addHeaders("id", "name", "stringValue", "description");
    tableModel.setData(dictSchemas);
    exportor.export(request, response, tableModel);
}
 
Example 17
Project: springcloudproject   File: MyFilter.java   View source code 6 votes vote down vote up
@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    HttpServletRequest request = ctx.getRequest();
    log.info(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));
    Object accessToken = request.getParameter("token");
    if (accessToken == null) {
        log.warn("token is empty");
        ctx.setSendZuulResponse(false);
        ctx.setResponseStatusCode(401);
        try {
            ctx.getResponse().getWriter().write("token is empty");
        } catch (Exception e) {
        }

        return null;
    }
    log.info("ok");
    return null;
}
 
Example 18
Project: grpc-proxy   File: LegacyHttpServer.java   View source code 6 votes vote down vote up
private LegacyHttpServer(int port, int threads) {
  this.server = new Server(new QueuedThreadPool(threads));
  server.setHandler(
      new AbstractHandler() {
        @Override
        public void handle(
            String target,
            Request baseRequest,
            HttpServletRequest request,
            HttpServletResponse response)
            throws IOException {
          final String method = baseRequest.getParameter("method");
          if ("helloworld.Greeter/SayHello".equals(method)) {
            baseRequest.setHandled(true);
            sayHello(baseRequest, response);
          }
        }
      });

  final ServerConnector connector = new ServerConnector(server);
  connector.setPort(port);
  server.addConnector(connector);
}
 
Example 19
Project: SpringTutorial   File: HelloWorldController.java   View source code 6 votes vote down vote up
@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
 HttpServletResponse response) throws Exception {

		ModelAndView model = new ModelAndView("HelloWorldPage");//JSP NAME
		model.addObject("msg", "Welcome beginner!");

		return model;
//http://localhost:8080/SpringMVC/welcome.sf is requested.
//
// URL has �.htm� extension, so it will redirect to �DispatcherServlet� 
// and send request to the default BeanNameUrlHandlerMapping.
//
// BeanNameUrlHandlerMapping returns HelloWorldController to the DispatcherServlet.
//
// DispatcherServlet forward requests to the HelloWorldController.
//
// HelloWorldController processes it and returns a ModelAndView object named �HelloWorldPage�.
//
// DispatcherServlet receives the ModelAndView and calls the viewResolver to process it.
//
// viewResolver returns the �/WEB-INF/pages/HelloWorldPage.jsp� back to the DispatcherServlet.
//
// DispatcherServlet return the �HelloWorldPage.jsp� back to user.		
	}
 
Example 20
Project: angular-spring-starter   File: TokenHelper.java   View source code 6 votes vote down vote up
public String getToken( HttpServletRequest request ) {
    /**
     *  Getting the token from Cookie store
     */
    Cookie authCookie = getCookieValueByName( request, AUTH_COOKIE );
    if ( authCookie != null ) {
        return authCookie.getValue();
    }
    /**
     *  Getting the token from Authentication header
     *  e.g Bearer your_token
     */
    String authHeader = request.getHeader(AUTH_HEADER);
    if ( authHeader != null && authHeader.startsWith("Bearer ")) {
        return authHeader.substring(7);
    }

    return null;
}
 
Example 21
Project: convertigo-engine   File: Delete.java   View source code 6 votes vote down vote up
protected void getServiceResult(HttpServletRequest request, Document document) throws Exception {
	String username = request.getParameter("username");
	
	Element root = document.getDocumentElement();
	Element response = document.createElement("response");

	try {
		Engine.authenticatedSessionManager.deleteUser(username);
		response.setAttribute("state", "success");
		response.setAttribute("message","User '" + username + "' have been successfully deleted!");
	} catch (Exception e) {
		Engine.logAdmin.error("Error during deleting the user!\n" + e.getMessage());
		
		response.setAttribute("state", "error");
		response.setAttribute("message","Error during deleting the user!\n" + e.getMessage());
	}
	root.appendChild(response);		
}
 
Example 22
Project: airsonic   File: HLSController.java   View source code 6 votes vote down vote up
private String createStreamUrl(HttpServletRequest request, Player player, int id, int offset, int duration, Pair<Integer, Dimension> bitRate) {
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(getContextPath(request) + "ext/stream/stream.ts");
    builder.queryParam("id", id);
    builder.queryParam("hls", "true");
    builder.queryParam("timeOffset", offset);
    builder.queryParam("player", player.getId());
    builder.queryParam("duration", duration);
    if (bitRate != null) {
        builder.queryParam("maxBitRate", bitRate.getFirst());
        Dimension dimension = bitRate.getSecond();
        if (dimension != null) {
            builder.queryParam("size", dimension.width);
            builder.queryParam("x", dimension.height);
        }
    }
    jwtSecurityService.addJWTToken(builder);
    return builder.toUriString();
}
 
Example 23
Project: zhkuas_ssm_maven   File: PublicCourseDataController.java   View source code 6 votes vote down vote up
@RequestMapping("/public")
public String show(HttpServletRequest request){
	List<Term> terms = termService.getAvailabelTerms();
	Term currentTerm  = null;
	for(Term term:terms){
		if(term.isCurrent()){
			currentTerm = term;
			request.setAttribute("currentTerm", currentTerm);
			break;
		}	
	}
	request.setAttribute("terms", terms);
	int compusId = 1;
	CampusArea currentCampus = campusAreaService.getCampusAreaById(compusId );
	List<CampusArea> campuses = campusAreaService.getCampusAreas();
	request.setAttribute("campuses", campuses);
	request.setAttribute("currentCampus", currentCampus);
	List<PublicCourse> publicCourses = publicCourseService.getPublicCoursesByTermNoAndCampusId(currentTerm.getNo(), currentCampus.getId());
	request.setAttribute("publicCourses", publicCourses);
	return "admin_public_course";
}
 
Example 24
Project: cas-fortress-example   File: FortressDecisionVoter.java   View source code 6 votes vote down vote up
private String getFilterUrl(HttpServletRequest request) {
  String commonString = null;
  for (String url : permissionModels) {
    LOG.trace("url : {}", url);
    if (commonString == null) {
      LOG.trace("request uri contains url : {}",
          request.getRequestURI().contains(url));
      if (request.getRequestURI().contains(url)) {
        String registeredUrl = getApplicationBasePath() + url;
        LOG.trace("requested url : {}", request.getRequestURL().toString());
        LOG.trace("registered url : {}", registeredUrl);
        commonString = StringUtils
            .getCommonPrefix(new String[] {request.getRequestURL().toString(), registeredUrl});
      }
    }
  }
  return commonString;
}
 
Example 25
Project: zxbangban   File: CustomerController.java   View source code 5 votes vote down vote up
/**
 * 顾客预约托管
 * @param name   顾客姓名
 * @param tel   顾客手机号
 * @param location  工程所在地
 * @param model   预约结果信息
 * @return 预约成功页面
 */
@RequestMapping(value = "/free-appointment",method = RequestMethod.POST)
public String freeAppointment(HttpServletRequest httpServletRequest, @RequestParam("name") String name, @RequestParam("tel") String tel,
                              @RequestParam("location") String location,Model model, SessionStatus sessionStatus){
    String workerId = (String) httpServletRequest.getSession().getAttribute("workerid");
    Customer customer = new Customer(name,tel,location,new Date(),"");
    if(workerId != null){
        WorkerInfo workerInfo = workerInfoService.queryWorkerByWorkerId(Long.parseLong(workerId));
        customer.setNotes("预约[工号:" + workerId + ";姓名:"+workerInfo.getName() +
               "]");
    }

    try{
        int result = customerService.newCustomer(customer);
        model.addAttribute("msg","预约成功!");
        aliyunMNService.SMSNotification(3,tel);
        UserInfo userInfo = userInfoService.queryByRoleId(8);
        String telphone = userInfo.getTelphone();
        aliyunMNService.SMSNotification(4,telphone);
        sessionStatus.setComplete();
        return "appointment/appointmentsuccess";
    }catch (Exception e){
        model.addAttribute("msg","预约失败!");
        return "appointment/appointmentsuccess";
    }

}
 
Example 26
Project: unitimes   File: AddNonUnivLocationAction.java   View source code 5 votes vote down vote up
/**
 * 
 * @param request
 * @param nonUnivLocationForm 
 * @throws Exception
 */
private void setDepts(HttpServletRequest request, Set<Department> departments) throws Exception {
	List<LabelValueBean> list = new ArrayList<LabelValueBean>();
	for (Department d: departments) {
		String code = d.getDeptCode().trim();
		String abbv = d.getName().trim();
		list.add(new LabelValueBean(code + " - " + abbv, code)); 
	}
	
	request.setAttribute(Department.DEPT_ATTR_NAME, list);
}
 
Example 27
Project: ssm-web   File: PageController.java   View source code 5 votes vote down vote up
@RequestMapping("/home.do")
public String homeHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws ServletException {

    SessionUser sessionUser = (SessionUser) this.getSessionObject(request, SysConstants.SESSION_USER_KEY);
    model.put("sessionUser", sessionUser);
    Map<String, Object> param = new HashMap<String, Object>();

    List<SeRole> seRoleList = sessionUser.getSeRoleList();

    if (seRoleList != null && seRoleList.size() > 0) {
        param.put("seRoleList", seRoleList);
        List<SeMenu> listUserMenu = seRolemenuService.listSeMenuByUsercode(param);

        if (listUserMenu != null && listUserMenu.size() > 0) {
            // 拼接菜单
            SeMenu rootSeMenu = listUserMenu.remove(0);
            MenuTree tree = new MenuTree(rootSeMenu,listUserMenu);
            model.put("listUserMenu", tree.buildTree());
        }

        for(SeMenu seMenu : listUserMenu){
            if(!Utils.strIsNull(seMenu.getSourceurl())){
                model.put("firstMenu", seMenu);
                break;
            }
        }

    }
    return "page/home";
}
 
Example 28
Project: netty-socketio-demo   File: WebUtils.java   View source code 5 votes vote down vote up
/**
 * 是否是微信内置浏览器
 * 
 * @param request
 * @return
 */
public static boolean isWeixinRequest(HttpServletRequest request) {
    if (request == null) {
        return false;
    }
    String agent = request.getHeader(USER_AGENT);
    return agent != null && agent.toLowerCase().contains(WEIXIN_REQUEST_MARK);
}
 
Example 29
Project: Pet-Supply-Store   File: DataBaseActionServlet.java   View source code 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected void doGetInternal(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException, LoadBalancerTimeoutException {

	if (request.getParameter("confirm") != null) {

		String[] infos = extractOrderInformation(request);
		if (infos.length == 0) {
			redirect("/database", response);
		} else {
			destroySessionBlob(getSessionBlob(request), response);
			Response resp = ServiceLoadBalancer.loadBalanceRESTOperation(Service.PERSISTENCE, "generatedb",
					String.class,
					client -> client.getService().path(client.getApplicationURI()).path(client.getEndpointURI())
							.queryParam(PARAMETERS[0], infos[0]).queryParam(PARAMETERS[1], infos[1])
							.queryParam(PARAMETERS[2], infos[2]).queryParam(PARAMETERS[3], infos[3])
							.request(MediaType.TEXT_PLAIN).get());
			if (resp.getStatus() == 200) {
				LOG.info("DB is re-generating.");
			}

			// Regenerate images
			List<Integer> status = LoadBalancedImageOperations.regenerateImages();
			status.stream().filter(r -> r != 200).forEach(
					r -> LOG.warn("An image provider service responded with " + r + " when regenerating images."));
			// Retrain recommender
			List<Response> recResp = ServiceLoadBalancer.multicastRESTOperation(Service.RECOMMENDER, "train",
					String.class,
					client -> client.getEndpointTarget().path("async").request(MediaType.TEXT_PLAIN).get());
			recResp.stream().filter(r -> r.getStatus() != 200).forEach(
					r -> LOG.warn("A recommender service responded with " + r.getStatus() + " when retraining."));
			redirect("/status", response);
		}

	} else {
		redirect("/", response);
	}
}
 
Example 30
Project: alfresco-remote-api   File: KerberosAuthenticationFilter.java   View source code 5 votes vote down vote up
@Override
protected void onValidateFailed(ServletContext sc, HttpServletRequest req, HttpServletResponse res, HttpSession session, WebCredentials credentials)
    throws IOException
{
    super.onValidateFailed(sc, req, res, session, credentials);
    // Restart the login challenge process if validation fails
    restartLoginChallenge(sc, req, res);
}
 
Example 31
Project: iunet-blog   File: WebUtil.java   View source code 5 votes vote down vote up
/**
 * 检测是否是移动设备访问
 * @param userAgent
 * @return
 */
public static boolean check(HttpServletRequest request) {
	String userAgent = request.getHeader("User-Agent").toLowerCase();
	if (null == userAgent) {
		userAgent = "";
	}
	Matcher matcherPhone = phonePat.matcher(userAgent);
	Matcher matcherTable = tablePat.matcher(userAgent);
	if (matcherPhone.find() || matcherTable.find()) {
		return true;
	} else {
		return false;
	}
}
 
Example 32
Project: batch-scheduler   File: ArgumentController.java   View source code 5 votes vote down vote up
private ArgumentDefineEntity parse(HttpServletRequest request) {
    ArgumentDefineEntity argumentDefineEntity = new ArgumentDefineEntity();
    argumentDefineEntity.setArgId(request.getParameter("arg_id"));
    argumentDefineEntity.setArgValue(request.getParameter("arg_value"));
    argumentDefineEntity.setArgType(request.getParameter("arg_type"));
    argumentDefineEntity.setArgDesc(request.getParameter("arg_desc"));
    argumentDefineEntity.setDomainId(request.getParameter("domain_id"));
    argumentDefineEntity.setBindAsOfDate(request.getParameter("bind_as_of_date"));
    String userId = JwtService.getConnUser(request).getUserId();
    argumentDefineEntity.setCreateUser(userId);
    argumentDefineEntity.setModifyUser(userId);
    return argumentDefineEntity;
}
 
Example 33
Project: sns-todo   File: CustomAccessDeniedHandler.java   View source code 5 votes vote down vote up
/**
 * https://docs.spring.io/spring-security/site/docs/4.2.3.RELEASE/reference/htmlsingle/#csrf-timeouts
 * https://stackoverflow.com/questions/32446903/what-is-the-best-way-to-handle-invalid-csrf-token-found-in-the-request-when-sess
 */
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
    LOGGER.warn("{},{},{}", Flag.BizLogFlag.WARN_CHECK, RequestHolder.getLastAccessUri(), accessDeniedException.getClass().getCanonicalName());
    if (accessDeniedException instanceof MissingCsrfTokenException
            || accessDeniedException instanceof InvalidCsrfTokenException) {
        response.sendRedirect("/");
    }
}
 
Example 34
Project: TeamNote   File: CustomSimpleUrlAuthenticationSuccessHandler.java   View source code 5 votes vote down vote up
/**
 * Invokes the configured {@code RedirectStrategy} with the URL returned by the
 * {@code determineTargetUrl} method.
 * <p>
 * The redirect will not be performed if the response has already been committed.
 */
private void handle(HttpServletRequest request, HttpServletResponse response,
                      Authentication authentication) throws IOException, ServletException {
    String targetUrl = determineTargetUrl(authentication);

    if (response.isCommitted()) {
        logger.debug("Response has already been committed. Unable to redirect to "
                + targetUrl);
        return;
    }

    redirectStrategy.sendRedirect(request, response, targetUrl);
}
 
Example 35
Project: cas-5.1.0   File: SamlProfileSamlSubjectBuilder.java   View source code 5 votes vote down vote up
@Override
public Subject build(final AuthnRequest authnRequest, final HttpServletRequest request, 
                     final HttpServletResponse response,
                     final Assertion assertion, final SamlRegisteredService service,
                     final SamlRegisteredServiceServiceProviderMetadataFacade adaptor,
                     final String binding) throws SamlException {
    return buildSubject(request, response, authnRequest, assertion, service, adaptor, binding);
}
 
Example 36
Project: oscm   File: UserBean.java   View source code 5 votes vote down vote up
private String outcomeLoginException(HttpServletRequest httpRequest) {
    if (isServiceProvider()) {
        httpRequest.setAttribute(Constants.REQ_ATTR_ERROR_KEY,
                BaseBean.ERROR_INVALID_SAML_RESPONSE);
        return OUTCOME_PUBLIC_ERROR_PAGE;
    } else {
        httpRequest.setAttribute(Constants.REQ_ATTR_ERROR_KEY,
                BaseBean.ERROR_LOGIN);
        return OUTCOME_STAY_ON_PAGE;
    }
}
 
Example 37
Project: urule   File: FrameServletHandler.java   View source code 5 votes vote down vote up
public void createProject(HttpServletRequest req, HttpServletResponse resp) throws Exception {
	String projectName=req.getParameter("newProjectName");
	projectName=Utils.decodeURL(projectName);
	boolean classify = getClassify(req,resp);
	User user=EnvironmentUtils.getLoginUser(new RequestContext(req,resp));
	RepositoryFile projectFileInfo=repositoryService.createProject(projectName,user,classify);
	writeObjectToJson(resp, projectFileInfo);
}
 
Example 38
Project: opencps-v2   File: ApplicantManagement.java   View source code 5 votes vote down vote up
@PUT
@Path("/{id}")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED })
@ApiOperation(value = "Update a applicant", response = ApplicantModel.class)
@ApiResponses(value = {
		@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the applicant was updated", response = ApplicantModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class) })
public Response updateApplicant(@Context HttpServletRequest request, @Context HttpHeaders header,
		@Context Company company, @Context Locale locale, @Context User user,
		@Context ServiceContext serviceContext, @PathParam("id") long id,
		@BeanParam ApplicantInputUpdateModel input);
 
Example 39
Project: kettle_support_kettle8.0   File: QuartzController.java   View source code 5 votes vote down vote up
@RequestMapping(value = ACTION_PAUSE)
public String pause(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
	try {
		String jobKeys = request.getParameter("id");
		if (null != jobKeys) {
			service.iQuartzScheduleService.pause(jobKeys);
		}
	} catch (SchedulerException e) {
		e.printStackTrace();
	}
	return REDIRECT + VIEW_WIDGET + VIEW_QUARTZ + ACTION_LIST;
}
 
Example 40
Project: cas-5.1.0   File: TerminateSessionAction.java   View source code 5 votes vote down vote up
/**
 * Terminates the CAS SSO session by destroying the TGT (if any) and removing cookies related to the SSO session.
 *
 * @param context Request context.
 * @return "success"
 */
public Event terminate(final RequestContext context) {
    // in login's webflow : we can get the value from context as it has already been stored
    try {
        final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
        final HttpServletResponse response = WebUtils.getHttpServletResponse(context);

        String tgtId = WebUtils.getTicketGrantingTicketId(context);
        // for logout, we need to get the cookie's value
        if (tgtId == null) {
            tgtId = this.ticketGrantingTicketCookieGenerator.retrieveCookieValue(request);
        }
        if (tgtId != null) {
            LOGGER.debug("Destroying SSO session linked to ticket-granting ticket [{}]", tgtId);
            final List<LogoutRequest> logoutRequests = this.centralAuthenticationService.destroyTicketGrantingTicket(tgtId);
            WebUtils.putLogoutRequests(context, logoutRequests);
        }
        LOGGER.debug("Removing CAS cookies");
        this.ticketGrantingTicketCookieGenerator.removeCookie(response);
        this.warnCookieGenerator.removeCookie(response);

        destroyApplicationSession(request, response);
        LOGGER.debug("Terminated all CAS sessions successfully.");
        return this.eventFactorySupport.success(this);
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}