Search in sources :

Example 96 with JSONException

use of org.json.JSONException in project Anki-Android by Ramblurr.

the class Finder method _findModel.

private String _findModel(String val) {
    LinkedList<Long> ids = new LinkedList<Long>();
    val = val.toLowerCase();
    try {
        for (JSONObject m : mCol.getModels().all()) {
            if (m.getString("name").toLowerCase().equals(val)) {
                ids.add(m.getLong("id"));
            }
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    return "n.mid in " + Utils.ids2str(ids);
}
Also used : JSONObject(org.json.JSONObject) JSONException(org.json.JSONException) LinkedList(java.util.LinkedList)

Example 97 with JSONException

use of org.json.JSONException in project Anki-Android by Ramblurr.

the class Finder method fieldNames.

public List<String> fieldNames(Collection col, boolean downcase) {
    Set<String> fields = new HashSet<String>();
    List<String> names = new ArrayList<String>();
    try {
        for (JSONObject m : col.getModels().all()) {
            JSONArray flds = m.getJSONArray("flds");
            for (int fi = 0; fi < flds.length(); ++fi) {
                JSONObject f = flds.getJSONObject(fi);
                if (!fields.contains(f.getString("name").toLowerCase())) {
                    names.add(f.getString("name"));
                    fields.add(f.getString("name").toLowerCase());
                }
            }
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    if (downcase) {
        return new ArrayList<String>(fields);
    }
    return names;
}
Also used : JSONObject(org.json.JSONObject) ArrayList(java.util.ArrayList) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) HashSet(java.util.HashSet)

Example 98 with JSONException

use of org.json.JSONException in project Anki-Android by Ramblurr.

the class Finder method findReplace.

public static int findReplace(Collection col, List<Long> nids, String src, String dst, boolean isRegex, String field, boolean fold) {
    Map<Long, Integer> mmap = new HashMap<Long, Integer>();
    if (field != null) {
        try {
            for (JSONObject m : col.getModels().all()) {
                JSONArray flds = m.getJSONArray("flds");
                for (int fi = 0; fi < flds.length(); ++fi) {
                    JSONObject f = flds.getJSONObject(fi);
                    if (f.getString("name").equals(field)) {
                        mmap.put(m.getLong("id"), f.getInt("ord"));
                    }
                }
            }
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        if (mmap.isEmpty()) {
            return 0;
        }
    }
    // find and gather replacements
    if (!isRegex) {
        src = Pattern.quote(src);
    }
    if (fold) {
        src = "(?i)" + src;
    }
    Pattern regex = Pattern.compile(src);
    ArrayList<Object[]> d = new ArrayList<Object[]>();
    String sql = "select id, mid, flds from notes where id in " + Utils.ids2str(nids.toArray(new Long[nids.size()]));
    nids = new ArrayList<Long>();
    Cursor cur = null;
    try {
        cur = col.getDb().getDatabase().rawQuery(sql, null);
        while (cur.moveToNext()) {
            String flds = cur.getString(2);
            String origFlds = flds;
            // does it match?
            String[] sflds = Utils.splitFields(flds);
            if (field != null) {
                long mid = cur.getLong(1);
                if (!mmap.containsKey(mid)) {
                    continue;
                }
                int ord = mmap.get(mid);
                sflds[ord] = regex.matcher(sflds[ord]).replaceAll(dst);
            } else {
                for (int i = 0; i < sflds.length; ++i) {
                    sflds[i] = regex.matcher(sflds[i]).replaceAll(dst);
                }
            }
            flds = Utils.joinFields(sflds);
            if (!flds.equals(origFlds)) {
                long nid = cur.getLong(0);
                nids.add(nid);
                d.add(new Object[] { flds, Utils.intNow(), col.usn(), nid });
            }
        }
    } finally {
        if (cur != null) {
            cur.close();
        }
    }
    if (d.isEmpty()) {
        return 0;
    }
    // replace
    col.getDb().executeMany("update notes set flds=?,mod=?,usn=? where id=?", d);
    long[] pnids = Utils.toPrimitive(nids);
    col.updateFieldCache(pnids);
    col.genCards(pnids);
    return d.size();
}
Also used : Pattern(java.util.regex.Pattern) HashMap(java.util.HashMap) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) JSONException(org.json.JSONException) Cursor(android.database.Cursor) JSONObject(org.json.JSONObject) JSONObject(org.json.JSONObject)

Example 99 with JSONException

use of org.json.JSONException in project Anki-Android by Ramblurr.

the class Finder method _findField.

private String _findField(String field, String val) {
    /*
         * We need two expressions to query the cards: One that will use JAVA REGEX syntax and another
         * that should use SQLITE LIKE clause syntax.
         */
    String sqlVal = val.replace("%", // For SQLITE, we escape all % signs
    "\\%").replace("*", // And then convert the * into non-escaped % signs
    "%");
    /*
         * The following three lines make sure that only _ and * are valid wildcards. 
         * Any other characters are enclosed inside the \Q \E markers, which force  
         * all meta-characters in between them to lose their special meaning 
         */
    String javaVal = val.replace("_", "\\E.\\Q").replace("*", "\\E.*\\Q");
    /*
         * For the pattern, we use the javaVal expression that uses JAVA REGEX syntax
         */
    Pattern pattern = Pattern.compile("\\Q" + javaVal + "\\E", Pattern.CASE_INSENSITIVE);
    // find models that have that field
    Map<Long, Object[]> mods = new HashMap<Long, Object[]>();
    try {
        for (JSONObject m : mCol.getModels().all()) {
            JSONArray flds = m.getJSONArray("flds");
            for (int fi = 0; fi < flds.length(); ++fi) {
                JSONObject f = flds.getJSONObject(fi);
                if (f.getString("name").equalsIgnoreCase(field)) {
                    mods.put(m.getLong("id"), new Object[] { m, f.getInt("ord") });
                }
            }
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    if (mods.isEmpty()) {
        // nothing has that field
        return "";
    }
    LinkedList<Long> nids = new LinkedList<Long>();
    Cursor cur = null;
    try {
        /*
             * Here we use the sqlVal expression, that is required for LIKE syntax in sqllite.
             * There is no problem with special characters, because only % and _ are special
             * characters in this syntax.
             */
        cur = mCol.getDb().getDatabase().rawQuery("select id, mid, flds from notes where mid in " + Utils.ids2str(new LinkedList<Long>(mods.keySet())) + " and flds like ? escape '\\'", new String[] { "%" + sqlVal + "%" });
        while (cur.moveToNext()) {
            String[] flds = Utils.splitFields(cur.getString(2));
            int ord = (Integer) mods.get(cur.getLong(1))[1];
            String strg = flds[ord];
            if (pattern.matcher(strg).matches()) {
                nids.add(cur.getLong(0));
            }
        }
    } finally {
        if (cur != null) {
            cur.close();
        }
    }
    if (nids.isEmpty()) {
        return "";
    }
    return "n.id in " + Utils.ids2str(nids);
}
Also used : Pattern(java.util.regex.Pattern) HashMap(java.util.HashMap) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) Cursor(android.database.Cursor) LinkedList(java.util.LinkedList) JSONObject(org.json.JSONObject) JSONObject(org.json.JSONObject)

Example 100 with JSONException

use of org.json.JSONException in project Anki-Android by Ramblurr.

the class Media method zipAdded.

// Media syncing - bundling zip files to send to server
// Because there's no standard filename encoding for zips, and because not
// all zip clients support retrieving mtime, we store the files as ascii
// and place a json file in the zip with the necessary information.
// /////////////////////////////////////////////////////
/**
     * Add files to a zip until over SYNC_ZIP_SIZE. Return zip data.
     * 
     * @return Returns a tuple with two objects. The first one is the zip file contents, the second a list with the
     *         filenames of the files inside the zip.
     */
public Pair<File, List<String>> zipAdded() {
    File f = new File(mCol.getPath().replaceFirst("collection\\.anki2$", "tmpSyncToServer.zip"));
    String sql = "select fname from log where type = " + Integer.toString(MEDIA_ADD);
    List<String> filenames = mMediaDb.queryColumn(String.class, sql, 0);
    List<String> fnames = new ArrayList<String>();
    try {
        ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(f)));
        zos.setLevel(8);
        JSONObject files = new JSONObject();
        int cnt = 0;
        long sz = 0;
        byte[] buffer = new byte[2048];
        boolean finished = true;
        for (String fname : filenames) {
            fnames.add(fname);
            File file = new File(getDir(), fname);
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file), 2048);
            ZipEntry entry = new ZipEntry(Integer.toString(cnt));
            zos.putNextEntry(entry);
            int count = 0;
            while ((count = bis.read(buffer, 0, 2048)) != -1) {
                zos.write(buffer, 0, count);
            }
            zos.closeEntry();
            bis.close();
            files.put(Integer.toString(cnt), fname);
            sz += file.length();
            if (sz > SYNC_ZIP_SIZE) {
                finished = false;
                break;
            }
            cnt += 1;
        }
        if (finished) {
            zos.putNextEntry(new ZipEntry("_finished"));
            zos.closeEntry();
        }
        zos.putNextEntry(new ZipEntry("_meta"));
        zos.write(Utils.jsonToString(files).getBytes());
        zos.close();
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    return new Pair<File, List<String>>(f, fnames);
}
Also used : ZipEntry(java.util.zip.ZipEntry) ArrayList(java.util.ArrayList) FileNotFoundException(java.io.FileNotFoundException) JSONException(org.json.JSONException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) JSONObject(org.json.JSONObject) BufferedInputStream(java.io.BufferedInputStream) ZipOutputStream(java.util.zip.ZipOutputStream) FileOutputStream(java.io.FileOutputStream) ZipFile(java.util.zip.ZipFile) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream) Pair(com.ichi2.anki.Pair)

Aggregations

JSONException (org.json.JSONException)1760 JSONObject (org.json.JSONObject)1346 JSONArray (org.json.JSONArray)593 IOException (java.io.IOException)315 ArrayList (java.util.ArrayList)194 HashMap (java.util.HashMap)139 Test (org.junit.Test)108 ClientException (edu.umass.cs.gnscommon.exceptions.client.ClientException)98 Bundle (android.os.Bundle)67 VolleyError (com.android.volley.VolleyError)66 File (java.io.File)63 DefaultGNSTest (edu.umass.cs.gnsserver.utils.DefaultGNSTest)62 Response (com.android.volley.Response)58 URL (java.net.URL)54 Map (java.util.Map)45 RandomString (edu.umass.cs.gnscommon.utils.RandomString)44 MalformedURLException (java.net.MalformedURLException)43 UnsupportedEncodingException (java.io.UnsupportedEncodingException)41 Intent (android.content.Intent)40 JsonObjectRequest (com.android.volley.toolbox.JsonObjectRequest)40