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.quartercode.eventbridge.test.def.bridge.module.DefaultStandardHandlerModuleTest.java

@SuppressWarnings("unchecked")
@Test/*from   w  w w  .j ava2  s.  c  o  m*/
public void testCallHandlerWrongTypeInPredicate() {

    final EventPredicate<Event> predicate = context.mock(EventPredicate.class);
    final EventHandler<CallableEvent> handler = new EventHandler<CallableEvent>() {

        @Override
        public void handle(CallableEvent event) {

            // Provoke a ClassCastException
            event.call();
        }

    };

    final AtomicReference<LowLevelHandler> lowLevelHandler = new AtomicReference<>();

    // @formatter:off
    context.checking(new Expectations() {
        {

            oneOf(lowLevelHandlerModule).addHandler(with(aLowLevelHandlerWithThePredicate(predicate)));
            will(storeArgument(0).in(lowLevelHandler));

        }
    });
    // @formatter:on

    module.addHandler(handler, predicate);

    lowLevelHandler.get().handle(new EmptyEvent1(), null);
}

From source file:org.bpmscript.process.hibernate.SpringHibernateInstanceManagerTest.java

public void testInstanceManagerSeparateThread() throws Exception {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "/org/bpmscript/endtoend/spring.xml");
    try {/* ww  w.j  a  v  a2 s .c o  m*/

        final IInstanceManager instanceManager = (IInstanceManager) context.getBean("instanceManager");

        final String pid1 = instanceManager.createInstance("parentVersion", "definitionId", "test",
                IJavascriptProcessDefinition.DEFINITION_TYPE_JAVASCRIPT, "one");
        IInstance instance = instanceManager.getInstance(pid1);
        assertNotNull(instance);

        instanceManager.createInstance("parentVersion", "definitionId", "test",
                IJavascriptProcessDefinition.DEFINITION_TYPE_JAVASCRIPT, "two");
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        final AtomicReference<Queue<String>> results = new AtomicReference<Queue<String>>(
                new LinkedList<String>());
        Future<Object> future1 = executorService.submit(new Callable<Object>() {

            public Object call() throws Exception {
                return instanceManager.doWithInstance(pid1, new IInstanceCallback() {
                    public IExecutorResult execute(IInstance instance) throws Exception {
                        log.info("locking one");
                        Thread.sleep(2000);
                        results.get().add("one");
                        return new IgnoredResult("", "", "");
                    }
                });
            }

        });
        Thread.sleep(100);
        assertNotNull(future1.get());
    } finally {
        context.destroy();
    }
}

From source file:com.example.app.profile.ui.user.UserMembershipManagement.java

@Override
public void init() {
    super.init();

    final SearchSupplierImpl searchSupplier = getSearchSupplier();
    searchSupplier.setSearchUIOperationHandler(this);
    SearchUIImpl.Options options = new SearchUIImpl.Options("User Role Management");
    options.setSearchOnPageLoad(true);/*from w  w w .  j  a va 2  s.  co  m*/

    options.setSearchActions(Collections.emptyList());
    options.addSearchSupplier(searchSupplier);
    options.setHistory(getHistory());

    _searchUI = new SearchUIImpl(options);

    Menu menu = new Menu(CommonButtonText.ADD);
    menu.setTooltip(ConcatTextSource.create(CommonButtonText.ADD, MEMBERSHIP()).withSpaceSeparator());
    AppUtil.enableTooltip(menu);
    menu.addClassName("entity-action");
    AtomicReference<Integer> counter = new AtomicReference<>(0);
    final TimeZone tz = getSession().getTimeZone();
    getProfiles().forEach(profile -> {
        MenuItem subMenu = getProfileMenuItem(profile);
        User currentUser = _userDAO.getAssertedCurrentUser();
        if (_profileDAO.canOperate(currentUser, profile, tz, _mop.modifyUserRoles())) {
            counter.set(counter.get() + 1);
            menu.add(subMenu);
        }
    });

    menu.setVisible(counter.get() > 0);

    setDefaultComponent(of("search-wrapper user-role-search", of("entity-actions actions", menu), _searchUI));
}

From source file:com.dataflowdeveloper.processors.process.NLPProcessor.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    FlowFile flowFile = session.get();//ww  w .  j  a  v a2  s.c  om
    if (flowFile == null) {
        flowFile = session.create();
    }
    try {
        flowFile.getAttributes();

        service = new OpenNLPService();

        String sentence = flowFile.getAttribute(ATTRIBUTE_INPUT_NAME);
        String sentence2 = context.getProperty(ATTRIBUTE_INPUT_NAME).evaluateAttributeExpressions(flowFile)
                .getValue();

        if (sentence == null) {
            sentence = sentence2;
        }

        try {
            // if they pass in a sentence do that instead of flowfile
            if (sentence == null) {
                final AtomicReference<String> contentsRef = new AtomicReference<>(null);

                session.read(flowFile, new InputStreamCallback() {
                    @Override
                    public void process(final InputStream input) throws IOException {
                        final String contents = IOUtils.toString(input, "UTF-8");
                        contentsRef.set(contents);
                    }
                });

                // use this as our text
                if (contentsRef.get() != null) {
                    sentence = contentsRef.get();
                }
            }

            List<PersonName> people = service.getPeople(
                    context.getProperty(EXTRA_RESOURCE).evaluateAttributeExpressions(flowFile).getValue(),
                    sentence);

            int count = 1;
            for (PersonName personName : people) {
                flowFile = session.putAttribute(flowFile, "nlp_name_" + count, personName.getName());
                count++;
            }

            List<String> dates = service.getDates(
                    context.getProperty(EXTRA_RESOURCE).evaluateAttributeExpressions(flowFile).getValue(),
                    sentence);

            count = 1;
            for (String aDate : dates) {
                flowFile = session.putAttribute(flowFile, "nlp_date_" + count, aDate);
                count++;
            }

            List<Location> locations = service.getLocations(
                    context.getProperty(EXTRA_RESOURCE).evaluateAttributeExpressions(flowFile).getValue(),
                    sentence);

            count = 1;
            for (Location location : locations) {
                flowFile = session.putAttribute(flowFile, "nlp_location_" + count, location.getLocation());
                count++;
            }

        } catch (Exception e) {
            throw new ProcessException(e);
        }

        session.transfer(flowFile, REL_SUCCESS);
        session.commit();
    } catch (final Throwable t) {
        getLogger().error("Unable to process NLP Processor file " + t.getLocalizedMessage());
        getLogger().error("{} failed to process due to {}; rolling back session", new Object[] { this, t });
        throw t;
    }
}

From source file:com.jayway.restassured.module.mockmvc.ContentTypeTest.java

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

    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")));
                }/*ww  w.ja va  2  s. co m*/
            }).when().get("/greeting?name={name}", "Johan").then().statusCode(200);

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

From source file:org.killbill.billing.plugin.meter.api.user.JsonSamplesOutputer.java

private void writeJsonForStoredChunks(final JsonGenerator generator, final List<Integer> hostIdsList,
        final List<Integer> sampleKindIdsList, final DateTime startTime, final DateTime endTime)
        throws IOException {
    final AtomicReference<Integer> lastHostId = new AtomicReference<Integer>(null);
    final AtomicReference<Integer> lastSampleKindId = new AtomicReference<Integer>(null);
    final List<TimelineChunk> chunksForHostAndSampleKind = new ArrayList<TimelineChunk>();

    timelineDao.getSamplesBySourceIdsAndMetricIds(hostIdsList, sampleKindIdsList, startTime, endTime,
            new TimelineChunkConsumer() {
                @Override/*from  www  .  j  av a2 s .co  m*/
                public void processTimelineChunk(final TimelineChunk chunks) {
                    final Integer previousHostId = lastHostId.get();
                    final Integer previousSampleKindId = lastSampleKindId.get();
                    final Integer currentHostId = chunks.getSourceId();
                    final Integer currentSampleKindId = chunks.getMetricId();

                    chunksForHostAndSampleKind.add(chunks);
                    if (previousHostId != null && (!previousHostId.equals(currentHostId)
                            || !previousSampleKindId.equals(currentSampleKindId))) {
                        try {
                            writeJsonForChunks(generator, chunksForHostAndSampleKind);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                        chunksForHostAndSampleKind.clear();
                    }

                    lastHostId.set(currentHostId);
                    lastSampleKindId.set(currentSampleKindId);
                }
            }, context);

    if (chunksForHostAndSampleKind.size() > 0) {
        writeJsonForChunks(generator, chunksForHostAndSampleKind);
        chunksForHostAndSampleKind.clear();
    }
}

From source file:org.elasticsearch.test.rest.yaml.ClientYamlTestExecutionContextTests.java

public void testHeadersSupportStashedValueReplacement() throws IOException {
    final AtomicReference<Map<String, String>> headersRef = new AtomicReference<>();
    final ClientYamlTestExecutionContext context = new ClientYamlTestExecutionContext(null, randomBoolean()) {
        @Override//w ww .j  a v  a2s. c o  m
        ClientYamlTestResponse callApiInternal(String apiName, Map<String, String> params, HttpEntity entity,
                Map<String, String> headers) {
            headersRef.set(headers);
            return null;
        }
    };
    final Map<String, String> headers = new HashMap<>();
    headers.put("foo", "$bar");
    headers.put("foo1", "baz ${c}");

    context.stash().stashValue("bar", "foo2");
    context.stash().stashValue("c", "bar1");

    assertNull(headersRef.get());
    context.callApi("test", Collections.emptyMap(), Collections.emptyList(), headers);
    assertNotNull(headersRef.get());
    assertNotEquals(headers, headersRef.get());

    assertEquals("foo2", headersRef.get().get("foo"));
    assertEquals("baz bar1", headersRef.get().get("foo1"));
}

From source file:com.dgtlrepublic.anitomyj.Parser.java

/** Search for anime keywords. */
private void searchForKeywords() {
    for (int i = 0; i < tokens.size(); i++) {
        Token token = tokens.get(i);//  w ww . jav a 2  s  . com
        if (token.getCategory() != kUnknown)
            continue;

        String word = token.getContent();
        word = StringHelper.trimAny(word, " -");
        if (word.isEmpty())
            continue;

        // Don't bother if the word is a number that cannot be CRC
        if (word.length() != 8 && StringHelper.isNumericString(word))
            continue;

        String keyword = KeywordManager.normalzie(word);
        AtomicReference<ElementCategory> category = new AtomicReference<>(kElementUnknown);
        AtomicReference<KeywordOptions> options = new AtomicReference<>(new KeywordOptions());

        if (KeywordManager.getInstance().findAndSet(keyword, category, options)) {
            if (!this.options.parseReleaseGroup && category.get() == kElementReleaseGroup)
                continue;
            if (!ParserHelper.isElementCategorySearchable(category.get()) || !options.get().isSearchable())
                continue;
            if (ParserHelper.isElementCategorySingular(category.get()) && !empty(category.get()))
                continue;
            if (category.get() == kElementAnimeSeasonPrefix) {
                parserHelper.checkAndSetAnimeSeasonKeyword(token, i);
                continue;
            } else if (category.get() == kElementEpisodePrefix) {
                if (options.get().isValid()) {
                    parserHelper.checkExtentKeyword(kElementEpisodeNumber, i, token);
                    continue;
                }
            } else if (category.get() == kElementReleaseVersion) {
                word = StringUtils.substring(word, 1);
            } else if (category.get() == kElementVolumePrefix) {
                parserHelper.checkExtentKeyword(kElementVolumeNumber, i, token);
                continue;
            }
        } else {
            if (empty(kElementFileChecksum) && ParserHelper.isCrc32(word)) {
                category.set(kElementFileChecksum);
            } else if (empty(kElementVideoResolution) && ParserHelper.isResolution(word)) {
                category.set(kElementVideoResolution);
            }
        }

        if (category.get() != kElementUnknown) {
            elements.add(new Element(category.get(), word));
            if (options.get() != null && options.get().isIdentifiable()) {
                token.setCategory(kIdentifier);
            }
        }
    }
}

From source file:com.jayway.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>();

    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")));
                }//  www  .ja v a2 s .  c o m
            }).when().get("/greeting?name={name}", "Johan").then().statusCode(200);

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

From source file:com.jeremydyer.nifi.processors.google.GoogleSpeechProcessor.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    FlowFile flowFile = session.get();/*from   w ww . j ava 2s  . com*/
    if (flowFile == null) {
        return;
    }

    try {

        AtomicReference<String> image = new AtomicReference<>();

        session.read(flowFile, new InputStreamCallback() {
            @Override
            public void process(InputStream inputStream) throws IOException {
                byte[] bytes = IOUtils.toByteArray(inputStream);
                byte[] encImage = Base64.getEncoder().encode(bytes);
                image.set(new String(encImage));
            }
        });

        AnnotateImageRequest request = new AnnotateImageRequest()
                .setImage(new Image().setContent(new String(image.get()))).setFeatures(ImmutableList
                        .of(new Feature().setType("LANDMARK_DETECTION").setMaxResults(MAX_RESULTS)));

        Vision.Images.Annotate annotate = vision.images()
                .annotate(new BatchAnnotateImagesRequest().setRequests(ImmutableList.of(request)));

        BatchAnnotateImagesResponse batchResponse = annotate.execute();
        assert batchResponse.getResponses().size() == 1;
        AnnotateImageResponse response = batchResponse.getResponses().get(0);
        if (response.getLandmarkAnnotations() == null) {
            throw new IOException(response.getError() != null ? response.getError().getMessage()
                    : "Unknown error getting image annotations");
        }

        StringBuilder lndMarks = new StringBuilder();

        List<EntityAnnotation> landmarks = response.getLandmarkAnnotations();
        System.out.printf("Found %d landmark%s\n", landmarks.size(), landmarks.size() == 1 ? "" : "s");
        for (EntityAnnotation annotation : landmarks) {
            System.out.printf("\t%s\n", annotation.getDescription());
            lndMarks.append(annotation.getDescription());
            lndMarks.append(", ");
        }

        flowFile = session.putAttribute(flowFile, "landmarks", lndMarks.toString());

        session.transfer(flowFile, REL_SUCCESS);

    } catch (Exception ex) {
        ex.printStackTrace();
    }

}