下面列出了java.net.http.HttpResponse.BodyHandlers#com.eclipsesource.json.JsonObject 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Tests a POST operation. This should attempt to
* install the application.
*/
@Test
public void postApplication() {
expect(appService.install(isA(InputStream.class)))
.andReturn(app4)
.once();
replay(appService);
ApplicationCodec codec = new ApplicationCodec();
String app4Json = codec.encode(app4,
new MockCodecContextWithAppService(appService))
.asText();
WebTarget wt = target();
String response = wt.path("applications").request().post(
Entity.entity(app4Json, MediaType.APPLICATION_OCTET_STREAM), String.class);
JsonObject result = Json.parse(response).asObject();
assertThat(result, notNullValue());
assertThat(result, matchesApp(app4));
verify(appService);
}
/**
* Tests the result of a rest api GET for an application.
*/
@Test
public void testGetFlowByAppId() {
setupMockFlows();
expect(mockApplicationService.getId(anyObject())).andReturn(APP_ID).anyTimes();
replay(mockApplicationService);
expect(mockFlowService.getFlowEntriesById(APP_ID)).andReturn(flowEntries).anyTimes();
replay(mockFlowService);
final WebTarget wt = target();
final String response = wt.path("/flows/application/1").request().get(String.class);
final JsonObject result = Json.parse(response).asObject();
assertThat(result, notNullValue());
assertThat(result.names(), hasSize(1));
assertThat(result.names().get(0), is("flows"));
final JsonArray jsonFlows = result.get("flows").asArray();
assertThat(jsonFlows, notNullValue());
assertThat(jsonFlows, hasFlowRule(flow1));
assertThat(jsonFlows, hasFlowRule(flow2));
assertThat(jsonFlows, hasFlowRule(flow3));
assertThat(jsonFlows, hasFlowRule(flow4));
}
public ForecastIO(String LATITUDE, String LONGITUDE, String PROXYNAME, int PROXYPORT, String API_KEY){
if (API_KEY.length()==32) {
this.ForecastIOApiKey = API_KEY;
this.forecast = new JsonObject();
this.currently = new JsonObject();
this.minutely = new JsonObject();
this.hourly = new JsonObject();
this.daily = new JsonObject();
this.flags = new JsonObject();
this.alerts = new JsonArray();
this.timeURL = null;
this.excludeURL = null;
this.extend = false;
this.unitsURL = UNITS_AUTO;
this.langURL = LANG_ENGLISH;
this.proxy_to_use = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXYNAME, PROXYPORT));
getForecast(LATITUDE, LONGITUDE);
}
else {
System.err.println("The API Key doesn't seam to be valid.");
}
}
/**
* Adds a {@link BoxWebHook} to a provided {@link BoxResource}.
*
* @param target
* {@link BoxResource} web resource
* @param address
* {@link URL} where the notification should send to
* @param triggers
* events this {@link BoxWebHook} is interested in
* @return created {@link BoxWebHook}
*
* @see #create(BoxResource, URL, Trigger...)
*/
public static BoxWebHook.Info create(BoxResource target, URL address, Set<BoxWebHook.Trigger> triggers) {
BoxAPIConnection api = target.getAPI();
String type = BoxResource.getResourceType(target.getClass());
validateTriggers(type, triggers);
JsonObject targetJSON = new JsonObject()
.add(JSON_KEY_TARGET_TYPE, type)
.add(JSON_KEY_TARGET_ID, target.getID());
JsonObject requestJSON = new JsonObject()
.add(JSON_KEY_TARGET, targetJSON)
.add(JSON_KEY_ADDRESS, address.toExternalForm())
.add(JSON_KEY_TRIGGERS, toJsonArray(CollectionUtils.map(triggers, TRIGGER_TO_VALUE)));
URL url = WEBHOOKS_URL_TEMPLATE.build(api.getBaseURL());
BoxJSONRequest request = new BoxJSONRequest(api, url, "POST");
request.setBody(requestJSON.toString());
BoxJSONResponse response = (BoxJSONResponse) request.send();
JsonObject responseJSON = JsonObject.readFrom(response.getJSON());
BoxWebHook webHook = new BoxWebHook(api, responseJSON.get(JSON_KEY_ID).asString());
return webHook.new Info(responseJSON);
}
public synchronized WalletBalance getWalletInfo()
throws WalletCallException, IOException, InterruptedException
{
WalletBalance balance = new WalletBalance();
JsonObject objResponse = this.executeCommandAndGetJsonObject("z_gettotalbalance", null);
balance.transparentBalance = Double.valueOf(objResponse.getString("transparent", "-1"));
balance.privateBalance = Double.valueOf(objResponse.getString("private", "-1"));
balance.totalBalance = Double.valueOf(objResponse.getString("total", "-1"));
objResponse = this.executeCommandAndGetJsonObject("z_gettotalbalance", "0");
balance.transparentUnconfirmedBalance = Double.valueOf(objResponse.getString("transparent", "-1"));
balance.privateUnconfirmedBalance = Double.valueOf(objResponse.getString("private", "-1"));
balance.totalUnconfirmedBalance = Double.valueOf(objResponse.getString("total", "-1"));
return balance;
}
/**
* Adds a new email alias to this user's account and confirms it without user interaction.
* This functionality is only available for enterprise admins.
* @param email the email address to add as an alias.
* @param isConfirmed whether or not the email alias should be automatically confirmed.
* @return the newly created email alias.
*/
public EmailAlias addEmailAlias(String email, boolean isConfirmed) {
URL url = EMAIL_ALIASES_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());
BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST");
JsonObject requestJSON = new JsonObject()
.add("email", email);
if (isConfirmed) {
requestJSON.add("is_confirmed", isConfirmed);
}
request.setBody(requestJSON.toString());
BoxJSONResponse response = (BoxJSONResponse) request.send();
JsonObject responseJSON = JsonObject.readFrom(response.getJSON());
return new EmailAlias(responseJSON);
}
/**
*
* @param responseCode HTTP error code of the response
* @param apiException BoxAPIException thrown
* @return true if the response is one that should be retried, otherwise false
*/
public static boolean isResponseRetryable(int responseCode, BoxAPIException apiException) {
String response = apiException.getResponse();
String message = apiException.getMessage();
String errorCode = "";
try {
JsonObject responseBody = JsonObject.readFrom(response);
if (responseBody.get("code") != null) {
errorCode = responseBody.get("code").toString();
}
} catch (Exception e) { }
Boolean isClockSkewError = responseCode == 400
&& errorCode.contains("invalid_grant")
&& message.contains("exp");
return (isClockSkewError || responseCode >= 500 || responseCode == 429);
}
private JsonObject buildRequest(){
JsonObject jo = new JsonObject();//parent object
JsonObject input = new JsonObject();//inut object to hold arrays of tokens and leads
JsonArray leads = new JsonArray();
int i;
for (i = 0; i < leadIds.length; i++) {
leads.add(leadIds[i]);
}
input.add("leads", leads);
//assemble array of tokens and add to input if present
if (tokens != null){
JsonArray tokensArray = new JsonArray();
for (JsonObject jsonObject : tokens) {
tokensArray.add(jsonObject);
}
input.add("tokens", tokensArray);
}
//add input as a member of the parent
jo.add("input", input);
return jo;
}
@Override
protected void parseJSONMember(JsonObject.Member member) {
String memberName = member.getName();
JsonValue value = member.getValue();
if (memberName.equals("entries")) {
JsonArray array = (JsonArray) value;
if (array.size() > 0) {
this.entries = this.getParts(array);
}
} else if (memberName.equals("offset")) {
this.offset = Double.valueOf(value.toString()).intValue();
} else if (memberName.equals("limit")) {
this.limit = Double.valueOf(value.toString()).intValue();
} else if (memberName.equals("total_count")) {
this.totalCount = Double.valueOf(value.toString()).intValue();
}
}
@Override
public ModelAndView doGet(IHTTPSession session) {
ModelAndView result = new ModelAndView();
JsonObject entity = new JsonObject();
entity.add("lat", config.getDouble("locaiton.lat"));
entity.add("lng", config.getDouble("locaiton.lon"));
entity.add("autoUpdate", autoUpdate.isEnabled());
entity.add("ppmType", config.getPpmType().toString());
entity.add("elevationMin", config.getDouble("scheduler.elevation.min"));
entity.add("elevationGuaranteed", config.getDouble("scheduler.elevation.guaranteed"));
entity.add("rotationEnabled", config.getBoolean("rotator.enabled"));
entity.add("rotctrldHostname", config.getProperty("rotator.rotctrld.hostname"));
entity.add("rotctrldPort", config.getInteger("rotator.rotctrld.port"));
entity.add("rotatorTolerance", config.getDouble("rotator.tolerance"));
entity.add("rotatorCycle", config.getInteger("rotator.cycleMillis"));
Integer currentPpm = config.getInteger("ppm.current");
if (currentPpm != null) {
entity.add("ppm", currentPpm);
}
result.setData(entity.toString());
return result;
}
@Override
protected boolean matchesSafely(JsonObject jsonAppId) {
// check id
short jsonId = (short) jsonAppId.get("id").asInt();
if (jsonId != appId.id()) {
reason = "id " + appId.id();
return false;
}
// check name
String jsonName = jsonAppId.get("name").asString();
if (!jsonName.equals(appId.name())) {
reason = "name " + appId.name();
return false;
}
return true;
}
/**
* Restores a trashed folder to a new location with a new name.
* @param folderID the ID of the trashed folder.
* @param newName an optional new name to give the folder. This can be null to use the folder's original name.
* @param newParentID an optional new parent ID for the folder. This can be null to use the folder's original
* parent.
* @return info about the restored folder.
*/
public BoxFolder.Info restoreFolder(String folderID, String newName, String newParentID) {
JsonObject requestJSON = new JsonObject();
if (newName != null) {
requestJSON.add("name", newName);
}
if (newParentID != null) {
JsonObject parent = new JsonObject();
parent.add("id", newParentID);
requestJSON.add("parent", parent);
}
URL url = RESTORE_FOLDER_URL_TEMPLATE.build(this.api.getBaseURL(), folderID);
BoxJSONRequest request = new BoxJSONRequest(this.api, url, "POST");
request.setBody(requestJSON.toString());
BoxJSONResponse response = (BoxJSONResponse) request.send();
JsonObject responseJSON = JsonObject.readFrom(response.getJSON());
BoxFolder restoredFolder = new BoxFolder(this.api, responseJSON.get("id").asString());
return restoredFolder.new Info(responseJSON);
}
@Override
protected boolean matchesSafely(JsonArray json) {
boolean regionFound = false;
for (int jsonRegionIndex = 0; jsonRegionIndex < json.size(); jsonRegionIndex++) {
final JsonObject jsonRegion = json.get(jsonRegionIndex).asObject();
final String regionId = region.id().toString();
final String jsonRegionId = jsonRegion.get("id").asString();
if (jsonRegionId.equals(regionId)) {
regionFound = true;
assertThat(jsonRegion, matchesRegion(region));
}
}
if (!regionFound) {
reason = "Region with id " + region.id().toString() + " not found";
return false;
} else {
return true;
}
}
public AndroidInjections(String jsonData) {
if (jsonData == null || jsonData.isEmpty())
return;
JsonObject root = Json.parse(jsonData).asObject();
fromArray(root.get("appSection"), appSection);
fromArray(root.get("gradleExt"), gradleExt);
fromArray(root.get("gradleBuildDep"), gradleBuildDep);
}
private boolean checkFlowSelector(FlowEntry flow, JsonObject jsonFlow) {
if (flow.selector() != null) {
JsonObject jsonTreatment =
jsonFlow.get(SELECTOR).asObject();
JsonArray jsonCriteria =
jsonTreatment.get(CRITERIA).asArray();
if (flow.selector().criteria().size() != jsonCriteria.size()) {
reason = CRITERIA + " array size of " +
Integer.toString(flow.selector().criteria().size());
return false;
}
for (Criterion criterion : flow.selector().criteria()) {
boolean criterionFound = false;
for (int criterionIndex = 0;
criterionIndex < jsonCriteria.size();
criterionIndex++) {
String jsonType =
jsonCriteria.get(criterionIndex)
.asObject().get(TYPE).asString();
String criterionType = criterion.type().name();
if (jsonType.equals(criterionType)) {
criterionFound = true;
}
}
if (!criterionFound) {
reason = "criterion " + criterion;
return false;
}
}
}
return true;
}
/**
* Sets the shared link password in the request.
*
* @param password new password for the shared link, or null to remove the password.
* @return request with the updated shared link password.
*/
public R setPassword(final String password){
JsonObject jsonObject = getSharedLinkJsonObject();
jsonObject.add(BoxSharedLink.FIELD_PASSWORD, password);
BoxSharedLink sharedLink = new BoxSharedLink(jsonObject);
mBodyMap.put(BoxItem.FIELD_SHARED_LINK, sharedLink);
return (R) this;
}
@Override
public Path getPath(Path workDir) throws IOException {
final Model model = bomArtifact.getPomModel();
final JsonObject json = Json.object();
json.set("bom", Json.object().set("groupId", model.getGroupId()).set("artifactId", model.getArtifactId()).set("version",
model.getVersion()));
String coreVersion = null;
for (Dependency dep : model.getDependencyManagement().getDependencies()) {
if (dep.getArtifactId().equals(ToolsConstants.QUARKUS_CORE_ARTIFACT_ID)
&& dep.getGroupId().equals(ToolsConstants.QUARKUS_CORE_GROUP_ID)) {
coreVersion = dep.getVersion();
}
}
if (coreVersion == null) {
throw new IllegalStateException("Failed to locate " + ToolsConstants.QUARKUS_CORE_GROUP_ID + ":"
+ ToolsConstants.QUARKUS_CORE_ARTIFACT_ID + " among the managed dependencies");
}
json.set("quarkus-core-version", coreVersion);
final Path jsonPath = workDir.resolve(bomArtifact.getArtifactFileName());
try (BufferedWriter writer = Files.newBufferedWriter(jsonPath)) {
json.writeTo(writer);
}
return jsonPath;
}
@Test
@Category(UnitTest.class)
public void testCreateRetentionPolicySucceeds() throws IOException {
String result = "";
final String policyID = "12345";
final String policyName = "Test Retention Policy";
final String policyType = "indefinite";
final String dispositionAction = "remove_retention";
final String createRetentionPolicyURL = "/retention_policies";
final String createdByLogin = "[email protected]";
final String policyStatus = "active";
JsonObject retentionPolicyObject = new JsonObject()
.add("policy_name", policyName)
.add("policy_type", policyType)
.add("dispositon_action", dispositionAction);
result = TestConfig.getFixture("BoxRetentionPolicy/CreateRetentionPolicy201");
WIRE_MOCK_CLASS_RULE.stubFor(WireMock.post(WireMock.urlPathEqualTo(createRetentionPolicyURL))
.willReturn(WireMock.aResponse()
.withHeader("Content-Type", "application/json")
.withBody(result)));
BoxRetentionPolicy.Info policyInfo = BoxRetentionPolicy.createIndefinitePolicy(this.api, policyName);
Assert.assertEquals(policyName, policyInfo.getPolicyName());
Assert.assertEquals(policyType, policyInfo.getPolicyType());
Assert.assertEquals(dispositionAction, policyInfo.getDispositionAction());
Assert.assertEquals(createdByLogin, policyInfo.getCreatedBy().getLogin());
Assert.assertEquals(policyID, policyInfo.getID());
Assert.assertEquals(policyStatus, policyInfo.getStatus());
}
public void addInJsonArray(final String field, final JsonObject value) {
JsonArray jsonArray = getAsJsonArray(field);
jsonArray.add(value);
if (mInternalCache.containsKey(field)) {
mInternalCache.remove(field);
}
}
public void sendIdentityMessageTo(MessagingIdentity contactIdentity)
throws InterruptedException, IOException, WalletCallException
{
// Only a limited set of values is sent over the wire, due to the limit of 330
// characters. // TODO: use protocol versions with larger messages
MessagingIdentity ownIdentity = this.messagingStorage.getOwnIdentity();
JsonObject innerIDObject = new JsonObject();
innerIDObject.set("nickname", ownIdentity.getNickname());
innerIDObject.set("firstname", ownIdentity.getFirstname());
innerIDObject.set("surname", ownIdentity.getSurname());
innerIDObject.set("senderidaddress", ownIdentity.getSenderidaddress());
innerIDObject.set("sendreceiveaddress", ownIdentity.getSendreceiveaddress());
JsonObject outerObject = new JsonObject();
outerObject.set("zenmessagingidentity", innerIDObject);
String identityString = outerObject.toString();
// Check and send the messaging identity as a message
if (identityString.length() <= 330) // Protocol V1 restriction
{
this.sendMessage(identityString, contactIdentity);
} else
{
JOptionPane.showMessageDialog(
this.parentFrame,
"The size of your messaging identity is unfortunately too large to be sent\n" +
"as a message. Your contact will have to import your messaging identity\n" +
"manually from a json file...",
"Messaging identity size is too large!", JOptionPane.ERROR_MESSAGE);
return;
}
}
@Test
@Category(UnitTest.class)
public void testUpdateWebhookInfoSucceeds() throws IOException {
String result = "";
String getResult = "";
final String newAddress = "https://newexample.com";
final String webhookID = "12345";
final String createdByLogin = "[email protected]";
final String webhookURL = "/webhooks/" + webhookID;
JsonObject updateObject = new JsonObject()
.add("triggers", "FILE.UPLOADED")
.add("address", newAddress);
getResult = TestConfig.getFixture("BoxWebhook/GetWebhook200");
result = TestConfig.getFixture("BoxWebhook/UpdateWebhookInfo200");
WIRE_MOCK_CLASS_RULE.stubFor(WireMock.get(WireMock.urlPathEqualTo(webhookURL))
.willReturn(WireMock.aResponse()
.withHeader("Content-Type", "application/json")
.withBody(result)));
WIRE_MOCK_CLASS_RULE.stubFor(WireMock.put(WireMock.urlPathEqualTo(webhookURL))
.withRequestBody(WireMock.equalToJson(updateObject.toString()))
.willReturn(WireMock.aResponse()
.withHeader("Content-Type", "application/json")
.withBody(result)));
BoxWebHook webhook = new BoxWebHook(this.api, webhookID);
BoxWebHook.Info info = webhook.getInfo();
info.addPendingChange("address", newAddress);
info.addPendingChange("triggers", "FILE.UPLOADED");
webhook.updateInfo(info);
Assert.assertEquals(new URL(newAddress), info.getAddress());
Assert.assertEquals(webhookID, info.getID());
Assert.assertEquals(createdByLogin, info.getCreatedBy().getLogin());
}
/**
* @param field
* Field accessor.
* @param type
* Field type.
* @param value
* Field value.
* @param json
* Json to write value to.
*/
default void saveType(FieldWrapper field, Class<?> type, Object value, JsonObject json) {
if (type.equals(ConfKeybinding.Binding.class)) {
JsonArray array = Json.array();
ConfKeybinding.Binding list = field.get();
// Don't write if empty/null
if (list == null || list.isEmpty())
return;
// Write keys
list.forEach(array::add);
json.set(field.key(), array);
}
}
/**
* Uploads a new version of this file, replacing the current version, while reporting the progress to a
* ProgressListener. Note that only users with premium accounts will be able to view and recover previous versions
* of the file.
*
* @param fileContent a stream containing the new file contents.
* @param fileContentSHA1 the SHA1 hash of the file contents. will be sent along in the Content-MD5 header
* @param modified the date that the new version was modified.
* @param name the new name for the file
* @param fileSize the size of the file used for determining the progress of the upload.
* @param listener a listener for monitoring the upload's progress.
* @return the uploaded file version.
*/
public BoxFile.Info uploadNewVersion(InputStream fileContent, String fileContentSHA1, Date modified, String name,
long fileSize, ProgressListener listener) {
URL uploadURL = CONTENT_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL(), this.getID());
BoxMultipartRequest request = new BoxMultipartRequest(getAPI(), uploadURL);
if (fileSize > 0) {
request.setFile(fileContent, "", fileSize);
} else {
request.setFile(fileContent, "");
}
if (fileContentSHA1 != null) {
request.setContentSHA1(fileContentSHA1);
}
JsonObject attributesJSON = new JsonObject();
if (modified != null) {
attributesJSON.add("content_modified_at", BoxDateFormat.format(modified));
}
if (name != null) {
attributesJSON.add("name", name);
}
request.putField("attributes", attributesJSON.toString());
BoxJSONResponse response;
if (listener == null) {
response = (BoxJSONResponse) request.send();
} else {
response = (BoxJSONResponse) request.send(listener);
}
String fileJSON = response.getJsonObject().get("entries").asArray().get(0).toString();
return new BoxFile.Info(fileJSON);
}
private Command parseCommand(JsonObject cmd) {
String name = cmd.getString("ID", null);
String ccf = cmd.getString("CCF", null);
Command command = null;
try {
command = new Command(name, null, ccf);
} catch (GirrException ex) {
Logger.getLogger(CommandFusionImporter.class.getName()).log(Level.SEVERE, null, ex);
}
return command;
}
/**
* Tests the result of the rest api GET of links for a specific device.
*/
@Test
public void testLinksByDevice() {
expect(mockLinkService.getDeviceLinks(isA(DeviceId.class)))
.andReturn(ImmutableSet.of(link2))
.anyTimes();
replay(mockLinkService);
WebTarget wt = target();
String response = wt
.path("links")
.queryParam("device", "src2")
.request()
.get(String.class);
assertThat(response, containsString("{\"links\":["));
JsonObject result = Json.parse(response).asObject();
assertThat(result, notNullValue());
assertThat(result.names(), hasSize(1));
assertThat(result.names().get(0), is("links"));
JsonArray jsonLinks = result.get("links").asArray();
assertThat(jsonLinks, notNullValue());
assertThat(jsonLinks.size(), is(1));
assertThat(jsonLinks, hasLink(link2));
}
public JsonObject buildRequest(){
JsonObject requestBody = new JsonObject();
JsonArray inputArray = new JsonArray();
for (JsonObject jo : roles) {
inputArray.add(jo);
}
requestBody.add("input", inputArray);
return requestBody;
}
@Test
public void testUpdateFolderRequest() throws Exception {
final String expectedRequestUrl = "https://api.box.com/2.0/folders/" + FOLDER_ID ;
BoxApiFolder folderApi = new BoxApiFolder(SessionUtil.newMockBoxSession(mMockContext));
BoxRequestsFolder.UpdateFolder updateRequest = folderApi.getUpdateRequest(FOLDER_ID);
updateRequest.setName("Pictures");
mockSuccessResponseWithJson(SAMPLE_FOLDER_JSON);
BoxFolder boxFolder = updateRequest.send();
Assert.assertEquals(expectedRequestUrl, updateRequest.mRequestUrlString);
Assert.assertEquals(JsonObject.readFrom(SAMPLE_FOLDER_JSON), boxFolder.toJsonObject());
}
public static void main(String[] args){
CreateFolder folder = new CreateFolder();
folder.name = "API Test Folder3";
folder.parent = new JsonObject().add("id", 1031).add("type", "Folder");
String result = folder.postData();
System.out.println(result);
}
public synchronized String[] getWalletPublicAddressesWithUnspentOutputs()
throws WalletCallException, IOException, InterruptedException
{
JsonArray jsonUnspentOutputs = executeCommandAndGetJsonArray("listunspent", "0");
Set<String> addresses = new HashSet<>();
for (int i = 0; i < jsonUnspentOutputs.size(); i++)
{
JsonObject outp = jsonUnspentOutputs.get(i).asObject();
addresses.add(outp.getString("address", "ERROR!"));
}
return addresses.toArray(new String[0]);
}
/**
* Get response as Json Object.
* @return response as JsonObject
*/
public JsonObject getJsonObject() {
if (this.jsonObject != null) {
return this.jsonObject;
} else {
return JsonObject.readFrom(this.getJSON());
}
}