Search in sources :

Example 81 with JSONArray

use of org.json.JSONArray in project qi4j-sdk by Qi4j.

the class SQLEntityStoreMixin method writeEntityState.

protected void writeEntityState(DefaultEntityState state, Writer writer, String version) throws EntityStoreException {
    try {
        JSONWriter json = new JSONWriter(writer);
        JSONWriter properties = json.object().key(JSONKeys.IDENTITY).value(state.identity().identity()).key(JSONKeys.APPLICATION_VERSION).value(application.version()).key(JSONKeys.TYPE).value(first(state.entityDescriptor().types()).getName()).key(JSONKeys.VERSION).value(version).key(JSONKeys.MODIFIED).value(state.lastModified()).key(JSONKeys.PROPERTIES).object();
        for (PropertyDescriptor persistentProperty : state.entityDescriptor().state().properties()) {
            Object value = state.properties().get(persistentProperty.qualifiedName());
            json.key(persistentProperty.qualifiedName().name());
            if (value == null || ValueType.isPrimitiveValue(value)) {
                json.value(value);
            } else {
                String serialized = valueSerialization.serialize(value);
                if (serialized.startsWith("{")) {
                    json.value(new JSONObject(serialized));
                } else if (serialized.startsWith("[")) {
                    json.value(new JSONArray(serialized));
                } else {
                    json.value(serialized);
                }
            }
        }
        JSONWriter associations = properties.endObject().key(JSONKeys.ASSOCIATIONS).object();
        for (Map.Entry<QualifiedName, EntityReference> stateNameEntityReferenceEntry : state.associations().entrySet()) {
            EntityReference value = stateNameEntityReferenceEntry.getValue();
            associations.key(stateNameEntityReferenceEntry.getKey().name()).value(value != null ? value.identity() : null);
        }
        JSONWriter manyAssociations = associations.endObject().key(JSONKeys.MANY_ASSOCIATIONS).object();
        for (Map.Entry<QualifiedName, List<EntityReference>> stateNameListEntry : state.manyAssociations().entrySet()) {
            JSONWriter assocs = manyAssociations.key(stateNameListEntry.getKey().name()).array();
            for (EntityReference entityReference : stateNameListEntry.getValue()) {
                assocs.value(entityReference.identity());
            }
            assocs.endArray();
        }
        JSONWriter namedAssociations = manyAssociations.endObject().key(JSONKeys.NAMED_ASSOCIATIONS).object();
        for (Map.Entry<QualifiedName, Map<String, EntityReference>> stateNameMapEntry : state.namedAssociations().entrySet()) {
            JSONWriter assocs = namedAssociations.key(stateNameMapEntry.getKey().name()).object();
            for (Map.Entry<String, EntityReference> entry : stateNameMapEntry.getValue().entrySet()) {
                assocs.key(entry.getKey()).value(entry.getValue().identity());
            }
            assocs.endObject();
        }
        namedAssociations.endObject().endObject();
    } catch (JSONException e) {
        throw new EntityStoreException("Could not store EntityState", e);
    }
}
Also used : JSONWriter(org.json.JSONWriter) PropertyDescriptor(org.qi4j.api.property.PropertyDescriptor) QualifiedName(org.qi4j.api.common.QualifiedName) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) EntityReference(org.qi4j.api.entity.EntityReference) JSONObject(org.json.JSONObject) List(java.util.List) ArrayList(java.util.ArrayList) EntityStoreException(org.qi4j.spi.entitystore.EntityStoreException) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap)

Example 82 with JSONArray

use of org.json.JSONArray in project qi4j-sdk by Qi4j.

the class SolrEntityIndexerMixin method indexEntityState.

private SolrInputDocument indexEntityState(final EntityState entityState, final SolrServer server) throws IOException, SolrServerException, JSONException {
    Graph graph = new GraphImpl();
    stateSerializer.serialize(entityState, false, graph);
    SolrInputDocument input = new SolrInputDocument();
    input.addField("id", entityState.identity().identity());
    input.addField("type", first(entityState.entityDescriptor().types()).getName());
    input.addField("lastModified", new Date(entityState.lastModified()));
    for (Statement statement : graph) {
        SchemaField field = indexedFields.get(statement.getPredicate().getLocalName());
        if (field != null) {
            if (statement.getObject() instanceof Literal) {
                String value = statement.getObject().stringValue();
                if (field.getType().getTypeName().equals("json")) {
                    if (value.charAt(0) == '[') {
                        JSONArray array = new JSONArray(value);
                        indexJson(input, array);
                    } else if (value.charAt(0) == '{') {
                        JSONObject object = new JSONObject(value);
                        indexJson(input, object);
                    }
                } else {
                    input.addField(field.getName(), value);
                }
            } else if (statement.getObject() instanceof URI && !"type".equals(field.getName())) {
                String value = statement.getObject().stringValue();
                value = value.substring(value.lastIndexOf(':') + 1, value.length());
                String name = field.getName();
                input.addField(name, value);
            } else if (statement.getObject() instanceof BNode) {
                Iterator<Statement> seq = graph.match((Resource) statement.getObject(), new URIImpl("http://www.w3.org/1999/02/22-rdf-syntax-ns#li"), null, (Resource) null);
                while (seq.hasNext()) {
                    Statement seqStatement = seq.next();
                    String value = seqStatement.getObject().stringValue();
                    value = value.substring(value.lastIndexOf(':') + 1, value.length());
                    input.addField(field.getName(), value);
                }
            }
        }
    }
    return input;
}
Also used : BNode(org.openrdf.model.BNode) Statement(org.openrdf.model.Statement) JSONArray(org.json.JSONArray) URIImpl(org.openrdf.model.impl.URIImpl) URI(org.openrdf.model.URI) Date(java.util.Date) SchemaField(org.apache.solr.schema.SchemaField) SolrInputDocument(org.apache.solr.common.SolrInputDocument) Graph(org.openrdf.model.Graph) JSONObject(org.json.JSONObject) GraphImpl(org.openrdf.model.impl.GraphImpl) Literal(org.openrdf.model.Literal)

Example 83 with JSONArray

use of org.json.JSONArray in project qi4j-sdk by Qi4j.

the class TableResponseReader method readResponse.

@Override
public Object readResponse(Response response, Class<?> resultType) throws ResourceException {
    if (response.getEntity().getMediaType().equals(MediaType.APPLICATION_JSON) && Table.class.isAssignableFrom(resultType)) {
        String jsonValue = response.getEntityAsText();
        try {
            JSONObject jsonObject = new JSONObject(jsonValue);
            JSONObject table = jsonObject.getJSONObject("table");
            TableBuilder builder = new TableBuilder(module);
            JSONArray cols = table.getJSONArray("cols");
            for (int i = 0; i < cols.length(); i++) {
                JSONObject col = cols.getJSONObject(i);
                builder.column(col.optString("id"), col.getString("label"), col.getString("type"));
            }
            JSONArray rows = table.getJSONArray("rows");
            for (int i = 0; i < rows.length(); i++) {
                builder.row();
                JSONObject row = rows.getJSONObject(i);
                JSONArray cells = row.getJSONArray("c");
                for (int j = 0; j < cells.length(); j++) {
                    JSONObject cell = cells.getJSONObject(j);
                    Object value = cell.opt("v");
                    String formatted = cell.optString("f");
                    if (cols.getJSONObject(j).getString("type").equals("datetime") && value != null)
                        value = Dates.fromString(value.toString());
                    else if (cols.getJSONObject(j).getString("type").equals("date") && value != null)
                        try {
                            value = new SimpleDateFormat("yyyy-MM-dd").parse(value.toString());
                        } catch (ParseException e) {
                            throw new ResourceException(e);
                        }
                    else if (cols.getJSONObject(j).getString("type").equals("timeofday") && value != null)
                        try {
                            value = new SimpleDateFormat("HH:mm:ss").parse(value.toString());
                        } catch (ParseException e) {
                            throw new ResourceException(e);
                        }
                    builder.cell(value, formatted);
                }
                builder.endRow();
            }
            return builder.newTable();
        } catch (JSONException e) {
            throw new ResourceException(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY, e);
        }
    }
    return null;
}
Also used : Table(org.qi4j.library.rest.common.table.Table) JSONObject(org.json.JSONObject) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) ResourceException(org.restlet.resource.ResourceException) ParseException(java.text.ParseException) TableBuilder(org.qi4j.library.rest.common.table.TableBuilder) SimpleDateFormat(java.text.SimpleDateFormat)

Example 84 with JSONArray

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

the class StudyOptionsFragment method createFilteredDeck.

private void createFilteredDeck(JSONArray delays, Object[] terms, Boolean resched) {
    JSONObject dyn;
    if (AnkiDroidApp.colIsOpen()) {
        Collection col = AnkiDroidApp.getCol();
        try {
            String deckName = col.getDecks().current().getString("name");
            String customStudyDeck = getResources().getString(R.string.custom_study_deck_name);
            JSONObject cur = col.getDecks().byName(customStudyDeck);
            if (cur != null) {
                if (cur.getInt("dyn") != 1) {
                    StyledDialog.Builder builder = new StyledDialog.Builder(getActivity());
                    builder.setMessage(R.string.custom_study_deck_exists);
                    builder.setNegativeButton(getResources().getString(R.string.cancel), new OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        //
                        }
                    });
                    builder.create().show();
                    return;
                } else {
                    // safe to empty
                    col.getSched().emptyDyn(cur.getLong("id"));
                    // reuse; don't delete as it may have children
                    dyn = cur;
                    col.getDecks().select(cur.getLong("id"));
                }
            } else {
                long did = col.getDecks().newDyn(customStudyDeck);
                dyn = col.getDecks().get(did);
            }
            // and then set various options
            dyn.put("delays", delays);
            JSONArray ar = dyn.getJSONArray("terms");
            ar.getJSONArray(0).put(0, new StringBuilder("deck:\"").append(deckName).append("\" ").append(terms[0]).toString());
            ar.getJSONArray(0).put(1, terms[1]);
            ar.getJSONArray(0).put(2, terms[2]);
            dyn.put("resched", resched);
            if (mFragmented) {
                Bundle config = new Bundle();
                config.putString("searchSuffix", "'deck:" + dyn.getString("name") + "'");
                initAllContentViews(getLayoutInflater(config));
                finishCongrats();
            } else {
                // Load a new fragment with the filtered deck view. The config passed is null, so it uses the
                // current deck. The deck we just created is internally set as the current deck.
                ((StudyOptionsActivity) getActivity()).loadContent(false, null);
            }
            // Initial rebuild
            mProgressDialog = StyledProgressDialog.show(getActivity(), "", getResources().getString(R.string.rebuild_custom_study_deck), true);
            DeckTask.launchDeckTask(DeckTask.TASK_TYPE_REBUILD_CRAM, mRebuildCustomStudyListener, new DeckTask.TaskData(AnkiDroidApp.getCol(), AnkiDroidApp.getCol().getDecks().selected(), mFragmented));
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }
}
Also used : DialogInterface(android.content.DialogInterface) Bundle(android.os.Bundle) ChartBuilder(com.ichi2.charts.ChartBuilder) StyledDialog(com.ichi2.themes.StyledDialog) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) TaskData(com.ichi2.async.DeckTask.TaskData) DeckTask(com.ichi2.async.DeckTask) JSONObject(org.json.JSONObject) Collection(com.ichi2.libanki.Collection) OnClickListener(android.content.DialogInterface.OnClickListener)

Example 85 with JSONArray

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

the class StudyOptionsFragment method onPrepareDialog.

private void onPrepareDialog(int id, StyledDialog styledDialog) {
    Resources res = getResources();
    switch(id) {
        case DIALOG_CUSTOM_STUDY_DETAILS:
            styledDialog.setTitle(res.getStringArray(R.array.custom_study_options_labels)[mCustomDialogChoice]);
            switch(mCustomDialogChoice + 1) {
                case CUSTOM_STUDY_NEW:
                    if (AnkiDroidApp.colIsOpen()) {
                        Collection col = AnkiDroidApp.getCol();
                        mCustomStudyTextView1.setText(res.getString(R.string.custom_study_new_total_new, col.getSched().totalNewForCurrentDeck()));
                    }
                    mCustomStudyTextView2.setText(res.getString(R.string.custom_study_new_extend));
                    mCustomStudyEditText.setText(Integer.toString(AnkiDroidApp.getSharedPrefs(getActivity()).getInt("extendNew", 10)));
                    styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (AnkiDroidApp.colIsOpen()) {
                                try {
                                    int n = Integer.parseInt(mCustomStudyEditText.getText().toString());
                                    AnkiDroidApp.getSharedPrefs(getActivity()).edit().putInt("extendNew", n).commit();
                                    Collection col = AnkiDroidApp.getCol();
                                    JSONObject deck = col.getDecks().current();
                                    deck.put("extendNew", n);
                                    col.getDecks().save(deck);
                                    col.getSched().extendLimits(n, 0);
                                    resetAndUpdateValuesFromDeck();
                                    finishCongrats();
                                } catch (NumberFormatException e) {
                                    // ignore non numerical values
                                    Themes.showThemedToast(getActivity().getBaseContext(), getResources().getString(R.string.custom_study_invalid_number), false);
                                } catch (JSONException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        }
                    });
                    break;
                case CUSTOM_STUDY_REV:
                    if (AnkiDroidApp.colIsOpen()) {
                        Collection col = AnkiDroidApp.getCol();
                        mCustomStudyTextView1.setText(res.getString(R.string.custom_study_rev_total_rev, col.getSched().totalRevForCurrentDeck()));
                    }
                    mCustomStudyTextView2.setText(res.getString(R.string.custom_study_rev_extend));
                    mCustomStudyEditText.setText(Integer.toString(AnkiDroidApp.getSharedPrefs(getActivity()).getInt("extendRev", 10)));
                    styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (AnkiDroidApp.colIsOpen()) {
                                try {
                                    int n = Integer.parseInt(mCustomStudyEditText.getText().toString());
                                    AnkiDroidApp.getSharedPrefs(getActivity()).edit().putInt("extendRev", n).commit();
                                    Collection col = AnkiDroidApp.getCol();
                                    JSONObject deck = col.getDecks().current();
                                    deck.put("extendRev", n);
                                    col.getDecks().save(deck);
                                    col.getSched().extendLimits(0, n);
                                    resetAndUpdateValuesFromDeck();
                                    finishCongrats();
                                } catch (NumberFormatException e) {
                                    // ignore non numerical values
                                    Themes.showThemedToast(getActivity().getBaseContext(), getResources().getString(R.string.custom_study_invalid_number), false);
                                } catch (JSONException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        }
                    });
                    break;
                case CUSTOM_STUDY_FORGOT:
                    mCustomStudyTextView1.setText("");
                    mCustomStudyTextView2.setText(res.getString(R.string.custom_study_forgotten));
                    mCustomStudyEditText.setText(Integer.toString(AnkiDroidApp.getSharedPrefs(getActivity()).getInt("forgottenDays", 2)));
                    styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            JSONArray ar = new JSONArray();
                            try {
                                int forgottenDays = Integer.parseInt(((EditText) mCustomStudyEditText).getText().toString());
                                ar.put(0, 1);
                                createFilteredDeck(ar, new Object[] { String.format(Locale.US, "rated:%d:1", forgottenDays), 9999, Sched.DYN_RANDOM }, false);
                            } catch (NumberFormatException e) {
                                // ignore non numerical values
                                Themes.showThemedToast(getActivity().getBaseContext(), getResources().getString(R.string.custom_study_invalid_number), false);
                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    });
                    break;
                case CUSTOM_STUDY_AHEAD:
                    mCustomStudyTextView1.setText("");
                    mCustomStudyTextView2.setText(res.getString(R.string.custom_study_ahead));
                    mCustomStudyEditText.setText(Integer.toString(AnkiDroidApp.getSharedPrefs(getActivity()).getInt("aheadDays", 1)));
                    styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            try {
                                int days = Integer.parseInt(((EditText) mCustomStudyEditText).getText().toString());
                                createFilteredDeck(new JSONArray(), new Object[] { String.format(Locale.US, "prop:due<=%d", days), 9999, Sched.DYN_DUE }, true);
                            } catch (NumberFormatException e) {
                                // ignore non numerical values
                                Themes.showThemedToast(getActivity().getBaseContext(), getResources().getString(R.string.custom_study_invalid_number), false);
                            }
                        }
                    });
                    break;
                case CUSTOM_STUDY_RANDOM:
                    mCustomStudyTextView1.setText("");
                    mCustomStudyTextView2.setText(res.getString(R.string.custom_study_random));
                    mCustomStudyEditText.setText(Integer.toString(AnkiDroidApp.getSharedPrefs(getActivity()).getInt("randomCards", 100)));
                    styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            try {
                                int randomCards = Integer.parseInt(((EditText) mCustomStudyEditText).getText().toString());
                                createFilteredDeck(new JSONArray(), new Object[] { "", randomCards, Sched.DYN_RANDOM }, true);
                            } catch (NumberFormatException e) {
                                // ignore non numerical values
                                Themes.showThemedToast(getActivity().getBaseContext(), getResources().getString(R.string.custom_study_invalid_number), false);
                            }
                        }
                    });
                    break;
                case CUSTOM_STUDY_PREVIEW:
                    mCustomStudyTextView1.setText("");
                    mCustomStudyTextView2.setText(res.getString(R.string.custom_study_preview));
                    mCustomStudyEditText.setText(Integer.toString(AnkiDroidApp.getSharedPrefs(getActivity()).getInt("previewDays", 1)));
                    styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String previewDays = ((EditText) mCustomStudyEditText).getText().toString();
                            createFilteredDeck(new JSONArray(), new Object[] { "is:new added:" + previewDays, 9999, Sched.DYN_OLDEST }, false);
                        }
                    });
                    break;
            }
    }
}
Also used : EditText(android.widget.EditText) DialogInterface(android.content.DialogInterface) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) OnClickListener(android.content.DialogInterface.OnClickListener) JSONObject(org.json.JSONObject) Collection(com.ichi2.libanki.Collection) JSONObject(org.json.JSONObject) Resources(android.content.res.Resources)

Aggregations

JSONArray (org.json.JSONArray)1596 JSONObject (org.json.JSONObject)1121 JSONException (org.json.JSONException)690 ArrayList (java.util.ArrayList)303 IOException (java.io.IOException)232 Test (org.junit.Test)199 HashMap (java.util.HashMap)105 ClientException (edu.umass.cs.gnscommon.exceptions.client.ClientException)96 DefaultGNSTest (edu.umass.cs.gnsserver.utils.DefaultGNSTest)61 List (java.util.List)59 HashSet (java.util.HashSet)53 File (java.io.File)49 Query (org.b3log.latke.repository.Query)47 RandomString (edu.umass.cs.gnscommon.utils.RandomString)44 Date (java.util.Date)44 GraphObject (com.abewy.android.apps.klyph.core.graph.GraphObject)43 Map (java.util.Map)40 FileNotFoundException (java.io.FileNotFoundException)37 GuidEntry (edu.umass.cs.gnsclient.client.util.GuidEntry)36 VolleyError (com.android.volley.VolleyError)35