Java Examples for com.google.gwt.json.client.JSONArray
The following java examples will help you to understand the usage of com.google.gwt.json.client.JSONArray. These source code samples are taken from different open source projects.
Example 1
Project: gwt-test-utils-master File: JSONArrayPatcher.java View source code |
private static List<JSONValue> getInnerList(JSONArray jsonArray) {
JavaScriptObject jsArray = jsonArray.getJavaScriptObject();
List<JSONValue> list = JavaScriptObjects.getObject(jsArray, JSONARRAY_LIST);
if (list == null) {
list = new ArrayList<JSONValue>();
JavaScriptObjects.setProperty(jsArray, JSONARRAY_LIST, list);
}
return list;
}
Example 2
Project: appinventor-sources-master File: TemplateUploadWizard.java View source code |
/**
* Sets the dynamic template Urls from a jsonStr. This method is
* called during start up where jsonStr is retrieved from User
* settings.
*
* @param jsonStr
*/
public static void setStoredTemplateUrls(String jsonStr) {
if (jsonStr == null || jsonStr.length() == 0)
return;
JSONValue jsonVal = JSONParser.parseLenient(jsonStr);
JSONArray jsonArr = jsonVal.isArray();
for (int i = 0; i < jsonArr.size(); i++) {
JSONValue value = jsonArr.get(i);
JSONString str = value.isString();
dynamicTemplateUrls.add(str.stringValue());
}
}
Example 3
Project: che-master File: ClientJsonImpl.java View source code |
@Override
public void writeImports(PrintWriter out) {
out.println("import com.google.gwt.json.client.JSONParser;");
out.println("import com.google.gwt.json.client.JSONObject;");
out.println("import com.google.gwt.json.client.JSONArray;");
out.println("import com.google.gwt.json.client.JSONString;");
out.println("import com.google.gwt.json.client.JSONNumber;");
out.println("import com.google.gwt.json.client.JSONBoolean;");
out.println("import com.google.gwt.json.client.JSONValue;");
out.println("import com.google.gwt.json.client.JSONNull;");
}
Example 4
Project: che-plugins-master File: DebuggerEventListUnmarshallerWS.java View source code |
/** {@inheritDoc} */
@Override
public void unmarshal(Message response) throws UnmarshallerException {
this.events.setEvents(new ArrayList<DebuggerEvent>());
JSONObject jsonObject = JSONParser.parseStrict(response.getBody()).isObject();
if (jsonObject == null) {
return;
}
if (jsonObject.containsKey("events")) {
JSONArray events = jsonObject.get("events").isArray();
for (int i = 0; i < events.size(); i++) {
JSONObject event = events.get(i).isObject();
if (event.containsKey("type")) {
final int type = (int) event.get("type").isNumber().doubleValue();
if (DebuggerEvent.BREAKPOINT == type) {
BreakPointEvent breakPointEvent = dtoFactory.createDtoFromJson(event.toString(), BreakPointEvent.class);
this.events.getEvents().add(breakPointEvent);
} else if (DebuggerEvent.STEP == type) {
StepEvent stepEvent = dtoFactory.createDtoFromJson(event.toString(), StepEvent.class);
this.events.getEvents().add(stepEvent);
} else if (DebuggerEvent.BREAKPOINT_ACTIVATED == type) {
BreakpointActivatedEvent breakpointActivatedEvent = dtoFactory.createDtoFromJson(event.toString(), BreakpointActivatedEvent.class);
this.events.getEvents().add(breakpointActivatedEvent);
}
}
}
}
}
Example 5
Project: DevTools-master File: ClientJsonImpl.java View source code |
@Override
public void writeImports(PrintWriter out) {
out.println("import com.google.gwt.json.client.JSONParser;");
out.println("import com.google.gwt.json.client.JSONObject;");
out.println("import com.google.gwt.json.client.JSONArray;");
out.println("import com.google.gwt.json.client.JSONString;");
out.println("import com.google.gwt.json.client.JSONNumber;");
out.println("import com.google.gwt.json.client.JSONBoolean;");
out.println("import com.google.gwt.json.client.JSONValue;");
out.println("import com.google.gwt.json.client.JSONNull;");
}
Example 6
Project: gwt-three.js-test-master File: Geometry.java View source code |
/** * FORMAT4 cant read directly JSONParser * use data.data * @return */ public final JSONObject gwtJSONWithBone() { JavaScriptObject core = toJSON(); JSONObject root = new JSONObject(core); JSONObject object = root.get("data").isObject(); //set bone JsArray<AnimationBone> bones = getBones(); if (bones != null) { JSONArray array = new JSONArray(bones); object.put("bones", array); } else { // object.put("bones", new JSONArray()); } int influencesPerVertex = gwtGetInfluencesPerVertex(); object.put("influencesPerVertex", new JSONNumber(influencesPerVertex)); JsArray<Vector4> skinIndices = getSkinIndices(); if (skinIndices != null) { JsArrayNumber indices = JavaScriptObject.createArray().cast(); for (int i = 0; i < skinIndices.length(); i++) { for (int j = 0; j < influencesPerVertex; j++) { indices.push(skinIndices.get(i).gwtGet(j)); } } object.put("skinIndices", new JSONArray(indices)); } else { // object.put("skinIndices", new JSONArray()); } JsArray<Vector4> skinWeights = getSkinWeights(); if (skinWeights != null) { JsArrayNumber weights = JavaScriptObject.createArray().cast(); for (int i = 0; i < skinWeights.length(); i++) { for (int j = 0; j < influencesPerVertex; j++) { weights.push(skinWeights.get(i).gwtGet(j)); } } object.put("skinWeights", new JSONArray(weights)); } else { // object.put("skinWeights", new JSONArray()); } return root; }
Example 7
Project: opennms_dashboard-master File: ChartUtils.java View source code |
public static DataTable convertJSONToDataTable(String text) { DataTable dataTable = DataTable.create(); dataTable.addColumn(ColumnType.DATETIME, "Date"); dataTable.addColumn(ColumnType.NUMBER, "DNS-AAAA"); dataTable.addColumn(ColumnType.STRING, "title1"); dataTable.addColumn(ColumnType.STRING, "text1"); dataTable.addColumn(ColumnType.NUMBER, "DNS-A"); dataTable.addColumn(ColumnType.STRING, "title2"); dataTable.addColumn(ColumnType.STRING, "text2"); dataTable.addColumn(ColumnType.NUMBER, "HTTP-v6"); dataTable.addColumn(ColumnType.STRING, "title2"); dataTable.addColumn(ColumnType.STRING, "text2"); dataTable.addColumn(ColumnType.NUMBER, "HTTP-v4"); dataTable.addColumn(ColumnType.STRING, "title2"); dataTable.addColumn(ColumnType.STRING, "text2"); JSONObject jsonData = (JSONObject) JSONParser.parseStrict(text); JSONObject data; if (jsonData.get("data").isObject() != null) { data = jsonData.get("data").isObject(); JSONArray values = data.get("values").isArray(); dataTable.addRow(); Date date = new Date(Long.valueOf(data.get("time").isString().stringValue())); dataTable.setValue(0, 0, date); for (int i = 0; i < values.size(); i++) { JSONObject value = values.get(i).isObject(); if (value != null) { String application = value.get("application").isString().stringValue(); insertApplicationData(dataTable, 0, value, application); } } } else if (jsonData.get("data").isArray() != null) { JSONArray d = jsonData.get("data").isArray(); for (int j = 0; j < d.size(); j++) { JSONObject dataPoint = d.get(j).isObject(); JSONArray values = dataPoint.get("values").isArray(); dataTable.addRow(); Date date = new Date(Long.valueOf(dataPoint.get("time").isString().stringValue())); dataTable.setValue(j, 0, date); for (int i = 0; i < values.size(); i++) { JSONObject value = values.get(i).isObject(); if (value != null) { String application = value.get("application").isString().stringValue(); insertApplicationData(dataTable, j, value, application); } } } } return dataTable; }
Example 8
Project: RUSSEL-master File: EditScreen.java View source code |
/**
* processServerZipIds0 Processes the imported node IDs when a zip was unzipped on the server side.
* @param ESBPacket esbPacket
*/
private final void processServerZipIds0(ESBPacket esbPacket) {
JSONArray rawImport = esbPacket.getArray("importedIDs");
for (int importIndex = 0; importIndex < rawImport.size(); importIndex++) {
RUSSELFileRecord node = new RUSSELFileRecord();
String[] importPair = rawImport.get(importIndex).toString().split(";");
node.setGuid(importPair[0]);
node.setFilename(importPair[1]);
FileHandler.addPendingServerZip(node);
}
}
Example 9
Project: tsdash-master File: HTTPService.java View source code |
public void loadTimeSeries(TimeRange timeRange, ArrayList<Metric> metrics, final AsyncCallback<TimeSeriesResponse> callback) { // encode parameters JSONObject paramObj = new JSONObject(); paramObj.put("tsFrom", new JSONNumber(timeRange.from / 1000)); paramObj.put("tsTo", new JSONNumber(timeRange.to / 1000)); JSONArray metricsArray = new JSONArray(); for (int i = 0; i < metrics.size(); i++) { if (metrics.get(i).isPlottable()) { metricsArray.set(i, metrics.get(i).toJSONParam()); } } paramObj.put("metrics", metricsArray); String param = "params=" + paramObj.toString(); get(callback, DATA_URL, param, new TimeSeriesDecoder()); }
Example 10
Project: wbi-master File: JSONSerializer.java View source code |
/** * Produce a {@code JSONValue} from the specified {@code Object}. * * @param object {@code Object}. * @return {@code JSONValue}. */ private JSONValue toJSONValue(Object object) { // Null if (object == null) { return JSONNull.getInstance(); } // Boolean Boolean asBoolean = Utils.isBoolean(object); if (asBoolean != null) { return JSONBoolean.getInstance(asBoolean); } // Integer Integer asInteger = Utils.isInteger(object); if (asInteger != null) { return new JSONNumber(asInteger); } // Long Long asLong = Utils.isLong(object); if (asLong != null) { return new JSONNumber(asLong); } // Float Float asFloat = Utils.isFloat(object); if (asFloat != null) { return new JSONNumber(asFloat); } // Double Double asDouble = Utils.isDouble(object); if (asDouble != null) { return new JSONNumber(asDouble); } // String String asString = Utils.isString(object); if (asString != null) { return new JSONString(asString); } // Enum Enum asEnum = Utils.isEnum(object); if (asEnum != null) { return new JSONString(asEnum.toString()); } // Serializable Serializable asSerializable = Utils.isSerializable(object); if (asSerializable != null) { JSONObject jsonObject = new JSONObject(); for (String field : asSerializable.fields().keySet()) { Object value = asSerializable.get(field); jsonObject.put(field, toJSONValue(value)); } return jsonObject; } // List List<Object> asSerializableList = Utils.isSerializableList(object); if (asSerializableList != null) { JSONArray jsonArray = new JSONArray(); for (int i = 0; i < asSerializableList.size(); i++) { Object item = asSerializableList.get(i); jsonArray.set(i, toJSONValue(item)); } return jsonArray; } // Map Map<Object, Object> asSerializableMap = Utils.isSerializableMap(object); if (asSerializableMap != null) { JSONObject jsonObject = new JSONObject(); for (Map.Entry<Object, Object> entry : asSerializableMap.entrySet()) { Object keyObject = entry.getKey(); Object valueObject = entry.getValue(); String key = null; String keyAsString = Utils.isString(keyObject); if (keyAsString != null) { key = keyAsString; } Enum keyAsEnum = Utils.isEnum(keyObject); if (keyAsEnum != null) { key = keyAsEnum.toString(); } jsonObject.put(key, toJSONValue(valueObject)); } return jsonObject; } return null; }
Example 11
Project: calendar-app-master File: CourseViewController.java View source code |
public void onResponseReceived(Request request, Response response) { try { JSONArray parsedArray = (JSONArray) JSONParser.parse(response.getText()); // remove the selected courses // filtered array JSONArray filteredArray = new JSONArray(); int filtered_index = 0; for (int i = 0; i < parsedArray.size(); i++) { JSONObject o = (JSONObject) parsedArray.get(i); int id = (int) ((JSONNumber) o.get("id")).doubleValue(); if (!isSelected(id)) { filteredArray.set(filtered_index++, o); } } // clear out the view so we can add courses view_.clear(); // add the selected values first for (int index : selectionIndexes_) { view_.addCourse(index, selectionValues_.get(index), true); } // add the remaining courses view_.loadJSON(filteredArray); } catch (Throwable e) { app_.error("Error: " + response.getText(), e); } }
Example 12
Project: cmestemp22-master File: StreamPanel.java View source code |
public void update(final StreamRequestEvent event) {
if (event.getForceReload() || !event.getJson().equals(jsonQuery)) {
streamName = event.getStreamName();
jsonQuery = event.getJson();
if (activityId != 0L) {
ActivityModel.getInstance().fetch(activityId, false);
} else {
setListMode();
stream.reinitialize();
String titleLinkUrl = null;
String updatedJson = jsonQuery;
JSONObject queryObject = JSONParser.parse(updatedJson).isObject().get("query").isObject();
// Only show cancel option if search is not part of the view.
Boolean canChange = !queryObject.containsKey("keywords");
if (queryObject.containsKey("keywords")) {
final String streamSearchText = queryObject.get("keywords").isString().stringValue();
searchBoxWidget.setSearchTerm(streamSearchText);
searchStatusWidget.setSearchTerm(streamSearchText);
updatedJson = StreamJsonRequestFactory.setSearchTerm(streamSearchText, StreamJsonRequestFactory.getJSONRequest(updatedJson)).toString();
} else if (!search.isEmpty()) {
searchBoxWidget.setSearchTerm(search);
searchStatusWidget.setSearchTerm(search);
updatedJson = StreamJsonRequestFactory.setSearchTerm(search, StreamJsonRequestFactory.getJSONRequest(updatedJson)).toString();
} else // see if the stream belongs to a group and set up the stream title as a link
if (queryObject.containsKey("recipient") && queryObject.get("recipient").isArray().size() == 1) {
JSONArray recipientArr = queryObject.get("recipient").isArray();
JSONObject recipientObj = recipientArr.get(0).isObject();
// only show the link if viewing a group stream on the activity page
if ("GROUP".equals(recipientObj.get("type").isString().stringValue()) && Session.getInstance().getUrlPage() == Page.ACTIVITY) {
String shortName = recipientObj.get("name").isString().stringValue();
titleLinkUrl = Session.getInstance().generateUrl(new CreateUrlRequest(Page.GROUPS, shortName));
}
searchBoxWidget.onSearchCanceled();
searchStatusWidget.onSearchCanceled();
} else {
searchBoxWidget.onSearchCanceled();
searchStatusWidget.onSearchCanceled();
}
sort = sortPanel.getSort();
updatedJson = StreamJsonRequestFactory.setSort(sort, StreamJsonRequestFactory.getJSONRequest(updatedJson)).toString();
streamTitleWidget.setStreamTitle(streamName, titleLinkUrl);
addGadgetWidget.setStreamTitle(streamName);
searchBoxWidget.setCanChange(canChange);
searchStatusWidget.setCanChange(canChange);
StreamModel.getInstance().fetch(updatedJson, false);
}
}
}
Example 13
Project: eurekastreams-master File: ActivityContent.java View source code |
public void update(final GotCurrentUserStreamBookmarks event) {
bookmarkList.clear();
bookmarksWidgetMap.clear();
List<StreamFilter> sortedStreamFilters = event.getResponse();
Collections.sort(sortedStreamFilters, new StreamFilterNameComparator());
for (final StreamFilter filter : sortedStreamFilters) {
JSONObject req = StreamJsonRequestFactory.getJSONRequest(filter.getRequest());
String uniqueId = null;
String entityType = null;
String imgUrl = "";
if (req.containsKey("query")) {
JSONObject query = req.get("query").isObject();
if (query.containsKey(StreamJsonRequestFactory.RECIPIENT_KEY)) {
JSONArray recipient = query.get(StreamJsonRequestFactory.RECIPIENT_KEY).isArray();
if (recipient.size() > 0) {
JSONObject recipientObj = recipient.get(0).isObject();
uniqueId = recipientObj.get("name").isString().stringValue();
entityType = recipientObj.get("type").isString().stringValue().toLowerCase();
AvatarUrlGenerator urlGen = groupUrlGen;
if ("person".equals(entityType)) {
urlGen = personUrlGen;
}
imgUrl = urlGen.getSmallAvatarUrl(filter.getOwnerAvatarId());
}
}
}
if (uniqueId != null && entityType != null) {
String bookmarkUrl = entityType + "/" + uniqueId;
StreamNamePanel bookmarkFilter = createPanel(filter.getName(), bookmarkUrl, imgUrl, new ClickHandler() {
public void onClick(final ClickEvent event) {
if (new WidgetJSNIFacadeImpl().confirm("Are you sure you want to delete this bookmark?")) {
StreamBookmarksModel.getInstance().delete(filter.getId());
}
event.stopPropagation();
}
}, style.deleteBookmark(), "", true);
bookmarkList.add(bookmarkFilter);
bookmarksWidgetMap.put(bookmarkUrl, bookmarkFilter);
}
}
if (sortedStreamFilters.size() == 0) {
Label defaultLabel = new Label("Bookmarks allow you to quickly jump to any stream in Eureka.");
defaultLabel.addStyleName(style.noBookmarksMessage());
bookmarkList.add(defaultLabel);
}
bookmarksLoaded = true;
checkInit();
}
Example 14
Project: gae-studio-master File: PropertyUtil.java View source code |
public static JSONValue cleanUpMetadata(JSONValue property) {
JSONValue result = property;
JSONObject object = property.isObject();
if (object != null) {
result = cleanUpObjectMetadata(object);
}
JSONArray array = property.isArray();
if (array != null) {
result = cleanUpArrayMetadata(array);
}
return result;
}
Example 15
Project: geomajas-project-client-gwt2-master File: JsonService.java View source code |
/** * Get a child JSON array from a parent JSON object. * * @param jsonObject The parent JSON object. * @param key The name of the child object. * @return Returns the child JSON array if it could be found, or null if the value was null. * @throws JSONException In case something went wrong while searching for the child. */ public static JSONArray getChildArray(JSONObject jsonObject, String key) throws JSONException { checkArguments(jsonObject, key); JSONValue value = jsonObject.get(key); if (value != null) { if (value.isArray() != null) { return value.isArray(); } else if (value.isNull() != null) { return null; } throw new JSONException("Child is not a JSONArray, but a: " + value.getClass()); } return null; }
Example 16
Project: gwt-client-util-master File: JsonUtil.java View source code |
/**
* Convert the JSON string array into a Java string array
* @param jsonArrayString
* the JSON string array
* @return
* the Java strings
*/
public static String[] toStringArray(String jsonArrayString) {
JSONValue jsonStrains = JSONParser.parse(jsonArrayString);
JSONArray jsonStrainsArray = jsonStrains.isArray();
if (jsonStrainsArray != null) {
final String[] stringArray = new String[jsonStrainsArray.size()];
for (int i = 0; i < stringArray.length; i++) {
JSONString currString = jsonStrainsArray.get(i).isString();
if (currString != null) {
stringArray[i] = currString.stringValue();
} else {
return null;
}
}
return stringArray;
} else {
return null;
}
}
Example 17
Project: hexa.tools-master File: ServiceGenerator.java View source code |
@Override
public String generate(TreeLogger logger, GeneratorContext context, String requestedClass) throws UnableToCompleteException {
this.logger = logger;
logger.log(TreeLogger.INFO, "Generate '" + requestedClass, null);
this.context = context;
typeOracle = context.getTypeOracle();
JClassType requestedType = typeOracle.findType(requestedClass);
if (requestedType == null) {
logger.log(TreeLogger.ERROR, "Type '" + requestedClass + "' has not been found by the Oracle", null);
throw new UnableToCompleteException();
}
proxiesToGenerate = new HashMap<String, JClassType>();
marshallsToGenerate = new HashMap<String, JType>();
onResponseCallbacks = new ArrayList<OnResponseCallbackInfo>();
dataProxyFastFactories = new HashSet<JType>();
requestedClassName = requestedType.getName();
createdClassName = requestedClassName + "Impl";
fullCreatedClassName = requestedClass + "Impl";
packageName = requestedType.getPackage().getName();
PrintWriter printWriter = context.tryCreate(logger, packageName, createdClassName);
if (printWriter == null) {
// " : CANNOT CREATE PRINT WRITER", null );
return fullCreatedClassName;
}
ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(packageName, createdClassName);
composerFactory.setSuperclass("ServiceBase");
composerFactory.addImplementedInterface(requestedClass);
composerFactory.addImport("fr.lteconsulting.hexa.client.comm.ServiceBase");
composerFactory.addImport("java.util.ArrayList");
composerFactory.addImport("java.util.List");
composerFactory.addImport("java.util.HashMap");
composerFactory.addImport("java.util.Iterator");
composerFactory.addImport("java.util.Map.Entry");
composerFactory.addImport("fr.lteconsulting.hexa.client.comm.GenericJSO");
composerFactory.addImport("com.google.gwt.core.client.JavaScriptObject");
composerFactory.addImport("fr.lteconsulting.hexa.client.comm.DataProxy");
composerFactory.addImport("fr.lteconsulting.hexa.client.comm.Service");
composerFactory.addImport("fr.lteconsulting.hexa.client.comm.RequestDesc");
composerFactory.addImport("fr.lteconsulting.hexa.client.comm.RPCProxy");
composerFactory.addImport("fr.lteconsulting.hexa.client.comm.AcceptsRPCRequests");
composerFactory.addImport("fr.lteconsulting.hexa.client.comm.ResponseJSO");
composerFactory.addImport("fr.lteconsulting.hexa.client.comm.JSArrayIterator");
composerFactory.addImport("fr.lteconsulting.hexa.client.comm.JSOArrayInteger");
composerFactory.addImport("fr.lteconsulting.hexa.client.comm.XRPCProxy");
composerFactory.addImport("fr.lteconsulting.hexa.client.interfaces.ITablesManager");
composerFactory.addImport("fr.lteconsulting.hexa.client.interfaces.IAsyncCallback");
composerFactory.addImport("fr.lteconsulting.hexa.client.comm.XRPCRequest");
composerFactory.addImport("com.google.gwt.core.client.GWT");
composerFactory.addImport("com.google.gwt.core.client.JsArray");
composerFactory.addImport("com.google.gwt.core.client.JsArrayInteger");
composerFactory.addImport("com.google.gwt.core.client.JsArrayString");
composerFactory.addImport("com.google.gwt.http.client.URL");
composerFactory.addImport("com.google.gwt.user.client.Window");
composerFactory.addImport("com.google.gwt.user.client.rpc.AsyncCallback");
composerFactory.addImport("fr.lteconsulting.hexa.client.common.HexaDate");
composerFactory.addImport("fr.lteconsulting.hexa.client.common.HexaTime");
composerFactory.addImport("fr.lteconsulting.hexa.client.common.HexaDateTime");
composerFactory.addImport("fr.lteconsulting.hexa.client.comm.FactoredInterface");
composerFactory.addImport("com.google.gwt.json.client.JSONValue");
composerFactory.addImport("com.google.gwt.json.client.JSONObject");
composerFactory.addImport("com.google.gwt.json.client.JSONArray");
composerFactory.addImport("com.google.gwt.json.client.JSONString");
composerFactory.addImport("com.google.gwt.json.client.JSONNumber");
composerFactory.addImport("fr.lteconsulting.hexa.client.comm.callparams.ListMarshall");
composerFactory.addImport("fr.lteconsulting.hexa.client.comm.callparams.SetMarshall");
composerFactory.addImport("fr.lteconsulting.hexa.client.comm.callparams.MapMarshall");
sw = composerFactory.createSourceWriter(context, printWriter);
if (sw == null) {
// " : CANNOT CREATE SOURCEWRITER", null );
return fullCreatedClassName;
}
JMethod[] methods = requestedType.getMethods();
String interfaceChecksum = generateChecksum(methods);
// generate server com initialisation method
sw.println("public void Init( AcceptsRPCRequests server )");
sw.println("{");
sw.println(" setConfig( server, \"" + interfaceChecksum + "\" );");
sw.println("}");
sw.println();
for (int i = 0; i < methods.length; i++) {
generateMethod(requestedClassName, interfaceChecksum, methods[i], i);
sw.println();
}
generateCallParamMarshalls();
generateOnResponseCallbacks();
generateDataProxyFastJSOClasses();
generateProxies();
sw.commit(logger);
// Generate the PHP interop service interface file
OutputStream phpStream = context.tryCreateResource(logger, requestedClassName + ".interface.php");
if (phpStream != null) {
PrintWriter phpPw = new PrintWriter(phpStream);
generatePHP(phpPw, requestedType, interfaceChecksum);
phpPw.flush();
context.commitResource(logger, phpStream);
}
// Generate the PHP interop service interface file
String javaInterfaceName = requestedClassName + "ServerSide";
OutputStream javaStream = context.tryCreateResource(logger, javaInterfaceName + ".java");
if (javaStream != null) {
PrintWriter javaPw = new PrintWriter(javaStream);
generateJavaInterface(javaPw, javaInterfaceName, requestedType, interfaceChecksum);
javaPw.flush();
context.commitResource(logger, javaStream);
}
return fullCreatedClassName;
}
Example 18
Project: incubator-wave-master File: GadgetDataStoreImpl.java View source code |
@Override public void getGadgetData(final String gadgetSpecUrl, WaveletName waveletName, int instanceId, final DataCallback receiveDataCommand) { cleanupExpiredCache(); final String secureGadgetDataKey = waveletName.waveId + " " + waveletName.waveletId + " " + instanceId + " " + gadgetSpecUrl; if (fetchDataByKey(secureGadgetDataKey, receiveDataCommand)) { return; } final String nonSecureGadgetDataKey = gadgetSpecUrl; if (fetchDataByKey(nonSecureGadgetDataKey, receiveDataCommand)) { return; } JSONObject request = new JSONObject(); JSONObject requestContext = new JSONObject(); JSONArray gadgets = new JSONArray(); JSONObject gadget = new JSONObject(); try { gadget.put("url", new JSONString(gadgetSpecUrl)); gadgets.set(0, gadget); requestContext.put("container", new JSONString("wave")); request.put("context", requestContext); request.put("gadgets", gadgets); RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, GADGET_METADATA_PATH); builder.sendRequest(request.toString(), new RequestCallback() { public void onError(Request request, Throwable exception) { receiveDataCommand.onError("Error retrieving metadata from the server.", exception); } public void onResponseReceived(Request request, Response response) { JSONObject gadgetMetadata = null; try { gadgetMetadata = JSONParser.parseLenient(response.getText()).isObject().get("gadgets").isArray().get(0).isObject(); } catch (NullPointerException exception) { receiveDataCommand.onError("Error in gadget metadata JSON.", exception); } if (gadgetMetadata != null) { GadgetMetadata metadata = new GadgetMetadata(gadgetMetadata); // TODO: Security token is unused therefore the gadget is stored // under the non secure key. String securityToken = null; metadataMap.put(nonSecureGadgetDataKey, new CacheElement(metadata, securityToken)); receiveDataCommand.onDataReady(metadata, securityToken); } else { receiveDataCommand.onError("Error in gadget metadata JSON.", null); } } }); } catch (RequestException e) { receiveDataCommand.onError("Unable to process gadget request.", e); } }
Example 19
Project: KKPortal-master File: JsonList.java View source code |
@Override
public List<T> fromJson(JSONValue jsonValue, List<Class<?>> subtypes, FrameEncoder<JSONValue> encoder) throws UnableToDeserialize {
JSONArray jsonArray = jsonValue.isArray();
if (jsonArray == null)
throw new UnableToDeserialize("Expected Json Array");
List<T> list = new ArrayList<T>();
for (int i = 0, l = jsonArray.size(); i < l; i++) {
T result = null;
// result = encoder.test(jsonArray.get(i),subtypes,result);
result = encoder.validate(jsonArray.get(i), result, subtypes.toArray(new Class<?>[subtypes.size()]));
list.add(result);
}
return list;
}
Example 20
Project: nexus-core-master File: RepositoriesDataStore.java View source code |
public void setElements(JSONArray repos) {
super.setElements(repos);
List proxies = new ArrayList();
List hosteds = new ArrayList();
List virtuals = new ArrayList();
for (int i = 0; i < repos.size(); i++) {
String repoType = repos.get(i).isObject().get("repoType").isString().stringValue();
if ("proxy".equals(repoType)) {
proxies.add(repos.get(i));
} else if ("hosted".equals(repoType)) {
hosteds.add(repos.get(i));
} else if ("virtual".equals(repoType)) {
virtuals.add(repos.get(i));
}
}
proxy.setElements(proxies);
hosted.setElements(hosteds);
virtual.setElements(virtuals);
}
Example 21
Project: pentaho-commons-gwt-modules-master File: ScheduleRecurrenceDialog.java View source code |
protected JSONObject getJsonComplexTrigger(ScheduleType scheduleType, MonthOfYear month, WeekOfMonth weekOfMonth, List<DayOfWeek> daysOfWeek, Date startDate, Date endDate) { JSONObject trigger = new JSONObject(); //$NON-NLS-1$ trigger.put("uiPassParam", new JSONString(scheduleEditorWizardPanel.getScheduleType().name())); if (month != null) { JSONArray jsonArray = new JSONArray(); jsonArray.set(0, new JSONString(Integer.toString(month.ordinal()))); //$NON-NLS-1$ trigger.put("monthsOfYear", jsonArray); } if (weekOfMonth != null) { JSONArray jsonArray = new JSONArray(); jsonArray.set(0, new JSONString(Integer.toString(weekOfMonth.ordinal()))); //$NON-NLS-1$ trigger.put("weeksOfMonth", jsonArray); } if (daysOfWeek != null) { JSONArray jsonArray = new JSONArray(); int index = 0; for (DayOfWeek dayOfWeek : daysOfWeek) { jsonArray.set(index++, new JSONString(Integer.toString(dayOfWeek.ordinal()))); } //$NON-NLS-1$ trigger.put("daysOfWeek", jsonArray); } addJsonStartEnd(trigger, startDate, endDate); return trigger; }
Example 22
Project: pentaho-gwt-modules-master File: ScheduleRecurrenceDialog.java View source code |
protected JSONObject getJsonComplexTrigger(ScheduleType scheduleType, MonthOfYear month, WeekOfMonth weekOfMonth, List<DayOfWeek> daysOfWeek, Date startDate, Date endDate) { JSONObject trigger = new JSONObject(); //$NON-NLS-1$ trigger.put("uiPassParam", new JSONString(scheduleEditorWizardPanel.getScheduleType().name())); if (month != null) { JSONArray jsonArray = new JSONArray(); jsonArray.set(0, new JSONString(Integer.toString(month.ordinal()))); //$NON-NLS-1$ trigger.put("monthsOfYear", jsonArray); } if (weekOfMonth != null) { JSONArray jsonArray = new JSONArray(); jsonArray.set(0, new JSONString(Integer.toString(weekOfMonth.ordinal()))); //$NON-NLS-1$ trigger.put("weeksOfMonth", jsonArray); } if (daysOfWeek != null) { JSONArray jsonArray = new JSONArray(); int index = 0; for (DayOfWeek dayOfWeek : daysOfWeek) { jsonArray.set(index++, new JSONString(Integer.toString(dayOfWeek.ordinal()))); } //$NON-NLS-1$ trigger.put("daysOfWeek", jsonArray); } addJsonStartEnd(trigger, startDate, endDate); return trigger; }
Example 23
Project: plugin-java-master File: Parser.java View source code |
private static String[] parseJsonArray(JSONValue value) {
if (value.isObject() != null) {
value = value.isObject().get("rsc").isArray();
}
if (value.isArray() == null)
throw new IllegalArgumentException("'json' parameter must represent a JSON array");
JSONArray array = value.isArray();
String result[] = new String[array.size()];
for (int i = 0; i < array.size(); i++) {
result[i] = array.get(i).isNull() == null ? array.get(i).isString().stringValue() : null;
}
return result;
}
Example 24
Project: socom-master File: AbstractGraph.java View source code |
private long[] getNodes() {
JSONArray contexts = graph.get("contexts").isArray();
long[] nodes = new long[contexts.size()];
for (int i = 0; i < contexts.size(); i++) {
JSONObject contextobject = contexts.get(i).isObject();
nodes[i] = (long) (contextobject.get("id").isNumber().doubleValue());
}
return nodes;
}
Example 25
Project: swellrt-master File: GadgetDataStoreImpl.java View source code |
@Override public void getGadgetData(final String gadgetSpecUrl, WaveletName waveletName, int instanceId, final DataCallback receiveDataCommand) { cleanupExpiredCache(); final String secureGadgetDataKey = waveletName.waveId + " " + waveletName.waveletId + " " + instanceId + " " + gadgetSpecUrl; if (fetchDataByKey(secureGadgetDataKey, receiveDataCommand)) { return; } final String nonSecureGadgetDataKey = gadgetSpecUrl; if (fetchDataByKey(nonSecureGadgetDataKey, receiveDataCommand)) { return; } JSONObject request = new JSONObject(); JSONObject requestContext = new JSONObject(); JSONArray gadgets = new JSONArray(); JSONObject gadget = new JSONObject(); try { gadget.put("url", new JSONString(gadgetSpecUrl)); gadgets.set(0, gadget); requestContext.put("container", new JSONString("wave")); request.put("context", requestContext); request.put("gadgets", gadgets); RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, GADGET_METADATA_PATH); builder.sendRequest(request.toString(), new RequestCallback() { public void onError(Request request, Throwable exception) { receiveDataCommand.onError("Error retrieving metadata from the server.", exception); } public void onResponseReceived(Request request, Response response) { JSONObject gadgetMetadata = null; try { gadgetMetadata = JSONParser.parseLenient(response.getText()).isObject().get("gadgets").isArray().get(0).isObject(); } catch (NullPointerException exception) { receiveDataCommand.onError("Error in gadget metadata JSON.", exception); } if (gadgetMetadata != null) { GadgetMetadata metadata = new GadgetMetadata(gadgetMetadata); // TODO: Security token is unused therefore the gadget is stored // under the non secure key. String securityToken = null; metadataMap.put(nonSecureGadgetDataKey, new CacheElement(metadata, securityToken)); receiveDataCommand.onDataReady(metadata, securityToken); } else { receiveDataCommand.onError("Error in gadget metadata JSON.", null); } } }); } catch (RequestException e) { receiveDataCommand.onError("Unable to process gadget request.", e); } }
Example 26
Project: Wave-master File: GadgetDataStoreImpl.java View source code |
@Override public void getGadgetData(final String gadgetSpecUrl, WaveletName waveletName, int instanceId, final DataCallback receiveDataCommand) { cleanupExpiredCache(); final String secureGadgetDataKey = waveletName.waveId + " " + waveletName.waveletId + " " + instanceId + " " + gadgetSpecUrl; if (fetchDataByKey(secureGadgetDataKey, receiveDataCommand)) { return; } final String nonSecureGadgetDataKey = gadgetSpecUrl; if (fetchDataByKey(nonSecureGadgetDataKey, receiveDataCommand)) { return; } JSONObject request = new JSONObject(); JSONObject requestContext = new JSONObject(); JSONArray gadgets = new JSONArray(); JSONObject gadget = new JSONObject(); try { gadget.put("url", new JSONString(gadgetSpecUrl)); gadgets.set(0, gadget); requestContext.put("container", new JSONString("wave")); request.put("context", requestContext); request.put("gadgets", gadgets); RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, GADGET_METADATA_PATH); builder.sendRequest(request.toString(), new RequestCallback() { public void onError(Request request, Throwable exception) { receiveDataCommand.onError("Error retrieving metadata from the server.", exception); } public void onResponseReceived(Request request, Response response) { JSONObject gadgetMetadata = null; try { gadgetMetadata = JSONParser.parseLenient(response.getText()).isObject().get("gadgets").isArray().get(0).isObject(); } catch (NullPointerException exception) { receiveDataCommand.onError("Error in gadget metadata JSON.", exception); } if (gadgetMetadata != null) { GadgetMetadata metadata = new GadgetMetadata(gadgetMetadata); // TODO: Security token is unused therefore the gadget is stored // under the non secure key. String securityToken = null; metadataMap.put(nonSecureGadgetDataKey, new CacheElement(metadata, securityToken)); receiveDataCommand.onDataReady(metadata, securityToken); } else { receiveDataCommand.onError("Error in gadget metadata JSON.", null); } } }); } catch (RequestException e) { receiveDataCommand.onError("Unable to process gadget request.", e); } }
Example 27
Project: akjava_gwtlib-master File: JSONFormatConverter.java View source code |
public static List<JSONObject> convertToJSONObject(JSONValue value) {
List<JSONObject> objects = Lists.newArrayList();
JSONArray array = value.isArray();
if (array == null) {
return null;
}
for (int i = 0; i < array.size(); i++) {
JSONValue v = array.get(i);
if (v != null) {
JSONObject object = v.isObject();
if (object != null) {
objects.add(object);
}
}
}
return objects;
}
Example 28
Project: bitcoin-transaction-explorer-master File: BitcoinJSONViewer.java View source code |
private void display(final int n, final FlowPanel container, final JSONValue tree) {
JSONObject jsonObject;
JSONString jsonString;
JSONNumber jsonNumber;
JSONArray jsonArray;
final JSONBoolean jsonBoolean;
// Just wanna point out the internal workings of JSONValue are weird as fuck
if ((jsonObject = tree.isObject()) != null) {
drawObject(container, n, jsonObject);
} else if ((jsonString = tree.isString()) != null) {
drawString(container, jsonString.stringValue());
} else if ((jsonNumber = tree.isNumber()) != null) {
drawNumber(container, jsonNumber.doubleValue());
} else if (tree.isNull() != null) {
drawNull(container);
} else if ((jsonArray = tree.isArray()) != null) {
drawArray(n, container, jsonArray);
} else if ((jsonBoolean = tree.isBoolean()) != null) {
drawBoolean(container, jsonBoolean.booleanValue());
}
}
Example 29
Project: bonita-web-master File: AbstractForm.java View source code |
public void setJson(final String json) {
// TODO Improve filling multilevel arrays
final JSONValue parsedJson = JSONParser.parseStrict(json);
if (parsedJson.isArray() != null) {
final JSONArray jsonArray = parsedJson.isArray();
for (int i = 0; i < jsonArray.size(); i++) {
setJson((JSONObject) jsonArray.get(i));
}
} else if (parsedJson.isObject() != null) {
setJson(parsedJson.isObject());
} else {
throw new IllegalArgumentException("Malformed JSON");
}
}
Example 30
Project: BVH-Pose-Editor-master File: PoseEditorDataConverter.java View source code |
/** * TODO set name and cdate by yourself */ @Override protected JSONObject doForward(BVH bvh) { List<BVHNode> nodes = bvh.getNodeList(); //for find Index List<String> boneNameList = new ArrayList<String>(); JsArrayString boneNames = (JsArrayString) JsArrayString.createArray(); for (BVHNode node : nodes) { boneNames.push(node.getName()); boneNameList.add(node.getName()); } List<NameAndChannel> channels = bvh.getNameAndChannels(); JsArray<JavaScriptObject> frames = (JsArray<JavaScriptObject>) JsArray.createArray(); for (int i = 0; i < bvh.getFrames(); i++) { //re create FrameData JsArray<JsArrayNumber> positions = (JsArray<JsArrayNumber>) JsArray.createArray(); JsArray<JsArrayNumber> rots = (JsArray<JsArrayNumber>) JsArray.createArray(); for (int j = 0; j < boneNameList.size(); j++) { JsArrayNumber pos = (JsArrayNumber) JsArrayNumber.createArray(); pos.push(0); pos.push(0); pos.push(0); positions.push(pos); JsArrayNumber rot = (JsArrayNumber) JsArrayNumber.createArray(); rot.push(0); rot.push(0); rot.push(0); rots.push(rot); } //must same channels size double[] values = bvh.getFrameAt(i); int valueIndex = 0; for (NameAndChannel channel : channels) { int index = boneNameList.indexOf(channel.getName()); if (index == -1) { LogUtils.log("not found:maybe invalid-channel:" + channel.getName()); continue; } boolean targetPos = false; int targetIndex = 0; switch(channel.getChannel()) { case Channels.XPOSITION: targetPos = true; targetIndex = 0; break; case Channels.YPOSITION: targetPos = true; targetIndex = 1; break; case Channels.ZPOSITION: targetPos = true; targetIndex = 2; break; case Channels.XROTATION: targetPos = false; targetIndex = 0; break; case Channels.YROTATION: targetPos = false; targetIndex = 1; break; case Channels.ZROTATION: targetPos = false; targetIndex = 2; break; default: LogUtils.log("invalid type:" + channel.getChannel()); } if (targetPos) { positions.get(index).set(targetIndex, values[valueIndex]); } else { rots.get(index).set(targetIndex, values[valueIndex]); } valueIndex++; } JSONObject frame = new JSONObject(); frame.put("angles", new JSONArray(rots)); frame.put("positions", new JSONArray(positions)); frames.push(frame.getJavaScriptObject()); } JSONObject jsonObject = new JSONObject(); jsonObject.put("frames", new JSONArray(frames)); jsonObject.put("bones", new JSONArray(boneNames)); return jsonObject; }
Example 31
Project: exo-training-master File: FormServerJsonValidationSample.java View source code |
@Override protected void transformResponse(DSResponse response, DSRequest request, Object jsonData) { JSONArray value = XMLTools.selectObjects(jsonData, "/response/status"); String status = ((JSONString) value.get(0)).stringValue(); if (!status.equals("success")) { response.setStatus(RPCResponse.STATUS_VALIDATION_ERROR); JSONArray errors = XMLTools.selectObjects(jsonData, "/response/errors"); response.setErrors(errors.getJavaScriptObject()); } }
Example 32
Project: Fall2010_Practicum_Samsung-master File: Remindme_appengine.java View source code |
public void onData(Object[] data) {
// Process userInfo RPC call results
JSONObject userInfoJson = (JSONObject) data[0];
if (userInfoJson.containsKey(RemindMeProtocol.UserInfo.RET_USER)) {
Remindme_appengine.sUserInfo = (ModelJso.UserInfo) userInfoJson.get(RemindMeProtocol.UserInfo.RET_USER).isObject().getJavaScriptObject();
InlineLabel label = new InlineLabel();
label.getElement().setId("userNameLabel");
label.setText(sUserInfo.getEmail());
loginPanel.add(label);
loginPanel.add(new InlineLabel(" | "));
Anchor anchor = new Anchor("Sign out", userInfoJson.get(RemindMeProtocol.UserInfo.RET_LOGOUT_URL).isString().stringValue());
loginPanel.add(anchor);
} else {
sLoginUrl = userInfoJson.get(RemindMeProtocol.UserInfo.RET_LOGIN_URL).isString().stringValue();
Anchor anchor = new Anchor("Sign in", sLoginUrl);
loginPanel.add(anchor);
}
// Process notesList RPC call results
JSONObject notesListJson = (JSONObject) data[1];
if (notesListJson != null) {
JSONArray notesJson = notesListJson.get(RemindMeProtocol.AlertsList.RET_NOTES).isArray();
for (int i = 0; i < notesJson.size(); i++) {
ModelJso.Alert alert = (ModelJso.Alert) notesJson.get(i).isObject().getJavaScriptObject();
sAlerts.put(alert.getId(), alert);
}
}
callback.run();
}
Example 33
Project: GKEngine-master File: EventHandler.java View source code |
/**
* 調用JavaScript的function
*
* @param func
* @param data
*/
protected void invokeFunction(JavaScriptObject func, Object data) {
if (data instanceof String) {
invokeFunction(func, (String) data);
} else if (data instanceof Map) {
JSONObject json = JsonConvert.toJSONObject((Map) data);
invokeFunction(func, json.getJavaScriptObject());
} else if (data instanceof List) {
JSONArray json = JsonConvert.toJSONArray((List) data);
invokeFunction(func, json.getJavaScriptObject());
} else {
invokeFunction(func, data + "");
}
}
Example 34
Project: google-web-toolkit-svnmirror-master File: JSON.java View source code |
/*
* Add the object presented by the JSONValue as a children to the requested
* TreeItem.
*/
private void addChildren(TreeItem treeItem, JSONValue jsonValue) {
JSONArray jsonArray;
JSONObject jsonObject;
JSONString jsonString;
if ((jsonArray = jsonValue.isArray()) != null) {
for (int i = 0; i < jsonArray.size(); ++i) {
TreeItem child = treeItem.addItem(getChildText("[" + Integer.toString(i) + "]"));
addChildren(child, jsonArray.get(i));
}
} else if ((jsonObject = jsonValue.isObject()) != null) {
Set<String> keys = jsonObject.keySet();
for (String key : keys) {
TreeItem child = treeItem.addItem(getChildText(key));
addChildren(child, jsonObject.get(key));
}
} else if ((jsonString = jsonValue.isString()) != null) {
// Use stringValue instead of toString() because we don't want escaping
treeItem.addItem(jsonString.stringValue());
} else {
// JSONBoolean, JSONNumber, and JSONNull work well with toString().
treeItem.addItem(getChildText(jsonValue.toString()));
}
}
Example 35
Project: gwt-master File: JSON.java View source code |
/*
* Add the object presented by the JSONValue as a children to the requested
* TreeItem.
*/
private void addChildren(TreeItem treeItem, JSONValue jsonValue) {
JSONArray jsonArray;
JSONObject jsonObject;
JSONString jsonString;
if ((jsonArray = jsonValue.isArray()) != null) {
for (int i = 0; i < jsonArray.size(); ++i) {
TreeItem child = treeItem.addItem(getChildText("[" + Integer.toString(i) + "]"));
addChildren(child, jsonArray.get(i));
}
} else if ((jsonObject = jsonValue.isObject()) != null) {
Set<String> keys = jsonObject.keySet();
for (String key : keys) {
TreeItem child = treeItem.addItem(getChildText(key));
addChildren(child, jsonObject.get(key));
}
} else if ((jsonString = jsonValue.isString()) != null) {
// Use stringValue instead of toString() because we don't want escaping
treeItem.addItem(SafeHtmlUtils.fromString(jsonString.stringValue()));
} else {
// JSONBoolean, JSONNumber, and JSONNull work well with toString().
treeItem.addItem(getChildText(jsonValue.toString()));
}
}
Example 36
Project: gwt-rest-master File: AbstractJsonEncoderDecoder.java View source code |
static JSONArray asArray(JSONValue value) { JSONArray array = value.isArray(); if (array == null) { //Jersey render arrays with one object as object and not as array. JSONObject object = value.isObject(); if (object == null) { throw new DecodingException("Expected a json array, but was given: " + value); } //Found a object and return it as array. array = new JSONArray(); array.set(0, object); } return array; }
Example 37
Project: gwt-sandbox-master File: JSON.java View source code |
/*
* Add the object presented by the JSONValue as a children to the requested
* TreeItem.
*/
private void addChildren(TreeItem treeItem, JSONValue jsonValue) {
JSONArray jsonArray;
JSONObject jsonObject;
JSONString jsonString;
if ((jsonArray = jsonValue.isArray()) != null) {
for (int i = 0; i < jsonArray.size(); ++i) {
TreeItem child = treeItem.addItem(getChildText("[" + Integer.toString(i) + "]"));
addChildren(child, jsonArray.get(i));
}
} else if ((jsonObject = jsonValue.isObject()) != null) {
Set<String> keys = jsonObject.keySet();
for (String key : keys) {
TreeItem child = treeItem.addItem(getChildText(key));
addChildren(child, jsonObject.get(key));
}
} else if ((jsonString = jsonValue.isString()) != null) {
// Use stringValue instead of toString() because we don't want escaping
treeItem.addItem(jsonString.stringValue());
} else {
// JSONBoolean, JSONNumber, and JSONNull work well with toString().
treeItem.addItem(getChildText(jsonValue.toString()));
}
}
Example 38
Project: gwt.svn-master File: JSON.java View source code |
/*
* Add the object presented by the JSONValue as a children to the requested
* TreeItem.
*/
private void addChildren(TreeItem treeItem, JSONValue jsonValue) {
JSONArray jsonArray;
JSONObject jsonObject;
JSONString jsonString;
if ((jsonArray = jsonValue.isArray()) != null) {
for (int i = 0; i < jsonArray.size(); ++i) {
TreeItem child = treeItem.addItem(getChildText("[" + Integer.toString(i) + "]"));
addChildren(child, jsonArray.get(i));
}
} else if ((jsonObject = jsonValue.isObject()) != null) {
Set<String> keys = jsonObject.keySet();
for (String key : keys) {
TreeItem child = treeItem.addItem(getChildText(key));
addChildren(child, jsonObject.get(key));
}
} else if ((jsonString = jsonValue.isString()) != null) {
// Use stringValue instead of toString() because we don't want escaping
treeItem.addItem(jsonString.stringValue());
} else {
// JSONBoolean, JSONNumber, and JSONNull work well with toString().
treeItem.addItem(getChildText(jsonValue.toString()));
}
}
Example 39
Project: horaz-master File: PersistentDataStore.java View source code |
/**
* reads the storage and deserialize models
*/
public void load() {
if (localStorage.getItem(storeName + "_" + KEY_STUB_COUNT) != null) {
int stubCount = Integer.valueOf(localStorage.getItem(storeName + "_" + KEY_STUB_COUNT));
for (int i = 0; i < stubCount; i++) {
String cont = localStorage.getItem(storeName + "_" + KEY_STUB_CONTENT + i);
if (cont != null) {
JSONArray stubModels = JSONParser.parseStrict(cont).isArray();
for (int ii = 0; ii < stubModels.size(); ii++) {
// hashmap attributes
JSONObject attrs = stubModels.get(ii).isObject();
add(deserializeModel(attrs));
}
}
}
}
}
Example 40
Project: Kornell-master File: CourseDetailsTOBuilder.java View source code |
private boolean parseJSON(JSONValue jsonValue, ParseType parseType) {
JSONArray jsonArray;
JSONObject jsonObject;
JSONString type;
JSONString text;
if (jsonValue == null) {
logger.warning("Error parsing the JSON");
return false;
}
if ((jsonArray = jsonValue.isArray()) == null) {
logger.warning("Error parsing the JSON");
return false;
}
switch(parseType) {
case HINTS:
List<HintTO> hints = new ArrayList<HintTO>();
for (int i = 0; i < jsonArray.size(); i++) {
jsonValue = jsonArray.get(i);
if ((jsonObject = jsonValue.isObject()) == null) {
logger.warning("Error parsing the JSON");
return false;
}
jsonValue = jsonObject.get("type");
if ((type = jsonValue.isString()) == null) {
logger.warning("Error parsing the JSON");
return false;
}
jsonValue = jsonObject.get("text");
if ((text = jsonValue.isString()) == null) {
logger.warning("Error parsing the JSON");
return false;
}
hints.add(new HintTO(type.stringValue(), text.stringValue()));
courseDetailsTO.setHints(hints);
}
break;
case INFOS:
List<InfoTO> infos = new ArrayList<InfoTO>();
for (int i = 0; i < jsonArray.size(); i++) {
jsonValue = jsonArray.get(i);
if ((jsonObject = jsonValue.isObject()) == null) {
logger.warning("Error parsing the JSON");
return false;
}
jsonValue = jsonObject.get("type");
if ((type = jsonValue.isString()) == null) {
logger.warning("Error parsing the JSON");
return false;
}
jsonValue = jsonObject.get("text");
if ((text = jsonValue.isString()) == null) {
logger.warning("Error parsing the JSON");
return false;
}
infos.add(new InfoTO(type.stringValue(), text.stringValue()));
courseDetailsTO.setInfos(infos);
}
break;
default:
break;
}
return true;
}
Example 41
Project: NASfVI-master File: NResponseWidget.java View source code |
/** * Creates and returns a visual representation for a subtree. * @param data Data of the subtree * @param depth Depth of the subtree in the analysis * @return Visual representation of <code>data</code> */ private TreeItem getSubtree(final JSONArray data, final int depth) { TreeItem root = new TreeItem(); int subtrees = 0; for (int i = 0; i < data.size(); i++) { JSONArray array = data.get(i).isArray(); if (array == null) { // just a string root.addItem(data.get(i).isString().stringValue()); } else if (array.size() == 1 && array.get(0).isString() != null) { // array with a single string as an element root.addItem(array.get(0).isString().stringValue()); subtrees++; } else { // arrays TreeItem item = getSubtree(array, depth + 1); int x = (depth < LABELS.length) ? depth : LABELS.length - 2; int y = (subtrees < LABELS[x].length) ? subtrees : LABELS[x].length - 1; String label = LABELS[x][y]; if (label == null && item.getChildCount() > 0) { TreeItem first = item.getChild(0); label = first.getText(); item.removeItem(first); } item.setText(label); root.addItem(item); subtrees++; } } return root; }
Example 42
Project: platform-api-client-gwt-master File: ClientDtoTest.java View source code |
// @Test @Ignore public void testListSimpleDtoDeserializer() throws Exception { final String fooString_1 = "Something 1"; final int fooId_1 = 1; final String fooString_2 = "Something 2"; final int fooId_2 = 2; final String _default_1 = "test_default_keyword_1"; final String _default_2 = "test_default_keyword_2"; JSONObject json1 = new JSONObject(); json1.put("name", new JSONString(fooString_1)); json1.put("id", new JSONNumber(fooId_1)); json1.put("default", new JSONString(_default_1)); JSONObject json2 = new JSONObject(); json2.put("name", new JSONString(fooString_2)); json2.put("id", new JSONNumber(fooId_2)); json2.put("default", new JSONString(_default_2)); JSONArray jsonArray = new JSONArray(); jsonArray.set(0, json1); jsonArray.set(1, json2); // TODO JSONParserPatcher doesn't handle JSON array Array<SimpleDto> listDtoFromJson = dtoFactory.createListDtoFromJson(jsonArray.toString(), SimpleDto.class); Assert.assertEquals(listDtoFromJson.get(0).getName(), fooString_1); Assert.assertEquals(listDtoFromJson.get(0).getId(), fooId_1); Assert.assertEquals(listDtoFromJson.get(0).getDefault(), _default_1); Assert.assertEquals(listDtoFromJson.get(1).getName(), fooString_2); Assert.assertEquals(listDtoFromJson.get(1).getId(), fooId_2); Assert.assertEquals(listDtoFromJson.get(1).getDefault(), _default_2); }
Example 43
Project: resty-gwt-master File: AbstractJsonEncoderDecoder.java View source code |
static JSONArray asArray(JSONValue value) { JSONArray array = value.isArray(); if (array == null) { //Jersey render arrays with one object as object and not as array. JSONObject object = value.isObject(); if (object == null) { throw new DecodingException("Expected a json array, but was given: " + value); } //Found a object and return it as array. array = new JSONArray(); array.set(0, object); } return array; }
Example 44
Project: scalagwt-gwt-master File: JSON.java View source code |
/*
* Add the object presented by the JSONValue as a children to the requested
* TreeItem.
*/
private void addChildren(TreeItem treeItem, JSONValue jsonValue) {
JSONArray jsonArray;
JSONObject jsonObject;
JSONString jsonString;
if ((jsonArray = jsonValue.isArray()) != null) {
for (int i = 0; i < jsonArray.size(); ++i) {
TreeItem child = treeItem.addItem(getChildText("[" + Integer.toString(i) + "]"));
addChildren(child, jsonArray.get(i));
}
} else if ((jsonObject = jsonValue.isObject()) != null) {
Set<String> keys = jsonObject.keySet();
for (String key : keys) {
TreeItem child = treeItem.addItem(getChildText(key));
addChildren(child, jsonObject.get(key));
}
} else if ((jsonString = jsonValue.isString()) != null) {
// Use stringValue instead of toString() because we don't want escaping
treeItem.addItem(jsonString.stringValue());
} else {
// JSONBoolean, JSONNumber, and JSONNull work well with toString().
treeItem.addItem(getChildText(jsonValue.toString()));
}
}
Example 45
Project: smartgwt-master File: FormServerJsonValidationSample.java View source code |
@Override protected void transformResponse(DSResponse response, DSRequest request, Object jsonData) { JSONArray value = XMLTools.selectObjects(jsonData, "/response/status"); String status = ((JSONString) value.get(0)).stringValue(); if (!status.equals("success")) { response.setStatus(RPCResponse.STATUS_VALIDATION_ERROR); JSONArray errors = XMLTools.selectObjects(jsonData, "/response/errors"); response.setErrors(errors.getJavaScriptObject()); } }
Example 46
Project: TheSocialOS-master File: TwitterAPI.java View source code |
@Override public void onSuccess(JavaScriptObject result) { JSONArray array; Columns c = panel.getColumns(); if (c.getType() == Columns.TYPE.SEARCH) { JSONObject json = new JSONObject(result); array = json.get("results").isArray(); } else array = new JSONArray(result); Set<Tweet> tweets = new HashSet<Tweet>(); for (int i = 0; i < array.size(); i++) { Tweet tweet = new Tweet(); tweet.id = array.get(i).isObject().get("id").isNumber().toString(); if (c.getType() == Columns.TYPE.SEARCH) { tweet.user_id = array.get(i).isObject().get("from_user_id").isNumber().toString(); tweet.user_name = array.get(i).isObject().get("from_user_name").isString().stringValue(); tweet.screen_name = array.get(i).isObject().get("from_user").isString().stringValue(); tweet.profile_image_url = array.get(i).isObject().get("profile_image_url").isString().stringValue(); } else { JSONObject user = array.get(i).isObject().get("user").isObject(); tweet.user_id = user.get("id").isNumber().toString(); tweet.user_name = user.get("name").isString().stringValue(); tweet.screen_name = user.get("screen_name").isString().stringValue(); tweet.profile_image_url = user.get("profile_image_url").isString().stringValue(); tweet.user_verified = user.get("verified").isBoolean().booleanValue(); } tweet.created_at = new Date(array.get(i).isObject().get("created_at").isString().stringValue()); tweet.text = array.get(i).isObject().get("text").isString().stringValue(); tweet.source = array.get(i).isObject().get("source").isString().stringValue(); // panel.addTweet(tweet); tweets.add(tweet); } Set<Tweet> oldTweets = panel.getTweets(); if (null != oldTweets && !oldTweets.isEmpty()) tweets.addAll(tweets); else panel.setTweets(tweets); // panel.clearTweets(); panel.loadAll(); }
Example 47
Project: tnoodle-master File: TNoodleJsUtils.java View source code |
private static JSONValue toJSONValue(Object obj) { if (obj instanceof HashMap) { HashMap<String, Object> map = (HashMap<String, Object>) obj; JSONObject jsonObj = new JSONObject(); for (String key : map.keySet()) { jsonObj.put(key, toJSONValue(map.get(key))); } return jsonObj; } else if (obj instanceof String) { return new JSONString((String) obj); } else if (obj instanceof Integer) { return new JSONNumber((Integer) obj); } else if (obj instanceof double[]) { JSONArray jsonArr = new JSONArray(); double[] arr = (double[]) obj; for (int i = 0; i < arr.length; i++) { jsonArr.set(i, new JSONNumber(arr[i])); } return jsonArr; } else if (obj instanceof Object[]) { JSONArray jsonArr = new JSONArray(); Object[] arr = (Object[]) obj; for (int i = 0; i < arr.length; i++) { jsonArr.set(i, toJSONValue(arr[i])); } return jsonArr; } else { azzert(false, "Unrecognized type " + obj.getClass()); return null; } }
Example 48
Project: xwiki-platform-master File: StyleDescriptorJSONParser.java View source code |
/**
* @param json JSON representation of a list of style descriptors
* @return the list of style descriptors read from the given JSON string
*/
public List<StyleDescriptor> parse(String json) {
JSONArray jsDescriptors = JSONParser.parseStrict(json).isArray();
if (jsDescriptors == null) {
return Collections.emptyList();
}
List<StyleDescriptor> descriptors = new ArrayList<StyleDescriptor>();
for (int i = 0; i < jsDescriptors.size(); i++) {
JSONObject jsDescriptor = jsDescriptors.get(i).isObject();
if (jsDescriptor == null) {
continue;
}
StyleDescriptor descriptor = createStyleDescriptor(jsDescriptor);
if (descriptor != null) {
descriptors.add(descriptor);
}
}
return descriptors;
}
Example 49
Project: daxplore-presenter-master File: PrefixDataModelImpl.java View source code |
/**
* {@inheritDoc}
*/
@Override
public void onResponseReceived(Request request, Response response) {
if (response.getStatusCode() == HttpServletResponse.SC_OK) {
LinkedList<String> prefixes = new LinkedList<>();
String responseText = response.getText();
if (responseText != null && responseText.length() > 0) {
JSONArray array = JSONParser.parseStrict(responseText).isArray();
for (int i = 0; i < array.size(); i++) {
prefixes.add(array.get(i).isString().stringValue());
}
eventBus.fireEvent(new PrefixListUpdateEvent(prefixes));
}
} else {
// TODO Reattempt? Depends on why it failed and number of attempts.
}
}
Example 50
Project: elemento-master File: TodoItemRepository.java View source code |
private LinkedHashMap<String, TodoItem> load() {
LinkedHashMap<String, TodoItem> items = new LinkedHashMap<>();
if (storage != null) {
String json = storage.getItem(key);
if (json != null) {
JSONValue jsonValue = JSONParser.parseStrict(json);
if (jsonValue != null) {
JSONArray jsonArray = jsonValue.isArray();
if (jsonArray != null) {
for (int i = 0; i < jsonArray.size(); i++) {
AutoBean<TodoItem> bean = AutoBeanCodex.decode(beanFactory, TodoItem.class, jsonArray.get(i).toString());
TodoItem todoItem = bean.as();
items.put(todoItem.getId(), todoItem);
}
}
}
}
}
return items;
}
Example 51
Project: eucalyptus-fork-2.0-master File: JSONUtil.java View source code |
public static <T> List<T> adaptArray(JSONValue arrayValue, ObjectAdapter<T> adapter) {
List<T> result = new ArrayList<T>();
if (arrayValue != null && arrayValue.isArray() != null) {
JSONArray array = arrayValue.isArray();
for (int i = 0; i != array.size(); i++) {
JSONObject object = array.get(i).isObject();
if (object != null) {
result.add(adapter.adaptObject(object));
}
}
}
return result;
}
Example 52
Project: FURCAS-master File: JsonReader.java View source code |
@SuppressWarnings("unchecked") public D read(Object loadConfig, Object data) { JSONObject jsonRoot = null; if (data instanceof JavaScriptObject) { jsonRoot = new JSONObject((JavaScriptObject) data); } else { jsonRoot = (JSONObject) JSONParser.parse((String) data); } JSONArray root = (JSONArray) jsonRoot.get(modelType.getRoot()); int size = root.size(); ArrayList<ModelData> models = new ArrayList<ModelData>(); for (int i = 0; i < size; i++) { JSONObject obj = (JSONObject) root.get(i); ModelData model = newModelInstance(); for (int j = 0; j < modelType.getFieldCount(); j++) { DataField field = modelType.getField(j); String name = field.getName(); Class type = field.getType(); String map = field.getMap() != null ? field.getMap() : field.getName(); JSONValue value = obj.get(map); if (value == null) continue; if (value.isArray() != null) { // nothing } else if (value.isBoolean() != null) { model.set(name, value.isBoolean().booleanValue()); } else if (value.isNumber() != null) { if (type != null) { Double d = value.isNumber().doubleValue(); if (type.equals(Integer.class)) { model.set(name, d.intValue()); } else if (type.equals(Long.class)) { model.set(name, d.longValue()); } else if (type.equals(Float.class)) { model.set(name, d.floatValue()); } else { model.set(name, d); } } else { model.set(name, value.isNumber().doubleValue()); } } else if (value.isObject() != null) { // nothing } else if (value.isString() != null) { String s = value.isString().stringValue(); if (type != null) { if (type.equals(Date.class)) { if (field.getFormat().equals("timestamp")) { Date d = new Date(Long.parseLong(s) * 1000); model.set(name, d); } else { DateTimeFormat format = DateTimeFormat.getFormat(field.getFormat()); Date d = format.parse(s); model.set(name, d); } } } else { model.set(name, s); } } else if (value.isNull() != null) { model.set(name, null); } } models.add(model); } int totalCount = models.size(); if (modelType.getTotalName() != null) { totalCount = getTotalCount(jsonRoot); } return (D) createReturnData(loadConfig, models, totalCount); }
Example 53
Project: google-apis-explorer-master File: ArraySchemaEditor.java View source code |
@Override
public void setJSONValue(JSONValue value) {
JSONArray arr = value.isArray();
if (arr != null) {
for (int i = 0; i < arr.size(); i++) {
// We may have to create additional editors
if (i >= editors.size()) {
addItem();
}
SchemaEditor editor = editors.get(i);
editor.setJSONValue(arr.get(i));
}
} else {
throw new JSONException("Not a valid JSON array: " + value.toString());
}
}
Example 54
Project: GWTP-master File: RestParameterBindingsSerializer.java View source code |
/**
* Used to deserialize the bindings once on the client. Usage of GWT code is allowed.
*/
public RestParameterBindings deserialize(String encodedParameters) {
RestParameterBindings parameters = new RestParameterBindings();
JSONObject json = JSONParser.parseStrict(encodedParameters).isObject();
for (String method : json.keySet()) {
HttpMethod httpMethod = HttpMethod.valueOf(method);
JSONArray jsonParameters = json.get(method).isArray();
for (int i = 0; i < jsonParameters.size(); ++i) {
HttpParameter parameter = deserialize(jsonParameters.get(i).isObject());
parameters.put(httpMethod, parameter);
}
}
return parameters;
}
Example 55
Project: GXT_RTL-master File: JsonConverter.java View source code |
protected static List<Object> decodeToList(JSONArray array) {
List<Object> list = new ArrayList<Object>();
for (int i = 0; i < array.size(); i++) {
JSONValue v = array.get(i);
if (v.isObject() != null) {
list.add(decode(v.isObject()));
} else if (v.isArray() != null) {
list.add(decodeToList(v.isArray()));
} else if (v.isNull() != null) {
list.add(null);
} else if (v.isNumber() != null) {
list.add(v.isNumber().doubleValue());
} else if (v.isBoolean() != null) {
list.add(v.isBoolean().booleanValue());
} else if (v.isString() != null) {
list.add(decodeValue(v.isString().stringValue()));
}
}
return list;
}
Example 56
Project: jsmoleditor-master File: ExtendedCanvas.java View source code |
public void drawText(String text, double x, double y, double size) { int total = 0; int len = text.length(); double x_origin = x; double mag = size / 25.0; y += size; this.save(); this.setLineCap("round"); this.setLineWidth(2.0 * mag); for (int i = 0; i < len; i++) { JSONValue cv = letters.get(String.valueOf(text.charAt(i))); if (cv == null) continue; JSONObject c = cv.isObject(); this.beginPath(); boolean penUp = true, needStroke = false; double width = c.get("width").isNumber().doubleValue(); JSONArray points = c.get("points").isArray(); for (int j = 0; j < points.size(); j++) { JSONArray point = points.get(j).isArray(); double x_ = point.get(0).isNumber().doubleValue(); double y_ = point.get(1).isNumber().doubleValue(); if (x_ == -1 && y_ == -1) { penUp = true; continue; } if (penUp) { this.moveTo(x + x_ * mag, y - y_ * mag); penUp = false; } else { this.lineTo(x + x_ * mag, y - y_ * mag); } } this.stroke(); x += width * mag; } this.restore(); }
Example 57
Project: kaa-master File: LogAppendersActivity.java View source code |
@Override public void onSuccess(LogAppenderDto key) { JSONObject json = (JSONObject) JSONParser.parseLenient(key.getJsonConfiguration()); json.put("minLogSchemaVersion", new JSONNumber(key.getMinLogSchemaVersion())); json.put("maxLogSchemaVersion", new JSONNumber(key.getMaxLogSchemaVersion())); json.put("pluginTypeName", new JSONString(key.getPluginTypeName())); json.put("pluginClassName", new JSONString(key.getPluginClassName())); JSONArray headersStructure = new JSONArray(); for (LogHeaderStructureDto header : key.getHeaderStructure()) { headersStructure.set(headersStructure.size(), new JSONString(header.getValue())); } json.put("headerStructure", headersStructure); ServletHelper.downloadJsonFile(json.toString(), key.getPluginTypeName() + ".json"); }
Example 58
Project: map4rdf-master File: PopupStatisticsView.java View source code |
private ArrayList<Statistic> getStatistics(String url, String geoResourceUri) {
String statistics = getQueryJSON(url, "getStatistics", "Server=all&URI=" + encodeParameter(geoResourceUri));
ArrayList<Statistic> stats = new ArrayList<Statistic>();
if (statistics != null) {
JSONValue value = JSONParser.parseStrict(statistics);
if (value.isObject() != null) {
JSONObject dataServer = value.isObject();
for (String serverURI : dataServer.keySet()) {
JSONObject objectResponseServer = dataServer.get(serverURI).isObject();
StatisticServer statisticServer = new StatisticServer(serverURI);
if (objectResponseServer != null) {
if (objectResponseServer.get("labels") != null && objectResponseServer.get("labels").isObject() != null) {
for (String key : objectResponseServer.get("labels").isObject().keySet()) {
if (objectResponseServer.get("labels").isObject().get(key) != null) {
statisticServer.addLabel(key.replace("\"", ""), objectResponseServer.get("labels").isObject().get(key).toString().replace("\"", ""));
}
}
}
if (objectResponseServer.get("values") != null && objectResponseServer.get("values").isArray() != null) {
JSONArray dataAllStatistics = objectResponseServer.get("values").isArray();
for (int i = 0; i < dataAllStatistics.size(); i++) {
JSONObject dataStatistic = dataAllStatistics.get(i).isObject();
if (dataStatistic != null && dataStatistic.get("uri") != null) {
Statistic statistic = new Statistic(dataStatistic.get("uri").toString().replace("\"", ""));
statistic.setServer(statisticServer);
if (dataStatistic.get("origin") != null) {
statistic.setOrigin(dataStatistic.get("origin").toString().replace("\"", ""));
}
JSONObject labels;
if (dataStatistic.get("labels") != null && dataStatistic.get("labels").isObject() != null) {
labels = dataStatistic.get("labels").isObject();
for (String key : labels.keySet()) {
if (labels.get(key) != null) {
statistic.addLabel(key.replace("\"", ""), labels.get(key).toString().replace("\"", ""));
}
}
}
stats.add(statistic);
}
}
}
}
}
}
Collections.sort(stats);
} else {
stats = null;
}
return stats;
}
Example 59
Project: motiver_fi-master File: OldDataFetchPresenter.java View source code |
@SuppressWarnings("deprecation") @Override public void loadOk(JSONObject json) { JSONArray measurements; try { measurements = json.get("cardio").isArray(); final int indexNew = (int) json.get("index").isNumber().doubleValue(); final int total = (int) json.get("total").isNumber().doubleValue(); List<CardioModel> arrCardios = new ArrayList<CardioModel>(); //values for each measurement List<List<CardioValueModel>> arrValues = new ArrayList<List<CardioValueModel>>(); for (int i = 0; i < measurements.size(); i++) { try { JSONObject obj = measurements.get(i).isObject(); CardioModel cardio = new CardioModel(); cardio.setName(obj.get("n").isString().stringValue()); //values List<CardioValueModel> val = new ArrayList<CardioValueModel>(); JSONArray values = obj.get("v").isArray(); for (int j = 0; j < values.size(); j++) { try { JSONObject objVal = values.get(j).isObject(); CardioValueModel ex = new CardioValueModel(); ex.setDate(new Date((long) (objVal.get("d").isNumber().doubleValue() * 1000))); String t1 = objVal.get("t").isString().stringValue(); if (t1.length() == 8) { t1 = t1.substring(0, 5); } final double time = CommonUtils.getTimeToSeconds(t1); ex.getDate().setHours((int) (time / 3600)); ex.getDate().setMinutes((int) ((time % 3600) / 60)); ex.setDuration((long) objVal.get("du").isNumber().doubleValue()); ex.setPulse((int) objVal.get("p").isNumber().doubleValue()); ex.setCalories((int) objVal.get("c").isNumber().doubleValue()); ex.setInfo(objVal.get("i").isString().stringValue()); val.add(ex); } catch (Exception e) { Motiver.showException(e); } } arrValues.add(val); arrCardios.add(cardio); } catch (Exception e) { Motiver.showException(e); } } display.showProgress("Fetching cardio", (indexNew != 0) ? indexNew : total, total); //add to server rpcService.fetchSaveCardios(arrCardios, arrValues, new MyAsyncCallback<Boolean>() { @Override public void onSuccess(Boolean result) { if (indexNew != 0) { fetchCardio(indexNew); } else { fetchRuns(0); } } }); } catch (Exception e) { Motiver.showException(e); showCompleted(false); } }
Example 60
Project: nuxeo-master File: NavigatorTree.java View source code |
@Override
public void onSuccess(HttpResponse response) {
// parse the response text into JSON
String text = response.getText();
JSONValue jsonValue = JSONParser.parse(text);
JSONObject resp = jsonValue.isObject().get("response").isObject();
if (resp.get("status").isNumber().doubleValue() < 0) {
// error
//TODO handle error
Window.alert("Error received from server" + resp.get("status"));
return;
}
JSONArray jsonArray = resp.get("data").isArray();
if (jsonArray != null) {
if (item == null) {
updateTree(jsonArray);
} else {
updateTree(jsonArray, item);
}
}
}
Example 61
Project: osgi-maven-master File: JsonConverter.java View source code |
protected static List<Object> decodeToList(JSONArray array) {
List<Object> list = new ArrayList<Object>();
for (int i = 0; i < array.size(); i++) {
JSONValue v = array.get(i);
if (v.isObject() != null) {
list.add(decode(v.isObject()));
} else if (v.isArray() != null) {
list.add(decodeToList(v.isArray()));
} else if (v.isNull() != null) {
list.add(null);
} else if (v.isNumber() != null) {
list.add(v.isNumber().doubleValue());
} else if (v.isBoolean() != null) {
list.add(v.isBoolean().booleanValue());
} else if (v.isString() != null) {
list.add(decodeValue(v.isString().stringValue()));
}
}
return list;
}
Example 62
Project: PonySDK-master File: UIBuilder.java View source code |
public void sendDataToServer(final JSONObject instruction) { final PTInstruction requestData = new PTInstruction(); final JSONArray jsonArray = new JSONArray(); jsonArray.set(0, instruction); requestData.put(ClientToServerModel.APPLICATION_INSTRUCTIONS, jsonArray); if (log.isLoggable(Level.FINE)) log.log(Level.FINE, "Data to send " + requestData.toString()); requestBuilder.send(requestData); }
Example 63
Project: qafe-platform-master File: JSNIUtil.java View source code |
private static List<Object> resolveJavaList(JSONArray jsonArray) {
if (jsonArray == null) {
return null;
}
List<Object> value = new ArrayList<Object>();
for (int i = 0; i < jsonArray.size(); i++) {
JSONValue jsonValue = jsonArray.get(i);
Object keyValue = resolveJavaValue(jsonValue);
if (keyValue != null) {
value.add(keyValue);
}
}
return value;
}
Example 64
Project: Socket.IO-Java-master File: GWTChatClient.java View source code |
private void onMessage(JSONObject obj) {
if (obj.containsKey("welcome")) {
JSONString str = obj.get("welcome").isString();
if (str != null) {
addLine("<em><b>" + str.stringValue() + "</b></em>");
}
} else if (obj.containsKey("announcement")) {
JSONString str = obj.get("announcement").isString();
if (str != null) {
addLine("<em>" + str.stringValue() + "</em>");
}
} else if (obj.containsKey("message")) {
JSONArray arr = obj.get("message").isArray();
if (arr != null && arr.size() >= 2) {
JSONString id = arr.get(0).isString();
JSONString msg = arr.get(1).isString();
if (id != null && msg != null) {
addLine("<b>" + id.stringValue() + ":</b> " + msg.stringValue());
}
}
}
}
Example 65
Project: wave-protocol-master File: GadgetDataStoreImpl.java View source code |
@Override public void getGadgetData(final String gadgetSpecUrl, WaveletName waveletName, int instanceId, final DataCallback receiveDataCommand) { cleanupExpiredCache(); final String secureGadgetDataKey = waveletName.waveId + " " + waveletName.waveletId + " " + instanceId + " " + gadgetSpecUrl; if (fetchDataByKey(secureGadgetDataKey, receiveDataCommand)) { return; } final String nonSecureGadgetDataKey = gadgetSpecUrl; if (fetchDataByKey(nonSecureGadgetDataKey, receiveDataCommand)) { return; } JSONObject request = new JSONObject(); JSONObject requestContext = new JSONObject(); JSONArray gadgets = new JSONArray(); JSONObject gadget = new JSONObject(); try { gadget.put("url", new JSONString(gadgetSpecUrl)); gadgets.set(0, gadget); requestContext.put("container", new JSONString("wave")); request.put("context", requestContext); request.put("gadgets", gadgets); RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, GADGET_METADATA_PATH); builder.sendRequest(request.toString(), new RequestCallback() { public void onError(Request request, Throwable exception) { receiveDataCommand.onError("Error retrieving metadata from the server.", exception); } public void onResponseReceived(Request request, Response response) { JSONObject gadgetMetadata = null; try { gadgetMetadata = JSONParser.parseLenient(response.getText()).isObject().get("gadgets").isArray().get(0).isObject(); } catch (NullPointerException exception) { receiveDataCommand.onError("Error in gadget metadata JSON.", exception); } if (gadgetMetadata != null) { GadgetMetadata metadata = new GadgetMetadata(gadgetMetadata); // TODO: Security token is unused therefore the gadget is stored // under the non secure key. String securityToken = null; metadataMap.put(nonSecureGadgetDataKey, new CacheElement(metadata, securityToken)); receiveDataCommand.onDataReady(metadata, securityToken); } else { receiveDataCommand.onError("Error in gadget metadata JSON.", null); } } }); } catch (RequestException e) { receiveDataCommand.onError("Unable to process gadget request.", e); } }
Example 66
Project: WaveInCloud-master File: GadgetDataStoreImpl.java View source code |
@Override public void getGadgetData(final String gadgetSpecUrl, WaveletName waveletName, int instanceId, final DataCallback receiveDataCommand) { cleanupExpiredCache(); final String secureGadgetDataKey = waveletName.waveId + " " + waveletName.waveletId + " " + instanceId + " " + gadgetSpecUrl; if (fetchDataByKey(secureGadgetDataKey, receiveDataCommand)) { return; } final String nonSecureGadgetDataKey = gadgetSpecUrl; if (fetchDataByKey(nonSecureGadgetDataKey, receiveDataCommand)) { return; } JSONObject request = new JSONObject(); JSONObject requestContext = new JSONObject(); JSONArray gadgets = new JSONArray(); JSONObject gadget = new JSONObject(); try { gadget.put("url", new JSONString(gadgetSpecUrl)); gadgets.set(0, gadget); requestContext.put("container", new JSONString("wave")); request.put("context", requestContext); request.put("gadgets", gadgets); RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, GADGET_METADATA_PATH); builder.sendRequest(request.toString(), new RequestCallback() { public void onError(Request request, Throwable exception) { receiveDataCommand.onError("Error retrieving metadata from the server.", exception); } public void onResponseReceived(Request request, Response response) { JSONObject gadgetMetadata = null; try { gadgetMetadata = JSONParser.parseLenient(response.getText()).isObject().get("gadgets").isArray().get(0).isObject(); } catch (NullPointerException exception) { receiveDataCommand.onError("Error in gadget metadata JSON.", exception); } if (gadgetMetadata != null) { GadgetMetadata metadata = new GadgetMetadata(gadgetMetadata); // TODO: Security token is unused therefore the gadget is stored // under the non secure key. String securityToken = null; metadataMap.put(nonSecureGadgetDataKey, new CacheElement(metadata, securityToken)); receiveDataCommand.onDataReady(metadata, securityToken); } else { receiveDataCommand.onError("Error in gadget metadata JSON.", null); } } }); } catch (RequestException e) { receiveDataCommand.onError("Unable to process gadget request.", e); } }
Example 67
Project: bpm-console-master File: Authentication.java View source code |
public static List<String> parseRolesAssigned(String json) {
// parse roles
List<String> roles = new ArrayList<String>();
JSONValue root = JSONParser.parse(json);
JSONArray array = JSONWalk.on(root).next("roles").asArray();
for (int i = 0; i < array.size(); ++i) {
JSONObject item = array.get(i).isObject();
boolean assigned = JSONWalk.on(item).next("assigned").asBool();
String roleName = JSONWalk.on(item).next("role").asString();
if (assigned) {
roles.add(roleName);
}
}
return roles;
}
Example 68
Project: errai-master File: ErraiManagedType.java View source code |
/** * Returns a JSON object that represents a reference to the given attribute. * The reference is done by Entity identity (the type of the attribute is * assumed to be an entity type). * * @param targetEntity * The instance of the entity to retrieve the attribute value from. * Not null. * @param attr * The attribute to read from {@code targetEntity}. Not null, and * must be an entity type. * @param eem * The ErraiEntityManager that owns the entity. Not null. * @return a JSONArray that contains references to each element in the given * attribute's collection value. Returns JSONNull if the attribute has * a null collection. */ private <C, E> JSONValue makeJsonReference(X targetEntity, ErraiPluralAttribute<? super X, C, E> attr, ErraiEntityManager eem) { // XXX when we support maps, we should use getCollection()/getMap() and this will fix the type safety warnings C attrValue = attr.get(targetEntity); if (attrValue == null) { return JSONNull.getInstance(); } Class<E> attributeType = attr.getElementType().getJavaType(); ErraiIdentifiableType<E> attrEntityType = eem.getMetamodel().entity(attributeType); if (attrEntityType == null) { throw new IllegalArgumentException("Can't make a reference to collection of non-entity-typed attributes " + attr); } JSONArray array = new JSONArray(); int index = 0; for (E element : (Iterable<E>) attrValue) { Object idToReference = attrEntityType.getId(Object.class).get(element); JSONValue ref; if (idToReference == null) { ref = JSONNull.getInstance(); } else { // XXX attrEntityType is incorrect for collection elements that are subtypes of the attrEntityType ref = new Key<E, Object>(attrEntityType, idToReference).toJsonObject(); } array.set(index++, ref); } return array; }
Example 69
Project: geogebra-master File: GeoGebraTubeAPIW.java View source code |
// /**
// * Return a list of all Materials from the specified author
// * ! Should be the same search as for materials!
// * @param author
// */
// public void getAuthorsMaterials(String author, RequestCallback callback)
// {
// throw new UnsupportedOperationException();
// }
/**
* Copies the user data from the API response to this user.
*
* @return true if the data could be parsed successfully, false otherwise
*/
@Override
public boolean parseUserDataFromResponse(GeoGebraTubeUser user, String result) {
try {
JSONValue tokener = JSONParser.parseStrict(result);
JSONObject response = tokener.isObject();
JSONObject userinfo = (JSONObject) response.get("responses");
userinfo = ((JSONArray) userinfo.get("response")).get(0).isObject();
userinfo = (JSONObject) userinfo.get("userinfo");
if (userinfo.get("user_id") instanceof JSONNumber) {
user.setUserId((int) (((JSONNumber) userinfo.get("user_id")).doubleValue()));
} else {
user.setUserId(Integer.parseInt(((JSONString) userinfo.get("user_id")).stringValue()));
}
user.setUserName(((JSONString) userinfo.get("username")).stringValue());
user.setRealName(((JSONString) userinfo.get("realname")).stringValue());
user.setIdentifier(((JSONString) userinfo.get("identifier")).stringValue());
if (userinfo.get("image") instanceof JSONString) {
user.setImageURL(((JSONString) userinfo.get("image")).stringValue());
}
if (userinfo.get("lang_ui") instanceof JSONString) {
user.setLanguage(((JSONString) userinfo.get("lang_ui")).stringValue());
}
if (userinfo.get("token") instanceof JSONString) {
user.setToken(((JSONString) userinfo.get("token")).stringValue());
}
// Further fields are not parsed yet, because they are not needed
// This is the complete response with all available fields:
/*
* <responses> <response> <userinfo> <user_id>4711</user_id>
* <username>johndoe</username>
* <ggt_profile_url>http://tube.geogebra.org/user/profile/id/4711
* </ggt_profile_url> <group>user</group>
* <date_created>2012-09-18</date_created> <lang_ui>en</lang_ui>
* <lang_content>en,en_US,it</lang_content>
* <timezone>America/New_York</timezone> <materials>31</materials>
* <favorites>4</favorites> <collections>2</collections>
* <identifier>forum:0815</identifier> <realname>John Doe</realname>
* <occupation>Maths teacher</occupation> <location>New
* York</location> <website>www.thisisme.com</website>
* <profilemessage>Any text</profilemessage> </userinfo> </response>
* </responses>
*/
// user.setGGTProfileURL(userinfo.getString("ggt_profile_url"));
// user.setGroup(userinfo.getString("group"));
// user.setDateCreated(userinfo.getString("date_created"));
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
Example 70
Project: GwtMobile-master File: BluetoothUi.java View source code |
@Override
public void onSuccess(String result) {
try {
String textHTML = "";
JSONValue value = JSONParser.parseLenient(result);
JSONArray devicesArray = value.isArray();
if (devicesArray != null) {
textHTML = "Result:";
for (int i = 0; i < devicesArray.size(); i++) {
JSONObject deviceObj = devicesArray.get(i).isObject();
textHTML = textHTML + "<br/>" + deviceObj.get("name");
}
text.setHTML(textHTML);
}
} catch (Exception e) {
e.printStackTrace();
text.setHTML("Error: " + e.getMessage());
}
}
Example 71
Project: GwtMobile-PhoneGap-master File: BluetoothUi.java View source code |
@Override
public void onSuccess(String result) {
try {
String textHTML = "";
JSONValue value = JSONParser.parseLenient(result);
JSONArray devicesArray = value.isArray();
if (devicesArray != null) {
textHTML = "Result:";
for (int i = 0; i < devicesArray.size(); i++) {
JSONObject deviceObj = devicesArray.get(i).isObject();
textHTML = textHTML + "<br/>" + deviceObj.get("name");
}
text.setHTML(textHTML);
}
} catch (Exception e) {
e.printStackTrace();
text.setHTML("Error: " + e.getMessage());
}
}
Example 72
Project: ipf-labs-master File: IpfFlowAdmin.java View source code |
@Override
protected void onSuccess(Response response) {
JSONArray results = getResultsFromResponse(response);
List<String> appIds = toStringList(results);
List<List<String>> contents = new ArrayList<List<String>>();
for (String appId : appIds) {
contents.add(Collections.singletonList(appId));
}
appsGrid.setContents(Collections.singletonList("AppId"), contents, Collections.singletonList("100%"));
}
Example 73
Project: jbpm-form-builder-master File: JsonLoadInput.java View source code |
private static Object asActualValue(JSONValue value) {
if (value.isArray() != null) {
JSONArray arr = value.isArray();
List<Object> retval = new ArrayList<Object>();
for (int index = 0; index < arr.size(); index++) {
JSONValue subValue = arr.get(index);
retval.add(asActualValue(subValue));
}
return retval;
} else if (value.isBoolean() != null) {
return String.valueOf(value.isBoolean().booleanValue());
} else if (value.isNull() != null) {
return null;
} else if (value.isNumber() != null) {
return String.valueOf(value.isNumber().doubleValue());
} else if (value.isString() != null) {
return value.isString().stringValue();
} else if (value.isObject() != null) {
return toFormData(value.isObject());
}
return null;
}
Example 74
Project: onebusaway-application-modules-master File: YelpLocalSearchProvider.java View source code |
public void onSuccess(JavaScriptObject jso) {
try {
JSONObject obj = new JSONObject(jso);
checkStatusCode(obj);
JSONArray businesses = JsonLibrary.getJsonArray(obj, "businesses");
if (businesses == null)
throw new YelpException("invalid businesses field in response");
List<LocalSearchResult> results = new ArrayList<LocalSearchResult>(businesses.size());
for (int i = 0; i < businesses.size(); i++) {
LocalSearchResult result = parseResult(businesses.get(i));
if (result != null)
results.add(result);
}
_handler.onSuccess(results);
} catch (YelpException ex) {
_handler.onFailure(ex);
}
}
Example 75
Project: Peergos-master File: JSON.java View source code |
/*
* Add the object presented by the JSONValue as a children to the requested
* TreeItem.
*/
private void addChildren(TreeItem treeItem, JSONValue jsonValue) {
JSONArray jsonArray;
JSONObject jsonObject;
JSONString jsonString;
if ((jsonArray = jsonValue.isArray()) != null) {
for (int i = 0; i < jsonArray.size(); ++i) {
TreeItem child = treeItem.addItem(getChildText("[" + Integer.toString(i) + "]"));
addChildren(child, jsonArray.get(i));
}
} else if ((jsonObject = jsonValue.isObject()) != null) {
Set<String> keys = jsonObject.keySet();
for (String key : keys) {
TreeItem child = treeItem.addItem(getChildText(key));
addChildren(child, jsonObject.get(key));
}
} else if ((jsonString = jsonValue.isString()) != null) {
// Use stringValue instead of toString() because we don't want escaping
treeItem.addItem(SafeHtmlUtils.fromString(jsonString.stringValue()));
} else {
// JSONBoolean, JSONNumber, and JSONNull work well with toString().
treeItem.addItem(getChildText(jsonValue.toString()));
}
}
Example 76
Project: pentaho-platform-master File: MantleController.java View source code |
public void onSuccess(JsArray<JsSetting> result) { if (result == null) { return; } JsSetting setting; for (int j = 0; j < result.length(); j++) { setting = result.get(j); if ("favorites".equalsIgnoreCase(setting.getName())) { //$NON-NLS-1$ try { // handle favorite JSONArray favorites = JSONParser.parseLenient(setting.getValue()).isArray(); if (favorites != null) { // Create the FavoritePickList object from the JSONArray favoritePickList = FavoritePickList.getInstanceFromJSON(favorites); } else { favoritePickList = FavoritePickList.getInstance(); } } catch (Throwable t) { } } else if ("recent".equalsIgnoreCase(setting.getName())) { //$NON-NLS-1$ try { // handle recent JSONArray recents = JSONParser.parseLenient(setting.getValue()).isArray(); if (recents != null) { // Create the RecentPickList object from the JSONArray recentPickList = RecentPickList.getInstanceFromJSON(recents); } else { recentPickList = RecentPickList.getInstance(); } recentPickList.setMaxSize(10); } catch (Throwable t) { } } } }
Example 77
Project: restlet-framework-java-master File: Contacts.java View source code |
public void handle(Request request, Response response) { try { JsonRepresentation representation = new JsonRepresentation(response.getEntity()); JSONArray jsonContacts = (JSONArray) representation.getValue(); for (int i = 0; i < jsonContacts.size(); i++) { JSONObject jsonContact = (JSONObject) jsonContacts.get(i); ContactRepresentation contact = new ContactRepresentation(); contact.setFirstName(((JSONString) jsonContact.get("firstName")).stringValue()); contact.setLastName(((JSONString) jsonContact.get("lastName")).stringValue()); contact.setEmail(((JSONString) jsonContact.get("email")).stringValue()); contact.setLogin(((JSONString) jsonContact.get("login")).stringValue()); contact.setSenderName(((JSONString) jsonContact.get("senderName")).stringValue()); } } catch (Exception ex) { GWT.log("Unable to parse JSON", ex); } }
Example 78
Project: rstudio-master File: RemoteServer.java View source code |
public void quitSession(boolean saveWorkspace, String switchToProject, RVersionSpec switchToRVersion, String hostPageUrl, ServerRequestCallback<Boolean> requestCallback) { JSONArray params = new JSONArray(); params.set(0, JSONBoolean.getInstance(saveWorkspace)); params.set(1, new JSONString(StringUtil.notNull(switchToProject))); if (switchToRVersion != null) params.set(2, new JSONObject(switchToRVersion)); else params.set(2, JSONNull.getInstance()); params.set(3, new JSONString(StringUtil.notNull(hostPageUrl))); sendRequest(RPC_SCOPE, QUIT_SESSION, params, requestCallback); }
Example 79
Project: soundtransit-rds-master File: YelpLocalSearchProvider.java View source code |
public void onSuccess(JavaScriptObject jso) {
try {
JSONObject obj = new JSONObject(jso);
checkStatusCode(obj);
JSONArray businesses = JsonLibrary.getJsonArray(obj, "businesses");
if (businesses == null)
throw new YelpException("invalid businesses field in response");
List<LocalSearchResult> results = new ArrayList<LocalSearchResult>(businesses.size());
for (int i = 0; i < businesses.size(); i++) {
LocalSearchResult result = parseResult(businesses.get(i));
if (result != null)
results.add(result);
}
_handler.onSuccess(results);
} catch (YelpException ex) {
_handler.onFailure(ex);
}
}
Example 80
Project: SpiffyForms-master File: User.java View source code |
@Override
public void onSuccess(JSONValue val) {
JSONArray usersArray = val.isArray();
ArrayList<User> users = new ArrayList<User>();
for (int i = 0; i < usersArray.size(); i++) {
if (usersArray.get(i).isNull() != null) {
continue;
}
User u = new User();
u.setFirstName(JSONUtil.getStringValue(usersArray.get(i).isObject(), "firstName"));
u.setLastName(JSONUtil.getStringValue(usersArray.get(i).isObject(), "lastName"));
u.setPassword(JSONUtil.getStringValue(usersArray.get(i).isObject(), "password"));
u.setUserId(JSONUtil.getStringValue(usersArray.get(i).isObject(), "userID"));
u.setEmail(JSONUtil.getStringValue(usersArray.get(i).isObject(), "email"));
u.setUserDesc(JSONUtil.getStringValue(usersArray.get(i).isObject(), "desc"));
u.setGender(JSONUtil.getStringValue(usersArray.get(i).isObject(), "gender"));
u.setBirthday(JSONUtil.getDateValue(usersArray.get(i).isObject(), "birthday"));
u.m_isNew = false;
users.add(u);
}
callback.success(users.toArray(new User[users.size()]));
}
Example 81
Project: StweetMap-master File: StweetMap.java View source code |
public void onRequestComplete(JavaScriptObject obj) { searchInputPanel.getBusy().setVisible(false); JSONObject json = new JSONObject(obj); JSONArray posts = (JSONArray) json.get("results"); for (int i = 0; i < posts.size(); i++) { JSONObject post = (JSONObject) posts.get(i); StatusMessage statusMessage = new StatusMessage(post); displayStatusMessage(statusMessage); if (Config.isGeolocationEnabled) checkLocation(statusMessage); } }
Example 82
Project: t3as-snomedct-service-master File: AnalyseHandler.java View source code |
// send the text from the mainTextArea to the server and accept an async response private void sendTextToServer() { statusLabel.setText(""); conceptList.clear(); // don't do anything if we have no text final String text = mainTextArea.getText(); if (text.length() < 1) { statusLabel.setText(messages.pleaseEnterTextLabel()); return; } // disable interaction while we wait for the response glassPanel.setPositionAndShow(); // build up the AnalysisRequest JSON object // start with any options final JSONArray options = new JSONArray(); setSemanticTypesOption(types, options); // defaults options.set(options.size(), new JSONString("word_sense_disambiguation")); options.set(options.size(), new JSONString("composite_phrases 8")); options.set(options.size(), new JSONString("no_derivational_variants")); options.set(options.size(), new JSONString("strict_model")); options.set(options.size(), new JSONString("ignore_word_order")); options.set(options.size(), new JSONString("allow_large_n")); options.set(options.size(), new JSONString("restrict_to_sources SNOMEDCT_US")); final JSONObject analysisRequest = new JSONObject(); analysisRequest.put("text", new JSONString(text)); analysisRequest.put("options", options); // send the input to the server final RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, webserviceUrl); builder.setHeader("Content-Type", MediaType.APPLICATION_JSON); builder.setRequestData(analysisRequest.toString()); // create the async callback builder.setCallback(new SnomedRequestCallback(conceptList, statusLabel, glassPanel, typeCodeToDescription)); // send the request try { builder.send(); } catch (final RequestException e) { statusLabel.setText(messages.problemPerformingAnalysisLabel()); GWT.log("There was a problem performing the analysis: " + e.getMessage(), e); glassPanel.hide(); } }
Example 83
Project: wsdot-mobile-app-master File: HomeActivity.java View source code |
@Override public void onSuccess(FerriesRouteFeed result) { if (result.getRoutes() != null) { ferriesRouteItems.clear(); FerriesRouteItem item; int numRoutes = result.getRoutes().length(); for (int i = 0; i < numRoutes; i++) { item = new FerriesRouteItem(); item.setRouteID(result.getRoutes().get(i).getRouteID()); item.setDescription(result.getRoutes().get(i).getDescription()); item.setCrossingTime(result.getRoutes().get(i).getCrossingTime()); item.setScheduleDate(new JSONArray(result.getRoutes().get(i).getDate()).toString()); item.setRouteAlert(new JSONArray(result.getRoutes().get(i).getRouteAlert()).toString()); item.setCacheDate(dateFormat.format(new Date(Long.parseLong(result.getRoutes().get(i).getCacheDate().substring(6, 19))))); if (starred.contains(result.getRoutes().get(i).getRouteID())) { item.setIsStarred(1); } ferriesRouteItems.add(item); } // Purge existing border wait times covered by incoming data dbService.deleteFerriesSchedules(new VoidCallback() { @Override public void onFailure(DataServiceException error) { } @Override public void onSuccess() { // Bulk insert all the new ferries schedules dbService.insertFerriesSchedules(ferriesRouteItems, new RowIdListCallback() { @Override public void onFailure(DataServiceException error) { } @Override public void onSuccess(List<Integer> rowIds) { // Update the cache table with the time we did the update List<CacheItem> cacheItems = new ArrayList<CacheItem>(); cacheItems.add(new CacheItem(Tables.FERRIES_SCHEDULES, System.currentTimeMillis())); dbService.updateCachesTable(cacheItems, new VoidCallback() { @Override public void onFailure(DataServiceException error) { } @Override public void onSuccess() { dbService.getStarredFerriesSchedules(new ListCallback<GenericRow>() { @Override public void onFailure(DataServiceException error) { } @Override public void onSuccess(final List<GenericRow> starredMountainPassRows) { getFerriesSchedules(starredFerriesSchedules); } }); } }); } }); } }); } }
Example 84
Project: XACML-Policy-Analysis-Tool-master File: Analysr.java View source code |
public void onSuccess(Object result) { JSONObject resultObj = (JSONObject) JSONParser.parse((String) result); JSONArray res = ((JSONArray) resultObj.get("result")); String messageText = ""; for (int i = 0; i < res.size(); i++) { messageText += res.get(i) + "\n"; } showMessageBox("Explanation", messageText); }
Example 85
Project: gwt-mvp-master File: FileUploader.java View source code |
@Override public void onComplete(String id, String filename, JSONValue response) { if (response.isArray() != null) { JSONArray array = (JSONArray) response; for (int i = 0; i < array.size(); i++) { filesInProgress--; if (filesInProgress == 0) { fireEvent(new UploadingCompletedEvent()); } final JSONObject value = (JSONObject) array.get(i); final JSONValue size = value.get("size"); final JSONValue url = value.get("url"); final JSONValue type = value.get("type"); final String url2 = String.valueOf(url); fileInfos.put(id, new FileInfo(id, // TODO: is there a good way to remove quotes? url2.substring(1, url2.length() - 1), filename, Integer.valueOf(String.valueOf(size)), Integer.valueOf(String.valueOf(size)), String.valueOf(type), null, false, value)); updateExactFileInfo(id); } } }
Example 86
Project: opentsdb-master File: QueryUi.java View source code |
public void got(final JSONValue json) {
// Do we need more manual type checking? Not sure what will happen
// in the browser if something other than an array is returned.
final JSONArray aggs = json.isArray();
for (int i = 0; i < aggs.size(); i++) {
aggregators.add(aggs.get(i).isString().stringValue());
}
((MetricForm) metrics.getWidget(0)).setAggregators(aggregators);
refreshFromQueryString();
refreshGraph();
}
Example 87
Project: R2Time-master File: QueryUi.java View source code |
public void got(final JSONValue json) {
// Do we need more manual type checking? Not sure what will happen
// in the browser if something other than an array is returned.
final JSONArray aggs = json.isArray();
for (int i = 0; i < aggs.size(); i++) {
aggregators.add(aggs.get(i).isString().stringValue());
}
((MetricForm) metrics.getWidget(0)).setAggregators(aggregators);
refreshFromQueryString();
refreshGraph();
}
Example 88
Project: 3f-lab-master File: Slider.java View source code |
/**
* A convenient way to create an options JSONObject. Use SliderOption for keys.
* @param min - default minimum of the slider
* @param max - default maximum of the slider
* @param defaultValues - default points of each anchor
* @return a JSONObject of Slider options
*/
public static JSONObject getOptions(int min, int max, int[] defaultValues) {
JSONObject options = new JSONObject();
options.put(SliderOption.MIN.toString(), new JSONNumber(min));
options.put(SliderOption.MAX.toString(), new JSONNumber(max));
JSONArray vals = intArrayToJSONArray(defaultValues);
options.put(SliderOption.VALUES.toString(), vals);
return options;
}
Example 89
Project: dhcalc-master File: JsonUtil.java View source code |
public static <T extends Enum<T>> Set<T> parseSet(Class<T> clazz, String text) {
if ((text == null) || (text.trim().length() == 0))
return null;
Set<T> set = new TreeSet<T>();
JSONValue value = JSONParser.parseLenient(text);
JSONArray array = value.isArray();
if (array == null)
return null;
for (int i = 0; i < array.size(); i++) {
JSONValue e = array.get(i);
if (e != null) {
JSONString str = e.isString();
if (str != null) {
String name = str.stringValue();
if (name != null) {
T elem = Enum.valueOf(clazz, name);
if (elem != null) {
set.add(elem);
}
}
}
}
}
return set;
}
Example 90
Project: gwt-bvh-master File: PoseEditorData.java View source code |
public static JSONObject convertToJson(PoseEditorData data) { JSONObject poseData = new JSONObject(); //name poseData.put("name", new JSONString(data.getName())); poseData.put("cdate", new JSONNumber(data.getCdate())); //LogUtils.log("name-cdate"); //bones JSONArray bones = new JSONArray(); for (int i = 0; i < data.getBones().size(); i++) { bones.set(i, new JSONString(data.getBones().get(i))); } poseData.put("bones", bones); JSONArray frames = new JSONArray(); for (int i = 0; i < data.getPoseFrameDatas().size(); i++) { JSONObject frameValue = new JSONObject(); PoseFrameData fdata = data.getPoseFrameDatas().get(i); //angles List<Vector3> angles = fdata.getAngles(); if (angles == null) { LogUtils.log("warn:angles is null"); } JSONArray anglesValue = new JSONArray(); for (int j = 0; j < angles.size(); j++) { anglesValue.set(j, toJSONArray(angles.get(j))); } frameValue.put("angles", anglesValue); //LogUtils.log("angles"); //positions List<Vector3> positions = fdata.getPositions(); JSONArray positionValue = new JSONArray(); for (int j = 0; j < positions.size(); j++) { positionValue.set(j, toJSONArray(positions.get(j))); } frameValue.put("positions", positionValue); //LogUtils.log("positions"); /* List<String> ikNames=fdata.getIkTargetNames(); JSONArray ikNameValue=new JSONArray(); for(int j=0;j<ikNames.size();j++){ ikNameValue.set(j, new JSONString(ikNames.get(j))); } frameValue.put("ik-names", ikNameValue); //LogUtils.log("ik-names"); * */ //positions /*//no more need ik value Map<String,Vector3> ikpositions=fdata.getIkTargetPositionMap(); JSONArray ikpositionsValue=new JSONArray(); int index=0; for(String name:ikpositions.keySet()){ JSONString jsonName=new JSONString(name); JSONArray jsonvec=toJSONArray(ikpositions.get(name)); JSONObject ikData=new JSONObject(); ikData.put("name", jsonName); ikData.put("pos", jsonvec); ikpositionsValue.set(index,ikData ); index++; } frameValue.put("ik-positions", ikpositionsValue); */ //LogUtils.log("ik-positions"); frames.set(i, frameValue); } poseData.put("frames", frames); return poseData; }
Example 91
Project: GWTChromeCast-master File: TicTacToe.java View source code |
/** * Request event for the board layout: sends the current layout of pieces on * the board through the channel. * * @param Channel * channel the channel the event came from. */ private void onBoardLayoutRequest(Channel channel) { console.log("****onBoardLayoutRequest"); JSONArray array = new JSONArray(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { array.set(i * 3 + j, new JSONNumber(this.mBoard.mBoard[i][j])); } } JSONObject data = new JSONObject(); data.put("event", new JSONString("board_layout_response")); data.put("board", array); channel.send(data); }
Example 92
Project: roda-master File: FormUtilities.java View source code |
private static void addList(FlowPanel panel, final FlowPanel layout, final MetadataValue mv, final boolean mandatory) { // Top Label Label mvLabel = new Label(getFieldLabel(mv)); mvLabel.addStyleName("form-label"); if (mandatory) { mvLabel.addStyleName("form-label-mandatory"); } // Field final ListBox mvList = new ListBox(); mvList.setTitle(mvLabel.getText()); mvList.addStyleName("form-textbox"); String options = mv.get("options"); JSONArray optionsArray = null; if (options != null) { optionsArray = JSONParser.parseLenient(options).isArray(); } String list = mv.get("optionsLabels"); mvList.addItem(""); if (list != null) { JSONArray jsonArray = JSONParser.parseLenient(list).isArray(); if (jsonArray != null) { for (int i = 0; i < jsonArray.size(); i++) { String value = jsonArray.get(i).isString().stringValue(); mvList.addItem(value); if (value.equals(mv.get("value"))) { mvList.setSelectedIndex(i + 1); } } } else { JSONObject jsonObject = JSONParser.parseLenient(list).isObject(); if (jsonObject != null) { String loc = LocaleInfo.getCurrentLocale().getLocaleName(); int i = 0; if (optionsArray != null) { for (int pos = 0; pos < optionsArray.size(); pos++) { String key = optionsArray.get(pos).isString().stringValue(); JSONValue entry = jsonObject.get(key); if (entry.isObject() != null) { JSONValue jsonValue = entry.isObject().get(loc); String value; if (jsonValue != null) { value = jsonValue.isString().stringValue(); } else { value = entry.isObject().get(entry.isObject().keySet().iterator().next()).isString().stringValue(); } if (value != null) { mvList.addItem(value, key); if (key.equals(mv.get("value"))) { mvList.setSelectedIndex(i + 1); } } } i++; } } else { for (String key : jsonObject.keySet()) { JSONValue entry = jsonObject.get(key); if (entry.isObject() != null) { JSONValue jsonValue = entry.isObject().get(loc); String value; if (jsonValue != null) { value = jsonValue.isString().stringValue(); } else { value = entry.isObject().get(entry.isObject().keySet().iterator().next()).isString().stringValue(); } if (value != null) { mvList.addItem(value, key); if (key.equals(mv.get("value"))) { mvList.setSelectedIndex(i + 1); } } } i++; } } } } } else { if (optionsArray != null) { int i = 0; for (int pos = 0; pos < optionsArray.size(); pos++) { String key = optionsArray.get(pos).isString().stringValue(); if (key != null) { mvList.addItem(key, key); if (key.equals(mv.get("value"))) { mvList.setSelectedIndex(i + 1); } } i++; } } } mvList.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent changeEvent) { mv.set("value", mvList.getSelectedValue()); if (mandatory && (mvList.getSelectedValue() != null && !"".equals(mvList.getSelectedValue().trim()))) { mvList.removeStyleName("isWrong"); } if (mandatory && (mvList.getSelectedValue() == null || "".equalsIgnoreCase(mvList.getSelectedValue().trim()))) { mvList.removeStyleName("isWrong"); } } }); if (mv.get("value") == null || mv.get("value").isEmpty()) { mvList.setSelectedIndex(0); mv.set("value", mvList.getSelectedValue()); } layout.add(mvLabel); layout.add(mvList); // Description String description = mv.get("description"); if (description != null && description.length() > 0) { Label mvDescription = new Label(description); mvDescription.addStyleName("form-help"); layout.add(mvDescription); } if (mv.get("error") != null && !"".equals(mv.get("error").trim())) { Label errorLabel = new Label(mv.get("error")); errorLabel.addStyleName("form-label-error"); layout.add(errorLabel); mvList.addStyleName("isWrong"); } panel.add(layout); }
Example 93
Project: SPIFF-master File: MultivalueSuggestBoxBase.java View source code |
/**
* Handle the query response for getting items to suggest.
*
* @param callback the callback for the request
* @param val the value we are getting suggestions for
*/
protected void handleQueryResponse(RESTObjectCallBack<OptionResultSet> callback, JSONValue val) {
JSONObject obj = val.isObject();
int totSize = JSONUtil.getIntValue(obj, m_helper.getTotalSizeKey());
OptionResultSet options = new OptionResultSet(totSize);
JSONArray optionsArray = JSONUtil.getJSONArray(obj, m_helper.getOptionsKey());
if (options.getTotalSize() > 0 && optionsArray != null) {
for (int i = 0; i < optionsArray.size(); i++) {
if (optionsArray.get(i) == null) {
/*
This happens when a JSON array has an invalid trailing comma
*/
continue;
}
JSONObject jsonOpt = optionsArray.get(i).isObject();
Option option = createOption(jsonOpt);
options.addOption(option);
}
}
callback.success(options);
}
Example 94
Project: spiffyui-master File: MultivalueSuggestBoxBase.java View source code |
/**
* Handle the query response for getting items to suggest.
*
* @param callback the callback for the request
* @param val the value we are getting suggestions for
*/
protected void handleQueryResponse(RESTObjectCallBack<OptionResultSet> callback, JSONValue val) {
JSONObject obj = val.isObject();
int totSize = JSONUtil.getIntValue(obj, m_helper.getTotalSizeKey());
OptionResultSet options = new OptionResultSet(totSize);
JSONArray optionsArray = JSONUtil.getJSONArray(obj, m_helper.getOptionsKey());
if (options.getTotalSize() > 0 && optionsArray != null) {
for (int i = 0; i < optionsArray.size(); i++) {
if (optionsArray.get(i) == null) {
/*
This happens when a JSON array has an invalid trailing comma
*/
continue;
}
JSONObject jsonOpt = optionsArray.get(i).isObject();
Option option = createOption(jsonOpt);
options.addOption(option);
}
}
callback.success(options);
}
Example 95
Project: crux-master File: JSonSerializerProxyCreator.java View source code |
/**
* @return
*/
protected String[] getImports() {
String[] imports = new String[] { JSONParser.class.getCanonicalName(), JSONValue.class.getCanonicalName(), JSONObject.class.getCanonicalName(), JSONArray.class.getCanonicalName(), JSONNull.class.getCanonicalName(), JSONNumber.class.getCanonicalName(), JSONBoolean.class.getCanonicalName(), JSONString.class.getCanonicalName(), JsUtils.class.getCanonicalName(), GWT.class.getCanonicalName() };
return imports;
}
Example 96
Project: guit-master File: JsonSerializerUtil.java View source code |
public static String generate(TreeLogger logger, GeneratorContext context, JClassType pojoType) throws UnableToCompleteException { JsonSerializerUtil.logger = logger; // We cannot serialize java.lang.Object String pojoQualifiedName = pojoType.getQualifiedSourceName(); if (pojoQualifiedName.equals(Object.class.getCanonicalName())) { error("You cannot serialize Object... we either"); } if (exceptions == null) { exceptions = new HashMap<String, String>(); try { List<String> ormExceptions = context.getPropertyOracle().getConfigurationProperty("json.orm.exception").getValues(); for (String e : ormExceptions) { String[] parts = e.split(" "); if (parts.length != 2) { error("Bad json orm exception format. i.e 'java.util.List java.util.ArrayList<%s>. Found: %s'", e); } exceptions.put(parts[0], parts[1]); } } catch (BadPropertyValueException e) { throw new IllegalStateException(e); } } String parameterizedQualifiedSourceName = pojoType.getParameterizedQualifiedSourceName(); String typeName = parameterizedQualifiedSourceName; // Basic types if (typeName.equals(Void.class.getCanonicalName())) { return VoidSerializer.class.getCanonicalName(); } else if (typeName.equals(String.class.getCanonicalName())) { return StringSerializer.class.getCanonicalName(); } else if (typeName.equals(Integer.class.getCanonicalName())) { return IntegerSerializer.class.getCanonicalName(); } else if (typeName.equals(Long.class.getCanonicalName())) { return LongSerializer.class.getCanonicalName(); } else if (typeName.equals(Double.class.getCanonicalName())) { return DoubleSerializer.class.getCanonicalName(); } else if (typeName.equals(Float.class.getCanonicalName())) { return FloatSerializer.class.getCanonicalName(); } else if (typeName.equals(Date.class.getCanonicalName())) { return DateSerializer.class.getCanonicalName(); } else if (typeName.equals(Boolean.class.getCanonicalName())) { return BooleanSerializer.class.getCanonicalName(); } // Build name avoiding generics collitions StringBuilder implName = new StringBuilder(); makeImplName(pojoType, implName); implName.append("_GuitJsonSerializer"); String packageName = pojoType.getPackage().getName(); if (packageName.startsWith("java.")) { packageName = "com.guit.java." + packageName.substring(5); } String implNameString = implName.toString(); if (getClass(packageName, implNameString)) { return packageName + "." + implNameString; } ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, implNameString); composer.addImplementedInterface(TypeJsonSerializer.class.getCanonicalName() + "<" + typeName + ">"); PrintWriter printWriter = context.tryCreate(logger, packageName, implNameString); String createdName = composer.getCreatedClassName(); if (printWriter != null) { SourceWriter writer = composer.createSourceWriter(context, printWriter); JType iterableParameterType = null; JPrimitiveType iterableParameterPrimitiveType = null; // Iterable JGenericType iterableType = context.getTypeOracle().findType(Iterable.class.getCanonicalName()).isGenericType(); boolean isIterable = false; if (iterableType.isAssignableFrom(pojoType)) { isIterable = true; iterableParameterType = pojoType.asParameterizationOf(iterableType).getTypeArgs()[0]; iterableParameterPrimitiveType = iterableParameterType.isPrimitive(); // Find if theres any exception String qualifiedSourceName = pojoQualifiedName; if (exceptions.containsKey(qualifiedSourceName)) { parameterizedQualifiedSourceName = exceptions.get(qualifiedSourceName) + "<" + iterableParameterType.getParameterizedQualifiedSourceName() + ">"; } } // Map JGenericType mapType = context.getTypeOracle().findType(Map.class.getCanonicalName()).isGenericType(); boolean isMap = false; JClassType mapKeyType = null; JClassType mapValueType = null; if (mapType.isAssignableFrom(pojoType)) { isMap = true; JParameterizedType pojoMap = pojoType.asParameterizationOf(mapType); JClassType[] args = pojoMap.getTypeArgs(); mapKeyType = args[0]; mapValueType = args[1]; // Find if theres any exception String qualifiedSourceName = pojoQualifiedName; if (exceptions.containsKey(qualifiedSourceName)) { parameterizedQualifiedSourceName = exceptions.get(qualifiedSourceName) + "<" + mapKeyType.getParameterizedQualifiedSourceName() + "," + mapValueType.getParameterizedQualifiedSourceName() + ">"; } } // Array boolean isArray = false; JArrayType pojoArray = pojoType.isArray(); if (pojoArray != null) { isArray = true; iterableParameterType = pojoArray.getComponentType(); iterableParameterPrimitiveType = iterableParameterType.isPrimitive(); } // For pojos ArrayList<JField> fields = null; writer.println("public static " + createdName + " singleton;"); writer.println("public static " + createdName + " getSingleton() {"); writer.indent(); writer.println("return singleton == null ? (singleton = new " + createdName + "()) : singleton;"); writer.outdent(); writer.println("}"); writer.println("@Override"); writer.println("public " + JSONValue.class.getCanonicalName() + " serialize(" + typeName + " data) {"); writer.indent(); if (isMap) { writer.println("if (data != null) {"); writer.indent(); writer.println(JSONArray.class.getCanonicalName() + " array = new " + JSONArray.class.getCanonicalName() + "();"); writer.println("int n = 0;"); writer.println("for (" + Entry.class.getCanonicalName() + "<" + mapKeyType.getParameterizedQualifiedSourceName() + ", " + mapValueType.getParameterizedQualifiedSourceName() + ">" + " entry : data.entrySet()) {"); writer.indent(); writer.print("array.set(n, "); JPrimitiveType mapKeyPrimitive = mapKeyType.isPrimitive(); if (mapKeyPrimitive == null) { printValueSerialized(logger, context, writer, "entry.getKey()", mapKeyType, pojoType); } else { printPrimitiveSerialized(typeName, writer, "entry.getKey()", mapKeyPrimitive); } writer.println(");"); writer.println("n++;"); writer.print("array.set(n, "); JPrimitiveType mapValuePrimitive = mapValueType.isPrimitive(); if (mapValuePrimitive == null) { printValueSerialized(logger, context, writer, "entry.getValue()", mapValueType, pojoType); } else { printPrimitiveSerialized(typeName, writer, "entry.getValue()", mapValuePrimitive); } writer.println(");"); writer.println("n++;"); writer.outdent(); writer.println("}"); writer.println("return array;"); writer.outdent(); writer.println("}"); writer.println("return " + JSONNull.class.getCanonicalName() + ".getInstance();"); } else if (isIterable || isArray) { writer.println("if (data != null) {"); writer.indent(); writer.println(JSONArray.class.getCanonicalName() + " array = new " + JSONArray.class.getCanonicalName() + "();"); writer.println("int n = 0;"); writer.println("for (" + iterableParameterType.getParameterizedQualifiedSourceName() + " item : data) {"); writer.indent(); writer.print("array.set(n, "); if (iterableParameterPrimitiveType == null) { printValueSerialized(logger, context, writer, "item", iterableParameterType, pojoType); } else { printPrimitiveSerialized(typeName, writer, "item", iterableParameterPrimitiveType); } writer.println(");"); writer.println("n++;"); writer.outdent(); writer.println("}"); writer.println("return array;"); writer.outdent(); writer.println("}"); writer.println("return " + JSONNull.class.getCanonicalName() + ".getInstance();"); } else if (pojoType.isEnum() != null) { writer.println("if (data != null) {"); writer.indent(); writer.println("return new " + JSONString.class.getCanonicalName() + "(data.name());"); writer.outdent(); writer.println("}"); writer.println("return " + JSONNull.class.getCanonicalName() + ".getInstance();"); } else { // Assert the type have an empty constructor try { pojoType.getConstructor(emptyParameter); } catch (NotFoundException e) { error("The data type of the place does not have an empty constructor. Found %s", typeName); } writer.println(jsonObject + " json = new " + jsonObject + "();"); fields = new ArrayList<JField>(); getFields(fields, pojoType); for (JField f : fields) { String fieldName = f.getName(); String getterName = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); JType fieldType = f.getType(); JPrimitiveType primitive = fieldType.isPrimitive(); String fieldTypeQualifiedType = fieldType.getQualifiedSourceName(); if (primitive != null) { writer.print("json.put(\"" + fieldName + "\","); printPrimitiveSerialized(typeName, writer, "get" + getterName + "(data)", primitive); writer.println(");"); } else { writer.println(fieldTypeQualifiedType + " " + fieldName + " = get" + getterName + "(data);"); writer.println("if (" + fieldName + " != null) {"); writer.indent(); writer.print("json.put(\"" + fieldName + "\","); printValueSerialized(logger, context, writer, fieldName, fieldType, pojoType); writer.println(");"); writer.outdent(); writer.println("}"); } } writer.println("return json;"); } writer.outdent(); writer.println("}"); // Getters and setters printJsniGettersAndSetters(writer, pojoType); writer.println("@Override"); writer.println("public " + typeName + " deserialize(" + JSONValue.class.getCanonicalName() + " jsonValue) {"); writer.indent(); if (isMap) { writer.println("if (jsonValue.isNull() == null) {"); writer.indent(); writer.println(JSONArray.class.getCanonicalName() + " jsonArray = jsonValue.isArray();"); writer.println("int jsonArraySize = jsonArray.size();"); writer.println(parameterizedQualifiedSourceName + " map = new " + parameterizedQualifiedSourceName + "();"); writer.println("for (int n = 0; n < jsonArraySize; n+=2) {"); writer.indent(); writer.println(JSONValue.class.getCanonicalName() + " key = jsonArray.get(n);"); writer.println(JSONValue.class.getCanonicalName() + " value = jsonArray.get(n + 1);"); writer.print("map.put("); JPrimitiveType mapKeyPrimitive = mapKeyType.isPrimitive(); if (mapKeyPrimitive == null) { printValueDeserialized(logger, context, writer, "key", mapKeyType); } else { printPrimitiveDeserialized(typeName, writer, "key", mapKeyPrimitive); } writer.print(","); JPrimitiveType mapValuePrimitive = mapValueType.isPrimitive(); if (mapValuePrimitive == null) { printValueDeserialized(logger, context, writer, "value", mapValueType); } else { printPrimitiveDeserialized(typeName, writer, "value", mapValuePrimitive); } writer.println(");"); writer.outdent(); writer.println("}"); writer.println("return map;"); writer.outdent(); writer.println("} else { return null; }"); } else if (isIterable || isArray) { writer.println("if (jsonValue.isNull() == null) {"); writer.indent(); writer.println(JSONArray.class.getCanonicalName() + " jsonArray = jsonValue.isArray();"); writer.println("int jsonArraySize = jsonArray.size();"); if (isIterable) { writer.println(parameterizedQualifiedSourceName + " array = new " + parameterizedQualifiedSourceName + "();"); } else { JArrayType array = iterableParameterType.isArray(); if (array != null) { String arrayName = array.getQualifiedSourceName() + "[]"; int index = arrayName.indexOf("["); String arrayDeclaration = arrayName.substring(0, index + 1) + "jsonArraySize" + arrayName.substring(index + 1); writer.println(arrayName + " array = new " + arrayDeclaration + ";"); } else { String parameterQualifiedName = iterableParameterType.getQualifiedSourceName(); writer.println(parameterQualifiedName + "[] array = new " + parameterQualifiedName + "[jsonArraySize];"); } } writer.println("for (int n = 0; n < jsonArraySize; n++) {"); writer.indent(); writer.println(JSONValue.class.getCanonicalName() + " item = jsonArray.get(n);"); if (isIterable) { writer.print("array.add("); } else { writer.print("array[n] = "); } if (iterableParameterPrimitiveType == null) { printValueDeserialized(logger, context, writer, "item", iterableParameterType); } else { printPrimitiveDeserialized(typeName, writer, "item", iterableParameterPrimitiveType); } if (isIterable) { writer.println(");"); } else { writer.println(";"); } writer.outdent(); writer.println("}"); writer.println("return array;"); writer.outdent(); writer.println("} else { return null; }"); } else if (pojoType.isEnum() != null) { writer.println("if (jsonValue.isNull() == null) {"); writer.indent(); writer.println("return " + typeName + ".valueOf(jsonValue.isString().stringValue());"); writer.outdent(); writer.println("} else { return null; }"); } else { // Assert the type have an empty constructor try { pojoType.getConstructor(emptyParameter); } catch (NotFoundException e) { error("The data type of the place does not have an empty constructor. Found %s", typeName); } writer.println(JSONObject.class.getCanonicalName() + " json = jsonValue.isObject();"); writer.println(typeName + " instance = new " + typeName + "();"); for (JField f : fields) { String fieldName = f.getName(); String setterName = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); JType fieldType = f.getType(); JPrimitiveType primitive = fieldType.isPrimitive(); if (primitive != null) { writer.print("set" + setterName + "(instance,"); printPrimitiveDeserialized(typeName, writer, "json.get(\"" + fieldName + "\")", primitive); writer.println(");"); } else { writer.println("if (json.containsKey(\"" + fieldName + "\")) {"); writer.indent(); writer.print("set" + setterName + "(instance,"); printValueDeserialized(logger, context, writer, "json.get(\"" + fieldName + "\")", fieldType); writer.println(");"); writer.outdent(); writer.println("}"); } } writer.println("return instance;"); } writer.outdent(); writer.println("}"); writer.commit(logger); } return createdName; }
Example 97
Project: gwtphonegap-master File: ContactBrowserImpl.java View source code |
public static Contact fromJSON(ContactsBrowserImpl controller, JSONObject jsonContact) { ContactBrowserImpl contact = new ContactBrowserImpl(controller); // simple fields contact.setId(getFieldAsString(jsonContact.get(FIELD_ID))); contact.setDisplayName(getFieldAsString(jsonContact.get(CONTACT_DISPLAY_NAME))); contact.setNickName(getFieldAsString(jsonContact.get(CONTACT_NICK_NAME))); contact.setNote(getFieldAsString(jsonContact.get(CONTACT_NOTE))); // birthday JSONValue dateValue = jsonContact.get(CONTACT_BIRTHDAY); if (dateValue != null && dateValue.isNumber() != null) { contact.setBirthDay(new Date((long) dateValue.isNumber().doubleValue())); } // contact fields JSONArray phoneNumberArray = jsonContact.get(CONTACT_PHONE_NUMBERS).isArray(); LightArray<ContactField> phoneNumbers = getContactFieldsForArray(phoneNumberArray); contact.setPhoneNumbers(phoneNumbers); JSONArray emailsArray = jsonContact.get(CONTACT_EMAILS).isArray(); LightArray<ContactField> emails = getContactFieldsForArray(emailsArray); contact.setEmails(emails); JSONArray imsArray = jsonContact.get(CONTACT_IMS).isArray(); LightArray<ContactField> ims = getContactFieldsForArray(imsArray); contact.setIms(ims); JSONArray photosArray = jsonContact.get(CONTACT_PHOTOS).isArray(); LightArray<ContactField> photos = getContactFieldsForArray(photosArray); contact.setPhotos(photos); JSONArray categoriesArray = jsonContact.get(CONTACT_CATEGORIES).isArray(); LightArray<ContactField> categories = getContactFieldsForArray(categoriesArray); contact.setCategories(categories); JSONArray urlsArray = jsonContact.get(CONTACT_URLS).isArray(); LightArray<ContactField> urls = getContactFieldsForArray(urlsArray); contact.setUrls(urls); ContactName name = getName(jsonContact.get(CONTACT_NAME).isObject()); contact.setName(name); LightArray<ContactAddress> addresses = getAddressArray(jsonContact.get(CONTACT_ADDRESSES).isArray()); contact.setContactAddresses(addresses); LightArray<ContactOrganisation> organisations = getContactOrganisationArray(jsonContact.get(CONTACT_ORGANISATION).isArray()); contact.setOrganisations(organisations); return contact; }
Example 98
Project: gwtphotoalbum-master File: ImageCollectionReader.java View source code |
private HashMap<String, int[][]> interpretSizes(JSONValue json) throws JSONException { HashMap<String, int[][]> resolutions = new HashMap<String, int[][]>(); HashMap<String, int[][]> sizes = new HashMap<String, int[][]>(); JSONObject dict = json.isObject(); JSONArray array = json.isArray(); if (array != null) { JSONObject resDict = array.get(0).isObject(); for (String key : resDict.keySet()) { JSONArray resSet = resDict.get(key).isArray(); resolutions.put(key, interpretResolutionsArray(resSet)); } dict = array.get(1).isObject(); } for (String key : dict.keySet()) { // JSONArray list = dict.get(key).isArray(); // resolutions.clear(); // for (int i = 0; i < list.size(); i++ ) { // JSONArray xy = list.get(i).isArray(); // int res[] = new int[2]; // res[0] = (int) xy.get(0).isNumber().doubleValue(); // res[1] = (int) xy.get(1).isNumber().doubleValue(); // resolutions.add(res); // } // sizes.put(key, resolutions.toArray(new int[resolutions.size()][])); JSONValue value = dict.get(key); array = value.isArray(); if (array != null) { sizes.put(key, interpretResolutionsArray(array)); } else { sizes.put(key, resolutions.get(value.isString().stringValue())); } } return sizes; }
Example 99
Project: GoogleMapWidget-master File: VGoogleMap.java View source code |
public void onResponseReceived(Request request, Response response) {
String markerJSON = response.getText();
System.out.println("" + markerJSON.length() + " bytes of marker response got in " + (System.currentTimeMillis() - markerRequestSentAt) + "ms");
JSONArray array = null;
try {
long start = System.currentTimeMillis();
JSONValue json = JSONParser.parse(markerJSON);
array = json.isArray();
log(1, "JSON parsed in " + (System.currentTimeMillis() - start) + "ms");
if (array == null) {
System.out.println("Marker JSON was not an array.");
return;
}
handleMarkerJSON(array);
} catch (Exception e) {
log(1, "Error parsing json: " + e.getMessage());
}
}
Example 100
Project: kune-master File: MultivalueSuggestBox.java View source code |
@Override
public void onResponseReceived(final com.google.gwt.http.client.Request request, final Response response) {
final JSONValue val = JSONParser.parse(response.getText());
final JSONObject obj = val.isObject();
final int totSize = (int) obj.get(OptionResultSet.TOTAL_SIZE).isNumber().doubleValue();
final OptionResultSet options = new OptionResultSet(totSize);
final JSONArray optionsArray = obj.get(OptionResultSet.OPTIONS).isArray();
if (options.getTotalSize() > 0 && optionsArray != null) {
for (int i = 0; i < optionsArray.size(); i++) {
if (optionsArray.get(i) == null) {
/*
* This happens when a JSON array has an invalid trailing comma
*/
continue;
}
final JSONObject jsonOpt = optionsArray.get(i).isObject();
final Option option = new Option();
final String longName = jsonOpt.get(OptionResultSet.DISPLAY_NAME).isString().stringValue();
final String shortName = jsonOpt.get(OptionResultSet.VALUE).isString().stringValue();
final JSONValue groupTypeJsonValue = jsonOpt.get("groupType");
final String prefix = groupTypeJsonValue.isString() == null ? "" : GroupType.PERSONAL.name().equals(groupTypeJsonValue.isString().stringValue()) ? I18n.t("User") + ": " : I18n.t("Group") + ": ";
option.setName(prefix + (!longName.equals(shortName) ? longName + " (" + shortName + ")" : shortName));
option.setValue(jsonOpt.get(OptionResultSet.VALUE).isString().stringValue());
options.addOption(option);
}
}
callback.success(options);
}
Example 101
Project: Evening-IDE-master File: JSONArray.java View source code |
/**
* Called from {@link #getUnwrapper()}.
*/
private static JavaScriptObject unwrap(JSONArray value) {
return value.jsArray;
}