Search in sources :

Example 36 with CopyOnWriteArrayList

use of java.util.concurrent.CopyOnWriteArrayList in project camel by apache.

the class WebsocketProducer method sendToAll.

void sendToAll(WebsocketStore store, Object message, Exchange exchange) throws Exception {
    log.debug("Sending to all {}", message);
    Collection<DefaultWebsocket> websockets = store.getAll();
    Exception exception = null;
    List<Future> futures = new CopyOnWriteArrayList<>();
    for (DefaultWebsocket websocket : websockets) {
        try {
            Future<Void> future = sendMessage(websocket, message);
            if (future != null) {
                futures.add(future);
            }
        } catch (Exception e) {
            if (exception == null) {
                exception = new WebsocketSendException("Failed to deliver message to one or more recipients.", exchange, e);
            }
        }
    }
    // check if they are all done within the timed out period
    StopWatch watch = new StopWatch();
    int timeout = endpoint.getSendTimeout();
    while (!futures.isEmpty() && watch.taken() < timeout) {
        // remove all that are done/cancelled
        for (Future future : futures) {
            if (future.isDone() || future.isCancelled()) {
                futures.remove(future);
            }
            // if there are still more then we need to wait a little bit before checking again, to avoid burning cpu cycles in the while loop
            if (!futures.isEmpty()) {
                long interval = Math.min(1000, timeout);
                log.debug("Sleeping {} millis waiting for sendToAll to complete sending with timeout {} millis", interval, timeout);
                try {
                    Thread.sleep(interval);
                } catch (InterruptedException e) {
                    handleSleepInterruptedException(e, exchange);
                }
            }
        }
    }
    if (!futures.isEmpty()) {
        exception = new WebsocketSendException("Failed to deliver message within " + endpoint.getSendTimeout() + " millis to one or more recipients.", exchange);
    }
    if (exception != null) {
        throw exception;
    }
}
Also used : IOException(java.io.IOException) StopWatch(org.apache.camel.util.StopWatch) Future(java.util.concurrent.Future) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Example 37 with CopyOnWriteArrayList

use of java.util.concurrent.CopyOnWriteArrayList in project SnapKit by reportmill.

the class WebFile method getFiles.

/**
 * Returns the directory files list.
 */
public synchronized List<WebFile> getFiles() {
    // If already set, just return
    if (_files != null)
        return _files;
    // Get response for files
    WebURL url = getURL();
    WebResponse resp = url.getResponse();
    if (resp.getCode() == WebResponse.OK)
        _exists = true;
    if (resp.getException() != null)
        throw new ResponseException(resp);
    // Get file headers
    WebSite site = getSite();
    List<FileHeader> fhdrs = resp.getFileHeaders();
    if (fhdrs == null)
        return Collections.EMPTY_LIST;
    List<WebFile> files = new ArrayList(fhdrs.size());
    for (FileHeader fhdr : fhdrs) {
        WebFile file = site.createFile(fhdr);
        file.setParent(this);
        file._exists = true;
        files.add(file);
    }
    // Sort files, put in safe array and return
    Collections.sort(files);
    files = new CopyOnWriteArrayList(files);
    return _files = files;
}
Also used : CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Example 38 with CopyOnWriteArrayList

use of java.util.concurrent.CopyOnWriteArrayList in project rt.equinox.framework by eclipse.

the class SystemBundleTests method testBundleIDLock.

public void testBundleIDLock() {
    // $NON-NLS-1$
    File config = OSGiTestsActivator.getContext().getDataFile(getName());
    Map<String, Object> configuration = new HashMap<String, Object>();
    configuration.put(EquinoxConfiguration.PROP_FILE_LIMIT, "10");
    configuration.put(Constants.FRAMEWORK_STORAGE, config.getAbsolutePath());
    final Equinox equinox = new Equinox(configuration);
    try {
        equinox.init();
    } catch (BundleException e) {
        // $NON-NLS-1$
        fail("Unexpected exception in init()", e);
    }
    // should be in the STARTING state
    // $NON-NLS-1$
    assertEquals("Wrong state for SystemBundle", Bundle.STARTING, equinox.getState());
    final BundleContext systemContext = equinox.getBundleContext();
    // $NON-NLS-1$
    assertNotNull("System context is null", systemContext);
    try {
        equinox.start();
    } catch (BundleException e) {
        // $NON-NLS-1$
        fail("Failed to start the framework", e);
    }
    // $NON-NLS-1$
    assertEquals("Wrong state for SystemBundle", Bundle.ACTIVE, equinox.getState());
    final int numBundles = 5000;
    final File[] testBundles;
    try {
        // $NON-NLS-1$
        testBundles = createBundles(new File(config, "bundles"), numBundles);
    } catch (IOException e) {
        // $NON-NLS-1$
        fail("Unexpected error creating budnles", e);
        throw new RuntimeException();
    }
    ExecutorService executor = Executors.newFixedThreadPool(50);
    final List<Throwable> errors = new CopyOnWriteArrayList<Throwable>();
    try {
        for (int i = 0; i < testBundles.length; i++) {
            final File testBundleFile = testBundles[i];
            executor.execute(new Runnable() {

                @Override
                public void run() {
                    try {
                        systemContext.installBundle("file:///" + testBundleFile.getAbsolutePath());
                    } catch (BundleException e) {
                        e.printStackTrace();
                        errors.add(e);
                    }
                }
            });
        }
    } finally {
        executor.shutdown();
        try {
            executor.awaitTermination(600, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            fail("Interrupted.", e);
        }
    }
    Assert.assertEquals("Errors found.", Collections.emptyList(), errors);
    Assert.assertEquals("Wrong number of bundles.", numBundles + 1, systemContext.getBundles().length);
    try {
        equinox.stop();
    } catch (BundleException e) {
        // $NON-NLS-1$
        fail("Unexpected erorr stopping framework", e);
    }
    try {
        equinox.waitForStop(10000);
    } catch (InterruptedException e) {
        // $NON-NLS-1$
        fail("Unexpected interrupted exception", e);
    }
    // $NON-NLS-1$
    assertEquals("Wrong state for SystemBundle", Bundle.RESOLVED, equinox.getState());
}
Also used : LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) IOException(java.io.IOException) Equinox(org.eclipse.osgi.launch.Equinox) ExecutorService(java.util.concurrent.ExecutorService) BundleException(org.osgi.framework.BundleException) File(java.io.File) BundleContext(org.osgi.framework.BundleContext) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Example 39 with CopyOnWriteArrayList

use of java.util.concurrent.CopyOnWriteArrayList in project vertx-examples by vert-x3.

the class VertxServiceIT method testThatTheServiceIsAvailable.

@Test
public void testThatTheServiceIsAvailable() throws Exception {
    for (Bundle bundle : context.getBundles()) {
        System.out.println("[" + bundle.getBundleId() + "] - " + bundle.getSymbolicName() + " - " + bundle.getVersion());
    }
    Class<?> loadClass = context.getBundle(0).loadClass("org.hsqldb.jdbcDriver");
    System.out.println("Driver: " + loadClass);
    assertNotNull(vertxService);
    assertNotNull(eventBus);
    // Wait for verticle deployment
    await(() -> {
        System.out.println(vertxService.deploymentIDs());
        return vertxService.deploymentIDs().size() >= 2;
    });
    // ==== Web Application
    // Check that the static assets has been published by the vert.x web app
    URL url = new URL("http://localhost:8081/assets/index.html");
    String page = IOUtils.toString(url.toURI(), "utf-8");
    assertNotNull(page);
    assertFalse(page.isEmpty());
    assertTrue(page.contains("Static web server"));
    url = new URL("http://localhost:8081/products");
    page = IOUtils.toString(url.toURI(), "utf-8");
    assertNotNull(page);
    assertFalse(page.isEmpty());
    assertTrue(page.contains("Egg Whisk"));
    // ==== Http Server
    url = new URL("http://localhost:8080");
    page = IOUtils.toString(url.toURI(), "utf-8");
    assertNotNull(page);
    assertFalse(page.isEmpty());
    assertTrue(page.contains("Hello from OSGi"));
    // ==== Data service (JDBC)
    assertNotNull(data);
    List<String> results = new CopyOnWriteArrayList<>();
    data.retrieve(ar -> {
        if (ar.succeeded()) {
            results.addAll(ar.result());
        }
    });
    await(() -> results.size() != 0);
    assertThat(results.size(), is(1));
    System.out.println("JDBC test results: " + results);
}
Also used : Bundle(org.osgi.framework.Bundle) URL(java.net.URL) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Test(org.junit.Test)

Example 40 with CopyOnWriteArrayList

use of java.util.concurrent.CopyOnWriteArrayList in project CloudNet by Dytanic.

the class CloudBootstrap method main.

public static synchronized void main(String[] args) throws Exception {
    ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.DISABLED);
    System.setProperty("file.encoding", "UTF-8");
    System.setProperty("java.net.preferIPv4Stack", "true");
    System.setProperty("io.netty.noPreferDirect", "true");
    System.setProperty("client.encoding.override", "UTF-8");
    System.setProperty("io.netty.maxDirectMemory", "0");
    System.setProperty("io.netty.leakDetectionLevel", "DISABLED");
    System.setProperty("io.netty.recycler.maxCapacity", "0");
    System.setProperty("io.netty.recycler.maxCapacity.default", "0");
    OptionParser optionParser = new OptionParser();
    optionParser.allowsUnrecognizedOptions();
    optionParser.acceptsAll(Arrays.asList("version", "v"));
    optionParser.acceptsAll(Arrays.asList("help", "?"));
    optionParser.acceptsAll(Arrays.asList("notifyWrappers"));
    optionParser.acceptsAll(Arrays.asList("disable-autoupdate"));
    optionParser.accepts("debug");
    optionParser.accepts("noconsole");
    optionParser.accepts("ssl");
    optionParser.accepts("systemTimer");
    optionParser.accepts("disable-statistics");
    optionParser.accepts("disable-modules");
    optionParser.accepts("installWrapper");
    optionParser.accepts("onlyConsole");
    OptionSet optionSet = optionParser.parse(args);
    List<String> consolePreInit = new CopyOnWriteArrayList<>();
    if (optionSet.has("help") || optionSet.has("?")) {
        HelpService helpService = new HelpService();
        helpService.getDescriptions().put("help", new ServiceDescription[] { new ServiceDescription("--help | --?", "This is the main argument to get all information about other parameters") });
        helpService.getDescriptions().put("ssl", new ServiceDescription[] { new ServiceDescription("--ssl", "Allows SSL encryption via a system-contained certificate or an open SSL certificate") });
        helpService.getDescriptions().put("debug", new ServiceDescription[] { new ServiceDescription("--debug", "Enables the debug mode, for extra consoles issues with more information, nothing is for people with interest in alto many consoles issues") });
        helpService.getDescriptions().put("noconsole", new ServiceDescription[] { new ServiceDescription("--noconsole", "Disables the console, for the rest of the service run time") });
        helpService.getDescriptions().put("notifyWrappers", new ServiceDescription[] { new ServiceDescription("--notifyWrappers", "Unites all the consoles that issued all wrapper instances to the master instance") });
        helpService.getDescriptions().put("disable-autoupdate", new ServiceDescription[] { new ServiceDescription("--disable-autoupdate", "Disabled the autoupdate function of cloudnet 2") });
        helpService.getDescriptions().put("version", new ServiceDescription[] { new ServiceDescription("--version | --v", "Displays the current version of CloudNet used") });
        helpService.getDescriptions().put("systemTimer", new ServiceDescription[] { new ServiceDescription("--systemTimer", "Time all informations of this instance into a custom log file") });
        helpService.getDescriptions().put("disable-statistics", new ServiceDescription[] { new ServiceDescription("--disable-statistics", "Disables the statistic service from cloudnet") });
        helpService.getDescriptions().put("disable-modules", new ServiceDescription[] { new ServiceDescription("--disable-modules", "Modules doesn't working in the \"/modules\" directory") });
        helpService.getDescriptions().put("installWrapper", new ServiceDescription[] { new ServiceDescription("--installWrapper", "Install a local wrapper automatic") });
        System.out.println(helpService.toString());
        return;
    }
    if (optionSet.has("systemTimer"))
        new SystemTimer();
    if (optionSet.has("version")) {
        System.out.println("CloudNet-Core RezSyM Version " + CloudBootstrap.class.getPackage().getImplementationVersion() + "-" + CloudBootstrap.class.getPackage().getSpecificationVersion());
        return;
    }
    CloudLogger cloudNetLogging = new CloudLogger();
    if (optionSet.has("debug"))
        cloudNetLogging.setDebugging(true);
    cloudNetLogging.getHandler().add(new ICloudLoggerHandler() {

        @Override
        public void handleConsole(String input) {
            if (!CloudNet.RUNNING)
                consolePreInit.add(input);
        }
    });
    new HeaderFunction();
    CloudConfig coreConfig = new CloudConfig(cloudNetLogging.getReader());
    CloudNet cloudNetCore = new CloudNet(coreConfig, cloudNetLogging, optionSet, consolePreInit, Arrays.asList(args));
    if (!cloudNetCore.bootstrap())
        System.exit(0);
    if (!optionSet.has("noconsole")) {
        System.out.println("Use the command \"help\" for further information!");
        String commandLine;
        try {
            while (true) while ((commandLine = cloudNetLogging.getReader().readLine()) != null && CloudNet.RUNNING) {
                String dispatcher = cloudNetCore.getDbHandlers().getCommandDispatcherDatabase().findDispatcher(commandLine);
                if (dispatcher != null) {
                    try {
                        if (!cloudNetCore.getCommandManager().dispatchCommand(dispatcher)) {
                            continue;
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
                if (!cloudNetCore.getCommandManager().dispatchCommand(commandLine)) {
                    System.out.println("Command not found. Use the command \"help\" for further information!");
                }
            }
        } catch (Exception ex) {
        }
    } else {
        while (true) NetworkUtils.sleepUninterruptedly(Long.MAX_VALUE);
    }
}
Also used : ServiceDescription(de.dytanic.cloudnet.help.ServiceDescription) CloudConfig(de.dytanic.cloudnetcore.CloudConfig) OptionParser(joptsimple.OptionParser) ICloudLoggerHandler(de.dytanic.cloudnet.logging.handler.ICloudLoggerHandler) HeaderFunction(de.dytanic.cloudnet.logging.util.HeaderFunction) CloudNet(de.dytanic.cloudnetcore.CloudNet) OptionSet(joptsimple.OptionSet) CloudLogger(de.dytanic.cloudnet.logging.CloudLogger) HelpService(de.dytanic.cloudnet.help.HelpService) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) SystemTimer(de.dytanic.cloudnet.lib.SystemTimer)

Aggregations

CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)304 CountDownLatch (java.util.concurrent.CountDownLatch)84 ArrayList (java.util.ArrayList)83 List (java.util.List)76 Test (org.junit.Test)71 IOException (java.io.IOException)53 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)32 HashMap (java.util.HashMap)24 Map (java.util.Map)24 ExecutionException (java.util.concurrent.ExecutionException)23 LinkedList (java.util.LinkedList)21 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)19 Set (java.util.Set)18 TimeUnit (java.util.concurrent.TimeUnit)18 ClientRequest (io.undertow.client.ClientRequest)17 Test (org.junit.jupiter.api.Test)17 HashSet (java.util.HashSet)16 ExecutorService (java.util.concurrent.ExecutorService)16 DiscoveryNode (org.elasticsearch.cluster.node.DiscoveryNode)16 ClientConnection (io.undertow.client.ClientConnection)15