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

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

Introduction

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

Prototype

public AtomicReference() 

Source Link

Document

Creates a new AtomicReference with null initial value.

Usage

From source file:com.networknt.basic.BasicAuthHandlerTest.java

@Test
public void testEncryptedPassword() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {/*from   w  w  w .ja  va 2s .  co  m*/
        connection = client.connect(new URI("http://localhost:17352"), Http2Client.WORKER, Http2Client.SSL,
                Http2Client.BUFFER_POOL, OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    try {
        ClientRequest request = new ClientRequest().setPath("/v2/pet").setMethod(Methods.GET);
        request.getRequestHeaders().put(Headers.HOST, "localhost");
        request.getRequestHeaders().put(Headers.AUTHORIZATION,
                "BASIC " + encodeCredentials("user2", "password"));
        connection.sendRequest(request, client.createClientCallback(reference, latch));
        latch.await();
    } catch (Exception e) {
        logger.error("Exception: ", e);
        throw new ClientException(e);
    } finally {
        IoUtils.safeClose(connection);
    }
    int statusCode = reference.get().getResponseCode();
    Assert.assertEquals(200, statusCode);
    if (statusCode == 200) {
        Assert.assertNotNull(reference.get().getAttachment(Http2Client.RESPONSE_BODY));
    }
}

From source file:com.cloudera.oryx.app.serving.als.model.ALSServingModel.java

/**
 * Creates an empty model./*from  w  w w .  j  a v  a 2 s .  c o m*/
 *
 * @param features number of features expected for user/item feature vectors
 * @param implicit whether model implements implicit feedback
 * @param sampleRate consider only approximately this fraction of all items when making recommendations.
 *  Candidates are chosen intelligently with locality sensitive hashing.
 * @param rescorerProvider optional instance of a {@link RescorerProvider}
 */
ALSServingModel(int features, boolean implicit, double sampleRate, RescorerProvider rescorerProvider) {
    Preconditions.checkArgument(features > 0);
    Preconditions.checkArgument(sampleRate > 0.0 && sampleRate <= 1.0);

    lsh = new LocalitySensitiveHash(sampleRate, features);

    X = new FeatureVectors();
    Y = new FeatureVectors[lsh.getNumPartitions()];
    for (int i = 0; i < Y.length; i++) {
        Y[i] = new FeatureVectors();
    }
    yPartitionMap = HashObjIntMaps.newMutableMap();
    yPartitionMapLock = new AutoReadWriteLock();

    knownItems = HashObjObjMaps.newMutableMap();
    knownItemsLock = new AutoReadWriteLock();

    expectedUserIDs = HashObjSets.newMutableSet();
    expectedUserIDsLock = new AutoReadWriteLock();
    expectedItemIDs = HashObjSets.newMutableSet();
    expectedItemIDsLock = new AutoReadWriteLock();

    cachedYTYSolver = new AtomicReference<>();

    this.features = features;
    this.implicit = implicit;
    this.rescorerProvider = rescorerProvider;
}

From source file:com.joyent.manta.client.MantaSeekableByteChannel.java

/**
 * Creates a new instance of a read-only seekable byte channel.
 *
 * @param path path of the object on the Manta API
 * @param position starting position in bytes from the start of the file
 * @param httpHelper helper class providing useful HTTP functions
 *//* w w  w .  j  ava 2s .  c  o m*/
public MantaSeekableByteChannel(final String path, final long position, final HttpHelper httpHelper) {
    this.path = path;
    this.position = new AtomicLong(position);
    this.httpHelper = httpHelper;
    this.requestRef = new AtomicReference<>();
    this.responseStream = new AtomicReference<>();
}

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 v  a  2  s  .c o 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:com.networknt.openapi.ValidatorHandlerTest.java

@Test
public void testInvalidMethod() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {// w w w .  j  a v a2  s. c o m
        connection = client.connect(new URI("http://localhost:8080"), Http2Client.WORKER, Http2Client.SSL,
                Http2Client.POOL, OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    try {
        ClientRequest request = new ClientRequest().setPath("/v1/pets").setMethod(Methods.DELETE);
        connection.sendRequest(request, client.createClientCallback(reference, latch));
        latch.await();
    } catch (Exception e) {
        logger.error("Exception: ", e);
        throw new ClientException(e);
    } finally {
        IoUtils.safeClose(connection);
    }
    int statusCode = reference.get().getResponseCode();
    Assert.assertEquals(405, statusCode);
    if (statusCode == 405) {
        Status status = Config.getInstance().getMapper()
                .readValue(reference.get().getAttachment(Http2Client.RESPONSE_BODY), Status.class);
        Assert.assertNotNull(status);
        Assert.assertEquals("ERR10008", status.getCode());
    }
}

From source file:com.jayway.restassured.itest.java.FilterITest.java

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

    given().filter(new Filter() {
        public Response filter(FilterableRequestSpecification requestSpec,
                FilterableResponseSpecification responseSpec, FilterContext ctx) {
            contentType.set(requestSpec.getRequestContentType());
            return ctx.next(requestSpec, responseSpec);
        }/*from w  ww  .ja  v a 2 s  .  co m*/
    }).formParam("firstName", "John").formParam("lastName", "Doe").when().post("/greet").then().statusCode(200);

    assertThat(contentType.get(), equalTo("application/x-www-form-urlencoded; charset=ISO-8859-1"));
}

From source file:io.restassured.itest.java.FilterITest.java

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

    given().filter(new Filter() {
        public Response filter(FilterableRequestSpecification requestSpec,
                FilterableResponseSpecification responseSpec, FilterContext ctx) {
            contentType.set(requestSpec.getContentType());
            return ctx.next(requestSpec, responseSpec);
        }// ww w.  j  a va2  s. c  o m
    }).formParam("firstName", "John").formParam("lastName", "Doe").when().post("/greet").then().statusCode(200);

    assertThat(contentType.get(), equalTo("application/x-www-form-urlencoded; charset=ISO-8859-1"));
}

From source file:com.splout.db.common.TestUtils.java

/**
 * Returns a DNode instance if, after a maximum of X trials, we can find a port to bind it to.
 * The configuration passed by instance might have been modified accordingly.
 *//*w w  w  . j a v a  2  s. c  om*/
public static DNode getTestDNode(final SploutConfiguration testConfig, final IDNodeHandler handler,
        final String dataFolder, boolean deleteDataFolder) throws Throwable {
    final AtomicReference<DNode> reference = new AtomicReference<DNode>();
    testConfig.setProperty(DNodeProperties.DATA_FOLDER, dataFolder);
    if (deleteDataFolder) {
        File file = new File(dataFolder);
        if (file.exists()) {
            FileUtils.deleteDirectory(file);
        }
        file.mkdir();
    }
    testConfig.setProperty(FetcherProperties.TEMP_DIR, "fetcher-" + dataFolder);
    File fetcherTmp = new File("fetcher-" + dataFolder);
    if (fetcherTmp.exists()) {
        FileUtils.deleteDirectory(fetcherTmp);
    }
    fetcherTmp.mkdir();
    CatchAndRetry dNodeInit = new CatchAndRetry(TTransportException.class, 50) {

        @Override
        public void businessLogic() throws Throwable {
            DNode dNode = new DNode(testConfig, handler);
            dNode.init();
            reference.set(dNode);
        }

        @Override
        public void retryLogic() {
            testConfig.setProperty(DNodeProperties.PORT, testConfig.getInt(DNodeProperties.PORT) + 1);
        }
    };
    dNodeInit.catchAndRetry();
    return reference.get();
}

From source file:com.github.jdye64.processors.provenance.ProvenanceEventsToPhoenix.java

@Override
public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {

    final FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;/*from   w  ww  .jav  a2  s . c  o m*/
    }

    String tableName = context.getProperty(PHOENIX_TABLE_NAME).evaluateAttributeExpressions(flowFile)
            .getValue();

    StringBuffer buffer = new StringBuffer();
    buffer.append(PREPEND_UPSERT);
    buffer.append(tableName);
    buffer.append(PROV_UPSERT_PREDICATES);
    buffer.append(PROV_PREP_VALUES);

    try {

        AtomicReference<JSONArray> provEvents = new AtomicReference<>();

        session.read(flowFile, new InputStreamCallback() {
            @Override
            public void process(InputStream in) throws IOException {
                StringWriter writer = new StringWriter();
                IOUtils.copy(in, writer, "UTF-8");
                provEvents.set(new JSONArray(writer.toString()));
            }
        });

        JSONArray events = provEvents.get();

        for (int i = 0; i < events.length(); i++) {
            JSONObject obj = events.getJSONObject(i);
            Map<String, String> attributes = generateAttributes(obj, tableName);

            FlowFile ff = session.write(session.clone(flowFile), new OutputStreamCallback() {
                @Override
                public void process(OutputStream out) throws IOException {
                    out.write(buffer.toString().getBytes());
                }
            });

            ff = session.putAllAttributes(ff, attributes);
            session.transfer(ff, REL_SUCCESS);
        }

        session.remove(flowFile);

    } catch (Exception ex) {
        getLogger().error("Error converting provenance event into Phoenix prepared statement {}",
                new Object[] { ex.getMessage() }, ex);
        session.transfer(flowFile, REL_FAILURE);
    }
}

From source file:io.undertow.server.handlers.sse.ServerSentEventTestCase.java

@Test
public void testProgressiveSSEWithCompression() throws IOException {
    final AtomicReference<ServerSentEventConnection> connectionReference = new AtomicReference<>();
    DecompressingHttpClient client = new DecompressingHttpClient(new TestHttpClient());
    try {// w  w w  .j av  a  2 s  .  c  o m

        DefaultServer.setRootHandler(new EncodingHandler(new ContentEncodingRepository()
                .addEncodingHandler("deflate", new DeflateEncodingProvider(), 50))
                        .setNext(new ServerSentEventHandler(new ServerSentEventConnectionCallback() {
                            @Override
                            public void connected(ServerSentEventConnection connection, String lastEventId) {
                                connectionReference.set(connection);
                                connection.send("msg 1", new ServerSentEventConnection.EventCallback() {
                                    @Override
                                    public void done(ServerSentEventConnection connection, String data,
                                            String event, String id) {

                                    }

                                    @Override
                                    public void failed(ServerSentEventConnection connection, String data,
                                            String event, String id, IOException e) {
                                        e.printStackTrace();
                                        IoUtils.safeClose(connection);
                                    }
                                });
                            }
                        })));

        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/");
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        InputStream stream = result.getEntity().getContent();
        assertData(stream, "data:msg 1\n\n");
        connectionReference.get().send("msg 2");
        assertData(stream, "data:msg 2\n\n");
        connectionReference.get().close();
    } finally {
        client.getConnectionManager().shutdown();
    }
}