List of usage examples for java.util.concurrent.atomic AtomicBoolean AtomicBoolean
public AtomicBoolean(boolean initialValue)
From source file:com.jkoolcloud.tnt4j.streams.parsers.GenericActivityParser.java
/** * Gets field value from raw data location and formats it according locator definition. * * @param locator//from www . ja va 2 s . co m * activity field locator * @param cData * parsing context data package * @return value formatted based on locator definition or {@code null} if locator is not defined * @throws ParseException * if exception occurs applying locator format properties to specified value * @see ActivityFieldLocator#formatValue(Object) */ protected Object getLocatorValue(ActivityFieldLocator locator, ActivityContext cData) throws ParseException { Object val = null; if (locator != null) { String locStr = locator.getLocator(); AtomicBoolean formattingNeeded = new AtomicBoolean(true); if (StringUtils.isNotEmpty(locStr)) { if (locator.getBuiltInType() == ActivityFieldLocatorType.StreamProp) { val = cData.getStream().getProperty(locStr); } else if (locator.getBuiltInType() == ActivityFieldLocatorType.Cache) { val = Utils.simplifyValue(StreamsCache.getValue(cData.getActivity(), locStr, getName())); } else if (locator.getBuiltInType() == ActivityFieldLocatorType.Activity) { val = cData.getActivity().getFieldValue(locator.getLocator()); } else { val = resolveLocatorValue(locator, cData, formattingNeeded); // logger().log(val == null && !locator.isOptional() ? OpLevel.WARNING : OpLevel.TRACE, logger().log(OpLevel.TRACE, StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME, "ActivityParser.locator.resolved"), locStr, toString(val)); } } if (formattingNeeded.get()) { val = locator.formatValue(val); } try { val = locator.transformValue(val); } catch (Exception exc) { logger().log(OpLevel.WARNING, StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME, "ActivityParser.transformation.failed"), locStr, toString(val), exc); } try { boolean filteredOut = locator.filterValue(val); if (filteredOut) { val = null; } } catch (Exception exc) { logger().log(OpLevel.WARNING, StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME, "ActivityParser.field.filtering.failed"), locStr, toString(val), exc); } } return val; }
From source file:com.alibaba.napoli.gecko.service.impl.BaseRemotingController.java
public void sendToGroups(final Map<String, RequestCommand> groupObjects, final MultiGroupCallBackListener listener, final long timeout, final TimeUnit timeUnit, final Object... args) throws NotifyRemotingException { if (groupObjects == null || groupObjects.size() == 0) { throw new NotifyRemotingException("groupObject"); }//from ww w . j ava2 s . co m if (listener == null) { throw new NotifyRemotingException("Null GroupCallBackListener"); } if (timeUnit == null) { throw new NotifyRemotingException("Null TimeUnit"); } // final CountDownLatch countDownLatch = new CountDownLatch(groupObjects.size()); final ConcurrentHashMap<String/* group */, ResponseCommand/* */> resultMap = new ConcurrentHashMap<String, ResponseCommand>(); // final Map<String/* group */, Connection> connectionMap = new HashMap<String, Connection>(); // final Map<String/* group */, CommandHeader> headerMap = new HashMap<String, CommandHeader>(); // ???? final AtomicBoolean responsed = new AtomicBoolean(false); InetSocketAddress remoteAddr = null; // ????? final long now = System.currentTimeMillis(); final long timeoutInMillis = TimeUnit.MILLISECONDS.convert(timeout, timeUnit); // callBack final MultiGroupRequestCallBack groupRequestCallBack = new MultiGroupRequestCallBack(listener, countDownLatch, timeoutInMillis, now, resultMap, responsed, args); // final TimerRef timerRef = new TimerRef(timeoutInMillis, new GroupCallBackRunner(connectionMap, groupRequestCallBack, headerMap, resultMap, remoteAddr)); groupRequestCallBack.setTimerRef(timerRef); for (final Map.Entry<String, RequestCommand> entry : groupObjects.entrySet()) { final RequestCommand requestCommand = entry.getValue(); final String group = entry.getKey(); final DefaultConnection conn = (DefaultConnection) this.selectConnectionForGroup(group, this.connectionSelector, requestCommand); if (conn != null) { try { // connectionMap.put(group, conn); // conn.addOpaqueToGroupMapping(requestCommand.getOpaque(), group); // conn.addRequestCallBack(requestCommand.getOpaque(), groupRequestCallBack); if (remoteAddr == null) { remoteAddr = conn.getRemoteSocketAddress(); } groupRequestCallBack.addWriteFuture(conn, conn.asyncSend(requestCommand)); headerMap.put(group, requestCommand.getRequestHeader()); } catch (final Throwable t) { groupRequestCallBack.onResponse(group, this.createCommErrorResponseCommand(requestCommand.getRequestHeader(), t.getMessage()), conn); } } else { // groupRequestCallBack.onResponse(group, this.createNoConnectionResponseCommand(requestCommand.getRequestHeader()), null); } } // ? this.insertTimer(timerRef); }
From source file:com.vmware.admiral.compute.container.HostContainerListDataCollection.java
private void checkIfSystemContainerStateExistsBeforeStartIt(ContainerState containerState, ContainerDescription containerDesc, String containerHostLink) { QueryTask containerQuery = QueryUtil.buildPropertyQuery(ContainerState.class, ContainerState.FIELD_NAME_DESCRIPTION_LINK, SystemContainerDescriptions.AGENT_CONTAINER_DESCRIPTION_LINK, ContainerState.FIELD_NAME_PARENT_LINK, containerState.parentLink);//from w w w .j a va2 s. com QueryUtil.addExpandOption(containerQuery); AtomicBoolean stateExists = new AtomicBoolean(false); new ServiceDocumentQuery<ContainerState>(getHost(), ContainerState.class).query(containerQuery, (r) -> { if (r.hasException()) { logWarning("Failed to retrieve system container state: %s", containerState.documentSelfLink); } else if (r.hasResult()) { // If System ContainerState exists, all supported container // operations start/stop will work. stateExists.set(true); } else { if (stateExists.get()) { // If System ContainerState exists we can start it. // if version is valid, although we don't know the power state, // start the containers anyway as start is idempotent logFine("start existing system container %s", containerState.documentSelfLink); startSystemContainer(containerState, null); } else { // If System ContainerState does not exists, we create it before // start operation. final ContainerState systemContainerState = createSystemContainerState(containerState, containerDesc, containerHostLink); sendRequest(OperationUtil.createForcedPost(this, ContainerFactoryService.SELF_LINK) .setBody(systemContainerState).setCompletion((o, e) -> { if (e != null) { logWarning("Failure creating system container: " + Utils.toString(e)); return; } ContainerState body = o.getBody(ContainerState.class); logInfo("Created system ContainerState: %s ", body.documentSelfLink); createSystemContainerInstanceRequest(body, null); updateNumberOfContainers(containerHostLink); startSystemContainer(containerState, null); })); } } }); }
From source file:io.atomix.protocols.gossip.map.AntiEntropyMapDelegate.java
private void processUpdates(Collection<UpdateEntry> updates) { if (closed) { return;/*from www . j a v a 2 s.c o m*/ } updates.forEach(update -> { final String key = update.key(); final MapValue value = update.value() == null ? null : update.value().copy(); if (value == null || value.isTombstone()) { MapValue previousValue = removeInternal(key, Optional.empty(), Optional.ofNullable(value)); if (previousValue != null && previousValue.isAlive()) { notifyListeners( new MapDelegateEvent<>(REMOVE, decodeKey(key), previousValue.get(this::decodeValue))); } } else { counter.incrementCount(); AtomicReference<byte[]> oldValue = new AtomicReference<>(); AtomicBoolean updated = new AtomicBoolean(false); items.compute(key, (k, existing) -> { if (existing == null || value.isNewerThan(existing)) { updated.set(true); oldValue.set(existing != null ? existing.get() : null); return value; } return existing; }); if (updated.get()) { if (oldValue.get() == null) { notifyListeners(new MapDelegateEvent<>(INSERT, decodeKey(key), decodeValue(value.get()))); } else { notifyListeners(new MapDelegateEvent<>(UPDATE, decodeKey(key), decodeValue(value.get()))); } } } }); }
From source file:com.amazonaws.services.kinesis.clientlibrary.lib.worker.WorkerTest.java
/** * This test is testing the {@link Worker}'s shutdown behavior and by extension the behavior of * {@link ThreadPoolExecutor#shutdownNow()}. It depends on the thread pool sending an interrupt to the pool threads. * This behavior makes the test a bit racy, since we need to ensure a specific order of events. * /*from w w w . j ava2s. c om*/ * @throws Exception */ @Test public final void testWorkerForcefulShutdown() throws Exception { final List<Shard> shardList = createShardListWithOneShard(); final boolean callProcessRecordsForEmptyRecordList = true; final long failoverTimeMillis = 50L; final int numberOfRecordsPerShard = 10; final List<KinesisClientLease> initialLeases = new ArrayList<KinesisClientLease>(); for (Shard shard : shardList) { KinesisClientLease lease = ShardSyncer.newKCLLease(shard); lease.setCheckpoint(ExtendedSequenceNumber.TRIM_HORIZON); initialLeases.add(lease); } final File file = KinesisLocalFileDataCreator.generateTempDataFile(shardList, numberOfRecordsPerShard, "normalShutdownUnitTest"); final IKinesisProxy fileBasedProxy = new KinesisLocalFileProxy(file.getAbsolutePath()); // Get executor service that will be owned by the worker, so we can get interrupts. ExecutorService executorService = getWorkerThreadPoolExecutor(); // Make test case as efficient as possible. final CountDownLatch processRecordsLatch = new CountDownLatch(1); final AtomicBoolean recordProcessorInterrupted = new AtomicBoolean(false); when(v2RecordProcessorFactory.createProcessor()).thenReturn(v2RecordProcessor); final Semaphore actionBlocker = new Semaphore(1); final Semaphore shutdownBlocker = new Semaphore(1); actionBlocker.acquire(); doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { // Signal that record processor has started processing records. processRecordsLatch.countDown(); // Block for some time now to test forceful shutdown. Also, check if record processor // was interrupted or not. final long startTimeMillis = System.currentTimeMillis(); long elapsedTimeMillis = 0; LOG.info("Entering sleep @ " + startTimeMillis + " with elapsedMills: " + elapsedTimeMillis); shutdownBlocker.acquire(); try { actionBlocker.acquire(); } catch (InterruptedException e) { LOG.info("Sleep interrupted @ " + System.currentTimeMillis() + " elapsedMillis: " + (System.currentTimeMillis() - startTimeMillis)); recordProcessorInterrupted.getAndSet(true); } shutdownBlocker.release(); elapsedTimeMillis = System.currentTimeMillis() - startTimeMillis; LOG.info( "Sleep completed @ " + System.currentTimeMillis() + " elapsedMillis: " + elapsedTimeMillis); return null; } }).when(v2RecordProcessor).processRecords(any(ProcessRecordsInput.class)); WorkerThread workerThread = runWorker(shardList, initialLeases, callProcessRecordsForEmptyRecordList, failoverTimeMillis, numberOfRecordsPerShard, fileBasedProxy, v2RecordProcessorFactory, executorService, nullMetricsFactory); // Only sleep for time that is required. processRecordsLatch.await(); // Make sure record processor is initialized and processing records. verify(v2RecordProcessorFactory, times(1)).createProcessor(); verify(v2RecordProcessor, times(1)).initialize(any(InitializationInput.class)); verify(v2RecordProcessor, atLeast(1)).processRecords(any(ProcessRecordsInput.class)); verify(v2RecordProcessor, times(0)).shutdown(any(ShutdownInput.class)); workerThread.getWorker().shutdown(); workerThread.join(); Assert.assertTrue(workerThread.getState() == State.TERMINATED); // Shutdown should not be called in this case because record processor is blocked. verify(v2RecordProcessor, times(0)).shutdown(any(ShutdownInput.class)); // // Release the worker thread // actionBlocker.release(); // // Give the worker thread time to execute it's interrupted handler. // shutdownBlocker.tryAcquire(100, TimeUnit.MILLISECONDS); // // Now we can see if it was actually interrupted. It's possible it wasn't and this will fail. // assertThat(recordProcessorInterrupted.get(), equalTo(true)); }
From source file:com.atlassian.jira.bc.group.TestDefaultGroupService.java
@Test public void testDeleteHappyPath() { final Mock mockProjectRoleService = new Mock(ProjectRoleService.class); mockProjectRoleService.setStrict(true); mockProjectRoleService.expectVoid("removeAllRoleActorsByNameAndType", P.ANY_ARGS); final Mock mockPermissionManager = new Mock(PermissionManager.class); mockPermissionManager.setStrict(true); mockPermissionManager.expectAndReturn("hasPermission", P.args(P.eq(Permissions.ADMINISTER), P.IS_ANYTHING), Boolean.TRUE);//from w w w .java2 s. co m mockPermissionManager.expectVoid("removeGroupPermissions", P.args(P.eq("TestGroup"))); final Mock mockNotificationManager = new Mock(NotificationSchemeManager.class); mockNotificationManager.setStrict(true); mockNotificationManager.expectAndReturn("removeEntities", P.args(P.eq(GroupDropdown.DESC), P.eq("TestGroup")), Boolean.TRUE); final Mock mockSubscriptionManager = new Mock(SubscriptionManager.class); mockSubscriptionManager.setStrict(true); mockSubscriptionManager.expectVoid("deleteSubscriptionsForGroup", P.ANY_ARGS); final AtomicBoolean calledSharePermissionDeleteUtils = new AtomicBoolean(false); final SharePermissionDeleteUtils deleteUtils = new SharePermissionDeleteUtils(null) { @Override public void deleteGroupPermissions(final String groupName) { calledSharePermissionDeleteUtils.set(true); } }; final AtomicBoolean updateCommentAndGroupsCalled = new AtomicBoolean(false); final AtomicBoolean removeGroupCalled = new AtomicBoolean(false); final AtomicBoolean clearCalled = new AtomicBoolean(false); final DefaultGroupService defaultGroupService = new DefaultGroupService(null, null, null, null, (NotificationSchemeManager) mockNotificationManager.proxy(), (PermissionManager) mockPermissionManager.proxy(), (ProjectRoleService) mockProjectRoleService.proxy(), null, null, deleteUtils, (SubscriptionManager) mockSubscriptionManager.proxy(), null, null, null) { @Override void updateCommentsAndWorklogs(final User user, final String groupName, final String swapGroup) { updateCommentAndGroupsCalled.set(true); } @Override Group getGroup(final String groupName) { return null; } @Override void removeGroup(final Group group) throws PermissionException { removeGroupCalled.set(true); } @Override void clearIssueSecurityLevelCache() { clearCalled.set(true); } }; final ErrorCollection errorCollection = new SimpleErrorCollection(); final JiraServiceContext jiraServiceContext = getContext(errorCollection); assertTrue(defaultGroupService.delete(jiraServiceContext, "TestGroup", "SwapGroup")); assertTrue(updateCommentAndGroupsCalled.get()); assertTrue(clearCalled.get()); assertTrue(removeGroupCalled.get()); assertTrue(calledSharePermissionDeleteUtils.get()); mockPermissionManager.verify(); mockProjectRoleService.verify(); mockNotificationManager.verify(); mockSubscriptionManager.verify(); }
From source file:de.acosix.alfresco.mtsupport.repo.sync.TenantAwareChainingUserRegistrySynchronizer.java
protected void synchronize(final boolean forceUpdate, final boolean isFullSync, final boolean splitTxns) { final String currentDomain = TenantUtil.getCurrentDomain(); LOGGER.debug("Running {} sync with deletions {}allowed in tenant {}", forceUpdate ? "full" : "differential", this.allowDeletions ? "" : "not ", TenantService.DEFAULT_DOMAIN.equals(currentDomain) ? "-default-" : currentDomain); final QName lockQName = this.getLockQNameForCurrentTenant(); String lockToken;/* w ww. jav a 2s . c o m*/ try { // splitTxns = true: likely startup-triggered so give up immediately if lock not available // (startup of a cluster node already performs synchronisation) // splitTxns = false: likely login-triggered so wait for the lock and retry lockToken = this.jobLockService.getLock(lockQName, LOCK_TTL, splitTxns ? 0 : LOCK_TTL, splitTxns ? 1 : 10); } catch (final LockAcquisitionException laex) { LOGGER.warn( "User registry synchronization already running in another thread / on another cluster node. Synchronize aborted"); lockToken = null; } if (lockToken != null) { final AtomicBoolean synchRunning = new AtomicBoolean(true); final AtomicBoolean lockReleased = new AtomicBoolean(false); try { // original class used complex setup with asynch refresher thread // this was legacy never adapted when JobLockRefreshCallback was introduced in 3.4 this.jobLockService.refreshLock(lockToken, lockQName, LOCK_TTL, new JobLockRefreshCallback() { /** * {@inheritDoc} */ @Override public void lockReleased() { lockReleased.set(true); } @Override public boolean isActive() { return synchRunning.get(); } }); final Map<String, UserRegistry> plugins = this.getPluginsToSync(); final Set<String> visitedIds = new TreeSet<>(); this.notifySyncStart(plugins.keySet()); for (final Entry<String, UserRegistry> pluginEntry : plugins.entrySet()) { final String id = pluginEntry.getKey(); final UserRegistry plugin = pluginEntry.getValue(); if (LOGGER.isDebugEnabled() && this.mbeanServer != null) { this.logPluginConfig(id); } LOGGER.info("Synchronizing users and groups with user registry {} in tenant {}", id, TenantService.DEFAULT_DOMAIN.equals(currentDomain) ? "-default-" : currentDomain); if (isFullSync) { LOGGER.info( "Full synchronisation with user registry {} in tenant {} - deletions enabled: {} (if true, some users and groups previously created by synchronization with this user registry may be removed, otherwise users / groups removed from this registry will be logged only and remain in the repository while users previously found in a different registry will be moved in the repository rather than recreated)", id, TenantService.DEFAULT_DOMAIN.equals(currentDomain) ? "-default-" : currentDomain, this.allowDeletions); } final boolean requiresNew = splitTxns || AlfrescoTransactionSupport.getTransactionReadState() == TxnReadState.TXN_READ_ONLY; this.syncWithPlugin(id, plugin, forceUpdate, isFullSync, requiresNew, visitedIds, plugins.keySet()); this.applicationEventPublisher.publishEvent(new SynchronizeDirectoryEndEvent(this, id)); } this.notifySyncEnd(); } catch (final RuntimeException re) { this.notifySyncEnd(re); LOGGER.error("Synchronization aborted due to error", re); throw re; } finally { synchRunning.set(false); this.jobLockService.releaseLock(lockToken, lockQName); } } }
From source file:com.photon.maven.plugins.android.AbstractAndroidMojo.java
/** * Undeploys an apk, specified by package name, from a connected emulator or * usb device. Also deletes the application's data and cache directories on * the device.// w ww. ja va 2s . c o m * * @param packageName * the package name to undeploy. * @return <code>true</code> if successfully undeployed, <code>false</code> * otherwise. */ protected boolean undeployApk(final String packageName) throws MojoExecutionException, MojoFailureException { final AtomicBoolean result = new AtomicBoolean(true); // if no devices // are present, // it counts as // successful doWithDevices(new DeviceCallback() { @Override public void doWithDevice(final IDevice device) throws MojoExecutionException { try { device.uninstallPackage(packageName); getLog().info("Successfully uninstalled " + packageName + " from " + DeviceHelper.getDescriptiveName(device)); result.set(true); } catch (InstallException e) { result.set(false); throw new MojoExecutionException("Uninstall of " + packageName + "failed.", e); } } }); return result.get(); }
From source file:com.streamsets.pipeline.stage.destination.hdfs.HdfsTargetConfigBean.java
private boolean validateHadoopDir(final Stage.Context context, final String configName, final String configGroup, String dirPathTemplate, final List<Stage.ConfigIssue> issues) { final AtomicBoolean ok = new AtomicBoolean(true); if (!dirPathTemplate.startsWith("/")) { issues.add(context.createConfigIssue(configGroup, configName, Errors.HADOOPFS_40)); ok.set(false);/*www .jav a 2s.c o m*/ } else { dirPathTemplate = (dirPathTemplate.isEmpty()) ? "/" : dirPathTemplate; try { final Path dir = new Path(dirPathTemplate); final FileSystem fs = getFileSystemForInitDestroy(); getUGI().doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { if (!fs.exists(dir)) { try { if (fs.mkdirs(dir)) { ok.set(true); } else { issues.add( context.createConfigIssue(configGroup, configName, Errors.HADOOPFS_41)); ok.set(false); } } catch (IOException ex) { issues.add(context.createConfigIssue(configGroup, configName, Errors.HADOOPFS_42, ex.toString())); ok.set(false); } } else { try { Path dummy = new Path(dir, "_sdc-dummy-" + UUID.randomUUID().toString()); fs.create(dummy).close(); fs.delete(dummy, false); ok.set(true); } catch (IOException ex) { issues.add(context.createConfigIssue(configGroup, configName, Errors.HADOOPFS_43, ex.toString())); ok.set(false); } } return null; } }); } catch (Exception ex) { issues.add(context.createConfigIssue(configGroup, configName, Errors.HADOOPFS_44, ex.toString())); ok.set(false); } } return ok.get(); }
From source file:com.ibm.jaggr.core.impl.layer.LayerImpl.java
/** * De-serialize this object from an ObjectInputStream * @param in The ObjectInputStream//from ww w.j a v a 2 s . c om * @throws IOException * @throws ClassNotFoundException */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { // Call the default implementation to de-serialize our object in.defaultReadObject(); // init transients _validateLastModified = new AtomicBoolean(true); _isReportCacheInfo = false; }