Java Code Examples for com.google.gwt.json.client.JSONObject

The following are top voted examples for showing how to use com.google.gwt.json.client.JSONObject. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: empiria.player   File: ItemBody.java   View source code 6 votes vote down vote up
public JSONArray getState() {

        JSONObject states = new JSONObject();

        for (IModule currModule : modules) {
            if (currModule instanceof StatefulModule) {
                StatefulModule statefulModule = (StatefulModule) currModule;
                states.put(statefulModule.getIdentifier(), statefulModule.getState());
            }
        }

        JSONArray statesArr = new JSONArray();
        statesArr.set(0, states);

        return statesArr;
    }
 
Example 2
Project: empiria.player   File: EmpiriaStateDeserializerGWTTestCase.java   View source code 6 votes vote down vote up
public void testShouldReturnIdentifierFromState() throws Exception {
    // given
    String givenState = "givenState";
    String identifier = "identifier";

    JSONObject givenStateObject = new JSONObject();
    givenStateObject.put(EmpiriaState.STATE, new JSONString(givenState));
    givenStateObject.put(EmpiriaState.LESSON_IDENTIFIER, new JSONString(identifier));
    givenStateObject.put(EmpiriaState.TYPE, new JSONString("LZ_GWT"));

    // when
    EmpiriaState result = testObj.deserialize(givenStateObject);

    // then
    assertEquals(result.getState(), givenState);
    assertEquals(result.getLessonIdentifier(), identifier);
}
 
Example 3
Project: empiria.player   File: EmpiriaStateImportCreatorTest.java   View source code 6 votes vote down vote up
@Test
public void shouldDecompressState_whileCreating() throws Exception {
    // GIVEN
    String givenState = "state";
    String expectedState = "compressed";

    JSONObject parsedState = new JSONObject();
    when(jsonParser.parse(givenState)).thenReturn(parsedState);

    EmpiriaState empiriaState = new EmpiriaState(EmpiriaStateType.LZ_GWT, givenState, "id");
    when(empiriaStateVerifier.verifyState(empiriaState)).thenReturn(empiriaState);
    when(empiriaStateDeserializer.deserialize(parsedState)).thenReturn(empiriaState);

    when(lzGwtWrapper.decompress(givenState)).thenReturn(expectedState);

    // WHEN
    String result = testObj.createState(givenState);

    // THEN
    assertThat(result).isEqualTo(expectedState);
}
 
Example 4
Project: empiria.player   File: EmpiriaStateImportCreatorTest.java   View source code 6 votes vote down vote up
@Test
public void shouldReturnEmptyState_whenStateIsUnknown() throws Exception {
    // GIVEN
    String givenState = "state";

    JSONObject parsedState = new JSONObject();
    when(jsonParser.parse(givenState)).thenReturn(parsedState);

    EmpiriaState empiriaState = new EmpiriaState(EmpiriaStateType.UNKNOWN, givenState, StringUtils.EMPTY);
    when(empiriaStateVerifier.verifyState(empiriaState)).thenReturn(empiriaState);
    when(empiriaStateDeserializer.deserialize(parsedState)).thenReturn(empiriaState);

    // WHEN
    String result = testObj.createState(givenState);

    // THEN
    assertThat(result).isEmpty();
}
 
Example 5
Project: empiria.player   File: EmpiriaStateImportCreatorTest.java   View source code 6 votes vote down vote up
@Test
public void shouldDoNothingWithState_whenStateHasOldType() throws Exception {
    // GIVEN
    String givenState = "state";

    JSONObject parsedState = new JSONObject();
    when(jsonParser.parse(givenState)).thenReturn(parsedState);

    EmpiriaState empiriaState = new EmpiriaState(EmpiriaStateType.OLD, givenState, StringUtils.EMPTY);
    when(empiriaStateVerifier.verifyState(empiriaState)).thenReturn(empiriaState);
    when(empiriaStateDeserializer.deserialize(parsedState)).thenReturn(empiriaState);

    // WHEN
    String result = testObj.createState(givenState);

    // THEN
    assertThat(result).isEqualTo(givenState);
    verify(lzGwtWrapper, never()).decompress(givenState);
}
 
Example 6
Project: empiria.player   File: ExternalStateEncoderGWTTestCase.java   View source code 6 votes vote down vote up
public void testShouldGetStateObject() {
    // given
    JavaScriptObject state = JavaScriptObject.createObject();
    JSONArray stateArray = new JSONArray();
    stateArray.set(0, new JSONObject(state));

    JSONObject stateObject = new JSONObject();
    stateObject.put("STATE", stateArray);

    JSONArray jsonArray = new JSONArray();
    jsonArray.set(0, stateObject);

    // when
    JavaScriptObject result = testObj.decodeState(jsonArray);

    // then
    assertEquals(result, state);
}
 
Example 7
Project: empiria.player   File: ModulesStateLoaderGWTTestCase.java   View source code 6 votes vote down vote up
public void testSetStateOnFirstModuleOnly() { // given //
    // given
    // @formatter:off
    String stateString = "{\"" +
            FIRST_IDENTIFIER + "\":" + FIRST_STATE +
            "}";
    // @formatter:on

    JSONObject stateObject = getStateObjectByString(stateString);
    JSONArray state = getJSONArrayWithObject(stateObject);

    // when
    loader.setState(state, modules);

    // then
    assertEquals(stateObject.get(FIRST_IDENTIFIER).isArray(), firstModule.getState());
    assertNull(secondModule.getState());
}
 
Example 8
Project: empiria.player   File: ModulesStateLoaderGWTTestCase.java   View source code 6 votes vote down vote up
public void testSetStateOnTwoModules() {
    // given
    // @formatter:off
    String stateString = "{\"" +
            FIRST_IDENTIFIER + "\":" + FIRST_STATE + ", \"" +
            SECOND_IDENTIFIER + "\":" + SECOND_STATE +
            "}";
    // @formatter:on

    JSONObject stateObject = getStateObjectByString(stateString);
    JSONArray state = getJSONArrayWithObject(stateObject);

    // when
    loader.setState(state, modules);

    // then
    assertEquals(stateObject.get(FIRST_IDENTIFIER).isArray(), firstModule.getState());
    assertEquals(stateObject.get(SECOND_IDENTIFIER).isArray(), secondModule.getState());
}
 
Example 9
Project: sig-seguimiento-vehiculos   File: Project.java   View source code 6 votes vote down vote up
public String toJSON() {

		JSONObject projectObject = new JSONObject();
		projectObject.put("version", new JSONString(getVersion()));
		projectObject.put("title", new JSONString(getTitle()));
		projectObject.put("description", new JSONString(getDescription()));
		projectObject.put("date", new JSONString(getDate()));		
		
		JSONArray layersArray = new JSONArray();
		int index = 0;
		for(ProjectVectorLayer projectLayer: vectors) {
			layersArray.set(index, projectLayer.getJSONObject());
			
			index++;
		}
		
		projectObject.put("vectors", layersArray);

		return projectObject.toString();
	}
 
Example 10
Project: sig-seguimiento-vehiculos   File: LeafletStyle.java   View source code 6 votes vote down vote up
public static ProjectLayerStyle getStyle(String geoJSONCSS) {
	ProjectLayerStyle style = null;
	final JSONValue jsonValue = JSONParser.parseLenient(geoJSONCSS);
	final JSONObject geoJSONCssObject = jsonValue.isObject();

	if (geoJSONCssObject.containsKey(GeoJSONCSS.STYLE_NAME)) {

		JSONObject styleObject = geoJSONCssObject
				.get(GeoJSONCSS.STYLE_NAME).isObject();

		String fillColor = getStringValue(styleObject, FILL_COLOR_NAME);
		Double fillOpacity = getDoubleValue(styleObject, FILL_OPACITY_NAME);
		if(fillOpacity == null) {
			fillOpacity = getDoubleValue(styleObject, FILL_OPACITY2_NAME);				
		}
		String strokeColor = getStringValue(styleObject, STROKE_COLOR_NAME);
		Double strokeWidth = getDoubleValue(styleObject, STROKE_WIDTH_NAME);

		style = new ProjectLayerStyle(fillColor, fillOpacity, strokeColor,
				strokeWidth);
	}

	return style;
}
 
Example 11
Project: appinventor-extensions   File: WaitForBuildResultCommand.java   View source code 6 votes vote down vote up
private static String extractFormName(RpcResult result) {
  String extraString = result.getExtra();
  if (extraString != null) {
    JSONValue extraJSONValue = JSONParser.parseStrict(extraString);
    JSONObject extraJSONObject = extraJSONValue.isObject();
    if (extraJSONObject != null) {
      JSONValue formNameJSONValue = extraJSONObject.get("formName");
      if (formNameJSONValue != null) {
        JSONString formNameJSONString = formNameJSONValue.isString();
        if (formNameJSONString != null) {
          return formNameJSONString.stringValue();
        }
      }
    }
  }
  return "Screen1";
}
 
Example 12
Project: gwt-cs   File: Materials.java   View source code 6 votes vote down vote up
public void applyAlphaMapMaterial(Primitive primitive) {
    JSONObject uniforms = new JSONObject();
    uniforms.put("image", new JSONString(GWT.getModuleBaseURL() + "images/Cesium_Logo_Color.jpg"));
    uniforms.put("channel", new JSONString("r"));

    JSONObject alphaMaterial = new JSONObject();
    alphaMaterial.put("type", new JSONString("AlphaMap"));
    alphaMaterial.put("uniforms", uniforms);

    JSONObject materials = new JSONObject();
    materials.put("alphaMaterial", alphaMaterial);

    JSONObject components = new JSONObject();
    components.put("diffuse", new JSONString("vec3(1.0)"));
    components.put("alpha", new JSONString("alphaMaterial.alpha"));

    JSONObject fabric = new JSONObject();
    fabric.put("materials", materials);
    fabric.put("components", components);

    MaterialOptions materialOptions = new MaterialOptions();
    materialOptions.fabric = JsonUtils.safeEval(fabric.toString());
    primitive.appearance.material = new Material(materialOptions);
}
 
Example 13
Project: gwt-cs   File: Materials.java   View source code 6 votes vote down vote up
public void applyWaterMaterial(Primitive primitive) {
    JSONObject uniforms = new JSONObject();
    uniforms.put("specularMap", new JSONString(GWT.getModuleBaseURL() + "images/earthspec1k.jpg"));
    uniforms.put("normalMap", new JSONString(GWT.getModuleBaseURL() + "images/waterNormals.jpg"));
    uniforms.put("frequency", new JSONNumber(10000.0));
    uniforms.put("animationSpeed", new JSONNumber(0.01));
    uniforms.put("amplitude", new JSONNumber(1.0));

    JSONObject fabric = new JSONObject();
    fabric.put("type", new JSONString("Water"));
    fabric.put("uniforms", uniforms);

    MaterialOptions materialOptions = new MaterialOptions();
    materialOptions.fabric = JsonUtils.safeEval(fabric.toString());
    primitive.appearance.material = new Material(materialOptions);
}
 
Example 14
Project: gwt-uploader   File: Configurable.java   View source code 6 votes vote down vote up
private void setOption(JSONObject rootObject, String path, Object value) {
  if (path == null) {
    return;
  }
  if (path.startsWith("/")) {
    path = path.substring(1);
  }
  if (path.length() <= 0) {
    return;
  }
  String nodeName = path;
  if (nodeName.contains("/")) {
    nodeName = nodeName.substring(0, nodeName.indexOf("/"));
    JSONValue objectAsValue = rootObject.get(nodeName);
    if (objectAsValue == null || objectAsValue.isObject() == null) {
      rootObject.put(nodeName, new JSONObject());
    }
    JSONObject object = (JSONObject) rootObject.get(nodeName);
    setOption(object, path.substring(path.indexOf("/") + 1), value);
  } else {
    rootObject.put(nodeName, convertToJSONValue(value));
  }
}
 
Example 15
Project: Wiab.pro   File: GadgetUserPrefs.java   View source code 6 votes vote down vote up
/**
 * Extracts default preference values from the gadget metadata JSON object
 * returned from GGS.
 *
 * @param prefs the preference JSON object received from GGS.
 */
public void parseDefaultValues(JSONObject prefs) {
  if (prefs != null) {
    for (String pref : prefs.keySet()) {
      if (!has(pref)) {
        JSONObject prefJson = prefs.get(pref).isObject();
        if (prefJson != null) {
          JSONValue value = prefJson.get("default");
          if ((value != null) && (value.isString() != null)) {
            put(pref, value.isString().stringValue());
            log("Gadget pref '" + pref + "' = '" + get(pref) + "'");
          }
        } else {
          log("Invalid pref '" + pref + "' value in Gadget metadata.");
        }
      }
    }
  }
}
 
Example 16
Project: Wiab.pro   File: GwtGadgetInfoParser.java   View source code 6 votes vote down vote up
private GadgetInfo parseGadgetInfo(JSONValue item) {
  JSONObject object = item.isObject();
  if (object != null) {
    String name = object.get("name").isString().stringValue();
    String desc = object.get("desc").isString().stringValue();
    GadgetCategoryType primaryCategory =
        GadgetCategoryType.of(object.get("primaryCategory").isString().stringValue());
    GadgetCategoryType secondaryCategory =
        GadgetCategoryType.of(object.get("secondaryCategory").isString().stringValue());
    String gadgetUrl = object.get("gadgetUrl").isString().stringValue();
    String author = object.get("author").isString().stringValue();
    String submittedBy = object.get("submittedBy").isString().stringValue();
    String imageUrl = object.get("imageUrl").isString().stringValue();

    return new GadgetInfo(name, desc, primaryCategory, secondaryCategory, gadgetUrl, author,
        submittedBy, imageUrl);
  }
  return null;
}
 
Example 17
Project: riscoss-corporate   File: RiskAnalysisResults.java   View source code 6 votes vote down vote up
public void showResults(JsonRiskAnalysis summary, JSONObject response) {
	risksLabel = new Label("Risks");
	risksLabel.setStyleName("smallTitle");
	goalsLabel = new Label("Goals");
	goalsLabel.setStyleName("smallTitle");
	
	this.response = response;
	this.summary = summary;
	this.jsonArgumentation = response.get("argumentation");
	Codec codec = GWT.create( Codec.class );
	
	if( jsonArgumentation != null ) {
		argumentation = codec.decode( jsonArgumentation );
	}
	results = new HashMap<>();
	
	tree.clear();
	if (response.get("hresults") != null ) generateTree(tree, response.get("hresults"));
	else {
		leftPanel.setWidth("0px");
		results.put(summary.getTarget(), response.get("results").isArray());
	}
	
	setSelectedEntity(summary.getTarget());
}
 
Example 18
Project: gwt-formlayout   File: App.java   View source code 6 votes vote down vote up
private void helloWorld() throws Exception {
  JSONObject sampleData = new JSONObject();
  sampleData.put("Field1", new JSONNumber(1.0));
  sampleData.put("Field2", new JSONString("Hello world"));
  sampleData.put("Field3", JSONBoolean.getInstance(true));

  // Sample 1 - basic usage
  final FormLayout formLayout = new FormLayout(sampleData.toString());
  RootPanel.get().add(formLayout);

  Button button = new Button("Apply");
  button.addStyleName(style.apply());
  button.addClickHandler(new ClickHandler() {

    @Override
    public void onClick(ClickEvent event) {
      Window.alert(formLayout.getDataJson());
    }
  });

  formLayout.appendWidgetToBottom(button);
}
 
Example 19
Project: dhcalc   File: JsonUtil.java   View source code 6 votes vote down vote up
public static Hero toHero(JSONObject obj) {

		Hero hero = new Hero();
		
		hero.name = obj.get("name").isString().stringValue();
		hero.id = (int) obj.get("id").isNumber().doubleValue();
		hero.level = (int) obj.get("level").isNumber().doubleValue();
		hero.paragonLevel = (int) obj.get("paragonLevel").isNumber().doubleValue();
		hero.lastUpdated = (long)obj.get("lastUpdated").isNumber().doubleValue();
		hero.hardcore = obj.get("hardcore").isBoolean().booleanValue();
		hero.seasonal = obj.get("seasonal").isBoolean().booleanValue();
		hero.dead = obj.get("dead").isBoolean().booleanValue();
		hero.clazz = obj.get("clazz").isString().stringValue();

		return hero;
		
	}
 
Example 20
Project: riscoss-corporate   File: IndicatorWidget.java   View source code 6 votes vote down vote up
NumberInput( JSONObject o ) {
	sb.setNotSelectedInFocus();
	
	sb.addBarValueChangedHandler( new BarValueChangedHandler() {
		public void onBarValueChanged(BarValueChangedEvent event) {
			label.setText( "" + sb.getValue() );
			for( Listener l : listeners ) {
				l.IndicatorValueChanged();
			}
		}
	});
	
	label.getElement().getStyle().setMarginLeft( 12, Unit.PX );
	
	panel.add( sb );
	panel.add( label );
	
	setValue( o );
}
 
Example 21
Project: dojo-ibl   File: GeneralItem.java   View source code 6 votes vote down vote up
private String depToHumanReadableString(JSONObject json) {
    if (json.containsKey("type") && json.get("type").isString().stringValue().contains("ActionDependency")) {
        return actionDepToHumanReadableString(json);
    }
    if (json.containsKey("type") && json.get("type").isString().stringValue().contains("TimeDependency")) {
        return timeDepToHumanReadableString(json);
    }
    if (json.containsKey("type") && json.get("type").isString().stringValue().contains("AndDependency")) {
        return andDepToHumanReadableString(json);
    }
    if (json.containsKey("type") && json.get("type").isString().stringValue().contains("OrDependency")) {
        return orDepToHumanReadableString(json);
    }
    if (json.containsKey("type") && json.get("type").isString().stringValue().contains("ProximityDependency")) {
        return proximityDepToHumanReadableString(json);
    }
    return "not supported in viewing mode";
}
 
Example 22
Project: riscoss-corporate   File: RDCConfigurationPage.java   View source code 6 votes vote down vote up
public JSONObject getJson() {
	for( String key : RDCConfigurationPage.this.rdcMap.keySet() ) {
		boolean enabled = enabledMap.isEnabled( key );
		enabledMap.enableRDC( key, enabled );
		if( enabled ) {
			JSONArray parameters = RDCConfigurationPage.this.rdcMap.parameters( key );
			for( int i = 0; i < parameters.size(); i++ ) {
				String parName = 
						RDCConfigurationPage.this.rdcMap.getParamterName( key, i );
				Element e = Document.get().getElementById( "txt:" + key + ":" + parName );
				if( e == null ) continue;
				String value = e.getPropertyString( "value" ) ;
				enabledMap.set( key, parName, value );
			}
		}
	}
	return enabledMap.getJson();
}
 
Example 23
Project: geowe-core   File: LeafletStyle.java   View source code 6 votes vote down vote up
public static ProjectLayerStyle getStyle(String geoJSONCSS) {
	ProjectLayerStyle style = null;
	final JSONValue jsonValue = JSONParser.parseLenient(geoJSONCSS);
	final JSONObject geoJSONCssObject = jsonValue.isObject();

	if (geoJSONCssObject.containsKey(GeoJSONCSS.STYLE_NAME)) {

		JSONObject styleObject = geoJSONCssObject
				.get(GeoJSONCSS.STYLE_NAME).isObject();

		String fillColor = getStringValue(styleObject, FILL_COLOR_NAME);
		Double fillOpacity = getDoubleValue(styleObject, FILL_OPACITY_NAME);
		if(fillOpacity == null) {
			fillOpacity = getDoubleValue(styleObject, FILL_OPACITY2_NAME);				
		}
		String strokeColor = getStringValue(styleObject, STROKE_COLOR_NAME);
		Double strokeWidth = getDoubleValue(styleObject, STROKE_WIDTH_NAME);

		style = new ProjectLayerStyle(fillColor, fillOpacity, strokeColor,
				strokeWidth);
	}

	return style;
}
 
Example 24
Project: riscoss-corporate   File: ComparisonPanel.java   View source code 6 votes vote down vote up
protected Widget generateIndicatorWidget(JSONObject v) {
	VerticalPanel panel = new VerticalPanel();
	GaugeImage img = new GaugeImage();
	img.setEvidence( v.get( "p" ).isString().stringValue(), v.get( "m" ).isString().stringValue() );
	SimplePanel pp = new SimplePanel();
	pp.setWidget(img);
	pp.setStyleName("contentResultsTable");
	panel.add(pp);
	panel.add( new HTML( 
			"Exposure: <font color='red'>" + 
					v.get( "e" ).isObject().get( "e" ).isNumber().doubleValue() +
			"</font>") );
	panel.setStyleName("headerTable");
	panel.setHeight("100%");
	return panel;
}
 
Example 25
Project: scheduling-portal   File: SchedulerJSONUtils.java   View source code 6 votes vote down vote up
/**
 * Parse a paginated list of tasks
 * @param jsonString the JSON representing the paginated list of tasks.
 * @return An object wrapping the list of tasks and the total number of tasks without pagination.
 * @throws JSONException if it fails to parse the JSON.
 */
public static JSONPaginatedTasks parseJSONPaginatedTasks(JSONValue value) throws JSONException {
    JSONObject jsonTasksTotal = getObject(value);

    JSONArray arr = getArray(getProperty(jsonTasksTotal, "list"));

    List<Task> tasks = new ArrayList<Task>();

    for (int i = 0; i < arr.size(); i++) {
        JSONObject jsonTask = arr.get(i).isObject();
        tasks.add(Task.parseJson(jsonTask));
    }

    long totalTasks = getSize(jsonTasksTotal);

    JSONPaginatedTasks result = new JSONPaginatedTasks(tasks, totalTasks);
    return result;
}
 
Example 26
Project: scheduling-portal   File: Job.java   View source code 6 votes vote down vote up
private static Map<String, String> extractMap(JSONValue mapValue) {
    if (mapValue != null) {
        JSONArray keyValueArray = mapValue.isArray();
        if (keyValueArray != null) {
            int arraySize = keyValueArray.size();
            Map<String, String> resultMap = new HashMap<>(arraySize);
            for (int i = 0; i < keyValueArray.size(); i++) {
                JSONObject object = keyValueArray.get(i).isObject();
                String key = object.get("key").isString().stringValue();
                String value = object.get("value").isString().stringValue();
                resultMap.put(key, value);
            }
            return resultMap;
        }
    }
    return Collections.emptyMap();
}
 
Example 27
Project: firefly   File: ClientEventQueue.java   View source code 6 votes vote down vote up
private static ServerEvent parseJsonEvent(String msg) {
    try {
        JSONObject eventJ = JSONParser.parseStrict(msg).isObject();
        Name name = new Name(eventJ.get("name").isString().stringValue(), "");
        ServerEvent.Scope scope = ServerEvent.Scope.valueOf(eventJ.get("scope").isString().stringValue());
        ServerEvent.DataType dataType = eventJ.get("dataType") == null ? ServerEvent.DataType.STRING :
                ServerEvent.DataType.valueOf(eventJ.get("dataType").isString().stringValue());
        Serializable data;
        String from =  eventJ.get("from") == null ? null : eventJ.get("from").toString();
        if (dataType == ServerEvent.DataType.BG_STATUS) {
            data = BackgroundStatus.parse(eventJ.get("data").isString().stringValue());
        } else if (dataType == ServerEvent.DataType.JSON) {
            data = eventJ.get("data").isObject().toString();
        } else {
            data = eventJ.get("data").isString().stringValue();
        }
        ServerEvent sEvent = new ServerEvent(name, scope, dataType, data);
        sEvent.setFrom(from);
        return sEvent;

    } catch (Exception e) {
        GwtUtil.getClientLogger().log(Level.WARNING, "Unable to parse json message into ServerEvent: " + msg, e);
        return null;
    }
}
 
Example 28
Project: dojo-ibl   File: DependencyGrid.java   View source code 6 votes vote down vote up
private JSONObject getJson(TreeNode node) {
	TreeNode[] childNodes = tree.getChildren(node);
	JSONObject[] childJsons = new JSONObject[childNodes.length];
	for (int i = 0; i < childNodes.length; i++) {
		childJsons[i] = getJson(childNodes[i]);
	}
	if (node.getAttributeAsInt("typeInt") != null) {
		switch (node.getAttributeAsInt("typeInt")) {
		case AndDependencyTreeNode.TYPE:
			return AndDependencyTreeNode.getJson(childJsons);
		case OrDependencyTreeNode.TYPE:
			return OrDependencyTreeNode.getJson(childJsons);
		case ActionDependencyNode.TYPE:
			return ActionDependencyNode.getJson(childNodes);
		case TimeDependencyNode.TYPE:
			return TimeDependencyNode.getJson(childJsons, childNodes);
		case ProximityDependencyNode.TYPE:
			return ProximityDependencyNode.getJson(childNodes);
		default:
			break;
		}
	}

	return new JSONObject();
}
 
Example 29
Project: riscoss-corporate   File: MissingDataInputForm.java   View source code 6 votes vote down vote up
protected void gatherUserEnteredDataAndRunAgain() {
	
	JSONObject o = new JSONObject();
	
	for( String key : textboxes.keySet() ) {
		ManualInputField txt = textboxes.get( key );
		JSONObject val = new JSONObject();
		val.put( "id", new JSONString( key ) );
		val.put( "value", new JSONString( txt.getValue().trim() ) );
		o.put( key, val );
	}
	
	dialog.hide();
	
	if( cb != null ) {
		cb.onDone( o );
	}
	
}
 
Example 30
Project: scheduling-portal   File: MBeanChart.java   View source code 6 votes vote down vote up
protected double[] getJsonSlice(JSONObject json, int i) {

        double[] res = new double[json.keySet().size()];

        int counter = 0;
        for (String key : json.keySet()) {
            JSONArray values = json.get(key).isArray();
            double numValue = 0;

            if (values != null) {
                JSONNumber num = values.get(i).isNumber();
                if (num != null) {
                    numValue = num.doubleValue();
                }
            }

            res[counter++] = numValue;
        }
        return res;
    }
 
Example 31
Project: dojo-ibl   File: ActionDependencyNode.java   View source code 6 votes vote down vote up
public static JSONObject getJson(TreeNode[] childNodes) {
	JSONObject dep = new JSONObject();
	dep.put("type", new JSONString(DEP_TYPE));
	for (TreeNode tn: childNodes) {
		if (tn.getAttribute("type").equals(ACTION)) {
			if (tn.getAttribute("Value")!=null) dep.put("action", new JSONString(tn.getAttribute("Value")));
		}
		if (tn.getAttribute("type").equals(GENERALITEM)) {
			if (tn.getAttribute("Value")!=null) dep.put("generalItemId", new JSONNumber(Long.parseLong(tn.getAttribute("Value"))));
		}
		if (tn.getAttribute("type").equals(SCOPE)) {
			if (tn.getAttribute("Value")!=null) dep.put("scope", new JSONNumber(Long.parseLong(tn.getAttribute("Value"))));
		}
		if (tn.getAttribute("type").equals(ROLE)) {
			if (tn.getAttribute("Value")!=null) if (tn.getAttribute("Value") != null) dep.put("role", new JSONString(tn.getAttribute("Value")));
		}
	}
	return dep;
}
 
Example 32
Project: scheduling-portal   File: RMController.java   View source code 6 votes vote down vote up
private void fetchNodesLimit() {
    this.rm.getState(LoginModel.getInstance().getSessionId(), new AsyncCallback<String>() {
        public void onSuccess(String result) {
            // Parse json response to extract the current node limit
            JSONObject rmState = JSONParser.parseStrict(result).isObject();
            if (rmState == null) {
                LogModel.getInstance().logMessage("Failed to parse json rmState: " + result);
            } else {
                JSONValue maxNumberOfNodes = rmState.get("maxNumberOfNodes");
                if (maxNumberOfNodes != null && maxNumberOfNodes.isNumber() != null) {
                    model.setMaxNumberOfNodes(Long.parseLong(maxNumberOfNodes.isNumber().toString()));
                }
            }
        }

        public void onFailure(Throwable caught) {
            LogModel.getInstance()
                    .logMessage("Failed to access node limit through rmState: " + caught.getMessage());
        }
    });
}
 
Example 33
Project: dojo-ibl   File: JsonResumptionListCallback.java   View source code 6 votes vote down vote up
public void onJsonReceived(JSONValue jsonValue) {
	JSONObject jsonObject = jsonValue.isObject();
	if (jsonObject == null) {
		return;
	}
	if (jsonObject.containsKey("resumptionToken")) {
		resumptionToken = jsonObject.get("resumptionToken").isString().stringValue();
		nextCall();
	} else {
		if (jsonObject.containsKey("serverTime"))
			dataSourceModel.setServerTime((long) jsonObject.get("serverTime").isNumber().doubleValue());
	}
	if (jsonObject.get("error") != null) {
		Authentication.getInstance().disAuthenticate();
	} else {
		onJsonArrayReceived(jsonObject);
	}
}
 
Example 34
Project: google-apis-explorer   File: RpcApiRequestGwtTest.java   View source code 6 votes vote down vote up
public void testRequestBody() {
  JSONObject root = new JSONObject();
  root.put("method", new JSONString("api.method.name"));
  root.put("version", new JSONString("v1"));

  JSONObject params = new JSONObject();
  root.put("params", params);
  params.put("param1", new JSONString("value1"));

  ApiService service = RpcApiService.Helper.fromString("{}");
  RpcApiRequest request = new RpcApiRequest(service, mockMethod);

  request.setBody(root);

  ListMultimap<String, String> paramValues = request.getParamValues();
  assertEquals(Sets.newHashSet("param1"), paramValues.keySet());
  assertEquals(ImmutableList.of("\"value1\""), paramValues.get("param1"));

  assertEquals(root.toString(), request.getRequestBody());
}
 
Example 35
Project: dhcalc   File: SavePanel.java   View source code 6 votes vote down vote up
protected void saveLocalStorage() {
	final Storage s = getStorage();

	if (s != null) {
		final int i = storageList.getSelectedIndex();

		if (i < 0) {
			ApplicationPanel.showErrorDialog("Select a Storage entry");
		} else {
			if (listener != null) {
				final FormData data = listener.getFormData();

				JSONObject obj = JsonUtil.toJSONObject(data);
				String key = storageList.getValue(i);
				s.setItem(key, obj.toString());
				
				ApplicationPanel.showInfoDialog("Configuration Saved.");
			}
		}
	}
}
 
Example 36
Project: riscoss-corporate   File: IndicatorWidget.java   View source code 6 votes vote down vote up
@Override
		public void setValue( JSONObject o ) {
			
			double min = Double.parseDouble( o.get( "min" ).isString().stringValue() );
			double max = Double.parseDouble( o.get( "max" ).isString().stringValue() );
			
			int intervals = 100;
			
			String datatype = o.get( "datatype" ).isString().stringValue();
//			REAL, INTEGER, STRING, EVIDENCE, DISTRIBUTION, NaN
			if( "REAL".equals( datatype ) )
				intervals = (int)(100 * (max - min));
			else if( "INTEGER".equals( datatype ) )
				intervals = (int)max - (int)min;
//			else if( "STRING".equals( datatype ) )
//				intervals = 100;
//			else if( "EVIDENCE".equals( datatype ) )
//				intervals = 100;
//			else if( "DISTRIBUTION".equals( datatype ) )
//				intervals = 100;
//			else if( "NaN".equals( datatype ) )
//				intervals = 100;
			
			range = new Range( min, max, intervals );
			sb.setMaxValue( (int)range.getSliderMax() );
		}
 
Example 37
Project: che   File: JsonHelper.java   View source code 6 votes vote down vote up
public static Map<String, String> toMap(String jsonStr) {
  Map<String, String> map = new HashMap<String, String>();

  JSONValue parsed = JSONParser.parseStrict(jsonStr);
  JSONObject jsonObj = parsed.isObject();
  if (jsonObj != null) {
    for (String key : jsonObj.keySet()) {
      JSONValue jsonValue = jsonObj.get(key);
      JSONString jsonString = jsonValue.isString();
      // if the json value is a string, set the unescaped value, else set the json representation
      // of the value
      String stringValue = (jsonString == null) ? jsonValue.toString() : jsonString.stringValue();
      map.put(key, stringValue);
    }
  }

  return map;
}
 
Example 38
Project: che   File: UrlBuilder.java   View source code 6 votes vote down vote up
/**
 * Parse url and set initial parameters(protocol, host, port, path)<br>
 *
 * @param url
 */
public UrlBuilder(String url) {
  JavaScriptObject jso = parseUrl(url);
  o = new JSONObject(jso);
  setHost(o.get("host").isString().stringValue());
  setProtocol(o.get("protocol").isString().stringValue());
  if (o.containsKey("port")) {
    final String port = o.get("port").isString().stringValue();
    if (!port.isEmpty()) {
      setPort(Integer.valueOf(port));
    }
  }
  setPath(o.get("path").isString().stringValue());
  // fill query parameters
  JSONObject query = o.get("queryKey").isObject();
  for (String key : query.keySet()) {
    setParameter(key, query.get(key).isString().stringValue());
  }
}
 
Example 39
Project: empiria.player   File: ExternalStateEncoder.java   View source code 5 votes vote down vote up
public JSONArray encodeState(JavaScriptObject state) {

        JavaScriptObject javaScriptObject = frameObjectFixer.fix(state);
        JSONObject obj = new JSONObject(javaScriptObject);
        JSONArray jsonArray = new JSONArray();

        jsonArray.set(0, obj);
        return jsonArray;
    }
 
Example 40
Project: empiria.player   File: ExternalStateEncoder.java   View source code 5 votes vote down vote up
private JavaScriptObject getState(JSONValue jsonValue) {
    JSONObject state = jsonValue.isObject();

    if (state.containsKey(STATE)) {
        return state.get(STATE).isArray().get(0).isObject().getJavaScriptObject();
    }

    return state.getJavaScriptObject();
}