Example usage for java.util.concurrent CopyOnWriteArrayList size

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

Introduction

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

Prototype

public int size() 

Source Link

Document

Returns the number of elements in this list.

Usage

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

/**
 * This method adds the url to the classloader.
 * @param warDirectory/*from w  w w. ja v a  2 s.c  o  m*/
 * @param classLoader
 */
/*private void AddUrlToClassLoader(File warDirectory,WebClassLoader classLoader){
   File webInfDirectory=new File(warDirectory.getAbsolutePath()+"/WEB-INF/lib/");
   //logger.info(webInfDirectory.getAbsolutePath());
   if(webInfDirectory.exists()){
 File[] jarfiles=webInfDirectory.listFiles();
 for(int jarcount=0;jarcount<jarfiles.length;jarcount++){
    //logger.info(jarfiles[jarcount]);
    if(jarfiles[jarcount].getName().endsWith(".jar")){
       try {
       //   //log.info("Adding absolute path "+jarfiles[jarcount].getAbsolutePath());
          new WebServer().addURL(new URL("file:"+jarfiles[jarcount].getAbsolutePath()),classLoader);
       } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
       }
    }
 }
   }
}*/

public void deployService(File sarFile) {
    try {
        Sar sar = (Sar) sardigester.parse(new InputSource(new FileInputStream(sarFile)));
        CopyOnWriteArrayList mbeans = sar.getMbean();
        //log.info(mbeanServer);
        ObjectName objName;
        for (int index = 0; index < mbeans.size(); index++) {
            Mbean mbean = (Mbean) mbeans.get(index);
            //log.info(mbean.getObjectname());
            //log.info(mbean.getCls());
            objName = new ObjectName(mbean.getObjectname());
            Class service = Thread.currentThread().getContextClassLoader().loadClass(mbean.getCls());
            Object obj = service.newInstance();
            if (mbeanServer.isRegistered(objName)) {
                //mbs.invoke(objName, "stopService", null, null);
                //mbs.invoke(objName, "destroy", null, null);
                mbeanServer.unregisterMBean(objName);
            }
            mbeanServer.createMBean(service.getName(), objName);
            //mbs.registerMBean(obj, objName);
            CopyOnWriteArrayList attrlist = mbean.getMbeanAttribute();
            if (attrlist != null) {
                for (int count = 0; count < attrlist.size(); count++) {
                    MBeanAttribute attr = (MBeanAttribute) attrlist.get(count);
                    Attribute mbeanattribute = new Attribute(attr.getName(), attr.getValue());
                    mbeanServer.setAttribute(objName, mbeanattribute);
                }
            }
            Attribute mbeanattribute = new Attribute("ObjectName", objName);
            mbeanServer.setAttribute(objName, mbeanattribute);
            if (((String) mbeanServer.getAttribute(objName, "Deployer")).equals("true")) {
                mbeanServer.invoke(objName, "init", new Object[] { deployerList },
                        new String[] { Vector.class.getName() });
                //this.deployerList.add(objName.getCanonicalName());

            }
            mbeanServer.invoke(objName, "init", new Object[] { serviceList, serverConfig, mbeanServer },
                    new String[] { Vector.class.getName(), ServerConfig.class.getName(),
                            MBeanServer.class.getName() });
            mbeanServer.invoke(objName, "start", null, null);
        }
    } catch (Exception ex) {
        log.error("Could not able to deploy the SAR package " + sarFile.toURI(), ex);
        //ex.printStackTrace();
    }
}

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

/**
 * This method undeployed the SAR/*  w w  w. ja v  a2 s  .  c  o m*/
 * @param dir
 * @return
 */
public boolean deleteDir(File dir) {
    String fileName = dir.getName();
    //log.info("Dirname to be deleted"+fileName);
    Sar sar = null;
    fileName = fileName.substring(0, fileName.indexOf('.'));
    fileName += "sar";
    try {
        sar = (Sar) sardigester.parse(new InputSource(new FileInputStream(
                serverConfig.getDeploydirectory() + "/" + fileName + "/META-INF/" + "mbean-service.xml")));
    } catch (Exception e) {
        log.error("Could not able to parse sar " + serverConfig.getDeploydirectory() + "/" + fileName
                + "/META-INF/" + "mbean-service.xml", e);
        // TODO Auto-generated catch block
        //e.printStackTrace();
    }
    URLClassLoader sarClassLoader = (URLClassLoader) sarsMap.get(fileName);
    if (sarClassLoader != null) {
        ClassLoaderUtil.closeClassLoader(sarClassLoader);
        CopyOnWriteArrayList mbeans = sar.getMbean();
        //log.info(mbeanServer);
        ObjectName objName;
        try {
            for (int index = 0; index < mbeans.size(); index++) {
                Mbean mbean = (Mbean) mbeans.get(index);
                //log.info(mbean.getObjectname());
                //log.info(mbean.getCls());
                objName = new ObjectName(mbean.getObjectname());
                if (mbeanServer.isRegistered(objName)) {
                    if (((String) mbeanServer.getAttribute(objName, "Deployer")).equals("true")) {
                        mbeanServer.invoke(objName, "undeploy", null, null);
                    }
                    mbeanServer.invoke(objName, "stop", null, null);
                    mbeanServer.invoke(objName, "destroy", null, null);
                    //mbs.invoke(objName, "stopService", null, null);
                    //mbs.invoke(objName, "destroy", null, null);
                    mbeanServer.unregisterMBean(objName);
                }
            }
        } catch (Exception e) {
            log.error("Could not able to undeploy stop and destroy sar in " + dir.getName(), e);
            // TODO Auto-generated catch block
            //e.printStackTrace();
        }
    }
    return recursiveDelete(new File(serverConfig.getDeploydirectory() + "/" + fileName + "/"));

}

From source file:org.github.gitswarm.GitSwarm.java

/**
 * TODO This could be made to look a lot better.
 *//*from  w w w.  j a  v  a 2s.  c  o m*/
private void drawPopular() {
    CopyOnWriteArrayList<FileNode> al = new CopyOnWriteArrayList<>();
    noStroke();
    textFont(font);
    textAlign(RIGHT, TOP);
    fill(fontColor, 200);
    text("Popular Nodes (touches):", width - 120, 0);
    for (FileNode fn : nodes.values()) {
        if (fn.qualifies()) {
            // Insertion Sort
            if (al.size() > 0) {
                int j = 0;
                for (; j < al.size(); j++) {
                    if (fn.compareTo(al.get(j)) > 0) {
                        break;
                    }
                }
                al.add(j, fn);
            } else {
                al.add(fn);
            }
        }
    }

    int i = 1;
    ListIterator<FileNode> it = al.listIterator();
    while (it.hasNext()) {
        FileNode n = it.next();
        // Limit to the top 10.
        if (i <= 10) {
            text(n.getName() + "  (" + n.getTouches() + ")", width - 100, 10 * i++);
        } else if (i > 10) {
            break;
        }
    }
}

From source file:ypcnv.converter.mainFrame.MainFrame.java

/**
 * Check configurations for nulls, arrange them, etc.
 * @param confsList - configurations to be processed.
 *//*from   w  ww .j a  v a2s  .c o  m*/
private void refactorConfigurations(ArrayList<DataSourceConf> confsList) {
    CopyOnWriteArrayList<DataSourceConf> confs = new CopyOnWriteArrayList<DataSourceConf>();
    confs.addAll(confsList);

    srcObjectConfig = null;
    dstObjectConfig = null;

    for (DataSourceConf config : confs) {
        Side side = config.getSide();
        if (side == null) {
            side = Side.heath;
        }
        switch (side) {
        case source:
            srcObjectConfig = new DataSourceConf(config);
            confsList.remove(config);
            break;
        case destination:
            dstObjectConfig = new DataSourceConf(config);
            confsList.remove(config);
            break;
        }
    }

    int quantityOfWantedDataSources = 2;
    for (int idx = 0; idx < confs.size() && idx < quantityOfWantedDataSources && confs.size() > 0; idx++) {
        Iterator<DataSourceConf> iter = confs.iterator();
        while (iter.hasNext()) {
            DataSourceConf conf = iter.next();
            if (srcObjectConfig == null) {
                srcObjectConfig = conf;
                confsList.remove(conf);
            } else if (dstObjectConfig == null) {
                dstObjectConfig = conf;
                confsList.remove(conf);
            }

        }
    }

    if (srcObjectConfig == null) {
        srcObjectConfig = new DataSourceConf(null, null, null);
    }
    if (dstObjectConfig == null) {
        dstObjectConfig = new DataSourceConf(null, null, null);
    }

    confsList = new ArrayList<DataSourceConf>();
    confsList.add(srcObjectConfig);
    confsList.add(dstObjectConfig);

}

From source file:com.web.server.EARDeployer.java

/**
 * This method configures the executor services from the jar file.
 * //from  ww  w.  j  av  a  2s  .  c o m
 * @param jarFile
 * @param classList
 * @throws FileSystemException
 */
public void deployExecutorServicesEar(String earFileName, FileObject earFile,
        StandardFileSystemManager fsManager) throws FileSystemException {
    try {
        System.out.println("EARFILE NAMEs=" + earFileName);
        CopyOnWriteArrayList<FileObject> fileObjects = new CopyOnWriteArrayList<FileObject>();
        CopyOnWriteArrayList<FileObject> warObjects = new CopyOnWriteArrayList<FileObject>();
        ConcurrentHashMap jarClassListMap = new ConcurrentHashMap();
        CopyOnWriteArrayList<String> classList;
        obtainUrls(earFile, earFile, fileObjects, jarClassListMap, warObjects, fsManager);
        VFSClassLoader customClassLoaderBaseLib = new VFSClassLoader(
                fileObjects.toArray(new FileObject[fileObjects.size()]), fsManager,
                Thread.currentThread().getContextClassLoader());
        VFSClassLoader customClassLoader = null;
        Set keys = jarClassListMap.keySet();
        Iterator key = keys.iterator();
        FileObject jarFileObject;
        ConcurrentHashMap classLoaderPath = new ConcurrentHashMap();
        filesMap.put(earFileName, classLoaderPath);
        for (FileObject warFileObj : warObjects) {
            if (warFileObj.getName().getBaseName().endsWith(".war")) {
                //logger.info("filePath"+filePath);
                String filePath = scanDirectory + "/" + warFileObj.getName().getBaseName();
                log.info(filePath);
                String fileName = warFileObj.getName().getBaseName();
                WebClassLoader classLoader = new WebClassLoader(new URL[] {});
                log.info(classLoader);
                warDeployer.deleteDir(
                        new File(deployDirectory + "/" + fileName.substring(0, fileName.lastIndexOf(".war"))));
                new File(deployDirectory + "/" + fileName.substring(0, fileName.lastIndexOf(".war"))).mkdirs();
                log.info(deployDirectory + "/" + fileName.substring(0, fileName.lastIndexOf(".war")));
                urlClassLoaderMap.put(
                        deployDirectory + "/" + fileName.substring(0, fileName.lastIndexOf(".war")),
                        classLoader);
                classLoaderPath.put(warFileObj.getName().getBaseName(),
                        deployDirectory + "/" + fileName.substring(0, fileName.lastIndexOf(".war")));
                warDeployer.extractWar(new File(filePath), classLoader);

                if (exec != null) {
                    exec.shutdown();
                }
                new File(scanDirectory + "/" + warFileObj.getName().getBaseName()).delete();
                exec = Executors.newSingleThreadScheduledExecutor();
                exec.scheduleAtFixedRate(task, 0, 1000, TimeUnit.MILLISECONDS);
            }
        }
        for (int keyCount = 0; keyCount < keys.size(); keyCount++) {
            jarFileObject = (FileObject) key.next();
            {
                classList = (CopyOnWriteArrayList<String>) jarClassListMap.get(jarFileObject);
                customClassLoader = new VFSClassLoader(jarFileObject, fsManager, customClassLoaderBaseLib);
                this.urlClassLoaderMap.put(
                        scanDirectory + "/" + earFileName + "/" + jarFileObject.getName().getBaseName(),
                        customClassLoader);
                classLoaderPath.put(jarFileObject.getName().getBaseName(),
                        scanDirectory + "/" + earFileName + "/" + jarFileObject.getName().getBaseName());
                for (int classCount = 0; classCount < classList.size(); classCount++) {
                    String classwithpackage = classList.get(classCount).substring(0,
                            classList.get(classCount).indexOf(".class"));
                    classwithpackage = classwithpackage.replace("/", ".");
                    // System.out.println("classList:"+classwithpackage.replace("/","."));
                    try {
                        if (!classwithpackage.contains("$")) {

                            /*System.out.println("EARFILE NAME="+fileName);
                            System.out
                                  .println(scanDirectory
                            + "/"
                            + fileName
                            + "/"
                            + jarFileObject.getName()
                                  .getBaseName());
                                    
                            System.out.println(urlClassLoaderMap);*/
                            Class executorServiceClass = customClassLoader.loadClass(classwithpackage);

                            Annotation[] classServicesAnnot = executorServiceClass.getDeclaredAnnotations();

                            if (classServicesAnnot != null) {
                                for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) {
                                    if (classServicesAnnot[annotcount] instanceof RemoteCall) {
                                        RemoteCall remoteCall = (RemoteCall) classServicesAnnot[annotcount];
                                        //registry.unbind(remoteCall.servicename());
                                        System.out.println(remoteCall.servicename().trim());
                                        try {
                                            for (int count = 0; count < 2; count++) {
                                                RemoteInterface reminterface = (RemoteInterface) UnicastRemoteObject
                                                        .exportObject(
                                                                (Remote) executorServiceClass.newInstance(), 0);
                                                registry.rebind(remoteCall.servicename().trim(), reminterface);
                                            }
                                        } catch (Exception ex) {
                                            ex.printStackTrace();
                                        }
                                    }
                                }
                            }
                            // System.out.println(executorServiceClass.newInstance());
                            // System.out.println("executor class in ExecutorServicesConstruct"+executorServiceClass);
                            // System.out.println();
                            Method[] methods = executorServiceClass.getDeclaredMethods();
                            for (Method method : methods) {
                                Annotation[] annotations = method.getDeclaredAnnotations();
                                for (Annotation annotation : annotations) {
                                    if (annotation instanceof ExecutorServiceAnnot) {
                                        ExecutorServiceAnnot executorServiceAnnot = (ExecutorServiceAnnot) annotation;
                                        ExecutorServiceInfo executorServiceInfo = new ExecutorServiceInfo();
                                        executorServiceInfo.setExecutorServicesClass(executorServiceClass);
                                        executorServiceInfo.setMethod(method);
                                        executorServiceInfo.setMethodParams(method.getParameterTypes());
                                        //                              System.out.println("serice name="
                                        //                                    + executorServiceAnnot
                                        //                                          .servicename());
                                        //                              System.out.println("method info="
                                        //                                    + executorServiceInfo);
                                        //                              System.out.println(method);
                                        // if(servicesMap.get(executorServiceAnnot.servicename())==null)throw
                                        // new Exception();
                                        executorServiceMap.put(executorServiceAnnot.servicename(),
                                                executorServiceInfo);
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            jarFileObject.close();
        }
        for (FileObject fobject : fileObjects) {
            fobject.close();
        }
        System.out.println("Channel unlocked");
        earFile.close();
        fsManager.closeFileSystem(earFile.getFileSystem());
        // ClassLoaderUtil.closeClassLoader(customClassLoader);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:android.bus.EventBus.java

private void subscribe(Object subscriber, SubscriberMethod subscriberMethod, boolean sticky, int priority) {
    Class<?> eventType = subscriberMethod.eventType;
    CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
    Subscription newSubscription = new Subscription(subscriber, subscriberMethod, priority);
    if (subscriptions == null) {
        subscriptions = new CopyOnWriteArrayList<Subscription>();
        subscriptionsByEventType.put(eventType, subscriptions);
    }//  w ww.  j a  v  a  2 s  . c o m
    // FIXME ???
    // else {
    // if (subscriptions.contains(newSubscription)) {
    // throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
    // + eventType);
    // }
    // }

    // Starting with EventBus 2.2 we enforced methods to be public (might change with annotations again)
    // subscriberMethod.method.setAccessible(true);

    int size = subscriptions.size();
    for (int i = 0; i <= size; i++) {
        if (i == size || newSubscription.priority > subscriptions.get(i).priority) {
            subscriptions.add(i, newSubscription);
            break;
        }
    }

    List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
    if (subscribedEvents == null) {
        subscribedEvents = new ArrayList<Class<?>>();
        typesBySubscriber.put(subscriber, subscribedEvents);
    }
    subscribedEvents.add(eventType);

    if (sticky) {
        if (eventInheritance) {
            // Existing sticky events of all subclasses of eventType have to be considered.
            // Note: Iterating over all events may be inefficient with lots of sticky events,
            // thus data structure should be changed to allow a more efficient lookup
            // (e.g. an additional map storing sub classes of super classes: Class -> List<Class>).
            Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet();
            for (Map.Entry<Class<?>, Object> entry : entries) {
                Class<?> candidateEventType = entry.getKey();
                if (eventType.isAssignableFrom(candidateEventType)) {
                    Object stickyEvent = entry.getValue();
                    checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                }
            }
        } else {
            Object stickyEvent = stickyEvents.get(eventType);
            checkPostStickyEventToSubscription(newSubscription, stickyEvent);
        }
    }
}

From source file:codeswarm.code_swarm.java

/**
 * TODO This could be made to look a lot better.
 *///from w  w  w  . j a v  a  2 s.c o  m
public void drawPopular() {
    CopyOnWriteArrayList<FileNode> al = new CopyOnWriteArrayList<FileNode>();
    noStroke();
    textFont(font);
    textAlign(RIGHT, TOP);
    fill(255, 200);
    text("Popular Nodes (touches):", width - 120, 0);
    for (int i = 0; i < nodes.size(); i++) {
        FileNode fn = nodes.get(i);
        if (fn.qualifies()) {
            // Insertion Sort
            if (al.size() > 0) {
                int j = 0;
                for (; j < al.size(); j++) {
                    if (fn.compareTo(al.get(j)) <= 0) {
                        continue;
                    } else {
                        break;
                    }
                }
                al.add(j, fn);
            } else {
                al.add(fn);
            }
        }
    }

    int i = 1;
    ListIterator<FileNode> it = al.listIterator();
    while (it.hasNext()) {
        FileNode n = it.next();
        // Limit to the top 10.
        if (i <= 10) {
            text(n.getName() + "  (" + n.getTouches() + ")", width - 100, 10 * i++);
        } else if (i > 10) {
            break;
        }
    }
}

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

/**
 * This method extracts the SAR archive and configures for the SAR and starts the services
 * @param file// w  ww  .  j a  va 2  s .c o  m
 * @param warDirectoryPath
 * @throws IOException
 */
public void extractSar(File file, String warDirectoryPath) throws IOException {
    ZipFile zip = new ZipFile(file);
    ZipEntry ze = null;
    String fileName = file.getName();
    fileName = fileName.substring(0, fileName.indexOf('.'));
    fileName += "sar";
    String fileDirectory;
    CopyOnWriteArrayList classPath = new CopyOnWriteArrayList();
    Enumeration<? extends ZipEntry> entries = zip.entries();
    int numBytes;
    while (entries.hasMoreElements()) {
        ze = entries.nextElement();
        // //System.out.println("Unzipping " + ze.getName());
        String filePath = deployDirectory + "/" + fileName + "/" + ze.getName();
        if (!ze.isDirectory()) {
            fileDirectory = filePath.substring(0, filePath.lastIndexOf('/'));
        } else {
            fileDirectory = filePath;
        }
        // //System.out.println(fileDirectory);
        createDirectory(fileDirectory);
        if (!ze.isDirectory()) {
            FileOutputStream fout = new FileOutputStream(filePath);
            byte[] inputbyt = new byte[8192];
            InputStream istream = zip.getInputStream(ze);
            while ((numBytes = istream.read(inputbyt, 0, inputbyt.length)) >= 0) {
                fout.write(inputbyt, 0, numBytes);
            }
            fout.close();
            istream.close();
            if (ze.getName().endsWith(".jar")) {
                classPath.add(filePath);
            }
        }
    }
    zip.close();
    URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    URL[] urls = loader.getURLs();
    WebClassLoader sarClassLoader = new WebClassLoader(urls);
    for (int index = 0; index < classPath.size(); index++) {
        System.out.println("file:" + classPath.get(index));
        new WebServer().addURL(new URL("file:" + classPath.get(index)), sarClassLoader);
    }
    new WebServer().addURL(new URL("file:" + deployDirectory + "/" + fileName + "/"), sarClassLoader);
    sarsMap.put(fileName, sarClassLoader);
    System.out.println(sarClassLoader.geturlS());
    try {
        Sar sar = (Sar) sardigester.parse(new InputSource(
                new FileInputStream(deployDirectory + "/" + fileName + "/META-INF/" + "mbean-service.xml")));
        CopyOnWriteArrayList mbeans = sar.getMbean();
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        System.out.println(mbs);
        ObjectName objName;
        for (int index = 0; index < mbeans.size(); index++) {
            Mbean mbean = (Mbean) mbeans.get(index);
            System.out.println(mbean.getObjectname());
            System.out.println(mbean.getCls());
            objName = new ObjectName(mbean.getObjectname());
            Class helloWorldService = sarClassLoader.loadClass(mbean.getCls());
            Object obj = helloWorldService.newInstance();
            if (mbs.isRegistered(objName)) {
                mbs.invoke(objName, "stopService", null, null);
                //mbs.invoke(objName, "destroy", null, null);
                mbs.unregisterMBean(objName);
            }
            mbs.registerMBean(obj, objName);
            CopyOnWriteArrayList attrlist = mbean.getMbeanAttribute();
            if (attrlist != null) {
                for (int count = 0; count < attrlist.size(); count++) {
                    MBeanAttribute attr = (MBeanAttribute) attrlist.get(count);
                    Attribute mbeanattribute = new Attribute(attr.getName(), attr.getValue());
                    mbs.setAttribute(objName, mbeanattribute);
                }
            }
            mbs.invoke(objName, "startService", null, null);
        }
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InstantiationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MalformedObjectNameException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InstanceAlreadyExistsException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MBeanRegistrationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NotCompliantMBeanException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InstanceNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ReflectionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MBeanException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvalidAttributeValueException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (AttributeNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

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

/**
 * Unregisters the client for all notifications
 * /* w  ww.  j av  a2  s.  c om*/
 * @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:com.microsoft.windowsazure.mobileservices.notifications.MobileServicePush.java

private ListenableFuture<Void> unregisterAllInternal(ArrayList<Registration> registrations) {
    final SettableFuture<Void> resultFuture = SettableFuture.create();

    final SyncState state = new SyncState();

    state.size = registrations.size();/*from   w ww .j  ava 2  s  .c o m*/

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

    final Object syncObject = new Object();

    if (state.size == 0) {

        removeAllRegistrationsId();

        mIsRefreshNeeded = false;

        resultFuture.set(null);

        return resultFuture;
    }

    for (final Registration registration : registrations) {

        ListenableFuture<Void> serviceFilterFuture = deleteRegistrationInternal(registration.getName(),
                registration.getRegistrationId());

        Futures.addCallback(serviceFilterFuture, new FutureCallback<Void>() {
            @Override
            public void onFailure(Throwable exception) {

                if (exception != null) {
                    synchronized (syncObject) {
                        if (!state.alreadyReturn) {
                            state.alreadyReturn = true;

                            resultFuture.setException(exception);

                            return;
                        }
                    }
                }
            }

            @Override
            public void onSuccess(Void v) {
                concurrentArray.add(registration.getRegistrationId());

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

                    mIsRefreshNeeded = false;

                    resultFuture.set(null);

                    return;
                }
            }
        });
    }

    return resultFuture;
}