Java Code Examples for javax.servlet.http.HttpServletRequest

The following examples show how to use javax.servlet.http.HttpServletRequest. These examples are extracted from open source projects. 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 Project: keycloak   Author: keycloak   File: ProductServiceAccountServlet.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    String reqUri = req.getRequestURI();
    if (reqUri.endsWith("/login")) {
        serviceAccountLogin(req);
    } else if (reqUri.endsWith("/logout")){
        logout(req);
    }

    // Don't load products if some error happened during login,refresh or logout
    if (req.getAttribute(ERROR) == null) {
        loadProducts(req);
    }

    req.getRequestDispatcher("/WEB-INF/page.jsp").forward(req, resp);
}
 
Example #2
Source Project: pentaho-kettle   Author: pentaho   File: StartExecutionTransServletTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@PrepareForTest( { Encode.class } )
public void testStartExecutionTransServletEscapesHtmlWhenTransNotFound() throws ServletException, IOException {
  HttpServletRequest mockHttpServletRequest = mock( HttpServletRequest.class );
  HttpServletResponse mockHttpServletResponse = mock( HttpServletResponse.class );

  StringWriter out = new StringWriter();
  PrintWriter printWriter = new PrintWriter( out );

  PowerMockito.spy( Encode.class );
  when( mockHttpServletRequest.getContextPath() ).thenReturn( StartExecutionTransServlet.CONTEXT_PATH );
  when( mockHttpServletRequest.getParameter( anyString() ) ).thenReturn( ServletTestUtils.BAD_STRING_TO_TEST );
  when( mockHttpServletResponse.getWriter() ).thenReturn( printWriter );

  startExecutionTransServlet.doGet( mockHttpServletRequest, mockHttpServletResponse );
  assertFalse( ServletTestUtils.hasBadText( ServletTestUtils.getInsideOfTag( "H1", out.toString() ) ) );

  PowerMockito.verifyStatic( atLeastOnce() );
  Encode.forHtml( anyString() );
}
 
Example #3
Source Project: microcks   Author: microcks   File: ParameterConstraintUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Validate that a parameter constraint it respected or violated. Return a message if violated.
 * @param request HttpServlet request holding parameters to validate
 * @param constraint Constraint to apply to one request parameter.
 * @return A string representing constraint violation if any. null otherwise.
 */
public static String validateConstraint(HttpServletRequest request, ParameterConstraint constraint) {
   String value = null;
   if (ParameterLocation.header == constraint.getIn()) {
      value = request.getHeader(constraint.getName());
   } else if (ParameterLocation.query == constraint.getIn()) {
      value = request.getParameter(constraint.getName());
   }

   if (value != null) {
      if (constraint.getMustMatchRegexp() != null) {
         if (!Pattern.matches(constraint.getMustMatchRegexp(), value)) {
            return "Parameter " + constraint.getName() +  " should match " + constraint.getMustMatchRegexp();
         }
      }
   } else  {
      if (constraint.isRequired()) {
         return "Parameter " + constraint.getName() +  " is required";
      }
   }
   return null;
}
 
Example #4
Source Project: ee8-sandbox   Author: hantsy   File: TestServlet.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String webName = null;
    if (request.getUserPrincipal() != null) {
        webName = request.getUserPrincipal().getName();
    }
    
    response.getWriter().write(
            "<html><body> This is a servlet <br><br>\n" +
    
                "web username: " + webName + "<br><br>\n" +
                        
                "web user has role \"foo\": " + request.isUserInRole("foo") + "<br>\n" +
                "web user has role \"bar\": " + request.isUserInRole("bar") + "<br>\n" +
                "web user has role \"kaz\": " + request.isUserInRole("kaz") + "<br><br>\n" + 

                    
                "<form method=\"POST\">" +
                    "<input type=\"hidden\" name=\"logout\" value=\"true\"  >" +
                    "<input type=\"submit\" value=\"Logout\">" +
                "</form>" +
            "</body></html>");
}
 
Example #5
Source Project: jeecg   Author: zhangdaiscott   File: TsBlackListController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 删除黑名单
 * 
 * @return
 */
@RequestMapping(params = "doDel")
@ResponseBody
public AjaxJson doDel(TsBlackListEntity tsBlackList, HttpServletRequest request) {
	String message = null;
	AjaxJson j = new AjaxJson();
	tsBlackList = systemService.getEntity(TsBlackListEntity.class, tsBlackList.getId());
	message = "黑名单删除成功";
	try{
		tsBlackListService.delete(tsBlackList);
		systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
	}catch(Exception e){
		e.printStackTrace();
		message = "黑名单删除失败";
		throw new BusinessException(e.getMessage());
	}
	j.setMsg(message);
	return j;
}
 
Example #6
Source Project: Benchmark   Author: OWASP   File: BenchmarkTest02664.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static String doSomething(HttpServletRequest request, String param) throws ServletException, IOException {

		String bar;
		String guess = "ABC";
		char switchTarget = guess.charAt(1); // condition 'B', which is safe
		
		// Simple case statement that assigns param to bar on conditions 'A', 'C', or 'D'
		switch (switchTarget) {
		  case 'A':
		        bar = param;
		        break;
		  case 'B': 
		        bar = "bob";
		        break;
		  case 'C':
		  case 'D':        
		        bar = param;
		        break;
		  default:
		        bar = "bob's your uncle";
		        break;
		}
	
		return bar;	
	}
 
Example #7
Source Project: openprodoc   Author: JHierrot   File: DependTree.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
private String GenDependTree(HttpServletRequest Req) 
{
StringBuilder DepTree=new StringBuilder(5000);
DepTree.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n").append("<tree id=\"0\">");
DriverGeneric PDSession=getSessOPD(Req);
String IdVersProdSec=Req.getParameter("IdVers");
try {
PDFolders F=new PDFolders(PDSession);
F.LoadFull(IdVersProdSec);
DepTree.append("<item id=\"").append(F.getPDId()).append("\" text=\"").append(F.getTitle()).append("\" open=\"1\">");
TreeSet<String> ListDep = F.getRecSum().getAttr(DEPENDENCIES).getValuesList();
for (Iterator<String> iterator = ListDep.iterator(); iterator.hasNext();)
    {
    String Rel = iterator.next();
    DepTree.append(SubDependTree(PDSession, Rel));
    }
DepTree.append("</item>");
} catch (Exception Ex)
    {
    Ex.printStackTrace();
    }
DepTree.append("</tree>");
return(DepTree.toString());
}
 
Example #8
Source Project: Benchmark   Author: OWASP   File: BenchmarkTest02080.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static String doSomething(HttpServletRequest request, String param) throws ServletException, IOException {

		String bar = "alsosafe";
		if (param != null) {
			java.util.List<String> valuesList = new java.util.ArrayList<String>( );
			valuesList.add("safe");
			valuesList.add( param );
			valuesList.add( "moresafe" );
			
			valuesList.remove(0); // remove the 1st safe value
			
			bar = valuesList.get(1); // get the last 'safe' value
		}
	
		return bar;	
	}
 
Example #9
Source Project: airsonic-advanced   Author: airsonic-advanced   File: EditTagsController.java    License: GNU General Public License v3.0 6 votes vote down vote up
@GetMapping
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {

    int id = ServletRequestUtils.getRequiredIntParameter(request, "id");
    MediaFile dir = mediaFileService.getMediaFile(id);
    List<MediaFile> files = mediaFileService.getChildrenOf(dir, true, false, true, false);

    Map<String, Object> map = new HashMap<String, Object>();
    if (!files.isEmpty()) {
        map.put("defaultArtist", files.get(0).getArtist());
        map.put("defaultAlbum", files.get(0).getAlbumName());
        map.put("defaultYear", files.get(0).getYear());
        map.put("defaultGenre", files.get(0).getGenre());
    }
    map.put("allGenres", JaudiotaggerParser.getID3V1Genres());

    List<Song> songs = new ArrayList<Song>();
    for (int i = 0; i < files.size(); i++) {
        songs.add(createSong(files.get(i), i));
    }
    map.put("id", id);
    map.put("songs", songs);

    return new ModelAndView("editTags","model",map);
}
 
Example #10
Source Project: dddsample-core   Author: citerus   File: CargoTrackingController.java    License: MIT License 6 votes vote down vote up
@RequestMapping(method = RequestMethod.POST)
protected String onSubmit(final HttpServletRequest request,
                                                         final TrackCommand command,
                                                         final Map<String, Object> model,
                                                         final BindingResult bindingResult) {
    new TrackCommandValidator().validate(command, bindingResult);

    final TrackingId trackingId = new TrackingId(command.getTrackingId());
    final Cargo cargo = cargoRepository.find(trackingId);

    if (cargo != null) {
        final Locale locale = RequestContextUtils.getLocale(request);
        final List<HandlingEvent> handlingEvents = handlingEventRepository.lookupHandlingHistoryOfCargo(trackingId).distinctEventsByCompletionTime();
        model.put("cargo", new CargoTrackingViewAdapter(cargo, messageSource, locale, handlingEvents));
    } else {
        bindingResult.rejectValue("trackingId", "cargo.unknown_id", new Object[]{command.getTrackingId()}, "Unknown tracking id");
    }
    return "track";
}
 
Example #11
Source Project: framework   Author: gyoomi   File: CsrfFilter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 检查CSRF Token
 *
 * @param req   ServletRequest
 */
private boolean checkCsrfToken(ServletRequest req) {
    AdamProperties adamProperties = CHERRY.SPRING_CONTEXT.getBean(AdamProperties.class);
    boolean isValid = false;

    String csrf = ((HttpServletRequest) req).getHeader(adamProperties.getCsrf().getHeaderName());
    if (StringUtils.isBlank(csrf)) {
        csrf = req.getParameter(adamProperties.getCsrf().getRequestName());
    }

    if (StringUtils.isNotBlank(csrf)) {
        Boolean hasKey = CHERRY.SPRING_CONTEXT.getBean(StringRedisTemplate.class).hasKey(CHERRY.REDIS_KEY_CSRF + csrf);
        isValid = hasKey == null ? false : hasKey;
    }

    return isValid;
}
 
Example #12
Source Project: cruise-control   Author: linkedin   File: Purgatory.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Add request to the purgatory and return the {@link ReviewResult} for the request that has been added to
 * the purgatory.
 *
 * @param request Http Servlet Request to add to the purgatory.
 * @param parameters Request parameters.
 * @param <P> Type corresponding to the request parameters.
 * @return The result showing the {@link ReviewResult} for the request that has been added to the purgatory.
 */
private synchronized <P extends CruiseControlParameters> ReviewResult addRequest(HttpServletRequest request,
                                                                                 P parameters) {
  if (!request.getMethod().equals(POST_METHOD)) {
    throw new IllegalArgumentException(String.format("Purgatory can only contain POST request (Attempted to add: %s).",
                                                     httpServletRequestToString(request)));
  }
  RequestInfo requestInfo = new RequestInfo(request, parameters);
  _requestInfoById.put(_requestId, requestInfo);

  Map<Integer, RequestInfo> requestInfoById = new HashMap<>();
  requestInfoById.put(_requestId, requestInfo);
  Set<Integer> filteredRequestIds = new HashSet<>();
  filteredRequestIds.add(_requestId);

  ReviewResult result = new ReviewResult(requestInfoById, filteredRequestIds, _config);
  _requestId++;
  return result;
}
 
Example #13
Source Project: ZTuoExchange_framework   Author: homeyanmi   File: SessionInterceptor.java    License: MIT License 5 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


    BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
    AdminService adminService = (AdminService) factory.getBean("adminService");
    System.out.println(request.getContextPath());
    Subject currentUser = SecurityUtils.getSubject();

    //判断用户是通过记住我功能自动登录,此时session失效
    if(!currentUser.isAuthenticated() && currentUser.isRemembered()){
        try {
            Admin admin = adminService.findByUsername(currentUser.getPrincipals().toString());
            //对密码进行加密后验证
            UsernamePasswordToken token = new UsernamePasswordToken(admin.getUsername(), admin.getPassword(),currentUser.isRemembered());
            //把当前用户放入session
            currentUser.login(token);
            Session session = currentUser.getSession();
            session.setAttribute(SysConstant.SESSION_ADMIN,admin);
            //设置会话的过期时间--ms,默认是30分钟,设置负数表示永不过期
            session.setTimeout(30*60*1000L);
        }catch (Exception e){
            //自动登录失败,跳转到登录页面
            //response.sendRedirect(request.getContextPath()+"/system/employee/sign/in");
            ajaxReturn(response, 4000, "unauthorized");
            return false;
        }
        if(!currentUser.isAuthenticated()){
            //自动登录失败,跳转到登录页面
            ajaxReturn(response, 4000, "unauthorized");
            return false;
        }
    }
    return true;
}
 
Example #14
Source Project: lucene-solr   Author: apache   File: SolrRequestParserTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAddHttpRequestToContext() throws Exception {
  HttpServletRequest request = getMock("/solr/select", null, -1);
  when(request.getMethod()).thenReturn("GET");
  when(request.getQueryString()).thenReturn("q=title:solr");
  Map<String, String> headers = new HashMap<>();
  headers.put("X-Forwarded-For", "10.0.0.1");
  when(request.getHeaderNames()).thenReturn(new Vector<>(headers.keySet()).elements());
  for(Map.Entry<String,String> entry:headers.entrySet()) {
    Vector<String> v = new Vector<>();
    v.add(entry.getValue());
    when(request.getHeaders(entry.getKey())).thenReturn(v.elements());
  }

  SolrRequestParsers parsers = new SolrRequestParsers(h.getCore().getSolrConfig());
  assertFalse(parsers.isAddRequestHeadersToContext());
  SolrQueryRequest solrReq = parsers.parse(h.getCore(), "/select", request);
  assertFalse(solrReq.getContext().containsKey("httpRequest"));
  
  parsers.setAddRequestHeadersToContext(true);
  solrReq = parsers.parse(h.getCore(), "/select", request);
  assertEquals(request, solrReq.getContext().get("httpRequest"));
  assertEquals("10.0.0.1", ((HttpServletRequest)solrReq.getContext().get("httpRequest")).getHeaders("X-Forwarded-For").nextElement());
  
}
 
Example #15
Source Project: kk-anti-reptile   Author: kekingcn   File: ValidateFormServlet.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    if (!initialized.get()) {
        init(request.getServletContext());
        initialized.set(true);
    }
    String result = validateFormService.validate(request);
    CrosUtil.setCrosHeader(response);
    response.setContentType("application/json;charset=utf-8");
    response.setStatus(200);
    response.getWriter().write(result);
    response.getWriter().close();
    return;
}
 
Example #16
Source Project: jeewx-boot   Author: zhangdaiscott   File: CmsSiteController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 跳转到添加页面
 * @return
 */
@RequestMapping(value = "/toAdd",method ={RequestMethod.GET, RequestMethod.POST})
public void toAddDialog(HttpServletRequest request,HttpServletResponse response,ModelMap model)throws Exception{
	 VelocityContext velocityContext = new VelocityContext();
	 String viewName = "cms/back/cmsSite-add.vm";
	//update-begin-author:taoYan date:20181018 for:cms默认appid设置---
	 String jwid =  (String) request.getSession().getAttribute("jwid");
	 String defaultJwid = CmsProperties.defaultJwid;
	 if(defaultJwid.equals(jwid)){
		 velocityContext.put("isDefaultJwid",1);
	 }
	//update-end-author:taoYan date:20181018 for:cms默认appid设置---
	 velocityContext.put("templateStyle", CmsSiteTemplateEnum.getAllEnumData());
	 ViewVelocity.view(request,response,viewName,velocityContext);
}
 
Example #17
Source Project: o2oa   Author: o2oa   File: ActionGet.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected ActionResult<Wo> execute( HttpServletRequest request, EffectivePerson effectivePerson, String id ) throws Exception {
	ActionResult<Wo> result = new ActionResult<>();
	Boolean check = true;
	
	if( check ){
		if( id == null || id.isEmpty() ){
			check = false;
			Exception exception = new ExceptionForumInfoIdEmpty();
			result.error( exception );
		}
	}
	
	if( check ){
		String cacheKey = "forum#" + id;
		Element element = cache.get( cacheKey );
		if ((null != element) && (null != element.getObjectValue())) {
			ActionResult<Wo> result_cache = (ActionResult<Wo>) element.getObjectValue();
			result.setData( result_cache.getData() );
			result.setCount( 1L);
		} else {
			//继续进行数据查询
			result = getForumQueryResult( id, request, effectivePerson );
			cache.put(new Element(cacheKey, result ));
		}
	}
	return result;
}
 
Example #18
Source Project: spring-security-oauth   Author: Baeldung   File: CustomPreZuulFilter.java    License: MIT License 5 votes vote down vote up
@Override
public Object run() {
    final RequestContext ctx = RequestContext.getCurrentContext();
    logger.info("in zuul filter " + ctx.getRequest().getRequestURI());
    byte[] encoded;
    try {
        encoded = Base64.getEncoder().encode("fooClientIdPassword:secret".getBytes("UTF-8"));
        ctx.addZuulRequestHeader("Authorization", "Basic " + new String(encoded));
        logger.info("pre filter");
        logger.info(ctx.getRequest().getHeader("Authorization"));

        final HttpServletRequest req = ctx.getRequest();

        final String refreshToken = extractRefreshToken(req);
        if (refreshToken != null) {
            final Map<String, String[]> param = new HashMap<String, String[]>();
            param.put("refresh_token", new String[] { refreshToken });
            param.put("grant_type", new String[] { "refresh_token" });

            ctx.setRequest(new CustomHttpServletRequest(req, param));
        }

    } catch (final UnsupportedEncodingException e) {
        logger.error("Error occured in pre filter", e);
    }

    //

    return null;
}
 
Example #19
Source Project: ruoyiplus   Author: kongshanxuelin   File: CommonController.java    License: MIT License 5 votes vote down vote up
public String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException
{
    final String agent = request.getHeader("USER-AGENT");
    String filename = fileName;
    if (agent.contains("MSIE"))
    {
        // IE浏览器
        filename = URLEncoder.encode(filename, "utf-8");
        filename = filename.replace("+", " ");
    }
    else if (agent.contains("Firefox"))
    {
        // 火狐浏览器
        filename = new String(fileName.getBytes(), "ISO8859-1");
    }
    else if (agent.contains("Chrome"))
    {
        // google浏览器
        filename = URLEncoder.encode(filename, "utf-8");
    }
    else
    {
        // 其它浏览器
        filename = URLEncoder.encode(filename, "utf-8");
    }
    return filename;
}
 
Example #20
@Override
public ActionForward execute(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    request.setAttribute("application.name", getStringFromDefaultBundle(getCandidacyNameKey()));
    request.setAttribute("mappingPath", mapping.getPath());
    request.setAttribute("isApplicationSubmissionPeriodValid", isApplicationSubmissionPeriodValid());
    request.setAttribute("application.information.link.default", getCandidacyInformationLinkDefaultLanguage());
    request.setAttribute("application.information.link.english", getCandidacyInformationLinkEnglish());
    setProcess(request);
    return super.execute(mapping, actionForm, request, response);
}
 
Example #21
Source Project: gerbil   Author: dice-group   File: MainController.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
private String getURLBase(HttpServletRequest request) {
    String scheme = request.getScheme();
    String serverName = request.getServerName();
    int serverPort = request.getServerPort();
    StringBuffer url = new StringBuffer();
    url.append(scheme).append("://").append(serverName);
    if ((serverPort != 80) && (serverPort != 443)) {
        url.append(":").append(serverPort);
    }
    url.append("/gerbil/");
    return url.toString();
}
 
Example #22
Source Project: Benchmark   Author: OWASP   File: BenchmarkTest02127.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static String doSomething(HttpServletRequest request, String param) throws ServletException, IOException {

		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"; 
	
		return bar;	
	}
 
Example #23
Source Project: gradle-in-action-source   Author: bmuschko   File: ToDoServlet.java    License: 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);
    RequestDispatcher dispatcher = request.getRequestDispatcher(view);
    dispatcher.forward(request, response);
}
 
Example #24
Source Project: io   Author: fujitsu-pio   File: FacadeResource.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param cookieAuthValue クッキー内の dc_cookieキーに指定された値
 * @param cookiePeer dc_cookie_peerクエリに指定された値
 * @param authzHeaderValue Authorization ヘッダ
 * @param host Host ヘッダ
 * @param uriInfo UriInfo
 * @param xDcUnitUser X-Dc-UnitUserヘッダ
 * @param httpServletRequest HttpServletRequest
 * @return CellResourceオブジェクトまたはResponseオブジェクト
 */
@Path("{path1}")
public final Object facade(
        @CookieParam(DC_COOKIE_KEY) final String cookieAuthValue,
        @QueryParam(COOKIE_PEER_QUERY_KEY) final String cookiePeer,
        @HeaderParam(HttpHeaders.AUTHORIZATION) final String authzHeaderValue,
        @HeaderParam(HttpHeaders.HOST) final String host,
        @HeaderParam(DcCoreUtils.HttpHeaders.X_DC_UNIT_USER) final String xDcUnitUser,
        @Context final UriInfo uriInfo,
        @Context HttpServletRequest httpServletRequest) {
    Cell cell = ModelFactory.cell(uriInfo);
    AccessContext ac = AccessContext.create(authzHeaderValue,
            uriInfo, cookiePeer, cookieAuthValue, cell, uriInfo.getBaseUri().toString(),
            host, xDcUnitUser);
    if (cell == null) {
        throw DcCoreException.Dav.CELL_NOT_FOUND;
    }

    long cellStatus = CellLockManager.getCellStatus(cell.getId());
    if (cellStatus == CellLockManager.CELL_STATUS_BULK_DELETION) {
        throw DcCoreException.Dav.CELL_NOT_FOUND;
    }

    CellLockManager.incrementReferenceCount(cell.getId());
    httpServletRequest.setAttribute("cellId", cell.getId());
    return new CellResource(ac);
}
 
Example #25
Source Project: opscenter   Author: appjishu   File: JWTAuthenticationFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, javax.servlet.FilterChain chain)
		throws IOException, ServletException {
	Authentication authentication = TokenAuthentication
               .getAuthentication((HttpServletRequest)request);
       SecurityContextHolder.getContext()
               .setAuthentication(authentication);
       chain.doFilter(request,response);
}
 
Example #26
Source Project: jhipster-ribbon-hystrix   Author: xetys   File: AccountResource.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * GET  /authenticate : check if the user is authenticated, and return its login.
 *
 * @param request the HTTP request
 * @return the login if the user is authenticated
 */
@RequestMapping(value = "/authenticate",
    method = RequestMethod.GET,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public String isAuthenticated(HttpServletRequest request) {
    log.debug("REST request to check if the current user is authenticated");
    return request.getRemoteUser();
}
 
Example #27
Source Project: carbon-identity   Author: wso2-attic   File: BasicAuthenticator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean canHandle(HttpServletRequest request) {
    String userName = request.getParameter(BasicAuthenticatorConstants.USER_NAME);
    String password = request.getParameter(BasicAuthenticatorConstants.PASSWORD);
    if (userName != null && password != null) {
        return true;
    }
    return false;
}
 
Example #28
Source Project: rice   Author: kuali   File: KualiForm.java    License: Educational Community License v2.0 5 votes vote down vote up
/**
 * @see org.apache.struts.action.ActionForm#reset(org.apache.struts.action.ActionMapping, javax.servlet.http.HttpServletRequest)
 */
@Override
public void reset(ActionMapping mapping, HttpServletRequest request) {
	super.reset(mapping, request);
	if (extraButtons != null) {
		extraButtons.clear();
	}
	//fieldNameToFocusOnAfterSubmit = "";
	clearDisplayedMessages();
}
 
Example #29
Source Project: olat   Author: huihoo   File: UserAuthenticationWebService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates and persists an authentication
 * 
 * @response.representation.qname {http://www.example.com}authenticationVO
 * @response.representation.mediaType application/xml, application/json
 * @response.representation.doc An authentication to save
 * @response.representation.example {@link org.olat.connectors.rest.support.vo.Examples#SAMPLE_AUTHVO}
 * @response.representation.200.qname {http://www.example.com}authenticationVO
 * @response.representation.200.mediaType application/xml, application/json
 * @response.representation.200.doc The saved authentication
 * @response.representation.200.example {@link org.olat.connectors.rest.support.vo.Examples#SAMPLE_AUTHVO}
 * @response.representation.401.doc The roles of the authenticated user are not sufficient
 * @response.representation.404.doc The identity not found
 * @param username
 *            The username of the user
 * @param authenticationVO
 *            The authentication object to persist
 * @param request
 *            The HTTP request
 * @return the saved authentication
 */
@PUT
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response create(@PathParam("username") final String username, final AuthenticationVO authenticationVO, @Context final HttpServletRequest request) {
    if (!RestSecurityHelper.isUserManager(request)) {
        return Response.serverError().status(Status.UNAUTHORIZED).build();
    }

    final BaseSecurity baseSecurity = getBaseSecurity();
    final Identity identity = baseSecurity.loadIdentityByKey(authenticationVO.getIdentityKey(), false);
    if (identity == null) {
        return Response.serverError().status(Status.NOT_FOUND).build();
    }
    if (!identity.getName().equals(username)) {
        return Response.serverError().status(Status.NOT_FOUND).build();
    }

    final String provider = authenticationVO.getProvider();
    final String authUsername = authenticationVO.getAuthUsername();
    final String credentials = authenticationVO.getCredential();
    final Authentication authentication = baseSecurity.createAndPersistAuthentication(identity, provider, authUsername, credentials);
    if (authentication == null) {
        return Response.serverError().status(Status.NOT_ACCEPTABLE).build();
    }
    log.info("Audit:New authentication created for " + authUsername + " with provider " + provider);
    final AuthenticationVO savedAuth = ObjectFactory.get(authentication, true);
    return Response.ok(savedAuth).build();
}
 
Example #30
Source Project: wingtips   Author: Nike-Inc   File: SampleResource.java    License: Apache License 2.0 5 votes vote down vote up
public void doGet(
    HttpServletRequest request, HttpServletResponse response
) throws ServletException, IOException {
    logger.info("Blocking forward endpoint hit");
    sleepThread(SLEEP_TIME_MILLIS);
    request.getServletContext().getRequestDispatcher(BLOCKING_PATH).forward(request, response);
}