Example usage for java.util Collections synchronizedList

List of usage examples for java.util Collections synchronizedList

Introduction

In this page you can find the example usage for java.util Collections synchronizedList.

Prototype

public static <T> List<T> synchronizedList(List<T> list) 

Source Link

Document

Returns a synchronized (thread-safe) list backed by the specified list.

Usage

From source file:com.orange.mmp.api.helpers.DefaultApiContainer.java

public void initialize() throws MMPException {
    //Initialize API observers
    this.apiObservers = Collections.synchronizedList(new ArrayList<ApiObserver>());

    //Initialized API cache
    this.apiCache = new ConcurrentHashMap<Api, Element>();

    //Get the ModuleContainer and add itself as a ModuleObserver
    ModuleContainerFactory.getInstance().getModuleContainer().registerModuleObserver(this);
}

From source file:org.apache.syncope.core.persistence.jpa.dao.JPASubjectSearchDAO.java

@Override
public <T extends Subject<?, ?, ?>> boolean matches(final T subject, final SearchCond searchCondition,
        final SubjectType type) {

    List<Object> parameters = Collections.synchronizedList(new ArrayList<>());

    // 1. get the query string from the search condition
    SearchSupport svs = new SearchSupport(type);
    StringBuilder queryString = getQuery(searchCondition, parameters, type, svs);

    boolean matches;
    if (queryString.length() == 0) {
        // Could be empty: got into a role search with a single membership condition ...
        matches = false;/*from   w  w w . ja v a  2s  .  c  o  m*/
    } else {
        // 2. take into account the passed user
        queryString.insert(0, "SELECT u.subject_id FROM (");
        queryString.append(") u WHERE subject_id=?").append(setParameter(parameters, subject.getKey()));

        // 3. prepare the search query
        Query query = entityManager.createNativeQuery(queryString.toString());

        // 4. populate the search query with parameter values
        fillWithParameters(query, parameters);

        // 5. executes query
        matches = !query.getResultList().isEmpty();
    }

    return matches;
}

From source file:org.springframework.integration.splunk.support.SplunkHECWriter.java

@Override
public void start() {

    try {//from w  ww  .  j a v a2 s . c  o m
        this.batchBuffer = Collections.synchronizedList(new LinkedList<String>());
        this.lastEventReceivedTime = System.currentTimeMillis();

        Registry<SchemeIOSessionStrategy> sslSessionStrategy = RegistryBuilder.<SchemeIOSessionStrategy>create()
                .register("http", NoopIOSessionStrategy.INSTANCE)
                .register("https", new SSLIOSessionStrategy(getSSLContext(), HOSTNAME_VERIFIER)).build();

        ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
        PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(ioReactor,
                sslSessionStrategy);
        cm.setMaxTotal(getPoolsize());

        HttpHost splunk = new HttpHost(getHost(), getPort());
        cm.setMaxPerRoute(new HttpRoute(splunk), getPoolsize());

        httpClient = HttpAsyncClients.custom().setConnectionManager(cm).build();

        uri = new URIBuilder().setScheme(isHttps() ? "https" : "http").setHost(getHost()).setPort(getPort())
                .setPath("/services/collector").build();

        httpClient.start();

        if (isBatchMode()) {
            new BatchBufferActivityCheckerThread(this).start();
        }
    } catch (Exception e) {
    }

    this.running = true;

}

From source file:org.syncope.core.persistence.dao.impl.UserSearchDAOImpl.java

private List<SyncopeUser> doSearch(final Set<Long> adminRoles, final NodeCond nodeCond, final int page,
        final int itemsPerPage) {

    List<Object> parameters = Collections.synchronizedList(new ArrayList<Object>());

    // 1. get the query string from the search condition
    final StringBuilder queryString = getQuery(nodeCond, parameters);

    // 2. take into account administrative roles
    if (queryString.charAt(0) == '(') {
        queryString.insert(0, "SELECT u.user_id FROM ");
        queryString.append(" u WHERE user_id NOT IN (");
    } else {/*from  w w w .j a v  a2s.  c o  m*/
        queryString.insert(0, "SELECT u.user_id FROM (");
        queryString.append(") u WHERE user_id NOT IN (");
    }
    queryString.append(getAdminRolesFilter(adminRoles)).append(")");

    // 3. prepare the search query
    final Query query = entityManager.createNativeQuery(queryString.toString());

    // page starts from 1, while setFirtResult() starts from 0
    query.setFirstResult(itemsPerPage * (page <= 0 ? 0 : page - 1));

    if (itemsPerPage >= 0) {
        query.setMaxResults(itemsPerPage);
    }

    // 4. populate the search query with parameter values
    fillWithParameters(query, parameters);

    LOG.debug("Native query\n{}\nwith parameters\n{}", queryString.toString(), parameters);

    // 5. Prepare the result (avoiding duplicates - set)
    final Set<Number> userIds = new HashSet<Number>();
    final List resultList = query.getResultList();

    //fix for HHH-5902 - bug hibernate
    if (resultList != null) {
        for (Object userId : resultList) {
            if (userId instanceof Object[]) {
                userIds.add((Number) ((Object[]) userId)[0]);
            } else {
                userIds.add((Number) userId);
            }
        }
    }

    final List<SyncopeUser> result = new ArrayList<SyncopeUser>(userIds.size());

    SyncopeUser user;
    for (Object userId : userIds) {
        user = userDAO.find(((Number) userId).longValue());
        if (user == null) {
            LOG.error("Could not find user with id {}, " + "even though returned by the native query", userId);
        } else {
            result.add(user);
        }
    }

    return result;
}

From source file:org.piwik.sdk.dispatcher.DispatcherTest.java

@Test
public void testBatchDispatch() throws Exception {
    List<Packet> dryRunData = Collections.synchronizedList(new ArrayList<Packet>());
    mDispatcher.setDryRunTarget(dryRunData);
    mDispatcher.setDispatchInterval(1500);

    final int threadCount = 5;
    final int queryCount = 5;
    final List<String> createdEvents = Collections.synchronizedList(new ArrayList<String>());
    launchTestThreads(mApiUrl, mDispatcher, threadCount, queryCount, createdEvents);
    Thread.sleep(1000);/*  w w w .  ja  v  a 2 s .  com*/
    assertEquals(threadCount * queryCount, createdEvents.size());
    assertEquals(0, dryRunData.size());
    Thread.sleep(1000);

    checkForMIAs(threadCount * queryCount, createdEvents, dryRunData);
}

From source file:org.apache.falcon.service.BacklogMetricEmitterService.java

@Override
public void highSLAMissed(String entityName, String clusterName, EntityType entityType, Date nominalTime)
        throws FalconException {
    if (entityType != EntityType.PROCESS) {
        return;//from  w  ww.j  a  v a2  s . c o m
    }
    Entity entity = EntityUtil.getEntity(entityType, entityName);
    entityBacklogs.putIfAbsent(entity, Collections.synchronizedList(new ArrayList<MetricInfo>()));
    List<MetricInfo> metricInfoList = entityBacklogs.get(entity);
    String nominalTimeStr = DATE_FORMAT.get().format(nominalTime);
    MetricInfo metricInfo = new MetricInfo(nominalTimeStr, clusterName);
    if (!metricInfoList.contains(metricInfo)) {
        synchronized (metricInfoList) {
            backlogMetricStore.addInstance(entityName, clusterName, nominalTime, entityType);
            metricInfoList.add(metricInfo);
        }
    }
}

From source file:com.fluidops.iwb.provider.CkanProvider.java

@Override
public void gather(List<Statement> res) throws Exception {
    // Read CKAN location and establish connection
    URL registryUrl = new URL(config.location);
    HttpURLConnection registryConnection = (HttpURLConnection) registryUrl.openConnection();
    registryConnection.setRequestMethod("GET");

    // Check if connection to CKAN could be established
    if (registryConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
        String msg = String.format("Connection to the CKAN registry could not be established. (%s, %s)",
                registryConnection.getResponseCode(), registryConnection.getResponseMessage());
        logger.info(msg);//from  ww w  .  j ava  2 s .  c  om
        throw new IllegalStateException(msg);
    }
    logger.trace("Connection to CKAN established successfully.");

    String siteContent = GenUtil.readUrl(registryConnection.getInputStream());

    JSONObject groupAsJson = null;
    JSONArray packageListJsonArray = null;
    try {
        groupAsJson = new JSONObject(new JSONTokener(siteContent));
        packageListJsonArray = groupAsJson.getJSONArray("packages");
    } catch (JSONException e) {
        String msg = String.format("Returned content %s is not valid JSON. Check if the registry URL is valid.",
                siteContent);
        logger.debug(msg);
        throw new IllegalStateException(msg);
    }
    logger.trace("Extracted JSON from CKAN successfully");

    // Create metadata about LOD catalog
    res.add(ProviderUtils.createStatement(CKAN.CKAN_CATALOG, RDF.TYPE, Vocabulary.DCAT.CATALOG));
    res.add(ProviderUtils.createStatement(CKAN.CKAN_CATALOG, RDFS.LABEL, CKAN.CKAN_CATALOG_LABEL));

    // Extract metadata for individual data sets listed in CKAN
    MultiThreadedHttpConnectionManager connectionManager = null;
    ExecutorService pool = null;
    try {
        pool = Executors.newFixedThreadPool(10);
        connectionManager = new MultiThreadedHttpConnectionManager();
        HttpClient client = new HttpClient(connectionManager);

        List<Statement> synchedList = Collections.synchronizedList(res);
        for (int i = 0; i < packageListJsonArray.length(); i++) {
            String host = "http://www.ckan.net/package/" + packageListJsonArray.get(i).toString();
            String baseUri = findBaseUri(
                    "http://www.ckan.net/api/rest/package/" + packageListJsonArray.get(i).toString());
            baseUri = (baseUri == null) ? host : baseUri;
            pool.execute(new MetadataReader(client, host, baseUri, CKAN.CKAN_CATALOG, synchedList));
        }
    } finally {
        if (pool != null) {
            pool.shutdown();
            pool.awaitTermination(4, TimeUnit.HOURS);
        }
        if (connectionManager != null)
            connectionManager.shutdown();
    }
}

From source file:org.opennms.netmgt.collectd.Collectd.java

/**
 * Constructor./*from  w  w  w.j  a va2 s.c o m*/
 */
public Collectd() {
    super(LOG4J_CATEGORY);

    m_collectableServices = Collections.synchronizedList(new LinkedList<CollectableService>());
}

From source file:com.aviary.android.feather.sdk.widget.AviaryWorkspace.java

private void reloadAdapter() {
    if (null != mAdapter) {
        mItemTypeCount = mAdapter.getViewTypeCount();
        mItemCount = mAdapter.getCount();

        mRecycleBin = Collections.synchronizedList(new ArrayList<Queue<View>>());
        for (int i = 0; i < mItemTypeCount; i++) {
            mRecycleBin.add(new LinkedList<View>());
        }//from  w w  w  .ja va 2s.  c  o m
    } else {
        mItemCount = 0;
    }

    mDataChanged = true;
    requestLayout();

}

From source file:com.teradata.benchto.driver.listeners.BenchmarkServiceExecutionListener.java

private CompletableFuture<List<Measurement>> getMeasurements(Measurable measurable) {
    List<CompletableFuture<?>> providerFutures = new ArrayList<>();
    List<Measurement> measurementsList = Collections.synchronizedList(new ArrayList<>());
    for (PostExecutionMeasurementProvider measurementProvider : measurementProviders) {
        CompletableFuture<?> future = measurementProvider.loadMeasurements(measurable)
                .thenAccept(measurementsList::addAll);
        providerFutures.add(future);//from w  ww . ja  va2s  . c  o m
    }

    return CompletableFuture.allOf(providerFutures.stream().toArray(CompletableFuture[]::new))
            .thenApply(aVoid -> ImmutableList.copyOf(measurementsList));
}