List of usage examples for java.util.concurrent.atomic AtomicReference set
public final void set(V newValue)
From source file:org.elasticsearch.smoketest.SmokeTestWatcherWithSecurityIT.java
private ObjectPath getWatchHistoryEntry(String watchId, String state) throws Exception { final AtomicReference<ObjectPath> objectPathReference = new AtomicReference<>(); assertBusy(() -> {//ww w .j a v a 2 s . c om client().performRequest("POST", ".watcher-history-*/_refresh"); try (XContentBuilder builder = jsonBuilder()) { builder.startObject(); builder.startObject("query").startObject("bool").startArray("must"); builder.startObject().startObject("term").startObject("watch_id").field("value", watchId) .endObject().endObject().endObject(); if (Strings.isNullOrEmpty(state) == false) { builder.startObject().startObject("term").startObject("state").field("value", state).endObject() .endObject().endObject(); } builder.endArray().endObject().endObject(); builder.startArray("sort").startObject().startObject("trigger_event.triggered_time") .field("order", "desc").endObject().endObject().endArray(); builder.endObject(); StringEntity entity = new StringEntity(Strings.toString(builder), ContentType.APPLICATION_JSON); Response response = client().performRequest("POST", ".watcher-history-*/_search", Collections.emptyMap(), entity); ObjectPath objectPath = ObjectPath.createFromResponse(response); int totalHits = objectPath.evaluate("hits.total"); assertThat(totalHits, is(greaterThanOrEqualTo(1))); String watchid = objectPath.evaluate("hits.hits.0._source.watch_id"); assertThat(watchid, is(watchId)); objectPathReference.set(objectPath); } }); return objectPathReference.get(); }
From source file:io.cloudslang.lang.tools.build.SlangBuilderTest.java
@Test public void testProcessRunTestsMixed() { final Map<String, SlangTestCase> testCases = new LinkedHashMap<>(); final SlangTestCase testCase1 = new SlangTestCase("test1", "testFlowPath", "desc", asList("abc", "new"), "mock", null, null, false, "SUCCESS"); final SlangTestCase testCase2 = new SlangTestCase("test2", "testFlowPath", "desc", asList("efg", "new"), "mock", null, null, false, "SUCCESS"); final SlangTestCase testCase3 = new SlangTestCase("test3", "testFlowPath", "desc", asList("new", "new2"), "mock", null, null, false, "SUCCESS"); final SlangTestCase testCase4 = new SlangTestCase("test4", "testFlowPath", "desc", asList("new", "new2"), "mock", null, null, false, "SUCCESS"); testCases.put("test1", testCase1); testCases.put("test2", testCase2); testCases.put("test3", testCase3); testCases.put("test4", testCase4); final List<String> testSuites = newArrayList("new"); final Map<String, CompilationArtifact> compiledFlows = new HashMap<>(); final String projectPath = "aaa"; final AtomicReference<ThreadSafeRunTestResults> theCapturedArgument = new AtomicReference<>(); final AtomicReference<Map<String, SlangTestCase>> capturedTestsSeq = new AtomicReference<>(); final AtomicReference<Map<String, SlangTestCase>> capturedTestsPar = new AtomicReference<>(); doCallRealMethod().when(slangTestRunner).isTestCaseInActiveSuite(any(SlangTestCase.class), anyList()); doReturn(SlangBuildMain.TestCaseRunMode.SEQUENTIAL).doReturn(SlangBuildMain.TestCaseRunMode.PARALLEL) .doReturn(SlangBuildMain.TestCaseRunMode.PARALLEL) .doReturn(SlangBuildMain.TestCaseRunMode.SEQUENTIAL).when(testRunInfoService) .getRunModeForTestCase(any(SlangTestCase.class), any(ConflictResolutionStrategy.class), any(DefaultResolutionStrategy.class)); doAnswer(new Answer() { @Override/*w ww . j av a2s. c o m*/ public Object answer(InvocationOnMock invocationOnMock) throws Throwable { Object[] arguments = invocationOnMock.getArguments(); Object argument = arguments[arguments.length - 2]; theCapturedArgument.set((ThreadSafeRunTestResults) argument); return invocationOnMock.callRealMethod(); } }).when(slangTestRunner).splitTestCasesByRunState(any(BulkRunMode.class), anyMap(), anyList(), any(IRunTestResults.class), eq(buildModeConfig)); doAnswer(new Answer() { @Override @SuppressWarnings("unchecked") public Object answer(InvocationOnMock invocationOnMock) throws Throwable { Object[] arguments = invocationOnMock.getArguments(); capturedTestsSeq.set((Map<String, SlangTestCase>) arguments[1]); return null; } }).when(slangTestRunner).runTestsSequential(anyString(), anyMap(), anyMap(), any(IRunTestResults.class)); doAnswer(new Answer() { @Override @SuppressWarnings("unchecked") public Object answer(InvocationOnMock invocationOnMock) throws Throwable { Object[] arguments = invocationOnMock.getArguments(); capturedTestsPar.set((Map<String, SlangTestCase>) arguments[1]); return null; } }).when(slangTestRunner).runTestsParallel(anyString(), anyMap(), anyMap(), any(ThreadSafeRunTestResults.class)); // Tested call slangBuilder.processRunTests(projectPath, testSuites, POSSIBLY_MIXED, compiledFlows, testCases, buildModeConfig); InOrder inOrder = inOrder(slangTestRunner); inOrder.verify(slangTestRunner).splitTestCasesByRunState(eq(POSSIBLY_MIXED), eq(testCases), eq(testSuites), isA(ThreadSafeRunTestResults.class), eq(buildModeConfig)); inOrder.verify(slangTestRunner).runTestsSequential(eq(projectPath), anyMap(), eq(compiledFlows), eq(theCapturedArgument.get())); inOrder.verify(slangTestRunner).runTestsParallel(eq(projectPath), anyMap(), eq(compiledFlows), eq(theCapturedArgument.get())); final List<SlangTestCase> listSeq = newArrayList(capturedTestsSeq.get().values()); final List<SlangTestCase> listPar = newArrayList(capturedTestsPar.get().values()); assertEquals(0, ListUtils.intersection(listSeq, listPar).size()); // assures that a test is run only once assertEquals(newHashSet(testCases.values()), newHashSet(ListUtils.union(listSeq, listPar))); }
From source file:com.android.ide.eclipse.adt.internal.editors.layout.gre.ClientRulesEngine.java
@Override public String displayFragmentSourceInput() { try {//from ww w . j a va 2 s . co m // Compute a search scope: We need to merge all the subclasses // android.app.Fragment and android.support.v4.app.Fragment IJavaSearchScope scope = SearchEngine.createWorkspaceScope(); IProject project = mRulesEngine.getProject(); final IJavaProject javaProject = BaseProjectHelper.getJavaProject(project); if (javaProject != null) { IType oldFragmentType = javaProject.findType(CLASS_V4_FRAGMENT); // First check to make sure fragments are available, and if not, // warn the user. IAndroidTarget target = Sdk.getCurrent().getTarget(project); // No, this should be using the min SDK instead! if (target.getVersion().getApiLevel() < 11 && oldFragmentType == null) { // Compatibility library must be present MessageDialog dialog = new MessageDialog(Display.getCurrent().getActiveShell(), "Fragment Warning", null, "Fragments require API level 11 or higher, or a compatibility " + "library for older versions.\n\n" + " Do you want to install the compatibility library?", MessageDialog.QUESTION, new String[] { "Install", "Cancel" }, 1 /* default button: Cancel */); int answer = dialog.open(); if (answer == 0) { if (!AddSupportJarAction.install(project)) { return null; } } else { return null; } } // Look up sub-types of each (new fragment class and compatibility fragment // class, if any) and merge the two arrays - then create a scope from these // elements. IType[] fragmentTypes = new IType[0]; IType[] oldFragmentTypes = new IType[0]; if (oldFragmentType != null) { ITypeHierarchy hierarchy = oldFragmentType.newTypeHierarchy(new NullProgressMonitor()); oldFragmentTypes = hierarchy.getAllSubtypes(oldFragmentType); } IType fragmentType = javaProject.findType(CLASS_FRAGMENT); if (fragmentType != null) { ITypeHierarchy hierarchy = fragmentType.newTypeHierarchy(new NullProgressMonitor()); fragmentTypes = hierarchy.getAllSubtypes(fragmentType); } IType[] subTypes = new IType[fragmentTypes.length + oldFragmentTypes.length]; System.arraycopy(fragmentTypes, 0, subTypes, 0, fragmentTypes.length); System.arraycopy(oldFragmentTypes, 0, subTypes, fragmentTypes.length, oldFragmentTypes.length); scope = SearchEngine.createJavaSearchScope(subTypes, IJavaSearchScope.SOURCES); } Shell parent = AdtPlugin.getShell(); final AtomicReference<String> returnValue = new AtomicReference<String>(); final AtomicReference<SelectionDialog> dialogHolder = new AtomicReference<SelectionDialog>(); final SelectionDialog dialog = JavaUI.createTypeDialog(parent, new ProgressMonitorDialog(parent), scope, IJavaElementSearchConstants.CONSIDER_CLASSES, false, // Use ? as a default filter to fill dialog with matches "?", //$NON-NLS-1$ new TypeSelectionExtension() { @Override public Control createContentArea(Composite parentComposite) { Composite composite = new Composite(parentComposite, SWT.NONE); composite.setLayout(new GridLayout(1, false)); Button button = new Button(composite, SWT.PUSH); button.setText("Create New..."); button.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { String fqcn = createNewFragmentClass(javaProject); if (fqcn != null) { returnValue.set(fqcn); dialogHolder.get().close(); } } }); return composite; } @Override public ITypeInfoFilterExtension getFilterExtension() { return new ITypeInfoFilterExtension() { @Override public boolean select(ITypeInfoRequestor typeInfoRequestor) { int modifiers = typeInfoRequestor.getModifiers(); if (!Flags.isPublic(modifiers) || Flags.isInterface(modifiers) || Flags.isEnum(modifiers)) { return false; } return true; } }; } }); dialogHolder.set(dialog); dialog.setTitle("Choose Fragment Class"); dialog.setMessage("Select a Fragment class (? = any character, * = any string):"); if (dialog.open() == IDialogConstants.CANCEL_ID) { return null; } if (returnValue.get() != null) { return returnValue.get(); } Object[] types = dialog.getResult(); if (types != null && types.length > 0) { return ((IType) types[0]).getFullyQualifiedName(); } } catch (JavaModelException e) { AdtPlugin.log(e, null); } catch (CoreException e) { AdtPlugin.log(e, null); } return null; }
From source file:com.sysunite.weaver.nifi.FilterXMLNodes.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException { final FlowFile flowFileIn = session.get(); if (flowFileIn == null) { return;//from w ww . j a v a 2 s .c o m } final AtomicReference<InputStream> savedNode = new AtomicReference<>(); //read the flow file session.read(flowFileIn, new InputStreamCallback() { @Override public void process(InputStream isIn) throws IOException { //System.out.println("contact!"); try { String contents = IOUtils.toString(isIn); XML xmlNode = new XMLDocument(contents); System.out.println(xmlNode.toString()); // works: .xpath("/FunctionalPhysicalObject/@name") String attributeToSearchFor = context.getProperty(PROP_NODE_ATTRIBUTE).getValue(); // name attributeToSearchFor = "@" + attributeToSearchFor; //@name String nodeToSearchFor = context.getProperty(PROP_NODE).getValue(); //FunctionalPhysicalObject nodeToSearchFor = "/" + nodeToSearchFor + "/"; // /FunctionalPhysicalObject/ String fullNodePathWithAttribute = nodeToSearchFor + attributeToSearchFor; // /FunctionalPhysicalObject/@name //System.out.println(fullNodePathWithAttribute); String valueOfAttribute = xmlNode.xpath(fullNodePathWithAttribute).get(0); //System.out.println("naam: " + valueOfAttribute); //"(.*)AB(.*)CT(.*)" String filter = context.getProperty(PROP_PREGMATCH).getValue(); if (valueOfAttribute.matches(filter)) { //System.out.println("match!!"); //dit is de node die we echt willen! InputStream is = new ByteArrayInputStream(xmlNode.toString().getBytes()); savedNode.set(is); } } catch (IOException e) { System.out.println("w00t");// + e.getMessage()); } catch (IllegalArgumentException e) { System.out.println("is xml niet geldig?"); } catch (IndexOutOfBoundsException e) { System.out.println("bah! de node waar gezocht naar moet worden is niet gevonden!"); } } }); session.remove(flowFileIn); //process what we have read try { //check if there is something to process String contents = IOUtils.toString(savedNode.get()); if (contents != null && contents.length() > 0) { FlowFile flowfileOut = session.create(); XML xmlNode = new XMLDocument(contents); InputStream data = new ByteArrayInputStream(xmlNode.toString().getBytes()); flowfileOut = session.importFrom(data, flowfileOut); session.transfer(flowfileOut, MY_RELATIONSHIP); session.commit(); } } catch (IOException e) { System.out.println("w00t");// + e.getMessage()); } catch (IllegalArgumentException e) { System.out.println("xml niet geldig?"); } catch (NullPointerException e) { System.out.println("zonder gevonden node geen waarde om te initialiseren."); } }
From source file:com.wk.lodge.composite.web.tomcat.IntegrationCompositeTests.java
@Test public void testUpdate() throws Exception { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<Throwable> failure = new AtomicReference<>(); URI uri = new URI("ws://localhost:" + port + "/composite"); WebSocketStompClient stompClient = new WebSocketStompClient(uri, this.headers, sockJsClient); stompClient.setMessageConverter(new MappingJackson2MessageConverter()); stompClient.connect(new StompMessageHandler() { private StompSession stompSession; @Override//from w w w . jav a 2s .c om public void afterConnected(StompSession stompSession, StompHeaderAccessor headers) { this.stompSession = stompSession; String topicUuid = simulateJoinEvent(); this.stompSession.subscribe("/user/queue/device", null); this.stompSession.subscribe(String.format("/topic/%s", topicUuid), null); try { HashMap<String, Object> update = new HashMap<String, Object>(); update.put("data", "TEST-UPDATE Data"); update.put("type", "update"); this.stompSession.send(String.format("/app/%s", topicUuid), update); } catch (Throwable t) { failure.set(t); latch.countDown(); } } @Override public void handleMessage(Message<byte[]> message) throws MessagingException { try { String json = parseMessageJson(message); new JsonPathExpectationsHelper("type").exists(json); new JsonPathExpectationsHelper("type").assertValue(json, "update"); new JsonPathExpectationsHelper("serverTime").exists(json); new JsonPathExpectationsHelper("data").assertValue(json, "TEST-UPDATE Data"); } catch (Throwable t) { failure.set(t); } finally { this.stompSession.disconnect(); latch.countDown(); } } @Override public void handleError(Message<byte[]> message) { StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message); String error = "[Producer] " + accessor.getShortLogMessage(message.getPayload()); logger.error(error); failure.set(new Exception(error)); } @Override public void handleReceipt(String receiptId) { } @Override public void afterDisconnected() { } }); if (!latch.await(10, TimeUnit.SECONDS)) { fail("Update response not received"); } else if (failure.get() != null) { throw new AssertionError("", failure.get()); } }
From source file:com.wk.lodge.composite.web.tomcat.IntegrationCompositeTests.java
@Test public void testStart() throws Exception { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<Throwable> failure = new AtomicReference<>(); URI uri = new URI("ws://localhost:" + port + "/composite"); WebSocketStompClient stompClient = new WebSocketStompClient(uri, this.headers, sockJsClient); stompClient.setMessageConverter(new MappingJackson2MessageConverter()); stompClient.connect(new StompMessageHandler() { private StompSession stompSession; @Override//w ww . j a v a2s . c o m public void afterConnected(StompSession stompSession, StompHeaderAccessor headers) { this.stompSession = stompSession; String topicUuid = simulateJoinEvent(); this.stompSession.subscribe("/user/queue/device", null); this.stompSession.subscribe(String.format("/topic/%s", topicUuid), null); try { // send a message to the start endpoint HashMap<String, Object> start = new HashMap<String, Object>(); start.put("data", "Some Data"); start.put("type", "start"); this.stompSession.send(String.format("/app/%s", topicUuid), start); } catch (Throwable t) { failure.set(t); latch.countDown(); } } @Override public void handleMessage(Message<byte[]> message) { try { String json = parseMessageJson(message); new JsonPathExpectationsHelper("type").exists(json); new JsonPathExpectationsHelper("type").assertValue(json, "start"); new JsonPathExpectationsHelper("serverTime").exists(json); } catch (Throwable t) { failure.set(t); } finally { this.stompSession.disconnect(); latch.countDown(); } } @Override public void handleError(Message<byte[]> message) { StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message); String error = "[Producer] " + accessor.getShortLogMessage(message.getPayload()); logger.error(error); failure.set(new Exception(error)); } @Override public void handleReceipt(String receiptId) { } @Override public void afterDisconnected() { } }); if (!latch.await(10, TimeUnit.SECONDS)) { fail("Start response not received"); } else if (failure.get() != null) { throw new AssertionError("", failure.get()); } }
From source file:com.microsoft.tfs.core.clients.versioncontrol.internal.WebServiceLayerLocalWorkspaces.java
@Override public GetOperation[] undoPendingChanges(final String workspaceName, final String ownerName, final ItemSpec[] items, final AtomicReference<Failure[]> failures, final String[] itemAttributeFilters, final String[] itemPropertyFilters, final AtomicBoolean onlineOperation, final boolean deleteAdds, final AtomicReference<ChangePendedFlags> changePendedFlags) { onlineOperation.set(true);/* w w w . j a v a2 s . c o m*/ // set this to none for local workspaces, if the call reaches the server // the flag will get overwritten changePendedFlags.set(ChangePendedFlags.NONE); final Workspace localWorkspace = getLocalWorkspace(workspaceName, ownerName); if (localWorkspace != null) { final AtomicReference<GetOperation[]> toReturn = new AtomicReference<GetOperation[]>(); final LocalWorkspaceTransaction transaction = new LocalWorkspaceTransaction(localWorkspace); try { final AtomicReference<Failure[]> delegateFailures = new AtomicReference<Failure[]>(new Failure[0]); final AtomicBoolean onlineOperationRequired = new AtomicBoolean(false); transaction.execute(new AllTablesTransaction() { @Override public void invoke(final LocalWorkspaceProperties wp, final WorkspaceVersionTable lv, final LocalPendingChangesTable pc) { toReturn.set(LocalDataAccessLayer.undoPendingChanges(localWorkspace, wp, lv, pc, items, delegateFailures, onlineOperationRequired, itemPropertyFilters)); if (onlineOperationRequired.get()) { transaction.abort(); toReturn.set(null); } /* * we should check to see if we are going to cause an * existing file conflict if we are abort the * transaction - since we don't want to try and contact * the server in an offline undo. */ if (toReturn.get() != null) { Map<String, GetOperation> localItemDictionary = null; for (final GetOperation op : toReturn.get()) { if (op.getItemType() == ItemType.FILE && op.getTargetLocalItem() != null && op.getTargetLocalItem().length() > 0 && LocalPath.equals(op.getTargetLocalItem(), op.getCurrentLocalItem()) == false) { final WorkspaceLocalItem item = lv.getByLocalItem(op.getTargetLocalItem()); if ((item == null || item.isDeleted()) && new File(op.getTargetLocalItem()).exists()) { if (localItemDictionary == null) { localItemDictionary = new HashMap<String, GetOperation>(); /* * we go through our list and keep * track of adds we are removing * this is for the shelve /move * case. */ for (final GetOperation getOp : toReturn.get()) { if (getOp.getTargetLocalItem() != null && getOp.getTargetLocalItem().length() > 0 && getOp.getItemType() == ItemType.FILE) { final GetOperation currentValue = localItemDictionary .get(getOp.getTargetLocalItem()); if (currentValue != null) { // don't overwrite an // add if (currentValue.getChangeType().contains(ChangeType.ADD)) { localItemDictionary.put(getOp.getTargetLocalItem(), getOp); } } else { localItemDictionary.put(getOp.getTargetLocalItem(), getOp); } } } } final GetOperation existingItem = localItemDictionary .get(op.getTargetLocalItem()); if (existingItem != null && existingItem.getChangeType().contains(ChangeType.ADD)) { /* * if we are going to be removing * this anyway don't worry */ if (deleteAdds) { continue; } } if (existingItem == null || !tryMoveAddLocation(existingItem, localItemDictionary)) { throw new VersionControlException(MessageFormat.format( //@formatter:off Messages.getString( "WebServiceLayerLocalWorkspaces.UndoItemExistsLocallyFormat"), //$NON-NLS-1$ //@formatter:on (op.getCurrentLocalItem() != null && op.getCurrentLocalItem().length() > 0) ? op.getCurrentLocalItem() : op.getTargetLocalItem(), op.getTargetLocalItem())); } } } } } } }); if (null != toReturn.get()) { onlineOperation.set(false); failures.set(delegateFailures.get()); return toReturn.get(); } } finally { try { transaction.close(); } catch (final IOException e) { throw new VersionControlException(e); } } final Workspace w = reconcileIfLocal(workspaceName, ownerName); // Lock the workspace which will receive the pending changes final WorkspaceLock lock = lockIfLocal(w); try { try { if (getServiceLevel().getValue() >= WebServiceLevel.TFS_2012_QU1.getValue()) { final _Repository5Soap_UndoPendingChangesInLocalWorkspaceResponse response = getRepository5() .undoPendingChangesInLocalWorkspace(workspaceName, ownerName, (_ItemSpec[]) WrapperUtils.unwrap(_ItemSpec.class, items), itemPropertyFilters, itemAttributeFilters, VersionControlConstants.MAX_SERVER_PATH_SIZE); failures.set((Failure[]) WrapperUtils.wrap(Failure.class, response.getFailures())); changePendedFlags.set(new ChangePendedFlags(response.getChangePendedFlags())); toReturn.set((GetOperation[]) WrapperUtils.wrap(GetOperation.class, response.getUndoPendingChangesInLocalWorkspaceResult())); } else { final _Repository4Soap_UndoPendingChangesInLocalWorkspaceResponse response = getRepository4() .undoPendingChangesInLocalWorkspace(workspaceName, ownerName, (_ItemSpec[]) WrapperUtils.unwrap(_ItemSpec.class, items), itemPropertyFilters, itemAttributeFilters); failures.set((Failure[]) WrapperUtils.wrap(Failure.class, response.getFailures())); changePendedFlags.set(new ChangePendedFlags(response.getChangePendedFlags())); toReturn.set((GetOperation[]) WrapperUtils.wrap(GetOperation.class, response.getUndoPendingChangesInLocalWorkspaceResult())); } } catch (final ProxyException e) { VersionControlExceptionMapper.map(e); } syncWorkingFoldersIfNecessary(w, changePendedFlags.get()); syncPendingChangesIfLocal(w, toReturn.get(), itemPropertyFilters); // When a pending add is undone, the item on disk is not // touched; so we need to inform the scanner that the item is // invalidated so it is re-scanned. We'll invalidate the scanner // if we detect that we went to the server to undo a pending // add. if (null != toReturn.get()) { for (final GetOperation op : toReturn.get()) { if (op.getChangeType().contains(ChangeType.ADD)) { localWorkspace.getWorkspaceWatcher().markPathChanged(""); //$NON-NLS-1$ break; } } } return toReturn.get(); } finally { if (lock != null) { lock.close(); } } } else { return super.undoPendingChanges(workspaceName, ownerName, items, failures, itemAttributeFilters, itemPropertyFilters, onlineOperation, deleteAdds, changePendedFlags); } }
From source file:com.wk.lodge.composite.web.tomcat.IntegrationCompositeTests.java
@Test public void testData() throws Exception { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<Throwable> failure = new AtomicReference<>(); URI uri = new URI("ws://localhost:" + port + "/composite"); WebSocketStompClient stompClient = new WebSocketStompClient(uri, this.headers, sockJsClient); stompClient.setMessageConverter(new MappingJackson2MessageConverter()); stompClient.connect(new StompMessageHandler() { private StompSession stompSession; @Override//from www .jav a2 s.co m public void afterConnected(StompSession stompSession, StompHeaderAccessor headers) { this.stompSession = stompSession; String topicUuid = simulateJoinEvent(); this.stompSession.subscribe("/user/queue/device", null); this.stompSession.subscribe(String.format("/topic/%s", topicUuid), null); try { // send a simple hashmap to the data endpoint HashMap<String, Object> data = new HashMap<String, Object>(); data.put("data", "TEST-DATA Data"); data.put("type", "data"); this.stompSession.send(String.format("/app/%s", topicUuid), data); } catch (Throwable t) { failure.set(t); latch.countDown(); } } @Override public void handleMessage(Message<byte[]> message) { try { String json = parseMessageJson(message); new JsonPathExpectationsHelper("type").exists(json); new JsonPathExpectationsHelper("type").assertValue(json, "data"); new JsonPathExpectationsHelper("serverTime").exists(json); new JsonPathExpectationsHelper("data").assertValue(json, "TEST-DATA Data"); } catch (Throwable t) { failure.set(t); } finally { this.stompSession.disconnect(); latch.countDown(); } } @Override public void handleError(Message<byte[]> message) { StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message); String error = "[Producer] " + accessor.getShortLogMessage(message.getPayload()); logger.error(error); failure.set(new Exception(error)); } @Override public void handleReceipt(String receiptId) { } @Override public void afterDisconnected() { } }); if (!latch.await(10, TimeUnit.SECONDS)) { fail("Data response not received"); } else if (failure.get() != null) { throw new AssertionError("", failure.get()); } }
From source file:org.elasticsearch.client.sniff.SnifferTests.java
/** * Test multiple sniffing rounds by mocking the {@link Scheduler} as well as the {@link HostsSniffer}. * Simulates the ordinary behaviour of {@link Sniffer} when sniffing on failure is not enabled. * The {@link CountingHostsSniffer} doesn't make any network connection but may throw exception or return no hosts, which makes * it possible to verify that errors are properly handled and don't affect subsequent runs and their scheduling. * The {@link Scheduler} implementation submits rather than scheduling tasks, meaning that it doesn't respect the requested sniff * delays while allowing to assert that the requested delays for each requested run and the following one are the expected values. *//* w w w .j a v a 2s . com*/ public void testOrdinarySniffRounds() throws Exception { final long sniffInterval = randomLongBetween(1, Long.MAX_VALUE); long sniffAfterFailureDelay = randomLongBetween(1, Long.MAX_VALUE); RestClient restClient = mock(RestClient.class); CountingHostsSniffer hostsSniffer = new CountingHostsSniffer(); final int iters = randomIntBetween(30, 100); final Set<Future<?>> futures = new CopyOnWriteArraySet<>(); final CountDownLatch completionLatch = new CountDownLatch(1); final AtomicInteger runs = new AtomicInteger(iters); final ExecutorService executor = Executors.newSingleThreadExecutor(); final AtomicReference<Future<?>> lastFuture = new AtomicReference<>(); final AtomicReference<Sniffer.Task> lastTask = new AtomicReference<>(); Scheduler scheduler = new Scheduler() { @Override public Future<?> schedule(Sniffer.Task task, long delayMillis) { assertEquals(sniffInterval, task.nextTaskDelay); int numberOfRuns = runs.getAndDecrement(); if (numberOfRuns == iters) { //the first call is to schedule the first sniff round from the Sniffer constructor, with delay O assertEquals(0L, delayMillis); assertEquals(sniffInterval, task.nextTaskDelay); } else { //all of the subsequent times "schedule" is called with delay set to the configured sniff interval assertEquals(sniffInterval, delayMillis); assertEquals(sniffInterval, task.nextTaskDelay); if (numberOfRuns == 0) { completionLatch.countDown(); return null; } } //we submit rather than scheduling to make the test quick and not depend on time Future<?> future = executor.submit(task); futures.add(future); if (numberOfRuns == 1) { lastFuture.set(future); lastTask.set(task); } return future; } @Override public void shutdown() { //the executor is closed externally, shutdown is tested separately } }; try { new Sniffer(restClient, hostsSniffer, scheduler, sniffInterval, sniffAfterFailureDelay); assertTrue("timeout waiting for sniffing rounds to be completed", completionLatch.await(1000, TimeUnit.MILLISECONDS)); assertEquals(iters, futures.size()); //the last future is the only one that may not be completed yet, as the count down happens //while scheduling the next round which is still part of the execution of the runnable itself. assertTrue(lastTask.get().hasStarted()); lastFuture.get().get(); for (Future<?> future : futures) { assertTrue(future.isDone()); future.get(); } } finally { executor.shutdown(); assertTrue(executor.awaitTermination(1000, TimeUnit.MILLISECONDS)); } int totalRuns = hostsSniffer.runs.get(); assertEquals(iters, totalRuns); int setHostsRuns = totalRuns - hostsSniffer.failures.get() - hostsSniffer.emptyList.get(); verify(restClient, times(setHostsRuns)).setHosts(Matchers.<HttpHost>anyVararg()); verifyNoMoreInteractions(restClient); }
From source file:com.wk.lodge.composite.web.tomcat.IntegrationCompositeTests.java
@Test public void testJoin() throws Exception { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<Throwable> failure = new AtomicReference<Throwable>(); URI uri = new URI("ws://localhost:" + port + "/composite"); WebSocketStompClient stompClient = new WebSocketStompClient(uri, this.headers, sockJsClient); stompClient.setMessageConverter(new MappingJackson2MessageConverter()); stompClient.connect(new StompMessageHandler() { private StompSession stompSession; @Override// w w w .j a va2s .c o m public void afterConnected(StompSession stompSession, StompHeaderAccessor headers) { this.stompSession = stompSession; this.stompSession.subscribe("/user/queue/device", null); try { JoinMessage join = new JoinMessage(); Device d = new Device(); d.setUuid(UUID.randomUUID()); join.setDevice(d); join.setGeo(new float[] { lat, lon }); join.setType(JoinMessage.Types.exit); join.setPoint(new int[] { 0, 0 }); join.setVector(new float[] { 1, 1 }); stompSession.send("/app/join", join); } catch (Throwable t) { failure.set(t); latch.countDown(); } } @Override public void handleMessage(Message<byte[]> message) { try { String json = parseMessageJson(message); new JsonPathExpectationsHelper("devices").exists(json); new JsonPathExpectationsHelper("devices").assertValueIsArray(json); new JsonPathExpectationsHelper("type").assertValue(json, "join"); } catch (Throwable t) { failure.set(t); } finally { this.stompSession.disconnect(); latch.countDown(); } } @Override public void handleError(Message<byte[]> message) { StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message); String error = "[Producer] " + accessor.getShortLogMessage(message.getPayload()); logger.error(error); failure.set(new Exception(error)); } @Override public void handleReceipt(String receiptId) { } @Override public void afterDisconnected() { } }); if (!latch.await(10, TimeUnit.SECONDS)) { fail("Join response not received"); } else if (failure.get() != null) { throw new AssertionError("", failure.get()); } }