Java Code Examples for org.apache.commons.lang3.StringUtils.substringBetween()

The following are Jave code examples for showing how to use substringBetween() of the org.apache.commons.lang3.StringUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: patternlab-for-sling   File: PatternLabUtils.java   View Source Code Vote up 6 votes
public static String constructPatternId(String patternResourcePath, String patternsPath, String templateName, String jsonDataFileName) {
    final String patternPath = StringUtils.substringAfter(patternResourcePath, patternsPath + SLASH);
    final StringBuilder patternIdBuilder = new StringBuilder();
    if (StringUtils.endsWith(patternPath, HTML_EXT)) {
        patternIdBuilder.append(StringUtils.substringBeforeLast(patternPath, HTML_EXT));
    } else {
        patternIdBuilder.append(patternPath);
    }
    if (StringUtils.isNotBlank(templateName)) {
        patternIdBuilder.append(SLASH).append(templateName);
    }
    if (StringUtils.isNotBlank(jsonDataFileName)) {
        final String patternFileName = StringUtils.substringAfterLast(patternPath, SLASH);
        final String fileNameWithoutExt = StringUtils.substringBeforeLast(patternFileName, HTML_EXT);
        final String dataFileSuffix = StringUtils.substringBetween(jsonDataFileName, fileNameWithoutExt
                + SELECTOR, DATA_EXT);
        patternIdBuilder.append(SLASH).append(StringUtils.defaultString(dataFileSuffix, fileNameWithoutExt));
    }
    return StringUtils.replace(patternIdBuilder.toString(), SLASH, PATTERN_ID_REPLACEMENT);
}
 
Example 2
Project: xm-commons   File: PrivilegeScanner.java   View Source Code Vote up 6 votes
private Privilege parse(String expression) {
    Privilege privilege = new Privilege();
    privilege.setMsName(appName);
    String[] inputParams = StringUtils.split(expression, ",");

    for (int i = 0; i < inputParams.length; i++) {
        if (i == inputParams.length - 1) {
            if (StringUtils.contains(inputParams[i], "'")) {
                privilege.setKey(StringUtils.substringBetween(inputParams[i], "'")
                    .replace("@msName", appName.toUpperCase()));
            } else {
                privilege.setKey(inputParams[i].replace("@msName", appName.toUpperCase()));
            }
        } else {
            String resource = StringUtils.substringBetween(inputParams[i], "'");
            if (StringUtils.isNotEmpty(resource)) {
                privilege.getResources().add(resource);
            }
        }
    }
    return privilege;
}
 
Example 3
Project: aceql-http   File: ServletPathAnalyzer.java   View Source Code Vote up 6 votes
public void buildElements(String servletName, String urlContent) {
	
if (urlContent == null) {
    throw new NullPointerException("urlContent is null");
}

if (! urlContent.contains("/session/")) {
    throw new IllegalArgumentException("Request does not contain /session/ subpath in path");
}

session = StringUtils.substringBetween(urlContent, "/session/", "/");

if (session == null) {
    throw new IllegalArgumentException("Request does not contain session id");
}

   }
 
Example 4
Project: xtf   File: OpenshiftUtil.java   View Source Code Vote up 6 votes
public String getToken(String username, String password) {
	try {
		String url = TestConfiguration.masterUrl() + "/oauth/authorize?response_type=token&client_id=openshift-challenging-client";
		List<Header> headers = HttpClient.get(url)
				.basicAuth(username, password)
				.preemptiveAuth()
				.disableRedirect()
				.responseHeaders();
		Optional<Header> location = headers.stream().filter(h -> "Location".equals(h.getName())).findFirst();
		if (location.isPresent()) {
			LOGGER.debug("Location: {}", location.get().getValue());
			String token = StringUtils.substringBetween(location.get().getValue(), "#access_token=", "&");
			LOGGER.info("Oauth token: {}", token);
			return token;
		}
		LOGGER.info("Location header with token not found");
		return null;
	} catch (IOException e) {
		LOGGER.error("Error getting token from master", e);
		return null;
	}
}
 
Example 5
Project: WechatBot   File: WechatBot.java   View Source Code Vote up 6 votes
private String[] syncCheck() throws IOException {
    Map<String, Object> request = new HashMap<>();
    request.put("r", new Date().getTime());
    request.put("sid", initData.get("wxsid"));
    request.put("uin", initData.get("wxuin"));
    request.put("skey", initData.get("skey"));
    request.put("deviceid", initData.get("deviceID"));
    request.put("synckey", syncKeyStr);
    request.put("_", new Date().getTime());

    String url = "https://" + syncHost + "/cgi-bin/mmwebwx-bin/synccheck?" + NetUtils.getUrlParamsByMap(request, false);
    log.trace("url: " + url);
    String response = NetUtils.request(url);
    log.trace("syncCheck response: " + response);

    String retcode = StringUtils.substringBetween(response, "retcode:\"", "\",");
    String selector = StringUtils.substringBetween(response, "selector:\"", "\"}");
    return new String[]{retcode, selector};
}
 
Example 6
Project: bandcamp-api   File: JSONUtil.java   View Source Code Vote up 5 votes
public static String getJsonData(String input, String startTag, String endTag)
{
	if(StringUtils.isNotBlank(startTag) && StringUtils.isNotBlank(endTag))
	{
		return StringUtils.substringBetween(input,startTag, endTag);
	}
	return null;
}
 
Example 7
Project: cas-5.1.0   File: OAuth20AccessTokenControllerTests.java   View Source Code Vote up 5 votes
private void internalVerifyClientOK(final RegisteredService service, final boolean basicAuth, final boolean refreshToken, final boolean json)
        throws Exception {

    final Principal principal = createPrincipal();
    final OAuthCode code = addCode(principal, service);

    final MockHttpServletRequest mockRequest = new MockHttpServletRequest(GET, CONTEXT + OAuth20Constants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuth20Constants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuth20Constants.GRANT_TYPE, OAuth20GrantTypes.AUTHORIZATION_CODE.name().toLowerCase());
    if (basicAuth) {
        final String auth = CLIENT_ID + ':' + CLIENT_SECRET;
        final String value = Base64.encodeBase64String(auth.getBytes(StandardCharsets.UTF_8));
        mockRequest.addHeader(HttpConstants.AUTHORIZATION_HEADER, HttpConstants.BASIC_HEADER_PREFIX + value);
    } else {
        mockRequest.setParameter(OAuth20Constants.CLIENT_ID, CLIENT_ID);
        mockRequest.setParameter(OAuth20Constants.CLIENT_SECRET, CLIENT_SECRET);
    }
    mockRequest.setParameter(OAuth20Constants.CODE, code.getId());
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequest(mockRequest, mockResponse);
    assertNull(this.ticketRegistry.getTicket(code.getId()));
    assertEquals(HttpStatus.SC_OK, mockResponse.getStatus());
    final String body = mockResponse.getContentAsString();

    final String accessTokenId;
    if (json) {
        assertEquals(MediaType.APPLICATION_JSON_VALUE, mockResponse.getContentType());
        assertTrue(body.contains('"' + OAuth20Constants.ACCESS_TOKEN + "\":\"AT-"));
        if (refreshToken) {
            assertTrue(body.contains('"' + OAuth20Constants.REFRESH_TOKEN + "\":\"RT-"));
        }
        assertTrue(body.contains('"' + OAuth20Constants.EXPIRES_IN + "\":7"));
        accessTokenId = StringUtils.substringBetween(body, OAuth20Constants.ACCESS_TOKEN + "\":\"", "\",\"");
    } else {
        assertEquals(MediaType.TEXT_PLAIN_VALUE, mockResponse.getContentType());
        assertTrue(body.contains(OAuth20Constants.ACCESS_TOKEN + "=AT-"));
        if (refreshToken) {
            assertTrue(body.contains(OAuth20Constants.REFRESH_TOKEN + "=RT-"));
        }
        assertTrue(body.contains(OAuth20Constants.EXPIRES_IN + '='));
        accessTokenId = StringUtils.substringBetween(body, OAuth20Constants.ACCESS_TOKEN + '=', "&");
    }

    final AccessToken accessToken = this.ticketRegistry.getTicket(accessTokenId, AccessToken.class);
    assertEquals(principal, accessToken.getAuthentication().getPrincipal());

    final int timeLeft = getTimeLeft(body, refreshToken, json);
    assertTrue(timeLeft >= TIMEOUT - 10 - DELTA);
}
 
Example 8
Project: cas-5.1.0   File: OAuth20AccessTokenControllerTests.java   View Source Code Vote up 5 votes
private void internalVerifyUserAuth(final boolean refreshToken, final boolean json) throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest(GET, CONTEXT + OAuth20Constants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuth20Constants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuth20Constants.GRANT_TYPE, OAuth20GrantTypes.PASSWORD.name().toLowerCase());
    mockRequest.setParameter(USERNAME, GOOD_USERNAME);
    mockRequest.setParameter(PASSWORD, GOOD_PASSWORD);
    mockRequest.addHeader(CasProtocolConstants.PARAMETER_SERVICE, REDIRECT_URI);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequest(mockRequest, mockResponse);
    assertEquals(200, mockResponse.getStatus());
    final String body = mockResponse.getContentAsString();

    final String accessTokenId;
    if (json) {
        assertEquals("application/json", mockResponse.getContentType());
        assertTrue(body.contains('"' + OAuth20Constants.ACCESS_TOKEN + "\":\"AT-"));
        if (refreshToken) {
            assertTrue(body.contains('"' + OAuth20Constants.REFRESH_TOKEN + "\":\"RT-"));
        }
        assertTrue(body.contains('"' + OAuth20Constants.EXPIRES_IN + "\":7"));
        accessTokenId = StringUtils.substringBetween(body, OAuth20Constants.ACCESS_TOKEN + "\":\"", "\",\"");
    } else {
        assertEquals("text/plain", mockResponse.getContentType());
        assertTrue(body.contains(OAuth20Constants.ACCESS_TOKEN + '='));
        if (refreshToken) {
            assertTrue(body.contains(OAuth20Constants.REFRESH_TOKEN + '='));
        }
        assertTrue(body.contains(OAuth20Constants.EXPIRES_IN + '='));
        accessTokenId = StringUtils.substringBetween(body, OAuth20Constants.ACCESS_TOKEN + '=', "&");
    }

    final AccessToken accessToken = this.ticketRegistry.getTicket(accessTokenId, AccessToken.class);
    assertEquals(GOOD_USERNAME, accessToken.getAuthentication().getPrincipal().getId());

    final int timeLeft = getTimeLeft(body, refreshToken, json);
    assertTrue(timeLeft >= TIMEOUT - 10 - DELTA);
}
 
Example 9
Project: cas-5.1.0   File: OAuth20AccessTokenControllerTests.java   View Source Code Vote up 5 votes
private void internalVerifyRefreshTokenOk(final OAuthRegisteredService service, final boolean json) throws Exception {
    final Principal principal = createPrincipal();
    final RefreshToken refreshToken = addRefreshToken(principal, service);

    final MockHttpServletRequest mockRequest = new MockHttpServletRequest(GET, CONTEXT + OAuth20Constants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuth20Constants.GRANT_TYPE, OAuth20GrantTypes.REFRESH_TOKEN.name().toLowerCase());
    mockRequest.setParameter(OAuth20Constants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuth20Constants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuth20Constants.REFRESH_TOKEN, refreshToken.getId());
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequest(mockRequest, mockResponse);
    assertEquals(200, mockResponse.getStatus());
    final String body = mockResponse.getContentAsString();

    final String accessTokenId;
    if (json) {
        assertEquals("application/json", mockResponse.getContentType());
        assertTrue(body.contains('"' + OAuth20Constants.ACCESS_TOKEN + "\":\"AT-"));
        assertFalse(body.contains('"' + OAuth20Constants.REFRESH_TOKEN + "\":\"RT-"));
        assertTrue(body.contains('"' + OAuth20Constants.EXPIRES_IN + "\":7"));
        accessTokenId = StringUtils.substringBetween(body, OAuth20Constants.ACCESS_TOKEN + "\":\"", "\",\"");
    } else {
        assertEquals("text/plain", mockResponse.getContentType());
        assertTrue(body.contains(OAuth20Constants.ACCESS_TOKEN + '='));
        assertFalse(body.contains(OAuth20Constants.REFRESH_TOKEN + '='));
        assertTrue(body.contains(OAuth20Constants.EXPIRES_IN + '='));
        accessTokenId = StringUtils.substringBetween(body, OAuth20Constants.ACCESS_TOKEN + '=', "&");
    }

    final AccessToken accessToken = this.ticketRegistry.getTicket(accessTokenId, AccessToken.class);
    assertEquals(principal, accessToken.getAuthentication().getPrincipal());

    final int timeLeft = getTimeLeft(body, false, json);
    assertTrue(timeLeft >= TIMEOUT - 10 - DELTA);
}
 
Example 10
Project: solo-spring   File: AdminConsole.java   View Source Code Vote up 5 votes
/**
 * Shows administrator functions with the specified context.
 *
 * @param request
 *            the specified request
 * @param context
 *            the specified context
 */
@RequestMapping(value = { "/admin-article.do", "/admin-article-list.do", "/admin-comment-list.do",
		"/admin-link-list.do", "/admin-page-list.do", "/admin-others.do", "/admin-draft-list.do",
		"/admin-user-list.do", "/admin-category-list.do", "/admin-plugin-list.do", "/admin-main.do",
		"/admin-about.do" }, method = RequestMethod.GET)
public void showAdminFunctions(final HttpServletRequest request, final HttpServletResponse response) {
	final AbstractFreeMarkerRenderer renderer = new ConsoleRenderer();

	final String requestURI = request.getRequestURI();
	final String templateName = StringUtils.substringBetween(requestURI, Latkes.getContextPath() + '/', ".")
			+ ".ftl";

	logger.trace("Admin function[templateName={}]", templateName);
	renderer.setTemplateName(templateName);

	final Locale locale = Latkes.getLocale();
	final Map<String, String> langs = langPropsService.getAll(locale);
	final Map<String, Object> dataModel = renderer.getDataModel();

	dataModel.put("isMySQL", RuntimeDatabase.MYSQL == Latkes.getRuntimeDatabase());
	dataModel.putAll(langs);
	Keys.fillRuntime(dataModel);
	dataModel.put(Option.ID_C_LOCALE_STRING, locale.toString());

	fireFreeMarkerActionEvent(templateName, dataModel);
	renderer.render(request, response);
}
 
Example 11
Project: aceql-http   File: SavepointHttp.java   View Source Code Vote up 5 votes
/**
    * Builds a Savepoint from a String
    * 
    * @param savepointStrthe
    *            String containing a SavepointHttp.toString()
    * @return a SavepointHttp
    */
   public static Savepoint buildFromString(String savepointStr) {

if (savepointStr == null) {
    throw new IllegalArgumentException("Savepoint can not be null!");
}

if (!savepointStr.contains("[id=") || !savepointStr.contains(", name")
	|| !savepointStr.endsWith("]")) {
    throw new IllegalArgumentException(
	    "Savepoint String is not conform to pattern [id=theId, name=theName]: "
		    + savepointStr);
}

String idStr = StringUtils.substringBetween(savepointStr, "[id=",
	", name=");

if (idStr == null) {
    throw new IllegalArgumentException("id as String can not be null!");
}

idStr = idStr.trim();

int id = Integer.parseInt(idStr);

String name = StringUtils
	.substringBetween(savepointStr, ", name=", "]");

if (name == null) {
    throw new IllegalArgumentException("name can not be null!");
}

name = name.trim();

SavepointHttp savepointHttp = new SavepointHttp(id, name);
return savepointHttp;

   }
 
Example 12
Project: wulkanowy   File: Timetable.java   View Source Code Vote up 5 votes
private String[] getLessonAndGroupInfoFromSpan(Element span) {
    String[] subjectNameArray = span.text().split(" ");
    String groupName = subjectNameArray[subjectNameArray.length - 1];

    return new String[]{
            span.text().replace(" " + groupName, ""),
            StringUtils.substringBetween(groupName, "[", "]")
    };
}
 
Example 13
Project: WechatBot   File: WechatBot.java   View Source Code Vote up 5 votes
public WechatBot getUuid() throws IOException {
    loginUrl = loginUrl + new Date().getTime();
    log.trace("loginUrl: " + loginUrl);
    String response = NetUtils.request(loginUrl);
    // e.g: window.QRLogin.code = 200; window.QRLogin.uuid = "wejZcbBd2w==";
    String code = StringUtils.substringBetween(response, "window.QRLogin.code = ", ";");
    uuid = StringUtils.substringBetween(response, "window.QRLogin.uuid = \"", "\";");

    log.debug("window.QRLogin.code = " + code);
    log.debug("window.QRLogin.uuid = " + uuid);
    return this;
}
 
Example 14
Project: WechatBot   File: WechatBot.java   View Source Code Vote up 5 votes
public WechatBot waitForLogin() throws IOException, InterruptedException {
    String url = StringUtils.join("https://login.weixin.qq.com/cgi-bin/mmwebwx-bin/login?uuid=", uuid, "&tip=1&_=", new Date().getTime());
    log.trace("login url: " + url);
    while (true) {
        String response = NetUtils.request(url);
        log.trace("response: " + response);

        // 登陆过程中
        if (StringUtils.startsWith(response, "window.code=")) {
            String code = StringUtils.substringBetween(response, "window.code=", ";");
            log.debug("code: " + code);
            if (StringUtils.equals(code, SUCCESS)) {
                log.info("登陆成功");
                response = NetUtils.request(url);
                redirectUrl = StringUtils.substringBetween(response, "window.redirect_uri=\"", "\";");
                if (StringUtils.isNotEmpty(redirectUrl)) {
                    log.debug("redirectUrl: " + redirectUrl);
                    break;
                }
            } else if (StringUtils.equals(code, SCANED))
                log.info("请点击确认按钮");
            else if (StringUtils.equals(code, TIMEOUT)) {
                log.info("登陆超时");
                System.exit(-1);
            } else {
                log.info("未知错误");
                log.error(response);
                System.exit(-1);
            }
        }

        // 轮询时间 1s
        Thread.sleep(1000);
    }
    return this;
}
 
Example 15
Project: JHosts   File: HostFileService.java   View Source Code Vote up 5 votes
private static Set<String> getLabels(String line) {
    String open = "#{";
    String close = "}#";
    Set<String> labels = new HashSet<>();
    String label = StringUtils.substringBetween(line, open, close);
    while (StringUtils.isNotBlank(label)) {
        labels.add(label);
        line = StringUtils.replace(line, open + label + close, "");
        label = StringUtils.substringBetween(line, open, close);
    }
    return labels;
}
 
Example 16
Project: cas-5.1.0   File: OAuth20AuthorizeControllerTests.java   View Source Code Vote up 4 votes
@Test
public void verifyTokenRedirectToClient() throws Exception {
    clearAllServices();

    final MockHttpServletRequest mockRequest = new MockHttpServletRequest(GET, CONTEXT + OAuth20Constants.AUTHORIZE_URL);
    mockRequest.setParameter(OAuth20Constants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuth20Constants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuth20Constants.RESPONSE_TYPE, OAuth20ResponseTypes.TOKEN.name().toLowerCase());
    mockRequest.setServerName(CAS_SERVER);
    mockRequest.setServerPort(CAS_PORT);
    mockRequest.setScheme(CAS_SCHEME);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();

    final OAuthRegisteredService service = getRegisteredService(REDIRECT_URI, SERVICE_NAME);
    service.setBypassApprovalPrompt(true);
    this.servicesManager.save(service);

    final CasProfile profile = new CasProfile();
    profile.setId(ID);
    final Map<String, Object> attributes = new HashMap<>();
    attributes.put(FIRST_NAME_ATTRIBUTE, FIRST_NAME);
    attributes.put(LAST_NAME_ATTRIBUTE, LAST_NAME);
    profile.addAttributes(attributes);

    final MockHttpSession session = new MockHttpSession();
    mockRequest.setSession(session);
    session.putValue(Pac4jConstants.USER_PROFILES, profile);

    final ModelAndView modelAndView = oAuth20AuthorizeEndpointController.handleRequest(mockRequest, mockResponse);
    final View view = modelAndView.getView();
    assertTrue(view instanceof RedirectView);
    final RedirectView redirectView = (RedirectView) view;
    final String redirectUrl = redirectView.getUrl();
    assertTrue(redirectUrl.startsWith(REDIRECT_URI + "#access_token="));

    final String code = StringUtils.substringBetween(redirectUrl, "#access_token=", "&token_type=bearer");
    final AccessToken accessToken = (AccessToken) this.ticketRegistry.getTicket(code);
    assertNotNull(accessToken);
    final Principal principal = accessToken.getAuthentication().getPrincipal();
    assertEquals(ID, principal.getId());
    final Map<String, Object> principalAttributes = principal.getAttributes();
    assertEquals(attributes.size(), principalAttributes.size());
    assertEquals(FIRST_NAME, principalAttributes.get(FIRST_NAME_ATTRIBUTE));
}
 
Example 17
Project: cas-5.1.0   File: OAuth20AuthorizeControllerTests.java   View Source Code Vote up 4 votes
@Test
public void verifyTokenRedirectToClientWithState() throws Exception {
    clearAllServices();

    final MockHttpServletRequest mockRequest = new MockHttpServletRequest(GET, CONTEXT + OAuth20Constants.AUTHORIZE_URL);
    mockRequest.setParameter(OAuth20Constants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuth20Constants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuth20Constants.RESPONSE_TYPE, OAuth20ResponseTypes.TOKEN.name().toLowerCase());
    mockRequest.setServerName(CAS_SERVER);
    mockRequest.setServerPort(CAS_PORT);
    mockRequest.setScheme(CAS_SCHEME);
    mockRequest.setParameter(OAuth20Constants.STATE, STATE);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();

    final OAuthRegisteredService service = getRegisteredService(REDIRECT_URI, SERVICE_NAME);
    service.setBypassApprovalPrompt(true);
    this.servicesManager.save(service);

    final CasProfile profile = new CasProfile();
    profile.setId(ID);
    final Map<String, Object> attributes = new HashMap<>();
    attributes.put(FIRST_NAME_ATTRIBUTE, FIRST_NAME);
    attributes.put(LAST_NAME_ATTRIBUTE, LAST_NAME);
    profile.addAttributes(attributes);

    final MockHttpSession session = new MockHttpSession();
    mockRequest.setSession(session);
    session.putValue(Pac4jConstants.USER_PROFILES, profile);

    final ModelAndView modelAndView = oAuth20AuthorizeEndpointController.handleRequest(mockRequest, mockResponse);
    final View view = modelAndView.getView();
    assertTrue(view instanceof RedirectView);
    final RedirectView redirectView = (RedirectView) view;
    final String redirectUrl = redirectView.getUrl();
    assertTrue(redirectUrl.startsWith(REDIRECT_URI + "#access_token="));
    assertTrue(redirectUrl.contains('&' + OAuth20Constants.STATE + '=' + STATE));

    final String code = StringUtils.substringBetween(redirectUrl, "#access_token=", "&token_type=bearer");
    final AccessToken accessToken = (AccessToken) this.ticketRegistry.getTicket(code);
    assertNotNull(accessToken);
    final Principal principal = accessToken.getAuthentication().getPrincipal();
    assertEquals(ID, principal.getId());
    final Map<String, Object> principalAttributes = principal.getAttributes();
    assertEquals(attributes.size(), principalAttributes.size());
    assertEquals(FIRST_NAME, principalAttributes.get(FIRST_NAME_ATTRIBUTE));
}
 
Example 18
Project: cas-5.1.0   File: OAuth20AuthorizeControllerTests.java   View Source Code Vote up 4 votes
@Test
public void verifyTokenRedirectToClientApproved() throws Exception {
    clearAllServices();

    final MockHttpServletRequest mockRequest = new MockHttpServletRequest(GET, CONTEXT + OAuth20Constants.AUTHORIZE_URL);
    mockRequest.setParameter(OAuth20Constants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuth20Constants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuth20Constants.RESPONSE_TYPE, OAuth20ResponseTypes.TOKEN.name().toLowerCase());
    mockRequest.setServerName(CAS_SERVER);
    mockRequest.setServerPort(CAS_PORT);
    mockRequest.setScheme(CAS_SCHEME);
    mockRequest.setParameter(OAuth20Constants.BYPASS_APPROVAL_PROMPT, "true");
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();

    final OAuthRegisteredService service = getRegisteredService(REDIRECT_URI, SERVICE_NAME);
    service.setBypassApprovalPrompt(false);
    this.servicesManager.save(service);

    final CasProfile profile = new CasProfile();
    profile.setId(ID);
    final Map<String, Object> attributes = new HashMap<>();
    attributes.put(FIRST_NAME_ATTRIBUTE, FIRST_NAME);
    attributes.put(LAST_NAME_ATTRIBUTE, LAST_NAME);
    profile.addAttributes(attributes);

    final MockHttpSession session = new MockHttpSession();
    mockRequest.setSession(session);
    session.putValue(Pac4jConstants.USER_PROFILES, profile);

    final ModelAndView modelAndView = oAuth20AuthorizeEndpointController.handleRequest(mockRequest, mockResponse);
    final View view = modelAndView.getView();
    assertTrue(view instanceof RedirectView);
    final RedirectView redirectView = (RedirectView) view;
    final String redirectUrl = redirectView.getUrl();
    assertTrue(redirectUrl.startsWith(REDIRECT_URI + "#access_token="));

    final String code = StringUtils.substringBetween(redirectUrl, "#access_token=", "&token_type=bearer");
    final AccessToken accessToken = (AccessToken) this.ticketRegistry.getTicket(code);
    assertNotNull(accessToken);
    final Principal principal = accessToken.getAuthentication().getPrincipal();
    assertEquals(ID, principal.getId());
    final Map<String, Object> principalAttributes = principal.getAttributes();
    assertEquals(attributes.size(), principalAttributes.size());
    assertEquals(FIRST_NAME, principalAttributes.get(FIRST_NAME_ATTRIBUTE));
}
 
Example 19
Project: solo-spring   File: ArticleController.java   View Source Code Vote up 4 votes
/**
 * Gets relevant articles with the specified context.
 *
 * @param context
 *            the specified context
 * @param request
 *            the specified request
 * @param response
 *            the specified response
 * @throws Exception
 *             exception
 */
@RequestMapping(value = "/article/id/*/relevant/articles", method = RequestMethod.GET)
public void getRelevantArticles(final HttpServletRequest request, final HttpServletResponse response)
		throws Exception {
	final JSONRenderer renderer = new JSONRenderer();

	final JSONObject jsonObject = new JSONObject();

	final JSONObject preference = preferenceQueryService.getPreference();

	final int displayCnt = preference.getInt(Option.ID_C_RELEVANT_ARTICLES_DISPLAY_CNT);

	if (0 == displayCnt) {
		jsonObject.put(Common.RANDOM_ARTICLES, new ArrayList<JSONObject>());
		renderer.setJSONObject(jsonObject);
		renderer.render(request, response);
		return;
	}

	Stopwatchs.start("Get Relevant Articles");
	final String requestURI = request.getRequestURI();

	final String articleId = StringUtils.substringBetween(requestURI, "/article/id/", "/relevant/articles");

	if (StringUtils.isBlank(articleId)) {
		response.sendError(HttpServletResponse.SC_NOT_FOUND);
		return;
	}

	final JSONObject article = articleQueryService.getArticleById(articleId);

	if (null == article) {
		response.sendError(HttpServletResponse.SC_NOT_FOUND);
		return;
	}

	final List<JSONObject> relevantArticles = articleQueryService.getRelevantArticles(article, preference);

	jsonObject.put(Common.RELEVANT_ARTICLES, relevantArticles);

	renderer.setJSONObject(jsonObject);

	Stopwatchs.end();
	renderer.render(request, response);
}
 
Example 20
Project: WechatBot   File: NetUtils.java   View Source Code Vote up 4 votes
public static String postImage(String id, String url, File file,
                               String mediatype, Map<String, Object> uploadMediaRequest,
                               String passTicket) throws IOException {

    log.debug("local cookies: " + localCookie.toString());
    String webwxDataTicket = StringUtils.substringBetween(localCookie.toString(), "webwx_data_ticket=", "; expires");
    if (StringUtils.isBlank(webwxDataTicket)) {
        log.error("No webwx_data_ticket in cookies");
        return null;
    }

    String type = Files.probeContentType(file.toPath());

    RequestBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("id", id)
            .addFormDataPart("name", file.getName())
            .addFormDataPart("type", type)
            .addFormDataPart("lastModifiedDate", LocalDate.now().getMonthValue()
                    + "/" + LocalDate.now().getDayOfMonth()
                    + "/" + LocalDate.now().getYear()
                    + ", " + LocalTime.now().withNano(0)
                    + " GMT+0800 (CST)")
            .addFormDataPart("size", String.valueOf(Files.size(file.toPath())))
            .addFormDataPart("mediatype", mediatype)
            .addFormDataPart("uploadmediarequest", mapper.writeValueAsString(uploadMediaRequest))
            .addFormDataPart("webwx_data_ticket", webwxDataTicket)
            .addFormDataPart("pass_ticket", passTicket)
            .addFormDataPart("filename", file.getName(), RequestBody.create(MediaType.parse(type), file))
            .build();

    Request request = new Request.Builder()
            .addHeader(USER_AGENT, USER_AGENT_CONTENT)
            .url(url)
            .post(requestBody)
            .build();

    try (ResponseBody responseBody = client.newCall(request).execute().body()) {
        return responseBody.string();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}