Example usage for java.util Collections synchronizedList

List of usage examples for java.util Collections synchronizedList

Introduction

In this page you can find the example usage for java.util Collections synchronizedList.

Prototype

public static <T> List<T> synchronizedList(List<T> list) 

Source Link

Document

Returns a synchronized (thread-safe) list backed by the specified list.

Usage

From source file:net.sourceforge.fenixedu.domain.accounting.report.events.EventReportQueueJob.java

private SheetData<EventBean> allEvents(final StringBuilder errors) {

    List<String> allEventsExternalIds = getAllEventsExternalIds();
    logger.info(String.format("%s events to process", allEventsExternalIds.size()));

    Integer blockRead = 0;/*  w  w w.  j a  va 2  s .c o  m*/

    final List<EventBean> result = Collections.synchronizedList(new ArrayList<EventBean>());

    while (blockRead < allEventsExternalIds.size()) {
        Integer inc = BLOCK;

        if (blockRead + inc >= allEventsExternalIds.size()) {
            inc = allEventsExternalIds.size() - blockRead;
        }

        final List<String> block = allEventsExternalIds.subList(blockRead, blockRead + inc);
        blockRead += inc;

        Thread thread = new Thread() {

            @Override
            @Atomic(mode = TxMode.READ)
            public void run() {
                for (String oid : block) {
                    Event event = null;
                    try {
                        event = FenixFramework.getDomainObject(oid);
                        if (!isAccountingEventForReport(event)) {
                            continue;
                        }
                        result.add(writeEvent(event));
                    } catch (Throwable e) {
                        errors.append(getErrorLine(event, e));
                    }
                }
            }
        };

        thread.start();

        try {
            thread.join();
        } catch (InterruptedException e) {
        }

        logger.info(String.format("Read %s events", blockRead));
    }

    logger.info(String.format("Catch %s events ", result.size()));

    return new SheetData<EventBean>(result) {

        @Override
        protected void makeLine(EventBean bean) {
            addCell("Identificador", bean.externalId);
            addCell("Aluno", bean.studentNumber);
            addCell("Nome", bean.studentName);
            addCell("Email", bean.email);
            addCell("Data inscrio", bean.registrationStartDate);
            addCell("Ano lectivo", bean.executionYear);
            addCell("Tipo de matricula", bean.studiesType);
            addCell("Nome do Curso", bean.degreeName);
            addCell("Tipo de curso", bean.degreeType);
            addCell("Programa doutoral", bean.phdProgramName);
            addCell("ECTS inscritos", bean.enrolledECTS);
            addCell("Regime", bean.regime);
            addCell("Modelo de inscrio", bean.enrolmentModel);
            addCell("Residncia - Ano", bean.residenceYear);
            addCell("Residncia - Ms", bean.residenceMonth);
            addCell("Tipo de divida", bean.description);
            addCell("Data de criao", bean.whenOccured);
            addCell("Valor Total", bean.totalAmount);
            addCell("Valor Pago", bean.payedAmount);
            addCell("Valor em divida", bean.amountToPay);
            addCell("Valor Reembolsvel", bean.reimbursableAmount);
            addCell("Desconto", bean.totalDiscount);
            addCell("Dvida Associada", bean.relatedEvent);
            addCell("Id. Fiscal Entidade", bean.debtorFiscalId);
            addCell("Nome Entidade", bean.debtorName);

            List<InstallmentWrapper> list = bean.installments;

            if (list != null) {
                for (InstallmentWrapper installment : list) {
                    addCell(installment.getExpirationDateLabel(), installment.getExpirationDate());
                    addCell(installment.getAmountToPayLabel(), installment.getAmountToPay());
                    addCell(installment.getRemainingAmountLabel(), installment.getRemainingAmount());
                }
            }
        }

    };
}

From source file:org.kuali.rice.krad.util.MessageMap.java

/**
 * Adds an error message to the given message map, adjusting the error path and message parameters if necessary
 *
 * @param messagesMap/*from w w  w .  ja  va2s .com*/
 * @param propertyName name of the property to add error under
 * @param errorMessage
 * @param prependFullErrorPath true if you want the whole parent error path prepended, false otherwise
 * @param escapeHtmlMessageParameters whether to escape HTML characters in the message parameters, provides
 * protection against XSS attacks
 * @return TypeArrayList
 */
protected List<ErrorMessage> putMessageInMap(Map<String, List<ErrorMessage>> messagesMap, String propertyName,
        ErrorMessage errorMessage, boolean prependFullErrorPath, boolean escapeHtmlMessageParameters) {
    if (StringUtils.isBlank(propertyName)) {
        throw new IllegalArgumentException("invalid (blank) propertyName");
    }
    if (StringUtils.isBlank(errorMessage.getErrorKey())) {
        throw new IllegalArgumentException("invalid (blank) errorKey");
    }

    // check if we have previous errors for this property
    List<ErrorMessage> errorList = null;
    String propertyKey = getKeyPath(propertyName, prependFullErrorPath);
    if (messagesMap.containsKey(propertyKey)) {
        errorList = messagesMap.get(propertyKey);
    } else {
        errorList = Collections.synchronizedList(new AutoPopulatingList<ErrorMessage>(ErrorMessage.class));
    }

    if (escapeHtmlMessageParameters) {
        if (errorMessage.getMessageParameters() != null) {
            String[] filteredMessageParameters = new String[errorMessage.getMessageParameters().length];
            for (int i = 0; i < errorMessage.getMessageParameters().length; i++) {
                filteredMessageParameters[i] = StringEscapeUtils
                        .escapeHtml(errorMessage.getMessageParameters()[i]);
            }
            errorMessage.setMessageParameters(filteredMessageParameters);
        }

        if (errorMessage.getMessagePrefixParameters() != null) {
            String[] filteredMessageParameters = new String[errorMessage.getMessagePrefixParameters().length];
            for (int i = 0; i < errorMessage.getMessagePrefixParameters().length; i++) {
                filteredMessageParameters[i] = StringEscapeUtils
                        .escapeHtml(errorMessage.getMessagePrefixParameters()[i]);
            }
            errorMessage.setMessagePrefixParameters(filteredMessageParameters);
        }

        if (errorMessage.getMessageSuffixParameters() != null) {
            String[] filteredMessageParameters = new String[errorMessage.getMessageSuffixParameters().length];
            for (int i = 0; i < errorMessage.getMessageSuffixParameters().length; i++) {
                filteredMessageParameters[i] = StringEscapeUtils
                        .escapeHtml(errorMessage.getMessageSuffixParameters()[i]);
            }
            errorMessage.setMessageSuffixParameters(filteredMessageParameters);
        }
    }

    // check if this error has already been added to the list
    boolean alreadyAdded = false;
    for (ErrorMessage e : errorList) {
        if (e.equals(errorMessage)) {
            alreadyAdded = true;
            break;
        }
    }
    if (!alreadyAdded) {
        errorList.add(errorMessage);
    }

    return messagesMap.put(propertyKey, errorList);
}

From source file:org.executequery.databaseobjects.impl.DefaultDatabaseTable.java

private List<DatabaseColumn> databaseColumnListWithSize(int size) {

    return Collections.synchronizedList(new ArrayList<DatabaseColumn>(size));
}

From source file:org.executequery.databaseobjects.impl.DefaultDatabaseTable.java

private List<ColumnConstraint> databaseConstraintsListWithSize(int size) {

    return Collections.synchronizedList(new ArrayList<ColumnConstraint>(size));
}

From source file:org.executequery.databaseobjects.impl.DefaultDatabaseTable.java

private List<TableColumnIndex> databaseIndexListWithSize(int size) {

    return Collections.synchronizedList(new ArrayList<TableColumnIndex>(size));
}

From source file:org.apache.solr.handler.IndexFetcher.java

/**
 * Fetches the list of files in a given index commit point and updates internal list of files to download.
 *///from   w w  w .  j ava 2s  . co m
private void fetchFileList(long gen) throws IOException {
    ModifiableSolrParams params = new ModifiableSolrParams();
    params.set(COMMAND, CMD_GET_FILE_LIST);
    params.set(GENERATION, String.valueOf(gen));
    params.set(CommonParams.WT, JAVABIN);
    params.set(CommonParams.QT, ReplicationHandler.PATH);
    QueryRequest req = new QueryRequest(params);

    // TODO modify to use shardhandler
    try (HttpSolrClient client = new HttpSolrClient.Builder(masterUrl).withHttpClient(myHttpClient).build()) {
        client.setSoTimeout(soTimeout);
        client.setConnectionTimeout(connTimeout);
        NamedList response = client.request(req);

        List<Map<String, Object>> files = (List<Map<String, Object>>) response.get(CMD_GET_FILE_LIST);
        if (files != null)
            filesToDownload = Collections.synchronizedList(files);
        else {
            filesToDownload = Collections.emptyList();
            LOG.error("No files to download for index generation: " + gen);
        }

        files = (List<Map<String, Object>>) response.get(CONF_FILES);
        if (files != null)
            confFilesToDownload = Collections.synchronizedList(files);

        files = (List<Map<String, Object>>) response.get(TLOG_FILES);
        if (files != null) {
            tlogFilesToDownload = Collections.synchronizedList(files);
        }
    } catch (SolrServerException e) {
        throw new IOException(e);
    }
}

From source file:com.sonyericsson.hudson.plugins.gerrit.trigger.playback.GerritMissedEventsPlaybackManager.java

/**
 * This allows us to persist a last known alive time
 * for the server./*from www.j  a v a  2 s  . com*/
 * @param event Gerrit Event
 */
@Override
public void gerritEvent(GerritEvent event) {
    if (!isSupported()) {
        return;
    }

    if (event instanceof GerritTriggeredEvent) {
        logger.debug("Recording timestamp due to an event {} for server: {}", event, serverName);
        GerritTriggeredEvent triggeredEvent = (GerritTriggeredEvent) event;
        persist(triggeredEvent);
        //add to cache
        if (!playBackComplete) {
            boolean receivedEvtFound = false;
            synchronized (receivedEventCache) {
                Iterator<GerritTriggeredEvent> i = receivedEventCache.iterator(); // Must be in synchronized block
                while (i.hasNext()) {
                    GerritTriggeredEvent rEvt = i.next();
                    if (rEvt.equals(triggeredEvent)) {
                        receivedEvtFound = true;
                        break;
                    }
                }
            }
            if (!receivedEvtFound) {
                receivedEventCache.add(triggeredEvent);
                logger.debug("Added event {} to received cache for server: {}", event, serverName);
            } else {
                logger.debug("Event {} ALREADY in received cache for server: {}", event, serverName);
            }
        } else {
            receivedEventCache = Collections.synchronizedList(new ArrayList<GerritTriggeredEvent>());
            logger.debug("Playback complete...will NOT add event {} to received cache for server: {}", event,
                    serverName);
        }
    }
}

From source file:org.apache.hadoop.hbase.security.AbstractTestSecureIPC.java

/**
 * Sets up a RPC Server and a Client. Does a RPC checks the result. If an exception is thrown
 * from the stub, this function will throw root cause of that exception.
 *///from   w ww  .  ja v  a2  s  .  com
private void callRpcService(User clientUser) throws Exception {
    SecurityInfo securityInfoMock = Mockito.mock(SecurityInfo.class);
    Mockito.when(securityInfoMock.getServerPrincipal()).thenReturn(HBaseKerberosUtils.KRB_PRINCIPAL);
    SecurityInfo.addInfo("TestProtobufRpcProto", securityInfoMock);

    InetSocketAddress isa = new InetSocketAddress(HOST, 0);

    RpcServerInterface rpcServer = new RpcServer(null, "AbstractTestSecureIPC",
            Lists.newArrayList(new RpcServer.BlockingServiceAndInterface(SERVICE, null)), isa, serverConf,
            new FifoRpcScheduler(serverConf, 1));
    rpcServer.start();
    try (RpcClient rpcClient = RpcClientFactory.createClient(clientConf,
            HConstants.DEFAULT_CLUSTER_ID.toString())) {
        InetSocketAddress address = rpcServer.getListenerAddress();
        if (address == null) {
            throw new IOException("Listener channel is closed");
        }
        BlockingRpcChannel channel = rpcClient.createBlockingRpcChannel(
                ServerName.valueOf(address.getHostName(), address.getPort(), System.currentTimeMillis()),
                clientUser, 0);
        TestRpcServiceProtos.TestProtobufRpcProto.BlockingInterface stub = TestRpcServiceProtos.TestProtobufRpcProto
                .newBlockingStub(channel);
        List<String> results = new ArrayList<>();
        TestThread th1 = new TestThread(stub, results);
        final Throwable exception[] = new Throwable[1];
        Collections.synchronizedList(new ArrayList<Throwable>());
        Thread.UncaughtExceptionHandler exceptionHandler = new Thread.UncaughtExceptionHandler() {
            public void uncaughtException(Thread th, Throwable ex) {
                exception[0] = ex;
            }
        };
        th1.setUncaughtExceptionHandler(exceptionHandler);
        th1.start();
        th1.join();
        if (exception[0] != null) {
            // throw root cause.
            while (exception[0].getCause() != null) {
                exception[0] = exception[0].getCause();
            }
            throw (Exception) exception[0];
        }
    } finally {
        rpcServer.stop();
    }
}

From source file:org.alfresco.dropbox.service.polling.DropboxPollerImpl.java

private List<NodeRef> getFolders(final NodeRef nodeRef) {
    List<NodeRef> folders = Collections.synchronizedList(new ArrayList<NodeRef>());

    ResultSet resultSet = AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<ResultSet>() {

        public ResultSet doWork() throws Exception {

            ResultSet resultSet = searchService.query(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE,
                    SearchService.LANGUAGE_CMIS_ALFRESCO,
                    CMIS_DROPBOX_FOLDERS_QUERY + " WHERE IN_TREE(F, '" + nodeRef + "')");

            return resultSet;
        }/*w  ww.  j  a v a  2s. c  o  m*/

    }, AuthenticationUtil.getAdminUserName());

    try {
        // TODO Hopefully one day this will go away --Open Bug??
        if (resultSet.length() > 0) {
            if (!resultSet.getNodeRef(0).equals(MISSING_NODE)) {
                folders = resultSet.getNodeRefs();
                log.debug("Folders synced to Dropbox: " + folders);
            }
        }
    } finally {
        resultSet.close();
    }

    return folders;
}

From source file:com.orange.mmp.message.jms.JMSMessageBroker.java

@SuppressWarnings("unchecked")
public void initialize() throws MMPException {
    //Initialize the Listeners list
    this.messageListeners = Collections.synchronizedList(new ArrayList<MessageListener>());
    //Initialize the module message listeners configuration cache
    this.moduleListenersCache = new ConcurrentHashMap<Class, MessageListener>();

    this.syncListenerPool = new ArrayBlockingQueue<JMSSyncMessageListener>(this.maxSynchronousListeners);
    try {//w  w w . ja va2s  .c  o m
        for (int i = 0; i < this.maxSynchronousListeners; i++) {
            this.syncListenerPool.put(new JMSSyncMessageListener());
        }
    } catch (InterruptedException e) {
        throw new MMPMessageException(e);
    }

    //Initialize Listeners Cache
    this.messageListenersMap = new ConcurrentHashMap<Serializable, MessageListener>();

    //Get the ModuleContainer and add itself as a ModuleObserver
    ModuleContainerFactory.getInstance().getModuleContainer().registerModuleObserver(this);
}