Example usage for java.util.concurrent CopyOnWriteArrayList CopyOnWriteArrayList

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

Introduction

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

Prototype

public CopyOnWriteArrayList() 

Source Link

Document

Creates an empty list.

Usage

From source file:com.shipdream.lib.android.mvc.MvcFragment.java

/**
 * Register a callback after {@link #onViewReady(View, Bundle, Reason)} is called. This is useful when an action that
 * can't be executed after the fragment is instantiated but before the fragment has gone through
 * life cycles and gets created and ready to use. If this is one time action, use
 * {@link #unregisterOnViewReadyListener(Runnable)} (Runnable)}  unregister itself in the given onCreateViewAction.
 *
 * @param action The action to registered to be run after view is ready
 *//*  w ww . j  a  v a  2  s .c o  m*/
public void registerOnViewReadyListener(Runnable action) {
    if (onViewReadyListeners == null) {
        onViewReadyListeners = new CopyOnWriteArrayList<>();
    }
    onViewReadyListeners.add(action);
}

From source file:org.exoplatform.services.jcr.ext.backup.impl.BackupManagerImpl.java

/**
 * BackupManagerImpl  constructor./*from  w  ww .j  a va2  s . c om*/
 *
 *          InitParams,  the init parameters
 * @param repoService
 *          RepositoryService, the repository service
 * @param registryService
 *          RegistryService, the registry service
 */
public BackupManagerImpl(ExoContainerContext ctx, InitParams initParams, RepositoryService repoService,
        RegistryService registryService) {
    this.messagesListener = new MessagesListener();
    this.repoService = repoService;
    this.registryService = registryService;
    this.initParams = initParams;
    this.tempDir = new File(PrivilegedSystemHelper.getProperty("java.io.tmpdir"));

    currentBackups = Collections.synchronizedSet(new HashSet<BackupChain>());

    currentRepositoryBackups = Collections.synchronizedSet(new HashSet<RepositoryBackupChain>());

    messages = new BackupMessagesLog(MESSAGES_MAXSIZE);

    this.restoreJobs = new ArrayList<JobWorkspaceRestore>();
    this.restoreRepositoryJobs = new CopyOnWriteArrayList<JobRepositoryRestore>();

    this.workspaceBackupStopper = new WorkspaceBackupAutoStopper(ctx);

    this.repositoryBackupStopper = new RepositoryBackupAutoStopper(ctx);
}

From source file:org.apache.ranger.biz.SessionMgr.java

public CopyOnWriteArrayList<UserSessionBase> getActiveSessionsOnServer() {

    CopyOnWriteArrayList<HttpSession> activeHttpUserSessions = RangerHttpSessionListener
            .getActiveSessionOnServer();
    CopyOnWriteArrayList<UserSessionBase> activeRangerUserSessions = new CopyOnWriteArrayList<UserSessionBase>();

    if (CollectionUtils.isEmpty(activeHttpUserSessions)) {
        return activeRangerUserSessions;
    }/* w w  w .  j  a v  a  2 s  . co m*/

    for (HttpSession httpSession : activeHttpUserSessions) {

        if (httpSession.getAttribute(RangerSecurityContextFormationFilter.AKA_SC_SESSION_KEY) == null) {
            continue;
        }

        RangerSecurityContext securityContext = (RangerSecurityContext) httpSession
                .getAttribute(RangerSecurityContextFormationFilter.AKA_SC_SESSION_KEY);
        if (securityContext.getUserSession() != null) {
            activeRangerUserSessions.add(securityContext.getUserSession());
        }
    }

    return activeRangerUserSessions;
}

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

/**
 * Write leaf meta data to File./*w  w w.  j  a  v  a  2s  .co m*/
 *
 * @throws CarbonDataWriterException
 */
public void writeleafMetaDataToFile() throws CarbonDataWriterException {
    if (!isNodeHolderRequired) {
        writeleafMetaDataToFile(this.blockletInfoList, fileChannel, fileName);
        this.blockletInfoList = new ArrayList<BlockletInfoColumnar>(CarbonCommonConstants.CONSTANT_SIZE_TEN);
    } else {
        if (this.nodeHolderList.size() > 0) {
            List<NodeHolder> localNodeHodlerList = nodeHolderList;
            writeData(fileChannel, localNodeHodlerList, fileName);
            nodeHolderList = new CopyOnWriteArrayList<NodeHolder>();
        }
    }
}

From source file:com.google.bitcoin.core.Wallet.java

/**
 * Creates a new, empty wallet with no keys and no transactions. If you want to restore a wallet from disk instead,
 * see loadFromFile.//w  w  w  . jav  a 2s.com
 */
public Wallet(NetworkParameters params) {
    this.params = checkNotNull(params);
    keychain = new ArrayList<ECKey>();
    watchedScripts = Sets.newHashSet();
    unspent = new HashMap<Sha256Hash, Transaction>();
    spent = new HashMap<Sha256Hash, Transaction>();
    pending = new HashMap<Sha256Hash, Transaction>();
    dead = new HashMap<Sha256Hash, Transaction>();
    transactions = new HashMap<Sha256Hash, Transaction>();
    eventListeners = new CopyOnWriteArrayList<ListenerRegistration<WalletEventListener>>();
    extensions = new HashMap<String, WalletExtension>();

    /* CSPK-mike START */
    // CoinSpark object initialization.
    CS = new CoinSpark(this);
    /* CSPK-mike END */

    if (keyCrypter != null) {
        // If the wallet is encrypted, add a wallet protect extension.
        MultiBitWalletExtension multibitWalletExtension = new MultiBitWalletExtension();
        extensions.put(multibitWalletExtension.getWalletExtensionID(), multibitWalletExtension);

        // The wallet version indicates the wallet is encrypted.
        setVersion(MultiBitWalletVersion.PROTOBUF_ENCRYPTED);
    } else {
        // The wallet version indicates the wallet is unencrypted.
        setVersion(MultiBitWalletVersion.PROTOBUF);
    }
    confidenceChanged = new HashMap<Transaction, TransactionConfidence.Listener.ChangeReason>();
    createTransientState();
}

From source file:codeswarm.code_swarm.java

/**
 * TODO This could be made to look a lot better.
 *//*from   w ww .j  ava  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:org.restcomm.connect.http.CallsEndpoint.java

@SuppressWarnings("unchecked")
protected Response putCall(final String accountSid, final MultivaluedMap<String, String> data,
        final MediaType responseType) {
    final Sid accountId;
    try {//  w  w w .j  ava  2  s . co  m
        accountId = new Sid(accountSid);
    } catch (final IllegalArgumentException exception) {
        return status(INTERNAL_SERVER_ERROR)
                .entity(buildErrorResponseBody(exception.getMessage(), responseType)).build();
    }
    secure(daos.getAccountsDao().getAccount(accountSid), "RestComm:Create:Calls");
    try {
        validate(data);
        if (normalizePhoneNumbers)
            normalize(data);
    } catch (final RuntimeException exception) {
        return status(BAD_REQUEST).entity(exception.getMessage()).build();
    }

    URI statusCallback = null;
    String statusCallbackMethod = "POST";
    List<String> statusCallbackEvent = new ArrayList<String>();
    statusCallbackEvent.add("initiated");
    statusCallbackEvent.add("ringing");
    statusCallbackEvent.add("answered");
    statusCallbackEvent.add("completed");

    final String from = data.getFirst("From").trim();
    final String to = data.getFirst("To").trim();
    final String username = data.getFirst("Username");
    final String password = data.getFirst("Password");
    final Integer timeout = getTimeout(data);
    final Timeout expires = new Timeout(Duration.create(60, TimeUnit.SECONDS));
    final URI rcmlUrl = getUrl("Url", data);

    try {
        if (data.containsKey("StatusCallback")) {
            statusCallback = new URI(data.getFirst("StatusCallback").trim());
        }
    } catch (Exception e) {
        //Handle Exception
    }

    if (statusCallback != null) {
        if (data.containsKey("StatusCallbackMethod")) {
            statusCallbackMethod = data.getFirst("StatusCallbackMethod").trim();
        }
        if (data.containsKey("StatusCallbackEvent")) {
            statusCallbackEvent = Arrays.asList(data.getFirst("StatusCallbackEvent").trim().split(","));
        }
    }

    CreateCall create = null;
    try {
        if (to.contains("@")) {
            create = new CreateCall(from, to, username, password, true, timeout != null ? timeout : 30,
                    CreateCallType.SIP, accountId, null, statusCallback, statusCallbackMethod,
                    statusCallbackEvent);
        } else if (to.startsWith("client")) {
            create = new CreateCall(from, to, username, password, true, timeout != null ? timeout : 30,
                    CreateCallType.CLIENT, accountId, null, statusCallback, statusCallbackMethod,
                    statusCallbackEvent);
        } else {
            create = new CreateCall(from, to, username, password, true, timeout != null ? timeout : 30,
                    CreateCallType.PSTN, accountId, null, statusCallback, statusCallbackMethod,
                    statusCallbackEvent);
        }
        create.setCreateCDR(false);
        if (callManager == null)
            callManager = (ActorRef) context.getAttribute("org.restcomm.connect.telephony.CallManager");
        Future<Object> future = (Future<Object>) ask(callManager, create, expires);
        Object object = Await.result(future, Duration.create(10, TimeUnit.SECONDS));
        Class<?> klass = object.getClass();
        if (CallManagerResponse.class.equals(klass)) {
            final CallManagerResponse<ActorRef> managerResponse = (CallManagerResponse<ActorRef>) object;
            if (managerResponse.succeeded()) {
                List<ActorRef> dialBranches;
                if (managerResponse.get() instanceof List) {
                    dialBranches = (List<ActorRef>) managerResponse.get();
                } else {
                    dialBranches = new CopyOnWriteArrayList<ActorRef>();
                    dialBranches.add(managerResponse.get());
                }
                List<CallDetailRecord> cdrs = new CopyOnWriteArrayList<CallDetailRecord>();
                for (ActorRef call : dialBranches) {
                    future = (Future<Object>) ask(call, new GetCallInfo(), expires);
                    object = Await.result(future, Duration.create(10, TimeUnit.SECONDS));
                    klass = object.getClass();
                    if (CallResponse.class.equals(klass)) {
                        final CallResponse<CallInfo> callResponse = (CallResponse<CallInfo>) object;
                        if (callResponse.succeeded()) {
                            final CallInfo callInfo = callResponse.get();
                            // Execute the call script.
                            final String version = getApiVersion(data);
                            final URI url = rcmlUrl;
                            final String method = getMethod("Method", data);
                            final URI fallbackUrl = getUrl("FallbackUrl", data);
                            final String fallbackMethod = getMethod("FallbackMethod", data);
                            final ExecuteCallScript execute = new ExecuteCallScript(call, accountId, version,
                                    url, method, fallbackUrl, fallbackMethod);
                            callManager.tell(execute, null);
                            cdrs.add(daos.getCallDetailRecordsDao().getCallDetailRecord(callInfo.sid()));
                        }
                    }
                }
                if (APPLICATION_XML_TYPE == responseType) {
                    if (cdrs.size() == 1) {
                        return ok(xstream.toXML(cdrs.get(0)), APPLICATION_XML).build();
                    } else {
                        final RestCommResponse response = new RestCommResponse(new CallDetailRecordList(cdrs));
                        return ok(xstream.toXML(response), APPLICATION_XML).build();
                    }
                } else if (APPLICATION_JSON_TYPE == responseType) {
                    if (cdrs.size() == 1) {
                        return ok(gson.toJson(cdrs.get(0)), APPLICATION_JSON).build();
                    } else {
                        return ok(gson.toJson(cdrs), APPLICATION_JSON).build();
                    }
                } else {
                    return null;
                }
                //                    if (APPLICATION_JSON_TYPE == responseType) {
                //                        return ok(gson.toJson(cdrs), APPLICATION_JSON).build();
                //                    } else if (APPLICATION_XML_TYPE == responseType) {
                //                        return ok(xstream.toXML(new RestCommResponse(cdrs)), APPLICATION_XML).build();
                //                    } else {
                //                        return null;
                //                    }
            } else {
                return status(INTERNAL_SERVER_ERROR).entity(managerResponse.cause().getMessage()).build();
            }
        }
        return status(INTERNAL_SERVER_ERROR).build();
    } catch (final Exception exception) {
        return status(INTERNAL_SERVER_ERROR).entity(exception.getMessage()).build();
    }
}

From source file:org.apache.sshd.common.forward.PortForwardingLoadTest.java

@Test
public void testForwardingOnLoad() throws Exception {
    //        final String path = "/history/recent/troubles/";
    //        final String host = "www.bbc.co.uk";
    //        final String path = "";
    //        final String host = "www.bahn.de";
    final String path = "";
    final String host = TEST_LOCALHOST;
    final int nbThread = 2;
    final int nbDownloads = 2;
    final int nbLoops = 2;

    StringBuilder resp = new StringBuilder();
    resp.append("<html><body>\n");
    for (int i = 0; i < 1000; i++) {
        resp.append("0123456789\n");
    }/*w  w w  .  jav a 2 s. co m*/
    resp.append("</body></html>\n");
    final StringBuilder sb = new StringBuilder();
    sb.append("HTTP/1.1 200 OK").append('\n');
    sb.append("Content-Type: text/HTML").append('\n');
    sb.append("Content-Length: ").append(resp.length()).append('\n');
    sb.append('\n');
    sb.append(resp);
    NioSocketAcceptor acceptor = new NioSocketAcceptor();
    acceptor.setHandler(new IoHandlerAdapter() {
        @Override
        public void messageReceived(IoSession session, Object message) throws Exception {
            session.write(IoBuffer.wrap(sb.toString().getBytes(StandardCharsets.UTF_8)));
        }
    });
    acceptor.setReuseAddress(true);
    acceptor.bind(new InetSocketAddress(0));
    final int port = acceptor.getLocalAddress().getPort();

    Session session = createSession();
    try {
        final int forwardedPort1 = session.setPortForwardingL(0, host, port);
        final int forwardedPort2 = Utils.getFreePort();
        session.setPortForwardingR(forwardedPort2, TEST_LOCALHOST, forwardedPort1);
        outputDebugMessage("URL: http://localhost %s", forwardedPort2);

        final CountDownLatch latch = new CountDownLatch(nbThread * nbDownloads * nbLoops);
        final Thread[] threads = new Thread[nbThread];
        final List<Throwable> errors = new CopyOnWriteArrayList<>();
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(getCurrentTestName() + "[" + i + "]") {
                @Override
                public void run() {
                    for (int j = 0; j < nbLoops; j++) {
                        final MultiThreadedHttpConnectionManager mgr = new MultiThreadedHttpConnectionManager();
                        final HttpClient client = new HttpClient(mgr);
                        client.getHttpConnectionManager().getParams().setDefaultMaxConnectionsPerHost(100);
                        client.getHttpConnectionManager().getParams().setMaxTotalConnections(1000);
                        for (int i = 0; i < nbDownloads; i++) {
                            try {
                                checkHtmlPage(client, new URL("http://localhost:" + forwardedPort2 + path));
                            } catch (Throwable e) {
                                errors.add(e);
                            } finally {
                                latch.countDown();
                                System.err.println("Remaining: " + latch.getCount());
                            }
                        }
                        mgr.shutdown();
                    }
                }
            };
        }
        for (Thread thread : threads) {
            thread.start();
        }
        latch.await();
        for (Throwable t : errors) {
            t.printStackTrace();
        }
        assertEquals(0, errors.size());
    } finally {
        session.disconnect();
    }
}

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

public ServiceResponse<KieContainerResource> activateContainer(String containerId) {

    List<Message> messages = new CopyOnWriteArrayList<Message>();
    try {/*from  w w  w  .jav a 2s .  c om*/
        KieContainerInstanceImpl kci = context.getContainer(containerId);
        if (kci != null && kci.getStatus().equals(KieContainerStatus.DEACTIVATED)) {

            synchronized (kci) {
                eventSupport.fireBeforeContainerActivated(this, kci);

                Map<String, Object> parameters = getContainerParameters(
                        kci.getKieContainer().getContainerReleaseId(), messages);
                // process server extensions
                List<KieServerExtension> extensions = context.getServerExtensions();
                for (KieServerExtension extension : extensions) {
                    extension.activateContainer(containerId, kci, parameters);
                    logger.debug("Container {} (for release id {}) {} activation: DONE", containerId,
                            kci.getKieContainer().getContainerReleaseId(), extension);
                }

                kci.setStatus(KieContainerStatus.STARTED);

                // store the current state of the server
                storeServerState(currentState -> {
                    currentState.getContainers().forEach(containerResource -> {
                        if (containerId.equals(containerResource.getContainerId())) {
                            containerResource.setStatus(KieContainerStatus.STARTED);
                        }
                    });
                });

                eventSupport.fireAfterContainerActivated(this, kci);

                messages.add(
                        new Message(Severity.INFO, "Container " + containerId + " activated successfully."));
                return new ServiceResponse<KieContainerResource>(ServiceResponse.ResponseType.SUCCESS,
                        "Container " + containerId + " activated successfully.", kci.getResource());
            }
        } else {
            messages.add(new Message(Severity.ERROR,
                    "Container " + containerId + " not found or not in deactivated status."));
            return new ServiceResponse<KieContainerResource>(ServiceResponse.ResponseType.FAILURE,
                    "Container " + containerId + " not found or not in deactivated status.");
        }
    } catch (Exception e) {
        messages.add(new Message(Severity.ERROR,
                "Error activating container '" + containerId + "' due to " + e.getMessage()));
        logger.error("Error activating Container '" + containerId + "'", e);
        return new ServiceResponse<KieContainerResource>(ServiceResponse.ResponseType.FAILURE,
                "Error activating container " + containerId + ": " + e.getClass().getName() + ": "
                        + e.getMessage());
    } finally {
        this.containerMessages.put(containerId, messages);
    }
}

From source file:org.pentaho.di.trans.step.BaseStep.java

/**
 * This is the base step that forms that basis for all steps. You can derive from this class to implement your own
 * steps./*from   w w  w. j  a  v a2s  . c  o  m*/
 *
 * @param stepMeta          The StepMeta object to run.
 * @param stepDataInterface the data object to store temporary data, database connections, caches, result sets,
 *                          hashtables etc.
 * @param copyNr            The copynumber for this step.
 * @param transMeta         The TransInfo of which the step stepMeta is part of.
 * @param trans             The (running) transformation to obtain information shared among the steps.
 */
public BaseStep(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta,
        Trans trans) {
    this.stepMeta = stepMeta;
    this.stepDataInterface = stepDataInterface;
    this.stepcopy = copyNr;
    this.transMeta = transMeta;
    this.trans = trans;
    this.stepname = stepMeta.getName();
    this.socketRepository = trans.getSocketRepository();

    // Set the name of the thread
    if (stepMeta.getName() == null) {
        throw new RuntimeException("A step in transformation [" + transMeta.toString()
                + "] doesn't have a name.  A step should always have a name to identify it by.");
    }

    log = KettleLogStore.getLogChannelInterfaceFactory().create(this, trans);

    first = true;
    clusteredPartitioningFirst = true;

    running = new AtomicBoolean(false);
    stopped = new AtomicBoolean(false);
    safeStopped = new AtomicBoolean(false);
    paused = new AtomicBoolean(false);

    init = false;

    synchronized (statusCountersLock) {
        linesRead = 0L; // new AtomicLong(0L); // Keep some statistics!
        linesWritten = 0L; // new AtomicLong(0L);
        linesUpdated = 0L; // new AtomicLong(0L);
        linesSkipped = 0L; // new AtomicLong(0L);
        linesRejected = 0L; // new AtomicLong(0L);
        linesInput = 0L; // new AtomicLong(0L);
        linesOutput = 0L; // new AtomicLong(0L);
    }

    inputRowSets = null;
    outputRowSets = null;
    nextSteps = null;

    terminator = stepMeta.hasTerminator();
    if (terminator) {
        terminator_rows = new ArrayList<Object[]>();
    } else {
        terminator_rows = null;
    }

    // debug="-";

    start_time = null;
    stop_time = null;

    distributed = stepMeta.isDistributes();
    rowDistribution = stepMeta.getRowDistribution();

    if (distributed) {
        if (rowDistribution != null) {
            if (log.isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "BaseStep.Log.CustomRowDistributionActivated",
                        rowDistributionCode));
            }
        } else {
            if (log.isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "BaseStep.Log.DistributionActivated"));
            }
        }
    } else {
        if (log.isDetailed()) {
            logDetailed(BaseMessages.getString(PKG, "BaseStep.Log.DistributionDeactivated"));
        }
    }

    rowListeners = new CopyOnWriteArrayList<RowListener>();
    resultFiles = new HashMap<String, ResultFile>();
    resultFilesLock = new ReentrantReadWriteLock();

    repartitioning = StepPartitioningMeta.PARTITIONING_METHOD_NONE;
    partitionTargets = new Hashtable<String, BlockingRowSet>();

    serverSockets = new ArrayList<ServerSocket>();

    extensionDataMap = new HashMap<String, Object>();

    // tuning parameters
    // putTimeOut = 10; //s
    // getTimeOut = 500; //s
    // timeUnit = TimeUnit.MILLISECONDS;
    // the smaller singleWaitTime, the faster the program run but cost CPU
    // singleWaitTime = 1; //ms
    // maxPutWaitCount = putTimeOut*1000/singleWaitTime;
    // maxGetWaitCount = getTimeOut*1000/singleWaitTime;

    // worker = Executors.newFixedThreadPool(10);
    checkTransRunning = false;

    blockPointer = 0;

    stepListeners = Collections.synchronizedList(new ArrayList<StepListener>());

    dispatch();

    upperBufferBoundary = (int) (transMeta.getSizeRowset() * 0.99);
    lowerBufferBoundary = (int) (transMeta.getSizeRowset() * 0.01);
}