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(V initialValue) 

Source Link

Document

Creates a new AtomicReference with the given initial value.

Usage

From source file:com.kixeye.janus.client.http.rest.DefaultRestHttpClientTest.java

@Test
public void getParamListTest() throws Exception {
    MetricRegistry metricRegistry = new MetricRegistry();
    Janus janus = new Janus(VIP_TEST, new ConstServerList(VIP_TEST, "http://localhost:" + server1Port),
            new ZoneAwareLoadBalancer(VIP_TEST, "default", metricRegistry),
            new ServerStatsFactory(ServerStats.class, metricRegistry));
    DefaultRestHttpClient client = new DefaultRestHttpClient(janus, 0, DefaultRestHttpClient.UTF8_STRING_SER_DE,
            "text/plain");

    final AtomicReference<String> requestMethod = new AtomicReference<>(null);
    final AtomicReference<String> requestPath = new AtomicReference<>(null);

    testContainer = new Container() {
        public void handle(Request req, Response resp) {
            requestMethod.set(req.getMethod());
            requestPath.set(req.getTarget());

            try {
                resp.getByteChannel().write(ByteBuffer.wrap("goofy".getBytes(StandardCharsets.UTF_8)));
            } catch (IOException e) {
                logger.error("Unable to write to channel.");
            }/*from  www. ja  v a  2s  .com*/
        }
    };

    String result = client.post("/test_params/{}", null, String.class, "goofy").getBody().deserialize();
    Assert.assertEquals("POST", requestMethod.get());
    Assert.assertEquals("/test_params/goofy", requestPath.get());
    Assert.assertEquals("goofy", result);
}

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

public void testInstanceManagerLocking() throws Exception {

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "/org/bpmscript/endtoend/spring.xml");

    try {/*from   ww w .  j av 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>());
        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);
        Future<Object> future2 = 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 two");
                        results.get().add("two");
                        return new IgnoredResult("", "", "");
                    }
                });
            }

        });
        future2.get();
        assertEquals(2, results.get().size());
        assertEquals("one", results.get().poll());
        assertEquals("two", results.get().poll());

    } finally {
        context.destroy();
    }
}

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 w  w  .  j  a va 2 s .c  o  m
        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.dataflowdeveloper.processors.process.NLPProcessor.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    FlowFile flowFile = session.get();//from www.j av  a 2s .c o m
    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:gobblin.compaction.dataset.Dataset.java

private Dataset(Builder builder) {
    this.inputPaths = builder.inputPaths;
    this.inputLatePaths = builder.inputLatePaths;
    this.outputPath = builder.outputPath;
    this.outputLatePath = builder.outputLatePath;
    this.outputTmpPath = builder.outputTmpPath;
    this.additionalInputPaths = Sets.newHashSet();
    this.throwables = Collections.synchronizedCollection(Lists.<Throwable>newArrayList());
    this.priority = builder.priority;
    this.lateDataThresholdForRecompact = builder.lateDataThresholdForRecompact;
    this.state = new AtomicReference<>(DatasetState.UNVERIFIED);
    this.datasetName = builder.datasetName;
    this.jobProps = builder.jobProps;
    this.renamePaths = builder.renamePaths;
}

From source file:info.archinnov.achilles.test.integration.tests.LWTOperationsIT.java

@Test
public void should_notify_listener_when_trying_to_insert_with_LWT_because_already_exist() throws Exception {
    //Given//from w  ww. j  ava  2  s. co m
    final AtomicReference<LWTResultListener.LWTResult> atomicLWTResult = new AtomicReference(null);
    LWTResultListener listener = new LWTResultListener() {
        @Override
        public void onSuccess() {
        }

        @Override
        public void onError(LWTResult lwtResult) {
            atomicLWTResult.compareAndSet(null, lwtResult);
        }
    };
    final EntityWithEnum entityWithEnum = new EntityWithEnum(10L, "name", EACH_QUORUM);
    Map<String, Object> expectedCurrentValues = ImmutableMap.<String, Object>of("id", 10L, "[applied]", false,
            "consistency_level", EACH_QUORUM.name(), "name", "name");
    manager.insert(entityWithEnum);

    manager.insert(entityWithEnum, OptionsBuilder.ifNotExists().lwtResultListener(listener));

    final LWTResultListener.LWTResult lwtResult = atomicLWTResult.get();
    assertThat(lwtResult.operation()).isEqualTo(INSERT);
    assertThat(lwtResult.currentValues()).isEqualTo(expectedCurrentValues);
    assertThat(lwtResult.toString()).isEqualTo(
            "CAS operation INSERT cannot be applied. Current values are: {[applied]=false, consistency_level=EACH_QUORUM, id=10, name=name}");
}

From source file:com.opengamma.examples.livedata.ExampleLiveDataServer.java

@Override
protected Map<String, Object> doSubscribe(Collection<String> uniqueIds) {
    ArgumentChecker.notNull(uniqueIds, "Subscriptions");
    Map<String, Object> result = Maps.newHashMap();
    List<String> missingSubscriptions = Lists.newArrayList();
    for (String uniqueId : uniqueIds) {
        if (!_marketValues.containsKey(uniqueId)) {
            missingSubscriptions.add(uniqueId);
        }/* w w  w .jav  a  2  s . c o  m*/
        result.put(uniqueId, new AtomicReference<String>(uniqueId));
    }
    if (!missingSubscriptions.isEmpty()) {
        s_logger.error("Could not subscribe to {}", missingSubscriptions);
    }
    return result;
}

From source file:com.dmbstream.android.service.RESTMusicService.java

private HttpResponse executeWithRetry(Context context, String url, HttpParams requestParams,
        List<String> parameterNames, List<Object> parameterValues, List<Header> headers,
        ProgressListener progressListener, CancellableTask task) throws IOException {
    Log.i(TAG, "Using URL " + url);

    final AtomicReference<Boolean> cancelled = new AtomicReference<Boolean>(false);
    int attempts = 0;
    while (true) {
        attempts++;/*from  ww w .ja v a  2s.  c  om*/
        HttpContext httpContext = new BasicHttpContext();
        final HttpPost request = new HttpPost(url);

        if (task != null) {
            // Attempt to abort the HTTP request if the task is cancelled.
            task.setOnCancelListener(new CancellableTask.OnCancelListener() {
                @Override
                public void onCancel() {
                    cancelled.set(true);
                    request.abort();
                }
            });
        }

        if (parameterNames != null) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            for (int i = 0; i < parameterNames.size(); i++) {
                params.add(
                        new BasicNameValuePair(parameterNames.get(i), String.valueOf(parameterValues.get(i))));
            }
            request.setEntity(new UrlEncodedFormEntity(params, Encoding.UTF_8.name()));
        }

        if (requestParams != null) {
            request.setParams(requestParams);
            Log.d(TAG, "Socket read timeout: " + HttpConnectionParams.getSoTimeout(requestParams) + " ms.");
        }

        if (headers != null) {
            for (Header header : headers) {
                request.addHeader(header);
            }
        }

        // Add default headers to identify this app
        request.addHeader("Content-Type", "application/json");
        request.addHeader("X-ApiKey", ApiConstants.instance().getApiKey());
        request.addHeader("User-Agent", ApiConstants.instance().getAppName());

        String userToken = Util.getUserToken(context);
        if (!ValidationHelper.isNullOrWhitespace(userToken))
            request.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(userToken, ""),
                    Encoding.UTF_8.name(), false));
        else
            Log.w(TAG, "No usertoken was specified for the request.");

        try {
            HttpResponse response = httpClient.execute(request, httpContext);
            return response;
        } catch (IOException x) {
            request.abort();
            if (attempts >= HTTP_REQUEST_MAX_ATTEMPTS || cancelled.get()) {
                throw x;
            }
            if (progressListener != null) {
                String msg = context.getResources().getString(R.string.music_service_retry, attempts,
                        HTTP_REQUEST_MAX_ATTEMPTS - 1);
                progressListener.updateProgress(msg);
            }
            Log.w(TAG, "Got IOException (" + attempts + "), will retry", x);
            increaseTimeouts(requestParams);
            Util.sleepQuietly(2000L);
        }
    }
}

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 ww  w  .j  ava  2s .c  o  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:gov.nih.nci.ncicb.tcga.dcc.common.util.IssueScanner.java

/**
 * Call this when you're done creating all the Issues.  This creates an output stream and writes out the beans one
 * by one calling each bean's toString() which returns a comma delimited string of the values contained in that
 * bean. This method also prints out the header of the file before looping over the beans.
 *
 * @throws java.io.IOException if we're not able to write the file out.
 *///from  www .  j a v  a 2s .com
private void writeCommaDelimitedFile() throws IOException {

    AtomicReference<BufferedWriter> out = null;
    FileWriter fileWriter = null;
    BufferedWriter bufferedWriter = null;
    try {
        // Create file
        //noinspection IOResourceOpenedButNotSafelyClosed
        fileWriter = new FileWriter(FILE_SYSTEM_LOCATION + "gforge-issues" + new Date().toString() + ".txt");
        final AtomicReference<FileWriter> fstream = new AtomicReference<FileWriter>(fileWriter);
        //noinspection IOResourceOpenedButNotSafelyClosed
        bufferedWriter = new BufferedWriter(fstream.get());
        out = new AtomicReference<BufferedWriter>(bufferedWriter);
        out.get().write(getHeader());
        for (final Issue anIssue : issueList) {
            out.get().write(anIssue.toString());
        }
    } finally {
        out.get().close();
        IOUtils.closeQuietly(fileWriter);
        IOUtils.closeQuietly(bufferedWriter);
    }
}