javax.servlet.http.HttpServletRequest Java Examples

The following examples show how to use javax.servlet.http.HttpServletRequest. 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: ProductServiceAccountServlet.java    From keycloak with Apache License 2.0 7 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 File: TsBlackListController.java    From jeecg with 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 #3
Source File: DependTree.java    From openprodoc with 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 #4
Source File: Purgatory.java    From cruise-control with 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 #5
Source File: BenchmarkTest02080.java    From Benchmark with 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 #6
Source File: BenchmarkTest02664.java    From Benchmark with 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 File: StartExecutionTransServletTest.java    From pentaho-kettle with 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 #8
Source File: CsrfFilter.java    From framework with 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 #9
Source File: ParameterConstraintUtil.java    From microcks with 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 #10
Source File: CargoTrackingController.java    From dddsample-core with 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 File: EditTagsController.java    From airsonic-advanced with 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 #12
Source File: TestServlet.java    From ee8-sandbox with 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 #13
Source File: BenchmarkTest00711.java    From Benchmark with GNU General Public License v2.0 5 votes vote down vote up
@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
	
		String[] values = request.getParameterValues("BenchmarkTest00711");
		String param;
		if (values != null && values.length > 0)
		  param = values[0];
		else param = "";
		
		
		String bar = "";
		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(0); // get the param value
		}
		
		
response.setHeader("X-XSS-Protection", "0");
		Object[] obj = { "a", bar };
		java.io.PrintWriter out = response.getWriter();
		out.write("<!DOCTYPE html>\n<html>\n<body>\n<p>");
		out.format(java.util.Locale.US,"Formatted like: %1$s and %2$s.",obj);
	    out.write("\n</p>\n</body>\n</html>");
	}
 
Example #14
Source File: KualiFeedbackHandlerForm.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * @see org.kuali.rice.kns.web.struts.pojo.PojoForm#populate(javax.servlet.http.HttpServletRequest)
 */
@Override
public void populate(HttpServletRequest request) {
	super.populate(request);
	// ie explorer needs this.
	if(StringUtils.isNotBlank(request.getParameter(KRADConstants.CANCEL_METHOD + ".x")) &&
          StringUtils.isNotBlank(request.getParameter(KRADConstants.CANCEL_METHOD + ".y"))){
		    this.setCancel(true);
	}                
}
 
Example #15
Source File: ComboEntryPoint.java    From quartz-manager with Apache License 2.0 5 votes vote down vote up
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
		AuthenticationException authException) throws IOException, ServletException {

	if (RESTRequestMatcher.isRestRequest(request)
			|| WebsocketRequestMatcher.isWebsocketConnectionRequest(request))
		response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
	else
		super.commence(request, response, authException);
}
 
Example #16
Source File: HttpServletUtils.java    From yfshop with Apache License 2.0 5 votes vote down vote up
/**
 * 获取完整请求路径,带请求参数
 *
 * @param request
 * @return
 */
public static String getFullPath(HttpServletRequest request) {
    StringBuffer uri = request.getRequestURL();
    String url = uri.toString();
    // 获取所有请求,返回 Map 集合
    Map<String, String[]> map = request.getParameterMap();
    Set<Map.Entry<String, String[]>> entry = map.entrySet();
    Iterator<Map.Entry<String, String[]>> iterator = entry.iterator();

    // 遍历集合
    StringBuffer sb = new StringBuffer();
    while (iterator.hasNext()) {
        Map.Entry<String, String[]> item = iterator.next();
        //请求名
        String key = item.getKey();
        //请求值
        for (String value : item.getValue()) {
            // 拼接每个请求参数 key=value&
            sb.append(key + "=" + value + "&");
        }
    }

    String string = sb.toString();
    // 拼接 URL, URL?key=value&key=value& 并且去掉最后一个 &
    if (StringUtils.isNotBlank(string)) {
        url = url + "?" + string.substring(0, string.lastIndexOf("&"));
    }
    return url;
}
 
Example #17
Source File: BirtReportServlet.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private Map getTaskContext(String userId, Map reportParams, HttpServletRequest request, String resourcePath, Map userProfileAttrs) throws IOException {
	Map context = BirtUtility.getAppContext(request);

	String spagoBiServerURL = EnginConf.getInstance().getSpagoBiServerUrl();
	HttpSession session = request.getSession();
	String secureAttributes = (String) session.getAttribute("isBackend");
	String serviceUrlStr = null;
	SourceBean engineConfig = EnginConf.getInstance().getConfig();
	if (engineConfig != null) {
		SourceBean sourceBeanConf = (SourceBean) engineConfig.getAttribute("DataSetServiceProxy_URL");
		serviceUrlStr = sourceBeanConf.getCharacters();
	}

	SsoServiceInterface proxyService = SsoServiceFactory.createProxyService();
	String token = proxyService.readTicket(session);

	context.put(REPORT_EXECUTION_ID, createNewExecutionId());
	context.put("RESOURCE_PATH_JNDI_NAME", resourcePath);
	context.put("SBI_BIRT_RUNTIME_IS_RUNTIME", "true");
	context.put("SBI_BIRT_RUNTIME_USER_ID", userId);
	context.put("SBI_BIRT_RUNTIME_SECURE_ATTRS", secureAttributes);
	context.put("SBI_BIRT_RUNTIME_SERVICE_URL", serviceUrlStr);
	context.put("SBI_BIRT_RUNTIME_SERVER_URL", spagoBiServerURL);
	context.put("SBI_BIRT_RUNTIME_TOKEN", token);
	context.put("SBI_BIRT_RUNTIME_PARS_MAP", reportParams);
	context.put("SBI_BIRT_RUNTIME_PROFILE_USER_ATTRS", userProfileAttrs);
	context.put("SBI_BIRT_RUNTIME_GROOVY_SCRIPT_FILE_NAME", predefinedGroovyScriptFileName);
	context.put("SBI_BIRT_RUNTIME_JS_SCRIPT_FILE_NAME", predefinedJsScriptFileName);
	context.put("SESSION", session);

	return context;
}
 
Example #18
Source File: CoverArtController.java    From subsonic with GNU General Public License v3.0 5 votes vote down vote up
private CoverArtRequest createMediaFileCoverArtRequest(int id, HttpServletRequest request) {
    MediaFile mediaFile = mediaFileService.getMediaFile(id);
    if (mediaFile == null) {
        return null;
    }
    if (mediaFile.isVideo()) {
        int offset = ServletRequestUtils.getIntParameter(request, "offset", 60);
        return new VideoCoverArtRequest(mediaFile, offset);
    }
    return new MediaFileCoverArtRequest(mediaFile);
}
 
Example #19
Source File: UserServlet.java    From code_quality_principles with Apache License 2.0 5 votes vote down vote up
/**
 * Shows Users in list.
 * @param list list of users.
 * @param req request param.
 * @param resp response param.
 * @throws IOException possible.
 */
private void showList(Map<Integer, User> list, HttpServletRequest req, HttpServletResponse resp) throws IOException {
    PrintWriter writer = new PrintWriter(resp.getOutputStream());
    writer.append("List: \n");
    list.forEach((integer, user) -> {
        writer.append("User id= ").append(String.valueOf(integer)).append("\n");
        writer.append("Name= ").append(user.getName()).append("\n");
        writer.append("Login= ").append(user.getLogin()).append("\n");
        writer.append("Email= ").append(user.getEmail()).append("\n");
        writer.append("Create Date= ").append(user.getCreated()).append("\n");
        writer.append("\n");
    });
    writer.flush();
}
 
Example #20
Source File: SolrRequestParserTest.java    From lucene-solr with 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 #21
Source File: IpPushConfigServlet.java    From qconfig with MIT License 5 votes vote down vote up
private Set<String> parseRequest(HttpServletRequest req) throws IOException {
    List<String> list = readLines(req);
    Set<String> ips = Sets.newHashSetWithExpectedSize(list.size());
    for (String line : list) {
        line = line.trim();
        if (!Strings.isNullOrEmpty(line)) {
            ips.add(line);
        }
    }
    return ips;
}
 
Example #22
Source File: HomeMenuController.java    From hauth-java with MIT License 5 votes vote down vote up
@RequestMapping(value = "/v1/auth/main/menu",method = RequestMethod.GET)
@ResponseBody
public List<HomeMenuEntity> homeMenu(HttpServletRequest request) {
    String TypeId = request.getParameter("TypeId");
    String Id = request.getParameter("Id");

    String username = JwtService.getConnUser(request).getUserId();
    List<HomeMenuEntity> homeMenusModel = homeMenuService.findAuthedMenus(username, TypeId, Id);
    return homeMenusModel;
}
 
Example #23
Source File: CmsTopicAct.java    From Lottery with GNU General Public License v2.0 5 votes vote down vote up
private WebErrors validateUpdate(Integer id, HttpServletRequest request) {
	WebErrors errors = WebErrors.create(request);
	if (vldExist(id, errors)) {
		return errors;
	}
	return errors;
}
 
Example #24
Source File: OrgController.java    From hauth-java with MIT License 5 votes vote down vote up
@RequestMapping(method = RequestMethod.GET)
public List findAll(HttpServletRequest request) {
    String domainId = request.getParameter("domain_id");
    if (domainId == null || domainId.isEmpty()) {
        domainId = JwtService.getConnUser(request).getDomainID();
    }
    return orgService.findAll(domainId);
}
 
Example #25
Source File: PhdIndividualProgramProcessDA.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public ActionForward prepareRequestPublicPresentationSeminarComission(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) {
    ActionForward forward = super.prepareRequestPublicPresentationSeminarComission(mapping, form, request, response);

    PublicPresentationSeminarProcessBean bean =
            (PublicPresentationSeminarProcessBean) request.getAttribute("requestPublicPresentationSeminarComissionBean");
    bean.setGenerateAlert(true);

    return forward;
}
 
Example #26
Source File: SampleResource.java    From wingtips with 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);
}
 
Example #27
Source File: UserAuthenticationWebService.java    From olat with 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 #28
Source File: KualiForm.java    From rice with 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 File: BasicAuthenticator.java    From carbon-identity with 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 #30
Source File: AccountResource.java    From jhipster-ribbon-hystrix with 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();
}