Example usage for java.util.concurrent CopyOnWriteArrayList CopyOnWriteArrayList

List of usage examples for java.util.concurrent CopyOnWriteArrayList CopyOnWriteArrayList

Introduction

In this page you can find the example usage for java.util.concurrent CopyOnWriteArrayList CopyOnWriteArrayList.

Prototype

public CopyOnWriteArrayList() 

Source Link

Document

Creates an empty list.

Usage

From source file:org.elasticsearch.client.RestClientIntegTests.java

public void testAsyncRequests() throws Exception {
    int numRequests = randomIntBetween(5, 20);
    final CountDownLatch latch = new CountDownLatch(numRequests);
    final List<TestResponse> responses = new CopyOnWriteArrayList<>();
    for (int i = 0; i < numRequests; i++) {
        final String method = RestClientTestUtil.randomHttpMethod(getRandom());
        final int statusCode = randomStatusCode(getRandom());
        restClient.performRequestAsync(method, "/" + statusCode, new ResponseListener() {
            @Override/*from  w w  w.  j a  va 2  s.  co m*/
            public void onSuccess(Response response) {
                responses.add(new TestResponse(method, statusCode, response));
                latch.countDown();
            }

            @Override
            public void onFailure(Exception exception) {
                responses.add(new TestResponse(method, statusCode, exception));
                latch.countDown();
            }
        });
    }
    assertTrue(latch.await(5, TimeUnit.SECONDS));

    assertEquals(numRequests, responses.size());
    for (TestResponse response : responses) {
        assertEquals(response.method, response.getResponse().getRequestLine().getMethod());
        assertEquals(response.statusCode, response.getResponse().getStatusLine().getStatusCode());

    }
}

From source file:org.deeplearning4j.text.invertedindex.LuceneInvertedIndex.java

@Override
public Pair<List<T>, Collection<String>> documentWithLabels(int index) {
    List<T> ret = new CopyOnWriteArrayList<>();
    Collection<String> labels = new ArrayList<>();

    try {//from   w  w  w .  java  2s . c  om
        DirectoryReader reader = readerManager.acquire();
        Document doc = reader.document(index);
        readerManager.release(reader);
        String[] values = doc.getValues(WORD_FIELD);
        String[] labels2 = doc.getValues(LABEL);

        for (String s : values) {
            T tok = vocabCache.wordFor(s);
            if (tok != null)
                ret.add(tok);
        }

        Collections.addAll(labels, labels2);

    }

    catch (Exception e) {
        e.printStackTrace();
    }
    return new Pair<>(ret, labels);

}

From source file:com.app.server.SARDeployer.java

public CopyOnWriteArrayList<String> unpack(final FileObject unpackFileObject, final File outputDir,
        StandardFileSystemManager fileSystemManager) throws IOException {
    outputDir.mkdirs();/*from w  ww .  ja va 2s.  c  o  m*/
    URLClassLoader webClassLoader;
    CopyOnWriteArrayList<String> classPath = new CopyOnWriteArrayList<String>();
    final FileObject packFileObject = fileSystemManager
            .resolveFile("jar:" + unpackFileObject.toString() + "!/");
    try {
        FileObject outputDirFileObject = fileSystemManager.toFileObject(outputDir);
        outputDirFileObject.copyFrom(packFileObject, new AllFileSelector());
        FileObject[] libs = outputDirFileObject.findFiles(new FileSelector() {

            public boolean includeFile(FileSelectInfo arg0) throws Exception {
                return arg0.getFile().getName().getBaseName().toLowerCase().endsWith(".jar");
            }

            public boolean traverseDescendents(FileSelectInfo arg0) throws Exception {
                // TODO Auto-generated method stub
                return true;
            }

        });
        /*String replaceString="file:///"+outputDir.getAbsolutePath().replace("\\","/");
        replaceString=replaceString.endsWith("/")?replaceString:replaceString+"/";*/
        // System.out.println(replaceString);
        for (FileObject lib : libs) {
            // System.out.println(outputDir.getAbsolutePath());
            // System.out.println(jsp.getName().getFriendlyURI());
            classPath.add(lib.getName().getFriendlyURI());
            // System.out.println(relJspName);
        }
    } finally {
        packFileObject.close();
    }
    return classPath;
}

From source file:org.nuxeo.ecm.core.io.registry.context.RenderingContextImpl.java

@Override
public void addParameterListValues(String name, List<Object> values) {
    if (StringUtils.isEmpty(name)) {
        return;//  w ww .j  a v  a2 s  .c  o m
    }
    String realName = name.toLowerCase().trim();
    if (values == null) {
        return;
    }
    List<Object> currentValues = parameters.get(realName);
    if (currentValues == null) {
        currentValues = new CopyOnWriteArrayList<Object>();
        parameters.put(realName, currentValues);
    }
    for (Object value : values) {
        currentValues.add(value);
    }
}

From source file:net.padlocksoftware.padlock.validator.Validator.java

/**
 * Create a new empty Validator instance with the License and PublicKey set. These are not changeable once
 * created, so every License/KeyPair combination will need its own Validator instance. When created, the
 * Validator contains only the build in Padlock plugins, which are fixed. New custom plugins can be added
 * by calling {@link #addPlugin(net.padlocksoftware.padlock.validator.ValidatorPlugin) addPlugin()}.
 * //from w  w w  . java  2s. com
 * @param license The license instance to validate.
 * @param publicKey The PublicKey corresponding to the PrivateKey used to sign the license.
 */
public Validator(License license, String publicKey) {
    logger = Logger.getLogger(getClass().getName());
    this.license = license;

    // Try DSA first
    this.publicKey = convertPublicKey(publicKey, false);

    if (this.publicKey == null) {
        this.publicKey = convertPublicKey(publicKey, true);
        isRSA = true;
    }

    logger.fine("Using RSA Key: " + isRSA);

    sigValidator = isRSA ? new RsaValidator() : new DsaValidator();

    // If the public Key is still null, throw a runtime exception
    if (this.publicKey == null) {
        throw new RuntimeException("Cannot create PublicKey object");
    }

    plugins = new CopyOnWriteArrayList<ValidatorPlugin>();

    // Default plugins
    expiredPlugin = new ExpiredPlugin();

    plugins.add(expiredPlugin);
    plugins.add(new PriorPlugin());
    plugins.add(new BlacklistPlugin());
    plugins.add(new HardwarePlugin());

    blacklist = new CopyOnWriteArraySet<String>();

    ignoreFloatTime = false;
    checkClockTurnback = true;
}

From source file:org.lightjason.agentspeak.common.CPath.java

/**
 * list factory//ww  w .j  a  v  a 2s .c  o m
 *
 * @return list
 */
private static List<String> listfactory() {
    return new CopyOnWriteArrayList<>();
}

From source file:org.kie.server.services.impl.KieServerImpl.java

public ServiceResponse<KieContainerResource> createContainer(String containerId,
        KieContainerResource container) {

    Optional<ServiceResponse<KieContainerResource>> optional = Optional
            .ofNullable(validateContainerReleaseAndMode("Error creating container.", container));

    if (optional.isPresent()) {
        ServiceResponse response = optional.get();

        logger.error(response.getMsg());

        return optional.get();
    }//from  w w w  .  j  a va2  s  .c o m

    List<Message> messages = new CopyOnWriteArrayList<Message>();

    container.setContainerId(containerId);
    ReleaseId releaseId = container.getReleaseId();
    try {
        KieContainerInstanceImpl ci = new KieContainerInstanceImpl(containerId, KieContainerStatus.CREATING,
                null, releaseId, this);
        ci.getResource().setContainerAlias(container.getContainerAlias());
        KieContainerInstanceImpl previous = null;
        // have to synchronize on the ci or a concurrent call to dispose may create inconsistencies
        synchronized (ci) {

            previous = context.registerContainer(containerId, ci);
            if (previous == null) {
                try {
                    eventSupport.fireBeforeContainerStarted(this, ci);

                    InternalKieContainer kieContainer = (InternalKieContainer) ks.newKieContainer(containerId,
                            releaseId);
                    if (kieContainer != null) {
                        ci.setKieContainer(kieContainer);
                        ci.getResource().setConfigItems(container.getConfigItems());
                        ci.getResource().setMessages(messages);
                        logger.debug("Container {} (for release id {}) general initialization: DONE",
                                containerId, releaseId);

                        Map<String, Object> parameters = getContainerParameters(releaseId, messages);
                        // process server extensions
                        List<KieServerExtension> extensions = getServerExtensions();
                        for (KieServerExtension extension : extensions) {
                            extension.createContainer(containerId, ci, parameters);
                            logger.debug("Container {} (for release id {}) {} initialization: DONE",
                                    containerId, releaseId, extension);
                        }

                        if (container.getScanner() != null) {
                            ServiceResponse<KieScannerResource> scannerResponse = configureScanner(containerId,
                                    ci, container.getScanner());
                            if (ResponseType.FAILURE.equals(scannerResponse.getType())) {
                                String errorMessage = "Failed to create scanner for container " + containerId
                                        + " with module " + releaseId + ".";
                                messages.add(new Message(Severity.ERROR, errorMessage));
                                ci.getResource().setStatus(KieContainerStatus.FAILED);
                                return new ServiceResponse<KieContainerResource>(
                                        ServiceResponse.ResponseType.FAILURE, errorMessage);
                            }
                        }

                        ci.getResource().setStatus(KieContainerStatus.STARTED);
                        logger.info("Container {} (for release id {}) successfully started", containerId,
                                releaseId);

                        // store the current state of the server
                        storeServerState(currentState -> {
                            container.setStatus(KieContainerStatus.STARTED);
                            currentState.getContainers().add(container);
                        });

                        // add successful message only when there are no errors
                        if (!messages.stream().filter(m -> m.getSeverity().equals(Severity.ERROR)).findAny()
                                .isPresent()) {
                            messages.add(new Message(Severity.INFO, "Container " + containerId
                                    + " successfully created with module " + releaseId + "."));
                            eventSupport.fireAfterContainerStarted(this, ci);

                            return new ServiceResponse<KieContainerResource>(
                                    ServiceResponse.ResponseType.SUCCESS, "Container " + containerId
                                            + " successfully deployed with module " + releaseId + ".",
                                    ci.getResource());
                        } else {
                            ci.getResource().setStatus(KieContainerStatus.FAILED);
                            ci.getResource().setReleaseId(releaseId);
                            return new ServiceResponse<KieContainerResource>(
                                    ServiceResponse.ResponseType.FAILURE, "Failed to create container "
                                            + containerId + " with module " + releaseId + ".");
                        }
                    } else {
                        messages.add(new Message(Severity.ERROR,
                                "KieContainer could not be found for release id " + releaseId));
                        ci.getResource().setStatus(KieContainerStatus.FAILED);
                        ci.getResource().setReleaseId(releaseId);
                        return new ServiceResponse<KieContainerResource>(ServiceResponse.ResponseType.FAILURE,
                                "Failed to create container " + containerId + " with module " + releaseId
                                        + ".");
                    }
                } catch (Exception e) {
                    messages.add(new Message(Severity.ERROR, "Error creating container '" + containerId
                            + "' for module '" + releaseId + "' due to " + e.getMessage()));
                    logger.error(
                            "Error creating container '" + containerId + "' for module '" + releaseId + "'", e);
                    ci.getResource().setStatus(KieContainerStatus.FAILED);
                    ci.getResource().setReleaseId(releaseId);
                    return new ServiceResponse<KieContainerResource>(ServiceResponse.ResponseType.FAILURE,
                            "Failed to create container " + containerId + " with module " + releaseId + ": "
                                    + e.getClass().getName() + ": " + e.getMessage());
                }
            } else {
                messages.add(new Message(Severity.ERROR, "Container " + containerId + " already exists."));
                return new ServiceResponse<KieContainerResource>(ServiceResponse.ResponseType.FAILURE,
                        "Container " + containerId + " already exists.", previous.getResource());
            }
        }
    } catch (Exception e) {
        messages.add(new Message(Severity.ERROR, "Error creating container '" + containerId + "' for module '"
                + releaseId + "' due to " + e.getMessage()));
        logger.error("Error creating container '" + containerId + "' for module '" + releaseId + "'", e);
        return new ServiceResponse<KieContainerResource>(ServiceResponse.ResponseType.FAILURE,
                "Error creating container " + containerId + " with module " + releaseId + ": "
                        + e.getClass().getName() + ": " + e.getMessage());
    } finally {
        this.containerMessages.put(containerId, messages);
    }
}

From source file:org.apache.myfaces.config.FacesConfigurator.java

public FacesConfigurator(ExternalContext externalContext) {
    if (externalContext == null) {
        throw new IllegalArgumentException("external context must not be null");
    }/*from ww  w.j a v a 2 s .  c o  m*/
    _externalContext = externalContext;

    _externalContext.getApplicationMap().put(INJECTED_BEAN_STORAGE_KEY, new CopyOnWriteArrayList());
}

From source file:org.hawkular.listener.cache.InventoryHelperTest.java

@Test
public void shouldListMetricsForType() {
    // Data & mocks
    String tenant = "tenant";
    String feed = "feed";
    Metric<String> r1 = new Metric<>("inventory.123.r.r1", null, 7, MetricType.STRING, null);
    Metric<String> r2 = new Metric<>("inventory.123.r.r2", null, 7, MetricType.STRING, null);
    long currentTime = System.currentTimeMillis();
    when(metricsService.findMetricsWithFilters(anyString(), anyObject(), anyString()))
            .thenAnswer(invocationOnMock -> Observable.just(r1, r2));
    // Each call to "buildRootResourceDatapointWithMetrics" will create a root resource
    //  that contains 2 metrics of type "metricType1" and 1 metric of type "metricType2"
    when(metricsService.findStringData(r1.getMetricId(), 0, currentTime, false, 0, Order.DESC)).thenReturn(
            Observable.just(buildRootResourceDatapointWithMetrics(tenant, feed, currentTime - 500, "r1"),
                    buildRootResourceDatapointWithMetrics(tenant, feed, currentTime - 1000, "r1")));
    when(metricsService.findStringData(r2.getMetricId(), 0, currentTime, false, 0, Order.DESC)).thenReturn(
            Observable.just(buildRootResourceDatapointWithMetrics(tenant, feed, currentTime - 10000, "r2")));
    org.hawkular.inventory.api.model.MetricType.Blueprint bp = org.hawkular.inventory.api.model.MetricType.Blueprint
            .builder(MetricDataType.GAUGE).withId("metricType1").withName("Metric type 1").withInterval(60L)
            .withUnit(MetricUnit.BYTES).build();

    // Test & assertions
    List<org.hawkular.inventory.api.model.Metric.Blueprint> collected = new CopyOnWriteArrayList<>();
    InventoryHelper.listMetricsForType(metricsService, tenant, feed, bp, currentTime).toList()
            .subscribe(collected::addAll, Throwables::propagate);
    Assert.assertEquals(4, collected.size());
    // Make sure we only have metric1 and metric2 (their type is metricType1), and not metric3 (type metricType2)
    Assert.assertEquals("metric1", collected.get(0).getId());
    Assert.assertEquals("metric2", collected.get(1).getId());
    Assert.assertEquals("metric1", collected.get(2).getId());
    Assert.assertEquals("metric2", collected.get(3).getId());
}

From source file:org.apache.sling.models.impl.AdapterImplementations.java

public void registerModelToResourceType(final Bundle bundle, final String resourceType,
        final Class<?> adaptableType, final Class<?> clazz) {
    if (resourceType.startsWith("/")) {
        log.warn("Registering model class {} for adaptable {} with absolute resourceType {}.",
                new Object[] { clazz, adaptableType, resourceType });
    }/*from  w w w .j  av a  2s  .  c  o m*/
    ConcurrentMap<String, Class<?>> map;
    ConcurrentMap<Bundle, List<String>> resourceTypeRemovalLists;
    if (adaptableType == Resource.class) {
        map = resourceTypeMappingsForResources;
        resourceTypeRemovalLists = resourceTypeRemovalListsForResources;
    } else if (adaptableType == SlingHttpServletRequest.class) {
        map = resourceTypeMappingsForRequests;
        resourceTypeRemovalLists = resourceTypeRemovalListsForRequests;
    } else {
        log.warn(
                "Found model class {} with resource type {} for adaptable {}. Unsupported type for resourceType binding.",
                new Object[] { clazz, resourceType, adaptableType });
        return;
    }
    Class<?> existingMapping = map.putIfAbsent(resourceType, clazz);
    if (existingMapping == null) {
        resourceTypeRemovalLists.putIfAbsent(bundle, new CopyOnWriteArrayList<String>());
        resourceTypeRemovalLists.get(bundle).add(resourceType);
    } else {
        log.warn(
                "Skipped registering {} for resourceType {} under adaptable {} because of existing mapping to {}",
                new Object[] { clazz, resourceType, adaptableType, existingMapping });
    }
}