List of usage examples for java.util.concurrent.atomic AtomicReference set
public final void set(V newValue)
From source file:de.hybris.platform.test.HJMPTest.java
private AtomicReference<Boolean> startPKLookupInOtherThread(final PK pk) { final Tenant tenant = Registry.getCurrentTenantNoFallback(); final AtomicReference<Boolean> success = new AtomicReference<Boolean>(null); final Thread thread = new Thread() { @Override//from w w w . j a v a 2 s. c o m public void run() { Registry.setCurrentTenant(tenant); try { assertNotNull(SystemEJB.getInstance().findRemoteObjectByPK(pk)); success.set(Boolean.TRUE); } catch (final EJBItemNotFoundException e) { success.set(Boolean.FALSE); } catch (final Exception e) { success.set(Boolean.FALSE); fail(e.getMessage()); } } }; thread.start(); return success; }
From source file:org.apache.nifi.hbase.ScanHBase.java
private FlowFile initNewFlowFile(final ProcessSession session, final FlowFile origFF, final String tableName) throws IOException { FlowFile flowFile = session.create(origFF); flowFile = session.putAttribute(flowFile, HBASE_TABLE_ATTR, tableName); flowFile = session.putAttribute(flowFile, CoreAttributes.MIME_TYPE.key(), "application/json"); final AtomicReference<IOException> ioe = new AtomicReference<>(null); flowFile = session.write(flowFile, (out) -> { try {/* w w w. jav a2 s . c om*/ out.write("[".getBytes()); } catch (IOException e) { ioe.set(e); } }); if (ioe.get() != null) { throw ioe.get(); } return flowFile; }
From source file:org.apache.nifi.hbase.ScanHBase.java
private void finalizeFlowFile(final ProcessSession session, final HBaseClientService hBaseClientService, FlowFile flowFile, final String tableName, Long rowsPulled, Exception e) { Relationship rel = REL_SUCCESS;/* w ww.j a v a 2s. c o m*/ flowFile = session.putAttribute(flowFile, HBASE_ROWS_COUNT_ATTR, rowsPulled.toString()); final AtomicReference<IOException> ioe = new AtomicReference<>(null); flowFile = session.append(flowFile, (out) -> { try { out.write("]".getBytes()); } catch (IOException ei) { ioe.set(ei); } }); if (e != null || ioe.get() != null) { flowFile = session.putAttribute(flowFile, "scanhbase.error", (e == null ? e : ioe.get()).toString()); rel = REL_FAILURE; } else { session.getProvenanceReporter().receive(flowFile, hBaseClientService.toTransitUri(tableName, "{ids}")); } session.transfer(flowFile, rel); }
From source file:io.pravega.client.stream.impl.ReaderGroupStateManager.java
private Map<Segment, Long> acquireSegment(long timeLag) throws ReinitializationRequiredException { AtomicReference<Map<Segment, Long>> result = new AtomicReference<>(); AtomicBoolean reinitRequired = new AtomicBoolean(false); sync.updateState(state -> {/*from www . j a v a 2 s . c om*/ if (!state.isReaderOnline(readerId)) { reinitRequired.set(true); return null; } int toAcquire = calculateNumSegmentsToAcquire(state); if (toAcquire == 0) { result.set(Collections.emptyMap()); return null; } Map<Segment, Long> unassignedSegments = state.getUnassignedSegments(); Map<Segment, Long> acquired = new HashMap<>(toAcquire); List<ReaderGroupStateUpdate> updates = new ArrayList<>(toAcquire); Iterator<Entry<Segment, Long>> iter = unassignedSegments.entrySet().iterator(); for (int i = 0; i < toAcquire; i++) { assert iter.hasNext(); Entry<Segment, Long> segment = iter.next(); acquired.put(segment.getKey(), segment.getValue()); updates.add(new AcquireSegment(readerId, segment.getKey())); } updates.add(new UpdateDistanceToTail(readerId, timeLag)); result.set(acquired); return updates; }); if (reinitRequired.get()) { throw new ReinitializationRequiredException(); } acquireTimer.reset(calculateAcquireTime(sync.getState())); return result.get(); }
From source file:org.zodiark.subscriber.SubscriberTest.java
@Test(enabled = false) public void sucessfulRequestForAction() throws IOException, InterruptedException { final CountDownLatch completed = new CountDownLatch(1); final ZodiarkClient wowzaClient = new ZodiarkClient.Builder().path("http://127.0.0.1:" + port).build(); final CountDownLatch connected = new CountDownLatch(1); final AtomicReference<String> uuid = new AtomicReference<>(); final AtomicReference<String> paths = new AtomicReference<>(); // =============== Wowza paths.set(""); wowzaClient.handler(new OnEnvelopHandler() { @Override/*from w ww. j ava 2 s . co m*/ public boolean onEnvelop(Envelope e) throws IOException { Message m = e.getMessage(); switch (m.getPath()) { case Paths.WOWZA_CONNECT: // Connected. Listen uuid.set(e.getUuid()); break; case Paths.SERVER_VALIDATE_OK: Envelope publisherOk = Envelope.newClientToServerRequest(e.getUuid(), new Message(new Path(paths.get()), e.getMessage().getData())); wowzaClient.send(publisherOk); break; case Paths.WOWZA_OBFUSCATE: WowzaMessage wm = mapper.readValue(m.getData(), WowzaMessage.class); Envelope ok = Envelope.newClientToServerRequest(e.getUuid(), new Message(new Path(Paths.WOWZA_OBFUSCATE_OK), e.getMessage().getData())); System.out.println("Obfuscating Subscribers"); wowzaClient.send(ok); case Paths.WOWZA_DEOBFUSCATE: wm = mapper.readValue(m.getData(), WowzaMessage.class); System.out.println("De-obfuscating Subscribers"); ok = Envelope.newClientToServerRequest(e.getUuid(), new Message(new Path(Paths.WOWZA_DEOBFUSCATE_OK), e.getMessage().getData())); wowzaClient.send(ok); default: // ERROR } connected.countDown(); return false; } }).open(); Envelope wowzaConnect = Envelope.newClientToServerRequest(new Message(new Path(Paths.WOWZA_CONNECT), mapper.writeValueAsString(new UserPassword("wowza", "bar")))); wowzaClient.send(wowzaConnect); connected.await(); // ================ Publisher final AtomicReference<PublisherResults> answer = new AtomicReference<>(); final ZodiarkClient publisherClient = new ZodiarkClient.Builder().path("http://127.0.0.1:" + port).build(); final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<String> publisherUUID = new AtomicReference<>(); publisherClient.handler(new OnEnvelopHandler() { @Override public boolean onEnvelop(Envelope e) throws IOException { answer.set(mapper.readValue(e.getMessage().getData(), PublisherResults.class)); publisherUUID.set(e.getUuid()); latch.countDown(); return true; } }).open(); // ================ Publisher create the session Envelope createSessionMessage = Envelope.newClientToServerRequest( new Message(new Path(""), mapper.writeValueAsString(new UserPassword("publisherex", "bar")))); createSessionMessage.setFrom(new From(ActorValue.PUBLISHER)); publisherClient.send(createSessionMessage); latch.await(); assertEquals("OK", answer.get().getResults()); answer.set(null); final CountDownLatch tlatch = new CountDownLatch(1); final AtomicReference<String> finalMessage = new AtomicReference<>(); publisherClient.handler(new OnEnvelopHandler() { @Override public boolean onEnvelop(Envelope e) throws IOException { switch (e.getMessage().getPath()) { case Paths.BEGIN_STREAMING_SESSION: answer.set(mapper.readValue(e.getMessage().getData(), PublisherResults.class)); tlatch.countDown(); break; case Paths.PUBLISHER_ACTION_ACCEPT: Action a = mapper.readValue(e.getMessage().getData(), Action.class); Envelope publisherOk = Envelope.newClientToServerRequest(e.getUuid(), new Message(new Path(Paths.ZODIARK_ACTION_ACCEPTED), e.getMessage().getData())); publisherClient.send(publisherOk); break; case Paths.ACTION_START: // Start action PublisherResults results = mapper.readValue(e.getMessage().getData(), PublisherResults.class); System.out.println("==> Start Action " + results.getResults()); publisherOk = Envelope.newClientToServerRequest(e.getUuid(), new Message(new Path(Paths.ACTION_START_OK), e.getMessage().getData())); publisherClient.send(publisherOk); break; case Paths.ACTION_TIMER: Time t = mapper.readValue(e.getMessage().getData(), Time.class); System.out.println("Publisher ===>" + t); break; case Paths.ACTION_COMPLETED: results = mapper.readValue(e.getMessage().getData(), PublisherResults.class); System.out.println("Publisher Action completed"); completed.countDown(); break; case Paths.PUBLISHER_ABOUT_READY: results = mapper.readValue(e.getMessage().getData(), PublisherResults.class); finalMessage.set(results.getResults()); break; } return false; } }); // ================ Prepare for streaming, handshake with Wowza Envelope startStreamingSession = Envelope .newClientToServerRequest(new Message(new Path(Paths.VALIDATE_PUBLISHER_STREAMING_SESSION), mapper.writeValueAsString(new WowzaUUID(uuid.get())))); createSessionMessage.setFrom(new From(ActorValue.PUBLISHER)); publisherClient.send(startStreamingSession); tlatch.await(); assertEquals("OK", answer.get().getResults()); // ================ Subscriber paths.set(Paths.JOIN_SUBSCRIBER_STREAMING_SESSION); final AtomicReference<SubscriberResults> sanswer = new AtomicReference<>(); final ZodiarkClient subscriberClient = new ZodiarkClient.Builder().path("http://127.0.0.1:" + port).build(); final CountDownLatch platch = new CountDownLatch(1); final AtomicReference<String> subscriberUUID = new AtomicReference<>(); subscriberClient.handler(new OnEnvelopHandler() { @Override public boolean onEnvelop(Envelope e) throws IOException { sanswer.set(mapper.readValue(e.getMessage().getData(), SubscriberResults.class)); subscriberUUID.set(e.getUuid()); platch.countDown(); return true; } }).open(); // ================ Subscriber create the session createSessionMessage = Envelope.newClientToServerRequest(subscriberUUID.get(), new Message(new Path(Paths.DB_POST_SUBSCRIBER_SESSION_CREATE), mapper.writeValueAsString(new UserPassword("123456", "bar")))); createSessionMessage.setFrom(new From(ActorValue.SUBSCRIBER)); subscriberClient.send(createSessionMessage); platch.await(); assertEquals("OK", sanswer.get().getResults()); sanswer.set(null); final CountDownLatch elatch = new CountDownLatch(1); subscriberClient.handler(new OnEnvelopHandler() { @Override public boolean onEnvelop(Envelope e) throws IOException { sanswer.set(mapper.readValue(e.getMessage().getData(), SubscriberResults.class)); elatch.countDown(); return true; } }); // ================ Join the Publisher Session StreamingRequest request = new StreamingRequestImpl(publisherUUID.get(), uuid.get()); startStreamingSession = Envelope.newClientToServerRequest(subscriberUUID.get(), new Message( new Path(Paths.VALIDATE_SUBSCRIBER_STREAMING_SESSION), mapper.writeValueAsString(request))); startStreamingSession.setFrom(new From(ActorValue.SUBSCRIBER)); subscriberClient.send(startStreamingSession); elatch.await(); assertEquals("OK", sanswer.get().getResults()); // ================ Ask for an Action the Publisher Session Action action = new Action(); action.setPath("/action/doSomething"); action.setData("{ \"foo\":\"bar\""); Envelope e = Envelope.newClientToServerRequest(subscriberUUID.get(), new Message(new Path(Paths.SUBSCRIBER_ACTION), mapper.writeValueAsString(action))); e.setFrom(new From(ActorValue.SUBSCRIBER)); final CountDownLatch actionLatch = new CountDownLatch(1); final AtomicReference<Envelope> response = new AtomicReference<>(); final AtomicBoolean timerCalled = new AtomicBoolean(); subscriberClient.handler(new OnEnvelopHandler() { @Override public boolean onEnvelop(Envelope e) throws IOException { switch (e.getMessage().getPath()) { case Paths.MESSAGE_ACTION_VALIDATE: response.set(e); actionLatch.countDown(); break; case Paths.ACTION_TIMER: Time t = mapper.readValue(e.getMessage().getData(), Time.class); System.out.println("Subscriber ===>" + t); timerCalled.set(true); break; case Paths.ACTION_COMPLETED: SubscriberResults results = mapper.readValue(e.getMessage().getData(), SubscriberResults.class); System.out.println("Action completed"); break; } return false; } }); subscriberClient.send(e); actionLatch.await(); assertEquals(Paths.MESSAGE_ACTION_VALIDATE, response.get().getMessage().getPath()); assertEquals("{\"results\":\"OK\",\"uuid\":null}", response.get().getMessage().getData()); completed.await(); assertTrue(timerCalled.get()); assertEquals("READY", finalMessage.get()); }
From source file:fr.pilato.elasticsearch.crawler.fs.test.integration.ElasticsearchClientIT.java
@Test public void testBulkWithErrors() throws IOException, InterruptedException { // Create the index first elasticsearchClient.createIndex(getCrawlerName()); elasticsearchClient.waitForHealthyIndex(getCrawlerName()); AtomicReference<BulkResponse> bulkResponse = new AtomicReference<>(); BulkProcessor bulkProcessor = new BulkProcessor.Builder(elasticsearchClient, new BulkProcessor.Listener() { @Override/*from w w w . j a va2 s .c o m*/ public void beforeBulk(long executionId, BulkRequest request) { } @Override public void afterBulk(long executionId, BulkRequest request, BulkResponse response) { bulkResponse.set(response); } @Override public void afterBulk(long executionId, BulkRequest request, Throwable failure) { } }).setBulkActions(100).setFlushInterval(TimeValue.timeValueMillis(200)).build(); bulkProcessor.add( new IndexRequest(getCrawlerName(), FsCrawlerUtil.INDEX_TYPE_DOC, "id").source("{\"foo\":\"bar\"")); bulkProcessor.close(); BulkResponse response = bulkResponse.get(); Throwable message = response.buildFailureMessage(); assertThat(message.getMessage(), containsString("1 failures")); // If we run the test with a TRACE level, we can check more things if (LogManager.getLogger(BulkResponse.class).isTraceEnabled()) { assertThat(message.getMessage(), containsString("failed to parse")); } }
From source file:it.reyboz.bustorino.backend.GTTJSONFetcher.java
@Override @NonNull//from www .ja va 2 s.c o m public Palina ReadArrivalTimesAll(String stopID, AtomicReference<result> res) { URL url; Palina p = new Palina(stopID); String routename; String bacino; String content; JSONArray json; int howManyRoutes, howManyPassaggi, i, j, pos; // il misto inglese-italiano un po' ridicolo ma tanto vale... JSONObject thisroute; JSONArray passaggi; try { url = new URL("http://www.gtt.to.it/cms/index.php?option=com_gtt&task=palina.getTransiti&palina=" + URLEncoder.encode(stopID, "utf-8") + "&realtime=true"); } catch (Exception e) { res.set(result.PARSER_ERROR); return p; } content = networkTools.queryURL(url, res); if (content == null) { return p; } try { json = new JSONArray(content); } catch (JSONException e) { res.set(result.PARSER_ERROR); return p; } try { // returns [{"PassaggiRT":[],"Passaggi":[]}] for non existing stops! json.getJSONObject(0).getString("Linea"); // if we can get this, then there's something useful in the array. } catch (JSONException e) { res.set(result.EMPTY_RESULT_SET); return p; } howManyRoutes = json.length(); if (howManyRoutes == 0) { res.set(result.EMPTY_RESULT_SET); return p; } try { for (i = 0; i < howManyRoutes; i++) { thisroute = json.getJSONObject(i); routename = thisroute.getString("Linea"); try { bacino = thisroute.getString("Bacino"); } catch (JSONException ignored) { // if "Bacino" gets removed... bacino = "U"; } pos = p.addRoute(routename, thisroute.getString("Direzione"), FiveTNormalizer.decodeType(routename, bacino)); /* * Okay, this is just absurd. * The underground always has 4 non-real-time timetable entries; however, the first * two are old\stale\bogus, as they're in the past. The other two are exactly the * same ones that appear on the screens in the stations. */ if (routename.equals("METRO")) { j = 2; } else { j = 0; } passaggi = thisroute.getJSONArray("PassaggiRT"); howManyPassaggi = passaggi.length(); for (; j < howManyPassaggi; j++) { p.addPassaggio(passaggi.getString(j).concat("*"), pos); } passaggi = thisroute.getJSONArray("Passaggi"); // now the non-real-time ones howManyPassaggi = passaggi.length(); for (; j < howManyPassaggi; j++) { p.addPassaggio(passaggi.getString(j), pos); } } } catch (JSONException e) { res.set(result.PARSER_ERROR); return p; } p.sortRoutes(); res.set(result.OK); return p; }
From source file:it.reyboz.bustorino.backend.GTTStopsFetcher.java
@Override @NonNull/*from w w w .j av a2 s . c om*/ public List<Stop> FindByName(String name, StopsDBInterface db, AtomicReference<result> res) { URL url; // sorting an ArrayList should be faster than a LinkedList and the API is limited to 15 results List<Stop> s = new ArrayList<>(15); List<Stop> s2 = new ArrayList<>(15); String fullname; String content; String bacino; String localita; Route.Type type; JSONArray json; int howManyStops, i; JSONObject thisstop; if (name.length() < 3) { res.set(result.QUERY_TOO_SHORT); return s; } try { url = new URL("http://www.gtt.to.it/cms/components/com_gtt/views/palinejson/view.html.php?term=" + URLEncoder.encode(name, "utf-8")); } catch (Exception e) { res.set(result.PARSER_ERROR); return s; } content = networkTools.queryURL(url, res); if (content == null) { return s; } try { json = new JSONArray(content); } catch (JSONException e) { if (content.contains("[]")) { // when no results are found, server returns a PHP Warning and an empty array. In case they fix the warning, we're looking for the array. res.set(result.EMPTY_RESULT_SET); } else { res.set(result.PARSER_ERROR); } return s; } howManyStops = json.length(); if (howManyStops == 0) { res.set(result.EMPTY_RESULT_SET); return s; } try { for (i = 0; i < howManyStops; i++) { thisstop = json.getJSONObject(i); fullname = thisstop.getString("data"); try { localita = thisstop.getString("localita"); if (localita.equals("[MISSING]")) { localita = null; } } catch (JSONException e) { localita = null; } try { bacino = thisstop.getString("bacino"); } catch (JSONException ignored) { bacino = "U"; } if (fullname.startsWith("Metro ")) { type = Route.Type.METRO; } else if (fullname.length() >= 6 && fullname.startsWith("S00")) { type = Route.Type.RAILWAY; } else if (fullname.startsWith("ST")) { type = Route.Type.RAILWAY; } else { type = FiveTNormalizer.decodeType("", bacino); } String ID = thisstop.getString("value"); s.add(new Stop(fullname, ID, localita, type, db.getRoutesByStop(ID))); } } catch (JSONException e) { res.set(result.PARSER_ERROR); return s; } if (s.size() < 1) { // shouldn't happen but prevents the next part from catching fire res.set(result.EMPTY_RESULT_SET); return s; } Collections.sort(s); // the next loop won't work with less than 2 items if (s.size() < 2) { res.set(result.OK); return s; } /* There are some duplicate stops returned by this API. * Long distance buses have stop IDs with 5 digits. Always. They are zero-padded if there * aren't enough. E.g. stop 631 becomes 00631. * * Unfortunately you can't use padded stops to query any API. * Fortunately, unpadded stops return both normal and long distance bus timetables. * FiveTNormalizer is already removing padding (there may be some padded stops for which the * API doesn't return an unpadded equivalent), here we'll remove duplicates by skipping * padded stops, which also never have a location. * * I had to draw a finite state machine on a piece of paper to understand how to implement * this loop. */ for (i = 1; i < howManyStops;) { Stop current = s.get(i); Stop previous = s.get(i - 1); // same stop: let's see which one to keep... if (current.ID.equals(previous.ID)) { if (previous.location == null) { // previous one is useless: discard it, increment i++; } else if (current.location == null) { // this one is useless: add previous and skip one s2.add(previous); i += 2; } else { // they aren't really identical: to err on the side of caution, keep them both. s2.add(previous); i++; } } else { // different: add previous, increment s2.add(previous); i++; } } // unless the last one was garbage (i would be howManyStops+1 in that case), add it if (i == howManyStops) { s2.add(s.get(i - 1)); } res.set(result.OK); return s2; }
From source file:com.jayway.restassured.itest.java.FilterITest.java
@Test public void content_type_in_filter_doesnt_contain_charset_if_configured_not_to() { final AtomicReference<String> contentType = new AtomicReference<String>(); given().config(RestAssuredConfig.config() .encoderConfig(encoderConfig().appendDefaultContentCharsetToContentTypeIfUndefined(false))) .filter(new Filter() { public Response filter(FilterableRequestSpecification requestSpec, FilterableResponseSpecification responseSpec, FilterContext ctx) { contentType.set(requestSpec.getRequestContentType()); return ctx.next(requestSpec, responseSpec); }//from w w w . j a va 2 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")); }
From source file:eu.eubrazilcc.lvl.storage.oauth2.dao.LinkedInStateDAO.java
/** * Checks whether or not the specified secret (state) was previously stored and is currently valid (not expired). * @param secret - the secret associated to the state * @param redirectUriRef - if set and the state is valid, then the redirect URI is returned to the caller * @param callbackRef - if set and the state is valid, then the callback URI is returned to the caller * @return {@code true} only if the provided secret (state) is found in the storage and is currently valid (not expired). * Otherwise, returns {@code false}. *///from ww w . java 2 s. c o m public boolean isValid(final String secret, final @Nullable AtomicReference<String> redirectUriRef, final @Nullable AtomicReference<String> callbackRef) { checkArgument(isNotBlank(secret), "Uninitialized or invalid state"); final LinkedInState state = find(secret); final boolean isValid = (state != null && state.getState() != null && secret.equals(state.getState()) && (state.getIssuedAt() + state.getExpiresIn()) > (currentTimeMillis() / 1000l)); if (isValid) { if (redirectUriRef != null) { redirectUriRef.set(state.getRedirectUri()); } if (callbackRef != null) { callbackRef.set(state.getCallback()); } } return isValid; }