List of usage examples for java.util.concurrent.atomic AtomicReference AtomicReference
public AtomicReference()
From source file:com.jeremydyer.nifi.processors.barcode.BarcodeScannerProcessor.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException { final FlowFile flowFile = session.get(); if (flowFile == null) { return;/*from w ww . j av a 2s . c om*/ } final AtomicBoolean errors = new AtomicBoolean(false); switch (context.getProperty(DESTINATION).getValue()) { case DESTINATION_ATTRIBUTE: final AtomicReference<String> BC = new AtomicReference<>(); session.read(flowFile, new InputStreamCallback() { @Override public void process(InputStream inputStream) throws IOException { Map hintMap = new HashMap(); hintMap.put(DecodeHintType.TRY_HARDER, Boolean.TRUE); try { BufferedImage barCodeBufferedImage = ImageIO.read(inputStream); LuminanceSource source = new BufferedImageLuminanceSource(barCodeBufferedImage); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); Reader reader = new MultiFormatReader(); Result result = reader.decode(bitmap, hintMap); BC.set(result.getText()); } catch (Exception ex) { ex.printStackTrace(); //session.transfer(flowFile, REL_FAILURE); errors.set(true); } } }); if (StringUtils.isNotEmpty(BC.get())) { FlowFile atFlowFile = session.putAttribute(flowFile, BARCODE_ATTRIBUTE_NAME, BC.get()); if (!errors.get()) { session.transfer(atFlowFile, REL_SUCCESS); } else { session.transfer(atFlowFile, REL_FAILURE); } } else { if (!errors.get()) { session.transfer(flowFile, REL_SUCCESS); } else { session.transfer(flowFile, REL_FAILURE); } } break; case DESTINATION_CONTENT: FlowFile conFlowFile = session.write(flowFile, new StreamCallback() { @Override public void process(InputStream inputStream, OutputStream outputStream) throws IOException { Map hintMap = new HashMap(); hintMap.put(DecodeHintType.TRY_HARDER, Boolean.TRUE); try { BufferedImage barCodeBufferedImage = ImageIO.read(inputStream); LuminanceSource source = new BufferedImageLuminanceSource(barCodeBufferedImage); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); Reader reader = new MultiFormatReader(); Result result = reader.decode(bitmap, hintMap); getLogger().info("Barcode Format: " + result.getBarcodeFormat().toString()); getLogger().info("Barcode Text is: ' " + result.getText() + "'"); outputStream.write(result.getText().getBytes()); } catch (Exception ex) { ex.printStackTrace(); //session.transfer(flowFile, REL_FAILURE); errors.set(true); } } }); if (!errors.get()) { session.transfer(conFlowFile, REL_SUCCESS); } else { session.transfer(conFlowFile, REL_FAILURE); } break; } }
From source file:com.mfizz.observer.core.ServiceObserver.java
public ServiceObserver(ServiceObserverConfiguration serviceConfig, ExecutorService executor, Class<D> dataClass, Class<A> aggregateClass, Class<S> summaryClass, ContentParser<D> contentParser, ObserverNamingStrategy ons) {/* w w w . j a v a 2 s .com*/ this.serviceConfig = serviceConfig; this.executor = executor; this.observers = new ConcurrentHashMap<String, Observer<D>>(); this.dataClass = dataClass; this.aggregateClass = aggregateClass; this.summaryClass = summaryClass; this.contentParser = contentParser; if (ons == null) { this.ons = ObserverNamingStrategy.DEFAULT; } else { this.ons = ons; } this.snapshotAllTimer = Metrics.newTimer( new MetricName("com.mfizz.observer.ServiceObservers", serviceConfig.getName(), "snapshot-all-time"), TimeUnit.MILLISECONDS, TimeUnit.MILLISECONDS); this.snapshotAllAttemptedCounter = new AtomicLong(); this.snapshotAllCompletedCounter = new AtomicLong(); this.lastSnapshotAllResult = new AtomicReference<SnapshotAllResult>(); //this.lastSnapshotAllTimestamp = new AtomicLong(0); //this.lastSnapshotsCompletedCounter = new AtomicInteger(); //this.lastSnapshotsFailedCounter = new AtomicInteger(); this.groups = new TreeSet<String>(); this.summary = new ConcurrentHashMap<String, SummaryGroup<S>>(); this.snapshots = new ConcurrentHashMap<String, TimeSeries<ObserveAggregateSnapshot<A>>>(); // always make sure "current" is added to set of vars to track // "current" always tracked for all this.serviceConfig.getPeriods().add(SummaryPeriod.parse("current")); // // create high performance http client that can be reused by all observers // SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry); // increase max total connection to 200 cm.setMaxTotal(200); // increase default max connection per route to 20 cm.setDefaultMaxPerRoute(20); this.httpclient = new DefaultHttpClient(cm); this.httpclient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() { @Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { // always return false -- we never want a request retried return false; } }); this.httpclient.getParams() .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer((int) serviceConfig.getSocketTimeout())) .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer((int) serviceConfig.getConnectionTimeout())) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false); }
From source file:info.archinnov.achilles.it.TestEntityWithStaticColumn.java
@Test public void should_insert_static_if_not_exist() throws Exception { //Given/* ww w . j a v a 2s .c o m*/ final AtomicReference<LWTResult> lwtResultRef = new AtomicReference<>(); final long id = RandomUtils.nextLong(0L, Long.MAX_VALUE); final EntityWithStaticColumn entity = new EntityWithStaticColumn(id, null, "static_val", null); manager.crud().insertStatic(entity).ifNotExists().execute(); //When manager.crud().insertStatic(entity).ifNotExists().withLwtResultListener(lwtResultRef::set).execute(); //Then assertThat(lwtResultRef.get()).isNotNull(); assertThat(lwtResultRef.get().currentValues().<String>getTyped("static_col")).isEqualTo("static_val"); }
From source file:com.netflix.config.DynamicContextualPropertyTest.java
@Test public void testCallback() { String json = "[{\"value\":5,\"if\":{\"d1\":[\"v1\",\"v2\"]}, \"comment\": \"some comment\"},{\"value\":10,\"if\":{\"d1\":[\"v3\"],\"d2\":[\"x1\"]}, \"runtimeEval\": true},{\"value\":2}]"; ConfigurationManager.getConfigInstance().setProperty("d1", "v2"); final AtomicReference<Integer> ref = new AtomicReference<Integer>(); DynamicContextualProperty<Integer> prop = new DynamicContextualProperty<Integer>("propWithCallback", 0) { @Override//from w ww .j a v a 2s . co m protected void propertyChanged(Integer newVal) { ref.set(newVal); } }; assertEquals(0, prop.getValue().intValue()); ConfigurationManager.getConfigInstance().setProperty("propWithCallback", json); assertEquals(5, ref.get().intValue()); assertEquals(5, prop.getValue().intValue()); assertEquals("some comment", prop.values.get(0).getComment()); assertTrue(prop.values.get(1).isRuntimeEval()); assertFalse(prop.values.get(0).isRuntimeEval()); // set the property as a single value integer ConfigurationManager.getConfigInstance().setProperty("propWithCallback", "7"); assertEquals(7, ref.get().intValue()); assertEquals(7, prop.getValue().intValue()); }
From source file:ca.psiphon.PsiphonTunnel.java
private PsiphonTunnel(HostService hostService) { mHostService = hostService;/*from ww w. ja va2 s . c o m*/ mVpnMode = new AtomicBoolean(false); mTunFd = new AtomicReference<ParcelFileDescriptor>(); mLocalSocksProxyPort = new AtomicInteger(0); mRoutingThroughTunnel = new AtomicBoolean(false); mIsWaitingForNetworkConnectivity = new AtomicBoolean(false); }
From source file:de.sainth.recipe.backend.db.repositories.RecipeRepository.java
public Recipe save(Recipe recipe) { AtomicReference<Recipe> bu = new AtomicReference<>(); create.transaction(configuration -> { Long id = null;/*w ww . ja v a 2 s.co m*/ if (recipe.getId() != null) { id = using(configuration).select(RECIPES.ID).from(RECIPES).where(RECIPES.ID.eq(recipe.getId())) .forUpdate().fetchOneInto(Long.class); } RecipesRecord recipeRecord; List<DirectionsRecord> directionsRecords = new ArrayList<>(); List<IngredientsRecord> ingredientsRecords = new ArrayList<>(); if (recipe.getId() == null || id == null) { recipeRecord = using(configuration) .insertInto(RECIPES, RECIPES.NAME, RECIPES.COMMENT, RECIPES.DIFFICULTY, RECIPES.PORTIONS, RECIPES.AUTHOR, RECIPES.PUBLIC_VISIBLE) .values(recipe.getName(), recipe.getComment(), recipe.getDifficulty(), recipe.getPortions(), recipe.getAuthor().getId(), recipe.isPublicVisible()) .returning().fetchOne(); for (Ingredient ingredient : recipe.getIngredients()) { ingredientsRecords.add(using(configuration) .insertInto(INGREDIENTS, INGREDIENTS.AMOUNT, INGREDIENTS.CATEGORY, INGREDIENTS.FOOD, INGREDIENTS.RECIPE) .values(ingredient.getAmount(), ingredient.getCategory(), ingredient.getFood().getId(), recipeRecord.getId()) .returning().fetchOne()); } for (Direction direction : recipe.getDirections()) { directionsRecords.add(using(configuration) .insertInto(DIRECTIONS, DIRECTIONS.POSITION, DIRECTIONS.DESCRIPTION, DIRECTIONS.DURATION, DIRECTIONS.RECIPE) .values(direction.getPosition(), direction.getDescription(), direction.getDuration(), recipeRecord.getId()) .returning().fetchOne()); } } else { recipeRecord = using(configuration).update(RECIPES).set(RECIPES.NAME, recipe.getName()) .set(RECIPES.COMMENT, recipe.getComment()).set(RECIPES.DIFFICULTY, recipe.getDifficulty()) .set(RECIPES.PORTIONS, recipe.getPortions()).set(RECIPES.AUTHOR, recipe.getAuthor().getId()) .set(RECIPES.PUBLIC_VISIBLE, recipe.isPublicVisible()).where(RECIPES.ID.eq(id)).returning() .fetchOne(); using(configuration).delete(INGREDIENTS).where(INGREDIENTS.RECIPE.eq(id)); for (Ingredient ingredient : recipe.getIngredients()) { ingredientsRecords.add(using(configuration) .insertInto(INGREDIENTS, INGREDIENTS.AMOUNT, INGREDIENTS.CATEGORY, INGREDIENTS.FOOD, INGREDIENTS.RECIPE) .values(ingredient.getAmount(), ingredient.getCategory(), ingredient.getFood().getId(), recipeRecord.getId()) .returning().fetchOne()); } using(configuration).delete(DIRECTIONS).where(DIRECTIONS.RECIPE.eq(id)); for (Direction direction : recipe.getDirections()) { directionsRecords.add(using(configuration) .insertInto(DIRECTIONS, DIRECTIONS.POSITION, DIRECTIONS.DESCRIPTION, DIRECTIONS.DURATION, DIRECTIONS.RECIPE) .values(direction.getPosition(), direction.getDescription(), direction.getDuration(), recipeRecord.getId()) .returning().fetchOne()); } } String username = using(configuration).select(USERS.NAME).from(USERS) .where(USERS.ID.eq(recipeRecord.getAuthor())).fetchOneInto(String.class); List<Ingredient> ingredients = ingredientsRecords.stream().map( i -> new Ingredient(i.getAmount(), i.getCategory(), selectFood(configuration, i.getFood()))) .collect(Collectors.toList()); List<Direction> directions = directionsRecords.stream() .map(d -> new Direction(d.getId(), d.getPosition(), d.getDescription(), d.getDuration())) .collect(Collectors.toList()); bu.set(new Recipe(recipeRecord.getId(), recipeRecord.getName(), recipeRecord.getComment(), recipeRecord.getDifficulty(), recipeRecord.getPortions(), recipeRecord.getPublicVisible(), new User(recipeRecord.getAuthor(), username), ingredients, directions)); }); return bu.get(); }
From source file:ch.algotrader.cache.CacheTest.java
@BeforeClass public static void beforeClass() { context = new AnnotationConfigApplicationContext(); context.getEnvironment().setActiveProfiles("embeddedDataSource", "simulation"); // register in-memory db EmbeddedDatabaseFactory dbFactory = new EmbeddedDatabaseFactory(); dbFactory.setDatabaseType(EmbeddedDatabaseType.H2); dbFactory.setDatabaseName("testdb;MODE=MYSQL;DATABASE_TO_UPPER=FALSE"); database = dbFactory.getDatabase();// w w w.j ava2 s . c om context.getDefaultListableBeanFactory().registerSingleton("dataSource", database); EngineManager engineManager = Mockito.mock(EngineManager.class); Mockito.when(engineManager.getCurrentEPTime()).thenReturn(new Date()); Mockito.when(engineManager.getCurrentEPTime()).thenReturn(new Date()); context.getDefaultListableBeanFactory().registerSingleton("engineManager", engineManager); AtomicReference<TransactionService> transactionService = new AtomicReference<>(); Engine engine = new NoopEngine(StrategyImpl.SERVER); context.getDefaultListableBeanFactory().registerSingleton("serverEngine", engine); ExternalMarketDataService externalMarketDataService = Mockito.mock(ExternalMarketDataService.class); context.getDefaultListableBeanFactory().registerSingleton("externalMarketDataService", externalMarketDataService); context.getDefaultListableBeanFactory().registerSingleton("historicalDataService", new NoopHistoricalDataServiceImpl()); Mockito.when(externalMarketDataService.getFeedType()).thenReturn(FeedType.IB.name()); // register Wirings context.register(CommonConfigWiring.class, CoreConfigWiring.class, EventDispatchWiring.class, EventDispatchPostInitWiring.class, HibernateWiring.class, CacheWiring.class, DaoWiring.class, ServiceWiring.class, SimulationWiring.class); context.refresh(); transactionService.set(context.getBean(TransactionService.class)); cache = context.getBean(CacheManager.class); txTemplate = context.getBean(TransactionTemplate.class); // create the database ResourceDatabasePopulator dbPopulator = new ResourceDatabasePopulator(); dbPopulator.addScript(new ClassPathResource("/db/h2/h2.sql")); DatabasePopulatorUtils.execute(dbPopulator, database); // populate the database SessionFactory sessionFactory = context.getBean(SessionFactory.class); Session session = sessionFactory.openSession(); Exchange exchange1 = new ExchangeImpl(); exchange1.setName("IDEALPRO"); exchange1.setCode("IDEALPRO"); exchange1.setTimeZone("US/Eastern"); session.save(exchange1); SecurityFamily family1 = new SecurityFamilyImpl(); family1.setName("FX"); family1.setTickSizePattern("0<0.1"); family1.setCurrency(Currency.USD); family1.setExchange(exchange1); family1.setTradeable(true); family1.setContractSize(1.0); securityFamilyId1 = (Long) session.save(family1); SecurityFamily family2 = new SecurityFamilyImpl(); family2.setName("NON_TRADEABLE"); family2.setTickSizePattern("0<0.1"); family2.setCurrency(Currency.USD); family2.setTradeable(false); family2.setContractSize(1.0); securityFamilyId2 = (Long) session.save(family2); Forex security1 = new ForexImpl(); security1.setSymbol("EUR.USD"); security1.setBaseCurrency(Currency.EUR); security1.setSecurityFamily(family1); securityId1 = (Long) session.save(security1); Forex security2 = new ForexImpl(); security2.setSymbol("GBP.USD"); security2.setBaseCurrency(Currency.GBP); security2.setSecurityFamily(family1); security2.setUnderlying(security1); securityId2 = (Long) session.save(security2); Strategy strategy1 = new StrategyImpl(); strategy1.setName(STRATEGY_NAME); strategyId1 = (Long) session.save(strategy1); Position position1 = new PositionImpl(); position1.setQuantity(222); position1.setStrategy(strategy1); position1.setSecurity(security2); position1.setCost(new BigDecimal(0.0)); position1.setRealizedPL(new BigDecimal(0.0)); session.save(position1); Property property1 = new PropertyImpl(); property1.setName(PROPERTY_NAME); property1.setDoubleValue(10.0); property1.setPropertyHolder(strategy1); session.save(property1); strategy1.getProps().put(PROPERTY_NAME, property1); Account account1 = new AccountImpl(); account1.setName("TEST"); account1.setBroker("TEST"); account1.setOrderServiceType(OrderServiceType.SIMULATION.toString()); accountId1 = (Long) session.save(account1); session.flush(); session.close(); }
From source file:io.wcm.caravan.io.http.impl.CaravanHttpClientThreadingTest.java
private Thread subscribeWaitAndGetEmissionThread(Observable<CaravanHttpResponse> rxResponse) throws InterruptedException { AtomicReference<Thread> observerThread = new AtomicReference<>(); AtomicReference<Throwable> error = new AtomicReference<>(); rxResponse.subscribe(response -> observerThread.set(Thread.currentThread()), ex -> error.set(ex)); while (observerThread.get() == null && error.get() == null) { Thread.sleep(1);/*from w ww . ja v a 2 s. co m*/ } if (error.get() != null) { throw new RuntimeException("The response observable emitted an exception.", error.get()); } return observerThread.get(); }
From source file:com.microsoft.tfs.client.common.ui.wizard.common.WizardServerSelectionPage.java
@Override protected boolean onPageFinished() { if (serverTypeSelectControl.isVstsSelected()) { final Action<DeviceFlowResponse> deviceFlowCallback = getDeviceFlowCallback(); final AtomicReference<JwtCredentials> vstsCredentials = new AtomicReference<JwtCredentials>(); final List<Account> accounts = getUserAccounts(vstsCredentials, deviceFlowCallback); final List<TFSConnection> configurationServers = getConfigurationServers(accounts, vstsCredentials, deviceFlowCallback);/*from ww w .j a v a 2s.c om*/ setPageData(configurationServers); return configurationServers.size() > 0; } else { final URI serverURI = serverTypeSelectControl.getServer(); if (serverURI == null) { return false; } final TFSConnection connection = openAccount(serverURI, null); setPageData(connection); return connection != null; } }
From source file:org.apache.servicemix.http.ProviderEndpointTest.java
public void testSoap() throws Exception { final AtomicReference<String> soapAction = new AtomicReference<String>(); EchoComponent echo = new EchoComponent(); echo.setService(new QName("http://servicemix.apache.org/samples/wsdl-first", "EchoService")); echo.setEndpoint("service"); container.activateComponent(echo, "echo"); HttpComponent http = new HttpComponent(); HttpConsumerEndpoint ep0 = new HttpConsumerEndpoint(); ep0.setService(new QName("http://servicemix.apache.org/samples/wsdl-first", "PersonService")); ep0.setEndpoint("consumer"); ep0.setTargetService(new QName("http://servicemix.apache.org/samples/wsdl-first", "EchoService")); ep0.setTargetEndpoint("service"); ep0.setLocationURI("http://localhost:8192/PersonService/"); ep0.setMarshaler(new DefaultHttpConsumerMarshaler() { public MessageExchange createExchange(HttpServletRequest request, ComponentContext context) throws Exception { soapAction.set(request.getHeader("SOAPAction")); return super.createExchange(request, context); //To change body of overridden methods use File | Settings | File Templates. }/*from w w w. j a va 2 s. c o m*/ }); HttpSoapProviderEndpoint ep1 = new HttpSoapProviderEndpoint(); ep1.setService(new QName("http://servicemix.apache.org/samples/wsdl-first", "PersonService")); ep1.setEndpoint("soap"); ep1.setWsdl(new ClassPathResource("person.wsdl")); ep1.setValidateWsdl(false); // TODO: Soap 1.2 not handled yet ep1.setUseJbiWrapper(true); http.setEndpoints(new HttpEndpointType[] { ep0, ep1 }); container.activateComponent(http, "http"); container.start(); ServiceMixClient client = new DefaultServiceMixClient(container); InOut me = client.createInOutExchange(); me.setService(new QName("http://servicemix.apache.org/samples/wsdl-first", "PersonService")); me.setOperation(new QName("http://servicemix.apache.org/samples/wsdl-first", "GetPerson")); me.getInMessage().setContent( new StringSource("<jbi:message xmlns:jbi=\"http://java.sun.com/xml/ns/jbi/wsdl-11-wrapper\"" + " xmlns:msg=\"http://servicemix.apache.org/samples/wsdl-first/types\" " + " name=\"Hello\" " + " type=\"msg:HelloRequest\" " + " version=\"1.0\">" + " <jbi:part>" + " <msg:GetPerson><msg:personId>id</msg:personId></msg:GetPerson>" + " </jbi:part>" + "</jbi:message>")); client.sendSync(me); client.done(me); assertEquals("\"urn:myaction\"", soapAction.get()); }