Example usage for java.util ArrayList toString

List of usage examples for java.util ArrayList toString

Introduction

In this page you can find the example usage for java.util ArrayList toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:org.apache.hadoop.hbase.master.procedure.TestMasterProcedureScheduler.java

/**
 * Verify that "write" operations for a single table are serialized,
 * but different tables can be executed in parallel.
 *//*from   w w  w  .java2 s .com*/
@Test(timeout = 90000)
public void testConcurrentWriteOps() throws Exception {
    final TestTableProcSet procSet = new TestTableProcSet(queue);

    final int NUM_ITEMS = 10;
    final int NUM_TABLES = 4;
    final AtomicInteger opsCount = new AtomicInteger(0);
    for (int i = 0; i < NUM_TABLES; ++i) {
        TableName tableName = TableName.valueOf(String.format("testtb-%04d", i));
        for (int j = 1; j < NUM_ITEMS; ++j) {
            procSet.addBack(new TestTableProcedure(i * 100 + j, tableName,
                    TableProcedureInterface.TableOperationType.EDIT));
            opsCount.incrementAndGet();
        }
    }
    assertEquals(opsCount.get(), queue.size());

    final Thread[] threads = new Thread[NUM_TABLES * 2];
    final HashSet<TableName> concurrentTables = new HashSet<TableName>();
    final ArrayList<String> failures = new ArrayList<String>();
    final AtomicInteger concurrentCount = new AtomicInteger(0);
    for (int i = 0; i < threads.length; ++i) {
        threads[i] = new Thread() {
            @Override
            public void run() {
                while (opsCount.get() > 0) {
                    try {
                        Procedure proc = procSet.acquire();
                        if (proc == null) {
                            queue.signalAll();
                            if (opsCount.get() > 0) {
                                continue;
                            }
                            break;
                        }

                        TableName tableId = procSet.getTableName(proc);
                        synchronized (concurrentTables) {
                            assertTrue("unexpected concurrency on " + tableId, concurrentTables.add(tableId));
                        }
                        assertTrue(opsCount.decrementAndGet() >= 0);
                        try {
                            long procId = proc.getProcId();
                            int concurrent = concurrentCount.incrementAndGet();
                            assertTrue("inc-concurrent=" + concurrent + " 1 <= concurrent <= " + NUM_TABLES,
                                    concurrent >= 1 && concurrent <= NUM_TABLES);
                            LOG.debug("[S] tableId=" + tableId + " procId=" + procId + " concurrent="
                                    + concurrent);
                            Thread.sleep(2000);
                            concurrent = concurrentCount.decrementAndGet();
                            LOG.debug("[E] tableId=" + tableId + " procId=" + procId + " concurrent="
                                    + concurrent);
                            assertTrue("dec-concurrent=" + concurrent, concurrent < NUM_TABLES);
                        } finally {
                            synchronized (concurrentTables) {
                                assertTrue(concurrentTables.remove(tableId));
                            }
                            procSet.release(proc);
                        }
                    } catch (Throwable e) {
                        LOG.error("Failed " + e.getMessage(), e);
                        synchronized (failures) {
                            failures.add(e.getMessage());
                        }
                    } finally {
                        queue.signalAll();
                    }
                }
            }
        };
        threads[i].start();
    }
    for (int i = 0; i < threads.length; ++i) {
        threads[i].join();
    }
    assertTrue(failures.toString(), failures.isEmpty());
    assertEquals(0, opsCount.get());
    assertEquals(0, queue.size());

    for (int i = 1; i <= NUM_TABLES; ++i) {
        TableName table = TableName.valueOf(String.format("testtb-%04d", i));
        assertTrue("queue should be deleted, table=" + table, queue.markTableAsDeleted(table));
    }
}

From source file:org.cesecore.util.CertTools.java

/**
 * Gets a list of all custom OIDs defined in the string. A custom OID is defined as an OID, simply as that. Otherwise, if it is not a custom oid,
 * the DNpart is defined by a name such as CN och rfc822Name. This method only returns a oid once, so if the input string has multiple of the same
 * oid, only one value is returned./*from ww  w  . ja  va2s.  c om*/
 * 
 * @param dn String containing DN, The DN string has the format "C=SE, O=xx, OU=yy, CN=zz", or "rfc822Name=foo@bar.com", etc.
 * @param dnpart String specifying which part of the DN to get, should be "CN" or "OU" etc.
 * 
 * @return ArrayList containing unique oids or empty list if no custom OIDs are present
 */
public static ArrayList<String> getCustomOids(String dn) {
    if (log.isTraceEnabled()) {
        log.trace(">getCustomOids: dn:'" + dn);
    }
    ArrayList<String> parts = new ArrayList<String>();
    if (dn != null) {
        String o;
        X509NameTokenizer xt = new X509NameTokenizer(dn);
        while (xt.hasMoreTokens()) {
            o = xt.nextToken().trim();
            // Try to see if it is a valid OID
            try {
                int i = o.indexOf('=');
                // An oid is never shorter than 3 chars and must start with 1.
                if ((i > 2) && (o.charAt(1) == '.')) {
                    String oid = o.substring(0, i);
                    // If we have multiple of the same custom oid, don't claim that we have more
                    // This method will only return "unique" custom oids.
                    if (!parts.contains(oid)) {
                        // Check if it is a real oid, if it is not we will ignore it (IllegalArgumentException will be thrown)
                        new ASN1ObjectIdentifier(oid);
                        parts.add(oid);
                    }
                }
            } catch (IllegalArgumentException e) {
                // Not a valid oid
            }
        }
    }
    if (log.isTraceEnabled()) {
        log.trace("<getCustomOids: resulting DN part=" + parts.toString());
    }
    return parts;
}

From source file:net.i2cat.csade.life2.backoffice.bl.StatisticsManager.java

/**
 * Returns the number of logins in the last xx days, grouped by day
 * @param days//  w  w  w.j  a  v  a 2  s  . c  o  m
 * @return
 */
public String getDatosConexionesDia(int days, int role, String lng) {
    ObjStats[] st = null;
    String sql;
    ArrayList<Pair> datos = new ArrayList<Pair>();
    Pair p;
    try {
        if (role >= 0 && !"all".equals(lng))
            sql = "SELECT 0 as idStat,count(*) as Event,\"\" as User_login,DATE(dTime) as dTime,0 as duration,\"\" as lat,\"\" as lon,\"\" as device,\"\" as query,0 as lng  FROM (SELECT * FROM  `Stat` INNER JOIN user_profile ON user_profile.Login=`Stat`.User_login AND user_profile.Role="
                    + role + " AND user_profile.Language like '" + lng + "' WHERE event=" + StatsDAO.LOGIN_EVENT
                    + " and DATE(dTime)<=CURDATE() and (DATE(dTime)>DATE_ADD(CURDATE(), INTERVAL -" + days
                    + " DAY)) ) AS t2 GROUP BY DATE(dTime)";
        else if (role >= 0)
            sql = "SELECT 0 as idStat,count(*) as Event,\"\" as User_login,DATE(dTime) as dTime,0 as duration,\"\" as lat,\"\" as lon,\"\" as device,\"\" as query,0 as lng  FROM (SELECT * FROM  `Stat` INNER JOIN user_profile ON user_profile.Login=`Stat`.User_login AND user_profile.Role="
                    + role + " WHERE event=" + StatsDAO.LOGIN_EVENT
                    + " and DATE(dTime)<=CURDATE() and (DATE(dTime)>DATE_ADD(CURDATE(), INTERVAL -" + days
                    + " DAY)) ) AS t2 GROUP BY DATE(dTime)";
        else if (!"all".equals(lng))
            sql = "SELECT 0 as idStat,count(*) as Event,\"\" as User_login,DATE(dTime) as dTime,0 as duration,\"\" as lat,\"\" as lon,\"\" as device,\"\" as query,0 as lng  FROM (SELECT * FROM  `Stat` INNER JOIN user_profile ON user_profile.Login=`Stat`.User_login AND user_profile.Language like '"
                    + lng + "' WHERE event=" + StatsDAO.LOGIN_EVENT
                    + " and DATE(dTime)<=CURDATE() and (DATE(dTime)>DATE_ADD(CURDATE(), INTERVAL -" + days
                    + " DAY)) ) AS t2 GROUP BY DATE(dTime)";
        else
            sql = "SELECT 0 as idStat,count(*) as Event,\"\" as User_login,DATE(dTime) as dTime,0 as duration,\"\" as lat,\"\" as lon,\"\" as device,\"\" as query,0 as lng  FROM (SELECT * FROM  `Stat` WHERE event="
                    + StatsDAO.LOGIN_EVENT
                    + " and DATE(dTime)<=CURDATE() and (DATE(dTime)>DATE_ADD(CURDATE(), INTERVAL -" + days
                    + " DAY)) ) AS t2 GROUP BY DATE(dTime)";

        st = sd.listStatsSQL(sql);
    } catch (RemoteException e) {
        e.printStackTrace();
    } catch (ServiceException e) {

        e.printStackTrace();
    }
    for (int i = 0; i < st.length; i++) {
        datos.add(new Pair(this.weDontSpeakAmericano(st[i].getDTime()), st[i].getIEvent()));
    }

    return datos.toString();
}

From source file:net.i2cat.csade.life2.backoffice.bl.StatisticsManager.java

public String getDatosNewUsersByDay(int days, int role, String lng) {
    ObjStats[] st = null;/*from   w  w  w. j  a v  a2s.  c  o m*/
    ArrayList<Pair> datos = new ArrayList<Pair>();
    Pair p;
    String sql;
    try {
        if (role >= 0 && !"all".equals(lng))
            sql = "SELECT 0 as idStat,count(*) as Event,\"\" as User_login,DATE(dTime) as dTime,0 as duration,\"\" as lat,\"\" as lon,\"\" as device,\"\" as query,0 as lng  FROM (SELECT * FROM  `Stat` INNER JOIN user_profile ON user_profile.Login=`Stat`.User_login AND user_profile.Role="
                    + role + " AND user_profile.Language like '" + lng + "' WHERE event=" + StatsDAO.USER_ADDED
                    + " and DATE(dTime)<=CURDATE() and (DATE(dTime)>DATE_ADD(CURDATE(), INTERVAL -" + days
                    + " DAY)) ) AS t2 GROUP BY DATE(dTime)";
        else if (role >= 0)
            sql = "SELECT 0 as idStat,count(*) as Event,\"\" as User_login,DATE(dTime) as dTime,0 as duration,\"\" as lat,\"\" as lon,\"\" as device,\"\" as query,0 as lng  FROM (SELECT * FROM  `Stat` INNER JOIN user_profile ON user_profile.Login=`Stat`.User_login AND user_profile.Role="
                    + role + " WHERE event=" + StatsDAO.USER_ADDED
                    + " and DATE(dTime)<=CURDATE() and (DATE(dTime)>DATE_ADD(CURDATE(), INTERVAL -" + days
                    + " DAY)) ) AS t2 GROUP BY DATE(dTime)";
        else if (!"all".equals(lng))
            sql = "SELECT 0 as idStat,count(*) as Event,\"\" as User_login,DATE(dTime) as dTime,0 as duration,\"\" as lat,\"\" as lon,\"\" as device,\"\" as query,0 as lng  FROM (SELECT * FROM  `Stat` INNER JOIN user_profile ON user_profile.Login=`Stat`.User_login AND user_profile.Language like '"
                    + lng + "' WHERE event=" + StatsDAO.USER_ADDED
                    + " and DATE(dTime)<=CURDATE() and (DATE(dTime)>DATE_ADD(CURDATE(), INTERVAL -" + days
                    + " DAY)) ) AS t2 GROUP BY DATE(dTime)";
        else
            sql = "SELECT 0 as idStat,count(*) as Event,\"\" as User_login,DATE(dTime) as dTime,0 as duration,\"\" as lat,\"\" as lon,\"\" as device,\"\" as query,0 as lng  FROM (SELECT * FROM  `Stat` WHERE event="
                    + StatsDAO.USER_ADDED
                    + " and DATE(dTime)<=CURDATE() and (DATE(dTime)>DATE_ADD(CURDATE(), INTERVAL -" + days
                    + " DAY)) ) AS t2 GROUP BY DATE(dTime)";
        st = sd.listStatsSQL(sql);
    } catch (RemoteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ServiceException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    for (int i = 0; i < st.length; i++) {
        datos.add(new Pair(this.weDontSpeakAmericano(st[i].getDTime()), st[i].getIEvent()));
    }

    return datos.toString();
}

From source file:bot.UniversalBot.java

@Override
public void run() {

    ArrayList<String> choices = new ArrayList<String>();
    int betAbility = 0;

    System.out.println("[DEBUG] Nick: " + nick);

    JSONArray toSend = new JSONArray();
    JSONObject object;/*from  w w w.j  a  va  2  s.  com*/

    try {
        object = new JSONObject().put("action", "first_connection");
        toSend.put(object);
        object = new JSONObject().put("nick", nick);
        toSend.put(object);
    } catch (JSONException e1) {
        e1.printStackTrace();
    }

    sendData(toSend.toString());

    String wynik;
    JSONArray jsonMainArr;
    JSONObject childJSONObject;

    while (isPlaying && connection) {

        try {
            wynik = in.readLine();
            System.out.println("[DEBUG] Get: " + wynik);

            jsonMainArr = new JSONArray(wynik);

            switch (jsonMainArr.getJSONObject(0).getString("action")) {

            /**
            * Getting cards for the first time from Server. Receiving cards from server.
            */
            case "cards":
                hand.clear();

                for (int i = 1; i < jsonMainArr.length(); i++) {
                    childJSONObject = jsonMainArr.getJSONObject(i);
                    final String rank = childJSONObject.getString("rank");
                    final String suit = childJSONObject.getString("suit");
                    hand.add(new Card(suit, rank));
                }

                betAbility = betAbility(hand) - (pot) / 2;

                System.out.println("[DEBUG] Rka bota " + hand);

                System.out.println("[DEBUG] OTO " + betAbility);

                break;

            /**
             * Overwriting:
             * bet
             * maxBet
             * chips 
             */
            case "bet_change":

                int bet = jsonMainArr.getJSONObject(1).getInt("bet");
                int chips = jsonMainArr.getJSONObject(1).getInt("chips");

                if (bet > maxBet)
                    maxBet = bet;

                if (jsonMainArr.getJSONObject(1).getString("player").equals(nick)) {
                    actualChips = chips;
                    actualBet = bet;
                }
                System.out.println("[DEBUG] Actual maxbet: " + maxBet + " Actual bet: " + actualBet
                        + " Actual chips: " + chips);
                //System.out.println("OTO "+jsonMainArr.getJSONObject(1).getString("player"));

                break;

            case "first_connection":

                chips(jsonMainArr.getJSONObject(1).getInt("chips"),
                        jsonMainArr.getJSONObject(2).getInt("chips"),
                        jsonMainArr.getJSONObject(3).getInt("chips"));

                break;

            /**
             * Sending cards to server.
             */
            case "exchange_cards":

                hand.clear();

                for (int i = 1; i < jsonMainArr.length(); i++) {
                    childJSONObject = jsonMainArr.getJSONObject(i);
                    final String rank = childJSONObject.getString("rank");
                    final String suit = childJSONObject.getString("suit");
                    hand.add(new Card(suit, rank));
                }

                betAbility = betAbility(hand) - (pot) / 2;
                System.out.println("[DEBUG] OTO " + hand);
                break;

            /**
             * Main bot's AI (actually it is ordinary behavior). Order has got the meaning.
             */
            case "available_choices":

                choices.clear(); // czyszcz list z poprzednich moliwoci

                for (int i = 1; i < jsonMainArr.length(); i++) {
                    childJSONObject = jsonMainArr.getJSONObject(i);
                    choices.add(childJSONObject.getString("choice"));
                }

                JSONArray doWyslania = new JSONArray();

                System.out.println("[DEBUG] OTO " + choices.toString()); // ok wszystko dziaa

                if (choices.contains("Bet") && betAbility > (pot) / 2
                        && !(betAbility + (maxBet - actualBet) >= actualChips) && betAbility >= maxBet) {

                    betAbility = betAbility(hand) - (pot) / 2;

                    doWyslania.put(new JSONObject().put("action", "bet"));
                    doWyslania.put(new JSONObject().put("bet", betAbility));
                    sendData(doWyslania.toString());

                } else if (choices.contains("Small Blind")) {
                    doWyslania.put(new JSONObject().put("action", "small_blind"));
                    sendData(doWyslania.toString());
                } else if (choices.contains("Big Blind")) {

                    doWyslania.put(new JSONObject().put("action", "big_blind"));
                    sendData(doWyslania.toString());
                } else if (choices.contains("Raise") && betAbility > (pot) / 2
                        && !(betAbility + (maxBet - actualBet) >= actualChips) && betAbility >= maxBet) {

                    betAbility = betAbility(hand) - (pot) / 2;

                    doWyslania.put(new JSONObject().put("action", "raise"));
                    doWyslania.put(new JSONObject().put("bet", betAbility));
                    sendData(doWyslania.toString());

                } else if (choices.contains("Exchange cards")) {

                    doWyslania.put(new JSONObject().put("action", "exchange_cards"));
                    System.out.println("[DEBUG] OTO " + hand);

                    for (int i = 0; i < cardsToExchange(hand).size(); i++) {
                        doWyslania.put(new JSONObject().put("suit", cardsToExchange(hand).get(i).getSuit())
                                .put("rank", cardsToExchange(hand).get(i).getRank()));
                    }
                    sendData(doWyslania.toString());
                    System.out.println("[DEBUG] OTO " + doWyslania);

                } else if (choices.contains("All-In")) {
                    doWyslania.put(new JSONObject().put("action", "all-in"));
                    sendData(doWyslania.toString());

                } else if (choices.contains("Call") && (maxBet - actualBet) <= actualChips
                        && (Math.random() < 0.6)) {
                    doWyslania.put(new JSONObject().put("action", "call"));
                    sendData(doWyslania.toString());
                } else if (choices.contains("Check")) {
                    doWyslania.put(new JSONObject().put("action", "check"));
                    sendData(doWyslania.toString());
                } else if (choices.contains("Fold")) {
                    doWyslania.put(new JSONObject().put("action", "fold"));
                    sendData(doWyslania.toString());
                }

                break;

            case "pot":
                pot = jsonMainArr.getJSONObject(1).getInt("pot_size");
                maxBet = 0;
                break;

            case "exit":
                connection = false;
                break;

            case "the_same_nick":
                System.out.println("[FATAL] Another player has the same nick");
                connection = false;
                break;

            case "you_lost":
                System.out.println("I lost ;-(");
                connection = false;
                break;

            case "you_won":
                System.out.println("I won :-)");
                connection = false;
                break;

            case "message":
                final String message = jsonMainArr.getJSONObject(1).getString("message");
                System.out.println("[DEBUG] Message from server" + message);
                break;

            case "connection_successful":
                break;

            default:
                System.out
                        .println("[ERROR] Unknown command " + jsonMainArr.getJSONObject(0).getString("action"));

            }
        } catch (NullPointerException | IOException | JSONException e) {
            e.printStackTrace();
            break;
        }
    }

    try {
        socket.close();
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    out.close();

}

From source file:com.t2.dataouthandler.DataOutHandler.java

/**
 * Processes the cache (updates the local cache and remote database to they are in sync)
 *  To be called from DispatchThread/*from  w  ww. j a v  a2s  .c  o m*/
 * 
 *  Here is the algorithm:
 *  1. Request a packet summary from Drupal
 *  2. Check for records in local cache but not in remote DB
 *     if Packet exists in Cache but not in remote DB
 *        if Packet newly inserted by self 
 *           Add (send) the packet to the remote DB
 *        else (Packet deleted by other from remote DB) 
 *           Remove the packet from the cache
 *  2. Check for records in remote DB but not in local cache
 *     if Packet exists in remote DB but not in local Cache
 *        if Packeted deleted by self
 *           Delete packet from remote DB
 *       else (Packet newly inserted by other into DB)
 *             Add packet to local Cache   
 * 3. If records exist both in local cache and remote DB
 *       if the remote DB record changed data is more recent
 *          Update the local cache from the remote DB
 *       else
 *          Update the remote DB from the local cache
 * 
 * 
 * Rules for presence of drupal node id in the cache
 * If synched from DB (added by another client):
 *      drupal ID is present immediately
 * If added from the UI
 *      drupal id is blank until the 200 ok is received from the Drupal server
 */
private void ProcessCacheThread() {

    final ArrayList<String> mDrupalNodeIdList = new ArrayList<String>();
    final ArrayList<String> mSqlNodeIdList;

    final HashMap<String, String> mDrupalRecordIdToDrupalChangedTime = new HashMap<String, String>();

    Log.d(TAG, "ProcessCacheThread()");

    // Get list of all records in the local database. This will be comared
    // to the list of records in the drupal database
    // in order to determine what needs to be synched
    mSqlNodeIdList = (ArrayList<String>) mDbCache.getSqlNodeIdList();

    // -------------------------------------
    // Get Drupal Node Summary:
    // -------------------------------------
    UserServices us;
    us = new UserServices(mServicesClient);

    JsonHttpResponseHandler responseHandler = new JsonHttpResponseHandler() {

        @Override
        protected void handleSuccessJsonMessage(Object arg0) {
            //             if (VERBOSE_LOGGING) {
            //                 Log.e(TAG, "handleSuccessJsonMessage(Object arg0");
            ////                  Log.e(TAG, "Drupal Node Summary: " + array.toString());
            //              }

            JSONArray array = (JSONArray) arg0;

            for (int i = 0; i < array.length(); i++) {
                JSONObject jObject = (JSONObject) array.opt(i);
                try {
                    String userId = (String) jObject.get("uid");
                    String nodeId = (String) jObject.get("nid");
                    String changedTime = (String) jObject.get("changed");
                    String type = (String) jObject.get("type");

                    // Check to see if this is a valid record
                    // If so then add the record to the summary arrays
                    if (GlobalH2.isValidRecordType(type)) {
                        mDrupalNodeIdList.add(nodeId);
                        mDrupalRecordIdToDrupalChangedTime.put(nodeId, changedTime);

                        //                        if (VERBOSE_LOGGING) {
                        //                         Log.e(TAG, "setting Array nodeId/changed " + nodeId + " =  " + changedTime);
                        //                        }                        

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            if (VERBOSE_LOGGING) {
                Log.e(TAG, "mDrupalNodeIdList = " + mDrupalNodeIdList.toString());
                Log.e(TAG, "mSqlNodeIdList = " + mSqlNodeIdList.toString());
            }
        }

        @Override
        public void onSuccess(JSONObject response) {
            if (VERBOSE_LOGGING) {
                Log.e(TAG, "onSuccess(JSONObject response) ");
            }
        }

        @Override
        public void onSuccess(JSONArray arg0) {
            //              if (VERBOSE_LOGGING) {
            //                      Log.e(TAG, "onSuccess(JSONArray arg0) ");
            //              }
            super.onSuccess(arg0);
        }

        @Override
        public void onFailure(Throwable e, JSONObject response) {
            Log.e(TAG, "OnFailure(Throwable e, JSONObject response) " + e.toString());
        }

        @Override
        public void onFailure(Throwable arg0, JSONArray arg1) {
            Log.e(TAG, "OnFailure(Throwable arg0, JSONArray arg1) " + arg0.toString());
        }

        /* (non-Javadoc)
         * The HTTP call to retrieve the summary contents from Drupal has succeeded.
         * Now process the results.
         * 
         * @see com.loopj.android.http.AsyncHttpResponseHandler#onFinish()
         */
        @Override
        public void onFinish() {
            Log.d(TAG, "onFinish(Drupal Node Summary)");

            // Now do processing of cache items, comparing what's on the device
            // to what's in the remote database.
            if (true) {
                // Now do record by record comparison between the records of the local database (mSqlRecordIdList)
                // to the records of the remote database (mDrupalNodeIdList).

                // Check for records in local cache but not in remote DB
                for (String sqlNodeId : mSqlNodeIdList) {
                    if (!mDrupalNodeIdList.contains(sqlNodeId)) {

                        if (VERBOSE_LOGGING) {
                            Log.e(TAG, "sqlNodeId: " + sqlNodeId
                                    + " - Packet exists in local Cache but not in remote DB");
                        }

                        if (sqlNodeId == null) {
                            break;
                        }

                        // Initially the nodeId is equal to the RecordId we can use getPacketByRecordId here
                        // Thereafter we can't because nodeId will have been replaced from the Drupal Server
                        SqlPacket sqlPacket = mDbCache.getPacketByDrupalId(sqlNodeId); // Since nodeId is in mSqlNodeIdList we know this will not return null

                        // Exists in cache but not on on Drupal
                        // Two possible cases here
                        // 1 Packet newly inserted by self                 -> Add (send) the packet to the remote DB
                        // 2 Packet deleted by other from remote DB         -> Remove the packet from the local cache
                        Boolean isSendingOrSend = (sqlPacket.getCacheStatus() == GlobalH2.CACHE_SENDING
                                || sqlPacket.getCacheStatus() == GlobalH2.CACHE_SENT);
                        if (isSendingOrSend) {

                            // Packet exists in cache but not on on Drupal
                            // Case 1 - Packet newly inserted by self        -> Add (send) the packet to the DB
                            if (VERBOSE_LOGGING) {
                                Log.e(TAG, "Case 1 - Send the packet to remoteDB");
                            }

                            DataOutPacket dataOutPacket;
                            if (VERBOSE_LOGGING) {
                                Log.e(TAG, "Status Sending/Sent - Sending packet to remote database ");
                            }
                            try {

                                synchronized (mDbCache) {
                                    sqlPacket.setCacheStatus(GlobalH2.CACHE_SENT);
                                    mDbCache.updateSqlPacket(sqlPacket);
                                }

                                dataOutPacket = new DataOutPacket(sqlPacket);
                                sendPacketToRemoteDbSync(dataOutPacket, "C", "");

                            } catch (DataOutHandlerException e) {
                                Log.e(TAG, e.toString());
                                e.printStackTrace();
                            }

                        } else {
                            // Packet exists in cache but not on on Drupal
                            // Case 2 - Packet deleted by other from remote DB      -> Remove the packet from the local cache
                            if (VERBOSE_LOGGING) {
                                Log.e(TAG, "Case 2 - Remove the packet from the local cache");
                            }
                            mDbCache.deletePacketFromCache(sqlPacket);

                            DataOutPacket dataOutPacket;
                            try {
                                // TODO: calling this too often slows the UI
                                dataOutPacket = new DataOutPacket(sqlPacket);
                                if (mInstance.mDatabaseUpdateListener != null) {
                                    mInstance.mDatabaseUpdateListener
                                            .remoteDatabaseDeleteComplete(dataOutPacket);
                                }
                            } catch (DataOutHandlerException e) {
                                Log.e(TAG, e.toString());
                                e.printStackTrace();
                            }
                        }
                    } // if (!mDrupalNodeIdList.contains(id))
                    else {
                        // Record exists in both local cache and remote db
                        // Need to merge the records
                        //                     if (VERBOSE_LOGGING) {
                        //                        Log.e(TAG, "Record exists in both local cache and remote db: " + sqlNodeId);
                        //                     }

                        // First see which record is most recent
                        try {
                            SqlPacket sqlPacket = mDbCache.getPacketByDrupalId(sqlNodeId);
                            if (sqlPacket != null) {
                                String localChangedAt = sqlPacket.getChangedDate();
                                //DateTime dtLocalChangedAt = new DateTime(localChangedAt);

                                //long lLocalChangedAt = dtLocalChangedAt.getMillis();
                                long lLocalChangedAt = Long.parseLong(localChangedAt);

                                String drupalChangedAt = mDrupalRecordIdToDrupalChangedTime.get(sqlNodeId);
                                //                           long lDrupalChangedAt = Long.parseLong(drupalChangedAt) * 1000; 
                                long lDrupalChangedAt = Long.parseLong(drupalChangedAt);

                                if (VERBOSE_LOGGING) {
                                    //                              Log.e(TAG, "Record exists in both local and remote, times: " + lLocalChangedAt + ", " + lDrupalChangedAt + ", " + sqlNodeId);

                                    if (lDrupalChangedAt == lLocalChangedAt) {
                                        //Log.e(TAG, "RemoteTime and local time are exactly equal");
                                    } else {
                                        if (lDrupalChangedAt > lLocalChangedAt) {
                                            Log.e(TAG,
                                                    "RemoteTime is most recent - updating cache from remote");
                                            addPacketToCacheSync(sqlNodeId, "U"); // Grabs the packet from Drupal and updates it in the Cache                     
                                        } else {
                                            Log.e(TAG, "localTime is most recent");
                                            if (VERBOSE_LOGGING) {
                                                Log.e(TAG, "Updatating record to remote database");
                                            }

                                            DataOutPacket dataOutPacket = new DataOutPacket(sqlPacket);
                                            sendPacketToRemoteDbSync(dataOutPacket, "U", sqlNodeId);
                                        }
                                    }
                                }

                            }
                        } catch (Exception e) {
                            Log.e(TAG, e.toString());
                            e.printStackTrace();
                        }
                    } // else
                } // end for (String id : mSqlIdList)    

                //                   // Check for records in remote DB but not in local cache
                for (String drupalNodeId : mDrupalNodeIdList) {
                    if (!mSqlNodeIdList.contains(drupalNodeId)) {
                        if (VERBOSE_LOGGING) {
                            Log.e(TAG, "drupalNodeId: " + drupalNodeId
                                    + " - Packet exists in remote DB but not in local Cache");
                        }

                        // Packet exists in remote DB but not in local Cache
                        // Two possible cases here:
                        // 3 Packeted deleted by self                         -> Delete packet from  remoteDB
                        // 4 Packet newly inserted by other into remote DB     -> Add packet to local Cache

                        //Log.e(TAG, "mNodeDeleteQueue = " + mNodeDeleteQueue.toString());

                        boolean listContainsId = false;
                        for (String id : mNodeDeleteQueue) {
                            if (id != null && id.equalsIgnoreCase(drupalNodeId)) {
                                listContainsId = true;
                                break;
                            }
                        }
                        // Determine which of the cases we have here
                        if (listContainsId) {

                            // Packet exists in remote DB but not in local Cache
                            // Case 3 - Packeted deleted by self                -> Delete packet from remote DB
                            if (VERBOSE_LOGGING) {
                                Log.e(TAG, "Case 3 - Delete packet from remote DB");
                            }
                            sendPacketToRemoteDbSync(null, "D", drupalNodeId);
                        } else {
                            // Packet exists in DB but not in Cache
                            // Case 4 - Packet newly inserted by other into DB  -> Add packet to Cache
                            if (VERBOSE_LOGGING) {
                                Log.e(TAG, "Case 4 - Add packet to local cache");
                            }
                            addPacketToCacheSync(drupalNodeId, "C"); // Grabs the packet from Drupal and adds it to the Cache                     
                        }
                    }
                }
            }
            try {
                //                  if (VERBOSE_LOGGING) {
                //                         Log.e(TAG, "Done processing all Drupal check entries");
                //                  }

                // Notify self that all entries have been processed
                synchronized (updateCacheSyncToken) {
                    updateCacheSyncToken.notifyAll();
                }
            } catch (Exception e) {
                Log.e(TAG, e.toString());
                e.printStackTrace();
            }
        } // void onFinish()
    };

    //       if (VERBOSE_LOGGING) {
    //          Log.e(TAG, "Requesting drupal node summary");
    //       }

    if (mDrupalUserId.equalsIgnoreCase("")) {
        us.NodeGet(responseHandler);
    } else {

        if (mFilterQueriesOnUserId) {
            us.NodeGet(responseHandler, "?parameters[uid]=" + mDrupalUserId);
        } else {
            us.NodeGet(responseHandler, "");
        }
    }

    if (VERBOSE_LOGGING) {
        Log.e(TAG, "Waiting for UpdateCacheSyncToken");
    }

    // Wait until all entries have been processed
    synchronized (updateCacheSyncToken) {
        try {
            updateCacheSyncToken.wait(SYNC_TIMEOUT);
        } catch (InterruptedException e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
        }
    }
    if (VERBOSE_LOGGING) {
        Log.e(TAG, "Done Waiting for UpdateCacheSyncToken");
    }

    // Give notice that the internal cache should now be in sync with the remote database
    if (mDatabaseUpdateListener != null) {
        mDatabaseUpdateListener.remoteDatabaseSyncComplete();
    }
}

From source file:org.idempiere.adinterface.ModelADServiceImpl.java

public StandardResponseDocument createUpdateData(ModelCRUDRequestDocument req) {
    boolean connected = getCompiereService().isConnected();

    Trx trx = null;//from  w  w  w .jav  a 2 s .c  om
    boolean manageTrx = this.manageTrx;

    try {
        if (!connected)
            getCompiereService().connect();

        StandardResponseDocument ret = StandardResponseDocument.Factory.newInstance();
        StandardResponse resp = ret.addNewStandardResponse();
        ModelCRUD modelCRUD = req.getModelCRUDRequest().getModelCRUD();
        String serviceType = modelCRUD.getServiceType();

        ADLoginRequest reqlogin = req.getModelCRUDRequest().getADLoginRequest();
        String err = login(reqlogin, webServiceName, "createData", serviceType);
        if (err != null && err.length() > 0) {
            resp.setError(err);
            resp.setIsError(true);
            return ret;
        }

        // Validate parameters vs service type
        try {
            validateCRUD(modelCRUD);
        } catch (IdempiereServiceFault e) {
            resp.setError(e.getMessage());
            resp.setIsError(true);
            return ret;
        }

        String tableName = modelCRUD.getTableName();

        CompiereService m_cs = getCompiereService();
        Properties ctx = m_cs.getCtx();

        // start a trx
        String trxName = localTrxName;

        if (trxName == null) {
            trxName = Trx.createTrxName("ws_modelCreateData");
            manageTrx = true;
        }
        trx = Trx.get(trxName, true);

        // get the PO for the tablename and record ID
        MTable table = MTable.get(ctx, tableName);
        if (table == null)
            return rollbackAndSetError(trx, resp, ret, true, "No table " + tableName);

        DataRow dr = modelCRUD.getDataRow();
        DataField fields[] = dr.getFieldArray();

        PO holderPo = table.getPO(0, trxName);
        POInfo poinfo = POInfo.getPOInfo(ctx, table.getAD_Table_ID());

        MWebServiceType m_webservicetype = getWebServiceType();
        Map<String, Object> requestCtx = getRequestCtx();

        StandardResponseDocument retResp = invokeWSValidator(m_webservicetype, IWSValidator.TIMING_BEFORE_PARSE,
                holderPo, fields, trx, requestCtx, resp, ret);
        if (retResp != null)
            return retResp;

        retResp = scanFields(fields, m_webservicetype, holderPo, poinfo, trx, resp, ret);
        if (retResp != null)
            return retResp;

        retResp = invokeWSValidator(m_webservicetype, IWSValidator.TIMING_AFTER_PARSE, holderPo, fields, trx,
                requestCtx, resp, ret);
        if (retResp != null)
            return retResp;

        boolean isCreate = false;
        boolean isUpdate = false;

        String action = modelCRUD.getAction().toString();
        if (action.equals("Create"))
            isCreate = true;
        if (action.equals("Update"))
            isUpdate = true;
        if (action.equals("CreateUpdate")) {
            isCreate = true;
            isUpdate = true;
        }

        ArrayList<String> identifierList = m_webservicetype.getKeyColumns();

        // For update it is mandatory to pass key column
        if (isUpdate && identifierList.size() == 0) {
            return rollbackAndSetError(trx, resp, ret, true,
                    "Web service type " + m_webservicetype.getValue() + ": There is no key column found ");
        }

        // Check for existing element
        int record_id = 0;
        ArrayList<Object> resovedValue = new ArrayList<Object>();
        if (identifierList.size() > 0) {
            StringBuilder sqlBuilder = new StringBuilder("Select ");
            sqlBuilder.append(table.getTableName()).append("_ID from ").append(table.getTableName())
                    .append(" ot Where ");
            ArrayList<Object> sqlParaList = new ArrayList<Object>();
            for (String colName : identifierList) {
                X_WS_WebServiceFieldInput fieldInput = m_webservicetype.getFieldInput(colName);
                if (fieldInput.getIdentifierLogic() == null) {
                    if (holderPo.get_Value(colName) == null && fieldInput.isNullIdentifier()) {
                        sqlBuilder.append(" ot.").append(colName).append(" Is Null AND ");
                    } else if (holderPo.get_Value(colName) == null) {
                        return rollbackAndSetError(trx, resp, ret, true,
                                "Web service type " + m_webservicetype.getValue()
                                        + ": Record Identifier column " + colName + " must be set");
                    } else {
                        sqlBuilder.append(" ot.").append(colName).append("=? AND ");
                        sqlParaList.add(holderPo.get_Value(colName));
                        resovedValue.add(holderPo.get_Value(colName));
                    }
                } else {
                    // SQL
                    String sql = parseSQL(fieldInput.getIdentifierLogic(), sqlParaList, holderPo, poinfo,
                            requestCtx);
                    sqlBuilder.append(" ot.").append(colName).append(" = (").append(sql).append(") AND ");
                    resovedValue.add("DYN SQL");
                }
            }
            sqlBuilder.append(" ot.AD_Client_ID= ?");
            sqlParaList.add(Env.getAD_Client_ID(Env.getCtx()));

            String sql = sqlBuilder.toString();
            if (log.isLoggable(Level.INFO))
                log.info("Web service type " + m_webservicetype.getValue() + "SQL to check existing record "
                        + sql);
            try {
                record_id = DB.getSQLValueEx(trxName, sql, sqlParaList);
            } catch (Exception e) {
                log.log(Level.SEVERE, "ExistingRecordCheck: Exception while executing SQL :" + sql);
                return rollbackAndSetError(trx, resp, ret, true, "Web service type "
                        + m_webservicetype.getValue() + " Exception while executing sql :" + sql);
            }
        }
        if (record_id == -1)
            record_id = 0;

        if (!isCreate && record_id == 0) {
            resp.setError("No Record to update for " + table.getTableName() + " with ("
                    + identifierList.toString() + ") = (" + resovedValue.toString() + ")");
            resp.setIsError(true);
            return ret;
        }

        if (record_id > 0 && !isUpdate) {
            resp.setError("Record already presents with " + table.getTableName() + "_ID = " + record_id);
            resp.setIsError(true);
            return ret;
        }

        PO po = table.getPO(record_id, trxName);

        if (po == null)
            return rollbackAndSetError(trx, resp, ret, true, "Cannot create PO for " + tableName);

        if (po.get_ColumnIndex("Processed") >= 0 && po.get_ValueAsBoolean("Processed")) {
            resp.setError("Record not updatable for " + table.getTableName() + "_ID = " + record_id);
            resp.setIsError(true);
            return ret;
        }

        // Setting value back from holder to new persistent po
        for (DataField field : fields) {
            int indx = poinfo.getColumnIndex(field.getColumn());
            if (indx != -1) {
                po.set_ValueNoCheck(field.getColumn(), holderPo.get_Value(field.getColumn()));
            }
        }

        retResp = invokeWSValidator(m_webservicetype, IWSValidator.TIMING_BEFORE_SAVE, holderPo, fields, trx,
                requestCtx, resp, ret);
        if (retResp != null)
            return retResp;

        if (!po.save())
            return rollbackAndSetError(trx, resp, ret, true, "Cannot save record in " + tableName + ": "
                    + CLogger.retrieveErrorString("no log message"));

        retResp = invokeWSValidator(m_webservicetype, IWSValidator.TIMING_AFTER_SAVE, holderPo, fields, trx,
                requestCtx, resp, ret);
        if (retResp != null)
            return retResp;

        int recordID = po.get_ID();
        resp.setRecordID(recordID);

        // Update ctx variable for consecutive calls
        if (requestCtx != null) {
            requestCtx.put(po.get_TableName(), po);
        }

        // close the trx
        if (manageTrx && !trx.commit())
            return rollbackAndSetError(trx, resp, ret, true,
                    "Cannot commit transaction after create record " + recordID + " in " + tableName);

        setOuputFields(resp, m_webservicetype, po, poinfo);

        return ret;
    } finally {
        if (manageTrx && trx != null)
            trx.close();

        if (!connected)
            getCompiereService().disconnect();
    }
}

From source file:com.rapid.actions.Database.java

public JSONObject doQuery(RapidRequest rapidRequest, JSONObject jsonAction, Application application,
        DataFactory df) throws Exception {

    // place holder for the object we're going to return
    JSONObject jsonData = null;//from w  w w  .j a v  a2 s . c o  m

    // retrieve the sql
    String sql = _query.getSQL();

    // only if there is some sql is it worth going further
    if (sql != null) {

        // get any json inputs
        JSONObject jsonInputData = jsonAction.optJSONObject("data");

        // initialise the parameters list
        ArrayList<Parameters> parametersList = new ArrayList<Parameters>();

        // populate the parameters from the inputs collection (we do this first as we use them as the cache key due to getting values from the session)
        if (_query.getInputs() == null) {

            // just add an empty parameters member if no inputs
            parametersList.add(new Parameters());

        } else {

            // if there is input data
            if (jsonInputData != null) {

                // get any input fields
                JSONArray jsonFields = jsonInputData.optJSONArray("fields");
                // get any input rows
                JSONArray jsonRows = jsonInputData.optJSONArray("rows");

                // if we have fields and rows
                if (jsonFields != null && jsonRows != null) {

                    // loop the input rows (only the top row if not multirow)
                    for (int i = 0; i < jsonRows.length() && (_query.getMultiRow() || i == 0); i++) {

                        // get this jsonRow
                        JSONArray jsonRow = jsonRows.getJSONArray(i);
                        // make the parameters for this row
                        Parameters parameters = new Parameters();

                        // loop the query inputs
                        for (Parameter input : _query.getInputs()) {
                            // get the input id
                            String id = input.getItemId();
                            // get the input field
                            String field = input.getField();
                            // add field to id if present
                            if (field != null && !"".equals(field))
                                id += "." + field;
                            // retain the value
                            String value = null;
                            // if it looks like a control, or a system value (bit of extra safety checking)
                            if ("P".equals(id.substring(0, 1)) && id.indexOf("_C") > 0
                                    || id.indexOf("System.") == 0) {
                                // loop the json inputs looking for the value
                                if (jsonInputData != null) {
                                    for (int j = 0; j < jsonFields.length(); j++) {
                                        // get the id from the fields
                                        String jsonId = jsonFields.optString(j);
                                        // if the id we want matches this one 
                                        if (id.toLowerCase().equals(jsonId.toLowerCase())) {
                                            // get the value
                                            value = jsonRow.optString(j, null);
                                            // no need to keep looking
                                            break;
                                        }
                                    }
                                }
                            }
                            // if still null try the session
                            if (value == null)
                                value = (String) rapidRequest.getSessionAttribute(input.getItemId());
                            // add the parameter
                            parameters.add(value);
                        }

                        // add the parameters to the list
                        parametersList.add(parameters);

                    } // row loop

                } // input fields and rows check

            } // input data check

        } // query inputs check

        // placeholder for the action cache
        ActionCache actionCache = rapidRequest.getRapidServlet().getActionCache();

        // if an action cache was found
        if (actionCache != null) {

            // log that we found action cache
            _logger.debug("Database action cache found");

            // attempt to fetch data from the cache
            jsonData = actionCache.get(application.getId(), getId(), parametersList.toString());

        }

        // if there isn't a cache or no data was retrieved
        if (jsonData == null) {

            try {

                // instantiate jsonData
                jsonData = new JSONObject();
                // fields collection
                JSONArray jsonFields = new JSONArray();
                // rows collection can start initialised
                JSONArray jsonRows = new JSONArray();

                // trim the sql
                sql = sql.trim();

                // check the verb
                if (sql.toLowerCase().startsWith("select") || sql.toLowerCase().startsWith("with")) {

                    // set readonly to true (makes for faster querying)
                    df.setReadOnly(true);

                    // loop the parameterList getting a result set for each parameters (input row)
                    for (Parameters parameters : parametersList) {

                        // get the result set!
                        ResultSet rs = df.getPreparedResultSet(rapidRequest, sql, parameters);

                        // get it's meta data for the field names
                        ResultSetMetaData rsmd = rs.getMetaData();

                        // got fields indicator
                        boolean gotFields = false;

                        // loop the result set
                        while (rs.next()) {

                            // initialise the row
                            JSONArray jsonRow = new JSONArray();

                            // loop the columns
                            for (int i = 0; i < rsmd.getColumnCount(); i++) {
                                // add the field name to the fields collection if not done yet
                                if (!gotFields)
                                    jsonFields.put(rsmd.getColumnLabel(i + 1));
                                // get the column type
                                int columnType = rsmd.getColumnType(i + 1);
                                // add the data to the row according to it's type   
                                switch (columnType) {
                                case (Types.NUMERIC):
                                    jsonRow.put(rs.getDouble(i + 1));
                                    break;
                                case (Types.INTEGER):
                                    jsonRow.put(rs.getInt(i + 1));
                                    break;
                                case (Types.BIGINT):
                                    jsonRow.put(rs.getLong(i + 1));
                                    break;
                                case (Types.FLOAT):
                                    jsonRow.put(rs.getFloat(i + 1));
                                    break;
                                case (Types.DOUBLE):
                                    jsonRow.put(rs.getDouble(i + 1));
                                    break;
                                default:
                                    jsonRow.put(rs.getString(i + 1));
                                }
                            }
                            // add the row to the rows collection
                            jsonRows.put(jsonRow);
                            // remember we now have our fields
                            gotFields = true;

                        }

                        // close the record set
                        rs.close();

                    }

                } else {

                    // assume rows affected is 0
                    int rows = 0;

                    // sql check
                    if (sql.length() > 0) {

                        // perform update for all incoming parameters (one parameters collection for each row)
                        for (Parameters parameters : parametersList) {
                            rows += df.getPreparedUpdate(rapidRequest, sql, parameters);
                        }

                        // add a psuedo field 
                        jsonFields.put("rows");

                        // create a row array
                        JSONArray jsonRow = new JSONArray();
                        // add the rows updated
                        jsonRow.put(rows);
                        // add the row we just made
                        jsonRows.put(jsonRow);

                    }

                }

                // add the fields to the data object
                jsonData.put("fields", jsonFields);
                // add the rows to the data object
                jsonData.put("rows", jsonRows);

                // check for any child database actions
                if (_childDatabaseActions != null) {
                    // if there really are some
                    if (_childDatabaseActions.size() > 0) {
                        // get any child data
                        JSONArray jsonChildQueries = jsonAction.optJSONArray("childQueries");
                        // if there was some
                        if (jsonChildQueries != null) {
                            // loop
                            for (int i = 0; i < jsonChildQueries.length(); i++) {
                                // fetch the data
                                JSONObject jsonChildAction = jsonChildQueries.getJSONObject(i);
                                // read the index (the position of the child this related to
                                int index = jsonChildAction.getInt("index");
                                // get the relevant child action
                                Database childDatabaseAction = _childDatabaseActions.get(index);
                                // get the resultant child data
                                JSONObject jsonChildData = childDatabaseAction.doQuery(rapidRequest,
                                        jsonChildAction, application, df);

                                // a map for indexes of matching fields between our parent and child
                                Map<Integer, Integer> fieldsMap = new HashMap<Integer, Integer>();
                                // the child fields
                                JSONArray jsonChildFields = jsonChildData.getJSONArray("fields");
                                if (jsonChildFields != null) {
                                    // loop the parent fields
                                    for (int j = 0; j < jsonFields.length(); j++) {
                                        // loop the child fields
                                        for (int k = 0; k < jsonChildFields.length(); k++) {
                                            // get parent field
                                            String field = jsonFields.getString(j);
                                            // get child field
                                            String childField = jsonChildFields.getString(k);
                                            // if both not null
                                            if (field != null && childField != null) {
                                                // check for match
                                                if (field.toLowerCase().equals(childField.toLowerCase()))
                                                    fieldsMap.put(j, k);
                                            }
                                        }
                                    }
                                }

                                // add a field for the results of this child action
                                jsonFields.put("childAction" + (i + 1));

                                // if matching fields
                                if (fieldsMap.size() > 0) {
                                    // an object with a null value for when there is no match
                                    Object nullObject = null;
                                    // get the child rows
                                    JSONArray jsonChildRows = jsonChildData.getJSONArray("rows");
                                    // if we had some
                                    if (jsonChildRows != null) {
                                        // loop the parent rows
                                        for (int j = 0; j < jsonRows.length(); j++) {
                                            // get the parent row
                                            JSONArray jsonRow = jsonRows.getJSONArray(j);
                                            // make a new rows collection for the child subset
                                            JSONArray jsonChildRowsSubset = new JSONArray();
                                            // loop the child rows
                                            for (int k = 0; k < jsonChildRows.length(); k++) {
                                                // get the child row
                                                JSONArray jsonChildRow = jsonChildRows.getJSONArray(k);
                                                // assume no matches
                                                int matches = 0;
                                                // loop the fields map
                                                for (Integer l : fieldsMap.keySet()) {
                                                    // parent value
                                                    Object parentValue = null;
                                                    // get the value if there are enough
                                                    if (jsonRow.length() > l)
                                                        parentValue = jsonRow.get(l);
                                                    // child value
                                                    Object childValue = null;
                                                    if (jsonChildRow.length() > l)
                                                        childValue = jsonChildRow.get(fieldsMap.get(l));
                                                    // non null check
                                                    if (parentValue != null && childValue != null) {
                                                        // a string we will concert the child value to
                                                        String parentString = null;
                                                        // check the parent value type
                                                        if (parentValue.getClass() == String.class) {
                                                            parentString = (String) parentValue;
                                                        } else if (parentValue.getClass() == Integer.class) {
                                                            parentString = Integer
                                                                    .toString((Integer) parentValue);
                                                        } else if (parentValue.getClass() == Long.class) {
                                                            parentString = Long.toString((Long) parentValue);
                                                        } else if (parentValue.getClass() == Double.class) {
                                                            parentString = Double
                                                                    .toString((Double) parentValue);
                                                        } else if (parentValue.getClass() == Boolean.class) {
                                                            parentString = Boolean
                                                                    .toString((Boolean) parentValue);
                                                        }
                                                        // a string we will convert the child value to
                                                        String childString = null;
                                                        // check the parent value type
                                                        if (childValue.getClass() == String.class) {
                                                            childString = (String) childValue;
                                                        } else if (childValue.getClass() == Integer.class) {
                                                            childString = Integer
                                                                    .toString((Integer) childValue);
                                                        } else if (childValue.getClass() == Long.class) {
                                                            childString = Long.toString((Long) childValue);
                                                        } else if (childValue.getClass() == Double.class) {
                                                            childString = Double.toString((Double) childValue);
                                                        } else if (childValue.getClass() == Boolean.class) {
                                                            childString = Boolean
                                                                    .toString((Boolean) childValue);
                                                        }
                                                        // non null check
                                                        if (parentString != null && childString != null) {
                                                            // do the match!
                                                            if (parentString.equals(childString))
                                                                matches++;
                                                        }
                                                    } // values non null                                          
                                                } // field map loop
                                                  // if we got some matches for all the fields add this row to the subset
                                                if (matches == fieldsMap.size())
                                                    jsonChildRowsSubset.put(jsonChildRow);
                                            } // child row loop
                                              // if our child subset has rows in it
                                            if (jsonChildRowsSubset.length() > 0) {
                                                // create a new childSubset object
                                                JSONObject jsonChildDataSubset = new JSONObject();
                                                // add the fields
                                                jsonChildDataSubset.put("fields", jsonChildFields);
                                                // add the subset of rows
                                                jsonChildDataSubset.put("rows", jsonChildRowsSubset);
                                                // add the child database action data subset
                                                jsonRow.put(jsonChildDataSubset);
                                            } else {
                                                // add an empty cell
                                                jsonRow.put(nullObject);
                                            }
                                        } // parent row loop                                 
                                    } // jsonChildRows null check
                                } else {
                                    // loop the parent rows
                                    for (int j = 0; j < jsonRows.length(); j++) {
                                        // get the row
                                        JSONArray jsonRow = jsonRows.getJSONArray(j);
                                        // add the child database action data
                                        jsonRow.put(jsonChildData);
                                    }
                                } // matching fields check

                            } // jsonChildQueries loop
                        } // jsonChildQueries null check                      
                    } // _childDatabaseActions size > 0                                                      
                } // _childDatabaseActions not null

                // cache if in use
                if (actionCache != null)
                    actionCache.put(application.getId(), getId(), parametersList.toString(), jsonData);

            } catch (Exception ex) {

                // log the error
                _logger.error(ex);

                // close the data factory and silently fail
                try {
                    df.close();
                } catch (Exception ex2) {
                }

                // only throw if no action cache
                if (actionCache == null) {
                    throw ex;
                } else {
                    _logger.debug("Error not shown to user due to cache : " + ex.getMessage());
                }

            } // jsonData not null

        } // jsonData == null

    } // got sql

    return jsonData;

}

From source file:com.krawler.spring.iphone.iphoneController.java

private String getModuleReports(HttpServletRequest request) throws ServiceException {
    String jdata = "";
    try {/*from w w  w  .  ja va2 s. c  o  m*/
        ArrayList li = new ArrayList();
        getLeadsReportsLink(request, li);
        getAccountReportsLink(request, li);
        getContactReportsLink(request, li);
        getOpportunityReportsLink(request, li);
        getActivityReportsLink(request, li);
        getCaseReportsLink(request, li);
        getProductReportsLink(request, li);
        getOpportunityProductReportsLink(request, li);
        getSalesReportsLink(request, li);
        getCampaignReportsLink(request, li);
        getTargetReportsLink(request, li);

        int start = 0; //Integer.parseInt(request.getParameter("start"));
        int limit = 45;//Integer.parseInt(request.getParameter("limit"));
        String limitReport = request.getParameter("limitReport");
        if (!StringUtil.isNullOrEmpty(limitReport)) {
            limit = Integer.parseInt(limitReport);
        }
        limit = (start + limit) > li.size() ? li.size() : (start + limit);
        List currli = (List) li.subList(start, limit);
        Iterator it = currli.iterator();
        ArrayList newArr = new ArrayList();
        while (it.hasNext()) {
            newArr.add(it.next());
        }
        JSONObject jobj = new JSONObject("{\"count\":" + li.size() + ",\"data\":" + newArr.toString() + "}");
        jdata = jobj.toString();
    } catch (JSONException ex) {
        logger.warn(ex.getMessage(), ex);
        String esc = ex.toString();
        jdata = "{'success':'false','data':[]}";
    } catch (ServiceException ex) {
        logger.warn(ex.getMessage(), ex);
        jdata = "{'success':'false','data':[]}";
    }
    return jdata;
}

From source file:org.akaza.openclinica.control.submit.DataEntryServlet.java

protected List<DisplayItemWithGroupBean> createItemWithGroups(DisplaySectionBean dsb, boolean hasItemGroup,
        int eventCRFDefId, HttpServletRequest request, boolean isSubmitted) {
    HttpSession session = request.getSession();
    List<DisplayItemWithGroupBean> displayItemWithGroups = new ArrayList<DisplayItemWithGroupBean>();
    EventCRFBean ecb = (EventCRFBean) request.getAttribute(INPUT_EVENT_CRF);
    ItemDAO idao = new ItemDAO(getDataSource());
    SectionBean sb = (SectionBean) request.getAttribute(SECTION_BEAN);
    EventDefinitionCRFBean edcb = (EventDefinitionCRFBean) request.getAttribute(EVENT_DEF_CRF_BEAN);
    // BWP>> Get a List<String> of any null values such as NA or NI
    // method returns null values as a List<String>
    // >>BWP
    ArrayList items = dsb.getItems();
    // For adding null values to display items
    FormBeanUtil formBeanUtil = new FormBeanUtil();
    List<String> nullValuesList = formBeanUtil.getNullValuesByEventCRFDefId(eventCRFDefId, getDataSource());

    LOGGER.trace("single items size: " + items.size());
    for (int i = 0; i < items.size(); i++) {
        DisplayItemBean item = (DisplayItemBean) items.get(i);
        DisplayItemWithGroupBean newOne = new DisplayItemWithGroupBean();
        newOne.setSingleItem(runDynamicsItemCheck(item, null, request));
        newOne.setOrdinal(item.getMetadata().getOrdinal());
        newOne.setInGroup(false);/*from   www .ja v  a2s.co  m*/
        newOne.setPageNumberLabel(item.getMetadata().getPageNumberLabel());
        displayItemWithGroups.add(newOne);
        // logger.trace("just added on line 1979:
        // "+newOne.getSingleItem().getData().getValue());
    }

    if (hasItemGroup) {
        ItemDataDAO iddao = new ItemDataDAO(getDataSource(), locale);

        ArrayList<ItemDataBean> data = iddao.findAllBySectionIdAndEventCRFId(sb.getId(), ecb.getId());
        HashMap<String, ItemDataBean> dataMap = (HashMap<String, ItemDataBean>) getAllActive(data);

        if (data != null && data.size() > 0) {
            session.setAttribute(HAS_DATA_FLAG, true);
        }
        LOGGER.trace("found data: " + data.size());
        LOGGER.trace("data.toString: " + data.toString());

        for (DisplayItemGroupBean itemGroup : dsb.getDisplayFormGroups()) {
            LOGGER.debug("found one itemGroup");
            DisplayItemWithGroupBean newOne = new DisplayItemWithGroupBean();
            // to arrange item groups and other single items, the ordinal of
            // a item group will be the ordinal of the first item in this
            // group
            DisplayItemBean firstItem = itemGroup.getItems().get(0);

            // so we are either checking the first or the last item, BUT ONLY ONCE
            newOne.setPageNumberLabel(firstItem.getMetadata().getPageNumberLabel());

            newOne.setItemGroup(itemGroup);
            newOne.setInGroup(true);
            newOne.setOrdinal(itemGroup.getGroupMetaBean().getOrdinal());

            List<ItemBean> itBeans = idao.findAllItemsByGroupIdOrdered(itemGroup.getItemGroupBean().getId(),
                    sb.getCRFVersionId());

            List<DisplayItemBean> dibs = new ArrayList();

            boolean hasData = false;
            int checkAllColumns = 0;
            if (data.size() > 0)
                hasData = true;
            //@pgawade 30-May-2012 Fix for issue 13963 - added an extra parameter 'isSubmitted' to method buildMatrixForRepeatingGroups
            newOne = buildMatrixForRepeatingGroups(newOne, itemGroup, ecb, sb, itBeans, dataMap, nullValuesList,
                    isSubmitted);

            if (hasData) {
                //TODO: fix the group_has_data flag on bean not on session
                session.setAttribute(GROUP_HAS_DATA, Boolean.TRUE);

            } else {
                session.setAttribute(GROUP_HAS_DATA, Boolean.FALSE);
                // no data, still add a blank row for displaying
                if (nullValuesList != null && nullValuesList.size() > 0) {
                    LOGGER.trace("set with nullValuesList of : " + nullValuesList);
                }
                dibs = FormBeanUtil.getDisplayBeansFromItems(itBeans, getDataSource(), ecb, sb.getId(),
                        nullValuesList, getServletContext());

                DisplayItemGroupBean digb2 = new DisplayItemGroupBean();

                digb2.setItems(dibs);
                digb2.setEditFlag("initial");

            }

            displayItemWithGroups.add(newOne);
        }

    } // if hasItemGroup

    Collections.sort(displayItemWithGroups);

    return displayItemWithGroups;
}