List of usage examples for java.util.concurrent CopyOnWriteArrayList CopyOnWriteArrayList
public CopyOnWriteArrayList()
From source file:com.autodomum.core.event.EventComponent.java
/** * Register callback to receive events for a specific type * /* w ww . j a va2 s . co m*/ * @param eventType * the event type that the callback should be assigned to * @param eventCallback * the callback */ public synchronized void register(final Class<?> eventType, final EventCallback eventCallback) { checkEventType(eventType); checkEventCallback(eventCallback); List<EventCallback> callbacks = this.eventCallbacks.get(eventType); if (callbacks == null) { callbacks = new CopyOnWriteArrayList<>(); this.eventCallbacks.put(eventType, callbacks); } LOG.debug("Registered callback {} for event type {}", eventCallback, eventType); callbacks.add(eventCallback); }
From source file:com.ibm.watson.app.common.services.impl.BluemixServicesBinder.java
static void parseBluemixConfig(String jsonString) { final BluemixServicesConfigurationParser parser = new BluemixServicesConfigurationParser() { @Override/* ww w .j a va 2 s. c om*/ protected void register(BluemixServiceInfo<? extends BluemixConfiguredService> service, BluemixConfiguredService serviceImpl) { // To not break backwards compatability, // override this method here and register the implementations with this class instead of the ServicesFactory List<BluemixConfiguredService> services = AVAILABLE_SERVICES.get(service.iface); if (services == null) { final List<BluemixConfiguredService> newServicesList = new CopyOnWriteArrayList<>(); services = AVAILABLE_SERVICES.putIfAbsent(service.iface, newServicesList); if (services == null) { services = newServicesList; } } services.add(serviceImpl); } }; if (logger.isDebugEnabled()) { logger.debug("Parsing service configuration: " + jsonString); } parser.parseAndRegisterServices(jsonString); }
From source file:com.app.server.EARDeployer.java
/** * This method configures the executor services from the jar file. * //from www . j a v a2s . co m * @param jarFile * @param classList * @throws FileSystemException */ public void deployExecutorServicesEar(String earFileName, FileObject earFile) throws FileSystemException { try { log.info("EARFILE NAMEs=" + earFileName); CopyOnWriteArrayList<URL> libs = new CopyOnWriteArrayList<URL>(); CopyOnWriteArrayList<FileObject> warObjects = new CopyOnWriteArrayList<FileObject>(); CopyOnWriteArrayList<FileObject> jarObjects = new CopyOnWriteArrayList<FileObject>(); CopyOnWriteArrayList<FileObject> sarObjects = new CopyOnWriteArrayList<FileObject>(); CopyOnWriteArrayList<FileObject> rarObjects = new CopyOnWriteArrayList<FileObject>(); CopyOnWriteArrayList<FileObject> ezbObjects = new CopyOnWriteArrayList<FileObject>(); WebClassLoader customClassLoaderBaseLib = new WebClassLoader(new URL[] { earFile.getURL() }, Thread.currentThread().getContextClassLoader()); final Field factoryField = URL.class.getDeclaredField("factory"); factoryField.setAccessible(true); factoryField.set(null, new RsrcURLStreamHandlerFactory(customClassLoaderBaseLib)); //URL.setURLStreamHandlerFactory(new RsrcURLStreamHandlerFactory(customClassLoaderBaseLib)); obtainUrls(earFile, earFile, libs, warObjects, jarObjects, sarObjects, rarObjects, ezbObjects, fsManager); VFSClassLoader customClassLoader = null; for (URL earLib : libs) { customClassLoaderBaseLib.addURL(earLib); } FileObject jarFileObject; ConcurrentHashMap classLoaderPath = new ConcurrentHashMap(); filesMap.put(earFileName, classLoaderPath); for (FileObject rarFileObj : rarObjects) { //log.info(classLoader); //warDeployer.deleteDir(new File(serverConfig.getDeploydirectory()+"/"+fileName.substring(0,fileName.lastIndexOf(".war")))); mbeanServer.invoke(rarObjectName, "deploy", new Object[] { rarFileObj }, new String[] { FileObject.class.getName() }); //} } for (FileObject sarFileObj : sarObjects) { //log.info(classLoader); //warDeployer.deleteDir(new File(serverConfig.getDeploydirectory()+"/"+fileName.substring(0,fileName.lastIndexOf(".war")))); mbeanServer.invoke(sarObjectName, "deploy", new Object[] { sarFileObj, fsManager, customClassLoaderBaseLib }, new String[] { FileObject.class.getName(), StandardFileSystemManager.class.getName(), ClassLoader.class.getName() }); //} } for (FileObject ezbFileObj : ezbObjects) { //log.info(classLoader); //warDeployer.deleteDir(new File(serverConfig.getDeploydirectory()+"/"+fileName.substring(0,fileName.lastIndexOf(".war")))); mbeanServer.invoke(ezbObjectName, "deploy", new Object[] { ezbFileObj, customClassLoaderBaseLib }, new String[] { FileObject.class.getName(), VFSClassLoader.class.getName() }); //} } for (FileObject warFileObj : warObjects) { //if(warFileObj.getName().getBaseName().endsWith(".war")){ //logger.info("filePath"+filePath); String filePath = serverConfig.getDeploydirectory() + "/" + warFileObj.getName().getBaseName(); log.info(filePath); String fileName = warFileObj.getName().getBaseName(); String directoryName = fileName.substring(0, fileName.indexOf('.')); log.info(customClassLoaderBaseLib); //warDeployer.deleteDir(new File(serverConfig.getDeploydirectory()+"/"+fileName.substring(0,fileName.lastIndexOf(".war")))); new File(serverConfig.getDeploydirectory() + "/" + fileName.substring(0, fileName.lastIndexOf(".war"))).mkdirs(); log.info(serverConfig.getDeploydirectory() + "/" + fileName.substring(0, fileName.lastIndexOf(".war"))); classLoaderPath.put(warFileObj.getName().getBaseName(), serverConfig.getDeploydirectory() + "/" + fileName.substring(0, fileName.lastIndexOf(".war"))); mbeanServer.invoke(warObjectName, "extractWar", new Object[] { warFileObj, customClassLoaderBaseLib, fsManager }, new String[] { FileObject.class.getName(), WebClassLoader.class.getName(), StandardFileSystemManager.class.getName() }); //} } //URL.setURLStreamHandlerFactory(new RsrcURLStreamHandlerFactory(null)); for (FileObject jarFileObj : jarObjects) { //log.info(classLoader); //warDeployer.deleteDir(new File(serverConfig.getDeploydirectory()+"/"+fileName.substring(0,fileName.lastIndexOf(".war")))); mbeanServer.invoke(ejbObjectName, "deploy", new Object[] { new URL(jarFileObj.getURL().toURI().toString()), fsManager, customClassLoaderBaseLib }, new String[] { URL.class.getName(), StandardFileSystemManager.class.getName(), ClassLoader.class.getName() }); //} } //for (int keyCount = 0; keyCount < keys.size(); keyCount++) {} /*for (FileObject fobject : fileObjects) { fobject.close(); }*/ //log.info("Channel unlocked"); earsDeployed.add(earFile.getName().getURI()); earFile.close(); fsManager.closeFileSystem(earFile.getFileSystem()); // ClassLoaderUtil.closeClassLoader(customClassLoader); } catch (Exception ex) { log.error("Error in deploying the ear ", ex); //ex.printStackTrace(); } }
From source file:org.hawkular.listener.cache.InventoryHelperTest.java
@Test public void shouldListMetricTypes() { // Data & mocks Metric<String> m1 = new Metric<>("inventory.123.mt.m1", null, 7, MetricType.STRING, null); Metric<String> m2 = new Metric<>("inventory.123.mt.m2", null, 7, MetricType.STRING, null); long currentTime = System.currentTimeMillis(); when(metricsService.findMetricsWithFilters(anyString(), anyObject(), anyString())) .thenAnswer(invocationOnMock -> Observable.just(m1, m2)); when(metricsService.findStringData(m1.getMetricId(), 0, currentTime, false, 0, Order.DESC)).thenReturn( Observable.just(buildMetricTypeDatapoint(currentTime - 500, "metricType1", "metric type 1"), buildMetricTypeDatapoint(currentTime - 1000, "oldMetricType1", "old metric type 1"))); when(metricsService.findStringData(m2.getMetricId(), 0, currentTime, false, 0, Order.DESC)).thenReturn( Observable.just(buildMetricTypeDatapoint(currentTime - 100000, "metricType2", "metric type 2"))); // Test & assertions List<org.hawkular.inventory.api.model.MetricType.Blueprint> collected = new CopyOnWriteArrayList<>(); InventoryHelper.listMetricTypes(metricsService, "tenant", "feed", currentTime).toList() .subscribe(collected::addAll, Throwables::propagate); Assert.assertEquals(2, collected.size()); Assert.assertEquals("metricType1", collected.get(0).getId()); Assert.assertEquals("metricType2", collected.get(1).getId()); }
From source file:org.pentaho.platform.plugin.action.olap.impl.OlapServiceImpl.java
/** * Constructor for testing purposes. Takes a repository as a parameter. *//*from ww w . j av a2 s . com*/ public OlapServiceImpl(IUnifiedRepository repo, final MondrianServer server) { this.repository = repo; this.filters = new CopyOnWriteArrayList<IOlapConnectionFilter>(); this.server = server; try { DefaultFileSystemManager dfsm = (DefaultFileSystemManager) VFS.getManager(); if (dfsm.hasProvider("mondrian") == false) { dfsm.addProvider("mondrian", new MondrianVfs()); } } catch (FileSystemException e) { throw new RuntimeException(e); } }
From source file:org.apache.ode.test.BPELTestAbstract.java
@Before public void setUp() throws Exception { EmbeddedGeronimoFactory factory = new EmbeddedGeronimoFactory(); if (_txManager == null) { _txManager = createTransactionManager(); org.springframework.mock.jndi.SimpleNamingContextBuilder.emptyActivatedContextBuilder() .bind("java:comp/UserTransaction", _txManager); _dataSource = createDataSource(false); {//from w w w. j a v a2 s. c o m _txManager.begin(); try { Connection c = _dataSource.getConnection(); c.prepareStatement(org.apache.commons.io.IOUtils .toString(getClass().getResourceAsStream("/scheduler-schema.sql"))).execute(); c.close(); } catch (Exception e) { } _txManager.commit(); } } // try { // _dataSource.getConnection(); // } catch (Exception e) { // // } // createDataSource(false); _failures = new CopyOnWriteArrayList<Failure>(); _server = new BpelServerImpl(); Properties props = getConfigProperties(); _server.setConfigProperties(props); mexContext = new MessageExchangeContextImpl(); _deployments = new ArrayList<Deployment>(); _invocations = new ArrayList<Invocation>(); _deployed = new ArrayList<Deployment>(); { JdbcDelegate del = new JdbcDelegate(_dataSource); scheduler = new SimpleScheduler("node", del, props); scheduler.setTransactionManager(_txManager); _cf = new BpelDAOConnectionFactoryImpl(scheduler); _server.setDaoConnectionFactory(_cf); } _server.setInMemDaoConnectionFactory(new BpelDAOConnectionFactoryImpl(scheduler)); _server.setScheduler(scheduler); _server.setBindingContext(new BindingContextImpl()); _server.setMessageExchangeContext(mexContext); scheduler.setJobProcessor(_server); scheduler.setExecutorService(executorService); store = new ProcessStoreImpl(null, _dataSource, "hib", new OdeConfigProperties(new Properties(), ""), true); store.registerListener(new ProcessStoreListener() { public void onProcessStoreEvent(ProcessStoreEvent event) { // bounce the process _server.unregister(event.pid); if (event.type != ProcessStoreEvent.Type.UNDEPLOYED) { ProcessConfImpl conf = (ProcessConfImpl) store.getProcessConfiguration(event.pid); // Test processes always run with in-mem DAOs conf.setTransient(true); _server.register(conf); } } }); _server.registerBpelEventListener(new DebugBpelEventListener()); _server.init(); _server.start(); scheduler.start(); }
From source file:com.joyent.manta.client.multipart.JobsMultipartManager.java
@Override public Stream<MantaMultipartUpload> listInProgress() throws IOException { final List<Exception> exceptions = new CopyOnWriteArrayList<>(); final Stream<MantaObject> multipartDirList; try {/* w ww. java2 s .c o m*/ multipartDirList = mantaClient.listObjects(this.resolvedMultipartUploadDirectory); // This catches an exception on the initial listObjects call } catch (final MantaClientHttpResponseException e) { if (e.getStatusCode() == HttpStatus.SC_NOT_FOUND) { return Stream.empty(); } else { throw e; } } final Stream<MantaMultipartUpload> stream = multipartDirList.filter(MantaObject::isDirectory) .map(object -> { final String idString = MantaUtils.lastItemInPath(object.getPath()); final UUID id = UUID.fromString(idString); try { MultipartMetadata mantaMetadata = downloadMultipartMetadata(id); MantaMultipartUpload upload = new JobsMultipartUpload(id, mantaMetadata.getPath()); return upload; } catch (MantaClientHttpResponseException e) { if (e.getStatusCode() == HttpStatus.SC_NOT_FOUND) { return null; } else { exceptions.add(e); return null; } } catch (IOException | RuntimeException e) { exceptions.add(e); return null; } }) /* We explicitly filter out items that stopped existing when we * went to get the multipart metadata because we encountered a * race condition. */ .filter(Objects::nonNull).onClose(multipartDirList::close); if (exceptions.isEmpty()) { danglingStreams.add(stream); return stream; } final MantaIOException aggregateException = new MantaIOException( "Problem(s) listing multipart uploads in progress"); MantaUtils.attachExceptionsToContext(aggregateException, exceptions); throw aggregateException; }
From source file:org.apache.qpid.server.store.berkeleydb.HATestClusterCreator.java
public void startClusterParallel() throws Exception { final ExecutorService executor = Executors.newFixedThreadPool(_brokerConfigurations.size()); try {/* w w w .jav a2 s. c o m*/ List<Future<Object>> brokers = new CopyOnWriteArrayList<Future<Object>>(); for (final Integer brokerPortNumber : _brokerConfigurations.keySet()) { final BrokerConfigHolder brokerConfigHolder = _brokerConfigurations.get(brokerPortNumber); Future<Object> future = executor.submit(new Callable<Object>() { public Object call() { try { _testcase.startBroker(brokerPortNumber, brokerConfigHolder.getTestConfiguration(), brokerConfigHolder.getTestVirtualhosts()); return "OK"; } catch (Exception e) { return e; } } }); brokers.add(future); } for (Future<Object> future : brokers) { Object result = future.get(30, TimeUnit.SECONDS); LOGGER.debug("Node startup result:" + result); if (result instanceof Exception) { throw (Exception) result; } else if (!"OK".equals(result)) { throw new Exception("One of the cluster nodes is not started"); } } } catch (Exception e) { stopCluster(); throw e; } finally { executor.shutdown(); } }
From source file:org.apache.phoenix.execute.HashJoinPlan.java
@Override public ResultIterator iterator(ParallelScanGrouper scanGrouper) throws SQLException { int count = subPlans.length; PhoenixConnection connection = getContext().getConnection(); ConnectionQueryServices services = connection.getQueryServices(); ExecutorService executor = services.getExecutor(); List<Future<Object>> futures = Lists.<Future<Object>>newArrayListWithExpectedSize(count); dependencies = Lists.newArrayList(); if (joinInfo != null) { hashClient = hashClient != null ? hashClient : new HashCacheClient(delegate.getContext().getConnection()); firstJobEndTime = new AtomicLong(0); keyRangeExpressions = new CopyOnWriteArrayList<Expression>(); }//from ww w. j a v a 2 s . c om for (int i = 0; i < count; i++) { final int index = i; futures.add(executor.submit(new JobCallable<Object>() { @Override public Object call() throws Exception { return subPlans[index].execute(HashJoinPlan.this); } @Override public Object getJobId() { return HashJoinPlan.this; } @Override public TaskExecutionMetricsHolder getTaskExecutionMetric() { return NO_OP_INSTANCE; } })); } SQLException firstException = null; for (int i = 0; i < count; i++) { try { Object result = futures.get(i).get(); subPlans[i].postProcess(result, this); } catch (InterruptedException e) { if (firstException == null) { firstException = new SQLException("Sub plan [" + i + "] execution interrupted.", e); } } catch (ExecutionException e) { if (firstException == null) { firstException = new SQLException("Encountered exception in sub plan [" + i + "] execution.", e.getCause()); } } } if (firstException != null) { SQLCloseables.closeAllQuietly(dependencies); throw firstException; } Expression postFilter = null; boolean hasKeyRangeExpressions = keyRangeExpressions != null && !keyRangeExpressions.isEmpty(); if (recompileWhereClause || hasKeyRangeExpressions) { StatementContext context = delegate.getContext(); PTable table = context.getCurrentTable().getTable(); ParseNode viewWhere = table.getViewStatement() == null ? null : new SQLParser(table.getViewStatement()).parseQuery().getWhere(); context.setResolver(FromCompiler.getResolverForQuery((SelectStatement) (delegate.getStatement()), delegate.getContext().getConnection())); if (recompileWhereClause) { postFilter = WhereCompiler.compile(delegate.getContext(), delegate.getStatement(), viewWhere, null); } if (hasKeyRangeExpressions) { WhereCompiler.compile(delegate.getContext(), delegate.getStatement(), viewWhere, keyRangeExpressions, true, null); } } if (joinInfo != null) { Scan scan = delegate.getContext().getScan(); HashJoinInfo.serializeHashJoinIntoScan(scan, joinInfo); } ResultIterator iterator = joinInfo == null ? delegate.iterator(scanGrouper) : ((BaseQueryPlan) delegate).iterator(dependencies, scanGrouper); if (statement.getInnerSelectStatement() != null && postFilter != null) { iterator = new FilterResultIterator(iterator, postFilter); } return iterator; }