List of usage examples for java.util.concurrent.atomic AtomicReference set
public final void set(V newValue)
From source file:org.jahia.test.services.atmosphere.AtmosphereTest.java
@Test public void testNodePublish() throws RepositoryException { TestHelper.createList(testHomeEdit, "contentList1", 4, INITIAL_ENGLISH_TEXT_NODE_PROPERTY_VALUE); final Value[] values = testHomeEdit.getResolveSite().getProperty("j:installedModules").getValues(); Value[] values1 = new Value[values.length + 1]; System.arraycopy(values, 0, values1, 0, values.length); values1[values.length] = JCRValueFactoryImpl.getInstance().createValue("atmosphere:7.0.0.0-SNAPSHOT"); testHomeEdit.getResolveSite().setProperty("j:installedModules", values1); englishEditSession.save();//from w ww .ja v a 2 s . co m final CountDownLatch latch = new CountDownLatch(1); AsyncHttpClient c = new AsyncHttpClient(); try { //Suspend final AtomicReference<Response> response = new AtomicReference<Response>(); c.prepareGet(getBaseServerURL() + Jahia.getContextPath() + "/atmosphere/sites/jcrAtmosphereTest-en") .execute(new AsyncCompletionHandler<Response>() { @Override public Response onCompleted(Response r) throws Exception { try { response.set(r); return r; } finally { latch.countDown(); } } }); Thread.sleep(2500); jcrService.publishByMainId(testHomeEdit.getIdentifier(), Constants.EDIT_WORKSPACE, Constants.LIVE_WORKSPACE, null, false, null); try { latch.await(20, TimeUnit.SECONDS); } catch (InterruptedException e) { fail(e.getMessage()); } Response r = response.get(); assertNotNull(r); assertEquals(HttpStatus.SC_OK, r.getStatusCode()); assertTrue(r.getResponseBody().contains("\"name\":\"contentList1_text0\"")); } catch (Exception e) { logger.error("test failed", e); fail(e.getMessage()); } c.close(); }
From source file:org.zodiark.publisher.PublisherTest.java
@Test(enabled = false) public void failedStreamingSession() throws IOException, InterruptedException { 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<>(); wowzaClient.handler(new OnEnvelopHandler() { @Override/*from w ww . ja va 2 s .co m*/ public boolean onEnvelop(Envelope e) throws IOException { Message m = e.getMessage(); switch (m.getPath()) { case WOWZA_CONNECT: // Connected. Listen uuid.set(e.getUuid()); break; case SERVER_VALIDATE_OK: UUID uuid = mapper.readValue(e.getMessage().getData(), UUID.class); PublisherResults result = new PublisherResults("error"); result.setUuid(uuid.getUuid()); Envelope publisherOk = Envelope.newClientToServerRequest(new Message( new Path(FAILED_PUBLISHER_STREAMING_SESSION), mapper.writeValueAsString(result))); wowzaClient.send(publisherOk); break; default: // ERROR } connected.countDown(); return false; } }).open(); Envelope wowzaConnect; wowzaConnect = Envelope.newClientToServerRequest( new Message(new Path(WOWZA_CONNECT), mapper.writeValueAsString(new UserPassword("wowza", "bar")))); wowzaClient.send(wowzaConnect); connected.await(); 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); publisherClient.handler(new OnEnvelopHandler() { @Override public boolean onEnvelop(Envelope e) throws IOException { answer.set(mapper.readValue(e.getMessage().getData(), PublisherResults.class)); latch.countDown(); return true; } }).open(); Envelope createSessionMessage = Envelope .newClientToServerRequest(new Message(new Path(DB_POST_PUBLISHER_SESSION_CREATE), 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); publisherClient.handler(new OnEnvelopHandler() { @Override public boolean onEnvelop(Envelope e) throws IOException { answer.set(mapper.readValue(e.getMessage().getData(), PublisherResults.class)); tlatch.countDown(); return true; } }); Envelope startStreamingSession = Envelope .newClientToServerRequest(new Message(new Path(VALIDATE_PUBLISHER_STREAMING_SESSION), mapper.writeValueAsString(new WowzaUUID(uuid.get())))); createSessionMessage.setFrom(new From(ActorValue.PUBLISHER)); publisherClient.send(startStreamingSession); tlatch.await(); assertEquals("ERROR", answer.get().getResults()); }
From source file:org.apache.storm.messaging.netty.NettyTest.java
private void doTestServerDelayed(Map<String, Object> stormConf) throws Exception { LOG.info("4. test server delayed"); String reqMessage = "0123456789abcdefghijklmnopqrstuvwxyz"; IContext context = TransportFactory.makeContext(stormConf); try {/*from w ww . j ava 2 s .c o m*/ AtomicReference<TaskMessage> response = new AtomicReference<>(); int port = Utils.getAvailablePort(6700); try (IConnection client = context.connect(null, "localhost", port, remoteBpStatus)) { AtomicReference<IConnection> server = new AtomicReference<>(); try { CompletableFuture<?> serverStart = CompletableFuture.runAsync(() -> { try { Thread.sleep(100); server.set(context.bind(null, port)); server.get().registerRecv(mkConnectionCallback(response::set)); waitUntilReady(client, server.get()); } catch (Exception e) { throw Utils.wrapInRuntime(e); } }); serverStart.get(Testing.TEST_TIMEOUT_MS, TimeUnit.MILLISECONDS); byte[] messageBytes = reqMessage.getBytes(StandardCharsets.UTF_8); send(client, taskId, messageBytes); waitForNotNull(response); TaskMessage responseMessage = response.get(); assertThat(responseMessage.task(), is(taskId)); assertThat(responseMessage.message(), is(messageBytes)); } finally { if (server.get() != null) { server.get().close(); } } } } finally { context.term(); } }
From source file:com.sysunite.nifi.StringSplit.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException { //position 4//from w w w .j a v a 2 s .c om FlowFile flowFile = session.get(); if (flowFile == null) { return; } int totalDynamicRelations = this.getRelationships().size(); System.out.println("rels= " + totalDynamicRelations); //-------reading final AtomicReference<String> flowFileContentStore = new AtomicReference<>(); session.read(flowFile, new InputStreamCallback() { @Override public void process(InputStream inputStream) throws IOException { System.out.println("read"); try { String flowFileContent = IOUtils.toString(inputStream); flowFileContentStore.set(flowFileContent); } catch (Exception e) { } } }); //-------using en editing try { //get contents String flowFileContent = flowFileContentStore.get(); //split contents by delimiter String regexForSplit = context.getProperty(SPLIT).getValue(); String[] splittedFlowFileContents = flowFileContent.split(regexForSplit); //count splits int totalSplits = splittedFlowFileContents.length; System.out.println("split= " + totalSplits); //get list of dynamic props final Map<Relationship, PropertyValue> propMap = this.propertyMap; for (final Map.Entry<Relationship, PropertyValue> entry : propMap.entrySet()) { final PropertyValue value = entry.getValue(); String oriValue = value.getValue(); //use only splits not empty if (oriValue != null) { try { int partFromSplittedFlowFileContents = Integer.parseInt(oriValue); //parts only in range are allowed if (partFromSplittedFlowFileContents < totalSplits) { String splittedPart = splittedFlowFileContents[partFromSplittedFlowFileContents]; String relationName = entry.getKey().getName(); System.out.println("relationship (" + relationName + ") -> " + splittedPart); //now we can tranfer splitted part to the relation FlowFile fNew = session.clone(flowFile); fNew = session.putAttribute(fNew, relationName, splittedPart); session.transfer(fNew, entry.getKey()); } } catch (Exception e) { } } } } catch (Exception e) { } session.transfer(flowFile, ORIGINAL); }
From source file:org.apache.nifi.hbase.PutHBaseJSON.java
@Override protected PutFlowFile createPut(final ProcessSession session, final ProcessContext context, final FlowFile flowFile) { final String tableName = context.getProperty(TABLE_NAME).evaluateAttributeExpressions(flowFile).getValue(); final String rowId = context.getProperty(ROW_ID).evaluateAttributeExpressions(flowFile).getValue(); final String rowFieldName = context.getProperty(ROW_FIELD_NAME).evaluateAttributeExpressions(flowFile) .getValue();//from w w w . j av a2s .c o m final String columnFamily = context.getProperty(COLUMN_FAMILY).evaluateAttributeExpressions(flowFile) .getValue(); final boolean extractRowId = !StringUtils.isBlank(rowFieldName); final String complexFieldStrategy = context.getProperty(COMPLEX_FIELD_STRATEGY).getValue(); final String fieldEncodingStrategy = context.getProperty(FIELD_ENCODING_STRATEGY).getValue(); final String rowIdEncodingStrategy = context.getProperty(ROW_ID_ENCODING_STRATEGY).getValue(); // Parse the JSON document final ObjectMapper mapper = new ObjectMapper(); final AtomicReference<JsonNode> rootNodeRef = new AtomicReference<>(null); try { session.read(flowFile, new InputStreamCallback() { @Override public void process(final InputStream in) throws IOException { try (final InputStream bufferedIn = new BufferedInputStream(in)) { rootNodeRef.set(mapper.readTree(bufferedIn)); } } }); } catch (final ProcessException pe) { getLogger().error("Failed to parse {} as JSON due to {}; routing to failure", new Object[] { flowFile, pe.toString() }, pe); return null; } final JsonNode rootNode = rootNodeRef.get(); if (rootNode.isArray()) { getLogger().error("Root node of JSON must be a single document, found array for {}; routing to failure", new Object[] { flowFile }); return null; } final Collection<PutColumn> columns = new ArrayList<>(); final AtomicReference<String> rowIdHolder = new AtomicReference<>(null); // convert each field/value to a column for the put, skip over nulls and arrays final Iterator<String> fieldNames = rootNode.getFieldNames(); while (fieldNames.hasNext()) { final String fieldName = fieldNames.next(); final AtomicReference<byte[]> fieldValueHolder = new AtomicReference<>(null); final JsonNode fieldNode = rootNode.get(fieldName); if (fieldNode.isNull()) { getLogger().debug("Skipping {} because value was null", new Object[] { fieldName }); } else if (fieldNode.isValueNode()) { // for a value node we need to determine if we are storing the bytes of a string, or the bytes of actual types if (STRING_ENCODING_VALUE.equals(fieldEncodingStrategy)) { final byte[] valueBytes = clientService.toBytes(fieldNode.asText()); fieldValueHolder.set(valueBytes); } else { fieldValueHolder.set(extractJNodeValue(fieldNode)); } } else { // for non-null, non-value nodes, determine what to do based on the handling strategy switch (complexFieldStrategy) { case FAIL_VALUE: getLogger().error("Complex value found for {}; routing to failure", new Object[] { fieldName }); return null; case WARN_VALUE: getLogger().warn("Complex value found for {}; skipping", new Object[] { fieldName }); break; case TEXT_VALUE: // use toString() here because asText() is only guaranteed to be supported on value nodes // some other types of nodes, like ArrayNode, provide toString implementations fieldValueHolder.set(clientService.toBytes(fieldNode.toString())); break; case IGNORE_VALUE: // silently skip break; default: break; } } // if we have a field value, then see if this is the row id field, if so store the value for later // otherwise add a new column where the fieldName and fieldValue are the column qualifier and value if (fieldValueHolder.get() != null) { if (extractRowId && fieldName.equals(rowFieldName)) { rowIdHolder.set(fieldNode.asText()); } else { columns.add(new PutColumn(columnFamily.getBytes(StandardCharsets.UTF_8), fieldName.getBytes(StandardCharsets.UTF_8), fieldValueHolder.get())); } } } // if we are expecting a field name to use for the row id and the incoming document doesn't have it // log an error message so the user can see what the field names were and return null so it gets routed to failure if (extractRowId && rowIdHolder.get() == null) { final String fieldNameStr = StringUtils.join(rootNode.getFieldNames(), ","); getLogger().error("Row ID field named '{}' not found in field names '{}'; routing to failure", new Object[] { rowFieldName, fieldNameStr }); return null; } final String putRowId = (extractRowId ? rowIdHolder.get() : rowId); byte[] rowKeyBytes = getRow(putRowId, context.getProperty(ROW_ID_ENCODING_STRATEGY).getValue()); return new PutFlowFile(tableName, rowKeyBytes, columns, flowFile); }
From source file:com.sybase365.mobiliser.custom.project.handlers.authentication.GtalkAuthenticationHandler.java
@Override public void authenticate(final SubTransaction transaction, final String authToken, final boolean payer) throws AuthenticationException { lazyInit();//from ww w . j a v a 2 s . c o m final Customer customer; final String otherName; if (payer) { customer = transaction.getTransaction().getPayer(); otherName = transaction.getTransaction().getPayee().getDisplayName(); } else { customer = transaction.getTransaction().getPayee(); otherName = transaction.getTransaction().getPayer().getDisplayName(); } final String email = this.notificationLogic.getCustomersEmail(customer, 0).get(0); final AtomicReference<String> userResponse = new AtomicReference<String>(); final ChatManager chatmanager = this.connection.getChatManager(); final MessageListener messageListener = new MessageListener() { @Override public void processMessage(Chat chat, Message message) { synchronized (userResponse) { LOG.info("got user response: " + message.getBody()); userResponse.set(message.getBody()); userResponse.notify(); } } }; final Chat newChat = chatmanager.createChat(email, messageListener); try { try { newChat.sendMessage("Please confirm payment to " + otherName + " by entering yes."); } catch (final XMPPException e) { LOG.info("can not send message to user " + email + ": " + e.getMessage(), e); throw new AuthenticationFailedPermanentlyException(StatusCodes.ERROR_IVR_NO_PICKUP); } synchronized (userResponse) { try { userResponse.wait(10000); } catch (final InterruptedException e) { LOG.info("Interrupted while waiting", e); Thread.currentThread().interrupt(); } } if (userResponse.get() == null) { LOG.info("did not receive a response in time."); throw new AuthenticationFailedPermanentlyException("did not receive a response in time.", StatusCodes.ERROR_IVR_NO_USER_INPUT, new HashMap<String, String>()); } if ("yes".equalsIgnoreCase(userResponse.get())) { LOG.debug("received confirmation."); try { newChat.sendMessage("Thank You."); } catch (final XMPPException e1) { LOG.debug("Thank you Response was not sent. Ignored", e1); } return; } LOG.debug("received unknown response: " + userResponse.get()); try { newChat.sendMessage("Transaction will be cancelled."); } catch (final XMPPException e2) { LOG.debug("Response was not sent. Ignored", e2); } throw new AuthenticationFailedPermanentlyException(StatusCodes.ERROR_IVR_HANGUP); } finally { newChat.removeMessageListener(messageListener); } }
From source file:org.commonjava.indy.tools.cache.Main.java
private int run(final MigrationOptions options) throws IndyBootException { try {//from w w w . j a v a 2 s . co m File inXml = options.getInfinispanXml(); if (inXml != null) { File outXmlDir = new File(System.getProperty("java.io.tmpdir", "/tmp"), "infinispan-config-" + System.currentTimeMillis()); if (!outXmlDir.isDirectory() && !outXmlDir.mkdirs()) { throw new IndyBootException( "Failed to create temporary direcory for infinispan configuration loading"); } File outXml = new File(outXmlDir, "infinispan.xml"); FileUtils.copyFile(inXml, outXml); Properties props = System.getProperties(); props.setProperty("indy.config.dir", outXmlDir.getAbsolutePath()); System.setProperties(props); } producer = new SimpleCacheProducer(); CacheHandle<Object, Object> cache = producer.getCache(options.getCacheName()); if (MigrationCommand.dump == options.getMigrationCommand()) { AtomicReference<Throwable> error = new AtomicReference<>(); try (ObjectOutputStream out = new ObjectOutputStream( new GZIPOutputStream(new FileOutputStream(options.getDataFile())))) { cache.executeCache((c) -> { try { out.writeLong(c.size()); } catch (IOException e) { logger.error("Failed to write data file header.", e); error.set(e); } if (error.get() == null) { c.forEach((k, v) -> { if (error.get() == null) { try { out.writeObject(k); out.writeObject(v); } catch (IOException e) { logger.error("Failed to write entry with key: " + k, e); error.set(e); } } }); } return true; }); } catch (IOException e) { error.set(e); } if (error.get() != null) { throw new IndyBootException("Failed to write data to file: " + options.getDataFile(), error.get()); } } else { AtomicReference<Throwable> error = new AtomicReference<>(); try (ObjectInputStream in = new ObjectInputStream( new GZIPInputStream(new FileInputStream(options.getDataFile())))) { cache.executeCache((c) -> { try { long records = in.readLong(); for (long i = 0; i < records; i++) { try { Object k = in.readObject(); Object v = in.readObject(); c.putAsync(k, v); } catch (Exception e) { logger.error("Failed to read entry at index: " + i, e); error.set(e); } } logger.info("Load {} complete, size: {}", options.getCacheName(), records); } catch (IOException e) { logger.error("Failed to read data file header.", e); error.set(e); } return true; }); } catch (IOException e) { error.set(e); } if (error.get() != null) { throw new IndyBootException("Failed to read data from file: " + options.getDataFile(), error.get()); } } } catch (final Throwable e) { if (e instanceof IndyBootException) throw (IndyBootException) e; logger.error("Failed to initialize Booter: " + e.getMessage(), e); return ERR_CANT_INIT_BOOTER; } finally { try { producer.stop(); } catch (final IndyLifecycleException e) { logger.error("Failed to stop cache subsystem: " + e.getMessage(), e); } } return 0; }
From source file:org.apache.hadoop.hbase.quotas.TestSnapshotQuotaObserverChore.java
@Test public void testSnapshotSize() throws Exception { // Create a table and set a quota TableName tn1 = helper.createTableWithRegions(5); admin.setQuota(QuotaSettingsFactory.limitTableSpace(tn1, SpaceQuotaHelperForTests.ONE_GIGABYTE, SpaceViolationPolicy.NO_INSERTS)); // Write some data and flush it helper.writeData(tn1, 256L * SpaceQuotaHelperForTests.ONE_KILOBYTE); admin.flush(tn1);/*w ww . jav a 2 s. com*/ final AtomicReference<Long> lastSeenSize = new AtomicReference<>(); // Wait for the Master chore to run to see the usage (with a fudge factor) TEST_UTIL.waitFor(30_000, new SpaceQuotaSnapshotPredicate(conn, tn1) { @Override boolean evaluate(SpaceQuotaSnapshot snapshot) throws Exception { lastSeenSize.set(snapshot.getUsage()); return snapshot.getUsage() > 230L * SpaceQuotaHelperForTests.ONE_KILOBYTE; } }); // Create a snapshot on the table final String snapshotName = tn1 + "snapshot"; admin.snapshot(new SnapshotDescription(snapshotName, tn1, SnapshotType.SKIPFLUSH)); // Get the snapshots Multimap<TableName, String> snapshotsToCompute = testChore.getSnapshotsToComputeSize(); assertEquals("Expected to see the single snapshot: " + snapshotsToCompute, 1, snapshotsToCompute.size()); // Get the size of our snapshot Multimap<TableName, SnapshotWithSize> snapshotsWithSize = testChore .computeSnapshotSizes(snapshotsToCompute); assertEquals(1, snapshotsWithSize.size()); SnapshotWithSize sws = Iterables.getOnlyElement(snapshotsWithSize.get(tn1)); assertEquals(snapshotName, sws.getName()); // The snapshot should take up no space since the table refers to it completely assertEquals(0, sws.getSize()); // Write some more data, flush it, and then major_compact the table helper.writeData(tn1, 256L * SpaceQuotaHelperForTests.ONE_KILOBYTE); admin.flush(tn1); TEST_UTIL.compact(tn1, true); // Test table should reflect it's original size since ingest was deterministic TEST_UTIL.waitFor(30_000, new SpaceQuotaSnapshotPredicate(conn, tn1) { @Override boolean evaluate(SpaceQuotaSnapshot snapshot) throws Exception { LOG.debug("Current usage=" + snapshot.getUsage() + " lastSeenSize=" + lastSeenSize.get()); return closeInSize(snapshot.getUsage(), lastSeenSize.get(), SpaceQuotaHelperForTests.ONE_KILOBYTE); } }); // Wait for no compacted files on the regions of our table TEST_UTIL.waitFor(30_000, new NoFilesToDischarge(TEST_UTIL.getMiniHBaseCluster(), tn1)); // Still should see only one snapshot snapshotsToCompute = testChore.getSnapshotsToComputeSize(); assertEquals("Expected to see the single snapshot: " + snapshotsToCompute, 1, snapshotsToCompute.size()); snapshotsWithSize = testChore.computeSnapshotSizes(snapshotsToCompute); assertEquals(1, snapshotsWithSize.size()); sws = Iterables.getOnlyElement(snapshotsWithSize.get(tn1)); assertEquals(snapshotName, sws.getName()); // The snapshot should take up the size the table originally took up assertEquals(lastSeenSize.get().longValue(), sws.getSize()); }
From source file:com.kixeye.chassis.support.test.hystrix.ChassisHystrixTest.java
@Test public void testBasicHystrixCommand() throws Exception { final AtomicBoolean done = new AtomicBoolean(false); final AtomicReference<String> result = new AtomicReference<>(null); // kick off async command Observable<String> observable = new TestCommand().observe(); // Sleep to test what happens if command finishes before subscription Thread.sleep(2000);//from www . j av a2 s. co m // Add handler observable.subscribe(new Observer<String>() { @Override public void onCompleted() { done.set(true); } @Override public void onError(Throwable e) { result.set("error!!"); done.set(true); } @Override public void onNext(String args) { result.set(args); done.set(true); } }); // spin until done while (!done.get()) { Thread.sleep(100); } Assert.assertEquals(resultString, result.get()); }
From source file:com.king.platform.net.http.integration.MultiPart.java
@Test public void postMultiPart() throws Exception { AtomicReference<List<FileItem>> partReferences = new AtomicReference<>(); AtomicReference<Exception> exceptionReference = new AtomicReference<>(); integrationServer.addServlet(new HttpServlet() { @Override/*from w ww . ja v a 2s.c om*/ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory()); try { List<FileItem> fileItems = servletFileUpload.parseRequest(req); partReferences.set(fileItems); } catch (FileUploadException e) { exceptionReference.set(e); } } }, "/testMultiPart"); httpClient .createPost( "http://localhost:" + port + "/testMultiPart") .idleTimeoutMillis( 0) .totalRequestTimeoutMillis( 0) .content( new MultiPartBuilder() .addPart( MultiPartBuilder .create("text1", "Message 1", StandardCharsets.ISO_8859_1) .contentType("multipart/form-data")) .addPart(MultiPartBuilder.create("binary1", new byte[] { 0x00, 0x01, 0x02 }) .contentType("application/octet-stream").charset(StandardCharsets.UTF_8) .fileName("application.bin")) .addPart(MultiPartBuilder.create("text2", "Message 2", StandardCharsets.ISO_8859_1)) .build()) .build().execute().join(); assertNull(exceptionReference.get()); List<FileItem> fileItems = partReferences.get(); FileItem fileItem = fileItems.get(1); assertEquals("application/octet-stream; charset=UTF-8", fileItem.getContentType()); assertEquals("binary1", fileItem.getFieldName()); assertEquals("application.bin", fileItem.getName()); }