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

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

Introduction

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

Prototype

public final void set(V newValue) 

Source Link

Document

Sets the value to newValue , with memory effects as specified by VarHandle#setVolatile .

Usage

From source file:org.apache.tinkerpop.gremlin.structure.TransactionTest.java

@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.VERTICES_ONLY)
@FeatureRequirement(featureClass = Graph.Features.GraphFeatures.class, feature = Graph.Features.GraphFeatures.FEATURE_TRANSACTIONS)
@FeatureRequirement(featureClass = Graph.Features.GraphFeatures.class, feature = Graph.Features.GraphFeatures.FEATURE_PERSISTENCE)
public void shouldRollbackOnCloseByDefault() throws Exception {
    final AtomicReference<Object> oid = new AtomicReference<>();
    final AtomicReference<Vertex> vid = new AtomicReference<>();
    final Thread t = new Thread(() -> {
        vid.set(graph.addVertex("name", "stephen"));
        graph.tx().commit();/*from w  w  w . ja  v a 2 s  .  c  o m*/

        try (Transaction ignored = graph.tx()) {
            final Vertex v1 = graph.addVertex("name", "marko");
            oid.set(v1.id());
        }
    });
    t.start();
    t.join();

    // this was committed
    assertTrue(graph.vertices(vid.get().id()).hasNext());

    try {
        // this was not
        graph.vertices(oid.get()).next();
        fail("Vertex should not be found as close behavior was set to rollback");
    } catch (Exception ex) {
        validateException(Graph.Exceptions.elementNotFound(Vertex.class, oid), ex);
    }
}

From source file:com.facebook.RequestTests.java

@LargeTest
public void testShareOpenGraphContent() throws Exception {
    ShareOpenGraphObject ogObject = new ShareOpenGraphObject.Builder().putString("og:title", "a title")
            .putString("og:type", TEST_OG_OBJECT_TYPE).putString("og:description", "a description").build();

    ShareOpenGraphAction ogAction = new ShareOpenGraphAction.Builder().setActionType(TEST_OG_ACTION_TYPE)
            .putObject("test", ogObject).build();

    ShareOpenGraphContent content = new ShareOpenGraphContent.Builder().setAction(ogAction)
            .setPreviewPropertyName("test").build();

    final ShareApi shareApi = new ShareApi(content);
    final AtomicReference<String> actionId = new AtomicReference<>(null);

    getActivity().runOnUiThread(new Runnable() {
        @Override//from ww  w . j  ava 2  s.  c  om
        public void run() {
            shareApi.share(new FacebookCallback<Sharer.Result>() {
                @Override
                public void onSuccess(Sharer.Result result) {
                    actionId.set(result.getPostId());
                    notifyShareFinished();
                }

                @Override
                public void onCancel() {
                    notifyShareFinished();
                }

                @Override
                public void onError(FacebookException error) {
                    notifyShareFinished();
                }

                private void notifyShareFinished() {
                    synchronized (shareApi) {
                        shareApi.notifyAll();
                    }
                }
            });
        }
    });

    synchronized (shareApi) {
        shareApi.wait(REQUEST_TIMEOUT_MILLIS);
    }
    assertNotNull(actionId.get());
}

From source file:io.syndesis.jsondb.impl.SqlJsonDB.java

@Override
public Set<String> fetchIdsByPropertyValue(final String collectionPath, final String property,
        final String value) {
    final String pathRegex = collectionPath + "/:[^/]+/" + property;

    final AtomicReference<Set<String>> ret = new AtomicReference<>();
    withTransaction(dbi -> {//from  w  w  w  .java 2  s .com
        final String query;
        if (databaseKind == DatabaseKind.PostgreSQL) {
            query = "SELECT regexp_replace(path, '(/.+/:[^/]+).*', '\\1') from jsondb where path ~ ? and value = ?";
        } else if (databaseKind == DatabaseKind.H2) {
            query = "SELECT regexp_replace(path, '(/.+/:[^/]+).*', '$1') from jsondb where path regexp ? and value = ?";
        } else {
            throw new UnsupportedOperationException(
                    "Don't know how to use regex in a query with database: " + databaseKind);
        }

        final List<String> paths = dbi.createQuery(query).bind(0, pathRegex).bind(1, value)
                .map(StringColumnMapper.INSTANCE).list();

        ret.set(new HashSet<>(paths));
    });

    return ret.get();
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.TestAMRMTokens.java

@Test(timeout = 20000)
public void testAMRMMasterKeysUpdate() throws Exception {
    final AtomicReference<AMRMTokenSecretManager> spySecretMgrRef = new AtomicReference<AMRMTokenSecretManager>();
    MockRM rm = new MockRM(conf) {
        @Override//from w w  w.j a  v  a 2  s .  com
        protected void doSecureLogin() throws IOException {
            // Skip the login.
        }

        @Override
        protected RMSecretManagerService createRMSecretManagerService() {
            return new RMSecretManagerService(conf, rmContext) {
                @Override
                protected AMRMTokenSecretManager createAMRMTokenSecretManager(Configuration conf,
                        RMContext rmContext) {
                    AMRMTokenSecretManager spySecretMgr = spy(
                            super.createAMRMTokenSecretManager(conf, rmContext));
                    spySecretMgrRef.set(spySecretMgr);
                    return spySecretMgr;
                }
            };
        }
    };
    rm.start();
    MockNM nm = rm.registerNode("127.0.0.1:1234", 8000);
    RMApp app = rm.submitApp(200);
    MockAM am = MockRM.launchAndRegisterAM(app, rm, nm);
    AMRMTokenSecretManager spySecretMgr = spySecretMgrRef.get();
    // Do allocate. Should not update AMRMToken
    AllocateResponse response = am.allocate(Records.newRecord(AllocateRequest.class));
    Assert.assertNull(response.getAMRMToken());
    Token<AMRMTokenIdentifier> oldToken = rm.getRMContext().getRMApps().get(app.getApplicationId())
            .getRMAppAttempt(am.getApplicationAttemptId()).getAMRMToken();

    // roll over the master key
    // Do allocate again. the AM should get the latest AMRMToken
    rm.getRMContext().getAMRMTokenSecretManager().rollMasterKey();
    response = am.allocate(Records.newRecord(AllocateRequest.class));
    Assert.assertNotNull(response.getAMRMToken());

    Token<AMRMTokenIdentifier> amrmToken = ConverterUtils.convertFromYarn(response.getAMRMToken(),
            new Text(response.getAMRMToken().getService()));

    Assert.assertEquals(amrmToken.decodeIdentifier().getKeyId(),
            rm.getRMContext().getAMRMTokenSecretManager().getMasterKey().getMasterKey().getKeyId());

    // Do allocate again with the same old token and verify the RM sends
    // back the last generated token instead of generating it again.
    reset(spySecretMgr);
    UserGroupInformation ugi = UserGroupInformation
            .createUserForTesting(am.getApplicationAttemptId().toString(), new String[0]);
    ugi.addTokenIdentifier(oldToken.decodeIdentifier());
    response = am.doAllocateAs(ugi, Records.newRecord(AllocateRequest.class));
    Assert.assertNotNull(response.getAMRMToken());
    verify(spySecretMgr, never()).createAndGetAMRMToken(isA(ApplicationAttemptId.class));

    // Do allocate again with the updated token and verify we do not
    // receive a new token to use.
    response = am.allocate(Records.newRecord(AllocateRequest.class));
    Assert.assertNull(response.getAMRMToken());

    // Activate the next master key. Since there is new master key generated
    // in AMRMTokenSecretManager. The AMRMToken will not get updated for AM
    rm.getRMContext().getAMRMTokenSecretManager().activateNextMasterKey();
    response = am.allocate(Records.newRecord(AllocateRequest.class));
    Assert.assertNull(response.getAMRMToken());
    rm.stop();
}

From source file:org.apache.tinkerpop.gremlin.structure.TransactionTest.java

@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.VERTICES_ONLY)
@FeatureRequirement(featureClass = Graph.Features.GraphFeatures.class, feature = Graph.Features.GraphFeatures.FEATURE_TRANSACTIONS)
public void shouldAllowReferenceOfVertexIdOutsideOfOriginalThreadManual() throws Exception {
    g.tx().onReadWrite(Transaction.READ_WRITE_BEHAVIOR.MANUAL);
    g.tx().open();//  w  ww. j  a v  a 2s.com
    final Vertex v1 = graph.addVertex("name", "stephen");

    final AtomicReference<Object> id = new AtomicReference<>();
    final Thread t = new Thread(() -> {
        g.tx().open();
        id.set(v1.id());
    });

    t.start();
    t.join();

    assertEquals(v1.id(), id.get());

    g.tx().rollback();
}

From source file:org.apache.tinkerpop.gremlin.structure.TransactionTest.java

@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.SIMPLE)
@FeatureRequirement(featureClass = Graph.Features.GraphFeatures.class, feature = Graph.Features.GraphFeatures.FEATURE_TRANSACTIONS)
public void shouldAllowReferenceOfEdgeIdOutsideOfOriginalThreadManual() throws Exception {
    g.tx().onReadWrite(Transaction.READ_WRITE_BEHAVIOR.MANUAL);
    g.tx().open();/*from  ww  w  .j av  a2 s .co m*/
    final Vertex v1 = graph.addVertex();
    final Edge e = v1.addEdge("self", v1, "weight", 0.5d);

    final AtomicReference<Object> id = new AtomicReference<>();
    final Thread t = new Thread(() -> {
        g.tx().open();
        id.set(e.id());
    });

    t.start();
    t.join();

    assertEquals(e.id(), id.get());

    g.tx().rollback();
}

From source file:com.facebook.RequestTests.java

@LargeTest
public void testExecuteUploadPhotoToAlbum() throws InterruptedException, JSONException {
    // first create an album
    Bundle params = new Bundle();
    params.putString("name", "Foo");
    GraphRequest request = new GraphRequest(AccessToken.getCurrentAccessToken(), "me/albums", params,
            HttpMethod.POST);/* ww w  . j  av a  2s .  c om*/

    GraphResponse response = request.executeAndWait();
    JSONObject jsonResponse = response.getJSONObject();
    assertNotNull(jsonResponse);
    String albumId = jsonResponse.optString("id");
    assertNotNull(albumId);

    // upload an image to the album
    Bitmap image = createTestBitmap(128);
    SharePhoto photo = new SharePhoto.Builder().setBitmap(image).setUserGenerated(true).build();
    SharePhotoContent content = new SharePhotoContent.Builder().addPhoto(photo).build();
    final ShareApi shareApi = new ShareApi(content);
    shareApi.setGraphNode(albumId);
    final AtomicReference<String> imageId = new AtomicReference<>(null);
    getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            shareApi.share(new FacebookCallback<Sharer.Result>() {
                @Override
                public void onSuccess(Sharer.Result result) {
                    imageId.set(result.getPostId());
                    notifyShareFinished();
                }

                @Override
                public void onCancel() {
                    notifyShareFinished();
                }

                @Override
                public void onError(FacebookException error) {
                    notifyShareFinished();
                }

                private void notifyShareFinished() {
                    synchronized (shareApi) {
                        shareApi.notifyAll();
                    }
                }
            });
        }
    });

    synchronized (shareApi) {
        shareApi.wait(REQUEST_TIMEOUT_MILLIS);
    }
    assertNotNull(imageId.get());

    // now check to see if the image is in the album
    GraphRequest listRequest = new GraphRequest(AccessToken.getCurrentAccessToken(), albumId + "/photos");

    GraphResponse listResponse = listRequest.executeAndWait();
    JSONObject listObject = listResponse.getJSONObject();
    assertNotNull(listObject);
    JSONArray jsonList = listObject.optJSONArray("data");
    assertNotNull(jsonList);

    boolean found = false;
    for (int i = 0; i < jsonList.length(); i++) {
        JSONObject imageObject = jsonList.getJSONObject(i);
        if (imageId.get().equals(imageObject.optString("id"))) {
            found = true;
        }
    }
    assertTrue(found);
}

From source file:com.jeremydyer.nifi.ObjectDetectionProcessor.java

final public Mat detectObjects(final ProcessSession session, FlowFile original, final JSONObject dd,
        final Mat image) {

    CascadeClassifier objectDetector = new CascadeClassifier(dd.getString("opencv_xml_cascade_path"));
    MatOfRect objectDetections = new MatOfRect();
    objectDetector.detectMultiScale(image, objectDetections);
    //getLogger().error("Detected " + objectDetections.toArray().length + " " + dd.getString("name") + " objects in the input flowfile");

    final AtomicReference<Mat> croppedImageReference = new AtomicReference<>();

    int counter = 0;
    for (int i = 0; i < objectDetections.toArray().length; i++) {
        final Rect rect = objectDetections.toArray()[i];
        FlowFile detection = session.write(session.create(original), new OutputStreamCallback() {
            @Override//from  w  ww . j  av a2 s  .c  o m
            public void process(OutputStream outputStream) throws IOException {

                Mat croppedImage = null;

                //Should the image be cropped? If so there is no need to draw bounds because that would be the same as the cropping
                if (dd.getBoolean("crop")) {
                    Rect rectCrop = new Rect(rect.x, rect.y, rect.width, rect.height);
                    croppedImage = new Mat(image, rectCrop);
                    MatOfByte updatedImage = new MatOfByte();
                    Imgcodecs.imencode(".jpg", croppedImage, updatedImage);
                    croppedImageReference.set(croppedImage);
                    outputStream.write(updatedImage.toArray());
                } else {
                    //Should the image have a border drawn around it?
                    if (dd.getBoolean("drawBounds")) {
                        Mat imageWithBorder = image.clone();
                        Imgproc.rectangle(imageWithBorder, new Point(rect.x, rect.y),
                                new Point(rect.x + rect.width, rect.y + rect.height),
                                new Scalar(255, 255, 255));
                        MatOfByte updatedImage = new MatOfByte();
                        Imgcodecs.imencode(".jpg", imageWithBorder, updatedImage);
                        outputStream.write(updatedImage.toArray());
                    } else {
                        MatOfByte updatedImage = new MatOfByte();
                        Imgcodecs.imencode(".jpg", image, updatedImage);
                        outputStream.write(updatedImage.toArray());
                    }
                }

            }
        });

        Map<String, String> atts = new HashMap<>();
        atts.put("object.detection.name", dd.getString("name"));
        atts.put("object.detection.id", new Long(System.currentTimeMillis() + counter).toString());

        counter++;

        detection = session.putAllAttributes(detection, atts);
        session.transfer(detection, REL_OBJECT_DETECTED);
    }

    Mat childResponse = null;

    if (croppedImageReference.get() != null) {
        childResponse = croppedImageReference.get();
    } else {
        childResponse = image;
    }

    if (dd.has("children")) {
        JSONArray children = dd.getJSONArray("children");
        if (children != null) {

            for (int i = 0; i < children.length(); i++) {
                JSONObject ddd = children.getJSONObject(i);
                childResponse = detectObjects(session, original, ddd, childResponse);
            }
        }
    }

    return childResponse;
}

From source file:com.facebook.RequestTests.java

@LargeTest
public void testUploadVideoFile() throws IOException, URISyntaxException {
    File tempFile = null;/*  w w  w.j  a  v a  2s.co m*/
    try {
        tempFile = createTempFileFromAsset("DarkScreen.mov");
        ShareVideo video = new ShareVideo.Builder().setLocalUrl(Uri.fromFile(tempFile)).build();
        ShareVideoContent content = new ShareVideoContent.Builder().setVideo(video).build();
        final ShareApi shareApi = new ShareApi(content);
        final AtomicReference<String> videoId = new AtomicReference<>(null);
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                shareApi.share(new FacebookCallback<Sharer.Result>() {
                    @Override
                    public void onSuccess(Sharer.Result result) {
                        videoId.set(result.getPostId());
                        notifyShareFinished();
                    }

                    @Override
                    public void onCancel() {
                        notifyShareFinished();
                    }

                    @Override
                    public void onError(FacebookException error) {
                        notifyShareFinished();
                    }

                    private void notifyShareFinished() {
                        synchronized (shareApi) {
                            shareApi.notifyAll();
                        }
                    }
                });
            }
        });

        synchronized (shareApi) {
            shareApi.wait(REQUEST_TIMEOUT_MILLIS);
        }
        assertNotNull(videoId.get());
    } catch (Exception ex) {
        fail();
    } finally {
        if (tempFile != null) {
            tempFile.delete();
        }
    }
}

From source file:net.java.sip.communicator.impl.googlecontacts.OAuth2TokenStore.java

/**
 * Create credential instance suitable for use in Google Contacts API.
 * /*from   w ww.  ja  v  a2s  . co m*/
 * @param store reference to the credential store for updating credential
 *            data upon refreshing and other cases
 * @param approvalCode the approval code received from Google by the user
 *            accepting the authorization request
 * @return Returns a Credential instance.
 * @throws URISyntaxException In case of bad OAuth 2 redirect URI.
 */
private static Credential createCredential(final AtomicReference<Credential> store, final TokenData data)
        throws URISyntaxException {
    final Credential.Builder builder = new Credential.Builder(BearerToken.authorizationHeaderAccessMethod());
    builder.setTokenServerUrl(GOOGLE_OAUTH2_TOKEN_SERVER);
    builder.setTransport(new NetHttpTransport());
    builder.setJsonFactory(new JacksonFactory());
    builder.setClientAuthentication(new HttpExecuteInterceptor() {

        @Override
        public void intercept(HttpRequest request) throws IOException {
            final Object data = ((UrlEncodedContent) request.getContent()).getData();
            if (data instanceof RefreshTokenRequest) {
                // Inject client authentication credentials in requests.
                final RefreshTokenRequest content = (RefreshTokenRequest) data;
                content.put("client_id", GOOGLE_API_CLIENT_ID);
                content.put("client_secret", GOOGLE_API_CLIENT_SECRET);
                LOGGER.info("Inserting client authentication data into " + "refresh token request.");
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Request: " + content.toString());
                }
            } else {
                LOGGER.debug("Unexpected type of request found.");
            }
        }
    });
    builder.addRefreshListener(new CredentialRefreshListener() {

        @Override
        public void onTokenResponse(Credential credential, TokenResponse tokenResponse) throws IOException {
            LOGGER.debug("Successful token refresh response: " + tokenResponse.toPrettyString());
            store.set(credential);
        }

        @Override
        public void onTokenErrorResponse(Credential credential, TokenErrorResponse tokenErrorResponse)
                throws IOException {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Failed token refresh response: " + tokenErrorResponse.toPrettyString());
            }
            LOGGER.error("Failed to refresh OAuth2 token: " + tokenErrorResponse.getError() + ": "
                    + tokenErrorResponse.getErrorDescription());
        }
    });
    final Credential credential = builder.build();
    credential.setAccessToken(data.accessToken);
    credential.setRefreshToken(data.refreshToken);
    credential.setExpiresInSeconds(data.expiration);
    return credential;
}