use of javax.json.JsonArrayBuilder in project sling by apache.
the class JsonReaderTest method toJsonArray.
protected String toJsonArray(String[] array) {
JsonArrayBuilder builder = Json.createArrayBuilder();
for (String value : array) {
builder.add(value);
}
StringWriter stringWriter = new StringWriter();
try (JsonWriter writer = Json.createWriter(stringWriter)) {
writer.writeArray(builder.build());
}
return stringWriter.toString();
}
use of javax.json.JsonArrayBuilder in project sling by apache.
the class AbstractGetAclServlet method internalGetAcl.
@SuppressWarnings("unchecked")
protected JsonObject internalGetAcl(Session jcrSession, String resourcePath) throws RepositoryException {
if (jcrSession == null) {
throw new RepositoryException("JCR Session not found");
}
Item item = jcrSession.getItem(resourcePath);
if (item != null) {
resourcePath = item.getPath();
} else {
throw new ResourceNotFoundException("Resource is not a JCR Node");
}
// Calculate a map of privileges to all the aggregate privileges it is contained in.
// Use for fast lookup during the mergePrivilegeSets calls below.
AccessControlManager accessControlManager = AccessControlUtil.getAccessControlManager(jcrSession);
Map<Privilege, Set<Privilege>> privilegeToAncestorMap = new HashMap<Privilege, Set<Privilege>>();
Privilege[] supportedPrivileges = accessControlManager.getSupportedPrivileges(item.getPath());
for (Privilege privilege : supportedPrivileges) {
if (privilege.isAggregate()) {
Privilege[] ap = privilege.getAggregatePrivileges();
for (Privilege privilege2 : ap) {
Set<Privilege> set = privilegeToAncestorMap.get(privilege2);
if (set == null) {
set = new HashSet<Privilege>();
privilegeToAncestorMap.put(privilege2, set);
}
set.add(privilege);
}
}
}
AccessControlEntry[] declaredAccessControlEntries = getAccessControlEntries(jcrSession, resourcePath);
Map<String, Map<String, Object>> aclMap = new LinkedHashMap<String, Map<String, Object>>();
int sequence = 0;
for (AccessControlEntry ace : declaredAccessControlEntries) {
Principal principal = ace.getPrincipal();
Map<String, Object> map = aclMap.get(principal.getName());
if (map == null) {
map = new LinkedHashMap<String, Object>();
aclMap.put(principal.getName(), map);
map.put("order", sequence++);
}
}
//evaluate these in reverse order so the most entries with highest specificity are last
for (int i = declaredAccessControlEntries.length - 1; i >= 0; i--) {
AccessControlEntry ace = declaredAccessControlEntries[i];
Principal principal = ace.getPrincipal();
Map<String, Object> map = aclMap.get(principal.getName());
Set<Privilege> grantedSet = (Set<Privilege>) map.get("granted");
if (grantedSet == null) {
grantedSet = new LinkedHashSet<Privilege>();
map.put("granted", grantedSet);
}
Set<Privilege> deniedSet = (Set<Privilege>) map.get("denied");
if (deniedSet == null) {
deniedSet = new LinkedHashSet<Privilege>();
map.put("denied", deniedSet);
}
boolean allow = AccessControlUtil.isAllow(ace);
if (allow) {
Privilege[] privileges = ace.getPrivileges();
for (Privilege privilege : privileges) {
mergePrivilegeSets(privilege, privilegeToAncestorMap, grantedSet, deniedSet);
}
} else {
Privilege[] privileges = ace.getPrivileges();
for (Privilege privilege : privileges) {
mergePrivilegeSets(privilege, privilegeToAncestorMap, deniedSet, grantedSet);
}
}
}
List<JsonObject> aclList = new ArrayList<>();
Set<Entry<String, Map<String, Object>>> entrySet = aclMap.entrySet();
for (Entry<String, Map<String, Object>> entry : entrySet) {
String principalName = entry.getKey();
Map<String, Object> value = entry.getValue();
JsonObjectBuilder aceObject = Json.createObjectBuilder();
aceObject.add("principal", principalName);
Set<Privilege> grantedSet = (Set<Privilege>) value.get("granted");
if (grantedSet != null && !grantedSet.isEmpty()) {
JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
for (Privilege v : grantedSet) {
arrayBuilder.add(v.getName());
}
aceObject.add("granted", arrayBuilder);
}
Set<Privilege> deniedSet = (Set<Privilege>) value.get("denied");
if (deniedSet != null && !deniedSet.isEmpty()) {
JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
for (Privilege v : deniedSet) {
arrayBuilder.add(v.getName());
}
aceObject.add("denied", arrayBuilder);
}
aceObject.add("order", (Integer) value.get("order"));
aclList.add(aceObject.build());
}
JsonObjectBuilder jsonAclMap = Json.createObjectBuilder();
for (Map.Entry<String, Map<String, Object>> entry : aclMap.entrySet()) {
JsonObjectBuilder builder = Json.createObjectBuilder();
for (Map.Entry<String, Object> inner : entry.getValue().entrySet()) {
addTo(builder, inner.getKey(), inner.getValue());
}
jsonAclMap.add(entry.getKey(), builder);
}
for (JsonObject jsonObj : aclList) {
jsonAclMap.add(jsonObj.getString("principal"), jsonObj);
}
return jsonAclMap.build();
}
use of javax.json.JsonArrayBuilder in project nifi by apache.
the class MetricsBuilder method build.
public JsonObject build() {
// builds JsonObject for individual metrics
final MetricBuilder metricBuilder = new MetricBuilder(factory);
metricBuilder.instanceId(instanceId).applicationId(applicationId).timestamp(timestamp).hostname(hostname);
final JsonArrayBuilder metricArrayBuilder = factory.createArrayBuilder();
for (Map.Entry<String, String> entry : metrics.entrySet()) {
metricBuilder.metricName(entry.getKey()).metricValue(entry.getValue());
metricArrayBuilder.add(metricBuilder.build());
}
// add the array of metrics to a top-level json object
final JsonObjectBuilder metricsBuilder = factory.createObjectBuilder();
metricsBuilder.add(ROOT_JSON_ELEMENT, metricArrayBuilder);
return metricsBuilder.build();
}
use of javax.json.JsonArrayBuilder in project nifi by apache.
the class MetricsBuilder method build.
public JsonObject build() {
// builds JsonObject for individual metrics
final MetricBuilder metricBuilder = new MetricBuilder(factory);
metricBuilder.instanceId(instanceId).applicationId(applicationId).timestamp(timestamp).hostname(hostname);
final JsonArrayBuilder metricArrayBuilder = factory.createArrayBuilder();
for (Map.Entry<String, String> entry : metrics.entrySet()) {
metricBuilder.metricName(entry.getKey()).metricValue(entry.getValue());
metricArrayBuilder.add(metricBuilder.build());
}
// add the array of metrics to a top-level json object
final JsonObjectBuilder metricsBuilder = factory.createObjectBuilder();
metricsBuilder.add(ROOT_JSON_ELEMENT, metricArrayBuilder);
return metricsBuilder.build();
}
use of javax.json.JsonArrayBuilder in project nifi by apache.
the class SiteToSiteBulletinReportingTask method onTrigger.
@Override
public void onTrigger(final ReportingContext context) {
final boolean isClustered = context.isClustered();
final String nodeId = context.getClusterNodeIdentifier();
if (nodeId == null && isClustered) {
getLogger().debug("This instance of NiFi is configured for clustering, but the Cluster Node Identifier is not yet available. " + "Will wait for Node Identifier to be established.");
return;
}
if (lastSentBulletinId < 0) {
Map<String, String> state;
try {
state = context.getStateManager().getState(Scope.LOCAL).toMap();
} catch (IOException e) {
getLogger().error("Failed to get state at start up due to:" + e.getMessage(), e);
return;
}
if (state.containsKey(LAST_EVENT_ID_KEY)) {
lastSentBulletinId = Long.parseLong(state.get(LAST_EVENT_ID_KEY));
}
}
final BulletinQuery bulletinQuery = new BulletinQuery.Builder().after(lastSentBulletinId).build();
final List<Bulletin> bulletins = context.getBulletinRepository().findBulletins(bulletinQuery);
if (bulletins == null || bulletins.isEmpty()) {
getLogger().debug("No events to send because no events are stored in the repository.");
return;
}
final OptionalLong opMaxId = bulletins.stream().mapToLong(t -> t.getId()).max();
final Long currMaxId = opMaxId.isPresent() ? opMaxId.getAsLong() : -1;
if (currMaxId < lastSentBulletinId) {
getLogger().warn("Current bulletin max id is {} which is less than what was stored in state as the last queried event, which was {}. " + "This means the bulletins repository restarted its ids. Restarting querying from the beginning.", new Object[] { currMaxId, lastSentBulletinId });
lastSentBulletinId = -1;
}
if (currMaxId == lastSentBulletinId) {
getLogger().debug("No events to send due to the current max id being equal to the last id that was sent.");
return;
}
final String platform = context.getProperty(PLATFORM).evaluateAttributeExpressions().getValue();
final Map<String, ?> config = Collections.emptyMap();
final JsonBuilderFactory factory = Json.createBuilderFactory(config);
final JsonObjectBuilder builder = factory.createObjectBuilder();
final DateFormat df = new SimpleDateFormat(TIMESTAMP_FORMAT);
df.setTimeZone(TimeZone.getTimeZone("Z"));
final long start = System.nanoTime();
// Create a JSON array of all the events in the current batch
final JsonArrayBuilder arrayBuilder = factory.createArrayBuilder();
for (final Bulletin bulletin : bulletins) {
if (bulletin.getId() > lastSentBulletinId) {
arrayBuilder.add(serialize(factory, builder, bulletin, df, platform, nodeId));
}
}
final JsonArray jsonArray = arrayBuilder.build();
// Send the JSON document for the current batch
try {
final Transaction transaction = getClient().createTransaction(TransferDirection.SEND);
if (transaction == null) {
getLogger().info("All destination nodes are penalized; will attempt to send data later");
return;
}
final Map<String, String> attributes = new HashMap<>();
final String transactionId = UUID.randomUUID().toString();
attributes.put("reporting.task.transaction.id", transactionId);
attributes.put("reporting.task.name", getName());
attributes.put("reporting.task.uuid", getIdentifier());
attributes.put("reporting.task.type", this.getClass().getSimpleName());
attributes.put("mime.type", "application/json");
final byte[] data = jsonArray.toString().getBytes(StandardCharsets.UTF_8);
transaction.send(data, attributes);
transaction.confirm();
transaction.complete();
final long transferMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
getLogger().info("Successfully sent {} Bulletins to destination in {} ms; Transaction ID = {}; First Event ID = {}", new Object[] { bulletins.size(), transferMillis, transactionId, bulletins.get(0).getId() });
} catch (final IOException e) {
throw new ProcessException("Failed to send Bulletins to destination due to IOException:" + e.getMessage(), e);
}
// Store the id of the last event so we know where we left off
try {
context.getStateManager().setState(Collections.singletonMap(LAST_EVENT_ID_KEY, String.valueOf(currMaxId)), Scope.LOCAL);
} catch (final IOException ioe) {
getLogger().error("Failed to update state to {} due to {}; this could result in events being re-sent after a restart.", new Object[] { currMaxId, ioe.getMessage() }, ioe);
}
lastSentBulletinId = currMaxId;
}
Aggregations