List of usage examples for java.util.concurrent.atomic AtomicBoolean AtomicBoolean
public AtomicBoolean(boolean initialValue)
From source file:com.jayway.restassured.examples.springmvc.controller.AutoSpringSecurityConfigurerITest.java
@Test public void doesnt_add_spring_security_configurer_automatically_when_a_spring_security_configurer_has_been_manually_applied() { final AtomicBoolean filterUsed = new AtomicBoolean(false); given().webAppContextSetup(context, springSecurity(), springSecurity(new Filter() { public void init(FilterConfig filterConfig) throws ServletException { }//from www . j a v a2s.c o m public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { filterUsed.set(true); chain.doFilter(request, response); } public void destroy() { } })).postProcessors(httpBasic("username", "password")).param("name", "Johan").when().get("/secured/greeting") .then().statusCode(200).body("content", equalTo("Hello, Johan!")) .expect(authenticated().withUsername("username")); assertThat(filterUsed.get(), is(true)); }
From source file:biz.ganttproject.impex.csv.CsvImportTest.java
public void testSkipUntilFirstHeader() throws IOException { String notHeader = "FOO, BAR, A"; String header = "A, B"; String data = "a1, b1"; final AtomicBoolean wasCalled = new AtomicBoolean(false); RecordGroup recordGroup = new RecordGroup("ABC", ImmutableSet.<String>of("A", "B")) { @Override//ww w. ja va2 s . c o m protected boolean doProcess(CSVRecord record) { if (!super.doProcess(record)) { return false; } wasCalled.set(true); assertEquals("a1", record.get("A")); assertEquals("b1", record.get("B")); return true; } }; GanttCSVOpen importer = new GanttCSVOpen(createSupplier(Joiner.on('\n').join(notHeader, header, data)), recordGroup); importer.load(); assertTrue(wasCalled.get()); assertEquals(1, importer.getSkippedLineCount()); }
From source file:com.turbospaces.model.BO.java
/** * create business object over actual basic persistent entity * //from www . j a v a 2s . c o m * @param delegate * the actual persistent entity meta-data provider * @throws NoSuchMethodException * re-throw cglib exception * @throws SecurityException * re-throw cglib exception * @throws IntrospectionException * re-throw exceptions */ public BO(final BasicPersistentEntity delegate) throws SecurityException, NoSuchMethodException, IntrospectionException { this.delegate = delegate; this.fastConstructor = FastClass.create(delegate.getType()) .getConstructor(delegate.getType().getConstructor()); // find optimistic lock version/routing fields { final Collection<PersistentProperty> versionCandidates = Lists.newLinkedList(); final Collection<PersistentProperty> routingCandidates = Lists.newLinkedList(); delegate.doWithProperties(new PropertyHandler() { @Override public void doWithPersistentProperty(final PersistentProperty persistentProperty) { PropertyDescriptor propertyDescriptor = persistentProperty.getPropertyDescriptor(); Field field = persistentProperty.getField(); if (hasAnnotation(propertyDescriptor, field, Version.class)) versionCandidates.add(persistentProperty); if (hasAnnotation(propertyDescriptor, field, Routing.class)) routingCandidates.add(persistentProperty); } private boolean hasAnnotation(final PropertyDescriptor descriptor, final Field field, final Class annotation) { if (descriptor != null && descriptor.getReadMethod() != null && descriptor.getReadMethod().getAnnotation(annotation) != null) return true; if (field != null && field.getAnnotation(annotation) != null) return true; return false; } }); Preconditions.checkArgument(versionCandidates.size() <= 1, "too many fields marked with @Version annotation, candidates = " + versionCandidates.toString()); Preconditions.checkArgument(routingCandidates.size() <= 1, "too many fields marked with @Routing annotation, candidates = " + routingCandidates.toString()); if (!versionCandidates.isEmpty()) optimisticLockVersionProperty = versionCandidates.iterator().next(); if (!routingCandidates.isEmpty()) routingProperty = routingCandidates.iterator().next(); } { // Java Beans convention marker AtomicBoolean propertyAccess = new AtomicBoolean(true); List<String> setters = Lists.newLinkedList(); List<String> getters = Lists.newLinkedList(); List<Class<?>> types = Lists.newLinkedList(); for (PersistentProperty<?> persistentProperty : getOrderedProperties()) { PropertyDescriptor propertyDescriptor = persistentProperty.getPropertyDescriptor(); if (propertyDescriptor != null) { if (propertyDescriptor.getReadMethod() != null && propertyDescriptor.getWriteMethod() != null) { setters.add(propertyDescriptor.getWriteMethod().getName()); getters.add(propertyDescriptor.getReadMethod().getName()); types.add(persistentProperty.getType()); } } else { propertyAccess.set(false); brokenProperties.add(persistentProperty); } } if (propertyAccess.get()) // create properties extract for all persistent properties bulkBean = BulkBean.create(delegate.getType(), getters.toArray(new String[getters.size()]), setters.toArray(new String[setters.size()]), types.toArray(new Class[types.size()])); else Log.warn(String.format( "PropetiesSerializer-%s unable to use getters-setters access optimization. Suspected/Corrupted properties = %s", delegate.getType().getSimpleName(), getBrokenProperties())); boolean canOptimizeIdProperty = hasReadWriteMethods(delegate.getIdProperty()); boolean canOptimizeVersionProperty = hasReadWriteMethods(getOptimisticLockVersionProperty()); boolean canOptimizeRoutingProperty = hasReadWriteMethods(getRoutingProperty()); // create id/version/routing bulk fields extractor if (canOptimizeIdProperty && canOptimizeVersionProperty && canOptimizeRoutingProperty) { String[] g = new String[] { delegate.getIdProperty().getPropertyDescriptor().getReadMethod().getName(), getOptimisticLockVersionProperty().getPropertyDescriptor().getReadMethod().getName(), getRoutingProperty().getPropertyDescriptor().getReadMethod().getName() }; String[] s = new String[] { delegate.getIdProperty().getPropertyDescriptor().getWriteMethod().getName(), getOptimisticLockVersionProperty().getPropertyDescriptor().getWriteMethod().getName(), getRoutingProperty().getPropertyDescriptor().getWriteMethod().getName() }; Class<?>[] c = new Class[] { delegate.getIdProperty().getType(), getOptimisticLockVersionProperty().getType(), getRoutingProperty().getType() }; idVersionRoutingBulkBean = BulkBean.create(delegate.getType(), g, s, c); } } }
From source file:net.sourceforge.ganttproject.io.CsvImportTest.java
public void testSkipLinesWithEmptyMandatoryFields() throws IOException { String header = "A, B, C"; String data1 = "a1,,c1"; String data2 = "a2,b2,c2"; String data3 = ",b3,c3"; final AtomicBoolean wasCalled = new AtomicBoolean(false); GanttCSVOpen.RecordGroup recordGroup = new GanttCSVOpen.RecordGroup("ABC", ImmutableSet.<String>of("A", "B", "C"), ImmutableSet.<String>of("A", "B")) { @Override//from ww w. ja v a 2 s. c o m protected boolean doProcess(CSVRecord record) { if (!hasMandatoryFields(record)) { return false; } wasCalled.set(true); assertEquals("a2", record.get("A")); assertEquals("b2", record.get("B")); return true; } }; GanttCSVOpen importer = new GanttCSVOpen(createSupplier(Joiner.on('\n').join(header, data1, data2, data3)), recordGroup); importer.load(); assertTrue(wasCalled.get()); assertEquals(2, importer.getSkippedLineCount()); }
From source file:ddf.catalog.resource.download.ReliableResourceDownloadManager.java
/** * @param resourceRequest// www .jav a 2 s. co m * the original @ResourceRequest to retrieve the resource * @param metacard * the @Metacard associated with the resource being downloaded * @param retriever * the @ResourceRetriever to be used to get the resource * @return the modified @ResourceResponse with the @ReliableResourceInputStream that the client * should read from * @throws DownloadException */ public ResourceResponse download(ResourceRequest resourceRequest, Metacard metacard, ResourceRetriever retriever) throws DownloadException { if (metacard == null) { throw new DownloadException("Cannot download resource if metacard is null"); } else if (StringUtils.isBlank(metacard.getId())) { throw new DownloadException("Metacard must have unique id."); } else if (retriever == null) { throw new DownloadException("Cannot download resource if retriever is null"); } else if (resourceRequest == null) { throw new DownloadException("Cannot download resource if request is null"); } try { resourceResponse = retriever.retrieveResource(); } catch (ResourceNotFoundException | ResourceNotSupportedException | IOException e) { throw new DownloadException("Cannot download resource", e); } resourceResponse.getProperties().put(Metacard.ID, metacard.getId()); // Sources do not create ResourceResponses with the original ResourceRequest, hence // it is added here because it will be needed for caching resourceResponse = new ResourceResponseImpl(resourceRequest, resourceResponse.getProperties(), resourceResponse.getResource()); // TODO - this should be before retrieveResource() but eventPublisher requires a // resourceResponse and that resource response must have a resource request in it (to get // USER property) eventPublisher.postRetrievalStatus(resourceResponse, ProductRetrievalStatus.STARTED, metacard, null, 0L, downloadIdentifier); AtomicBoolean downloadStarted = new AtomicBoolean(Boolean.FALSE); ReliableResourceDownloader downloader = new ReliableResourceDownloader(downloaderConfig, downloadStarted, downloadIdentifier, resourceResponse, retriever); resourceResponse = downloader.setupDownload(metacard, downloadStatusInfo); // Start download in separate thread so can return ResourceResponse with // ReliableResourceInputStream available for client to start reading from executor.submit(downloader); // Wait for download to get started before returning control to client Stopwatch stopwatch = Stopwatch.createStarted(); while (!downloadStarted.get()) { try { Thread.sleep(10); } catch (InterruptedException e) { } long elapsedTime = stopwatch.elapsed(TimeUnit.MILLISECONDS); if (elapsedTime > ONE_SECOND_IN_MS) { LOGGER.debug("downloadStarted still FALSE - elapsedTime = {}", elapsedTime); break; } } LOGGER.debug("elapsedTime = {}", stopwatch.elapsed(TimeUnit.MILLISECONDS)); stopwatch.stop(); return resourceResponse; }
From source file:net.centro.rtb.monitoringcenter.metrics.tomcat.TomcatMetricSet.java
public TomcatMetricSet() { this.mBeanServer = ManagementFactory.getPlatformMBeanServer(); Map<String, Metric> metricsByNames = new HashMap<>(); // Executors/* w ww . j a va2 s .c o m*/ List<TomcatExecutorStatus> executorStatuses = new ArrayList<>(); Set<ObjectName> executorObjectNames = null; try { executorObjectNames = mBeanServer.queryNames(new ObjectName("Catalina:type=Executor,*"), null); } catch (MalformedObjectNameException e) { logger.debug("Invalid ObjectName defined for the Tomcat's Executor MxBean", e); } if (executorObjectNames != null && !executorObjectNames.isEmpty()) { for (final ObjectName executorObjectName : executorObjectNames) { TomcatExecutorMetricSet executorMetricSet = new TomcatExecutorMetricSet(executorObjectName); if (!executorMetricSet.getMetrics().isEmpty()) { metricsByNames.put(MetricNamingUtil.join("executors", executorMetricSet.getName()), executorMetricSet); } executorStatuses.add(executorMetricSet); } } this.executorStatuses = executorStatuses; // Thread Pools final List<TomcatConnectorMetricSet> connectorMetricSets = new ArrayList<>(); List<TomcatConnectorStatus> connectorStatuses = new ArrayList<>(); Set<ObjectName> threadPoolObjectNames = null; try { threadPoolObjectNames = mBeanServer.queryNames(new ObjectName("Catalina:type=ThreadPool,*"), null); } catch (MalformedObjectNameException e) { logger.debug("Invalid ObjectName defined for the Tomcat's ThreadPool MxBean", e); } if (threadPoolObjectNames != null && !threadPoolObjectNames.isEmpty()) { for (final ObjectName threadPoolObjectName : threadPoolObjectNames) { TomcatConnectorMetricSet connectorMetricSet = new TomcatConnectorMetricSet(threadPoolObjectName); if (!connectorMetricSet.getMetrics().isEmpty()) { metricsByNames.put(MetricNamingUtil.join("connectors", connectorMetricSet.getName()), connectorMetricSet); connectorMetricSets.add(connectorMetricSet); } connectorStatuses.add(connectorMetricSet); } } this.connectorStatuses = connectorStatuses; if (!connectorMetricSets.isEmpty()) { this.executorService = Executors.newSingleThreadScheduledExecutor( new ThreadFactoryBuilder().setNameFormat("TomcatMetricSet-%d").build()); this.executorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { for (TomcatConnectorMetricSet connectorMetricSet : connectorMetricSets) { try { connectorMetricSet.updateQps(); } catch (Exception e) { logger.debug("Error while updating QPS for connector {}", connectorMetricSet.getName(), e); if (InterruptedException.class.isInstance(e)) { Thread.currentThread().interrupt(); } } } } }, 1, 1, TimeUnit.SECONDS); } this.metricsByNames = metricsByNames; this.shutdown = new AtomicBoolean(false); }
From source file:info.archinnov.achilles.it.TestAsyncDSLSimpleEntity.java
@Test public void should_dsl_update_value_async() throws Exception { //Given//from www .ja v a 2 s . c o m final long id = RandomUtils.nextLong(0L, Long.MAX_VALUE); final Date date = buildDateKey(); final AtomicBoolean success = new AtomicBoolean(false); scriptExecutor.executeScriptTemplate("SimpleEntity/insert_single_row.cql", ImmutableMap.of("id", id, "table", "simple")); final CountDownLatch latch = new CountDownLatch(1); final CassandraLogAsserter logAsserter = new CassandraLogAsserter(); logAsserter.prepareLogLevel(ASYNC_LOGGER_STRING, "%msg - [%thread]%n"); //When manager.dsl().update().fromBaseTable().value_Set("new value").where().id_Eq(id).date_Eq(date) .ifValue_Eq("0 AM").withLwtResultListener(new LWTResultListener() { @Override public void onSuccess() { success.getAndSet(true); } @Override public void onError(LWTResult lwtResult) { } }).withResultSetAsyncListener(rs -> { LOGGER.info(CALLED); latch.countDown(); return rs; }).executeAsync(); //Then latch.await(); logAsserter.assertContains("Called - [achilles-default-executor"); }
From source file:com.yahoo.sql4d.sql4ddriver.sql.MysqlAccessor.java
/** * Suitable for CRUD operations where no result set is expected. * @param params/* w ww .j a v a 2s . c o m*/ * @param query * @return */ public boolean execute(Map<String, String> params, String query) { final AtomicBoolean result = new AtomicBoolean(false); Tuple2<DataSource, Connection> conn = null; try { conn = getConnection(); NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(conn._1()); jdbcTemplate.execute(query, params, new PreparedStatementCallback<Void>() { @Override public Void doInPreparedStatement(PreparedStatement ps) { try { result.set(ps.execute()); } catch (SQLException e) { result.set(false); } return null; } }); } catch (Exception ex) { Logger.getLogger(MysqlAccessor.class.getName()).log(Level.SEVERE, null, ex); result.set(false); } finally { returnConnection(conn); } return result.get(); }
From source file:com.googlecode.android_scripting.facade.ui.UiFacade.java
public UiFacade(FacadeManager manager) { super(manager); mService = manager.getService();//from www . ja va2s .c o m mTaskQueue = ((BaseApplication) mService.getApplication()).getTaskExecutor(); mContextMenuItems = new CopyOnWriteArrayList<UiMenuItem>(); mOptionsMenuItems = new CopyOnWriteArrayList<UiMenuItem>(); mEventFacade = manager.getReceiver(EventFacade.class); mMenuUpdated = new AtomicBoolean(false); }
From source file:docs.AbstractGemFireIntegrationTests.java
protected static boolean waitForCacheServerToStart(final String host, final int port, long duration) { return waitOnCondition(new Condition() { AtomicBoolean connected = new AtomicBoolean(false); public boolean evaluate() { Socket socket = null; try { if (!connected.get()) { socket = new Socket(host, port); connected.set(true); }/* w w w .j a v a 2s . co m*/ } catch (IOException ignore) { } finally { GemFireUtils.close(socket); } return connected.get(); } }, duration); }