Example usage for java.util.concurrent ConcurrentHashMap values

List of usage examples for java.util.concurrent ConcurrentHashMap values

Introduction

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

Prototype

ValuesView values

To view the source code for java.util.concurrent ConcurrentHashMap values.

Click Source Link

Usage

From source file:com.taobao.common.tedis.cache.DefaultLocalCache.java

public Collection<V> values() {
    checkAll();//from  w  w  w .  j  ava 2s  .  com

    Collection<V> values = new ArrayList<V>();

    for (ConcurrentHashMap<K, SoftReference<V>> cache : caches) {
        for (SoftReference<V> sr : cache.values()) {
            values.add(sr.get());
        }
    }

    return values;
}

From source file:com.guang.eunormia.common.cache.DefaultLocalCache.java

@Override
public Collection<V> values() {
    checkAll();/*from   ww  w  .  ja va  2 s .  c  o m*/

    Collection<V> values = new ArrayList<V>();

    for (ConcurrentHashMap<K, SoftReference<V>> cache : caches) {
        for (SoftReference<V> sr : cache.values()) {
            values.add(sr.get());
        }
    }

    return values;
}

From source file:com.doctor.other.concurrent_hash_map_based_table.ConcurrentHashMapBasedTable.java

public Long getSumForRowKey(final String rowKey) {
    if (StringUtils.isBlank(rowKey)) {
        return Long.valueOf(0L);
    }//from www  .  j  av a2 s  . com

    ConcurrentHashMap<String, ConcurrentSkipListMap<String, ConcurrentSet<T>>> map = table.get(rowKey);
    if (map == null) {
        return Long.valueOf(0L);
    }

    return map.values().parallelStream().flatMap(k -> k.values().parallelStream()).mapToLong(k2 -> k2.size())
            .sum();
}

From source file:edu.isi.karma.kr2rml.writer.JSONKR2RMLRDFWriter.java

@Override
public void finishRow() {
    for (ConcurrentHashMap<String, JSONObject> records : this.rootObjectsByTriplesMapId.values()) {
        for (JSONObject value : records.values()) {
            if (value.has(atId)) {
                String Id = value.get(atId).toString();
                if (!isValidURI(Id)) {
                    if (!disableNesting) {
                        value.remove(atId);
                    } else if (!isValidBlankNode(Id)) {
                        value.remove(atId);
                    }//w w  w .j  av a 2 s  .co  m
                }

            }
            collapseSameType(value);
            if (!firstObject) {
                outWriter.println(",");
            }
            firstObject = false;
            if (location != null) {
                value.put("@context", location.toString());
            } else if (context != null) {
                value.put("@context", context);
            }
            outWriter.print(value.toString(4));
        }
    }
    for (Entry<String, ConcurrentHashMap<String, JSONObject>> entry : this.rootObjectsByTriplesMapId
            .entrySet()) {
        entry.getValue().clear();
    }
    for (Entry<String, ConcurrentHashMap<String, JSONObject>> entry : this.generatedObjectsByTriplesMapId
            .entrySet()) {
        entry.getValue().clear();
    }
    this.generatedObjectsWithoutTriplesMap.clear();
}

From source file:com.weibo.api.motan.registry.support.LocalRegistryService.java

private void notifyListeners(URL changedUrl) {
    List<URL> interestingUrls = discover(changedUrl);
    if (interestingUrls != null) {
        ConcurrentHashMap<URL, ConcurrentHashSet<NotifyListener>> urlListeners = subscribeListeners
                .get(getSubscribeKey(changedUrl));
        if (urlListeners == null) {
            return;
        }/*from  w ww  .j a  v  a  2 s  .co  m*/

        for (ConcurrentHashSet<NotifyListener> listeners : urlListeners.values()) {
            for (NotifyListener ln : listeners) {
                try {
                    ln.notify(getUrl(), interestingUrls);
                } catch (Exception e) {
                    LoggerUtil.warn(
                            String.format("Exception when notify listerner %s, changedUrl: %s", ln, changedUrl),
                            e);
                }
            }
        }

    }
}

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

public void deployEjbJar(URL url, StandardFileSystemManager manager, ClassLoader cL) {
    try {//from  w  w  w. j ava 2 s  .co m
        Vector<EJBContext> ejbContexts = null;
        EJBContext ejbContext;
        log.info(url.toURI());
        ConcurrentHashMap<String, RARArchiveData> rardata = (ConcurrentHashMap<String, RARArchiveData>) mbeanServer
                .getAttribute(rarDeployerName, "RARArchiveDataAllAdapters");
        Collection<RARArchiveData> rarcls = rardata.values();
        Iterator<RARArchiveData> rarcl = rarcls.iterator();
        RARArchiveData rararcdata;

        FileObject filetoScan = manager.resolveFile("jar:" + url.toString() + "!/");
        HashSet<Class<?>>[] classes = new HashSet[] { new HashSet(), new HashSet(), new HashSet() };

        VFSClassLoader jarCL;

        if (cL != null) {
            jarCL = new VFSClassLoader(new FileObject[] { filetoScan }, manager, cL);
        } else {
            jarCL = new VFSClassLoader(new FileObject[] { filetoScan }, manager,
                    Thread.currentThread().getContextClassLoader());
        }
        Class[] annot = new Class[] { Stateless.class, Stateful.class, MessageDriven.class };
        scanJar(filetoScan, classes, annot, jarCL);
        Set<Class<?>> clsStateless = classes[0];
        Set<Class<?>> clsStateful = classes[1];
        Set<Class<?>> clsMessageDriven = classes[2];
        //System.gc();
        staticObjs = null;
        EJBContainer container = EJBContainer.getInstance(classes);
        container.inject();
        if (clsStateless.size() > 0) {
            staticObjs = new Vector<Object>();
            ejbContexts = new Vector<EJBContext>();
            ejbContext = new EJBContext();
            ejbContext.setJarPath(url.toString());
            ejbContext.setJarDeployed(url.toString());
            for (Class<?> ejbInterface : clsStateless) {
                BeanPool.getInstance().create(ejbInterface);
                obj = BeanPool.getInstance().get(ejbInterface);
                System.out.println(obj);
                ProxyFactory factory = new ProxyFactory();
                proxyobj = factory.createWithBean(obj);
                staticObjs.add(proxyobj);
                Object unicastobj = UnicastRemoteObject.exportObject((Remote) proxyobj, 0);
                String remoteBinding = container.getRemoteBinding(ejbInterface);
                System.out.println(remoteBinding + " for EJB" + obj);
                if (remoteBinding != null) {
                    // registry.unbind(remoteBinding);
                    ic.bind("java:/" + remoteBinding, (Remote) unicastobj);
                    ejbContext.put(remoteBinding, obj.getClass());
                    //registry.rebind(remoteBinding, (Remote)unicastobj);
                }
                // registry.rebind("name", (Remote) obj);
            }
            ejbContexts.add(ejbContext);
            jarEJBMap.put(url.toString(), ejbContexts);
        }
        if (clsStateful.size() > 0) {
            if (staticObjs == null) {
                staticObjs = new Vector<Object>();
            }
            if (ejbContexts == null) {
                ejbContexts = new Vector<EJBContext>();
            }
            ejbContext = new EJBContext();
            ejbContext.setJarPath(url.toString());
            ejbContext.setJarDeployed(url.toString());
            StatefulBeanObject statefulBeanObject = null;
            for (Class<?> ejbInterface : clsStateful) {
                BeanPool.getInstance().create(ejbInterface);
                obj1 = ejbInterface.newInstance();
                if (statefulBeanObject == null) {
                    statefulBeanObject = new StatefulBeanObject(obj1, url.toString());
                } else {
                    statefulBeanObject.addStatefulSessionBeanObject(obj1);
                }
                //System.out.println(obj1);
                staticObjs.add(statefulBeanObject);
                /*Object unicastobj1 = UnicastRemoteObject.exportObject(
                      (Remote) obj1,
                      0);*/
                String remoteBinding = container.getRemoteBinding(ejbInterface);
                System.out.println(remoteBinding + " for EJB" + statefulBeanObject);
                if (remoteBinding != null) {
                    // registry.unbind(remoteBinding);
                    ic.bind("java:/" + remoteBinding, statefulBeanObject);
                    ejbContext.put(remoteBinding, statefulBeanObject.getClass());
                    //registry.rebind(remoteBinding, (Remote)unicastobj1);
                }
                // registry.rebind("name", (Remote) obj);
            }
            ejbContexts.add(ejbContext);
            jarEJBMap.put(url.toString(), ejbContexts);
        }
        if (clsMessageDriven.size() > 0) {

            MDBContext mdbContext = null;
            ConcurrentHashMap<String, MDBContext> mdbContexts;
            if (jarMDBMap.get(url.toString()) != null) {
                mdbContexts = jarMDBMap.get(url.toString());
            } else {
                mdbContexts = new ConcurrentHashMap<String, MDBContext>();
            }
            jarMDBMap.put(url.toString(), mdbContexts);
            MDBContext mdbContextOld;
            for (Class<?> mdbBean : clsMessageDriven) {
                String classwithpackage = mdbBean.getName();
                //System.out.println("class package" + classwithpackage);
                classwithpackage = classwithpackage.replace("/", ".");
                //System.out.println("classList:"
                //   + classwithpackage.replace("/", "."));
                final Class mdbBeanCls = mdbBean;
                try {
                    if (!classwithpackage.contains("$")) {
                        // System.out.println("executor class in ExecutorServicesConstruct"+executorServiceClass);
                        // System.out.println();
                        if (!mdbBean.isInterface()) {
                            Annotation[] classServicesAnnot = mdbBean.getDeclaredAnnotations();
                            if (classServicesAnnot != null) {
                                Adapter adapter = null;
                                ActivationConfigProperty[] activationConfigProp = null;
                                for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) {
                                    if (classServicesAnnot[annotcount] instanceof Adapter) {
                                        adapter = (Adapter) classServicesAnnot[annotcount];
                                    } else if (classServicesAnnot[annotcount] instanceof MessageDriven) {
                                        MessageDriven messageDrivenAnnot = (MessageDriven) classServicesAnnot[annotcount];
                                        activationConfigProp = messageDrivenAnnot.activationConfig();
                                        mdbContext = new MDBContext();
                                        mdbContext.setMdbName(messageDrivenAnnot.name());
                                    }
                                }
                                if (adapter != null) {
                                    /*if(rarcl.hasNext()){
                                       rararcdata=rardata.get(rarDeployerName);
                                          rararcdata=rarcl.next();
                                          //classLoader = new VFSClassLoader(rararcdata.getVfsClassLoader().getFileObjects(),rararcdata.getFsManager(),classLoader);
                                          FileObject[] fileObjectArray=rararcdata.getVfsClassLoader().getFileObjects();
                                          //urlset.addAll(ClasspathHelper.forClassLoader(rararcdata.getVfsClassLoader()));
                                          for(FileObject fileObject:fileObjectArray){
                                             fileObjects.add(fileObject.getURL());
                                             //urlset.add(fileObject.getURL());
                                             //System.out.println(Vfs.fromURL(fileObject.getURL()).getFiles().iterator().next().getRelativePath());
                                          }
                                          classLoader = new URLClassLoader(fileObjects.toArray(new URL[fileObjects.size()]),Thread.currentThread().getContextClassLoader());
                                    }*/
                                    RARArchiveData rarArchiveData = (RARArchiveData) mbeanServer.invoke(
                                            rarDeployerName, "getRARArchiveData",
                                            new Object[] { adapter.adapterName() },
                                            new String[] { String.class.getName() });
                                    if (rarArchiveData == null)
                                        throw new Exception("RAR Adapter " + adapter.adapterName()
                                                + " Not found in deploy folder");
                                    Class resourceAdapterClass = rarArchiveData.getResourceAdapterClass();
                                    final ResourceAdapter resourceAdapter = (ResourceAdapter) resourceAdapterClass
                                            .newInstance();
                                    Class activationSpecClass = rarArchiveData.getActivationspecclass();
                                    final ActivationSpec activationSpec = (ActivationSpec) activationSpecClass
                                            .newInstance();
                                    Vector<ConfigProperty> configProperties = rarArchiveData.getConfigPropery();
                                    Integer configPropertyInteger;
                                    Long configPropertyLong;
                                    Boolean configPropertyBoolean;
                                    Method method;
                                    if (configProperties != null) {
                                        for (ConfigProperty configProperty : configProperties) {
                                            String property = configProperty.getConfigpropertyname();
                                            property = (property.charAt(0) + "").toUpperCase()
                                                    + property.substring(1);
                                            Class propertytype = Class
                                                    .forName(configProperty.getConfigpropertytype());
                                            try {

                                                method = activationSpecClass.getMethod("set" + property,
                                                        propertytype);
                                                if (propertytype == String.class) {
                                                    method.invoke(activationSpec,
                                                            configProperty.getConfigpropertyvalue());
                                                    ConfigResourceAdapter(resourceAdapterClass, propertytype,
                                                            resourceAdapter, property, configProperty);
                                                } else if (propertytype == Integer.class) {
                                                    if (configProperty.getConfigpropertyvalue() != null
                                                            && !configProperty.getConfigpropertyvalue()
                                                                    .equalsIgnoreCase("")) {
                                                        configPropertyInteger = new Integer(
                                                                configProperty.getConfigpropertyvalue());
                                                        try {
                                                            method.invoke(activationSpec,
                                                                    configPropertyInteger);
                                                        } catch (Exception ex) {
                                                            method.invoke(activationSpec,
                                                                    configPropertyInteger.intValue());
                                                        }
                                                        ConfigResourceAdapter(resourceAdapterClass,
                                                                propertytype, resourceAdapter, property,
                                                                configProperty);
                                                    }
                                                } else if (propertytype == Long.class) {
                                                    if (configProperty.getConfigpropertyvalue() != null
                                                            && !configProperty.getConfigpropertyvalue()
                                                                    .equalsIgnoreCase("")) {
                                                        configPropertyLong = new Long(
                                                                configProperty.getConfigpropertyvalue());
                                                        method.invoke(activationSpec, configPropertyLong);
                                                        ConfigResourceAdapter(resourceAdapterClass,
                                                                propertytype, resourceAdapter, property,
                                                                configProperty);
                                                    }
                                                } else if (propertytype == Boolean.class) {
                                                    if (configProperty.getConfigpropertyvalue() != null
                                                            && !configProperty.getConfigpropertyvalue()
                                                                    .equalsIgnoreCase("")) {
                                                        configPropertyBoolean = new Boolean(
                                                                configProperty.getConfigpropertyvalue());
                                                        method.invoke(activationSpec, configPropertyBoolean);
                                                        ConfigResourceAdapter(resourceAdapterClass,
                                                                propertytype, resourceAdapter, property,
                                                                configProperty);
                                                    }
                                                }
                                            } catch (Exception ex) {
                                                try {
                                                    if (propertytype == Integer.class) {
                                                        method = activationSpecClass.getMethod("set" + property,
                                                                int.class);
                                                        if (configProperty.getConfigpropertyvalue() != null
                                                                && !configProperty.getConfigpropertyvalue()
                                                                        .equalsIgnoreCase("")) {
                                                            method = activationSpecClass
                                                                    .getMethod("set" + property, int.class);
                                                            configPropertyInteger = new Integer(
                                                                    configProperty.getConfigpropertyvalue());
                                                            method.invoke(activationSpec,
                                                                    configPropertyInteger.intValue());
                                                            //ConfigResourceAdapter(resourceAdapterClass,propertytype,resourceAdapter,property,configProperty);                                       
                                                        }
                                                    } else if (propertytype == Long.class) {
                                                        if (configProperty.getConfigpropertyvalue() != null
                                                                && !configProperty.getConfigpropertyvalue()
                                                                        .equalsIgnoreCase("")) {
                                                            method = activationSpecClass
                                                                    .getMethod("set" + property, long.class);
                                                            configPropertyLong = new Long(
                                                                    configProperty.getConfigpropertyvalue());
                                                            method.invoke(activationSpec,
                                                                    configPropertyLong.longValue());
                                                            //ConfigResourceAdapter(resourceAdapterClass,propertytype,resourceAdapter,property,configProperty);
                                                        }
                                                    } else if (propertytype == Boolean.class) {
                                                        if (configProperty.getConfigpropertyvalue() != null
                                                                && !configProperty.getConfigpropertyvalue()
                                                                        .equalsIgnoreCase("")) {
                                                            method = activationSpecClass
                                                                    .getMethod("set" + property, boolean.class);
                                                            configPropertyBoolean = new Boolean(
                                                                    configProperty.getConfigpropertyvalue());
                                                            method.invoke(activationSpec,
                                                                    configPropertyBoolean.booleanValue());
                                                            //ConfigResourceAdapter(resourceAdapterClass,propertytype,resourceAdapter,property,configProperty);
                                                        }
                                                    }
                                                    ConfigResourceAdapter(resourceAdapterClass, propertytype,
                                                            resourceAdapter, property, configProperty);
                                                } catch (Exception ex1) {
                                                    ConfigResourceAdapter(resourceAdapterClass, propertytype,
                                                            resourceAdapter, property, configProperty);
                                                }
                                                //log.error("Could not set Configuration for rar activation spec", ex);
                                            }
                                        }
                                    }
                                    for (ActivationConfigProperty activationConfig : activationConfigProp) {
                                        String property = activationConfig.propertyName();
                                        property = (property.charAt(0) + "").toUpperCase()
                                                + property.substring(1);
                                        try {
                                            method = activationSpecClass.getMethod("set" + property,
                                                    String.class);
                                            method.invoke(activationSpec, activationConfig.propertyValue());
                                        } catch (Exception ex) {
                                            try {
                                                method = activationSpecClass.getMethod("set" + property,
                                                        boolean.class);
                                                method.invoke(activationSpec,
                                                        new Boolean(activationConfig.propertyValue()));
                                            } catch (Exception ex1) {
                                                method = activationSpecClass.getMethod("set" + property,
                                                        Boolean.class);
                                                method.invoke(activationSpec,
                                                        new Boolean(activationConfig.propertyValue()));
                                            }
                                        }

                                    }
                                    final Class listenerClass = rarArchiveData.getMessagelistenertype();
                                    ClassLoader cCL = Thread.currentThread().getContextClassLoader();
                                    Thread.currentThread()
                                            .setContextClassLoader(resourceAdapter.getClass().getClassLoader());
                                    resourceAdapter
                                            .start(new com.app.server.connector.impl.BootstrapContextImpl());
                                    MessageEndPointFactoryImpl messageEndPointFactoryImpl = new MessageEndPointFactoryImpl(
                                            listenerClass, mdbBeanCls.newInstance(), jarCL);
                                    resourceAdapter.endpointActivation(messageEndPointFactoryImpl,
                                            activationSpec);
                                    Thread.currentThread().setContextClassLoader(cCL);
                                    if (mdbContext != null) {
                                        mdbContext.setResourceAdapter(resourceAdapter);
                                        mdbContext.setMessageEndPointFactory(messageEndPointFactoryImpl);
                                        mdbContext.setActivationSpec(activationSpec);
                                        mdbContexts.put(mdbContext.getMdbName(), mdbContext);
                                    }
                                    /*new Thread(){
                                       public void run(){
                                          try {
                                             resourceAdapter.endpointActivation(new com.app.server.connector.impl.MessageEndPointFactoryImpl(listenerClass, mdbBeanCls.newInstance(),raCl), activationSpec);
                                          } catch (
                                                Exception e) {
                                             // TODO Auto-generated catch block
                                             e.printStackTrace();
                                          }
                                       }
                                    }.start();*/

                                } else {
                                    for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) {
                                        if (classServicesAnnot[annotcount] instanceof MessageDriven) {
                                            MessageDriven messageDrivenAnnot = (MessageDriven) classServicesAnnot[annotcount];
                                            ActivationConfigProperty[] activationConfigProperties = messageDrivenAnnot
                                                    .activationConfig();
                                            mdbContext = new MDBContext();
                                            mdbContext.setMdbName(messageDrivenAnnot.name());
                                            for (ActivationConfigProperty activationConfigProperty : activationConfigProperties) {
                                                if (activationConfigProperty.propertyName()
                                                        .equals(MDBContext.DESTINATIONTYPE)) {
                                                    mdbContext.setDestinationType(
                                                            activationConfigProperty.propertyValue());
                                                } else if (activationConfigProperty.propertyName()
                                                        .equals(MDBContext.DESTINATION)) {
                                                    mdbContext.setDestination(
                                                            activationConfigProperty.propertyValue());
                                                } else if (activationConfigProperty.propertyName()
                                                        .equals(MDBContext.ACKNOWLEDGEMODE)) {
                                                    mdbContext.setAcknowledgeMode(
                                                            activationConfigProperty.propertyValue());
                                                }
                                            }
                                            if (mdbContext.getDestinationType().equals(Queue.class.getName())) {
                                                mdbContextOld = null;
                                                if (mdbContexts.get(mdbContext.getMdbName()) != null) {
                                                    mdbContextOld = mdbContexts.get(mdbContext.getMdbName());
                                                    if (mdbContextOld != null && mdbContext.getDestination()
                                                            .equals(mdbContextOld.getDestination())) {
                                                        throw new Exception(
                                                                "Only one MDB can listen to destination:"
                                                                        + mdbContextOld.getDestination());
                                                    }
                                                }
                                                mdbContexts.put(mdbContext.getMdbName(), mdbContext);
                                                Queue queue = (Queue) jms.lookup(mdbContext.getDestination());
                                                Connection connection = connectionFactory
                                                        .createConnection("guest", "guest");
                                                connection.start();
                                                Session session;
                                                if (mdbContext.getAcknowledgeMode() != null && mdbContext
                                                        .getAcknowledgeMode().equals("Auto-Acknowledge")) {
                                                    session = connection.createSession(false,
                                                            Session.AUTO_ACKNOWLEDGE);
                                                } else {
                                                    session = connection.createSession(false,
                                                            Session.AUTO_ACKNOWLEDGE);
                                                }
                                                MessageConsumer consumer = session.createConsumer(queue);
                                                consumer.setMessageListener(
                                                        (MessageListener) mdbBean.newInstance());
                                                mdbContext.setConnection(connection);
                                                mdbContext.setSession(session);
                                                mdbContext.setConsumer(consumer);
                                                System.out.println("Queue=" + queue);
                                            } else if (mdbContext.getDestinationType()
                                                    .equals(Topic.class.getName())) {
                                                if (mdbContexts.get(mdbContext.getMdbName()) != null) {
                                                    mdbContextOld = mdbContexts.get(mdbContext.getMdbName());
                                                    if (mdbContextOld.getConsumer() != null)
                                                        mdbContextOld.getConsumer().setMessageListener(null);
                                                    if (mdbContextOld.getSession() != null)
                                                        mdbContextOld.getSession().close();
                                                    if (mdbContextOld.getConnection() != null)
                                                        mdbContextOld.getConnection().close();
                                                }
                                                mdbContexts.put(mdbContext.getMdbName(), mdbContext);
                                                Topic topic = (Topic) jms.lookup(mdbContext.getDestination());
                                                Connection connection = connectionFactory
                                                        .createConnection("guest", "guest");
                                                connection.start();
                                                Session session;
                                                if (mdbContext.getAcknowledgeMode() != null && mdbContext
                                                        .getAcknowledgeMode().equals("Auto-Acknowledge")) {
                                                    session = connection.createSession(false,
                                                            Session.AUTO_ACKNOWLEDGE);
                                                } else {
                                                    session = connection.createSession(false,
                                                            Session.AUTO_ACKNOWLEDGE);
                                                }
                                                MessageConsumer consumer = session.createConsumer(topic);
                                                consumer.setMessageListener(
                                                        (MessageListener) mdbBean.newInstance());
                                                mdbContext.setConnection(connection);
                                                mdbContext.setSession(session);
                                                mdbContext.setConsumer(consumer);
                                                System.out.println("Topic=" + topic);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("Error : ", e);
                    // TODO Auto-generated catch block
                    //e.printStackTrace();
                }
            }
        }
        if (staticObjs != null) {
            staticObjsEjbMap.put(url.toString(), staticObjs);
        }
        this.jarsDeployed.add(url.toURI().toString());
        log.info(url.toString() + " Deployed");
    } catch (Exception ex) {
        log.error("Error in deploying the jar file: " + url, ex);
        //ex.printStackTrace();
    } finally {
        /*if(classLoader!=null){
           try {
              classLoader.close();
           } catch (Exception e) {
              log.error("error in closing the classloader", e);
              // TODO Auto-generated catch block
              //e.printStackTrace();
           }
           ClassLoaderUtil.closeClassLoader(classLoader);
        }*/
    }

}

From source file:io.crate.integrationtests.BlobHttpIntegrationTest.java

protected boolean mget(String[] uris, Header[][] headers, final String[] expectedContent) throws Throwable {
    final CountDownLatch latch = new CountDownLatch(uris.length);
    final ConcurrentHashMap<Integer, Boolean> results = new ConcurrentHashMap<>(uris.length);
    for (int i = 0; i < uris.length; i++) {
        final int indexerId = i;
        final String uri = uris[indexerId];
        final Header[] header = headers[indexerId];
        final String expected = expectedContent[indexerId];
        Thread thread = new Thread() {
            @Override/*from   w  w w.j  av a 2  s .c o m*/
            public void run() {
                try {
                    CloseableHttpResponse res = get(uri, header);
                    Integer statusCode = res.getStatusLine().getStatusCode();
                    String resultContent = EntityUtils.toString(res.getEntity());
                    if (!resultContent.equals(expected)) {
                        logger.warn(String.format(Locale.ENGLISH,
                                "incorrect response %d -- length: %d expected: %d%n", indexerId,
                                resultContent.length(), expected.length()));
                    }
                    results.put(indexerId,
                            (statusCode >= 200 && statusCode < 300 && expected.equals(resultContent)));
                } catch (Exception e) {
                    logger.warn("**** failed indexing thread {}", e, indexerId);
                } finally {
                    latch.countDown();
                }
            }
        };
        thread.start();
    }
    assertThat(latch.await(30L, TimeUnit.SECONDS), is(true));
    return Iterables.all(results.values(), new Predicate<Boolean>() {
        @Override
        public boolean apply(Boolean input) {
            return input;
        }
    });
}

From source file:be.solidx.hot.test.TestScriptExecutors.java

@SuppressWarnings("rawtypes")
private Collection<Long> multiThreadedTest(final Script script, final int max,
        final ScriptExecutor scriptExecutor) throws InterruptedException {
    final int iterations = 100;
    ExecutorService executor = Executors.newFixedThreadPool(8);
    final ConcurrentHashMap<String, Long> results = new ConcurrentHashMap<String, Long>();
    final ConcurrentHashMap<String, Long> avgs = new ConcurrentHashMap<String, Long>();
    long benchStart = System.currentTimeMillis();
    for (int i = 0; i < iterations; i++) {
        Runnable runnable = new Runnable() {
            @SuppressWarnings("unchecked")
            @Override//  ww w . j  a va 2s  . c  o  m
            public void run() {
                try {
                    long res = 0;
                    Map<String, Object> parameters = new HashMap<String, Object>();
                    parameters.put("i", new Integer(max));
                    parameters.put("n", new Integer(0));

                    //long starting = System.currentTimeMillis();
                    Object object = scriptExecutor.execute(script, parameters);
                    if (object instanceof Bindings) {
                        Bindings bindings = (Bindings) object;
                        res = (Integer) bindings.get("result");
                        bindings.clear();
                    } else if (object instanceof Double) {
                        res = Math.round((Double) object);
                    } else if (object instanceof Long) {
                        res = (long) object;
                    } else
                        res = new Long((Integer) object);
                    long end = System.currentTimeMillis() - avgs.get(this.toString());
                    results.put(UUID.randomUUID().getLeastSignificantBits() + "", res);
                    avgs.put(this.toString(), end);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        avgs.put(runnable.toString(), System.currentTimeMillis());
        executor.submit(runnable);
    }

    while (results.size() < iterations) {
        Thread.sleep(50);
    }
    //Thread.sleep(20000);
    double sum = 0;
    for (Long value : avgs.values()) {
        sum += value;
    }
    System.out.println((sum / (double) iterations) + "");
    System.out.println("==== Time needed for all requests: " + (System.currentTimeMillis() - benchStart));
    results.remove("avg");
    executor = null;
    return results.values();
}

From source file:org.apache.falcon.entity.store.ConfigurationStore.java

private void loadEntity(final EntityType type) throws FalconException {
    try {//from w w  w  . jav  a2s . com
        final ConcurrentHashMap<String, Entity> entityMap = dictionary.get(type);
        FileStatus[] files = fs.globStatus(new Path(storePath, type.name() + Path.SEPARATOR + "*"));
        if (files != null) {
            final ExecutorService service = Executors.newFixedThreadPool(100);
            for (final FileStatus file : files) {
                service.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String fileName = file.getPath().getName();
                            String encodedEntityName = fileName.substring(0, fileName.length() - 4); // drop
                            // ".xml"
                            String entityName = URLDecoder.decode(encodedEntityName, UTF_8);
                            Entity entity = restore(type, entityName);
                            entityMap.put(entityName, entity);
                        } catch (IOException | FalconException e) {
                            LOG.error("Unable to restore entity of", file);
                        }
                    }
                });
            }
            service.shutdown();
            if (service.awaitTermination(10, TimeUnit.MINUTES)) {
                LOG.info("Restored Configurations for entity type: {} ", type.name());
            } else {
                LOG.warn("Time out happened while waiting for all threads to finish while restoring entities "
                        + "for type: {}", type.name());
            }
            // Checking if all entities were loaded
            if (entityMap.size() != files.length) {
                throw new FalconException("Unable to restore configurations for entity type " + type.name());
            }
            for (Entity entity : entityMap.values()) {
                onReload(entity);
            }
        }
    } catch (IOException e) {
        throw new FalconException("Unable to restore configurations", e);
    } catch (InterruptedException e) {
        throw new FalconException(
                "Failed to restore configurations in 10 minutes for entity type " + type.name());
    }
}

From source file:org.apache.oodt.cas.catalog.struct.impl.index.DataSourceIndex.java

/**
 * {@inheritDoc}//from  w w  w.j a v  a 2  s .c  o m
 */
public List<TermBucket> getBuckets(TransactionId<?> transactionId) throws QueryServiceException {
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    try {
        ConcurrentHashMap<String, TermBucket> termBuckets = new ConcurrentHashMap<String, TermBucket>();
        conn = this.dataSource.getConnection();
        stmt = conn.createStatement();
        rs = stmt.executeQuery(
                "SELECT bucket_name,term_name,term_value FROM transaction_terms WHERE transaction_id = '"
                        + transactionId + "'");
        while (rs.next()) {
            String bucketName = rs.getString("bucket_name");
            String termName = rs.getString("term_name");
            String termValue = rs.getString("term_value");
            TermBucket bucket = termBuckets.get(bucketName);
            if (bucket == null) {
                bucket = new TermBucket(bucketName);
            }
            Term term = new Term(termName, Collections
                    .singletonList((this.useUTF8 ? URLDecoder.decode(termValue, "UTF8") : termValue)));
            bucket.addTerm(term);
            termBuckets.put(bucketName, bucket);
        }
        return new Vector<TermBucket>(termBuckets.values());
    } catch (Exception e) {
        throw new QueryServiceException(
                "Failed to get term buckets for transaction id '" + transactionId + "' : " + e.getMessage(), e);
    } finally {
        try {
            conn.close();
        } catch (Exception ignored) {
        }
        try {
            stmt.close();
        } catch (Exception ignored) {
        }
        try {
            rs.close();
        } catch (Exception ignored) {
        }
    }
}