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:uk.ac.ebi.intact.editor.services.curate.cvobject.CvObjectService.java

public List<SelectItem> createSelectItems(Collection<IntactCvTerm> cvObjects, String noSelectionText) {
    List<SelectItem> selectItems = new CopyOnWriteArrayList<SelectItem>();

    if (noSelectionText != null) {
        selectItems.add(new SelectItem(null, noSelectionText, noSelectionText, false, false, true));
    }/*from  w  w  w  .j a  v a  2  s  . co m*/

    for (IntactCvTerm cvObject : cvObjects) {
        selectItems.add(createSelectItem(cvObject));
    }

    return selectItems;
}

From source file:uk.ac.ebi.intact.editor.services.curate.cvobject.CvObjectService.java

public List<SelectItem> createSelectItems(Collection<IntactCvTerm> cvObjects, String noSelectionText,
        String idPrefixToIgnore) {
    List<SelectItem> selectItems = new CopyOnWriteArrayList<SelectItem>();

    if (noSelectionText != null) {
        selectItems.add(new SelectItem(null, noSelectionText, noSelectionText, false, false, true));
    }/*w  w  w . j a v a 2s  . c o  m*/

    for (IntactCvTerm cvObject : cvObjects) {
        boolean ignore = false;
        if (!cvObject.getIdentifiers().isEmpty()) {
            for (Xref ref : cvObject.getIdentifiers()) {
                if (ref.getId().startsWith(idPrefixToIgnore)) {
                    ignore = true;
                }
            }
        }
        if (!ignore) {
            selectItems.add(createSelectItem(cvObject));

        }
    }

    return selectItems;
}

From source file:com.l2jfree.gameserver.model.entity.events.TvT.java

public static boolean addPlayerOk(String teamName, L2Player eventPlayer) {
    if (GlobalRestrictions.isRestricted(eventPlayer, TvTRestriction.class)) {
        // TODO: msg
        return false;
    }/* ww w.  j  av a2  s . c om*/

    try {
        if (checkShufflePlayers(eventPlayer) || eventPlayer.isInEvent(TvTPlayerInfo.class)) {
            eventPlayer.sendMessage("You are already participating in the event!");
            return false;
        }

        for (L2Player player : _players) {
            if (player.getObjectId() == eventPlayer.getObjectId()) {
                eventPlayer.sendMessage("You are already participating in the event!");
                return false;
            } else if (player.getName() == eventPlayer.getName()) {
                eventPlayer.sendMessage("You are already participating in the event!");
                return false;
            }
        }
        if (_players.contains(eventPlayer)) {
            eventPlayer.sendMessage("You are already participating in the event!");
            return false;
        }
        if (CTF._savePlayers.contains(eventPlayer.getName())) {
            eventPlayer.sendMessage("You are already participating in another event!");
            return false;
        }
    } catch (Exception e) {
        _log.warn("TvT Engine exception: ", e);
    }

    if (Config.TVT_EVEN_TEAMS.equals("NO"))
        return true;
    else if (Config.TVT_EVEN_TEAMS.equals("BALANCE")) {
        boolean allTeamsEqual = true;
        int countBefore = -1;

        for (int playersCount : _teamPlayersCount) {
            if (countBefore == -1)
                countBefore = playersCount;

            if (countBefore != playersCount) {
                allTeamsEqual = false;
                break;
            }

            countBefore = playersCount;
        }

        if (allTeamsEqual)
            return true;

        countBefore = Integer.MAX_VALUE;

        for (int teamPlayerCount : _teamPlayersCount) {
            if (teamPlayerCount < countBefore)
                countBefore = teamPlayerCount;
        }

        CopyOnWriteArrayList<String> joinableTeams = new CopyOnWriteArrayList<String>();

        for (String team : _teams) {
            if (teamPlayersCount(team) == countBefore)
                joinableTeams.add(team);
        }

        if (joinableTeams.contains(teamName))
            return true;
    } else if (Config.TVT_EVEN_TEAMS.equals("SHUFFLE"))
        return true;

    eventPlayer.sendMessage("Too many players in team \"" + teamName + "\"");
    return false;
}

From source file:org.mobicents.servlet.restcomm.telephony.CallManager.java

private void outboundToClient(final CreateCall request, final ActorRef sender) throws ServletParseException {
    SipURI outboundIntf = null;//w w  w.j  ava2s.c om
    SipURI from = null;
    SipURI to = null;
    boolean webRTC = false;
    boolean isLBPresent = false;

    final RegistrationsDao registrationsDao = storage.getRegistrationsDao();
    final String client = request.to().replaceFirst("client:", "");

    //1, If this is a WebRTC client check if the instance is the current instance
    //2. Check if the client has more than one registrations

    List<Registration> registrationToDial = new CopyOnWriteArrayList<Registration>();

    List<Registration> registrations = registrationsDao.getRegistrations(client);
    if (registrations != null && registrations.size() > 0) {
        if (logger.isInfoEnabled()) {
            logger.info("Preparing call for client: " + client + ". There are " + registrations.size()
                    + " registrations at the database for this client");
        }
        for (Registration registration : registrations) {
            if (registration.isWebRTC()) {
                if (registration.isLBPresent()) {
                    if (logger.isInfoEnabled())
                        logger.info("WebRTC registration behind LB. Will add WebRTC registration: "
                                + registration.getLocation() + " to the list to be dialed for client: "
                                + client);
                    registrationToDial.add(registration);
                } else {
                    //If this is a WebRTC client registration, check that the InstanceId of the registration is for the current Restcomm instance
                    if ((registration.getInstanceId() != null && !registration.getInstanceId()
                            .equals(RestcommConfiguration.getInstance().getMain().getInstanceId()))) {
                        logger.warning("Cannot create call for user agent: " + registration.getLocation()
                                + " since this is a webrtc client registered in another Restcomm instance.");
                    } else {
                        if (logger.isInfoEnabled())
                            logger.info("Will add WebRTC registration: " + registration.getLocation()
                                    + " to the list to be dialed for client: " + client);
                        registrationToDial.add(registration);
                    }
                }
            } else {
                if (logger.isInfoEnabled())
                    logger.info("Will add registration: " + registration.getLocation()
                            + " to the list to be dialed for client: " + client);
                registrationToDial.add(registration);
            }
        }
    } else {
        String errMsg = "The SIP Client " + request.to() + " is not registered or does not exist";
        logger.error(errMsg);
        sendNotification(errMsg, 11008, "error", true);
        sender.tell(new CallManagerResponse<ActorRef>(new NullPointerException(errMsg), this.createCallRequest),
                self());
        return;
    }

    if (registrationToDial.size() > 0) {
        if (logger.isInfoEnabled()) {
            if (registrationToDial.size() > 1) {
                logger.info(
                        "Preparing call for client: " + client + ", after WebRTC check, Restcomm have to dial :"
                                + registrationToDial.size() + " registrations");
            }
        }
        List<ActorRef> calls = new CopyOnWriteArrayList<>();
        for (Registration registration : registrationToDial) {
            if (logger.isInfoEnabled())
                logger.info("Will proceed to create call for client: " + registration.getLocation()
                        + " registration instanceId: " + registration.getInstanceId() + " own InstanceId: "
                        + RestcommConfiguration.getInstance().getMain().getInstanceId());
            String transport;
            if (registration.getLocation().contains("transport")) {
                transport = registration.getLocation().split(";")[1].replace("transport=", "");
                outboundIntf = outboundInterface(transport);
            } else {
                transport = "udp";
                outboundIntf = outboundInterface(transport);
            }
            if (outboundIntf == null) {
                String errMsg = "The outbound interface for transport: " + transport
                        + " is NULL, something is wrong with container, cannot proceed to call client "
                        + request.to();
                logger.error(errMsg);
                sendNotification(errMsg, 11008, "error", true);
                sender.tell(new CallManagerResponse<ActorRef>(new NullPointerException(errMsg),
                        this.createCallRequest), self());
                return;
            }
            if (request.from() != null && request.from().contains("@")) {
                // https://github.com/Mobicents/RestComm/issues/150 if it contains @ it means this is a sip uri and we allow
                // to use it directly
                from = (SipURI) sipFactory.createURI(request.from());
            } else if (request.from() != null) {
                if (outboundIntf != null) {
                    from = sipFactory.createSipURI(request.from(),
                            mediaExternalIp + ":" + outboundIntf.getPort());
                } else {
                    logger.error(
                            "Outbound interface is null, cannot create From header to be used to Dial client: "
                                    + client);
                }
            } else {
                from = outboundIntf;
            }
            final String location = registration.getLocation();
            to = (SipURI) sipFactory.createURI(location);
            webRTC = registration.isWebRTC();
            if (from == null || to == null) {
                //In case From or To are null we have to cancel outbound call and hnagup initial call if needed
                final String errMsg = "From and/or To are null, we cannot proceed to the outbound call to: "
                        + request.to();
                logger.error(errMsg);
                sender.tell(new CallManagerResponse<ActorRef>(new NullPointerException(errMsg),
                        this.createCallRequest), self());
            } else {
                calls.add(createOutbound(request, from, to, webRTC));
            }
        }
        if (calls.size() > 0) {
            sender.tell(new CallManagerResponse<List<ActorRef>>(calls), self());
        }
    } else {
        String errMsg = "The SIP Client " + request.to() + " is not registered or does not exist";
        logger.error(errMsg);
        sendNotification(errMsg, 11008, "error", true);
        sender.tell(new CallManagerResponse<ActorRef>(new NullPointerException(errMsg), this.createCallRequest),
                self());
    }
}

From source file:uk.ac.ebi.intact.editor.services.curate.cvobject.CvObjectService.java

public List<SelectItem> createExperimentalRoleSelectItems(Collection<IntactCvTerm> cvObjects,
        String noSelectionText) {
    List<SelectItem> selectItems = new CopyOnWriteArrayList<SelectItem>();

    if (noSelectionText != null) {
        selectItems.add(new SelectItem(null, noSelectionText, noSelectionText, false, false, true));
    }//  w w  w  .  j av  a2  s  .c o m

    for (IntactCvTerm cvObject : cvObjects) {
        selectItems.add(createSelectItem(cvObject));

        if (CvTermUtils.isCvTerm(cvObject, Participant.UNSPECIFIED_ROLE_MI, Participant.UNSPECIFIED_ROLE)) {
            defaultExperimentalRole = cvObject;
        }
    }

    return selectItems;
}

From source file:uk.ac.ebi.intact.editor.services.curate.cvobject.CvObjectService.java

public List<SelectItem> createBiologicalRoleSelectItems(Collection<IntactCvTerm> cvObjects,
        String noSelectionText) {
    List<SelectItem> selectItems = new CopyOnWriteArrayList<SelectItem>();

    if (noSelectionText != null) {
        selectItems.add(new SelectItem(null, noSelectionText, noSelectionText, false, false, true));
    }/*from ww w .  ja  va  2  s  .  co  m*/

    for (IntactCvTerm cvObject : cvObjects) {
        selectItems.add(createSelectItem(cvObject));

        if (CvTermUtils.isCvTerm(cvObject, Participant.UNSPECIFIED_ROLE_MI, Participant.UNSPECIFIED_ROLE)) {
            defaultBiologicalRole = cvObject;
        }
    }

    return selectItems;
}

From source file:ml.shifu.shifu.core.dtrain.dt.DTMaster.java

private void recoverMasterStatus(SourceType sourceType) {
    FSDataInputStream stream = null;/*from   w  w  w.j av  a  2  s.c  o m*/
    FileSystem fs = ShifuFileUtils.getFileSystemBySourceType(sourceType);
    try {
        stream = fs.open(this.checkpointOutput);
        int treeSize = stream.readInt();
        this.trees = new CopyOnWriteArrayList<TreeNode>();
        for (int i = 0; i < treeSize; i++) {
            TreeNode treeNode = new TreeNode();
            treeNode.readFields(stream);
            this.trees.add(treeNode);
        }

        int queueSize = stream.readInt();
        for (int i = 0; i < queueSize; i++) {
            TreeNode treeNode = new TreeNode();
            treeNode.readFields(stream);
            this.toDoQueue.offer(treeNode);
        }

        if (this.isLeafWise && this.toSplitQueue != null) {
            queueSize = stream.readInt();
            for (int i = 0; i < queueSize; i++) {
                TreeNode treeNode = new TreeNode();
                treeNode.readFields(stream);
                this.toSplitQueue.offer(treeNode);
            }
        }

        this.cpMasterParams = new DTMasterParams();
        this.cpMasterParams.readFields(stream);
    } catch (IOException e) {
        throw new GuaguaRuntimeException(e);
    } finally {
        org.apache.commons.io.IOUtils.closeQuietly(stream);
    }
}

From source file:org.apache.druid.indexing.common.task.AppenderatorDriverRealtimeIndexTaskTest.java

private void makeToolboxFactory(final File directory) {
    taskStorage = new HeapMemoryTaskStorage(new TaskStorageConfig(null));
    taskLockbox = new TaskLockbox(taskStorage);

    publishedSegments = new CopyOnWriteArrayList<>();

    ObjectMapper mapper = new DefaultObjectMapper();
    mapper.registerSubtypes(LinearShardSpec.class);
    mapper.registerSubtypes(NumberedShardSpec.class);
    IndexerSQLMetadataStorageCoordinator mdc = new IndexerSQLMetadataStorageCoordinator(mapper,
            derbyConnectorRule.metadataTablesConfigSupplier().get(), derbyConnectorRule.getConnector()) {
        @Override/*from  www . j  av a  2 s  . c o  m*/
        public Set<DataSegment> announceHistoricalSegments(Set<DataSegment> segments) throws IOException {
            Set<DataSegment> result = super.announceHistoricalSegments(segments);

            Assert.assertFalse("Segment latch not initialized, did you forget to call expectPublishSegments?",
                    segmentLatch == null);

            publishedSegments.addAll(result);
            segments.forEach(s -> segmentLatch.countDown());

            return result;
        }

        @Override
        public SegmentPublishResult announceHistoricalSegments(Set<DataSegment> segments,
                DataSourceMetadata startMetadata, DataSourceMetadata endMetadata) throws IOException {
            SegmentPublishResult result = super.announceHistoricalSegments(segments, startMetadata,
                    endMetadata);

            Assert.assertFalse("Segment latch not initialized, did you forget to call expectPublishSegments?",
                    segmentLatch == null);

            publishedSegments.addAll(result.getSegments());
            result.getSegments().forEach(s -> segmentLatch.countDown());

            return result;
        }
    };
    final TaskConfig taskConfig = new TaskConfig(directory.getPath(), null, null, 50000, null, false, null,
            null);

    final TaskActionToolbox taskActionToolbox = new TaskActionToolbox(taskLockbox, taskStorage, mdc, emitter,
            EasyMock.createMock(SupervisorManager.class), new Counters());
    final TaskActionClientFactory taskActionClientFactory = new LocalTaskActionClientFactory(taskStorage,
            taskActionToolbox, new TaskAuditLogConfig(false));
    IntervalChunkingQueryRunnerDecorator queryRunnerDecorator = new IntervalChunkingQueryRunnerDecorator(null,
            null, null) {
        @Override
        public <T> QueryRunner<T> decorate(QueryRunner<T> delegate,
                QueryToolChest<T, ? extends Query<T>> toolChest) {
            return delegate;
        }
    };
    final QueryRunnerFactoryConglomerate conglomerate = new DefaultQueryRunnerFactoryConglomerate(
            ImmutableMap.of(TimeseriesQuery.class,
                    new TimeseriesQueryRunnerFactory(new TimeseriesQueryQueryToolChest(queryRunnerDecorator),
                            new TimeseriesQueryEngine(), (query, future) -> {
                                // do nothing
                            })));
    handOffCallbacks = new ConcurrentHashMap<>();
    final SegmentHandoffNotifierFactory handoffNotifierFactory = dataSource -> new SegmentHandoffNotifier() {
        @Override
        public boolean registerSegmentHandoffCallback(SegmentDescriptor descriptor, Executor exec,
                Runnable handOffRunnable) {
            handOffCallbacks.put(descriptor, new Pair<>(exec, handOffRunnable));
            handoffLatch.countDown();
            return true;
        }

        @Override
        public void start() {
            //Noop
        }

        @Override
        public void close() {
            //Noop
        }

    };
    final TestUtils testUtils = new TestUtils();
    rowIngestionMetersFactory = testUtils.getRowIngestionMetersFactory();
    SegmentLoaderConfig segmentLoaderConfig = new SegmentLoaderConfig() {
        @Override
        public List<StorageLocationConfig> getLocations() {
            return Lists.newArrayList();
        }
    };

    taskToolboxFactory = new TaskToolboxFactory(taskConfig, taskActionClientFactory, emitter,
            new TestDataSegmentPusher(), new TestDataSegmentKiller(), null, // DataSegmentMover
            null, // DataSegmentArchiver
            new TestDataSegmentAnnouncer(), EasyMock.createNiceMock(DataSegmentServerAnnouncer.class),
            handoffNotifierFactory, () -> conglomerate, MoreExecutors.sameThreadExecutor(), // queryExecutorService
            EasyMock.createMock(MonitorScheduler.class),
            new SegmentLoaderFactory(new SegmentLoaderLocalCacheManager(null, segmentLoaderConfig,
                    testUtils.getTestObjectMapper())),
            testUtils.getTestObjectMapper(), testUtils.getTestIndexIO(), MapCache.create(1024),
            new CacheConfig(), new CachePopulatorStats(), testUtils.getTestIndexMergerV9(),
            EasyMock.createNiceMock(DruidNodeAnnouncer.class), EasyMock.createNiceMock(DruidNode.class),
            new LookupNodeService("tier"), new DataNodeService("tier", 1000, ServerType.INDEXER_EXECUTOR, 0),
            new TaskReportFileWriter(reportsFile));
}

From source file:com.l2jfree.gameserver.model.entity.events.TvT.java

public static void cleanTvT() {
    _log.info("TvT : Cleaning players.");
    for (L2Player player : _players) {
        if (player != null) {
            removePlayer(player);//from   ww  w. j  a v a  2s.com
        }
    }
    if (_playersShuffle != null && !_playersShuffle.isEmpty()) {
        for (L2Player player : _playersShuffle) {
            if (player != null)
                player.setPlayerInfo(null);
        }
    }
    _log.info("TvT : Cleaning teams.");
    for (String team : _teams) {
        int index = _teams.indexOf(team);

        _teamPlayersCount.set(index, 0);
        _teamKillsCount.set(index, 0);
    }

    _topKills = 0;
    _topTeam = "";
    _players = new CopyOnWriteArrayList<L2Player>();
    _playersShuffle = new CopyOnWriteArrayList<L2Player>();
    _savePlayers = new CopyOnWriteArrayList<String>();
    _savePlayerTeams = new CopyOnWriteArrayList<String>();
    _log.info("Cleaning TvT done.");
}

From source file:com.l2jfree.gameserver.model.entity.events.CTF.java

public static void loadData() {
    _eventName = "";
    _eventDesc = "";
    _topTeam = "";
    _joiningLocationName = "";
    _teams = new CopyOnWriteArrayList<String>();
    _savePlayers = new CopyOnWriteArrayList<String>();
    _savePlayerTeams = new CopyOnWriteArrayList<String>();
    _players = new CopyOnWriteArrayList<L2Player>();
    _playersShuffle = new CopyOnWriteArrayList<L2Player>();
    _teamPlayersCount = new CopyOnWriteArrayList<Integer>();
    _teamPointsCount = new CopyOnWriteArrayList<Integer>();
    _teamColors = new CopyOnWriteArrayList<Integer>();
    _teamsX = new CopyOnWriteArrayList<Integer>();
    _teamsY = new CopyOnWriteArrayList<Integer>();
    _teamsZ = new CopyOnWriteArrayList<Integer>();

    _throneSpawns = new CopyOnWriteArrayList<L2Spawn>();
    _flagSpawns = new CopyOnWriteArrayList<L2Spawn>();
    _flagsTaken = new CopyOnWriteArrayList<Boolean>();
    _flagIds = new CopyOnWriteArrayList<Integer>();
    _flagsX = new CopyOnWriteArrayList<Integer>();
    _flagsY = new CopyOnWriteArrayList<Integer>();
    _flagsZ = new CopyOnWriteArrayList<Integer>();

    _joining = false;/*from w  w  w.ja  v a  2  s . c om*/
    _teleport = false;
    _started = false;
    _sitForced = false;
    _npcId = 0;
    _npcX = 0;
    _npcY = 0;
    _npcZ = 0;
    _npcHeading = 0;
    _rewardId = 0;
    _rewardAmount = 0;
    _topScore = 0;
    _minlvl = 0;
    _maxlvl = 0;
    _joinTime = 0;
    _eventTime = 0;
    _minPlayers = 0;
    _maxPlayers = 0;

    Connection con = null;
    try {
        PreparedStatement statement;
        ResultSet rs;

        con = L2DatabaseFactory.getInstance().getConnection(con);

        statement = con.prepareStatement("Select * from ctf");
        rs = statement.executeQuery();

        int teams = 0;

        while (rs.next()) {
            _eventName = rs.getString("eventName");
            _eventDesc = rs.getString("eventDesc");
            _joiningLocationName = rs.getString("joiningLocation");
            _minlvl = rs.getInt("minlvl");
            _maxlvl = rs.getInt("maxlvl");
            _npcId = rs.getInt("npcId");
            _npcX = rs.getInt("npcX");
            _npcY = rs.getInt("npcY");
            _npcZ = rs.getInt("npcZ");
            _npcHeading = rs.getInt("npcHeading");
            _rewardId = rs.getInt("rewardId");
            _rewardAmount = rs.getInt("rewardAmount");
            teams = rs.getInt("teamsCount");
            _joinTime = rs.getInt("joinTime");
            _eventTime = rs.getInt("eventTime");
            _minPlayers = rs.getInt("minPlayers");
            _maxPlayers = rs.getInt("maxPlayers");
        }
        statement.close();

        int index = -1;
        if (teams > 0)
            index = 0;
        while (index < teams && index > -1) {
            statement = con.prepareStatement("Select * from ctf_teams where teamId = ?");
            statement.setInt(1, index);
            rs = statement.executeQuery();
            while (rs.next()) {
                _teams.add(rs.getString("teamName"));
                _teamPlayersCount.add(0);
                _teamPointsCount.add(0);
                _teamColors.add(0);
                _teamsX.add(0);
                _teamsY.add(0);
                _teamsZ.add(0);
                _teamsX.set(index, rs.getInt("teamX"));
                _teamsY.set(index, rs.getInt("teamY"));
                _teamsZ.set(index, rs.getInt("teamZ"));
                _teamColors.set(index, rs.getInt("teamColor"));
                _flagsX.add(0);
                _flagsY.add(0);
                _flagsZ.add(0);
                _flagsX.set(index, rs.getInt("flagX"));
                _flagsY.set(index, rs.getInt("flagY"));
                _flagsZ.set(index, rs.getInt("flagZ"));
                _flagSpawns.add(null);
                _flagIds.add(_FlagNPC);
                _flagsTaken.add(false);

            }
            index++;
            statement.close();
        }
    } catch (Exception e) {
        _log.error("Exception: CTF.loadData(): ", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}