本文整理汇总了Java中org.apache.sling.commons.json.JSONException类的典型用法代码示例。如果您正苦于以下问题:Java JSONException类的具体用法?Java JSONException怎么用?Java JSONException使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
JSONException类属于org.apache.sling.commons.json包,在下文中一共展示了JSONException类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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);
}
}
开发者ID:servicecatalog,项目名称:oscm,代码行数:21,代码来源:MockURLStreamHandler.java
示例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());
}
}
开发者ID:servicecatalog,项目名称:oscm,代码行数:18,代码来源:AbstractStackRequest.java
示例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");
}
开发者ID:deveth0,项目名称:elasticsearch-aem,代码行数:18,代码来源:ElasticSearchTransportHandler.java
示例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");
}
开发者ID:deveth0,项目名称:elasticsearch-aem,代码行数:35,代码来源:ElasticSearchTransportHandler.java
示例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;
}
开发者ID:shinesolutions,项目名称:aem-healthcheck,代码行数:23,代码来源:HealthCheckExecutorServlet.java
示例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;
}
开发者ID:ottogroup,项目名称:flink-operator-library,代码行数:30,代码来源:JsonContentProjectionMapper.java
示例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);
}
}
}
开发者ID:ottogroup,项目名称:flink-operator-library,代码行数:43,代码来源:WindowedJsonContentAggregator.java
示例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;
}
开发者ID:ottogroup,项目名称:flink-operator-library,代码行数:35,代码来源:WindowedJsonContentAggregator.java
示例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;
}
开发者ID:ottogroup,项目名称:flink-operator-library,代码行数:25,代码来源:Base64ContentDecoder.java
示例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);
}
开发者ID:ottogroup,项目名称:flink-operator-library,代码行数:22,代码来源:MatchJSONContentFlinkSpectorTest.java
示例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);
}
}
开发者ID:buildit,项目名称:aem-react-scaffold,代码行数:23,代码来源:ReactScriptEngine.java
示例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();
}
开发者ID:axbaretto,项目名称:flink,代码行数:22,代码来源:JSONGenerator.java
示例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());
}
开发者ID:axbaretto,项目名称:flink,代码行数:22,代码来源:JSONGenerator.java
示例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;
}
开发者ID:sinnerschrader,项目名称:aem-react,代码行数:30,代码来源:ReactScriptEngine.java
示例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);
}
}
开发者ID:sinnerschrader,项目名称:aem-react,代码行数:30,代码来源:Sling.java
示例16: testParsingOfHistoryFile
import org.apache.sling.commons.json.JSONException; //导入依赖的package包/类
@Test
public void testParsingOfHistoryFile () throws IOException, JSONException, URISyntaxException {
File jsonFile = new File(TestJsonParser.class.getClassLoader().getSystemResource("TestJsonParser/history.json").toURI());
Path jsonPath = jsonFile.toPath();
List<String> jsonLines = Files.readAllLines(jsonPath, Charset.forName("UTF-8")) ;
for (String jsonLine : jsonLines ) {
JSONParser parser = new JSONParser(jsonLine);
String author = parser.parse("user.name").getString("retValue");
String text = parser.parse("text").getString("retValue");
String geo = parser.parse("geo").getString("retValue");
Assert.assertNotNull(author);
Assert.assertEquals("Bad mapping of field during json parsing",author,"Laurent T");
Assert.assertNotNull(text);
Assert.assertNotNull(geo);
}
}
开发者ID:LaurentTardif,项目名称:AgileGrenoble2015,代码行数:19,代码来源:TestJsonParser.java
示例17: extractFieldValues
import org.apache.sling.commons.json.JSONException; //导入依赖的package包/类
public List<String> extractFieldValues(String json, String field) {
final List<String> lines = Arrays.asList(json.split("\n")).stream().map(String::trim).collect(Collectors.toList());
StringBuilder buffer = new StringBuilder();
List<String> result = new ArrayList<>();
for (String line : lines) {
buffer.append(line);
if (isJson(buffer.toString())) {
try {
final JSONObject jsonObject = new JSONObject(buffer.toString());
buffer.setLength(0);
Optional.ofNullable(toMap(jsonObject).get(field))
.ifPresent(result::add);
} catch (JSONException ignore) {
//;
}
}
}
return result;
}
开发者ID:otros-systems,项目名称:otroslogviewer,代码行数:20,代码来源:JsonExtractor.java
示例18: format
import org.apache.sling.commons.json.JSONException; //导入依赖的package包/类
@Override
public String format(String message) {
final ArrayList<SubText> jsonFragments = jsonFinder.findJsonFragments(message);
StringBuilder sb = new StringBuilder();
int lastEnd = 0;
for (SubText jsonFragment : jsonFragments) {
sb.append(message.substring(lastEnd, jsonFragment.getStart()));
final String group = jsonFragment.subString(message);
String toAppend = group;
try {
JSONObject o = new JSONObject(group);
final String jsonFormatted = o.toString(2);
toAppend = jsonFormatted;
} catch (JSONException e) {
LOGGER.debug("There is no need to format {}", group);
}
if (!sb.toString().endsWith("\n")) {
sb.append("\n");
}
sb.append(toAppend).append("\n");
lastEnd = jsonFragment.getEnd();
}
sb.append(message.substring(lastEnd));
return sb.toString().trim();
}
开发者ID:otros-systems,项目名称:otroslogviewer,代码行数:26,代码来源:JsonMessageFormatter.java
示例19: sendResponse
import org.apache.sling.commons.json.JSONException; //导入依赖的package包/类
/**
* Send the JSON response.
*
* @param writer The PrintWriter.
* @param header The header to send.
* @param message The message to send.
* @param data The data, probably JSON string
*/
protected void sendResponse(final PrintWriter writer, final String header, final String message, final String data) {
try {
JSONObject json = new JSONObject();
json.put("header", header);
json.put("message", message);
if (StringUtils.isNotBlank(data)) {
json.put("data", data);
}
writer.write(json.toString());
} catch (JSONException e) {
LOGGER.error("Could not write JSON", e);
if (StringUtils.isNotBlank(data)) {
writer.write(String.format("{\"header\" : \"%s\", \"message\" : \"%s\", \"data\" : \"%s\"}", header, message, data));
} else {
writer.write(String.format("{\"header\" : \"%s\", \"message\" : \"%s\"}", header, message));
}
}
}
开发者ID:nateyolles,项目名称:publick-sling-blog,代码行数:31,代码来源:AdminServlet.java
示例20: write
import org.apache.sling.commons.json.JSONException; //导入依赖的package包/类
@Override
public final void write(Hit hit, JSONWriter jsonWriter, Query query) throws RepositoryException, JSONException {
// This example assume the "hit" represents a [cq:Page] node (and not the [cq:Page]/jcr:content node)
// The Resource that represents a Query "hit" (result); This can used to access other related resources in the JCR.
final Resource resource = hit.getResource();
// The Hit object contains the ValueMap representing the "hit" resource.
// This can be used to quickly get properties/relative properties from the hit to expose via the HitWriter.
final ValueMap properties = hit.getProperties();
// Write simple values like the node's path to the JSON result object
jsonWriter.key("path").value(resource.getPath());
// Write resource properties from the hit result node (or relative nodes) to the JSON result object
// You have full control over the names/values of the JSON key/value pairs returned.
// These do not have to match node names
jsonWriter.key("key-to-use-in-json").value(properties.get("jcr:content/jcr:title", "")
+ "(pulled from jcr:content node)");
// Custom logic can be used to transform and/or retrieve data to be added to the resulting JSON object
// Note: Keep this logic as light as possible. Complex logic can introduce performance issues that are
// less visible (Will not appear in JMX Slow Query logs as this logic executes after the actual Query returns).
String complexValue = sampleComplexLogic(resource);
jsonWriter.key("complex").value(complexValue);
}
开发者ID:Adobe-Consulting-Services,项目名称:acs-aem-samples,代码行数:27,代码来源:SampleJsonHitWriter.java
注:本文中的org.apache.sling.commons.json.JSONException类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论