本文整理汇总了Java中org.apache.sling.commons.json.JSONException类的典型用法代码示例。如果您正苦于以下问题:Java JSONException类的具体用法?Java JSONException怎么用?Java JSONException使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
JSONException类属于org.apache.sling.commons.json包,在下文中一共展示了JSONException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: respStacks
import org.apache.sling.commons.json.JSONException; //导入依赖的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.JSONException; //导入依赖的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: doDeactivate
import org.apache.sling.commons.json.JSONException; //导入依赖的package包/类
private ReplicationResult doDeactivate(TransportContext ctx, ReplicationTransaction tx, RestClient restClient) throws ReplicationException, JSONException, IOException {
ReplicationLog log = tx.getLog();
ObjectMapper mapper = new ObjectMapper();
IndexEntry content = mapper.readValue(tx.getContent().getInputStream(), IndexEntry.class);
Response deleteResponse = restClient.performRequest(
"DELETE",
"/" + content.getIndex() + "/" + content.getType() + "/" + DigestUtils.md5Hex(content.getPath()),
Collections.<String, String>emptyMap());
LOG.debug(deleteResponse.toString());
log.info(getClass().getSimpleName() + ": Delete Call returned " + deleteResponse.getStatusLine().getStatusCode() + ": " + deleteResponse.getStatusLine().getReasonPhrase());
if (deleteResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED || deleteResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return ReplicationResult.OK;
}
LOG.error("Could not delete " + content.getType() + " at " + content.getPath());
return new ReplicationResult(false, 0, "Replication failed");
}
示例4: doActivate
import org.apache.sling.commons.json.JSONException; //导入依赖的package包/类
/**
* Perform the replication. All logic is covered in {@link ElasticSearchIndexContentBuilder} so we only need to transmit the JSON to ElasticSearch
*
* @param ctx
* @param tx
* @param restClient
* @return
* @throws ReplicationException
*/
private ReplicationResult doActivate(TransportContext ctx, ReplicationTransaction tx, RestClient restClient) throws ReplicationException, JSONException, IOException {
ReplicationLog log = tx.getLog();
ObjectMapper mapper = new ObjectMapper();
IndexEntry content = mapper.readValue(tx.getContent().getInputStream(), IndexEntry.class);
if (content != null) {
log.info(getClass().getSimpleName() + ": Indexing " + content.getPath());
String contentString = mapper.writeValueAsString(content.getContent());
log.debug(getClass().getSimpleName() + ": Index-Content: " + contentString);
LOG.debug("Index-Content: " + contentString);
HttpEntity entity = new NStringEntity(contentString, "UTF-8");
Response indexResponse = restClient.performRequest(
"PUT",
"/" + content.getIndex() + "/" + content.getType() + "/" + DigestUtils.md5Hex(content.getPath()),
Collections.<String, String>emptyMap(),
entity);
LOG.debug(indexResponse.toString());
log.info(getClass().getSimpleName() + ": " + indexResponse.getStatusLine().getStatusCode() + ": " + indexResponse.getStatusLine().getReasonPhrase());
if (indexResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED || indexResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return ReplicationResult.OK;
}
}
LOG.error("Could not replicate");
return new ReplicationResult(false, 0, "Replication failed");
}
示例5: generateResponse
import org.apache.sling.commons.json.JSONException; //导入依赖的package包/类
/**
* Creates a JSON representation of the given HealthCheckExecutionResult list.
* @param executionResults
* @param resultJson
* @return
* @throws JSONException
*/
private static JSONObject generateResponse(List<HealthCheckExecutionResult> executionResults,
JSONObject resultJson) throws JSONException {
JSONArray resultsJsonArr = new JSONArray();
resultJson.put("results", resultsJsonArr);
for (HealthCheckExecutionResult healthCheckResult : executionResults) {
JSONObject result = new JSONObject();
result.put("name", healthCheckResult.getHealthCheckMetadata() != null ?
healthCheckResult.getHealthCheckMetadata().getName() : "");
result.put("status", healthCheckResult.getHealthCheckResult().getStatus());
result.put("timeMs", healthCheckResult.getElapsedTimeInMs());
resultsJsonArr.put(result);
}
return resultJson;
}
示例6: project
import org.apache.sling.commons.json.JSONException; //导入依赖的package包/类
/**
* Reads selected content from provided {@link JSONObject} and inserts it into a newly created
* {@link JSONObject} instance at configuration locations
* @param json
* @return
* @throws IllegalArgumentException
* @throws NoSuchElementException
* @throws JSONException
*/
protected JSONObject project(final JSONObject json) throws IllegalArgumentException, NoSuchElementException, JSONException {
// prepare result object as new and independent instance to avoid any dirty remains inside the return value
JSONObject result = new JSONObject();
// step through the configuration, read content from referenced location and write it to selected destination
for(final ProjectionMapperConfiguration c : this.configuration) {
Object value = null;
try {
value = this.jsonUtils.getFieldValue(json, c.getProjectField().getPath(), c.getProjectField().isRequired());
} catch(Exception e) {
// if the field value is required return an empty object and interrupt the projection
if(c.getProjectField().isRequired())
return new JSONObject();
// ignore
}
this.jsonUtils.insertField(result, c.getDestinationPath(), (value != null ? value : ""));
}
return result;
}
示例7: getFieldValue
import org.apache.sling.commons.json.JSONException; //导入依赖的package包/类
/**
* Returns the value referenced by the given path from the provided {@link JSONObject}. The result depends on the {@link JsonContentType}. All
* provided input must be checked for not being null and holding valid values before calling this method.
* @param jsonObject
* The {@link JSONObject} to retrieve the value from
* @param path
* The path which points towards the value
* @param contentType
* The expected {@link JsonContentType}
* @param formatString
* Optional format string required to parse out date / time values
* @return
* The referenced value
* @throws JSONException
* Thrown in case anything fails during JSON content extraction
* @throws ParseException
* @throws NoSuchElementException
* @throws IllegalArgumentException
*/
protected Serializable getFieldValue(final JSONObject jsonObject, final String[] path, final JsonContentType contentType, final String formatString) throws JSONException, IllegalArgumentException, NoSuchElementException, ParseException {
if(contentType == null)
throw new IllegalArgumentException("Required content type information missing");
switch(contentType) {
case BOOLEAN: {
return this.jsonUtils.getBooleanFieldValue(jsonObject, path);
}
case DOUBLE: {
return this.jsonUtils.getDoubleFieldValue(jsonObject, path);
}
case INTEGER: {
return this.jsonUtils.getIntegerFieldValue(jsonObject, path);
}
case TIMESTAMP: {
return this.jsonUtils.getDateTimeFieldValue(jsonObject, path, formatString);
}
default: {
return this.jsonUtils.getTextFieldValue(jsonObject, path);
}
}
}
示例8: addOptionalFields
import org.apache.sling.commons.json.JSONException; //导入依赖的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;
}
示例9: processJSON
import org.apache.sling.commons.json.JSONException; //导入依赖的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;
}
示例10: testIntegration_withWorkingExample
import org.apache.sling.commons.json.JSONException; //导入依赖的package包/类
/**
* Test case to show the integration of {@link MatchJSONContent} with {@link StreamTestBase}
* of flink-spector
*/
@Test
public void testIntegration_withWorkingExample() throws JSONException {
DataStream<JSONObject> jsonStream =
createTestStreamWith(new JSONObject("{\"key1\":123}"))
.emit(new JSONObject("{\"key2\":\"test\"}"))
.emit(new JSONObject("{\"key3\":{\"key4\":0.122}}"))
.close();
OutputMatcher<JSONObject> matcher =
new MatchJSONContent()
.assertInteger("key1", Matchers.is(123))
.assertString("key2", Matchers.isIn(new String[]{"test","test1"}))
.assertDouble("key3.key4", Matchers.greaterThan(0.12)).atLeastNOfThem(1).onAnyRecord();
assertStream(jsonStream, matcher);
}
示例11: createReactProps
import org.apache.sling.commons.json.JSONException; //导入依赖的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);
}
}
示例12: getJSON
import org.apache.sling.commons.json.JSONException; //导入依赖的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();
}
示例13: decorateNode
import org.apache.sling.commons.json.JSONException; //导入依赖的package包/类
private void decorateNode(Integer vertexID, JSONObject node) throws JSONException {
StreamNode vertex = streamGraph.getStreamNode(vertexID);
node.put(ID, vertexID);
node.put(TYPE, vertex.getOperatorName());
if (streamGraph.getSourceIDs().contains(vertexID)) {
node.put(PACT, "Data Source");
} else if (streamGraph.getSinkIDs().contains(vertexID)) {
node.put(PACT, "Data Sink");
} else {
node.put(PACT, "Operator");
}
StreamOperator<?> operator = streamGraph.getStreamNode(vertexID).getOperator();
node.put(CONTENTS, vertex.getOperatorName());
node.put(PARALLELISM, streamGraph.getStreamNode(vertexID).getParallelism());
}
示例14: wrapHtml
import org.apache.sling.commons.json.JSONException; //导入依赖的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;
}
示例15: getResource
import org.apache.sling.commons.json.JSONException; //导入依赖的package包/类
/**
* get a resource
*
* @param path
* @param depth
* @return json string
*/
public String getResource(final String path, final Integer depth) {
SlingHttpServletRequest request = (SlingHttpServletRequest) context.getBindings(ScriptContext.ENGINE_SCOPE).get(SlingBindings.REQUEST);
int actualDepth;
try {
if (depth == null || depth < 1) {
actualDepth = -1;
} else {
actualDepth = depth.intValue();
}
Resource resource = request.getResourceResolver().getResource(path);
if (resource == null) {
return null;
}
return JsonObjectCreator.create(resource, actualDepth).toString();
} catch (JSONException e) {
throw new TechnicalException("could not get current resource", e);
}
}