当前位置: 首页>>代码示例>>Java>>正文


Java Connection类代码示例

本文整理汇总了Java中org.springframework.social.connect.Connection的典型用法代码示例。如果您正苦于以下问题:Java Connection类的具体用法?Java Connection怎么用?Java Connection使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


Connection类属于org.springframework.social.connect包,在下文中一共展示了Connection类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: authenticate

import org.springframework.social.connect.Connection; //导入依赖的package包/类
public void authenticate(Connection<?> connection) {
    Facebook facebook = (Facebook) connection.getApi();
    String [] fields = { "id", "name", "email", "first_name", "last_name" };
    User userProfile = facebook.fetchObject("me", User.class, fields);
    String username = userProfile.getName();

    log.info("User Profile by facebook {} {} {}", userProfile.getFirstName(), userProfile.getLastName(), userProfile.getEmail());

    Optional<io.osoon.domain.User> byEmail = userService.findByEmail(userProfile.getEmail());
    io.osoon.domain.User osoonUser;

    if (byEmail.isPresent()) {
        osoonUser = byEmail.get();
    } else {
        io.osoon.domain.User newUser = io.osoon.domain.User.of(userProfile.getEmail(), username);
        newUser.setImageUrl(connection.getImageUrl());
        osoonUser = userService.saveOne(newUser);
    }

    OSoonUserDetails userDetails = new OSoonUserDetails(osoonUser);
    RememberMeAuthenticationToken rememberMeToken = new RememberMeAuthenticationToken("osoon-remember-me", userDetails, null);
    SecurityContextHolder.getContext().setAuthentication(rememberMeToken);

    log.info("User {} {} {} connected.", userProfile.getFirstName(), userProfile.getLastName(), userProfile.getEmail());
}
 
开发者ID:spring-sprout,项目名称:osoon,代码行数:26,代码来源:AuthUtil.java

示例2: completeConnection

import org.springframework.social.connect.Connection; //导入依赖的package包/类
/**
 * Complete the connection to the OAuth2 provider.
 *
 * @param connectionFactory the service provider's connection factory e.g. FacebookConnectionFactory
 * @param request the current web request
 * @return a new connection to the service provider
 */
public Connection completeConnection(OAuth2ConnectionFactory<?> connectionFactory, NativeWebRequest request) {
    if (connectionFactory.supportsStateParameter()) {
        verifyStateParameter(request);
    }

    String code = request.getParameter("code");
    try {
        AccessGrant accessGrant = connectionFactory.getOAuthOperations()
            .exchangeForAccess(code, callbackUrl(request), null);
        return connectionFactory.createConnection(accessGrant);
    } catch (HttpClientErrorException e) {
        log.warn("HttpClientErrorException while completing connection: " + e.getMessage());
        log.warn("      Response body: " + e.getResponseBodyAsString());
        throw e;
    }
}
 
开发者ID:xm-online,项目名称:xm-uaa,代码行数:24,代码来源:ConnectSupport.java

示例3: signUp

import org.springframework.social.connect.Connection; //导入依赖的package包/类
@GetMapping("/signup")
public RedirectView signUp(WebRequest webRequest,
    @CookieValue(name = "NG_TRANSLATE_LANG_KEY", required = false, defaultValue = "\"en\"") String langKey) {
    String providerId = null;
    try {
        Connection<?> connection = providerSignInUtils.getConnectionFromSession(webRequest);
        providerId = connection.getKey().getProviderId();
        socialService.createSocialUser(connection, langKey.replace("\"", ""));
        return redirect(URIBuilder
                        .fromUri(TenantUtil.getApplicationUrl() + "/social-register/"
                                        + connection.getKey().getProviderId())
                        .queryParam("success", "true").build().toString());
    } catch (Exception e) {
        log.error("Exception creating social user: ", e);
        return redirectOnError(providerId);
    }
}
 
开发者ID:xm-online,项目名称:xm-uaa,代码行数:18,代码来源:SocialController.java

示例4: handleSignIn

import org.springframework.social.connect.Connection; //导入依赖的package包/类
private RedirectView handleSignIn(Connection<?> connection, ConnectionFactory<?> connectionFactory,
    NativeWebRequest request) {
    List<String> userIds = usersConnectionRepository.findUserIdsWithConnection(connection);
    if (userIds.isEmpty()) {
        ProviderSignInAttempt signInAttempt = new ProviderSignInAttempt(connection);
        sessionStrategy.setAttribute(request, ProviderSignInAttempt.SESSION_ATTRIBUTE, signInAttempt);
        return redirect(getSignUpUrl());
    } else if (userIds.size() == 1) {
        usersConnectionRepository.createConnectionRepository(userIds.get(0)).updateConnection(connection);
        String originalUrl = signInAdapter.signIn(userIds.get(0), connection, request);
        return originalUrl != null ? redirect(originalUrl) : redirect(POST_SIGN_IN_URL);
    } else {
        log.error("Find more than one user with connection key: {}", connection.getKey());
        return redirectOnError(connection.getKey().getProviderId());
    }
}
 
开发者ID:xm-online,项目名称:xm-uaa,代码行数:17,代码来源:SocialController.java

示例5: findConnectionsToUsers

import org.springframework.social.connect.Connection; //导入依赖的package包/类
@Test
@SuppressWarnings("unchecked")
public void findConnectionsToUsers() {
    connectionFactoryRegistry.addConnectionFactory(new TestTwitterConnectionFactory());
    insertTwitterConnection();
    insertFacebookConnection();
    insertFacebookConnection2();
    MultiValueMap<String, String> providerUsers = new LinkedMultiValueMap<>();
    providerUsers.add("facebook", "10");
    providerUsers.add("facebook", "9");
    providerUsers.add("twitter", "1");
    MultiValueMap<String, Connection<?>> connectionsForUsers = connectionRepository.findConnectionsToUsers(providerUsers);
    assertEquals(2, connectionsForUsers.size());
    String providerId=connectionsForUsers.getFirst("facebook").getKey().getProviderUserId();
    assertTrue("10".equals(providerId) || "9".equals(providerId) );
    assertFacebookConnection((Connection<TestFacebookApi>) connectionRepository.getConnection(new ConnectionKey("facebook", "9")));
    assertTwitterConnection((Connection<TestTwitterApi>) connectionsForUsers.getFirst("twitter"));
}
 
开发者ID:xm-online,项目名称:xm-uaa,代码行数:19,代码来源:CustomSocialUsersConnectionRepositoryIntTest.java

示例6: viewModel

import org.springframework.social.connect.Connection; //导入依赖的package包/类
private DiscordConnectionVM viewModel(Connection<Discord> connection, boolean user, boolean guilds, boolean connections) {
    DiscordConnectionVM vm = new DiscordConnectionVM();
    vm.setUserId(connection.getKey().getProviderUserId());
    vm.setUsername(connection.getDisplayName());
    vm.setAvatarUrl(connection.getImageUrl());
    if (user) {
        UserProfile userProfile = connection.fetchUserProfile();
        vm.setNickname(userProfile.getFirstName() + "#" + userProfile.getLastName());
    }
    if (guilds) {
        vm.setGuilds(connection.getApi().userOperations().getGuilds());
    }
    if (connections) {
        vm.setConnections(connection.getApi().userOperations().getConnections());
    }
    return vm;
}
 
开发者ID:quanticc,项目名称:sentry,代码行数:18,代码来源:DiscordResource.java

示例7: facebook

import org.springframework.social.connect.Connection; //导入依赖的package包/类
@Bean
@ConditionalOnMissingBean(Facebook.class)
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
public Facebook facebook(ConnectionRepository repository) {
	Connection<Facebook> connection = repository
			.findPrimaryConnection(Facebook.class);
	return connection != null ? connection.getApi() : null;
}
 
开发者ID:PacktPublishing,项目名称:OAuth-2.0-Cookbook,代码行数:9,代码来源:FacebookConfiguration.java

示例8: signIn

import org.springframework.social.connect.Connection; //导入依赖的package包/类
@Override
public String signIn(String userId, Connection<?> connection, NativeWebRequest request){
    try {
        UserDetails user = userDetailsService.loadUserByUsername(userId);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
            user,
            null,
            user.getAuthorities());

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        String jwt = tokenProvider.createToken(authenticationToken, false);
        ServletWebRequest servletWebRequest = (ServletWebRequest) request;
        servletWebRequest.getResponse().addCookie(getSocialAuthenticationCookie(jwt));
    } catch (AuthenticationException exception) {
        log.error("Social authentication error");
    }
    return jHipsterProperties.getSocial().getRedirectAfterSignIn();
}
 
开发者ID:AppertaFoundation,项目名称:Code4Health-Platform,代码行数:19,代码来源:CustomSignInAdapter.java

示例9: signIn

import org.springframework.social.connect.Connection; //导入依赖的package包/类
@Override
public String signIn(String userId, Connection<?> connection, NativeWebRequest request){
    try {
        UserDetails user = userDetailsService.loadUserByUsername(userId);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
            user,
            null,
            user.getAuthorities());

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        String jwt = tokenProvider.createToken(authenticationToken, false);
        ServletWebRequest servletWebRequest = (ServletWebRequest) request;
        servletWebRequest.getResponse().addCookie(getSocialAuthenticationCookie(jwt));
    } catch (AuthenticationException ae) {
        log.error("Social authentication error");
        log.trace("Authentication exception trace: {}", ae);
    }
    return jHipsterProperties.getSocial().getRedirectAfterSignIn();
}
 
开发者ID:deepu105,项目名称:spring-io,代码行数:20,代码来源:CustomSignInAdapter.java

示例10: createRegistrationDTO

import org.springframework.social.connect.Connection; //导入依赖的package包/类
/**
 * Creates the form object used in the registration form.
 * @param connection
 * @return  If a user is signing in by using a social provider, this method returns a form
 *          object populated by the values given by the provider. Otherwise this method returns
 *          an empty form object (normal form registration).
 */
private RegistrationForm createRegistrationDTO(Connection<?> connection) {
    RegistrationForm dto = new RegistrationForm();

    if (connection != null) {
        UserProfile socialMediaProfile = connection.fetchUserProfile();
        dto.setEmail(socialMediaProfile.getEmail());
        dto.setFirstName(socialMediaProfile.getFirstName());
        dto.setLastName(socialMediaProfile.getLastName());

        ConnectionKey providerKey = connection.getKey();
        dto.setSignInProvider(SocialMediaService.valueOf(providerKey.getProviderId().toUpperCase()));
    }

    return dto;
}
 
开发者ID:eduyayo,项目名称:gamesboard,代码行数:23,代码来源:RegistrationController.java

示例11: createCalendarUserFromProvider

import org.springframework.social.connect.Connection; //导入依赖的package包/类
public static CalendarUser createCalendarUserFromProvider(Connection<?> connection){
    // TODO: FIXME: Need to put this into a Utility:
    UserProfile profile = connection.fetchUserProfile();

    CalendarUser user = new CalendarUser();

    if(profile.getEmail() != null){
        user.setEmail(profile.getEmail());
    }
    else if(profile.getUsername() != null){
        user.setEmail(profile.getUsername());
    }
    else {
        user.setEmail(connection.getDisplayName());
    }

    user.setFirstName(profile.getFirstName());
    user.setLastName(profile.getLastName());

    user.setPassword(randomAlphabetic(32));

    return user;

}
 
开发者ID:PacktPublishing,项目名称:Spring-Security-Third-Edition,代码行数:25,代码来源:SocialAuthenticationUtils.java

示例12: addProfile

import org.springframework.social.connect.Connection; //导入依赖的package包/类
/**
 * Add profile information to the model map.
 *
 * @param map
 *            the model map
 * @param principal
 *            the princial or <code>null</code>
 */
private void addProfile(ModelMap map, Principal principal) {
	if (principal != null) {
		Connection<?> connection = null;
		connection = connectionRepository.findPrimaryConnection(Twitter.class);
		if (connection == null)
			connection = connectionRepository.findPrimaryConnection(Google.class);
		if (connection == null)
			connection = connectionRepository.findPrimaryConnection(GitHub.class);
		if (connection != null) {
			map.addAttribute("profileImage", connection.getImageUrl());
			map.addAttribute("profile", connection.getProfileUrl());
		}
		Account findAccountByUsername = accountRepository.findOne(principal.getName());
		map.addAttribute(findAccountByUsername);
	}
}
 
开发者ID:Itema-as,项目名称:dawn-marketplace-server,代码行数:25,代码来源:AbstractController.java

示例13: findAllConnections

import org.springframework.social.connect.Connection; //导入依赖的package包/类
@Override
public MultiValueMap<String, Connection<?>> findAllConnections() {
    final List<SocialUserConnection> socialUserConnections
            = socialUserConnectionRepository.findAllByUserIdOrderByProviderIdAscRankAsc(userId);

    final List<Connection<?>> connections = socialUserConnectionsToConnections(socialUserConnections);

    final MultiValueMap<String, Connection<?>> connectionsByProviderId = new LinkedMultiValueMap<>();

    final Set<String> registeredProviderIds = connectionFactoryLocator.registeredProviderIds();

    registeredProviderIds.forEach(registeredProviderId -> connectionsByProviderId
            .put(registeredProviderId, Collections.emptyList()));

    connections.forEach(connection -> {
        final String providerId = connection.getKey().getProviderId();

        if (connectionsByProviderId.get(providerId).isEmpty()) {
            connectionsByProviderId.put(providerId, new LinkedList<>());
        }
        connectionsByProviderId.add(providerId, connection);
    });

    return connectionsByProviderId;
}
 
开发者ID:vlsidlyarevich,项目名称:unity,代码行数:26,代码来源:CustomSocialConnectionRepository.java

示例14: findConnectionsToUsers

import org.springframework.social.connect.Connection; //导入依赖的package包/类
@Override
public MultiValueMap<String, Connection<?>> findConnectionsToUsers(
        final MultiValueMap<String, String> providerUserIdsByProviderId) {

    if (Objects.isNull(providerUserIdsByProviderId) || providerUserIdsByProviderId.isEmpty()) {
        throw new IllegalArgumentException("Unable to execute find: no providerUsers provided");
    }

    final MultiValueMap<String, Connection<?>> connectionsForUsers = new LinkedMultiValueMap<>();

    providerUserIdsByProviderId.forEach((providerId, providerUserIds) -> {
        final List<Connection<?>> connections = providerUserIdsToConnections(providerId, providerUserIds);
        connections.forEach(connection -> connectionsForUsers.add(providerId, connection));
    });

    return connectionsForUsers;
}
 
开发者ID:vlsidlyarevich,项目名称:unity,代码行数:18,代码来源:CustomSocialConnectionRepository.java

示例15: connectionToUserSocialConnection

import org.springframework.social.connect.Connection; //导入依赖的package包/类
private SocialUserConnection connectionToUserSocialConnection(final Connection<?> connection,
                                                              final Long rank) {
    final ConnectionData connectionData = connection.createData();

    return SocialUserConnection.builder()
            .userId(userId)
            .providerId(connection.getKey().getProviderId())
            .providerUserId(connection.getKey().getProviderUserId())
            .rank(rank)
            .displayName(connection.getDisplayName())
            .profileURL(connection.getProfileUrl())
            .imageURL(connection.getImageUrl())
            .accessToken(connectionData.getAccessToken())
            .secret(connectionData.getSecret())
            .refreshToken(connectionData.getRefreshToken())
            .expireTime(connectionData.getExpireTime())
            .build();
}
 
开发者ID:vlsidlyarevich,项目名称:unity,代码行数:19,代码来源:CustomSocialConnectionRepository.java


注:本文中的org.springframework.social.connect.Connection类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。