use of org.json.simple.JSONArray 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.JSONArray in project TotalFreedomMod by TotalFreedom.
the class Module_players method getResponse.
@Override
@SuppressWarnings("unchecked")
public NanoHTTPD.Response getResponse() {
final JSONObject responseObject = new JSONObject();
final JSONArray players = new JSONArray();
final JSONArray superadmins = new JSONArray();
final JSONArray telnetadmins = new JSONArray();
final JSONArray senioradmins = new JSONArray();
final JSONArray developers = new JSONArray();
// All online players
for (Player player : Bukkit.getOnlinePlayers()) {
players.add(player.getName());
}
// Admins
for (Admin admin : plugin.al.getActiveAdmins()) {
final String username = admin.getName();
switch(admin.getRank()) {
case SUPER_ADMIN:
superadmins.add(username);
break;
case TELNET_ADMIN:
telnetadmins.add(username);
break;
case SENIOR_ADMIN:
senioradmins.add(username);
break;
}
}
// Developers
developers.addAll(FUtil.DEVELOPERS);
responseObject.put("players", players);
responseObject.put("superadmins", superadmins);
responseObject.put("telnetadmins", telnetadmins);
responseObject.put("senioradmins", senioradmins);
responseObject.put("developers", developers);
final NanoHTTPD.Response response = new NanoHTTPD.Response(NanoHTTPD.Response.Status.OK, NanoHTTPD.MIME_JSON, responseObject.toString());
response.addHeader("Access-Control-Allow-Origin", "*");
return response;
}
use of org.json.simple.JSONArray in project spatial-portal by AtlasOfLivingAustralia.
the class AreaMapPolygon method onSearchPoint.
/**
* Searches the gazetter at a given point and then maps the polygon feature
* found at the location (for the current top contextual layer).
*
* @param event
*/
public void onSearchPoint(Event event) {
String searchPoint = (String) event.getData();
String lon = searchPoint.split(",")[0];
String lat = searchPoint.split(",")[1];
LOGGER.debug("*************************************");
LOGGER.debug("CommonData.getLayerList");
LOGGER.debug("*************************************");
JSONArray layerlist = CommonData.getLayerListJSONArray();
MapComposer mc = getMapComposer();
List<MapLayer> activeLayers = getPortalSession().getActiveLayers();
Boolean searchComplete = false;
for (int i = 0; i < activeLayers.size(); i++) {
MapLayer ml = activeLayers.get(i);
String activeLayerName = StringConstants.NONE;
if (ml.getUri() != null) {
activeLayerName = ml.getUri().replaceAll("^.*&style=", "").replaceAll("&.*", "").replaceAll("_style", "");
}
LOGGER.debug("ACTIVE LAYER: " + activeLayerName);
if (ml.isDisplayed() && ml.isContextualLayer()) {
for (int j = 0; j < layerlist.size() && !searchComplete; j++) {
JSONObject field = (JSONObject) layerlist.get(j);
JSONObject layer = (JSONObject) field.get("layer");
if (layer.get(StringConstants.TYPE) != null && layer.get(StringConstants.TYPE).toString().length() > 0 && StringConstants.CONTEXTUAL.equalsIgnoreCase(layer.get(StringConstants.TYPE).toString()) && field.get(StringConstants.ID).toString().equalsIgnoreCase(activeLayerName)) {
LOGGER.debug(ml.getName());
Map<String, String> feature = GazetteerPointSearch.pointSearch(lon, lat, activeLayerName, CommonData.getGeoServer());
if (feature == null || !feature.containsKey(StringConstants.PID)) {
continue;
}
layerName = (mc.getMapLayer(txtLayerName.getValue()) == null) ? txtLayerName.getValue() : mc.getNextAreaLayerName(txtLayerName.getValue());
getMapComposer().addObjectByPid(feature.get(StringConstants.PID), layerName, 1);
//found the object on the layer
btnOk.setDisabled(false);
btnClear.setDisabled(false);
mc.updateLayerControls();
searchComplete = true;
displayGeom.setValue("layer: " + feature.get(StringConstants.LAYERNAME) + "\r\n" + "area: " + feature.get(StringConstants.VALUE));
return;
}
}
}
}
}
use of org.json.simple.JSONArray in project spatial-portal by AtlasOfLivingAustralia.
the class BiocacheQuery method retrieveCustomFacets.
/**
* Retrieves a list of custom facets for the supplied query.
*
* @return
*/
private List<QueryField> retrieveCustomFacets() {
List<QueryField> customFacets = new ArrayList<QueryField>();
//custom fields can only be retrieved with specific query types
String full = getFullQ(false);
Matcher match = Pattern.compile("data_resource_uid:\"??dr[t][0-9]+\"??").matcher(full);
if (!match.find()) {
return customFacets;
}
//look up facets
try {
final String jsonUri = biocacheServer + "/upload/dynamicFacets?q=" + URLEncoder.encode(match.group(), "UTF-8");
HttpClient client = new HttpClient();
GetMethod get = new GetMethod(jsonUri);
get.addRequestHeader(StringConstants.CONTENT_TYPE, StringConstants.APPLICATION_JSON);
client.executeMethod(get);
String slist = get.getResponseBodyAsString();
JSONParser jp = new JSONParser();
JSONArray ja = (JSONArray) jp.parse(slist);
for (Object arrayElement : ja) {
JSONObject jsonObject = (JSONObject) arrayElement;
String facetName = jsonObject.get(StringConstants.NAME).toString();
String facetDisplayName = jsonObject.get("displayName").toString();
//TODO: remove this when _RNG fields work in legend &cm= parameter
if (!(facetDisplayName.contains("(Range)") && facetName.endsWith("_RNG"))) {
LOGGER.debug("Adding custom index : " + arrayElement);
customFacets.add(new QueryField(facetName, facetDisplayName, QueryField.GroupType.CUSTOM, QueryField.FieldType.STRING));
}
}
} catch (Exception e) {
LOGGER.error("error loading custom facets for: " + getFullQ(false), e);
}
return customFacets;
}
use of org.json.simple.JSONArray in project spatial-portal by AtlasOfLivingAustralia.
the class BiocacheQuery method getAutoComplete.
/**
* Returns the "autocomplete" values for the query based on the supplied facet field. Extensible so that we can add autocomplete
* based on queries in other areas.
* <p/>
* NC 20131126 - added to support an autocomplete of raw taxon name for a fix associated with Fungi
*
* @param facet The facet to autocomplete on
* @param value The prefix for the autocomplete
* @param limit The maximum number of values to return
* @return
*/
public String getAutoComplete(String facet, String value, int limit) {
HttpClient client = new HttpClient();
StringBuilder slist = new StringBuilder();
if (value.length() >= 3 && StringUtils.isNotBlank(facet)) {
try {
String url = biocacheServer + QUERY_TITLE_URL + "q=" + getQ() + getQc() + "&facets=" + facet + "&fprefix=" + URLEncoder.encode(value, StringConstants.UTF_8) + "&pageSize=0&flimit=" + limit;
GetMethod get = new GetMethod(url);
get.addRequestHeader(StringConstants.CONTENT_TYPE, StringConstants.TEXT_PLAIN);
int result = client.executeMethod(get);
if (result == 200) {
//success
String rawJSON = get.getResponseBodyAsString();
//parse
JSONParser jp = new JSONParser();
JSONObject jo = (JSONObject) jp.parse(rawJSON);
JSONArray ja = (JSONArray) jo.get("facetResults");
for (int i = 0; i < ja.size(); i++) {
JSONObject o = (JSONObject) ja.get(i);
if (o.get("fieldName").equals(facet)) {
//process the values in the list
JSONArray values = (JSONArray) o.get("fieldResult");
for (int j = 0; j < values.size(); j++) {
JSONObject vo = (JSONObject) values.get(j);
if (slist.length() > 0) {
slist.append("\n");
}
slist.append(vo.get("label")).append("//found ").append(vo.get(StringConstants.COUNT).toString());
}
}
}
} else {
LOGGER.warn("There was an issue performing the autocomplete from the biocache: " + result);
}
} catch (Exception e) {
LOGGER.error("failed to get autocomplete facet=" + facet + ", value=" + value, e);
}
}
return slist.toString();
}
Aggregations