Example usage for java.util.concurrent ConcurrentHashMap put

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

Introduction

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

Prototype

public V put(K key, V value) 

Source Link

Document

Maps the specified key to the specified value in this table.

Usage

From source file:com.web.server.WebServer.java

/**
 * This methos is the implementation of the HTPP request and sends the response.
 *//*from w ww.java2  s.  c om*/
public void run() {
    byte[] response;
    byte[] content;
    byte[] uploadData = null;
    HttpHeaderClient httpHeaderClient = null;
    InputStream istream = null;
    OutputStream ostream = null;
    HttpHeaderServer serverParam = new HttpHeaderServer();
    StringBuffer buffer = new StringBuffer();
    String value;
    char c;
    String endvalue = "\r\n\r\n";
    String urlFormEncoded;
    int responseCode;
    try {
        ////System.out.println("value=");
        istream = socket.getInputStream();
        BufferedInputStream bistr = new BufferedInputStream(istream);
        //socket.setReceiveBufferSize(10000);
        //System.out.println("value1=");
        int availbleStream;
        int totalBytRead = 0;
        int ch;
        ByteArrayOutputStream bytout = new ByteArrayOutputStream();
        ByteArrayOutputStream contentout = new ByteArrayOutputStream();
        //System.out.println(istream.available());
        int bytesRead;
        int endbytIndex = 0;
        int contentbytIndex = 0;
        boolean httpHeaderEndFound = false;
        byte[] byt;
        while ((ch = bistr.read()) != -1) {
            bytout.write(ch);
            if (!httpHeaderEndFound && (char) ch == endvalue.charAt(endbytIndex)) {
                endbytIndex++;
                if (endbytIndex == endvalue.length()) {
                    byt = bytout.toByteArray();
                    value = new String(ObtainBytes(byt, 0, byt.length - 4));
                    //System.out.println(value);
                    httpHeaderClient = parseHttpHeaders(value);
                    httpHeaderEndFound = true;
                    bytout.close();
                    endbytIndex = 0;
                    if (httpHeaderClient.getContentLength() == null)
                        break;
                }
            } else {
                endbytIndex = 0;
            }
            if (httpHeaderClient != null && httpHeaderEndFound) {
                contentout.write(ch);
                contentbytIndex++;
                if (httpHeaderClient.getContentLength() != null
                        && contentbytIndex >= Integer.parseInt(httpHeaderClient.getContentLength())) {
                    break;
                }
            }
            totalBytRead++;
        }
        /*while(totalBytRead==0){
           while((ch = bistr.read())!=-1){
              System.out.println((char)ch);
              ////System.out.println("availableStream="+availbleStream);
              bytarrayOutput.write(ch);
              totalBytRead++;
           }
        }*/
        if (totalBytRead == 0) {
            System.out.println("Since byte is 0 sock and istream os closed");
            //istream.close();
            socket.close();
            return;
        }
        //istream.read(bt,0,9999999);
        System.out.println("bytes read");
        byte[] contentByte = contentout.toByteArray();
        contentout.close();
        //System.out.println("String="+new String(bt));
        /*int index=containbytes(bt,endvalue.getBytes());
        if(index==-1)index=totalBytRead;
        value=new String(ObtainBytes(bt,0,index));*/
        System.out.println("value2=");

        ConcurrentHashMap<String, HttpCookie> httpCookies = httpHeaderClient.getCookies();
        HttpSessionServer session = null;
        if (httpCookies != null) {
            Iterator<String> cookieNames = httpCookies.keySet().iterator();
            for (; cookieNames.hasNext();) {
                String cookieName = cookieNames.next();
                //System.out.println(cookieName+" "+httpCookies.get(cookieName).getValue());
                if (cookieName.equals("SERVERSESSIONID")) {
                    session = (HttpSessionServer) sessionObjects.get(httpCookies.get(cookieName).getValue());
                    httpHeaderClient.setSession(session);
                    //break;
                }
            }
        }
        //System.out.println("Session="+session);
        if (session == null) {
            HttpCookie cookie = new HttpCookie();
            cookie.setKey("SERVERSESSIONID");
            cookie.setValue(UUID.randomUUID().toString());
            httpCookies.put("SERVERSESSIONID", cookie);
            session = new HttpSessionServer();
            sessionObjects.put(cookie.getValue(), session);
            httpHeaderClient.setSession(session);
        }
        if (httpHeaderClient.getContentType() != null
                && httpHeaderClient.getContentType().equals(HttpHeaderParamNames.MULTIPARTFORMDATAVALUE)) {
            ////System.out.println(new String(uploadData));
            ConcurrentHashMap paramMap = new MultipartFormData().parseContent(contentByte, httpHeaderClient);
            httpHeaderClient.setParameters(paramMap);
            ////logger.info(uploadData);
        } else if (httpHeaderClient.getContentType() != null
                && httpHeaderClient.getContentType().equals(HttpHeaderParamNames.URLENCODED)) {
            urlFormEncoded = new String(contentByte);
            ConcurrentHashMap paramMap = parseUrlEncoded(urlFormEncoded);
            httpHeaderClient.setParameters(paramMap);
        }
        ////logger.info(serverconfig.getDeploydirectory()+httpHeaderClient.getResourceToObtain());
        ////System.out.println("value3=");

        ////logger.info(new String(bt));
        serverParam.setContentType("text/html");
        URLDecoder decoder = new URLDecoder();
        System.out.println("content Length= " + socket);
        responseCode = 200;
        File file = new File(deployDirectory + decoder.decode(httpHeaderClient.getResourceToObtain()));
        FileContent fileContent = (FileContent) cache.get(httpHeaderClient.getResourceToObtain());
        if (fileContent != null && file.lastModified() == fileContent.getLastModified()) {
            System.out.println("In cache");
            content = (byte[]) fileContent.getContent();
        } else {
            content = ObtainContentExecutor(deployDirectory, httpHeaderClient.getResourceToObtain(),
                    httpHeaderClient, serverdigester, urlClassLoaderMap, servletMapping, session);
            System.out.println("content Length2= " + content);
            if (content == null) {
                //System.out.println("In caching content");
                content = obtainContent(
                        deployDirectory + decoder.decode(httpHeaderClient.getResourceToObtain()));
                if (content != null) {
                    fileContent = new FileContent();
                    fileContent.setContent(content);
                    fileContent.setFileName(httpHeaderClient.getResourceToObtain());
                    fileContent.setLastModified(file.lastModified());
                    cache.put(httpHeaderClient.getResourceToObtain(), fileContent);
                }
            }
            ////System.out.println("value4=");

        }

        if (content == null) {
            responseCode = 404;
            content = ("<html><body><H1>The Request resource " + httpHeaderClient.resourceToObtain
                    + " Not Found</H1><body></html>").getBytes();
        }
        ////System.out.println("content Length3= ");
        serverParam.setContentLength("" + (content.length + 4));
        if (httpHeaderClient.getResourceToObtain().endsWith(".ico")) {
            serverParam.setContentType("image/png");
        }
        ////System.out.println("value5=");

        ////System.out.println("content Length4= ");
        response = formHttpResponseHeader(responseCode, serverParam, content, httpHeaderClient.getCookies());
        ////System.out.println("value6=");
        ostream = socket.getOutputStream();
        //logger.info("Response="+new String(response));
        //System.out.println("value6=");
        //logger.info("Response="+new String(response));
        ////System.out.println("content "+"Response="+new String(response));
        ostream.write(response);
        ostream.flush();
        ostream.close();
        socket.close();
    } catch (IOException e) {
        Socket socket;
        e.printStackTrace();

        //logger.error(e);
        try {
            socket = new Socket("localhost", shutdownPort);
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("shutdown WebServer\r\n\r\n".getBytes());
            outputStream.close();
        } catch (Exception ex) {

            ex.printStackTrace();
        }
        e.printStackTrace();
    } catch (NumberFormatException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.web.server.WebServer.java

/**
 * This method obtains the url parameters
 * @param url/*from w  w w .  java 2 s  .  c om*/
 * @param params
 * @return string
 */
public String ObtainUrlAndParams(String url, ConcurrentHashMap params) {

    URLDecoder decoder = new URLDecoder();
    url = decoder.decode(url);
    if (url.indexOf("?") > -1) {
        String paramaters = url.substring(url.indexOf("?") + 1);
        StringTokenizer paramGroup = new StringTokenizer(paramaters, "&");

        while (paramGroup.hasMoreTokens()) {

            StringTokenizer value = new StringTokenizer(paramGroup.nextToken(), "=");
            String param = null;
            if (value.hasMoreTokens()) {
                param = value.nextToken();
            }
            String paramValue = null;
            if (value.hasMoreTokens()) {
                paramValue = value.nextToken();
            }
            if (param != null && paramValue != null) {
                if (params.get(param) != null) {
                    if (params.get(param) instanceof String[]) {
                        String[] parameters = (String[]) params.get(param);
                        String[] paramValues = new String[parameters.length + 1];
                        for (int paramcount = 0; paramcount < parameters.length; paramcount++) {
                            paramValues[paramcount] = parameters[paramcount];
                        }
                        paramValues[parameters.length] = paramValue;
                        params.put(param, paramValues);
                    } else if (params.get(param) instanceof String) {
                        String[] paramValues = new String[2];
                        paramValues[0] = (String) params.get(param);
                        paramValues[1] = paramValue;
                        params.put(param, paramValues);
                    }
                } else {
                    params.put(param, paramValue);
                }
            }
        }
    }
    if (url.indexOf("?") != -1) {
        return url.substring(0, url.indexOf("?"));
    }
    return url;
}

From source file:com.dbmojo.DBMojoServer.java

private static DBMojoServer getMojoServerFromConfig(String[] args) {

    DBMojoServer server = null;/*from w  w  w  .j  av a  2 s. com*/

    try {
        String configFilePath = null;
        String json = null;
        JSONObject jObj = null;

        parseJson: {
            //If a command line argument is passed then assume it is the config file.
            //Otherwise use the default location
            if (args.length > 0) {
                configFilePath = args[0];
            } else {
                configFilePath = DBMojoServer.defaultConfigPath;
            }

            try {
                json = Util.fileToString(configFilePath);
            } catch (Exception fileEx) {
                throw new Exception(
                        "the specified config file, '" + configFilePath + "', could not be found and/or read");
            }

            if (json == null || json.equals("")) {
                throw new Exception("the specified config file, '" + configFilePath + "', is empty");
            }

            try {
                jObj = new JSONObject(json);
            } catch (Exception je) {
                throw new Exception(
                        "the specified config file, '" + configFilePath + "', does not contain valid JSON");
            }
        }

        //Load basic config data
        short serverPort = (short) jObj.optInt("serverPort");
        boolean useGzip = jObj.optBoolean("useGzip");
        short maxConcReq = (short) jObj.optInt("maxConcurrentRequests");
        String accessLogPath = jObj.optString("accessLogPath");
        String errorLogPath = jObj.optString("errorLogPath");
        String debugLogPath = jObj.optString("debugLogPath");

        checkMaxConcurrentReqeusts: {
            if (maxConcReq <= 0) {
                throw new Exception("please set the max concurrent requests to " + "a resonable number");
            }
        }

        checkServerPort: {
            //Make sure serverPort was specified
            if (serverPort <= 0) {
                throw new Exception("the server port was not specified");
            }

            //Make sure serverPort is not in use
            ServerSocket tSocket = null;
            try {
                tSocket = new ServerSocket(serverPort);
            } catch (Exception se) {
                tSocket = null;
                throw new Exception("the server port specified is already in use");
            } finally {
                if (tSocket != null) {
                    tSocket.close();
                }
                tSocket = null;
            }
        }

        startLogs: {
            if (!accessLogPath.equals("")) {
                //Make sure accessLogPath exists
                Util.pathExists(accessLogPath, true);
                //Start logging
                AccessLog.start(accessLogPath);
            }

            if (!errorLogPath.equals("")) {
                //Make sure errorLogPath exists
                Util.pathExists(errorLogPath, true);
                //Start logging
                ErrorLog.start(errorLogPath);
            }

            if (!debugLogPath.equals("")) {
                //Make sure debugLogPath exists
                Util.pathExists(debugLogPath, true);
                //Start logging
                DebugLog.start(debugLogPath);
            }
        }

        ConcurrentHashMap<String, ConnectionPool> dbPools = new ConcurrentHashMap<String, ConnectionPool>();
        loadDbAlaises: {
            ClassLoader classLoader = ClassLoader.getSystemClassLoader();
            final JSONArray dbAliases = jObj.getJSONArray("dbAliases");

            for (int i = 0; i < dbAliases.length(); i++) {
                final JSONObject tObj = dbAliases.getJSONObject(i);
                final String tAlias = tObj.getString("alias");
                final String tDriver = tObj.getString("driver");
                final String tDsn = tObj.getString("dsn");
                final String tUsername = tObj.getString("username");
                final String tPassword = tObj.getString("password");
                int tMaxConnections = tObj.getInt("maxConnections");
                //Seconds
                int tExpirationTime = tObj.getInt("expirationTime") * 1000;
                //Seconds
                int tConnectTimeout = tObj.getInt("connectTimeout");

                //Make sure each alias is named
                if (tAlias.equals("")) {
                    throw new Exception("alias #" + i + " is missing a name");
                }

                //Attempt to load each JDBC driver to ensure they are on the class path
                try {
                    Class aClass = classLoader.loadClass(tDriver);
                } catch (ClassNotFoundException cnf) {
                    throw new Exception("JDBC Driver '" + tDriver + "' is not on the class path");
                }

                //Make sure each alias has a JDBC connection string
                if (tDsn.equals("")) {
                    throw new Exception("JDBC URL, 'dsn', is missing for alias '" + tAlias + "'");
                }

                //Attempt to create a JDBC Connection
                ConnectionPool tPool;
                try {
                    tPool = new JDBCConnectionPool(tDriver, tDsn, tUsername, tPassword, 1, 1, 1, tAlias);
                    tPool.checkOut(false);
                } catch (Exception e) {
                    throw new Exception(
                            "JDBC Connection cannot be established " + "for database '" + tAlias + "'");
                } finally {
                    tPool = null;
                }

                //If the max connections option is not set for this alias 
                //then set it to 25
                if (tMaxConnections <= 0) {
                    tMaxConnections = 25;
                    System.out.println("DBMojoServer: Warning, 'maxConnections' " + "not set for alias '"
                            + tAlias + "' using 25");
                }

                //If the connection expiration time is not set for this alias then 
                //set it to 30 seconds
                if (tExpirationTime <= 0) {
                    tExpirationTime = 30;
                    System.out.println("DBMojoServer: Warning, 'expirationTime' not " + "set for alias '"
                            + tAlias + "' using 30 seconds");
                }

                //If the connection timeout is not set for this alias then 
                //set it to 10 seconds
                if (tConnectTimeout <= 0) {
                    tConnectTimeout = 10;
                    System.out.println("DBMojoServer Warning, 'connectTimeout' not " + "set for alias '"
                            + tAlias + "' using 10 seconds");
                }

                //Make sure another alias with the same name is not already 
                //defined in the config
                if (dbPools.containsKey(tAlias)) {
                    throw new Exception(
                            "the alias '" + tAlias + "' is already defined in " + " the provided config file");
                }

                //Everything is nicely set! Lets add a connection pool to the 
                //dbPool Hashtable keyed by this alias name
                dbPools.put(tAlias, new JDBCConnectionPool(tDriver, tDsn, tUsername, tPassword, tMaxConnections,
                        tExpirationTime, tConnectTimeout, tAlias));
            }
        }

        loadClusters: {
            final JSONArray tClusters = jObj.optJSONArray("clusters");

            if (tClusters != null) {
                for (int c = 0; c < tClusters.length(); c++) {
                    final JSONObject tObj = tClusters.getJSONObject(c);
                    final String tAlias = tObj.getString("alias");
                    final String tWriteTo = tObj.getString("writeTo");

                    if (dbPools.containsKey(tAlias)) {
                        throw new Exception("the alias '" + tAlias + "' is already defined.");
                    }

                    if (!dbPools.containsKey(tWriteTo)) {
                        throw new Exception(
                                "the alias '" + tWriteTo + "' is not present in the valid dbAliases. "
                                        + "This alias cannot be used for a cluster.");
                    }

                    //Add the dbAlias to the cluster writeTo list
                    ConnectionPool writeTo = dbPools.get(tWriteTo);

                    final JSONArray tReadFrom = tObj.getJSONArray("readFrom");
                    ArrayList<ConnectionPool> readFromList = new ArrayList<ConnectionPool>();
                    for (int r = 0; r < tReadFrom.length(); r++) {
                        final String tRead = tReadFrom.getString(r);
                        if (!dbPools.containsKey(tRead)) {
                            throw new Exception(
                                    "the alias '" + tRead + "' is not present in the valid dbAliases. "
                                            + "This alias cannot be used for a cluster.");
                        }
                        //Add the dbAlias to the cluster readFrom list
                        readFromList.add(dbPools.get(tRead));
                    }

                    dbPools.put(tAlias, new JDBCClusteredConnectionPool(tAlias, writeTo, readFromList));
                }
            }
        }

        server = new DBMojoServer(useGzip, serverPort, maxConcReq, dbPools);

    } catch (Exception jsonEx) {
        System.out.println("DBMojoServer: Config error, " + jsonEx);
        System.exit(-1);
    }

    return server;
}

From source file:org.apache.stratos.rest.endpoint.api.StratosApiV41Utils.java

/**
 * This method validates group aliases recursively
 *
 * @param groupsSet - the group collection in which the groups are added to
 * @param groups    - the group collection in which it traverses through
 * @throws RestAPIException//from  ww  w.jav a  2 s.c o  m
 */

private static void validateGroupsRecursively(ConcurrentHashMap<String, CartridgeGroupReferenceBean> groupsSet,
        Collection<CartridgeGroupReferenceBean> groups, boolean hasDeploymentPolicy) throws RestAPIException {

    boolean groupHasDeploymentPolicy = false;

    for (CartridgeGroupReferenceBean group : groups) {
        if (groupsSet.get(group.getAlias()) != null) {
            String message = "Cartridge group alias exists more than once: [group-alias] " + group.getAlias();
            throw new RestAPIException(message);
        }

        if (group.getDeploymentPolicy() != null) {
            if (hasDeploymentPolicy) {
                String message = "Parent group has a deployment policy. Remove deployment policy from the"
                        + " group: [group-alias] " + group.getAlias();
                throw new RestAPIException(message);
            } else {
                groupHasDeploymentPolicy = true;
            }
        } else {
            groupHasDeploymentPolicy = hasDeploymentPolicy;
        }

        if (group.getCartridges() != null) {
            validateCartridgesForDeploymentPolicy(group.getCartridges(), groupHasDeploymentPolicy);
        }

        groupsSet.put(group.getAlias(), group);

        if (group.getGroups() != null) {
            validateGroupsRecursively(groupsSet, group.getGroups(), groupHasDeploymentPolicy);
        }
    }
}

From source file:org.apache.stratos.rest.endpoint.api.StratosApiV41Utils.java

/**
 * This method is to validate the application definition to have unique aliases among its groups
 *
 * @param applicationDefinition - the application definition
 * @throws RestAPIException/*w  ww . j a  va 2 s  .c  o  m*/
 */
private static void validateGroupsInApplicationDefinition(ApplicationBean applicationDefinition)
        throws RestAPIException {

    ConcurrentHashMap<String, CartridgeGroupReferenceBean> groupsInApplicationDefinition = new ConcurrentHashMap<String, CartridgeGroupReferenceBean>();
    boolean groupParentHasDeploymentPolicy = false;

    if ((applicationDefinition.getComponents().getGroups() != null)
            && (!applicationDefinition.getComponents().getGroups().isEmpty())) {

        //This is to validate the top level groups in the application definition
        for (CartridgeGroupReferenceBean group : applicationDefinition.getComponents().getGroups()) {
            if (groupsInApplicationDefinition.get(group.getAlias()) != null) {
                String message = "Cartridge group alias exists more than once: [group-alias] "
                        + group.getAlias();
                throw new RestAPIException(message);
            }

            // Validate top level group deployment policy with cartridges
            if (group.getCartridges() != null) {
                if (group.getDeploymentPolicy() != null) {
                    groupParentHasDeploymentPolicy = true;
                }
                validateCartridgesForDeploymentPolicy(group.getCartridges(), groupParentHasDeploymentPolicy);
            }

            groupsInApplicationDefinition.put(group.getAlias(), group);

            if (group.getGroups() != null) {
                //This is to validate the groups aliases recursively
                validateGroupsRecursively(groupsInApplicationDefinition, group.getGroups(),
                        groupParentHasDeploymentPolicy);
            }
        }
    }

    if ((applicationDefinition.getComponents().getCartridges() != null)
            && (!applicationDefinition.getComponents().getCartridges().isEmpty())) {
        validateCartridgesForDeploymentPolicy(applicationDefinition.getComponents().getCartridges(), false);
    }

}

From source file:com.chen.emailsync.SyncManager.java

/**
 * Sent by services indicating that their thread is finished; action depends on the exitStatus
 * of the service.//from  ww  w  . j av a 2 s  .com
 *
 * @param svc the service that is finished
 */
static public void done(AbstractSyncService svc) {
    SyncManager ssm = INSTANCE;
    if (ssm == null)
        return;
    synchronized (sSyncLock) {
        long mailboxId = svc.mMailboxId;
        // If we're no longer the syncing thread for the mailbox, just return
        if (!ssm.isRunningInServiceThread(mailboxId)) {
            return;
        }
        ssm.releaseMailbox(mailboxId);
        ssm.setMailboxSyncStatus(mailboxId, EmailContent.SYNC_STATUS_NONE);

        ConcurrentHashMap<Long, SyncError> errorMap = ssm.mSyncErrorMap;
        SyncError syncError = errorMap.get(mailboxId);

        int exitStatus = svc.mExitStatus;
        Mailbox m = Mailbox.restoreMailboxWithId(ssm, mailboxId);
        if (m == null)
            return;

        if (exitStatus != AbstractSyncService.EXIT_LOGIN_FAILURE) {
            long accountId = m.mAccountKey;
            Account account = Account.restoreAccountWithId(ssm, accountId);
            if (account == null)
                return;
            if (ssm.releaseSyncHolds(ssm, AbstractSyncService.EXIT_LOGIN_FAILURE, account)) {
                new AccountServiceProxy(ssm).notifyLoginSucceeded(accountId);
            }
        }

        int lastResult = EmailContent.LAST_SYNC_RESULT_SUCCESS;
        // For error states, whether the error is fatal (won't automatically be retried)
        boolean errorIsFatal = true;
        try {
            switch (exitStatus) {
            case AbstractSyncService.EXIT_DONE:
                if (svc.hasPendingRequests()) {
                    // TODO Handle this case
                }
                errorMap.remove(mailboxId);
                // If we've had a successful sync, clear the shutdown count
                synchronized (SyncManager.class) {
                    sClientConnectionManagerShutdownCount = 0;
                }
                // Leave now; other statuses are errors
                return;
            // I/O errors get retried at increasing intervals
            case AbstractSyncService.EXIT_IO_ERROR:
                if (syncError != null) {
                    syncError.escalate();
                    log(m.mDisplayName + " held for " + (syncError.holdDelay / 1000) + "s");
                    return;
                } else {
                    log(m.mDisplayName + " added to syncErrorMap, hold for 15s");
                }
                lastResult = EmailContent.LAST_SYNC_RESULT_CONNECTION_ERROR;
                errorIsFatal = false;
                break;
            // These errors are not retried automatically
            case AbstractSyncService.EXIT_LOGIN_FAILURE:
                new AccountServiceProxy(ssm).notifyLoginFailed(m.mAccountKey, svc.mExitReason);
                lastResult = EmailContent.LAST_SYNC_RESULT_AUTH_ERROR;
                break;
            case AbstractSyncService.EXIT_SECURITY_FAILURE:
            case AbstractSyncService.EXIT_ACCESS_DENIED:
                lastResult = EmailContent.LAST_SYNC_RESULT_SECURITY_ERROR;
                break;
            case AbstractSyncService.EXIT_EXCEPTION:
                lastResult = EmailContent.LAST_SYNC_RESULT_INTERNAL_ERROR;
                break;
            }
            // Add this box to the error map
            errorMap.put(mailboxId, ssm.new SyncError(exitStatus, errorIsFatal));
        } finally {
            // Always set the last result
            ssm.setMailboxLastSyncResult(mailboxId, lastResult);
            kick("sync completed");
        }
    }
}

From source file:org.telegram.android.MessagesController.java

public boolean processUpdateArray(ArrayList<TLRPC.Update> updates, final ArrayList<TLRPC.User> usersArr,
        final ArrayList<TLRPC.Chat> chatsArr) {
    if (updates.isEmpty()) {
        return true;
    }//www .j  a  va  2s .  co m
    long currentTime = System.currentTimeMillis();

    final HashMap<Long, ArrayList<MessageObject>> messages = new HashMap<>();
    final HashMap<Long, TLRPC.WebPage> webPages = new HashMap<>();
    final ArrayList<MessageObject> pushMessages = new ArrayList<>();
    final ArrayList<TLRPC.Message> messagesArr = new ArrayList<>();
    final HashMap<Integer, Integer> markAsReadMessagesInbox = new HashMap<>();
    final HashMap<Integer, Integer> markAsReadMessagesOutbox = new HashMap<>();
    final ArrayList<Integer> markAsReadMessages = new ArrayList<>();
    final HashMap<Integer, Integer> markAsReadEncrypted = new HashMap<>();
    final ArrayList<Integer> deletedMessages = new ArrayList<>();
    boolean printChanged = false;
    final ArrayList<TLRPC.ChatParticipants> chatInfoToUpdate = new ArrayList<>();
    final ArrayList<TLRPC.Update> updatesOnMainThread = new ArrayList<>();
    final ArrayList<TLRPC.TL_updateEncryptedMessagesRead> tasks = new ArrayList<>();
    final ArrayList<Integer> contactsIds = new ArrayList<>();

    boolean checkForUsers = true;
    ConcurrentHashMap<Integer, TLRPC.User> usersDict;
    ConcurrentHashMap<Integer, TLRPC.Chat> chatsDict;
    if (usersArr != null) {
        usersDict = new ConcurrentHashMap<>();
        for (TLRPC.User user : usersArr) {
            usersDict.put(user.id, user);
        }
    } else {
        checkForUsers = false;
        usersDict = users;
    }
    if (chatsArr != null) {
        chatsDict = new ConcurrentHashMap<>();
        for (TLRPC.Chat chat : chatsArr) {
            chatsDict.put(chat.id, chat);
        }
    } else {
        checkForUsers = false;
        chatsDict = chats;
    }

    if (usersArr != null || chatsArr != null) {
        AndroidUtilities.runOnUIThread(new Runnable() {
            @Override
            public void run() {
                putUsers(usersArr, false);
                putChats(chatsArr, false);
            }
        });
    }

    int interfaceUpdateMask = 0;

    for (TLRPC.Update update : updates) {
        if (update instanceof TLRPC.TL_updateNewMessage) {
            TLRPC.TL_updateNewMessage upd = (TLRPC.TL_updateNewMessage) update;
            if (checkForUsers) {
                TLRPC.User user = getUser(upd.message.from_id);
                if (usersDict.get(upd.message.from_id) == null && user == null
                        || upd.message.to_id.chat_id != 0 && chatsDict.get(upd.message.to_id.chat_id) == null
                                && getChat(upd.message.to_id.chat_id) == null) {
                    return false;
                }

                if (user != null && user.status != null && user.status.expires <= 0) {
                    onlinePrivacy.put(upd.message.from_id, ConnectionsManager.getInstance().getCurrentTime());
                    interfaceUpdateMask |= UPDATE_MASK_STATUS;
                }
            }
            messagesArr.add(upd.message);
            ImageLoader.saveMessageThumbs(upd.message);
            MessageObject obj = new MessageObject(upd.message, usersDict, true);
            if (obj.type == 11) {
                interfaceUpdateMask |= UPDATE_MASK_CHAT_AVATAR;
            } else if (obj.type == 10) {
                interfaceUpdateMask |= UPDATE_MASK_CHAT_NAME;
            }
            long uid;
            if (upd.message.to_id.chat_id != 0) {
                uid = -upd.message.to_id.chat_id;
            } else {
                if (upd.message.to_id.user_id == UserConfig.getClientUserId()) {
                    upd.message.to_id.user_id = upd.message.from_id;
                }
                uid = upd.message.to_id.user_id;
            }
            ArrayList<MessageObject> arr = messages.get(uid);
            if (arr == null) {
                arr = new ArrayList<>();
                messages.put(uid, arr);
            }
            arr.add(obj);
            if (!obj.isOut() && obj.isUnread()) {
                pushMessages.add(obj);
            }
        } else if (update instanceof TLRPC.TL_updateReadMessagesContents) {
            markAsReadMessages.addAll(update.messages);
        } else if (update instanceof TLRPC.TL_updateReadHistoryInbox) {
            TLRPC.Peer peer = ((TLRPC.TL_updateReadHistoryInbox) update).peer;
            if (peer.chat_id != 0) {
                markAsReadMessagesInbox.put(-peer.chat_id, update.max_id);
            } else {
                markAsReadMessagesInbox.put(peer.user_id, update.max_id);
            }
        } else if (update instanceof TLRPC.TL_updateReadHistoryOutbox) {
            TLRPC.Peer peer = ((TLRPC.TL_updateReadHistoryOutbox) update).peer;
            if (peer.chat_id != 0) {
                markAsReadMessagesOutbox.put(-peer.chat_id, update.max_id);
            } else {
                markAsReadMessagesOutbox.put(peer.user_id, update.max_id);
            }
        } else if (update instanceof TLRPC.TL_updateDeleteMessages) {
            deletedMessages.addAll(update.messages);
        } else if (update instanceof TLRPC.TL_updateUserTyping
                || update instanceof TLRPC.TL_updateChatUserTyping) {
            if (update.user_id != UserConfig.getClientUserId()) {
                long uid = -update.chat_id;
                if (uid == 0) {
                    uid = update.user_id;
                }
                ArrayList<PrintingUser> arr = printingUsers.get(uid);
                if (update.action instanceof TLRPC.TL_sendMessageCancelAction) {
                    if (arr != null) {
                        for (int a = 0; a < arr.size(); a++) {
                            PrintingUser pu = arr.get(a);
                            if (pu.userId == update.user_id) {
                                arr.remove(a);
                                printChanged = true;
                                break;
                            }
                        }
                        if (arr.isEmpty()) {
                            printingUsers.remove(uid);
                        }
                    }
                } else {
                    if (arr == null) {
                        arr = new ArrayList<>();
                        printingUsers.put(uid, arr);
                    }
                    boolean exist = false;
                    for (PrintingUser u : arr) {
                        if (u.userId == update.user_id) {
                            exist = true;
                            u.lastTime = currentTime;
                            u.action = update.action;
                            break;
                        }
                    }
                    if (!exist) {
                        PrintingUser newUser = new PrintingUser();
                        newUser.userId = update.user_id;
                        newUser.lastTime = currentTime;
                        newUser.action = update.action;
                        arr.add(newUser);
                        printChanged = true;
                    }
                }
                onlinePrivacy.put(update.user_id, ConnectionsManager.getInstance().getCurrentTime());
            }
        } else if (update instanceof TLRPC.TL_updateChatParticipants) {
            interfaceUpdateMask |= UPDATE_MASK_CHAT_MEMBERS;
            chatInfoToUpdate.add(update.participants);
        } else if (update instanceof TLRPC.TL_updateUserStatus) {
            interfaceUpdateMask |= UPDATE_MASK_STATUS;
            updatesOnMainThread.add(update);
        } else if (update instanceof TLRPC.TL_updateUserName) {
            interfaceUpdateMask |= UPDATE_MASK_NAME;
            updatesOnMainThread.add(update);
        } else if (update instanceof TLRPC.TL_updateUserPhoto) {
            interfaceUpdateMask |= UPDATE_MASK_AVATAR;
            MessagesStorage.getInstance().clearUserPhotos(update.user_id);
            updatesOnMainThread.add(update);
        } else if (update instanceof TLRPC.TL_updateUserPhone) {
            interfaceUpdateMask |= UPDATE_MASK_PHONE;
            updatesOnMainThread.add(update);
        } else if (update instanceof TLRPC.TL_updateContactRegistered) {
            if (enableJoined && usersDict.containsKey(update.user_id)) {
                TLRPC.TL_messageService newMessage = new TLRPC.TL_messageService();
                newMessage.action = new TLRPC.TL_messageActionUserJoined();
                newMessage.local_id = newMessage.id = UserConfig.getNewMessageId();
                UserConfig.saveConfig(false);
                newMessage.flags = TLRPC.MESSAGE_FLAG_UNREAD;
                newMessage.date = update.date;
                newMessage.from_id = update.user_id;
                newMessage.to_id = new TLRPC.TL_peerUser();
                newMessage.to_id.user_id = UserConfig.getClientUserId();
                newMessage.dialog_id = update.user_id;

                messagesArr.add(newMessage);
                MessageObject obj = new MessageObject(newMessage, usersDict, true);
                ArrayList<MessageObject> arr = messages.get(newMessage.dialog_id);
                if (arr == null) {
                    arr = new ArrayList<>();
                    messages.put(newMessage.dialog_id, arr);
                }
                arr.add(obj);
                pushMessages.add(obj);
            }
        } else if (update instanceof TLRPC.TL_updateContactLink) {
            if (update.my_link instanceof TLRPC.TL_contactLinkContact) {
                int idx = contactsIds.indexOf(-update.user_id);
                if (idx != -1) {
                    contactsIds.remove(idx);
                }
                if (!contactsIds.contains(update.user_id)) {
                    contactsIds.add(update.user_id);
                }
            } else {
                int idx = contactsIds.indexOf(update.user_id);
                if (idx != -1) {
                    contactsIds.remove(idx);
                }
                if (!contactsIds.contains(update.user_id)) {
                    contactsIds.add(-update.user_id);
                }
            }
        } else if (update instanceof TLRPC.TL_updateNewAuthorization) {
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    NotificationCenter.getInstance()
                            .postNotificationName(NotificationCenter.newSessionReceived);
                }
            });
            TLRPC.TL_messageService newMessage = new TLRPC.TL_messageService();
            newMessage.action = new TLRPC.TL_messageActionLoginUnknownLocation();
            newMessage.action.title = update.device;
            newMessage.action.address = update.location;
            newMessage.local_id = newMessage.id = UserConfig.getNewMessageId();
            UserConfig.saveConfig(false);
            newMessage.flags = TLRPC.MESSAGE_FLAG_UNREAD;
            newMessage.date = update.date;
            newMessage.from_id = 777000;
            newMessage.to_id = new TLRPC.TL_peerUser();
            newMessage.to_id.user_id = UserConfig.getClientUserId();
            newMessage.dialog_id = 777000;

            messagesArr.add(newMessage);
            MessageObject obj = new MessageObject(newMessage, usersDict, true);
            ArrayList<MessageObject> arr = messages.get(newMessage.dialog_id);
            if (arr == null) {
                arr = new ArrayList<>();
                messages.put(newMessage.dialog_id, arr);
            }
            arr.add(obj);
            pushMessages.add(obj);
        } else if (update instanceof TLRPC.TL_updateNewGeoChatMessage) {
            //DEPRECATED
        } else if (update instanceof TLRPC.TL_updateNewEncryptedMessage) {
            ArrayList<TLRPC.Message> decryptedMessages = SecretChatHelper.getInstance()
                    .decryptMessage(((TLRPC.TL_updateNewEncryptedMessage) update).message);
            if (decryptedMessages != null && !decryptedMessages.isEmpty()) {
                int cid = ((TLRPC.TL_updateNewEncryptedMessage) update).message.chat_id;
                long uid = ((long) cid) << 32;
                ArrayList<MessageObject> arr = messages.get(uid);
                if (arr == null) {
                    arr = new ArrayList<>();
                    messages.put(uid, arr);
                }
                for (TLRPC.Message message : decryptedMessages) {
                    ImageLoader.saveMessageThumbs(message);
                    messagesArr.add(message);
                    MessageObject obj = new MessageObject(message, usersDict, true);
                    arr.add(obj);
                    pushMessages.add(obj);
                }
            }
        } else if (update instanceof TLRPC.TL_updateEncryptedChatTyping) {
            TLRPC.EncryptedChat encryptedChat = getEncryptedChatDB(update.chat_id);
            if (encryptedChat != null) {
                update.user_id = encryptedChat.user_id;
                long uid = ((long) update.chat_id) << 32;
                ArrayList<PrintingUser> arr = printingUsers.get(uid);
                if (arr == null) {
                    arr = new ArrayList<>();
                    printingUsers.put(uid, arr);
                }
                boolean exist = false;
                for (PrintingUser u : arr) {
                    if (u.userId == update.user_id) {
                        exist = true;
                        u.lastTime = currentTime;
                        u.action = new TLRPC.TL_sendMessageTypingAction();
                        break;
                    }
                }
                if (!exist) {
                    PrintingUser newUser = new PrintingUser();
                    newUser.userId = update.user_id;
                    newUser.lastTime = currentTime;
                    newUser.action = new TLRPC.TL_sendMessageTypingAction();
                    arr.add(newUser);
                    printChanged = true;
                }
                onlinePrivacy.put(update.user_id, ConnectionsManager.getInstance().getCurrentTime());
            }
        } else if (update instanceof TLRPC.TL_updateEncryptedMessagesRead) {
            markAsReadEncrypted.put(update.chat_id, Math.max(update.max_date, update.date));
            tasks.add((TLRPC.TL_updateEncryptedMessagesRead) update);
        } else if (update instanceof TLRPC.TL_updateChatParticipantAdd) {
            MessagesStorage.getInstance().updateChatInfo(update.chat_id, update.user_id, false,
                    update.inviter_id, update.version);
        } else if (update instanceof TLRPC.TL_updateChatParticipantDelete) {
            MessagesStorage.getInstance().updateChatInfo(update.chat_id, update.user_id, true, 0,
                    update.version);
        } else if (update instanceof TLRPC.TL_updateDcOptions) {
            ConnectionsManager.getInstance().updateDcSettings(0);
        } else if (update instanceof TLRPC.TL_updateEncryption) {
            SecretChatHelper.getInstance().processUpdateEncryption((TLRPC.TL_updateEncryption) update,
                    usersDict);
        } else if (update instanceof TLRPC.TL_updateUserBlocked) {
            final TLRPC.TL_updateUserBlocked finalUpdate = (TLRPC.TL_updateUserBlocked) update;
            if (finalUpdate.blocked) {
                ArrayList<Integer> ids = new ArrayList<>();
                ids.add(finalUpdate.user_id);
                MessagesStorage.getInstance().putBlockedUsers(ids, false);
            } else {
                MessagesStorage.getInstance().deleteBlockedUser(finalUpdate.user_id);
            }
            MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
                @Override
                public void run() {
                    AndroidUtilities.runOnUIThread(new Runnable() {
                        @Override
                        public void run() {
                            if (finalUpdate.blocked) {
                                if (!blockedUsers.contains(finalUpdate.user_id)) {
                                    blockedUsers.add(finalUpdate.user_id);
                                }
                            } else {
                                blockedUsers.remove((Integer) finalUpdate.user_id);
                            }
                            NotificationCenter.getInstance()
                                    .postNotificationName(NotificationCenter.blockedUsersDidLoaded);
                        }
                    });
                }
            });
        } else if (update instanceof TLRPC.TL_updateNotifySettings) {
            updatesOnMainThread.add(update);
        } else if (update instanceof TLRPC.TL_updateServiceNotification) {
            TLRPC.TL_message newMessage = new TLRPC.TL_message();
            newMessage.local_id = newMessage.id = UserConfig.getNewMessageId();
            UserConfig.saveConfig(false);
            newMessage.flags = TLRPC.MESSAGE_FLAG_UNREAD;
            newMessage.date = ConnectionsManager.getInstance().getCurrentTime();
            newMessage.from_id = 777000;
            newMessage.to_id = new TLRPC.TL_peerUser();
            newMessage.to_id.user_id = UserConfig.getClientUserId();
            newMessage.dialog_id = 777000;
            newMessage.media = update.media;
            newMessage.message = ((TLRPC.TL_updateServiceNotification) update).message;

            messagesArr.add(newMessage);
            MessageObject obj = new MessageObject(newMessage, usersDict, true);
            ArrayList<MessageObject> arr = messages.get(newMessage.dialog_id);
            if (arr == null) {
                arr = new ArrayList<>();
                messages.put(newMessage.dialog_id, arr);
            }
            arr.add(obj);
            pushMessages.add(obj);
        } else if (update instanceof TLRPC.TL_updatePrivacy) {
            updatesOnMainThread.add(update);
        } else if (update instanceof TLRPC.TL_updateWebPage) {
            webPages.put(update.webpage.id, update.webpage);
        }
    }
    if (!messages.isEmpty()) {
        for (HashMap.Entry<Long, ArrayList<MessageObject>> pair : messages.entrySet()) {
            Long key = pair.getKey();
            ArrayList<MessageObject> value = pair.getValue();
            if (updatePrintingUsersWithNewMessages(key, value)) {
                printChanged = true;
            }
        }
    }

    if (printChanged) {
        updatePrintingStrings();
    }

    final int interfaceUpdateMaskFinal = interfaceUpdateMask;
    final boolean printChangedArg = printChanged;

    if (!contactsIds.isEmpty()) {
        ContactsController.getInstance().processContactsUpdates(contactsIds, usersDict);
    }

    MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
        @Override
        public void run() {
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    if (!pushMessages.isEmpty()) {
                        NotificationsController.getInstance().processNewMessages(pushMessages, true);
                    }
                }
            });
        }
    });

    if (!messagesArr.isEmpty()) {
        MessagesStorage.getInstance().putMessages(messagesArr, true, true, false,
                MediaController.getInstance().getAutodownloadMask());
    }

    AndroidUtilities.runOnUIThread(new Runnable() {
        @Override
        public void run() {
            int updateMask = interfaceUpdateMaskFinal;

            boolean avatarsUpdate = false;
            if (!updatesOnMainThread.isEmpty()) {
                ArrayList<TLRPC.User> dbUsers = new ArrayList<>();
                ArrayList<TLRPC.User> dbUsersStatus = new ArrayList<>();
                SharedPreferences.Editor editor = null;
                for (TLRPC.Update update : updatesOnMainThread) {
                    final TLRPC.User toDbUser = new TLRPC.User();
                    toDbUser.id = update.user_id;
                    final TLRPC.User currentUser = getUser(update.user_id);
                    if (update instanceof TLRPC.TL_updatePrivacy) {
                        if (update.key instanceof TLRPC.TL_privacyKeyStatusTimestamp) {
                            ContactsController.getInstance().setPrivacyRules(update.rules);
                        }
                    } else if (update instanceof TLRPC.TL_updateUserStatus) {
                        if (update.status instanceof TLRPC.TL_userStatusRecently) {
                            update.status.expires = -100;
                        } else if (update.status instanceof TLRPC.TL_userStatusLastWeek) {
                            update.status.expires = -101;
                        } else if (update.status instanceof TLRPC.TL_userStatusLastMonth) {
                            update.status.expires = -102;
                        }
                        if (currentUser != null) {
                            currentUser.id = update.user_id;
                            currentUser.status = update.status;
                        }
                        toDbUser.status = update.status;
                        dbUsersStatus.add(toDbUser);
                        if (update.user_id == UserConfig.getClientUserId()) {
                            NotificationsController.getInstance()
                                    .setLastOnlineFromOtherDevice(update.status.expires);
                        }
                    } else if (update instanceof TLRPC.TL_updateUserName) {
                        if (currentUser != null) {
                            if (!(currentUser instanceof TLRPC.TL_userContact)) {
                                currentUser.first_name = update.first_name;
                                currentUser.last_name = update.last_name;
                            }
                            if (currentUser.username != null && currentUser.username.length() > 0) {
                                usersByUsernames.remove(currentUser.username);
                            }
                            if (update.username != null && update.username.length() > 0) {
                                usersByUsernames.put(update.username, currentUser);
                            }
                            currentUser.username = update.username;
                        }
                        toDbUser.first_name = update.first_name;
                        toDbUser.last_name = update.last_name;
                        toDbUser.username = update.username;
                        dbUsers.add(toDbUser);
                    } else if (update instanceof TLRPC.TL_updateUserPhoto) {
                        if (currentUser != null) {
                            currentUser.photo = update.photo;
                        }
                        avatarsUpdate = true;
                        toDbUser.photo = update.photo;
                        dbUsers.add(toDbUser);
                    } else if (update instanceof TLRPC.TL_updateUserPhone) {
                        if (currentUser != null) {
                            currentUser.phone = update.phone;
                            Utilities.phoneBookQueue.postRunnable(new Runnable() {
                                @Override
                                public void run() {
                                    ContactsController.getInstance().addContactToPhoneBook(currentUser, true);
                                }
                            });
                        }
                        toDbUser.phone = update.phone;
                        dbUsers.add(toDbUser);
                    } else if (update instanceof TLRPC.TL_updateNotifySettings) {
                        if (update.notify_settings instanceof TLRPC.TL_peerNotifySettings
                                && update.peer instanceof TLRPC.TL_notifyPeer) {
                            if (editor == null) {
                                SharedPreferences preferences = ApplicationLoader.applicationContext
                                        .getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
                                editor = preferences.edit();
                            }
                            long dialog_id = update.peer.peer.user_id;
                            if (dialog_id == 0) {
                                dialog_id = -update.peer.peer.chat_id;
                            }
                            TLRPC.TL_dialog dialog = dialogs_dict.get(dialog_id);
                            if (dialog != null) {
                                dialog.notify_settings = update.notify_settings;
                            }
                            if (update.notify_settings.mute_until > ConnectionsManager.getInstance()
                                    .getCurrentTime()) {
                                int until = 0;
                                if (update.notify_settings.mute_until > ConnectionsManager.getInstance()
                                        .getCurrentTime() + 60 * 60 * 24 * 365) {
                                    editor.putInt("notify2_" + dialog_id, 2);
                                    if (dialog != null) {
                                        dialog.notify_settings.mute_until = Integer.MAX_VALUE;
                                    }
                                } else {
                                    until = update.notify_settings.mute_until;
                                    editor.putInt("notify2_" + dialog_id, 3);
                                    editor.putInt("notifyuntil_" + dialog_id,
                                            update.notify_settings.mute_until);
                                    if (dialog != null) {
                                        dialog.notify_settings.mute_until = until;
                                    }
                                }
                                MessagesStorage.getInstance().setDialogFlags(dialog_id,
                                        ((long) until << 32) | 1);
                            } else {
                                if (dialog != null) {
                                    dialog.notify_settings.mute_until = 0;
                                }
                                editor.remove("notify2_" + dialog_id);
                                MessagesStorage.getInstance().setDialogFlags(dialog_id, 0);
                            }

                        } /* else if (update.peer instanceof TLRPC.TL_notifyChats) { disable global settings sync
                          if (editor == null) {
                              SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
                              editor = preferences.edit();
                          }
                          editor.putBoolean("EnableGroup", update.notify_settings.mute_until == 0);
                          editor.putBoolean("EnablePreviewGroup", update.notify_settings.show_previews);
                          } else if (update.peer instanceof TLRPC.TL_notifyUsers) {
                          if (editor == null) {
                              SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
                              editor = preferences.edit();
                          }
                          editor.putBoolean("EnableAll", update.notify_settings.mute_until == 0);
                          editor.putBoolean("EnablePreviewAll", update.notify_settings.show_previews);
                          }*/
                    }
                }
                if (editor != null) {
                    editor.commit();
                    NotificationCenter.getInstance()
                            .postNotificationName(NotificationCenter.notificationsSettingsUpdated);
                }
                MessagesStorage.getInstance().updateUsers(dbUsersStatus, true, true, true);
                MessagesStorage.getInstance().updateUsers(dbUsers, false, true, true);
            }

            if (!webPages.isEmpty()) {
                NotificationCenter.getInstance()
                        .postNotificationName(NotificationCenter.didReceivedWebpagesInUpdates, webPages);
            }

            if (!messages.isEmpty()) {
                for (HashMap.Entry<Long, ArrayList<MessageObject>> entry : messages.entrySet()) {
                    Long key = entry.getKey();
                    ArrayList<MessageObject> value = entry.getValue();
                    updateInterfaceWithMessages(key, value);
                }
                NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
            }
            if (printChangedArg) {
                updateMask |= UPDATE_MASK_USER_PRINT;
            }
            if (!contactsIds.isEmpty()) {
                updateMask |= UPDATE_MASK_NAME;
                updateMask |= UPDATE_MASK_USER_PHONE;
            }
            if (!chatInfoToUpdate.isEmpty()) {
                for (TLRPC.ChatParticipants info : chatInfoToUpdate) {
                    MessagesStorage.getInstance().updateChatInfo(info.chat_id, info, true);
                    NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatInfoDidLoaded,
                            info.chat_id, info);
                }
            }
            if (updateMask != 0) {
                NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces,
                        updateMask);
            }
        }
    });

    MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
        @Override
        public void run() {
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    int updateMask = 0;
                    if (!markAsReadMessagesInbox.isEmpty() || !markAsReadMessagesOutbox.isEmpty()) {
                        NotificationCenter.getInstance().postNotificationName(NotificationCenter.messagesRead,
                                markAsReadMessagesInbox, markAsReadMessagesOutbox);
                        NotificationsController.getInstance().processReadMessages(markAsReadMessagesInbox, 0, 0,
                                0, false);
                        for (HashMap.Entry<Integer, Integer> entry : markAsReadMessagesInbox.entrySet()) {
                            TLRPC.TL_dialog dialog = dialogs_dict.get((long) entry.getKey());
                            if (dialog != null && dialog.top_message <= entry.getValue()) {
                                MessageObject obj = dialogMessage.get(dialog.top_message);
                                if (obj != null) {
                                    obj.setIsRead();
                                    updateMask |= UPDATE_MASK_READ_DIALOG_MESSAGE;
                                }
                            }
                        }
                        for (HashMap.Entry<Integer, Integer> entry : markAsReadMessagesOutbox.entrySet()) {
                            TLRPC.TL_dialog dialog = dialogs_dict.get((long) entry.getKey());
                            if (dialog != null && dialog.top_message <= entry.getValue()) {
                                MessageObject obj = dialogMessage.get(dialog.top_message);
                                if (obj != null) {
                                    obj.setIsRead();
                                    updateMask |= UPDATE_MASK_READ_DIALOG_MESSAGE;
                                }
                            }
                        }
                    }
                    if (!markAsReadEncrypted.isEmpty()) {
                        for (HashMap.Entry<Integer, Integer> entry : markAsReadEncrypted.entrySet()) {
                            NotificationCenter.getInstance().postNotificationName(
                                    NotificationCenter.messagesReadEncrypted, entry.getKey(), entry.getValue());
                            long dialog_id = (long) (entry.getKey()) << 32;
                            TLRPC.TL_dialog dialog = dialogs_dict.get(dialog_id);
                            if (dialog != null) {
                                MessageObject message = dialogMessage.get(dialog.top_message);
                                if (message != null && message.messageOwner.date <= entry.getValue()) {
                                    message.setIsRead();
                                    updateMask |= UPDATE_MASK_READ_DIALOG_MESSAGE;
                                }
                            }
                        }
                    }
                    if (!markAsReadMessages.isEmpty()) {
                        NotificationCenter.getInstance().postNotificationName(
                                NotificationCenter.messagesReadContent, markAsReadMessages);
                    }
                    if (!deletedMessages.isEmpty()) {
                        NotificationCenter.getInstance()
                                .postNotificationName(NotificationCenter.messagesDeleted, deletedMessages);
                        for (Integer id : deletedMessages) {
                            MessageObject obj = dialogMessage.get(id);
                            if (obj != null) {
                                obj.deleted = true;
                            }
                        }
                    }
                    if (updateMask != 0) {
                        NotificationCenter.getInstance()
                                .postNotificationName(NotificationCenter.updateInterfaces, updateMask);
                    }
                }
            });
        }
    });

    if (!webPages.isEmpty()) {
        MessagesStorage.getInstance().putWebPages(webPages);
    }
    if (!markAsReadMessagesInbox.isEmpty() || !markAsReadMessagesOutbox.isEmpty()
            || !markAsReadEncrypted.isEmpty()) {
        if (!markAsReadMessagesInbox.isEmpty() || !markAsReadMessagesOutbox.isEmpty()) {
            MessagesStorage.getInstance().updateDialogsWithReadedMessages(markAsReadMessagesInbox, true);
        }
        MessagesStorage.getInstance().markMessagesAsRead(markAsReadMessagesInbox, markAsReadMessagesOutbox,
                markAsReadEncrypted, true);
    }
    if (!markAsReadMessages.isEmpty()) {
        MessagesStorage.getInstance().markMessagesContentAsRead(markAsReadMessages);
    }
    if (!deletedMessages.isEmpty()) {
        MessagesStorage.getInstance().markMessagesAsDeleted(deletedMessages, true);
    }
    if (!deletedMessages.isEmpty()) {
        MessagesStorage.getInstance().updateDialogsWithDeletedMessages(deletedMessages, true);
    }
    if (!tasks.isEmpty()) {
        for (TLRPC.TL_updateEncryptedMessagesRead update : tasks) {
            MessagesStorage.getInstance().createTaskForSecretChat(update.chat_id, update.max_date, update.date,
                    1, null);
        }
    }

    return true;
}

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

@Override
public void fileChanged(FileChangeEvent arg0) throws Exception {
    try {//from w w  w.j a va  2s  .  c  om
        FileObject baseFile = arg0.getFile();
        EJBContext ejbContext;
        if (baseFile.getName().getURI().endsWith(".jar")) {
            fileDeleted(arg0);
            URLClassLoader classLoader = new URLClassLoader(new URL[] { new URL(baseFile.getName().getURI()) },
                    Thread.currentThread().getContextClassLoader());
            ConfigurationBuilder config = new ConfigurationBuilder();
            config.addUrls(ClasspathHelper.forClassLoader(classLoader));
            config.addClassLoader(classLoader);
            org.reflections.Reflections reflections = new org.reflections.Reflections(config);
            EJBContainer container = EJBContainer.getInstance(baseFile.getName().getURI(), config);
            container.inject();
            Set<Class<?>> cls = reflections.getTypesAnnotatedWith(Stateless.class);
            Set<Class<?>> clsMessageDriven = reflections.getTypesAnnotatedWith(MessageDriven.class);
            Object obj;
            System.gc();
            if (cls.size() > 0) {
                ejbContext = new EJBContext();
                ejbContext.setJarPath(baseFile.getName().getURI());
                ejbContext.setJarDeployed(baseFile.getName().getBaseName());
                for (Class<?> ejbInterface : cls) {
                    //BeanPool.getInstance().create(ejbInterface);
                    obj = BeanPool.getInstance().get(ejbInterface);
                    System.out.println(obj);
                    ProxyFactory factory = new ProxyFactory();
                    obj = UnicastRemoteObject.exportObject((Remote) factory.createWithBean(obj),
                            servicesRegistryPort);
                    String remoteBinding = container.getRemoteBinding(ejbInterface);
                    System.out.println(remoteBinding + " for EJB" + obj);
                    if (remoteBinding != null) {
                        //registry.unbind(remoteBinding);
                        registry.rebind(remoteBinding, (Remote) obj);
                        ejbContext.put(remoteBinding, obj.getClass());
                    }
                    //registry.rebind("name", (Remote) obj);
                }
                jarEJBMap.put(baseFile.getName().getURI(), ejbContext);
            }
            System.out.println("Class Message Driven" + clsMessageDriven);
            System.out.println("Class Message Driven" + clsMessageDriven);
            if (clsMessageDriven.size() > 0) {
                System.out.println("Class Message Driven");
                MDBContext mdbContext;
                ConcurrentHashMap<String, MDBContext> mdbContexts;
                if (jarMDBMap.get(baseFile.getName().getURI()) != null) {
                    mdbContexts = jarMDBMap.get(baseFile.getName().getURI());
                } else {
                    mdbContexts = new ConcurrentHashMap<String, MDBContext>();
                }
                jarMDBMap.put(baseFile.getName().getURI(), 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("/", "."));
                    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) {
                                    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) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            classLoader.close();
            System.out.println(baseFile.getName().getURI() + " Deployed");
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

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

@Override
public void fileCreated(FileChangeEvent arg0) throws Exception {
    try {/*from   w ww .  j  av  a2  s .  c o  m*/
        FileObject baseFile = arg0.getFile();
        EJBContext ejbContext;
        if (baseFile.getName().getURI().endsWith(".jar")) {
            System.out.println(baseFile.getName().getURI());
            URLClassLoader classLoader = new URLClassLoader(new URL[] { new URL(baseFile.getName().getURI()) },
                    Thread.currentThread().getContextClassLoader());
            ConfigurationBuilder config = new ConfigurationBuilder();
            config.addUrls(ClasspathHelper.forClassLoader(classLoader));
            config.addClassLoader(classLoader);
            org.reflections.Reflections reflections = new org.reflections.Reflections(config);
            EJBContainer container = EJBContainer.getInstance(baseFile.getName().getURI(), config);
            container.inject();
            Set<Class<?>> clsStateless = reflections.getTypesAnnotatedWith(Stateless.class);
            Set<Class<?>> clsMessageDriven = reflections.getTypesAnnotatedWith(MessageDriven.class);
            Object obj;
            System.gc();
            if (clsStateless.size() > 0) {
                ejbContext = new EJBContext();
                ejbContext.setJarPath(baseFile.getName().getURI());
                ejbContext.setJarDeployed(baseFile.getName().getBaseName());
                for (Class<?> ejbInterface : clsStateless) {
                    //BeanPool.getInstance().create(ejbInterface);
                    obj = BeanPool.getInstance().get(ejbInterface);
                    System.out.println(obj);
                    ProxyFactory factory = new ProxyFactory();
                    obj = UnicastRemoteObject.exportObject((Remote) factory.createWithBean(obj),
                            servicesRegistryPort);
                    String remoteBinding = container.getRemoteBinding(ejbInterface);
                    System.out.println(remoteBinding + " for EJB" + obj);
                    if (remoteBinding != null) {
                        //registry.unbind(remoteBinding);
                        registry.rebind(remoteBinding, (Remote) obj);
                        ejbContext.put(remoteBinding, obj.getClass());
                    }
                    //registry.rebind("name", (Remote) obj);
                }
                jarEJBMap.put(baseFile.getName().getURI(), ejbContext);
            }
            System.out.println("Class Message Driven" + clsMessageDriven);
            System.out.println("Class Message Driven" + clsMessageDriven);
            if (clsMessageDriven.size() > 0) {
                System.out.println("Class Message Driven");
                MDBContext mdbContext;
                ConcurrentHashMap<String, MDBContext> mdbContexts;
                if (jarMDBMap.get(baseFile.getName().getURI()) != null) {
                    mdbContexts = jarMDBMap.get(baseFile.getName().getURI());
                } else {
                    mdbContexts = new ConcurrentHashMap<String, MDBContext>();
                }
                jarMDBMap.put(baseFile.getName().getURI(), 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("/", "."));
                    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) {
                                    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) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            classLoader.close();
        }
        System.out.println(baseFile.getName().getURI() + " Deployed");
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

From source file:structuredPredictionNLG.SFX.java

/**
 * Infers the feature/cost vectors for the content and word actions.
 * @return The feature/cost vectors for the content and word actions
 *///w w w  .  j a va 2 s .c  o m
public Object[] inferFeatureAndCostVectors() {
    ConcurrentHashMap<DatasetInstance, HashMap<String, ArrayList<Instance>>> contentTrainingData = new ConcurrentHashMap<>();
    ConcurrentHashMap<DatasetInstance, HashMap<String, HashMap<String, ArrayList<Instance>>>> wordTrainingData = new ConcurrentHashMap<>();

    if (!getAvailableWordActions().isEmpty() && !getPredicates().isEmpty()) {
        // Initialize collections
        getTrainingData().stream().map((di) -> {
            contentTrainingData.put(di, new HashMap<String, ArrayList<Instance>>());
            return di;
        }).map((di) -> {
            wordTrainingData.put(di, new HashMap<String, HashMap<String, ArrayList<Instance>>>());
            return di;
        }).forEachOrdered((di) -> {
            getPredicates().stream().map((predicate) -> {
                contentTrainingData.get(di).put(predicate, new ArrayList<Instance>());
                return predicate;
            }).map((predicate) -> {
                wordTrainingData.get(di).put(predicate, new HashMap<String, ArrayList<Instance>>());
                return predicate;
            }).forEachOrdered((predicate) -> {
                getAttributes().get(predicate).stream().filter(
                        (attribute) -> (!wordTrainingData.get(di).get(predicate).containsKey(attribute)))
                        .forEachOrdered((attribute) -> {
                            wordTrainingData.get(di).get(predicate).put(attribute, new ArrayList<Instance>());
                        });
            });
        });

        // Infer the vectors in parallel processes to save time
        ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT);
        getTrainingData().forEach((di) -> {
            executor.execute(new InferSFXVectorsThread(di, this, contentTrainingData, wordTrainingData));
        });
        executor.shutdown();
        while (!executor.isTerminated()) {
        }
    }
    Object[] results = new Object[2];
    results[0] = contentTrainingData;
    results[1] = wordTrainingData;
    return results;
}