本文整理汇总了Java中org.apache.sling.commons.json.JSONObject类的典型用法代码示例。如果您正苦于以下问题:Java JSONObject类的具体用法?Java JSONObject怎么用?Java JSONObject使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
JSONObject类属于org.apache.sling.commons.json包,在下文中一共展示了JSONObject类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: respStacks
import org.apache.sling.commons.json.JSONObject; //导入依赖的package包/类
private static String respStacks() {
try {
JSONObject response = new JSONObject();
JSONObject state = new JSONObject();
state.put("label", "OK");
state.put("id", "OK");
response.put("state", state);
response.put("id", "1234");
response.put("stack", "1234");
response.put("name", "Appliance1");
response.put("projectUri",
"http://test.com/cloud/api/projects/54346");
JSONObject stack = new JSONObject();
stack.put("id", "idValue");
response.put("stack", stack);
return response.toString();
} catch (JSONException ex) {
throw new RuntimeException(ex);
}
}
示例2: put
import org.apache.sling.commons.json.JSONObject; //导入依赖的package包/类
protected void put(String key, Object value) {
if (key == null) {
throw new IllegalArgumentException(
"JSON object key must not be null!");
}
if (!(value instanceof String) && !(value instanceof JSONObject)) {
throw new IllegalArgumentException("Object type "
+ (value == null ? "NULL" : value.getClass().getName())
+ " not allowed as JSON value.");
}
try {
request.put(key, value);
} catch (JSONException e) {
// this can basically not happen
throw new IllegalArgumentException(e.getMessage());
}
}
示例3: addOptionalFields
import org.apache.sling.commons.json.JSONObject; //导入依赖的package包/类
/**
* Adds the requested set of optional fields to provided {@link JSONObject}
* @param jsonObject
* The {@link JSONObject} to add optional fields to
* @param optionalFields
* The optional fields along with the requested values to be added to the provided {@link JSONObject}
* @param dateFormatter
* The format to apply when adding time stamp values
* @param totalMessageCount
* The total number of messages received from the window
* @return
* The provided {@link JSONObject} enhanced by the requested values
* @throws JSONException
* Thrown in case anything fails during operations on the JSON object
*/
protected JSONObject addOptionalFields(final JSONObject jsonObject, final Map<String, String> optionalFields, final SimpleDateFormat dateFormatter, final int totalMessageCount) throws JSONException {
// step through the optional fields if any were provided
if(jsonObject != null && optionalFields != null && !optionalFields.isEmpty()) {
for(final String fieldName : optionalFields.keySet()) {
final String value = optionalFields.get(fieldName);
// check if the value references a pre-defined type and thus requests a special value or
// whether the field name must be added along with the value without any modifications
if(StringUtils.equalsIgnoreCase(value, OPTIONAL_FIELD_TYPE_TIMESTAMP))
jsonObject.put(fieldName, dateFormatter.format(new Date()));
else if(StringUtils.equalsIgnoreCase(value, OPTIONAL_FIELD_TYPE_TOTAL_MESSAGE_COUNT))
jsonObject.put(fieldName, totalMessageCount);
else
jsonObject.put(fieldName, value);
}
}
return jsonObject;
}
示例4: createReactProps
import org.apache.sling.commons.json.JSONObject; //导入依赖的package包/类
private JSONObject createReactProps(ReactComponentConfig config, SlingHttpServletRequest request, Resource resource) {
try {
int depth = config.getDepth();
JSONObject resourceAsJson = JsonObjectCreator.create(resource, depth);
JSONObject reactProps = new JSONObject();
reactProps.put("resource", resourceAsJson);
reactProps.put("component", config.getComponent());
reactProps.put("resourceType", resource.getResourceType());
// TODO remove depth and provide custom service to get the resource as
// json without spcifying the depth. This makes it possible to privde
// custom loader.
reactProps.put("depth", config.getDepth());
reactProps.put("wcmmode", getWcmMode(request));
reactProps.put("path", resource.getPath());
reactProps.put("root", true);
return reactProps;
} catch (JSONException e) {
throw new TechnicalException("cannot create react props", e);
}
}
示例5: testReportTime_withJSONHavingTimestampValueAtLocationCalcAndPrefixButNoValue
import org.apache.sling.commons.json.JSONObject; //导入依赖的package包/类
/**
* Test case for {@link StatsdExtractedMetricsReporter#reportTime(StatsdMetricConfig, JSONObject)} being provided a json which returns an integer for selected path.
* Value is reported as execution time --> computation (and prefix but no value)
*/
@Test
public void testReportTime_withJSONHavingTimestampValueAtLocationCalcAndPrefixButNoValue() throws Exception {
final StatsDClient client = Mockito.mock(StatsDClient.class);
StatsdExtractedMetricsReporterConfiguration cfg = new StatsdExtractedMetricsReporterConfiguration("host", 8125, "prefix");
cfg.addMetricConfig(new StatsdMetricConfig("path.to.field", StatsdMetricType.TIME, new JsonContentReference(new String[]{"path","field"}, JsonContentType.INTEGER), true));
StatsdExtractedMetricsReporter reporter = new StatsdExtractedMetricsReporter(cfg);
reporter.setStatsdClient(client);
SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
Date now = new Date();
Date expected = f.parse(f.format(now));
reporter.reportTime(new StatsdMetricConfig("path.to.field", new JsonContentReference(new String[]{"prefix"}, JsonContentType.STRING), StatsdMetricType.TIME, new JsonContentReference(new String[]{"key"}, JsonContentType.TIMESTAMP, "yyyyMMdd")), new JSONObject("{\"key\":\""+f.format(now)+"\"}"));
Mockito.verify(client).recordExecutionTimeToNow("path.to.field", expected.getTime());
Mockito.verify(client, Mockito.never()).recordExecutionTime(Mockito.anyString(), Mockito.anyLong());
}
示例6: demoOAuth2Code
import org.apache.sling.commons.json.JSONObject; //导入依赖的package包/类
private void demoOAuth2Code(HttpServletRequest request, HttpServletResponse response) {
String code = request.getParameter("code");
String apiURL = "https://" + WATSON_ANALYTICS_API_URL + WATSON_ANALYTICS_API_BASE_PATH + "/oauth2/v1/token";
HttpPost apiRequest = new HttpPost(apiURL);
apiRequest.addHeader("X-IBM-Client-Id", yourAppKey.getProperty("client_id"));
apiRequest.addHeader("X-IBM-Client-Secret", yourAppKey.getProperty("client_secret"));
try {
String form = "grant_type=authorization_code&code=" + URLEncoder.encode(code, "UTF-8");
apiRequest.setEntity(new StringEntity(form, ContentType.create("application/x-www-form-urlencoded")));
HttpClient httpClient = new DefaultHttpClient();
HttpResponse apiResponse = httpClient.execute( apiRequest );
ByteArrayOutputStream stream = new ByteArrayOutputStream();
apiResponse.getEntity().writeTo( stream );
JSONObject obj = new JSONObject( stream.toString() );
stream.close();
ACCESS_TOKENS = (String)obj.get( "access_token" );
} catch (Exception e) {
System.err.println(e.getLocalizedMessage());
}
String locationURI = "http://" + APPLICATION_URL + ":" + APPLICATION_PORT + "/demo/integration.html";
response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
response.setHeader("Location", locationURI);
}
示例7: processJSON
import org.apache.sling.commons.json.JSONObject; //导入依赖的package包/类
/**
* Steps through {@link Base64ContentDecoderConfiguration field configurations}, reads the referenced value from the {@link JSONObject}
* and attempts to decode {@link Base64} string. If the result is expected to hold a {@link JSONObject} the value is replaced inside the
* original document accordingly. Otherwise the value simply replaces the existing value
* @param jsonObject
* @return
* @throws JSONException
* @throws UnsupportedEncodingException
*/
protected JSONObject processJSON(final JSONObject jsonObject) throws JSONException, UnsupportedEncodingException {
if(jsonObject == null)
return null;
for(final Base64ContentDecoderConfiguration cfg : this.contentReferences) {
final String value = this.jsonUtils.getTextFieldValue(jsonObject, cfg.getJsonRef().getPath(), false);
final String decodedValue = decodeBase64(value, cfg.getNoValuePrefix(), cfg.getEncoding());
if(cfg.isJsonContent())
this.jsonUtils.insertField(jsonObject, cfg.getJsonRef().getPath(), new JSONObject(decodedValue), true);
else
this.jsonUtils.insertField(jsonObject, cfg.getJsonRef().getPath(), decodedValue, true);
}
return jsonObject;
}
示例8: wrapHtml
import org.apache.sling.commons.json.JSONObject; //导入依赖的package包/类
/**
* wrap the rendered react markup with the teaxtarea that contains the
* component's props.
*
* @param path
* @param reactProps
* @param component
* @param renderedHtml
* @param serverRendering
* @return
*/
private String wrapHtml(String path, Resource resource, String renderedHtml, boolean serverRendering, String wcmmode, String cache) {
JSONObject reactProps = new JSONObject();
try {
if (cache != null) {
reactProps.put("cache", new JSONObject(cache));
}
reactProps.put("resourceType", resource.getResourceType());
reactProps.put("path", resource.getPath());
reactProps.put("wcmmode", wcmmode);
} catch (JSONException e) {
throw new TechnicalException("cannot create react props", e);
}
String jsonProps = StringEscapeUtils.escapeHtml4(reactProps.toString());
String allHtml = "<div data-react-server=\"" + String.valueOf(serverRendering) + "\" data-react=\"app\" data-react-id=\"" + path + "_component\">"
+ renderedHtml + "</div>" + "<textarea id=\"" + path + "_component\" style=\"display:none;\">" + jsonProps + "</textarea>";
return allHtml;
}
示例9: testReportTime_withJSONHavingTimestampValueAtLocationCalc
import org.apache.sling.commons.json.JSONObject; //导入依赖的package包/类
/**
* Test case for {@link StatsdExtractedMetricsReporter#reportTime(StatsdMetricConfig, JSONObject)} being provided a json which returns an integer for selected path.
* Value is reported as execution time --> computation
*/
@Test
public void testReportTime_withJSONHavingTimestampValueAtLocationCalc() throws Exception {
final StatsDClient client = Mockito.mock(StatsDClient.class);
StatsdExtractedMetricsReporterConfiguration cfg = new StatsdExtractedMetricsReporterConfiguration("host", 8125, "prefix");
cfg.addMetricConfig(new StatsdMetricConfig("path.to.field", StatsdMetricType.TIME, new JsonContentReference(new String[]{"path","field"}, JsonContentType.INTEGER), true));
StatsdExtractedMetricsReporter reporter = new StatsdExtractedMetricsReporter(cfg);
reporter.setStatsdClient(client);
SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
Date now = new Date();
Date expected = f.parse(f.format(now));
reporter.reportTime(new StatsdMetricConfig("path.to.field", StatsdMetricType.TIME, new JsonContentReference(new String[]{"key"}, JsonContentType.TIMESTAMP, "yyyyMMdd")), new JSONObject("{\"key\":\""+f.format(now)+"\"}"));
Mockito.verify(client).recordExecutionTimeToNow("path.to.field", expected.getTime());
Mockito.verify(client, Mockito.never()).recordExecutionTime(Mockito.anyString(), Mockito.anyLong());
}
示例10: testReportTime_withJSONHavingTimestampValueAtLocationCalcAndPrefix
import org.apache.sling.commons.json.JSONObject; //导入依赖的package包/类
/**
* Test case for {@link StatsdExtractedMetricsReporter#reportTime(StatsdMetricConfig, JSONObject)} being provided a json which returns an integer for selected path.
* Value is reported as execution time --> computation (and prefix)
*/
@Test
public void testReportTime_withJSONHavingTimestampValueAtLocationCalcAndPrefix() throws Exception {
final StatsDClient client = Mockito.mock(StatsDClient.class);
StatsdExtractedMetricsReporterConfiguration cfg = new StatsdExtractedMetricsReporterConfiguration("host", 8125, "prefix");
cfg.addMetricConfig(new StatsdMetricConfig("path.to.field", StatsdMetricType.TIME, new JsonContentReference(new String[]{"path","field"}, JsonContentType.INTEGER), true));
StatsdExtractedMetricsReporter reporter = new StatsdExtractedMetricsReporter(cfg);
reporter.setStatsdClient(client);
SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
Date now = new Date();
Date expected = f.parse(f.format(now));
reporter.reportTime(new StatsdMetricConfig("path.to.field", new JsonContentReference(new String[]{"prefix"}, JsonContentType.STRING), StatsdMetricType.TIME, new JsonContentReference(new String[]{"key"}, JsonContentType.TIMESTAMP, "yyyyMMdd")), new JSONObject("{\"prefix\":\"pref\",\"key\":\""+f.format(now)+"\"}"));
Mockito.verify(client).recordExecutionTimeToNow("pref.path.to.field", expected.getTime());
Mockito.verify(client, Mockito.never()).recordExecutionTime(Mockito.anyString(), Mockito.anyLong());
}
示例11: testExtractAndReport_withValidJSONValidConfig
import org.apache.sling.commons.json.JSONObject; //导入依赖的package包/类
/**
* Test case for {@link StatsdExtractedMetricsReporter#extractAndReport(java.util.List, JSONObject)} being provided valid json and valid config
*/
@Test
public void testExtractAndReport_withValidJSONValidConfig() throws Exception{
final StatsDClient client = Mockito.mock(StatsDClient.class);
StatsdExtractedMetricsReporterConfiguration cfg = new StatsdExtractedMetricsReporterConfiguration("host", 8125, "prefix");
cfg.addMetricConfig(new StatsdMetricConfig("timestampCalc", StatsdMetricType.TIME, new JsonContentReference(new String[]{"timecalc"}, JsonContentType.TIMESTAMP, "yyyyMMdd")));
cfg.addMetricConfig(new StatsdMetricConfig("time", StatsdMetricType.TIME, new JsonContentReference(new String[]{"time"}, JsonContentType.INTEGER)));
cfg.addMetricConfig(new StatsdMetricConfig("gauge", StatsdMetricType.GAUGE, new JsonContentReference(new String[]{"gauge"}, JsonContentType.INTEGER)));
cfg.addMetricConfig(new StatsdMetricConfig("diffCounter", StatsdMetricType.COUNTER, new JsonContentReference(new String[]{"diffCounter"}, JsonContentType.INTEGER), true));
cfg.addMetricConfig(new StatsdMetricConfig("incCounter", StatsdMetricType.COUNTER, new JsonContentReference(new String[]{"incCounter"}, JsonContentType.INTEGER), false));
StatsdExtractedMetricsReporter reporter = new StatsdExtractedMetricsReporter(cfg);
reporter.setStatsdClient(client);
SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
Date now = new Date();
Date expected = f.parse(f.format(now));
reporter.extractAndReport(cfg.getFields(), new JSONObject("{\"timecalc\":\""+f.format(now)+"\", \"time\":123, \"gauge\":987, \"diffCounter\":231}"));
Mockito.verify(client).recordExecutionTimeToNow("timestampCalc", expected.getTime());
Mockito.verify(client).recordExecutionTime("time", Long.valueOf(123));
Mockito.verify(client).gauge("gauge", Long.valueOf(987));
Mockito.verify(client).count("diffCounter", Long.valueOf(231));
Mockito.verify(client).incrementCounter("incCounter");
}
示例12: testAggregate_withTwoDifferentDocumentValidConfigurationGroupingElementOptional
import org.apache.sling.commons.json.JSONObject; //导入依赖的package包/类
/**
* Test case for {@link WindowedJsonContentAggregator#aggregate(JSONObject, AggregatorConfiguration, Map)}
* being called twice with different filled documents and a valid configuration with group-by settings
*/
@Test
public void testAggregate_withTwoDifferentDocumentValidConfigurationGroupingElementOptional() throws Exception {
String content1 = "{\"field1\": {\"field2\":\"test-value\"}, \"field3\":\"test-value-2\"}";
String content2 = "{\"field1\": {\"field2\":\"test-value4\"}, \"field3\":\"test-value-3\"}";
FieldAggregationConfiguration fieldCfg = new FieldAggregationConfiguration("fieldOutput",
new JsonContentReference(new String[]{"field1","field2"}, JsonContentType.STRING, false));
fieldCfg.addAggregationMethod(ContentAggregator.COUNT);
AggregatorConfiguration cfg = new AggregatorConfiguration();
cfg.setOutputElement("output");
cfg.addGroupByField(new JsonContentReference(new String[]{"field1", "field2"}, JsonContentType.STRING, true));
cfg.addGroupByField(new JsonContentReference(new String[]{"field3"}, JsonContentType.STRING, true));
cfg.addFieldAggregation(fieldCfg);
WindowedJsonContentAggregator aggregator = new WindowedJsonContentAggregator("id", cfg);
Map<String, Serializable> result = aggregator.aggregate(new JSONObject(content1), cfg, new HashMap<>());
result = aggregator.aggregate(new JSONObject(content2), cfg, result);
Assert.assertEquals(1, result.get("test-value.test-value-2.fieldOutput."+ContentAggregator.COUNT.name()));
Assert.assertEquals(1, result.get("test-value4.test-value-3.fieldOutput."+ContentAggregator.COUNT.name()));
}
示例13: testAggregate_withTwoDifferentDocumentOneTwiceValidConfigurationGroupingElementOptional
import org.apache.sling.commons.json.JSONObject; //导入依赖的package包/类
/**
* Test case for {@link WindowedJsonContentAggregator#aggregate(JSONObject, AggregatorConfiguration, Map)}
* being called three times with different filled documents (one applied two times) and a valid configuration with group-by settings
*/
@Test
public void testAggregate_withTwoDifferentDocumentOneTwiceValidConfigurationGroupingElementOptional() throws Exception {
String content1 = "{\"field1\": {\"field2\":\"test-value\"}, \"field3\":\"test-value-2\"}";
String content2 = "{\"field1\": {\"field2\":\"test-value4\"}, \"field3\":\"test-value-3\"}";
FieldAggregationConfiguration fieldCfg = new FieldAggregationConfiguration("fieldOutput",
new JsonContentReference(new String[]{"field1","field2"}, JsonContentType.STRING, false));
fieldCfg.addAggregationMethod(ContentAggregator.COUNT);
AggregatorConfiguration cfg = new AggregatorConfiguration();
cfg.setOutputElement("output");
cfg.addGroupByField(new JsonContentReference(new String[]{"field1", "field2"}, JsonContentType.STRING, true));
cfg.addGroupByField(new JsonContentReference(new String[]{"field3"}, JsonContentType.STRING, true));
cfg.addFieldAggregation(fieldCfg);
WindowedJsonContentAggregator aggregator = new WindowedJsonContentAggregator("id", cfg);
Map<String, Serializable> result = aggregator.aggregate(new JSONObject(content1), cfg, new HashMap<>());
result = aggregator.aggregate(new JSONObject(content2), cfg, result);
result = aggregator.aggregate(new JSONObject(content2), cfg, result);
Assert.assertEquals(1, result.get("test-value.test-value-2.fieldOutput."+ContentAggregator.COUNT.name()));
Assert.assertEquals(2, result.get("test-value4.test-value-3.fieldOutput."+ContentAggregator.COUNT.name()));
}
示例14: getJSON
import org.apache.sling.commons.json.JSONObject; //导入依赖的package包/类
public String getJSON() throws JSONException {
JSONObject json = new JSONObject();
JSONArray nodes = new JSONArray();
json.put("nodes", nodes);
List<Integer> operatorIDs = new ArrayList<Integer>(streamGraph.getVertexIDs());
Collections.sort(operatorIDs, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
// put sinks at the back
if (streamGraph.getSinkIDs().contains(o1)) {
return 1;
} else if (streamGraph.getSinkIDs().contains(o2)) {
return -1;
} else {
return o1 - o2;
}
}
});
visit(nodes, operatorIDs, new HashMap<Integer, Integer>());
return json.toString();
}
示例15: testApply_withDocumentThrowingAnExceptionWithRawDataIncluded
import org.apache.sling.commons.json.JSONObject; //导入依赖的package包/类
/**
* Test case for {@link WindowedJsonContentAggregator#apply(TimeWindow, Iterable, org.apache.flink.util.Collector)}
* being provided an iterable holding a document which misses a required field (with raw data included)
*/
@Test
public void testApply_withDocumentThrowingAnExceptionWithRawDataIncluded() throws Exception {
String content = "{\"field1\": {\"field2\":\"test-value\"}}";
FieldAggregationConfiguration fieldCfg = new FieldAggregationConfiguration("fieldOutput",
new JsonContentReference(new String[]{"field1","field2","field3"}, JsonContentType.STRING, true));
fieldCfg.addAggregationMethod(ContentAggregator.COUNT);
AggregatorConfiguration cfg = new AggregatorConfiguration();
cfg.setOutputElement("output");
cfg.setRaw(true);
cfg.addFieldAggregation(fieldCfg);
List<JSONObject> values = new ArrayList<>();
values.add(new JSONObject(content));
List<JSONObject> result = new ArrayList<>();
ListCollector<JSONObject> resultCollector = new ListCollector<>(result);
new WindowedJsonContentAggregator("id", cfg).apply(null,values,resultCollector);
Assert.assertEquals(1, result.size());
JSONObject resultObject = result.get(0);
Assert.assertEquals("{\"output\":{},\"raw\":[{\"field1\":{\"field2\":\"test-value\"}}]}",resultObject.toString());
}