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);
}
}
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;
}
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;
}
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);
}
}
}
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;
}
}
}
Aggregations