Example usage for org.json.simple JSONArray toJSONString

List of usage examples for org.json.simple JSONArray toJSONString

Introduction

In this page you can find the example usage for org.json.simple JSONArray toJSONString.

Prototype

public String toJSONString() 

Source Link

Usage

From source file:hd3gtv.mydmam.db.orm.CassandraOrm.java

public void pushColumn(String rowkey, Integer ttl, String name, Object o)
        throws InvalidClassException, ConnectionException {
    if (rowkey == null) {
        return;// w w w.j a v a 2 s.co  m
    }
    if (rowkey.equals("")) {
        return;
    }
    if (mutator == null) {
        mutator = CassandraDb.prepareMutationBatch();
    }
    if (ttl == 0) {
        ttl = null;
    }
    if (o == null) {
        mutator.withRow(columnfamily, rowkey).putColumn(name, null_value, ttl);
    } else if (o instanceof String) {
        if (((String) o).equals(null_value)) {
            StringBuffer sb = new StringBuffer();
            sb.append("String value equals to null String reference : security problem ?");
            sb.append("[");
            sb.append(rowkey);
            sb.append("]");
            sb.append(name);
            throw new InvalidClassException(o.getClass().getName(), sb.toString());
        }
        mutator.withRow(columnfamily, rowkey).putColumn(name, (String) o, ttl);
    } else if (o instanceof byte[]) {
        mutator.withRow(columnfamily, rowkey).putColumn(name, (byte[]) o, ttl);
    } else if (o instanceof Integer) {
        mutator.withRow(columnfamily, rowkey).putColumn(name, (Integer) o, ttl);
    } else if (o instanceof Long) {
        mutator.withRow(columnfamily, rowkey).putColumn(name, (Long) o, ttl);
    } else if (o instanceof Boolean) {
        if ((Boolean) o) {
            mutator.withRow(columnfamily, rowkey).putColumn(name, "true", ttl);
        } else {
            mutator.withRow(columnfamily, rowkey).putColumn(name, "false", ttl);
        }
    } else if (o instanceof Date) {
        mutator.withRow(columnfamily, rowkey).putColumn(name, (Date) o, ttl);
    } else if (o instanceof Float) {
        mutator.withRow(columnfamily, rowkey).putColumn(name, String.valueOf((Float) o), ttl);
    } else if (o instanceof Double) {
        mutator.withRow(columnfamily, rowkey).putColumn(name, String.valueOf((Double) o), ttl);
    } else if (o instanceof UUID) {
        mutator.withRow(columnfamily, rowkey).putColumn(name, (UUID) o, ttl);
    } else if (o instanceof JSONObject) {
        mutator.withRow(columnfamily, rowkey).putColumn(name, ((JSONObject) o).toJSONString(), ttl);
    } else if (o instanceof JSONArray) {
        mutator.withRow(columnfamily, rowkey).putColumn(name, ((JSONArray) o).toJSONString(), ttl);
    } else if (o instanceof InetAddress) {
        mutator.withRow(columnfamily, rowkey).putColumn(name, ((InetAddress) o).getHostAddress(), ttl);
    } else if (o instanceof StringBuffer) {
        mutator.withRow(columnfamily, rowkey).putColumn(name, ((StringBuffer) o).toString(), ttl);
    } else if (o instanceof Calendar) {
        mutator.withRow(columnfamily, rowkey).putColumn(name, ((Calendar) o).getTimeInMillis(), ttl);
    } else if (o instanceof String[]) {
        JSONArray ja = new JSONArray();
        String[] o_str = (String[]) o;
        for (int pos = 0; pos < o_str.length; pos++) {
            ja.add(o_str[pos]);
        }
        mutator.withRow(columnfamily, rowkey).putColumn(name, ja.toJSONString(), ttl);
    } else if (o instanceof Serializable) {
        mutator.withRow(columnfamily, rowkey).putColumn(name, serialize(o), ttl);
    } else if (o instanceof Enum) {
        mutator.withRow(columnfamily, rowkey).putColumn(name, serialize(o), ttl);
    } else {
        StringBuffer sb = new StringBuffer();
        sb.append("Class type is not managed for this record ");
        sb.append("[");
        sb.append(rowkey);
        sb.append("]");
        sb.append(name);
        throw new InvalidClassException(o.getClass().getName(), sb.toString());
    }
}

From source file:com.websystique.springmvc.youtube_api.Function.java

@SuppressWarnings({ "static-access", "unchecked" })

private String printNote(NodeList nodeList) {
    List<VideoSub> listsub = new ArrayList<VideoSub>();
    List<VideoSub> savelistsub = new ArrayList<VideoSub>();
    for (int count = 0; count < nodeList.getLength(); count++) {
        VideoSub v = new VideoSub();
        Node tempNode = nodeList.item(count);
        if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
            v.setTextsb(replace_all(replacetext(tempNode.getTextContent().replace("...", "."))));
            if (tempNode.hasAttributes()) {
                NamedNodeMap nodeMap = tempNode.getAttributes();
                for (int i = 0; i < nodeMap.getLength(); i++) {
                    Node node = nodeMap.item(i);
                    if (i == 0) {
                        v.setEnd(node.getNodeValue());
                    } else {
                        v.setStart(node.getNodeValue());
                    }/*from ww  w . j  ava 2 s .  c om*/
                }
            }
        }
        listsub.add(v);
    }
    String savetext = "";
    double sodu = 0;
    double savedur = 0;
    String dutext = "";
    double start = 0;
    String kq = "";
    boolean flag = true;// vo lan dau
    boolean flagchamcuoi = false;// vo lan dau
    for (int i = 0; i < listsub.size(); i++) {
        String cau = listsub.get(i).getTextsb();
        if (flag || flagchamcuoi == true) {
            start = Double.parseDouble(listsub.get(i).getStart());
            savedur = Double.parseDouble(listsub.get(i).getEnd());
            flag = false;
            flagchamcuoi = false;
        }

        double dur = Double.parseDouble(listsub.get(i).getEnd());
        if (sodu != 0) {
            savetext += dutext;
            start = Double.parseDouble(listsub.get(i).getStart());
            start -= sodu;
            System.out.println(sodu + "So du" + start);
            dutext = "";
            sodu = 0;
        }
        if (cau.contains("####") == true) {
            float sogiay = (float) dur;
            float phantram = 0;
            int socau = 0;
            int sotu = demsotu(cau);
            String[] savecau = new String[100];
            int[] savesotu = new int[1000];
            double[] phantramsotu = new double[1000];
            for (String retval : cau.split("####")) { // split("\\|;\\s*|\\.\\s*|\\?\\s*")
                if (retval != "" && retval.length() > 0) {
                    savecau[socau] = retval;
                    savesotu[socau] = (1 + StringUtils.countMatches(retval.trim(), " "));
                    double pt = 0.0;
                    double so1 = (double) savesotu[socau];
                    double so2 = (double) sotu;
                    pt = so1 / so2;
                    phantramsotu[socau] = pt * sogiay;
                    socau++;
                }
            }

            // *******************************
            char[] array = cau.toCharArray();
            // save cau 1
            VideoSub cau1 = new VideoSub();
            cau1.setTextsb((savetext + " " + savecau[0]).replace("\n", " ").replace("'", " ").trim());
            cau1.setStart(start + "");
            String end = (savedur + phantramsotu[0]) + "";
            cau1.setEnd(end + "");
            if (savecau[0] != ".")
                savelistsub.add(cau1);
            // add vao
            savetext = "";
            // cap nhat start
            start += Double.parseDouble(cau1.getEnd());

            savedur = 0;
            // save cau giua
            for (int i1 = 1; i1 < socau - 1; i1++) {
                // add vao
                VideoSub Cau2 = new VideoSub();
                Cau2.setTextsb(savecau[i1].replace("\n", " ").replace("'", " ").trim());
                Cau2.setStart(start + "");
                Cau2.setEnd(phantramsotu[i1] + "");
                if (savecau[i1] != ".")
                    savelistsub.add(Cau2);

                start += phantramsotu[i1];
            }

            // save cau cuoi
            if (array[cau.length() - 5] == '.' || array[cau.length() - 5] == '?'
                    || array[cau.length() - 5] == ';') {
                flagchamcuoi = true;

            }

            System.out.println(cau);
            if (array[cau.length() - 5] == '.' || array[cau.length() - 5] == ';'
                    || array[cau.length() - 5] == '?') {
                if (socau - 1 != 0) {
                    VideoSub Cau3 = new VideoSub();
                    Cau3.setTextsb(savecau[socau - 1].replace("\n", " ").replace("'", "-").trim());
                    Cau3.setStart(start + "");
                    Cau3.setEnd(phantramsotu[socau - 1] + "");
                    if (savecau[socau - 1] != ".")
                        savelistsub.add(Cau3);

                    start += phantramsotu[socau - 1];
                }
            } else {
                dutext = savecau[socau - 1];
                sodu = phantramsotu[socau - 1];
            }
        } else {
            savetext += " " + cau;
            savedur += dur;
        }
    }
    // ================Xuat File Json===============
    JSONArray jsonArray = new JSONArray();
    for (int i = 0; i < savelistsub.size(); i++) {
        JSONObject obj = new JSONObject();
        if (savelistsub.get(i).getTextsb() != ".") {
            String startadd = savelistsub.get(i).getStart();
            String duradd = savelistsub.get(i).getEnd();
            String textadd = savelistsub.get(i).getTextsb();
            obj.put("start", startadd);
            obj.put("dur", duradd);
            obj.put("text", textadd);
            jsonArray.add(obj);
        }

    }
    String out_String = jsonArray.toJSONString();
    out_String = out_String.toString();

    // ================Xuat File Json===============

    return out_String;
}

From source file:com.flaptor.indextank.api.resources.DeleteDocs.java

/**
 * @see java.lang.Runnable#run()//from  w ww  .  ja  va2  s.  co m
 */
public void run() {
    IndexEngineApi api = (IndexEngineApi) ctx().getAttribute("api");
    try {
        Object parse = JSONValue.parseWithException(req().getReader());
        if (parse instanceof JSONObject) { // 200, 400, 404, 409, 503
            JSONObject jo = (JSONObject) parse;
            try {
                deleteDocument(api, jo);
                res().setStatus(200);
                return;

            } catch (Exception e) {
                e.printStackTrace();
                if (LOG_ENABLED)
                    LOG.severe(e.getMessage());
                res().setStatus(400);
                print("Invalid or missing argument"); // TODO: descriptive error msg
                return;
            }
        } else if (parse instanceof JSONArray) {
            JSONArray statuses = new JSONArray();
            JSONArray ja = (JSONArray) parse;
            if (!validateDocuments(ja)) {
                res().setStatus(400);
                print("Invalid or missing argument"); // TODO: descriptive error msg
                return;
            }
            boolean hasError = false;
            for (Object o : ja) {
                JSONObject jo = (JSONObject) o;
                JSONObject status = new JSONObject();
                try {
                    deleteDocument(api, jo);
                    status.put("added", true);
                } catch (Exception e) {
                    status.put("added", false);
                    status.put("error", "Invalid or missing argument"); // TODO: descriptive error msg
                    hasError = true;
                }
                statuses.add(status);
            }
            print(statuses.toJSONString());
            return;
        }
    } catch (IOException e) {
        if (LOG_ENABLED)
            LOG.severe("DELETE doc, parse input " + e.getMessage());
    } catch (ParseException e) {
        if (LOG_ENABLED)
            LOG.severe("DELETE doc, parse input " + e.getMessage());
    } catch (Exception e) {
        if (LOG_ENABLED)
            LOG.severe("DELETE doc " + e.getMessage());
    }
    res().setStatus(503);
    print("Service unavailable"); // TODO: descriptive error msg
}

From source file:com.flaptor.indextank.api.resources.Docs.java

/**
 * @see java.lang.Runnable#run()//from  w  w w . j  a v a 2s  .  c o m
 */
public void run() {
    IndexEngineApi api = (IndexEngineApi) ctx().getAttribute("api");
    HttpServletResponse res = res();
    HttpServletRequest req = req();

    String characterEncoding = api.getCharacterEncoding();
    try {
        req.setCharacterEncoding(characterEncoding);
        res.setCharacterEncoding(characterEncoding);
        res.setContentType("application/json");
    } catch (UnsupportedEncodingException ignored) {
    }

    try {
        Object parse = JSONValue.parseWithException(req.getReader());
        if (parse instanceof JSONObject) { // 200, 400, 404, 409, 503
            JSONObject jo = (JSONObject) parse;
            try {
                putDocument(api, jo);
                res.setStatus(200);
                return;

            } catch (Exception e) {
                e.printStackTrace();
                if (LOG_ENABLED)
                    LOG.severe(e.getMessage());
                res.setStatus(400);
                print("Invalid or missing argument"); // TODO: descriptive error msg
                return;
            }
        } else if (parse instanceof JSONArray) {
            JSONArray statuses = new JSONArray();
            JSONArray ja = (JSONArray) parse;
            if (!validateDocuments(ja)) {
                res.setStatus(400);
                print("Invalid or missing argument"); // TODO: descriptive error msg
                return;
            }
            boolean hasError = false;
            for (Object o : ja) {
                JSONObject jo = (JSONObject) o;
                JSONObject status = new JSONObject();
                try {
                    putDocument(api, jo);
                    status.put("added", true);
                } catch (Exception e) {
                    status.put("added", false);
                    status.put("error", "Invalid or missing argument"); // TODO: descriptive error msg
                    hasError = true;
                }
                statuses.add(status);
            }
            print(statuses.toJSONString());
            return;
        }
    } catch (IOException e) {
        if (LOG_ENABLED)
            LOG.severe("PUT doc, parse input " + e.getMessage());
    } catch (ParseException e) {
        if (LOG_ENABLED)
            LOG.severe("PUT doc, parse input " + e.getMessage());
    } catch (Exception e) {
        if (LOG_ENABLED)
            LOG.severe("PUT doc " + e.getMessage());
    }
    res.setStatus(503);
    print("Service unavailable"); // TODO: descriptive error msg
}

From source file:luceneprueba.Reader.java

public void searchOnIndex(String wordQuery, String date) {
    // Parse a simple query that searches for "text":
    QueryParser parser = new QueryParser("review", analyzer);
    Query query;/* w  w w . j  a  v a 2s.  co  m*/
    try {
        query = parser.parse("date: \"+" + date + "\" AND " + cleanInput(wordQuery));
        ScoreDoc[] hits = indexSearcher.search(query, 60).scoreDocs;

        if (hits.length == 0) {
            //System.out.println("[Search] No se han encontrado coincidencias.");
        } else {
            //System.out.println("[Search] Se han encontrado: " + hits.length + " coincidencias.");
            JSONArray reviews = new JSONArray();
            for (ScoreDoc hit : hits) {
                Document hitDoc = indexSearcher.doc(hit.doc);
                //System.out.println(i+".- Score: " + hit.score + ", Doc: " + hitDoc.get("movieId") + ", path: " + hitDoc.get("path") + ", Tile review: " + hitDoc.get("title"));
                JSONObject json = new JSONObject();
                json.put("date", hitDoc.get("date"));
                json.put("genre", hitDoc.get("genre"));
                json.put("review", hitDoc.get("review"));
                json.put("score", hitDoc.get("score"));
                reviews.add(json);
            }
            try (FileWriter file = new FileWriter(
                    "files/output/top-k/reviews_" + date.replace(" ", "") + ".json")) {
                file.write(reviews.toJSONString());
                file.flush();
                //indexReader.close();
            }
        }

    } catch (ParseException | IOException ex) {
        Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex);
        for (StackTraceElement st : ex.getStackTrace()) {
            System.out.println(st.toString());
        }
        System.out.println(ex.getLocalizedMessage());
    }

}

From source file:com.skelril.aurora.authentication.AuthComponent.java

public synchronized void updateWhiteList(JSONArray object) {

    // Load the storage directory
    File charactersDirectory = new File(inst.getDataFolder().getPath() + "/characters");
    if (!charactersDirectory.exists())
        charactersDirectory.mkdir();//from w w  w  . j  a  v  a 2 s.c  o  m
    log.info("Updating white list...");

    if (!loadCharacters((JSONObject[]) object.toArray(new JSONObject[object.size()]))) {
        log.info("No changes detected.");
        return;
    }

    // Remove outdated JSON backup files
    for (File file : charactersDirectory.listFiles(filenameFilter)) {
        file.delete();
    }

    // Create new JSON backup file
    BufferedWriter out = null;

    File characterList = new File(charactersDirectory, "character-list.json");
    try {
        if (characterList.createNewFile()) {
            out = new BufferedWriter(new FileWriter(characterList));
            out.write(object.toJSONString());
        } else {
            log.warning("Could not create the new character list offline file!");
        }
    } catch (IOException ignored) {
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException ignored) {
            }
        }
    }

    log.info("The white list has updated successfully.");
}

From source file:com.imagelake.android.usersmanagement.Servlet_UserManagement.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    PrintWriter out = response.getWriter();
    try {//from  ww w. j av  a  2  s.  c  om

        String type = request.getParameter("type");
        JSONArray ja;
        if (type != null && !type.trim().equals("")) {

            if (type.equals("all")) {
                ja = new JSONArray();
                List<User> li = udi.listSellersBuyers();
                if (!li.isEmpty()) {

                    for (User u : li) {
                        JSONObject jo = new JSONObject();
                        jo.put("id", u.getUser_id());
                        jo.put("user_name", u.getUser_name());
                        jo.put("f_name", u.getFirst_name());
                        jo.put("l_name", u.getLast_name());
                        jo.put("em", u.getEmail());
                        jo.put("phn", u.getPhone());
                        jo.put("state", u.getState());
                        jo.put("type", u.getUser_type());
                        ja.add(jo);
                    }
                    out.write("json=" + ja.toJSONString());
                } else {
                    out.write("msg=No item found.");
                }
            } else if (type.equals("sort")) {
                ja = new JSONArray();

                String uid, date, buy, sell, name;
                uid = request.getParameter("uid");
                date = request.getParameter("date");
                buy = request.getParameter("buy");
                sell = request.getParameter("sell");
                name = request.getParameter("name");

                System.out.println("uid:" + uid);
                System.out.println("date:" + date);
                System.out.println("buy:" + buy);
                System.out.println("sell:" + sell);

                String sql = "SELECT * FROM user WHERE ";

                if (!sell.equals("false") || !buy.equals("false")) {

                    if (!uid.equals("") && !uid.equals(null)) {
                        System.out.println("user id=" + uid);
                        sql += " user_id='" + Integer.parseInt(uid) + "'";
                        if (!date.trim().equals("") && !date.equals(null)
                                || !buy.equals("") && !buy.equals(null)
                                || !sell.equals("") && !sell.equals(null)
                                || !name.equals("") && !name.equals(null)) {
                            sql += " AND ";
                        }
                    }
                    if (!date.equals("") && !date.equals(null)) {
                        String[] dt = date.split("-");
                        String orDate = dt[2] + "-" + dt[1] + "-" + dt[0];
                        System.out.println("date=" + orDate);

                        sql += " date='" + orDate + "'";
                        if (!buy.equals("") && !buy.equals(null) || !sell.equals("") && !sell.equals(null)
                                || !name.equals("") && !name.equals(null)) {
                            sql += " AND ";
                        }

                    }

                    //                    if (!name.equals("") && !name.equals(null)) {
                    //                        System.out.println("Name=" + name);
                    //                        sql += "user_name='" + name + "'";
                    //                        if (!buy.equals("") && !buy.equals(null) || !sell.equals("") && !sell.equals(null)) {
                    //                            sql += " AND ";
                    //                        }
                    //                    }
                    if (!buy.equals("") && !buy.equals(null) && !buy.equals("false")) {
                        System.out.println("buyers=" + buy);
                        sql += "user_type_user_type_id='" + 3 + "'";
                        if (!sell.equals("") && !sell.equals(null) && !sell.equals("false")) {
                            sql += " OR ";
                        }

                    }
                    if (!sell.equals("") && !sell.equals(null) && !sell.equals("false")) {
                        System.out.println("Sellers=" + sell);
                        sql += "user_type_user_type_id='" + 2 + "'";

                    }
                    System.out.println("sql=" + sql);
                    PreparedStatement ps;

                    try {
                        ps = DBFactory.getConnection().prepareStatement(sql);
                        ResultSet rs = ps.executeQuery();
                        while (rs.next()) {
                            JSONObject jo = new JSONObject();
                            jo.put("id", rs.getInt(1));
                            jo.put("user_name", rs.getString(2));
                            jo.put("f_name", rs.getString(3));
                            jo.put("l_name", rs.getString(4));
                            jo.put("em", rs.getString(5));
                            jo.put("phn", rs.getString(12));
                            jo.put("state", rs.getInt(19));
                            jo.put("type", rs.getInt(21));
                            ja.add(jo);
                        }

                        out.write("json=" + ja.toJSONString());
                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("error sql");
                        out.write("msg=Internal server error,Please try again later.");
                    }

                } else {
                    System.out.println("no item");
                    out.write("msg=No item found.");
                }
            } else if (type.equals("update")) {
                String id = request.getParameter("id");
                String uid = request.getParameter("uid");
                String state = request.getParameter("state");

                System.out.println("id:" + id);
                System.out.println("uid:" + uid);
                System.out.println("state:" + state);

                String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                        .format(Calendar.getInstance().getTime());

                User user = (User) udi.getUser(Integer.parseInt(uid));

                boolean ok = udi.updateUserState(Integer.parseInt(uid), Integer.parseInt(state));
                String un = udi.getUn(Integer.parseInt(uid));
                if (ok) {
                    //                        AdminNotification a = new AdminNotification();
                    //                        a.setUser_id(user.getUser_id());
                    //                        a.setDate(timeStamp);
                    //
                    //                        a.setShow(1);
                    //                        if (state.equals("2")) {
                    //                            a.setType(2);
                    //                            String not = "Admin " + user.getUser_name() + " has blocked user " + un;
                    //                            a.setNotification(not);
                    //                        } else if (state.equals("1")) {
                    //                            a.setType(4);
                    //                            String not = "Admin " + user.getUser_name() + " has activated user " + un;
                    //                            a.setNotification(not);
                    //                        }
                    //
                    //                        int an = new AdminNotificationDAOImp().insertNotificaation(a);
                    //                        System.out.println("PPPPPPPPPPPPPPPPPPPPPPPPPPPPPP " + an);
                    //
                    //                        boolean kl = new AdminHasNotificationDAOImp().insertNotification(udi.notMeList(user.getUser_id()), an, 1);
                    //                        if (kl) {
                    //                            out.write("ok");
                    //                        } else {
                    //                            out.write("no");
                    //                        }
                    out.write("msg=Successful...");
                } else {
                    out.write("msg=Unable to complete the action,Please try agin later.");
                }

            }

        } else {
            System.out.println("type");
            out.write("msg=Internal server error,Please try again later.");
        }

    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("error");
        out.write("msg=Internal server error,Please try again later.");
    }

}

From source file:luceneprueba.Reader.java

public void searchOnIndexByDate() {
    // Parse a simple query that searches for "text":
    QueryParser parser = new QueryParser("review", analyzer);
    Query query;//  w  w  w.  j a va2s . c om
    try {
        BufferedReader br = new BufferedReader(new FileReader("files/dates_reviews"));
        String date;

        JSONArray reviews = new JSONArray();

        while ((date = br.readLine()) != null) {
            query = parser.parse("date: \"+" + date + "\"");
            ScoreDoc[] hits = indexSearcher.search(query, 1).scoreDocs;

            if (hits.length == 0) {
                System.out.println("No se encontraron reviews para la fecha " + date);
            } else {
                System.out.println("Guardando review de la fecha " + date);
                Document hitDoc = indexSearcher.doc(hits[0].doc);

                JSONObject json = new JSONObject();
                json.put("date", hitDoc.get("date"));
                //json.put("genre", hitDoc.get("genre"));
                json.put("review", hitDoc.get("review"));
                //json.put("score", hitDoc.get("score"));
                reviews.add(json);

            }
        }

        try (FileWriter file = new FileWriter("files/output/review_date.json")) {
            file.write(reviews.toJSONString());
            file.flush();
        }
        //indexReader.close();

    } catch (ParseException | IOException ex) {
        Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex);
        for (StackTraceElement st : ex.getStackTrace()) {
            System.out.println(st.toString());
        }
        System.out.println(ex.getLocalizedMessage());
    }

}

From source file:net.mybox.mybox.ServerClientConnection.java

private void sendServerFileList() {

    System.out.println("getting local file list for: " + localDir);

    Statement statement = null;/*from  w w  w.j a  v a2  s  .co m*/

    // refresh the database
    try {
        statement = connection.createStatement();
        statement.setQueryTimeout(30);

        statement.executeUpdate(
                "create table if not exists archive (name text primary key, type char(1), lastupdate integer)");
    } catch (Exception e) {
        System.out.println("SQLite error: " + e.getMessage());
    }

    try {
        List<MyFile> files = Common.getFileListing(new File(localDir));

        JSONArray jsonArray = new JSONArray();

        PreparedStatement prep = connection.prepareStatement("insert or ignore into archive values(?,?,?);");

        for (MyFile thisFile : files) {
            System.out.println(" " + thisFile.name);

            // TODO: do not insert directories that are already in the DB
            //  compare against getFilesFromDB ?

            prep.setString(1, thisFile.name);
            prep.setString(2, thisFile.getTypeChar() + "");
            prep.setLong(3, thisFile.modtime);
            prep.addBatch();

            jsonArray.add(thisFile.serialize());
        }

        prep.executeBatch();
        connection.commit();

        sendCommandToClient(Common.Signal.requestServerFileList_response);
        ByteStream.toStream(outStream, jsonArray.toJSONString());

        System.out.println("local file list: " + jsonArray.size() + " files");

    } catch (Exception e) {
        System.out.println("Error when getting local file list " + e.getMessage());
    }

}

From source file:com.p000ison.dev.simpleclans2.converter.Converter.java

public void convertClans() throws SQLException {
    ResultSet result = from.query("SELECT * FROM `sc_clans`;");

    while (result.next()) {
        JSONObject flags = new JSONObject();

        String name = result.getString("name");
        String tag = result.getString("tag");
        boolean verified = result.getBoolean("verified");
        boolean friendly_fire = result.getBoolean("friendly_fire");
        long founded = result.getLong("founded");
        long last_used = result.getLong("last_used");
        String flagsString = result.getString("flags");
        String cape = result.getString("cape_url");

        ConvertedClan clan = new ConvertedClan(tag);
        clan.setPackedAllies(result.getString("packed_allies"));
        clan.serPackedRivals(result.getString("packed_rivals"));

        if (friendly_fire) {
            flags.put("ff", friendly_fire);
        }//from  w ww.  j a va  2s.  c  o m

        if (cape != null && !cape.isEmpty()) {
            flags.put("cape-url", cape);
        }

        JSONParser parser = new JSONParser();
        try {
            JSONObject object = (JSONObject) parser.parse(flagsString);
            String world = object.get("homeWorld").toString();
            if (!world.isEmpty()) {
                int x = ((Long) object.get("homeX")).intValue();
                int y = ((Long) object.get("homeY")).intValue();
                int z = ((Long) object.get("homeZ")).intValue();

                flags.put("home", x + ":" + y + ":" + z + ":" + world + ":0:0");
            }

            clan.setRawWarring((JSONArray) object.get("warring"));
        } catch (ParseException e) {
            Logging.debug(e, true);
            continue;
        }

        insertClan(name, tag, verified, founded, last_used, flags.isEmpty() ? null : flags.toJSONString(),
                result.getDouble("balance"));

        String selectLastQuery = "SELECT `id` FROM `sc2_clans` ORDER BY ID DESC LIMIT 1;";

        ResultSet selectLast = to.query(selectLastQuery);
        selectLast.next();
        clan.setId(selectLast.getLong("id"));
        selectLast.close();

        insertBB(Arrays.asList(result.getString("packed_bb").split("\\s*(\\||$)")), clan.getId());

        clans.add(clan);
    }

    for (ConvertedClan clan : clans) {
        JSONArray allies = new JSONArray();
        JSONArray rivals = new JSONArray();
        JSONArray warring = new JSONArray();

        for (String allyTag : clan.getRawAllies()) {
            long allyID = getIDByTag(allyTag);
            if (allyID != -1) {
                allies.add(allyID);
            }
        }

        for (String rivalTag : clan.getRawAllies()) {
            long rivalID = getIDByTag(rivalTag);
            if (rivalID != -1) {
                rivals.add(rivalID);
            }
        }

        for (String warringTag : clan.getRawWarring()) {
            long warringID = getIDByTag(warringTag);
            if (warringID != -1) {
                warring.add(warringID);
            }
        }

        if (!allies.isEmpty()) {
            updateClan.setString(1, allies.toJSONString());
        } else {
            updateClan.setNull(1, Types.VARCHAR);
        }

        if (!rivals.isEmpty()) {
            updateClan.setString(2, rivals.toJSONString());
        } else {
            updateClan.setNull(2, Types.VARCHAR);
        }

        if (!warring.isEmpty()) {
            updateClan.setString(3, warring.toJSONString());
        } else {
            updateClan.setNull(3, Types.VARCHAR);
        }

        updateClan.setLong(4, clan.getId());
        updateClan.executeUpdate();
    }
}