下面列出了java.net.http.HttpRequest.BodyPublishers#com.eclipsesource.json.JsonValue 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Tests the result of the rest api GET when there is a config.
*/
@Test
public void testConfigs() {
setUpConfigData();
final WebTarget wt = target();
final String response = wt.path("network/configuration").request().get(String.class);
final JsonObject result = Json.parse(response).asObject();
Assert.assertThat(result, notNullValue());
Assert.assertThat(result.names(), hasSize(2));
JsonValue devices = result.get("devices");
Assert.assertThat(devices, notNullValue());
JsonValue device1 = devices.asObject().get("device1");
Assert.assertThat(device1, notNullValue());
JsonValue basic = device1.asObject().get("basic");
Assert.assertThat(basic, notNullValue());
checkBasicAttributes(basic);
}
private void decomposeJSONValue(String name, JsonValue val, Map<String, String> map)
{
if (val.isObject())
{
JsonObject obj = val.asObject();
for (String memberName : obj.names())
{
this.decomposeJSONValue(name + "." + memberName, obj.get(memberName), map);
}
} else if (val.isArray())
{
JsonArray arr = val.asArray();
for (int i = 0; i < arr.size(); i++)
{
this.decomposeJSONValue(name + "[" + i + "]", arr.get(i), map);
}
} else
{
map.put(name, val.toString());
}
}
/**
* Gets information about all of the collaborations for this folder.
*
* @return a collection of information about the collaborations for this folder.
*/
public Collection<BoxCollaboration.Info> getCollaborations() {
BoxAPIConnection api = this.getAPI();
URL url = GET_COLLABORATIONS_URL.build(api.getBaseURL(), this.getID());
BoxAPIRequest request = new BoxAPIRequest(api, url, "GET");
BoxJSONResponse response = (BoxJSONResponse) request.send();
JsonObject responseJSON = JsonObject.readFrom(response.getJSON());
int entriesCount = responseJSON.get("total_count").asInt();
Collection<BoxCollaboration.Info> collaborations = new ArrayList<BoxCollaboration.Info>(entriesCount);
JsonArray entries = responseJSON.get("entries").asArray();
for (JsonValue entry : entries) {
JsonObject entryObject = entry.asObject();
BoxCollaboration collaboration = new BoxCollaboration(api, entryObject.get("id").asString());
BoxCollaboration.Info info = collaboration.new Info(entryObject);
collaborations.add(info);
}
return collaborations;
}
private static Long readObservationId(String con) {
JsonValue result;
try {
result = Json.parse(con);
} catch (ParseException e) {
LOG.info("malformed json");
return null;
}
if (!result.isObject()) {
LOG.info("malformed json");
return null;
}
JsonObject resultObj = result.asObject();
String status = resultObj.getString("status", null);
if (status == null || !status.equalsIgnoreCase("SUCCESS")) {
LOG.info("response error: {}", resultObj);
return null;
}
long id = resultObj.getLong("id", -1);
if (id == -1) {
return null;
}
return id;
}
private static JsonValue convertPrimitive(Object value) {
JsonValue jsonValue;
if (value instanceof Integer) {
jsonValue = Json.value((Integer) value);
} else if (value instanceof Long) {
jsonValue = Json.value((Long) value);
} else if (value instanceof Float) {
jsonValue = Json.value((Float) value);
} else if (value instanceof Double) {
jsonValue = Json.value((Double) value);
} else if (value instanceof Boolean) {
jsonValue = Json.value((Boolean) value);
} else if (value instanceof Byte) {
jsonValue = Json.value((Byte) value);
} else if (value instanceof Short) {
jsonValue = Json.value((Short) value);
} else if (value instanceof String) {
jsonValue = Json.value((String) value);
} else {
jsonValue = null;
}
return jsonValue;
}
private static void getSavedTags(PythonDetails pythonDetails,
EditablePythonAbiContainer editablePythonAbiContainer,
File supportedAbiFormatsFile) throws IOException {
JsonArray array = Json.parse(new FileReader(supportedAbiFormatsFile)).asArray();
for (JsonValue jsonValue : array) {
JsonObject entry = jsonValue.asObject();
String pythonTag = entry.get("pythonTag").asString();
String abiTag = entry.get("abiTag").asString();
String platformTag = entry.get("platformTag").asString();
AbiDetails triple = new AbiDetails(pythonDetails.getVirtualEnvInterpreter(),
pythonTag, abiTag, platformTag);
editablePythonAbiContainer.addSupportedAbi(triple);
}
}
public static void loadGUI() {
try {
JsonObject settings = JsonObject.readFrom(new FileReader(JDA.settingsFile));
for (JDADecompiler decompiler : Decompilers.getAllDecompilers())
decompiler.getSettings().loadFrom(settings);
for (Setting setting : Settings.ALL_SETTINGS) {
String nodeId = setting.node;
JsonValue nodeValue = settings.get(nodeId);
if (nodeValue != null) {
if ((nodeValue = nodeValue.asObject().get(setting.name)) != null)
setting.set(nodeValue.asString());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void setupManufacturers(boolean verbose) throws IOException {
ArrayList<String> newManufacturers = new ArrayList<>(1024);
String path = String.format(urlFormatBrands, 1);
for (int index = 1; index <= 100 && !path.isEmpty(); index++) {
JsonObject o = getJsonObject(path, verbose);
JsonValue meta = o.get("meta");
JsonObject metaObject = meta.asObject();
path = metaObject.get("next").asString();
if (verbose)
System.err.println("Read page " + metaObject.get("page").asInt());
JsonArray objects = o.get("objects").asArray();
for (JsonValue val : objects) {
JsonObject obj = val.asObject();
String brand = obj.get("brand").asString();
if (!newManufacturers.contains(brand))
newManufacturers.add(brand);
}
}
manufacturers = newManufacturers;
}
@Override
public void getContactRequests(boolean fromWebsocket) throws ConnectionException {
JsonArray array = Endpoints.AUTH_REQUESTS_URL
.open(this)
.as(JsonArray.class)
.expect(200, "While loading authorization requests")
.get();
for (JsonValue contactRequest : array) {
JsonObject contactRequestObj = contactRequest.asObject();
try {
ContactRequestImpl request = new ContactRequestImpl(contactRequestObj.get("event_time").asString(),
contactRequestObj.get("sender").asString(),
contactRequestObj.get("greeting").asString(), this);
if (this.allContactRequests.add(request)) {
if (fromWebsocket) {
ContactRequestEvent event = new ContactRequestEvent(request);
getEventDispatcher().callEvent(event);
}
}
} catch (java.text.ParseException e) {
getLogger().log(Level.WARNING, "Could not parse date for contact request", e);
}
}
if (fromWebsocket) this.updateContactList();
}
@Override
public void updateContactList() throws ConnectionException {
JsonObject obj = Endpoints.GET_ALL_CONTACTS
.open(this, getUsername(), "notification")
.as(JsonObject.class)
.expect(200, "While loading contacts")
.get();
for (JsonValue value : obj.get("contacts").asArray()) {
if (value.asObject().get("suggested") == null || !value.asObject().get("suggested").asBoolean()) {
String id = value.asObject().get("id").asString();
ContactImpl impl = (ContactImpl) allContacts.get(id);
if (impl == null) impl = (ContactImpl) loadContact(id);
impl.update(value.asObject());
}
}
}
private static JsonValue urlGetJson(String getUrl) {
try {
String proxyAddress = Configuration.updateProxyAddress.get();
URL url = new URL(getUrl);
URLConnection uc;
if (proxyAddress != null && !proxyAddress.isEmpty()) {
int port = 8080;
if (proxyAddress.contains(":")) {
String[] parts = proxyAddress.split(":");
port = Integer.parseInt(parts[1]);
proxyAddress = parts[0];
}
uc = url.openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAddress, port)));
} else {
uc = url.openConnection();
}
uc.setRequestProperty("User-Agent", ApplicationInfo.shortApplicationVerName);
uc.connect();
JsonValue value = Json.parse(new InputStreamReader(uc.getInputStream()));
return value;
} catch (IOException | NumberFormatException ex) {
return null;
}
}
/**
* Gets information about all of the group memberships for this user.
* Does not support paging.
*
* <p>Note: This method is only available to enterprise admins.</p>
*
* @return a collection of information about the group memberships for this user.
*/
public Collection<BoxGroupMembership.Info> getMemberships() {
BoxAPIConnection api = this.getAPI();
URL url = USER_MEMBERSHIPS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());
BoxAPIRequest request = new BoxAPIRequest(api, url, "GET");
BoxJSONResponse response = (BoxJSONResponse) request.send();
JsonObject responseJSON = JsonObject.readFrom(response.getJSON());
int entriesCount = responseJSON.get("total_count").asInt();
Collection<BoxGroupMembership.Info> memberships = new ArrayList<BoxGroupMembership.Info>(entriesCount);
JsonArray entries = responseJSON.get("entries").asArray();
for (JsonValue entry : entries) {
JsonObject entryObject = entry.asObject();
BoxGroupMembership membership = new BoxGroupMembership(api, entryObject.get("id").asString());
BoxGroupMembership.Info info = membership.new Info(entryObject);
memberships.add(info);
}
return memberships;
}
/**
* Locks a file.
*
* @param expiresAt expiration date of the lock.
* @param isDownloadPrevented is downloading of file prevented when locked.
* @return the lock returned from the server.
*/
public BoxLock lock(Date expiresAt, boolean isDownloadPrevented) {
String queryString = new QueryStringBuilder().appendParam("fields", "lock").toString();
URL url = FILE_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID());
BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "PUT");
JsonObject lockConfig = new JsonObject();
lockConfig.add("type", "lock");
if (expiresAt != null) {
lockConfig.add("expires_at", BoxDateFormat.format(expiresAt));
}
lockConfig.add("is_download_prevented", isDownloadPrevented);
JsonObject requestJSON = new JsonObject();
requestJSON.add("lock", lockConfig);
request.setBody(requestJSON.toString());
BoxJSONResponse response = (BoxJSONResponse) request.send();
JsonObject responseJSON = JsonObject.readFrom(response.getJSON());
JsonValue lockValue = responseJSON.get("lock");
JsonObject lockJSON = JsonObject.readFrom(lockValue.toString());
return new BoxLock(lockJSON, this.getAPI());
}
/**
* Retrieves a list of Terms of Service that belong to your Enterprise as an Iterable.
* @param api api the API connection to be used by the resource.
* @param termsOfServiceType the type of terms of service to be retrieved. Can be set to "managed" or "external"
* @return the Iterable of Terms of Service in an Enterprise that match the filter parameters.
*/
public static List<BoxTermsOfService.Info> getAllTermsOfServices(final BoxAPIConnection api,
BoxTermsOfService.TermsOfServiceType
termsOfServiceType) {
QueryStringBuilder builder = new QueryStringBuilder();
if (termsOfServiceType != null) {
builder.appendParam("tos_type", termsOfServiceType.toString());
}
URL url = ALL_TERMS_OF_SERVICES_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString());
BoxAPIRequest request = new BoxAPIRequest(api, url, "GET");
BoxJSONResponse response = (BoxJSONResponse) request.send();
JsonObject responseJSON = JsonObject.readFrom(response.getJSON());
int totalCount = responseJSON.get("total_count").asInt();
List<BoxTermsOfService.Info> termsOfServices = new ArrayList<BoxTermsOfService.Info>(totalCount);
JsonArray entries = responseJSON.get("entries").asArray();
for (JsonValue value : entries) {
JsonObject termsOfServiceJSON = value.asObject();
BoxTermsOfService termsOfService = new BoxTermsOfService(api, termsOfServiceJSON.get("id").asString());
BoxTermsOfService.Info info = termsOfService.new Info(termsOfServiceJSON);
termsOfServices.add(info);
}
return termsOfServices;
}
private static int getInt(JsonObject root, String name) throws IOException {
JsonValue jsv = root.get(name);
if (jsv.isNull()) {
throw new IOException(String.format("No %s value present in configuration file", name));
}
if (!jsv.isNumber()) {
throw new IOException(String.format("Invalid value for %s, expected integer", name));
}
return jsv.asInt();
}
private JsonValue getRequiredAttr(final JsonObject json, String name) {
final JsonValue jsonValue = json.get(name);
if (jsonValue == null) {
throw new IllegalStateException("Failed to locate '" + name + "' attribute in the JSON descriptor");
}
return jsonValue;
}
@Override
public void validate(JsonValue value) {
super.validate(value);
int intValue = value.asInt();
if (intValue < minValue) {
throw new IllegalArgumentException(value + " is below the allowed minimum of " + minValue);
}
if (intValue > maxValue) {
throw new IllegalArgumentException(value + " is above the allowed maximum of " + maxValue);
}
}
private List<BoxTaskAssignment.Info> parseTaskAssignmentCollection(JsonObject jsonObject) {
int count = jsonObject.get("total_count").asInt();
List<BoxTaskAssignment.Info> taskAssignmentCollection = new ArrayList<BoxTaskAssignment.Info>(count);
JsonArray entries = jsonObject.get("entries").asArray();
for (JsonValue value : entries) {
JsonObject entry = value.asObject();
String id = entry.get("id").asString();
BoxTaskAssignment assignment = new BoxTaskAssignment(getAPI(), id);
taskAssignmentCollection.add(assignment.new Info(entry));
}
return taskAssignmentCollection;
}
private EnumSet<Permission> parsePermissions(JsonObject jsonObject) {
EnumSet<Permission> permissions = EnumSet.noneOf(Permission.class);
for (JsonObject.Member member : jsonObject) {
JsonValue value = member.getValue();
if (value.isNull() || !value.asBoolean()) {
continue;
}
String memberName = member.getName();
if (memberName.equals("can_download")) {
permissions.add(Permission.CAN_DOWNLOAD);
} else if (memberName.equals("can_upload")) {
permissions.add(Permission.CAN_UPLOAD);
} else if (memberName.equals("can_rename")) {
permissions.add(Permission.CAN_RENAME);
} else if (memberName.equals("can_delete")) {
permissions.add(Permission.CAN_DELETE);
} else if (memberName.equals("can_share")) {
permissions.add(Permission.CAN_SHARE);
} else if (memberName.equals("can_invite_collaborator")) {
permissions.add(Permission.CAN_INVITE_COLLABORATOR);
} else if (memberName.equals("can_set_share_access")) {
permissions.add(Permission.CAN_SET_SHARE_ACCESS);
}
}
return permissions;
}
/**
* Retrieves a list of User Status for Terms of Service as an Iterable.
* @param api the API connection to be used by the resource.
* @param termsOfServiceID the ID of the terms of service.
* @param userID the ID of the user to retrieve terms of service for.
* @return the Iterable of User Status for Terms of Service.
*/
public static List<BoxTermsOfServiceUserStatus.Info> getInfo(final BoxAPIConnection api,
String termsOfServiceID, String userID) {
QueryStringBuilder builder = new QueryStringBuilder();
builder.appendParam("tos_id", termsOfServiceID);
if (userID != null) {
builder.appendParam("user_id", userID);
}
URL url = ALL_TERMS_OF_SERVICE_USER_STATUSES_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString());
BoxAPIRequest request = new BoxAPIRequest(api, url, "GET");
BoxJSONResponse response = (BoxJSONResponse) request.send();
JsonObject responseJSON = JsonObject.readFrom(response.getJSON());
int totalCount = responseJSON.get("total_count").asInt();
List<BoxTermsOfServiceUserStatus.Info> termsOfServiceUserStatuses = new
ArrayList<BoxTermsOfServiceUserStatus.Info>(totalCount);
JsonArray entries = responseJSON.get("entries").asArray();
for (JsonValue value : entries) {
JsonObject termsOfServiceUserStatusJSON = value.asObject();
BoxTermsOfServiceUserStatus termsOfServiceUserStatus = new
BoxTermsOfServiceUserStatus(api, termsOfServiceUserStatusJSON.get("id").asString());
BoxTermsOfServiceUserStatus.Info info = termsOfServiceUserStatus.new Info(termsOfServiceUserStatusJSON);
termsOfServiceUserStatuses.add(info);
}
return termsOfServiceUserStatuses;
}
@Override
public void validate(JsonValue value) {
super.validate(value);
try {
value.asInt();
} catch (NumberFormatException exception) {
throw new IllegalArgumentException(value + " is not an integer.");
}
}
public static Double getDouble(JsonValue value, String name) {
JsonValue result = ((JsonObject) value).get(name);
if (result == null || result.isNull()) {
return null;
}
return result.asDouble();
}
@Override
void parseJSONMember(JsonObject.Member member) {
super.parseJSONMember(member);
String memberName = member.getName();
JsonValue value = member.getValue();
try {
if (memberName.equals("item")) {
JsonObject itemJSON = value.asObject();
String itemID = itemJSON.get("id").asString();
BoxFile file = new BoxFile(getAPI(), itemID);
this.item = file.new Info(itemJSON);
} else if (memberName.equals("due_at")) {
this.dueAt = BoxDateFormat.parse(value.asString());
} else if (memberName.equals("action")) {
this.action = value.asString();
} else if (memberName.equals("completion_rule")) {
this.completionRule = value.asString();
} else if (memberName.equals("message")) {
this.message = value.asString();
} else if (memberName.equals("task_assignment_collection")) {
this.taskAssignments = this.parseTaskAssignmentCollection(value.asObject());
} else if (memberName.equals("is_completed")) {
this.completed = value.asBoolean();
} else if (memberName.equals("created_by")) {
JsonObject userJSON = value.asObject();
String userID = userJSON.get("id").asString();
BoxUser user = new BoxUser(getAPI(), userID);
this.createdBy = user.new Info(userJSON);
} else if (memberName.equals("created_at")) {
this.createdAt = BoxDateFormat.parse(value.asString());
}
} catch (Exception e) {
throw new BoxDeserializationException(memberName, value.toString(), e);
}
}
/**
* @deprecated As of 2.39.0, BatchAPI Request will no longer be supported.
*
* Parses btch api response to create a list of BoxAPIResponse objects.
* @param batchResponse response of a batch api request
* @return list of BoxAPIResponses
*/
@Deprecated
protected List<BoxAPIResponse> parseResponse(BoxJSONResponse batchResponse) {
JsonObject responseJSON = JsonObject.readFrom(batchResponse.getJSON());
List<BoxAPIResponse> responses = new ArrayList<BoxAPIResponse>();
Iterator<JsonValue> responseIterator = responseJSON.get("responses").asArray().iterator();
while (responseIterator.hasNext()) {
JsonObject jsonResponse = responseIterator.next().asObject();
BoxAPIResponse response = null;
//Gather headers
Map<String, String> responseHeaders = new HashMap<String, String>();
if (jsonResponse.get("headers") != null) {
JsonObject batchResponseHeadersObject = jsonResponse.get("headers").asObject();
for (JsonObject.Member member : batchResponseHeadersObject) {
String headerName = member.getName();
String headerValue = member.getValue().asString();
responseHeaders.put(headerName, headerValue);
}
}
// Construct a BoxAPIResponse when response is null, or a BoxJSONResponse when there's a response
// (not anticipating any other response as per current APIs.
// Ideally we should do it based on response header)
if (jsonResponse.get("response") == null || jsonResponse.get("response").isNull()) {
response =
new BoxAPIResponse(jsonResponse.get("status").asInt(), responseHeaders);
} else {
response =
new BoxJSONResponse(jsonResponse.get("status").asInt(), responseHeaders,
jsonResponse.get("response").asObject());
}
responses.add(response);
}
return responses;
}
@Override
protected void parseJSONMember(JsonObject.Member member) {
super.parseJSONMember(member);
String memberName = member.getName();
JsonValue value = member.getValue();
try {
if (memberName.equals("owner_enterprise")) {
JsonObject jsonObject = value.asObject();
this.ownerEnterprise = new BoxEnterprise(jsonObject);
} else if (memberName.equals("parent")) {
JsonObject parentJSON = value.asObject();
if (this.parent == null) {
String parentID = parentJSON.get("id").asString();
BoxFolder folder = new BoxFolder(getAPI(), parentID);
this.parent = folder.new Info(parentJSON);
} else {
this.parent.update(parentJSON);
}
} else if (memberName.equals("scope")) {
this.scope = value.asString();
} else if (memberName.equals("templateKey")) {
this.templateKey = value.asString();
}
} catch (Exception e) {
throw new BoxDeserializationException(memberName, value.toString(), e);
}
}
@Override
public void validate(JsonValue value) {
super.validate(value);
try {
DungeonTimeParser.parseDuration(value.asString());
} catch (IllegalArgumentException invalidValue) {
throw new IllegalArgumentException(value + " is not a valid Dungeon period.");
}
}
private List<BoxFileUploadSessionPart> getParts(JsonArray partsArray) {
List<BoxFileUploadSessionPart> parts = new ArrayList<BoxFileUploadSessionPart>();
for (JsonValue value: partsArray) {
BoxFileUploadSessionPart part = new BoxFileUploadSessionPart((JsonObject) value);
parts.add(part);
}
return parts;
}
@Override
public GherkinDialect getDialect(String language, Location location) {
JsonValue languageObject = DIALECTS.get(language);
if (languageObject == null) {
throw new ParserException.NoSuchLanguageException(language, location);
}
return new GherkinDialect(language, languageObject.asObject());
}
@Override
public void validate(JsonValue value) {
super.validate(value);
if (!StringUtils.isAllUpperCase(value.asString())) {
throw new IllegalArgumentException(value + " is not uppercase.");
}
}
@Listener
public void onSaveMapRequest(SaveMapEvent save) {
JsonValue value = Mappings.INSTANCE.toMapping();
try {
Path path = save.getDestination().toPath();
byte[] content = value.toString(WriterConfig.PRETTY_PRINT).getBytes(StandardCharsets.UTF_8);
Files.write(path, content, StandardOpenOption.CREATE);
} catch (Exception e) {
e.printStackTrace();
}
}