I am trying to store a MessageChannel in a json file, then reading it and sending a message into that channel later
InputStream is = new FileInputStream("OmgIt'sJasonBourne.json");
JSONTokener tokener = new JSONTokener(is);
JSONObject jsonObject = new JSONObject(tokener);
JSONObject jsonAlarm = (JSONObject) jsonObject.get("alarm");
MessageChannel theChannel= (MessageChannel) jsonAlarm.get("channel");
theChannel.sendMessage(jsonAlarm.get("message").toString());
When I try and use this code it gives me:
String cannot be cast to class net.dv8tion.jda.api.entities.channel.middleman.MessageChannel
Is there any way to convert a string into a MessageChannel?
Related
My code is below in brief :
private void havayı_gösterActionPerformed(java.awt.event.ActionEvent evt) {
String WEATHER_URL = "https://api.collectapi.com/weather/getWeather?data.lang=tr&data.city="+şehir_ismi.getText();
//REQUEST GÖNDERME
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = (HttpRequest) HttpRequest.newBuilder()
.GET()
.header("content-type", "application/json")
.header("authorization", "apikey myapikey")
.uri(URI.create(WEATHER_URL))
.build();
//REQUESTE CEVAP
try {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
String content = response.body();
JSONParser parser = new JSONParser();
Object obj;
obj = parser.parse(content);
JSONArray array = new JSONArray();
array.add(obj);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String req_result = gson.toJson(array.get(0));
String text;
text = req_result.replaceAll("\"", "")
.replaceAll("\\{", "")
.replaceAll("result:", "")
.replaceAll("\\},", "")
.replaceAll("\\,", "")
.replaceAll("\\]","")
.replaceAll("\\[","")
.replaceAll("success: true","")
.replaceAll("\\}","");
havayı_listele.setText(text);
I want to show a pretty printed data in the java swing, but attribute "icon" causes unreadability. Also Java does not support svg files. What's the easiest way to get rid of this problem ? Here is my screenshot :
I'm trying to test this method:
private ServiceApiMetadata getConfig(final HttpServletRequest request, final String path)
throws IOException {
final Schema schema;
try (final InputStream inStream = this.getClass().getResourceAsStream(path)) {
final JSONObject origSchema = new JSONObject(new JSONTokener(inStream));
if (isGoldStar()) {
origSchema.getJSONObject("properties")
.getJSONObject("notifications")
.getJSONObject("properties")
.getJSONObject("topic")
.put("pattern", "^[0-9A-Za-z-.]*$");
}
schema = SchemaLoader.load(origSchema);
}
final ServiceApiMetadata config;
try (final BufferedReader reader = request.getReader()) {
final JSONObject json = new JSONObject(new JSONTokener(reader));
schema.validate(json);
config = ServiceApiMetadata.read(json);
} catch (final ValidationException e) {
_logger.debug(e.getMessage());
if (e.getLocation().contains("#/properties/notifications")) {
throw new ServiceApiException(ServiceApiError.MALFORMED_NOTIFICATIONS_ERROR,
ServiceApiErrorMessage.MALFORMED_JSON);
} else {
throw new ServiceApiException(ServiceApiError.MALFORMED_JSON);
}
} catch (final JSONException e) {
_logger.debug(e.getMessage());
throw new ServiceApiException(ServiceApiError.MALFORMED_JSON);
}
return config;
}
As it's private I created the following method in my class:
#TestOnly
protected void runGetConfig(final HttpServletRequest request, final String schemaPath) throws IOException {
final ServiceApiMetadata conf = getConfig(request, schemaPath);
}
When I run my test getConfig() throws an exception. The problem is that when line final JSONObject json = new JSONObject(new JSONTokener(reader)); I get this exception:
HttpException(400,{"status_code":400,"error_code":"MalformedJson","uri":"uri","message":"MalformedJson"},null)
I also see this error in my log:
at 0 [character 1 line 1]
For the HttpServletRequest I'm using org.springframework.mock.web.MockHttpServletRequest.MockHttpServletRequest() as follows:
final MockHttpServletRequest request = new MockHttpServletRequest();
Is it possible this is creating an incorrect reader which in turn means the JSONObject is incorrect and if so how do I resolve this?
Additional info
I added a body to the MockHttpServletRequest but the issue is still the same. I added some logging as can be seen below:
final JSONObject rawSchema = new JSONObject(new JSONTokener(inputStream));
_logger.info("rawSchema: " + rawSchema);
if (isPulsar()) {
rawSchema.getJSONObject("properties")
.getJSONObject("notifications")
.getJSONObject("properties")
.getJSONObject("topic")
.put("pattern", "^[0-9A-Za-z-._:/]*$");
}
schema = SchemaLoader.load(rawSchema);
}
final ServiceApiContainerMetadata conf;
try (final BufferedReader reader = request.getReader()) {
_logger.info("reader: " + reader);
_logger.info("JSONTokener(reader): " + new JSONTokener(reader.readLine()));
final JSONObject json = new JSONObject(new JSONTokener(reader.readLine()));
It shows me this in the output:
rawSchema: {VALID JSON STRUCTURE. IT'S TOO BIG TO INCLUDE IN THIS QUESTION}
reader: java.io.BufferedReader#4c4d27c8
JSONTokener(reader): at 0 [character 1 line 1]
Info on MockHttpServletRequest
The body of my MockHttpServletRequest contains the Lorem ipsum text. If I add the following code below my BufferedReader that text is printed to console. That same text is also used in ``final JSONObject json = new JSONObject(new JSONTokener(reader.readLine()));so the malformed JSON error in myHttpException` is no surprise.
while ((strCurrentLine = reader.readLine()) != null) {
_logger.info("reader: " + strCurrentLine);
}
Could this be a bug in my code? Should final JSONObject json = new JSONObject(new JSONTokener(reader.readLine())); in fact be final JSONObject json = new JSONObject(schema);? If I try that I can get see the code now reaches schema.validate(json); but there are 12 schema violations found. I can't see what these are though. Another thought is should the body be JSON?
I updated the body to JSON which resulted in 2 validation errors. One was that service_id was missing and testkey was present so I resolved that and my method no longer throws an exception when I use final JSONObject json = new JSONObject(new JSONTokener(reader));.
If you do just request = new MockHttpServletRequest(); then the request will have no body and the reader will not have data.
You can use MockMvcRequestBuilders to create a complete request.
request = MockMvcRequestBuilders.get("/message")
.contentType(MediaType.TEXT_PLAIN)
.content("{... json body ...}")
.buildRequest(context);
To resolve this I added a notifications key to my body JSON. This allowed final JSONObject json = new JSONObject(new JSONTokener(reader.readLine())); to work.
I am using Java Spring and I am trying to return a JSON object in json format. However my controller below returns a funny HTML format for JSON data, see below.
I want the controller to return the data as JSON formatted data not XML...
Any Ideas?
Thanks,
Pete
Data Returned:
<JSONArray><item><date><date>11</date><hours>15</hours><seconds>52</seconds>
<month>11</month><nanos>0</nanos><timezoneOffset>300</timezoneOffset>
<year>117</year><minutes>32</minutes><time>1513024372000</time><day>1</day>
</date><exception></exception><level>DEBUG</level>
<logger>com.foo.bar.webapp.controller.ReconcileController</logger><id>91</id>
<message>filter was empty</message></item><item><date><date>11</date>
<hours>15</hours><seconds>52</seconds><month>11</month><nanos>0</nanos>
<timezoneOffset>300</timezoneOffset><year>117</year><minutes>32</minutes>
<time>1513024372000</time><day>1</day></date><exception></exception>
<level>DEBUG</level><logger>com.foo.bar.webapp.controller.ReconcileController
</logger><id>92</id><message>returning labels as string</message>
</item><item><date><date>11</date><hours>15</hours><seconds>52</seconds>
<month>11</month><nanos>0</nanos><timezoneOffset>300</timezoneOffset>
<year>117</year><minutes>32</minutes><time>1513024372000</time><day>1</day>
</date><exception></exception><level>DEBUG</level>
<logger>com.foo.bar.webapp.controller.ReconcileController...
Controller Method :
#RequestMapping("/data*")
#Produces("application/json")
#ResponseBody
public JSONArray getData() {
List<LogEntry> logs = logEntryManager.getLogsByDate( new Date() );
JsonConfig config = new JsonConfig();
config.addIgnoreFieldAnnotation(com.fasterxml.jackson.annotation.JsonIgnore.class);
Log.trace("Get LogEntry Data Only");
JSONArray jsonArray = JSONArray.fromObject( logs, config );
return jsonArray;
}
#RequestMapping(value = "data", method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON) // import javax.ws.rs.core.MediaType
public #ResponseBody JSONArray getData() {
List<LogEntry> logs = logEntryManager.getLogsByDate( new Date() );
JsonConfig config = new JsonConfig();
config.addIgnoreFieldAnnotation(com.fasterxml.jackson.annotation.JsonIgnore.class);
Log.trace("Get LogEntry Data Only");
JSONArray jsonArray = JSONArray.fromObject( logs, config );
return jsonArray;
}
ignore your #Produces annotation
try this.
i am new to servlet and i succeeded to send a json format to the client using json-simple package/jar file; and import it like-
import org.json.simple.JSONObject;
and to get response in json i have following code-
response.setContentType("application/json");
JSONObject obj = new JSONObject();
obj.put("name", "veshraj joshi");
obj.put("id",request.getParameter("id"));
obj.put("num", new Integer(100));
obj.put("balance", new Double(1000.21));
out.println(obj);
and its format is like:
{"name":"veshraj joshi","id":"","num":"100","balance":"1000.21"}
and works fine,
but i need json format like-
{ status:"ok",
message:"record has been added successfully",
data:{
name:"veshraj joshi",
email:"email#gmail.com",
address:"kathmandu, Nepal"
}
}
and dont have any idea how to achieve this in servlet;
It works fine while try to make nested json and new code become-
response.setContentType("application/json");
JSONObject obj = new JSONObject();
JSONObject obj1 = new JSONObject();
obj1.put("email",'email#gmail.com');
obj1.put("name", "veshraj joshi");
obj1.put("id",request.getParameter("id"));
obj1.put("num", new Integer(100));
obj1.put("balance", new Double(1000.21));
obj.put("status","ok");
obj.put("message","record has been added successfully");
obj.put("data",obj1);
out.println(obj);
I'm trying to post a JSON to some REST service, but I always end up with a HTTP Error 415: Unsupported Media Type.
The REST Documentation clearly notes I should use application/json, which I do. Surely I must be overlooking something.
public JSONObject fetchResponse() throws ResourceException, JSONException, IOException {
JRRequest jr = new JRRequest();
jr.setJql(jql);
jr.setMaxResults(Integer.parseInt(maxresults));
jr.setFields(fields);
Gson json = new Gson();
String payload = json.toJson(jr);
JSONObject jsObj = new JSONObject(getClientResource(restUri).post(payload,MediaType.APPLICATION_JSON).getText());
return jsObj;
}
private ClientResource getClientResource(String uri) {
ClientResource clientResource = new ClientResource(uri);
Application app = new Application();
clientResource.setChallengeResponse(ChallengeScheme.HTTP_BASIC,username, password);
return clientResource;
}
Okay, I found the solution. Instead of doing it all in one line, I tried this:
Representation rep = new StringRepresentation(payload, MediaType.APPLICATION_JSON);
JSONObject jsObj = new JSONObject(getClientResource(restUri).post(rep).getText());
And it works now!