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:com.connectsdk.discovery.DiscoveryManager.java

/**
 * Create a new instance of DiscoveryManager.
 * Direct use of this constructor is not recommended. In most cases,
 * you should use DiscoveryManager.getInstance() instead.
 *///w ww .j av a2  s. c  om
public DiscoveryManager(Context context, ConnectableDeviceStore connectableDeviceStore) {
    this.context = context;
    this.connectableDeviceStore = connectableDeviceStore;

    allDevices = new ConcurrentHashMap<String, ConnectableDevice>(8, 0.75f, 2);
    compatibleDevices = new ConcurrentHashMap<String, ConnectableDevice>(8, 0.75f, 2);

    deviceClasses = new ConcurrentHashMap<String, Class<? extends DeviceService>>(4, 0.75f, 2);
    discoveryProviders = new CopyOnWriteArrayList<DiscoveryProvider>();

    discoveryListeners = new CopyOnWriteArrayList<DiscoveryManagerListener>();

    WifiManager wifiMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    multicastLock = wifiMgr.createMulticastLock("Connect SDK");
    multicastLock.setReferenceCounted(true);

    capabilityFilters = new ArrayList<CapabilityFilter>();
    pairingLevel = PairingLevel.OFF;

    receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
                NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);

                switch (networkInfo.getState()) {
                case CONNECTED:
                    if (mSearching) {
                        for (DiscoveryProvider provider : discoveryProviders) {
                            provider.start();
                        }
                    }

                    break;

                case DISCONNECTED:
                    Log.w("Connect SDK", "Network connection is disconnected");

                    for (DiscoveryProvider provider : discoveryProviders) {
                        provider.reset();
                    }

                    allDevices.clear();

                    for (ConnectableDevice device : compatibleDevices.values()) {
                        handleDeviceLoss(device);
                    }
                    compatibleDevices.clear();

                    for (DiscoveryProvider provider : discoveryProviders) {
                        provider.stop();
                    }

                    break;

                case CONNECTING:
                    break;
                case DISCONNECTING:
                    break;
                case SUSPENDED:
                    break;
                case UNKNOWN:
                    break;
                }
            }
        }
    };

    registerBroadcastReceiver();
}

From source file:com.ritesh.idea.plugin.reviewboard.ReviewDataProvider.java

public List<Review.File> files(final Review review, final Progress progress) throws Exception {
    List<Review.File> result = new ArrayList<>();
    final List<Future> futures = new CopyOnWriteArrayList<>();
    final MutableFloat progressF = new MutableFloat(0f);
    final RBDiffList diffList = client.diffListApi(review.id);

    if (diffList.total_results > 0) {
        final String revision = String.valueOf(diffList.diffs[0].revision);
        RBFileDiff fileDiff = client.fileDiffApi(review.id, revision);

        for (final RBFileDiff.File file : fileDiff.files) {
            final Review.File diffFile = new Review.File();

            diffFile.fileId = file.id;/*from w ww  .ja  v a2  s  .  c o  m*/
            diffFile.srcFileName = file.source_file;
            diffFile.dstFileName = file.dest_file;
            diffFile.sourceRevision = file.source_revision;
            diffFile.revision = revision;

            futures.add(ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
                @Override
                public void run() {
                    progress.progress("Loading file contents " + Paths.get(diffFile.srcFileName).getFileName(),
                            progressF.floatValue());
                    diffFile.srcFileContents = client.contents(file.links.original_file.href);
                    progressF.setValue(progressF.floatValue() + 1.0f / diffList.total_results);
                    progress.progress("Completed loading contents", progressF.floatValue());
                }
            }));

            futures.add(ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
                @Override
                public void run() {
                    progress.progress("Loading file contents " + Paths.get(diffFile.dstFileName).getFileName(),
                            progressF.floatValue());
                    diffFile.dstFileContents = client.contents(file.links.patched_file.href);
                    progressF.setValue(progressF.floatValue() + 1.0f / diffList.total_results);
                    progress.progress("Completed loading contents", progressF.floatValue());
                }
            }));
            result.add(diffFile);
        }
    }
    for (Future future : futures)
        future.get();
    return result;
}

From source file:be.agiv.security.AGIVSecurity.java

/**
 * Constructor for X509 credentials. The certificate and corresponding
 * private key are loaded from a PKCS#12 keystore file.
 * /*from w w  w.j a v  a 2 s .  c o m*/
 * @param ipStsLocation
 *            the location of the IP-STS WS-Trust web service.
 * @param rStsLocation
 *            the location of the R-STS WS-Trust web service.
 * @param rStsRealm
 *            the AGIV R-STS realm.
 * @param pkcs12File
 *            the PKCS#12 keystore file.
 * @param pkcs12Password
 *            the PKCS#12 keystore password.
 * @throws SecurityException
 *             gets thrown in case of a PKCS#12 keystore error.
 * @see AGIVSecurity#AGIVSecurity(String, String, X509Certificate,
 *      PrivateKey)
 */
public AGIVSecurity(String ipStsLocation, String rStsLocation, String rStsRealm, File pkcs12File,
        String pkcs12Password) throws SecurityException {
    this.ipStsLocation = ipStsLocation;
    this.rStsLocation = rStsLocation;
    this.rStsRealm = rStsRealm;
    this.username = null;
    this.password = null;

    InputStream pkcs12InputStream;
    try {
        pkcs12InputStream = new FileInputStream(pkcs12File);
    } catch (FileNotFoundException e) {
        throw new SecurityException("PKCS#12 file does not exist: " + pkcs12File.getAbsolutePath());
    }
    Provider sunJSSEProvider = Security.getProvider("SunJSSE");
    try {
        KeyStore keyStore;
        if (null != sunJSSEProvider) {
            // avoid older BouncyCastle implementations
            keyStore = KeyStore.getInstance("PKCS12", sunJSSEProvider);
        } else {
            keyStore = KeyStore.getInstance("PKCS12");
        }
        keyStore.load(pkcs12InputStream, pkcs12Password.toCharArray());
        Enumeration<String> aliases = keyStore.aliases();
        String alias = aliases.nextElement();
        this.certificate = (X509Certificate) keyStore.getCertificate(alias);
        this.privateKey = (PrivateKey) keyStore.getKey(alias, pkcs12Password.toCharArray());
    } catch (Exception e) {
        LOG.error("error loading PKCS#12 keystore: " + e.getMessage(), e);
        throw new SecurityException("error loading PKCS#12 certificate: " + e.getMessage(), e);
    }
    this.externalIpStsClient = null;
    this.secureConversationTokens = new ConcurrentHashMap<String, SecurityToken>();
    this.rStsSecurityTokens = new ConcurrentHashMap<String, SecurityToken>();
    this.stsListeners = new CopyOnWriteArrayList<STSListener>();
}

From source file:org.geoserver.catalog.ResourcePool.java

protected ResourcePool() {
    crsCache = createCrsCache();//ww  w  .  jav a 2  s .c o  m
    dataStoreCache = createDataStoreCache();
    featureTypeCache = createFeatureTypeCache(FEATURETYPE_CACHE_SIZE_DEFAULT);

    featureTypeAttributeCache = createFeatureTypeAttributeCache(FEATURETYPE_CACHE_SIZE_DEFAULT);
    coverageReaderCache = createCoverageReaderCache();
    hintCoverageReaderCache = createHintCoverageReaderCache();

    wmsCache = createWmsCache();
    styleCache = createStyleCache();

    listeners = new CopyOnWriteArrayList<Listener>();
}

From source file:com.microsoft.windowsazure.mobileservices.MobileServicePush.java

/**
 * Unregisters the client for all notifications
 * //from   w  w w. ja  v  a2 s .  c o m
 * @param pnsHandle
 *            PNS specific identifier
 * @param callback
 *            The operation callback
 */
public void unregisterAll(String pnsHandle, final UnregisterCallback callback) {
    getFullRegistrationInformation(pnsHandle, new GetFullRegistrationInformationCallback() {

        @Override
        public void onCompleted(ArrayList<Registration> registrations, Exception exception) {

            if (exception != null) {
                callback.onUnregister(exception);
                return;
            }

            final SyncState state = new SyncState();

            state.size = registrations.size();

            final CopyOnWriteArrayList<String> concurrentArray = new CopyOnWriteArrayList<String>();

            final Object syncObject = new Object();

            if (state.size == 0) {

                removeAllRegistrationsId();

                mIsRefreshNeeded = false;

                callback.onUnregister(null);
                return;
            }

            for (Registration registration : registrations) {
                deleteRegistrationInternal(registration.getName(), registration.getRegistrationId(),
                        new DeleteRegistrationInternalCallback() {

                            @Override
                            public void onDelete(String registrationId, Exception exception) {

                                concurrentArray.add(registrationId);

                                if (exception != null) {
                                    synchronized (syncObject) {
                                        if (!state.alreadyReturn) {
                                            callback.onUnregister(exception);
                                            state.alreadyReturn = true;
                                            return;
                                        }
                                    }
                                }

                                if (concurrentArray.size() == state.size && !state.alreadyReturn) {
                                    removeAllRegistrationsId();

                                    mIsRefreshNeeded = false;

                                    callback.onUnregister(null);

                                    return;
                                }
                            }
                        });
            }
        }
    });
}

From source file:org.carbondata.processing.store.writer.AbstractFactDataWriter.java

/**
 * This method will be used to update the file channel with new file; new
 * file will be created once existing file reached the file size limit This
 * method will first check whether existing file size is exceeded the file
 * size limit if yes then write the leaf metadata to file then set the
 * current file size to 0 close the existing file channel get the new file
 * name and get the channel for new file
 *
 * @throws CarbonDataWriterException if any problem
 *///from w  w w  .  j  a  v a 2 s.c o  m
protected void updateBlockletFileChannel(long blockletDataSize) throws CarbonDataWriterException {
    // get the current file size exceeding the file size threshold
    if ((currentFileSize + blockletDataSize) >= dataBlockSize && currentFileSize != 0) {
        // set the current file size to zero
        LOGGER.info("Writing data to file as max file size reached for file: " + fileName
                + " .Data block size: " + currentFileSize);
        this.currentFileSize = 0;
        if (this.isNodeHolderRequired) {
            FileChannel channel = fileChannel;
            List<NodeHolder> localNodeHolderList = this.nodeHolderList;
            executorService.submit(new WriterThread(fileName, channel, localNodeHolderList));
            this.nodeHolderList = new CopyOnWriteArrayList<NodeHolder>();
            // close the current open file channel
        } else {
            // write meta data to end of the existing file
            writeleafMetaDataToFile(blockletInfoList, fileChannel, fileName);
            blockletInfoList = new ArrayList<BlockletInfoColumnar>(CarbonCommonConstants.CONSTANT_SIZE_TEN);
            CarbonUtil.closeStreams(fileChannel);
        }
        // initialize the new channel
        initializeWriter();
    }
    currentFileSize += blockletDataSize;
}

From source file:com.starit.diamond.client.impl.DefaultSubscriberListener.java

/**
 * DataIDManagerListener/*from ww w . j av  a  2  s  .c o  m*/
 * 
 * @param dataId
 * @param addListeners
 */
public void addManagerListeners(String dataId, String group, String instanceId,
        List<ManagerListener> addListeners) {
    if (null == dataId || null == addListeners || null == instanceId) {
        return;
    }
    if (addListeners.size() == 0) {
        return;
    }

    String key = makeKey(dataId, group);
    ConcurrentMap<String, CopyOnWriteArrayList<ManagerListener>> map = allListeners.get(key);
    if (map == null) {
        map = new ConcurrentHashMap<String, CopyOnWriteArrayList<ManagerListener>>();
        ConcurrentMap<String, CopyOnWriteArrayList<ManagerListener>> oldMap = allListeners.putIfAbsent(key,
                map);
        if (oldMap != null) {
            map = oldMap;
        }
    }

    CopyOnWriteArrayList<ManagerListener> listenerList = map.get(instanceId);
    if (listenerList == null) {
        listenerList = new CopyOnWriteArrayList<ManagerListener>();
        CopyOnWriteArrayList<ManagerListener> oldList = map.putIfAbsent(instanceId, listenerList);
        if (oldList != null) {
            listenerList = oldList;
        }
    }
    listenerList.addAll(addListeners);
}

From source file:org.mqnaas.extensions.odl.capabilities.impl.ODLRootResourceProvider.java

/**
 * Retrieves ODL controller switches and creates switch IRootResources representing them.
 * /* ww w. ja  va  2  s.com*/
 * @param portsMapping
 *            Optional map where (when provided) this function will store a mapping between retrieved NodeConnectors and ports (IResources)
 *            created to represent them.
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws CapabilityNotFoundException
 * @throws ApplicationNotFoundException
 */
private void initializeResources(Map<NodeConnector, IResource> portsMapping) throws InstantiationException,
        IllegalAccessException, CapabilityNotFoundException, ApplicationNotFoundException {
    log.info("Initializing ODL resources for ODL network " + resource.getId());

    resources = new CopyOnWriteArrayList<IRootResource>();

    Nodes nodes = odlSwitchManagerClient.getNodes(DEFAULT_CONNECTOR_NAME);

    for (NodeProperties nodeProperties : nodes.getNodeProperties()) {
        // get information from the node
        String nodeId = nodeProperties.getNode().getNodeID();
        Type nodeType = parseNodeType(nodeProperties.getNode().getNodeType());

        // initialize new RootResource representing this node.
        Collection<Endpoint> odlResourceEndpoints = new ArrayList<Endpoint>(
                resource.getDescriptor().getEndpoints());
        IRootResource odlResource = new RootResource(
                RootResourceDescriptor.create(new Specification(nodeType), odlResourceEndpoints));
        rmListener.resourceAdded(odlResource, this, IRootResourceProvider.class);

        // create ports
        IPortManagement portMgm = serviceProvider.getCapability(odlResource, IPortManagement.class);
        NodeConnectors nodePorts = odlSwitchManagerClient.getNodeConnectors(DEFAULT_CONNECTOR_NAME,
                nodeProperties.getNode().getNodeType().toString(), nodeId);
        for (NodeConnectorProperties nodePortProperties : nodePorts.getNodeConnectorProperties()) {
            String nodePortId = nodePortProperties.getNodeConnector().getNodeConnectorID();
            String nodePortName = nodePortProperties.getProperties().get("name").getValue();
            IResource port = portMgm.createPort();
            IAttributeStore portAttributeStore = serviceProvider.getCapability(port, IAttributeStore.class);
            portAttributeStore.setAttribute(IAttributeStore.RESOURCE_EXTERNAL_ID, nodePortId);
            portAttributeStore.setAttribute(IAttributeStore.RESOURCE_EXTERNAL_NAME, nodePortName);

            if (portsMapping != null)
                portsMapping.put(nodePortProperties.getNodeConnector(), port);
        }

        // stores the map between the created RootResource and the odl node id
        IAttributeStore attributeStore = serviceProvider.getCapability(odlResource, IAttributeStore.class);
        attributeStore.setAttribute(AttributeStore.RESOURCE_EXTERNAL_ID, nodeId);

        // add resource to resources list.
        resources.add(odlResource);

    }

    log.info("Initialized ODL resources in ODL network " + resource.getId());

}

From source file:org.apache.bval.jsr.xml.ValidationParser.java

private static void applyExecutableValidation(final ValidationConfigType xmlConfig,
        final ConfigurationImpl targetConfig) {
    final CopyOnWriteArrayList<ExecutableType> executableTypes = new CopyOnWriteArrayList<ExecutableType>();
    if (xmlConfig.getExecutableValidation() != null && xmlConfig.getExecutableValidation().getEnabled()
            && xmlConfig.getExecutableValidation().getDefaultValidatedExecutableTypes() != null) {
        executableTypes.addAll(/*w  w w  . ja v a  2  s . c  om*/
                xmlConfig.getExecutableValidation().getDefaultValidatedExecutableTypes().getExecutableType());
    }

    if (executableTypes.contains(ExecutableType.ALL)) {
        executableTypes.clear();
        executableTypes.add(ExecutableType.CONSTRUCTORS);
        executableTypes.add(ExecutableType.NON_GETTER_METHODS);
        executableTypes.add(ExecutableType.GETTER_METHODS);
    } else if (executableTypes.contains(ExecutableType.NONE)) { // if both are present ALL gains
        executableTypes.clear();
    }

    targetConfig.setExecutableValidation(executableTypes);
}

From source file:org.danann.cernunnos.runtime.XmlGrammar.java

void addEntry(Entry e) {

    List<Entry> list = entries.get(e.getName());
    if (list == null) {
        list = new CopyOnWriteArrayList<Entry>();
        final List<Entry> oldList = entries.putIfAbsent(e.getName(), list);
        if (oldList != null) {
            list = oldList;/*from ww w.  ja va2 s .c  om*/
        }
    }
    list.add(e);

}