use of org.json.simple.parser.JSONParser in project opennms by OpenNMS.
the class MemosChangeNotificationClient method sendDbNotification.
@Override
public void sendDbNotification(DbNotification dbNotification) {
try {
String payload = dbNotification.getPayload();
JSONObject memoJsonObject = null;
JSONObject alarmIdJsonObject = null;
String alarmId = null;
String body = null;
String author = null;
String reductionkey = null;
try {
JSONParser parser = new JSONParser();
Object obj;
obj = parser.parse(payload);
JSONArray jsonArray = (JSONArray) obj;
if (LOG.isDebugEnabled())
LOG.debug("payload memo jsonArray.toString():" + jsonArray.toString());
memoJsonObject = (JSONObject) jsonArray.get(0);
memoJsonObject = jsonMemoTimeNormaliser(memoJsonObject);
alarmIdJsonObject = (JSONObject) jsonArray.get(1);
alarmId = (alarmIdJsonObject.get("alarmid") == null) ? null : alarmIdJsonObject.get("alarmid").toString();
body = (memoJsonObject.get("body") == null) ? null : memoJsonObject.get("body").toString();
author = (memoJsonObject.get("author") == null) ? null : memoJsonObject.get("author").toString();
reductionkey = (memoJsonObject.get("reductionkey") == null) ? null : memoJsonObject.get("reductionkey").toString();
} catch (ParseException e1) {
throw new RuntimeException("cannot parse notification payload to json object. payload=" + payload, e1);
}
if (!memoJsonObject.isEmpty()) {
// sticky note event
if ("Memo".equals(memoJsonObject.get("type").toString())) {
if (LOG.isDebugEnabled())
LOG.debug("sticky memo updated=" + memoJsonObject.get("id"));
EventBuilder eb = new EventBuilder(AlarmChangeEventConstants.STICKY_MEMO_EVENT, EVENT_SOURCE_NAME);
//copy in all values as json in params
eb.addParam(AlarmChangeEventConstants.MEMO_VALUES_PARAM, memoJsonObject.toString());
eb.addParam(AlarmChangeEventConstants.MEMO_ALARMID_PARAM, alarmId);
eb.addParam(AlarmChangeEventConstants.MEMO_BODY_PARAM, body);
eb.addParam(AlarmChangeEventConstants.MEMO_AUTHOR_PARAM, author);
sendEvent(eb.getEvent());
} else if ("ReductionKeyMemo".equals(memoJsonObject.get("type").toString())) {
if (LOG.isDebugEnabled())
LOG.debug("reduction key memo updated=" + memoJsonObject.get("id"));
EventBuilder eb = new EventBuilder(AlarmChangeEventConstants.JOURNAL_MEMO_EVENT, EVENT_SOURCE_NAME);
//copy in all values as json in params
eb.addParam(AlarmChangeEventConstants.MEMO_VALUES_PARAM, memoJsonObject.toString());
eb.addParam(AlarmChangeEventConstants.MEMO_ALARMID_PARAM, alarmId);
eb.addParam(AlarmChangeEventConstants.MEMO_BODY_PARAM, body);
eb.addParam(AlarmChangeEventConstants.MEMO_AUTHOR_PARAM, author);
eb.addParam(AlarmChangeEventConstants.MEMO_REDUCTIONKEY_PARAM, reductionkey);
sendEvent(eb.getEvent());
}
}
} catch (Exception e) {
LOG.error("problem creating opennms alarm change event from database notification", e);
}
}
use of org.json.simple.parser.JSONParser in project opennms by OpenNMS.
the class AlarmEventToIndexTest method jestClientAlarmToESTest.
/**
* simple test to create an alarm change event which will create a new alarm in the alarm index
* and create an alarm change event in the alarm change index
*/
@Test
public void jestClientAlarmToESTest() {
LOG.debug("***************** start of test jestClientAlarmToESTest");
EventToIndex eventToIndex = new EventToIndex();
JestClient jestClient = null;
try {
// Get Jest client
String esusername = "";
String espassword = "";
String elasticsearchUrl = "http://localhost:9200";
RestClientFactory restClientFactory = new RestClientFactory(elasticsearchUrl, esusername, espassword);
IndexNameFunction indexNameFunction = new IndexNameFunction("yyyy.MM");
NodeCache nodeCache = new MockNodeCache();
eventToIndex.setRestClientFactory(restClientFactory);
eventToIndex.setNodeCache(nodeCache);
eventToIndex.setIndexNameFunction(indexNameFunction);
eventToIndex.setLogEventDescription(true);
eventToIndex.setArchiveRawEvents(true);
eventToIndex.setArchiveAlarms(true);
eventToIndex.setArchiveAlarmChangeEvents(true);
eventToIndex.setArchiveOldAlarmValues(true);
eventToIndex.setArchiveNewAlarmValues(true);
// create an alarm change event
EventBuilder eb = new EventBuilder(ALARM_ACKNOWLEDGED_EVENT, EVENT_SOURCE_NAME);
//copy in all values as json in params
eb.addParam("oldalarmvalues", TEST_ALARM_JSON_1);
eb.addParam("newalarmvalues", TEST_ALARM_JSON_1);
Event event = eb.getEvent();
event.setDbid(100);
event.setNodeid((long) 34);
// forward event to Elasticsearch
eventToIndex.forwardEvents(Collections.singletonList(event));
// waiting INDEX_WAIT_SECONDS seconds for index
try {
TimeUnit.SECONDS.sleep(INDEX_WAIT_SECONDS);
} catch (InterruptedException e) {
}
// send query to check that alarm has been created
jestClient = restClientFactory.getJestClient();
// search for resulting alarm
String query = "{\n" + "\n \"query\": {" + "\n \"match\": {" + "\n \"alarmid\": \"807\"" + "\n }" + "\n }" + "\n }";
LOG.debug("alarm check search query: " + query);
Search search = new Search.Builder(query).addIndex("opennms-*").build();
SearchResult sresult = jestClient.execute(search);
LOG.debug("received search sresult: " + sresult.getJsonString() + "\n response code:" + sresult.getResponseCode() + "\n error message: " + sresult.getErrorMessage());
assertEquals(200, sresult.getResponseCode());
JSONParser parser = new JSONParser();
Object obj = parser.parse(sresult.getJsonString());
JSONObject resultValues = (JSONObject) obj;
JSONObject hits = (JSONObject) resultValues.get("hits");
LOG.debug("search result hits:total=" + hits.get("total"));
assertEquals(Long.valueOf(1), hits.get("total"));
// waiting INDEX_WAIT_SECONDS seconds for index
try {
TimeUnit.SECONDS.sleep(INDEX_WAIT_SECONDS);
} catch (InterruptedException e) {
}
// search for resulting alarm change event
String eventquery = "{\n" + "\n \"query\": {" + "\n \"match\": {" + "\n \"id\": \"100\"" + "\n }" + "\n }" + "\n }";
LOG.debug("event check search query: " + eventquery);
Search eventsearch = new Search.Builder(eventquery).addIndex("opennms-*").build();
SearchResult eventsresult = jestClient.execute(eventsearch);
LOG.debug("received search eventsresult: " + eventsresult.getJsonString() + "\n response code:" + eventsresult.getResponseCode() + "\n error message: " + eventsresult.getErrorMessage());
assertEquals(200, eventsresult.getResponseCode());
Object obj2 = parser.parse(eventsresult.getJsonString());
JSONObject eventsresultValues = (JSONObject) obj2;
JSONObject eventhits = (JSONObject) eventsresultValues.get("hits");
LOG.debug("search result event hits:total=" + eventhits.get("total"));
assertEquals(Long.valueOf(1), eventhits.get("total"));
JSONArray eventhitsvalues = (JSONArray) eventhits.get("hits");
LOG.debug(" eventhitsvalues: " + eventhitsvalues.toJSONString());
JSONObject hitObj = (JSONObject) eventhitsvalues.get(0);
LOG.debug(" hitObj: " + hitObj.toJSONString());
String typeStr = hitObj.get("_type").toString();
LOG.debug("search result index type=" + typeStr);
assertEquals(EVENT_INDEX_TYPE, typeStr);
JSONObject sourceObj = (JSONObject) hitObj.get("_source");
LOG.debug(" sourceObj: " + sourceObj.toJSONString());
String eventUeiStr = sourceObj.get("eventuei").toString();
LOG.debug("search result event eventueistr=" + eventUeiStr);
assertEquals(ALARM_ACKNOWLEDGED_EVENT, eventUeiStr);
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
} finally {
// shutdown client
if (jestClient != null)
jestClient.shutdownClient();
if (eventToIndex != null)
eventToIndex.close();
}
LOG.debug("***************** end of test jestClientAlarmToESTest");
}
use of org.json.simple.parser.JSONParser in project tdi-studio-se by Talend.
the class OAuthClient method refreshToken.
public Token refreshToken(String refreshToken) throws Exception {
Token newToken = new Token();
newToken.setRefresh_token(refreshToken);
// get token using refresh token
String token_url = baseOAuthURL.endsWith("/") ? baseOAuthURL + OAUTH2_TOKEN : baseOAuthURL + "/" + OAUTH2_TOKEN;
URLConnection conn = new URL(token_url).openConnection();
// post
conn.setDoOutput(true);
String query = String.format("grant_type=%s&client_id=%s&client_secret=%s&refresh_token=%s&format=%s", "refresh_token", clientID, clientSecret, refreshToken, "json");
OutputStream output = null;
try {
output = conn.getOutputStream();
output.write(query.getBytes(UTF8));
} finally {
if (output != null) {
try {
output.close();
} catch (IOException ignore) {
}
}
}
InputStream input = conn.getInputStream();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(input));
JSONParser jsonParser = new JSONParser();
JSONObject json = (JSONObject) jsonParser.parse(reader);
if (json.get("error") == null) {
if (json.get("access_token") != null) {
newToken.setAccess_token(json.get("access_token").toString());
}
if (json.get("instance_url") != null) {
newToken.setInstance_url(json.get("instance_url").toString());
}
if (json.get("id") != null) {
newToken.setId(json.get("id").toString());
}
if (json.get("issued_at") != null) {
newToken.setIssued_at(Long.parseLong(json.get("issued_at").toString()));
}
if (json.get("signature") != null) {
newToken.setSignature(json.get("signature").toString());
}
} else {
throw new Exception(json.toString());
}
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ignore) {
}
}
}
return newToken;
}
use of org.json.simple.parser.JSONParser in project tdi-studio-se by Talend.
the class OAuthClient method getToken.
public Token getToken() throws Exception {
Token token = new Token();
URL callback_url = new URL("https", callbackHost, callbackPort, "");
String oauth2_authorize_url = baseOAuthURL.endsWith("/") ? baseOAuthURL + OAUTH2_AUTHORIZE : baseOAuthURL + "/" + OAUTH2_AUTHORIZE;
String authorize_url = // &scope=%s
String.format(// &scope=%s
"%s?response_type=%s&client_id=%s&redirect_uri=%s", // &scope=%s
oauth2_authorize_url, "code", clientID, // , "full%20refresh_token"
URLEncoder.encode(callback_url.toString(), UTF8));
System.out.println("Paste this URL into a web browser to authorize Salesforce Access:");
System.out.println(authorize_url);
// start a service to get Authorization code
HttpsService service = new HttpsService(callbackPort);
String code = null;
while (service.getCode() == null) {
Thread.sleep(2 * 1000);
}
code = service.getCode();
// stop service
service.stop();
// get token using Authorization code
String token_url = baseOAuthURL.endsWith("/") ? baseOAuthURL + OAUTH2_TOKEN : baseOAuthURL + "/" + OAUTH2_TOKEN;
URLConnection conn = new URL(token_url).openConnection();
// post
conn.setDoOutput(true);
String query = String.format("grant_type=%s&client_id=%s&client_secret=%s&redirect_uri=%s&code=%s", "authorization_code", clientID, clientSecret, URLEncoder.encode(callback_url.toString(), UTF8), code);
OutputStream output = null;
try {
output = conn.getOutputStream();
output.write(query.getBytes(UTF8));
} finally {
if (output != null) {
try {
output.close();
} catch (IOException ignore) {
}
}
}
InputStream input = conn.getInputStream();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(input));
JSONParser jsonParser = new JSONParser();
JSONObject json = (JSONObject) jsonParser.parse(reader);
if (json.get("access_token") != null) {
token.setAccess_token(json.get("access_token").toString());
}
if (json.get("refresh_token") != null) {
token.setRefresh_token(json.get("refresh_token").toString());
}
if (json.get("instance_url") != null) {
token.setInstance_url(json.get("instance_url").toString());
}
if (json.get("id") != null) {
token.setId(json.get("id").toString());
}
if (json.get("issued_at") != null) {
token.setIssued_at(Long.parseLong(json.get("issued_at").toString()));
}
if (json.get("signature") != null) {
token.setSignature(json.get("signature").toString());
}
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ignore) {
}
}
}
return token;
}
use of org.json.simple.parser.JSONParser in project tdi-studio-se by Talend.
the class OAuthClient method getTokenForWizard.
public Token getTokenForWizard(String code) throws Exception {
Token token = new Token();
URL callback_url = new URL("https", callbackHost, callbackPort, "");
String oauth2_authorize_url = baseOAuthURL.endsWith("/") ? baseOAuthURL + OAUTH2_AUTHORIZE : baseOAuthURL + "/" + OAUTH2_AUTHORIZE;
String authorize_url = // &scope=%s
String.format(// &scope=%s
"%s?response_type=%s&client_id=%s&redirect_uri=%s", // &scope=%s
oauth2_authorize_url, "code", clientID, // , "full%20refresh_token"
URLEncoder.encode(callback_url.toString(), UTF8));
String token_url = baseOAuthURL.endsWith("/") ? baseOAuthURL + OAUTH2_TOKEN : baseOAuthURL + "/" + OAUTH2_TOKEN;
URLConnection conn = new URL(token_url).openConnection();
// post
conn.setDoOutput(true);
String query = String.format("grant_type=%s&client_id=%s&client_secret=%s&redirect_uri=%s&code=%s", "authorization_code", clientID, clientSecret, URLEncoder.encode(callback_url.toString(), UTF8), code);
OutputStream output = null;
try {
output = conn.getOutputStream();
output.write(query.getBytes(UTF8));
} finally {
if (output != null) {
try {
output.close();
} catch (IOException ignore) {
}
}
}
InputStream input = conn.getInputStream();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(input));
JSONParser jsonParser = new JSONParser();
JSONObject json = (JSONObject) jsonParser.parse(reader);
if (json.get("access_token") != null) {
token.setAccess_token(json.get("access_token").toString());
}
if (json.get("refresh_token") != null) {
token.setRefresh_token(json.get("refresh_token").toString());
}
if (json.get("instance_url") != null) {
token.setInstance_url(json.get("instance_url").toString());
}
if (json.get("id") != null) {
token.setId(json.get("id").toString());
}
if (json.get("issued_at") != null) {
token.setIssued_at(Long.parseLong(json.get("issued_at").toString()));
}
if (json.get("signature") != null) {
token.setSignature(json.get("signature").toString());
}
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ignore) {
}
}
}
return token;
}
Aggregations