Example usage for java.util.concurrent.atomic AtomicReference get

List of usage examples for java.util.concurrent.atomic AtomicReference get

Introduction

In this page you can find the example usage for java.util.concurrent.atomic AtomicReference get.

Prototype

public final V get() 

Source Link

Document

Returns the current value, with memory effects as specified by VarHandle#getVolatile .

Usage

From source file:com.google.gdt.eclipse.designer.util.Utils.java

/**
 * @return the default locale from "set-property-fallback" property in module file.
 *///w ww  . j a v a 2 s  .  co m
public static String getDefaultLocale(ModuleDescription moduleDescription) throws Exception {
    final AtomicReference<String> defaultLocale = new AtomicReference<String>("default");
    ModuleVisitor.accept(moduleDescription, new ModuleVisitor() {
        @Override
        public void endVisitModule(ModuleElement module) {
            List<SetPropertyFallbackElement> elements = module.getSetPropertyFallbackElements();
            for (SetPropertyFallbackElement element : elements) {
                if (element.getName().equals("locale")) {
                    defaultLocale.set(element.getValue());
                }
            }
        }
    });
    return defaultLocale.get();
}

From source file:eu.eubrazilcc.lvl.oauth2.rest.LinkedInAuthz.java

@GET
@Path("callback")
public Response authorize(final @Context HttpServletRequest request) {
    final String code = parseQuery(request, "code");
    final String state = parseQuery(request, "state");
    final AtomicReference<String> redirectUriRef = new AtomicReference<String>(),
            callbackRef = new AtomicReference<String>();
    if (!LINKEDIN_STATE_DAO.isValid(state, redirectUriRef, callbackRef)) {
        throw new NotAuthorizedException(status(UNAUTHORIZED).build());
    }/*from  ww w.j  a va  2  s .co  m*/
    URI callback_uri = null;
    Map<String, String> map = null;
    try {
        final List<NameValuePair> form = form().add("grant_type", "authorization_code").add("code", code)
                .add("redirect_uri", redirectUriRef.get()).add("client_id", CONFIG_MANAGER.getLinkedInAPIKey())
                .add("client_secret", CONFIG_MANAGER.getLinkedInSecretKey()).build();
        // exchange authorization code for a request token
        final long issuedAt = currentTimeMillis() / 1000l;
        String response = Request.Post("https://www.linkedin.com/uas/oauth2/accessToken")
                .addHeader("Accept", "application/json").bodyForm(form).execute().returnContent().asString();
        map = JSON_MAPPER.readValue(response, new TypeReference<HashMap<String, String>>() {
        });
        final String accessToken = map.get("access_token");
        final long expiresIn = parseLong(map.get("expires_in"));
        checkState(isNotBlank(accessToken), "Uninitialized or invalid access token: " + accessToken);
        checkState(expiresIn > 0l, "Uninitialized or invalid expiresIn: " + expiresIn);
        // retrieve user profile data
        final URIBuilder uriBuilder = new URIBuilder(
                "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,industry,positions,email-address)");
        uriBuilder.addParameter("format", "json");
        response = Request.Get(uriBuilder.build()).addHeader("Authorization", "Bearer " + accessToken).execute()
                .returnContent().asString();
        final LinkedInMapper linkedInMapper = createLinkedInMapper().readObject(response);
        final String userId = linkedInMapper.getUserId();
        final String emailAddress = linkedInMapper.getEmailAddress();
        // register or update user in the database
        final String ownerid = toResourceOwnerId(LINKEDIN_IDENTITY_PROVIDER, userId);
        ResourceOwner owner = RESOURCE_OWNER_DAO.find(ownerid);
        if (owner == null) {
            final User user = User.builder().userid(userId).provider(LINKEDIN_IDENTITY_PROVIDER)
                    .email(emailAddress).password("password").firstname(linkedInMapper.getFirstName())
                    .lastname(linkedInMapper.getLastName()).industry(linkedInMapper.getIndustry().orNull())
                    .positions(linkedInMapper.getPositions().orNull()).roles(newHashSet(USER_ROLE))
                    .permissions(asPermissionSet(userPermissions(ownerid))).build();
            owner = ResourceOwner.builder().user(user).build();
            RESOURCE_OWNER_DAO.insert(owner);
        } else {
            owner.getUser().setEmail(emailAddress);
            owner.getUser().setFirstname(linkedInMapper.getFirstName());
            owner.getUser().setLastname(linkedInMapper.getLastName());
            owner.getUser().setIndustry(linkedInMapper.getIndustry().orNull());
            owner.getUser().setPositions(linkedInMapper.getPositions().orNull());
            RESOURCE_OWNER_DAO.update(owner);
        }
        // register access token in the database
        final AccessToken accessToken2 = AccessToken.builder().token(accessToken).issuedAt(issuedAt)
                .expiresIn(expiresIn).scope(asPermissionList(oauthScope(owner, false))).ownerId(ownerid)
                .build();
        TOKEN_DAO.insert(accessToken2);
        // redirect to default portal endpoint
        callback_uri = new URI(callbackRef.get() + "?email=" + urlEncodeUtf8(emailAddress) + "&access_token="
                + urlEncodeUtf8(accessToken));
    } catch (Exception e) {
        String errorCode = null, message = null, status = null;
        if (e instanceof IllegalStateException && map != null) {
            errorCode = map.get("errorCode");
            message = map.get("message");
            status = map.get("status");
        }
        LOGGER.error("Failed to authorize LinkedIn user [errorCode=" + errorCode + ", status=" + status
                + ", message=" + message + "]", e);
        throw new WebApplicationException(status(INTERNAL_SERVER_ERROR)
                .header("WWW-Authenticate", "Bearer realm='" + RESOURCE_NAME + "', error='invalid-code'")
                .build());
    } finally {
        LINKEDIN_STATE_DAO.delete(state);
    }
    return Response.seeOther(callback_uri).build();
}

From source file:org.eclipse.hono.adapter.http.AbstractVertxBasedHttpProtocolAdapter.java

private void cancelResponseTimer(final AtomicReference<Handler<Void>> cancelTimerHandlerRef) {
    Optional.ofNullable(cancelTimerHandlerRef.get()).map(cancelTimerHandler -> {
        cancelTimerHandler.handle(null);
        return null;
    });//from  w  w w . j  av  a  2  s .c om
}

From source file:org.eclipse.hono.adapter.http.AbstractVertxBasedHttpProtocolAdapter.java

private void closeCommandReceiverLink(final AtomicReference<MessageConsumer> messageConsumerRef) {
    Optional.ofNullable(messageConsumerRef.get()).map(messageConsumer -> {
        messageConsumer.close(v2 -> {
        });//  w w  w  .j  a  v  a  2 s  . c o  m
        return null;
    });
}

From source file:io.restassured.module.mockmvc.ContentTypeTest.java

@Test
public void adds_default_charset_to_content_type_by_default() {
    final AtomicReference<String> contentType = new AtomicReference<String>();

    RestAssuredMockMvc.given().standaloneSetup(new GreetingController()).contentType(ContentType.JSON)
            .interceptor(new MockHttpServletRequestBuilderInterceptor() {
                public void intercept(MockHttpServletRequestBuilder requestBuilder) {
                    MultiValueMap<String, Object> headers = Whitebox.getInternalState(requestBuilder,
                            "headers");
                    contentType.set(String.valueOf(headers.getFirst("Content-Type")));
                }/*from  ww  w.  ja v  a  2s.  com*/
            }).when().get("/greeting?name={name}", "Johan").then().statusCode(200);

    assertThat(contentType.get()).isEqualTo("application/json;charset="
            + RestAssuredMockMvc.config().getEncoderConfig().defaultContentCharset());
}

From source file:com.twitter.distributedlog.config.TestConfigurationSubscription.java

@Test(timeout = 60000)
public void testReloadConfiguration() throws Exception {
    PropertiesWriter writer = new PropertiesWriter();
    FileConfigurationBuilder builder = new PropertiesConfigurationBuilder(writer.getFile().toURI().toURL());
    ConcurrentConstConfiguration conf = new ConcurrentConstConfiguration(new DistributedLogConfiguration());
    DeterministicScheduler executorService = new DeterministicScheduler();
    List<FileConfigurationBuilder> fileConfigBuilders = Lists.newArrayList(builder);
    ConfigurationSubscription confSub = new ConfigurationSubscription(conf, fileConfigBuilders, executorService,
            100, TimeUnit.MILLISECONDS);
    final AtomicReference<ConcurrentBaseConfiguration> confHolder = new AtomicReference<>();
    confSub.registerListener(new com.twitter.distributedlog.config.ConfigurationListener() {
        @Override//from w ww .  j  ava 2 s.c o m
        public void onReload(ConcurrentBaseConfiguration conf) {
            confHolder.set(conf);
        }
    });
    assertEquals(null, conf.getProperty("prop1"));

    // add
    writer.setProperty("prop1", "1");
    writer.save();
    // ensure the file change reloading event can be triggered
    ensureConfigReloaded();
    // reload the config
    confSub.reload();
    assertNotNull(confHolder.get());
    assertTrue(conf == confHolder.get());
    assertEquals("1", conf.getProperty("prop1"));
}

From source file:com.microsoft.tfs.client.common.ui.teambuild.egit.dialogs.GitBuildDefinitionDialog.java

@Override
protected boolean searchForBuildFile(final boolean forceCheckForBuildFile) {
    if (super.searchForBuildFile(forceCheckForBuildFile)) {
        return true;
    } else {//  w  w w. ja  v a 2 s.  c o m
        final GitProjectFileControl gitProjectFileControl = projectFileTabPage.getControl();
        final String buildFileLocation = gitProjectFileControl.getConfigFolderText().getText();

        final GitRepositoriesMap repositoriesMap = getRepositoriesMap();
        final List<GitRepository> mappedRepositories = repositoriesMap.getMappedRepositories();

        gitProjectFileControl.clearProjectFileStatus();

        final AtomicReference<String> projectName = new AtomicReference<String>();
        final AtomicReference<String> repositoryName = new AtomicReference<String>();
        final AtomicReference<String> branchName = new AtomicReference<String>();
        final AtomicReference<String> path = new AtomicReference<String>();

        if (GitProperties.parseGitItemUrl(buildFileLocation, projectName, repositoryName, branchName, path)
                && projectName.get().equalsIgnoreCase(teamProjectName)) {
            for (final GitRepository repository : mappedRepositories) {
                if (repository.getName().equalsIgnoreCase(repositoryName.get())) {
                    gitProjectFileControl.setRepositoryCloned(true);

                    if (branchName.get().equalsIgnoreCase(repository.getCurrentBranch().getRemoteName())) {
                        gitProjectFileControl.setBranchCheckedOut(true);

                        final String configFolderLocalPath = LocalPath
                                .combine(repository.getWorkingDirectoryPath(), path.get());

                        localCopyExists = LocalPath.exists(
                                LocalPath.combine(configFolderLocalPath, BuildConstants.PROJECT_FILE_NAME));

                        gitProjectFileControl.setLocalCopyExists(localCopyExists);
                    }

                    break;
                }
            }
        }

        return false;
    }
}

From source file:org.zodiark.service.subscriber.SubscriberServiceImpl.java

@Override
public SubscriberEndpoint createSession(final Envelope e, AtmosphereResource r) {
    String uuid = e.getUuid();//from   w ww .  ja va 2  s  .c  om
    SubscriberEndpoint s = endpoints.get(uuid);
    if (s == null || !s.hasSession()) {
        s = createEndpoint(r, e.getMessage());
        endpoints.put(uuid, s);

        final AtomicReference<SubscriberEndpoint> subscriberEndpoint = new AtomicReference<>(s);
        eventBus.message(DB_ENDPOINT_STATE, new RetrieveMessage(s.uuid(), e.getMessage()),
                new Reply<EndpointState, String>() {

                    @Override
                    public void ok(EndpointState state) {
                        SubscriberEndpoint s = subscriberEndpoint.get();
                        // Subscriber will be deleted in case an error happens.
                        s.hasSession(true).state(state).publisherEndpoint(retrieve(state.publisherUUID()));
                        utils.statusEvent(DB_POST_SUBSCRIBER_SESSION_CREATE, e, s);
                    }

                    @Override
                    public void fail(ReplyException replyException) {
                        error(e, subscriberEndpoint.get(),
                                utils.constructMessage(DB_ENDPOINT_STATE, "error", e.getMessage().getUUID()));
                    }
                });
    } else {
        error(e, r, new Message().setPath("/error").setData("unauthorized"));
    }
    return s;
}

From source file:io.restassured.module.mockmvc.ContentTypeTest.java

@Test
public void doesnt_add_default_charset_to_content_type_if_charset_is_defined_explicitly() {
    final AtomicReference<String> contentType = new AtomicReference<String>();

    RestAssuredMockMvc.given().standaloneSetup(new GreetingController())
            .contentType(ContentType.JSON.withCharset("UTF-16"))
            .interceptor(new MockHttpServletRequestBuilderInterceptor() {
                public void intercept(MockHttpServletRequestBuilder requestBuilder) {
                    MultiValueMap<String, Object> headers = Whitebox.getInternalState(requestBuilder,
                            "headers");
                    contentType.set(String.valueOf(headers.getFirst("Content-Type")));
                }//from  www  .j a v  a 2  s .  co  m
            }).when().get("/greeting?name={name}", "Johan").then().statusCode(200);

    assertThat(contentType.get()).isEqualTo("application/json;charset=UTF-16");
}

From source file:de.sainth.recipe.backend.db.repositories.UnitRepository.java

public Unit save(Unit unit) {
    AtomicReference<Unit> bu = new AtomicReference<>();
    create.transaction(configuration -> {
        using(configuration)//from w ww  . jav  a 2 s . com
                .insertInto(UNITS, UNITS.SHORTNAME, UNITS.LONGNAME, UNITS.CONVERSION_FACTOR, UNITS.BASIC_UNIT)
                .values(unit.getShortname(), unit.getLongname(), unit.getConversionFactor(),
                        unit.getBasicUnit())
                .onConflict().doUpdate().set(UNITS.LONGNAME, unit.getLongname())
                .set(UNITS.CONVERSION_FACTOR, unit.getConversionFactor())
                .set(UNITS.BASIC_UNIT, unit.getBasicUnit()).execute();
        bu.set(using(configuration).selectFrom(UNITS).where(UNITS.SHORTNAME.eq(unit.getShortname()))
                .fetchOneInto(Unit.class));
    });

    return bu.get();
}