Search in sources :

Example 6 with JsonArrayBuilder

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();
}
Also used : StringWriter(java.io.StringWriter) JsonArrayBuilder(javax.json.JsonArrayBuilder) JsonWriter(javax.json.JsonWriter)

Example 7 with JsonArrayBuilder

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();
}
Also used : AccessControlManager(javax.jcr.security.AccessControlManager) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) Set(java.util.Set) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ArrayList(java.util.ArrayList) JsonObject(javax.json.JsonObject) LinkedHashMap(java.util.LinkedHashMap) Item(javax.jcr.Item) AccessControlEntry(javax.jcr.security.AccessControlEntry) Entry(java.util.Map.Entry) JsonArrayBuilder(javax.json.JsonArrayBuilder) ResourceNotFoundException(org.apache.sling.api.resource.ResourceNotFoundException) JsonObjectBuilder(javax.json.JsonObjectBuilder) AccessControlEntry(javax.jcr.security.AccessControlEntry) RepositoryException(javax.jcr.RepositoryException) JsonObject(javax.json.JsonObject) Privilege(javax.jcr.security.Privilege) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) Principal(java.security.Principal)

Example 8 with JsonArrayBuilder

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();
}
Also used : JsonArrayBuilder(javax.json.JsonArrayBuilder) JsonObjectBuilder(javax.json.JsonObjectBuilder) Map(java.util.Map) HashMap(java.util.HashMap)

Example 9 with JsonArrayBuilder

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();
}
Also used : JsonArrayBuilder(javax.json.JsonArrayBuilder) JsonObjectBuilder(javax.json.JsonObjectBuilder) Map(java.util.Map) HashMap(java.util.HashMap)

Example 10 with JsonArrayBuilder

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;
}
Also used : StandardValidators(org.apache.nifi.processor.util.StandardValidators) JsonArrayBuilder(javax.json.JsonArrayBuilder) CapabilityDescription(org.apache.nifi.annotation.documentation.CapabilityDescription) JsonBuilderFactory(javax.json.JsonBuilderFactory) SimpleDateFormat(java.text.SimpleDateFormat) HashMap(java.util.HashMap) PropertyDescriptor(org.apache.nifi.components.PropertyDescriptor) ProcessException(org.apache.nifi.processor.exception.ProcessException) ArrayList(java.util.ArrayList) OptionalLong(java.util.OptionalLong) Scope(org.apache.nifi.components.state.Scope) SchedulingStrategy(org.apache.nifi.scheduling.SchedulingStrategy) Map(java.util.Map) Json(javax.json.Json) DateFormat(java.text.DateFormat) Restricted(org.apache.nifi.annotation.behavior.Restricted) JsonObject(javax.json.JsonObject) Restriction(org.apache.nifi.annotation.behavior.Restriction) TransferDirection(org.apache.nifi.remote.TransferDirection) RequiredPermission(org.apache.nifi.components.RequiredPermission) TimeZone(java.util.TimeZone) JsonArray(javax.json.JsonArray) IOException(java.io.IOException) UUID(java.util.UUID) Transaction(org.apache.nifi.remote.Transaction) StandardCharsets(java.nio.charset.StandardCharsets) TimeUnit(java.util.concurrent.TimeUnit) Stateful(org.apache.nifi.annotation.behavior.Stateful) List(java.util.List) DefaultSchedule(org.apache.nifi.annotation.configuration.DefaultSchedule) Tags(org.apache.nifi.annotation.documentation.Tags) Collections(java.util.Collections) JsonObjectBuilder(javax.json.JsonObjectBuilder) HashMap(java.util.HashMap) JsonArrayBuilder(javax.json.JsonArrayBuilder) JsonObjectBuilder(javax.json.JsonObjectBuilder) IOException(java.io.IOException) JsonArray(javax.json.JsonArray) ProcessException(org.apache.nifi.processor.exception.ProcessException) Transaction(org.apache.nifi.remote.Transaction) JsonBuilderFactory(javax.json.JsonBuilderFactory) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) OptionalLong(java.util.OptionalLong) OptionalLong(java.util.OptionalLong) JsonObject(javax.json.JsonObject) JsonArrayBuilder(javax.json.JsonArrayBuilder) JsonObjectBuilder(javax.json.JsonObjectBuilder) SimpleDateFormat(java.text.SimpleDateFormat)

Aggregations

JsonArrayBuilder (javax.json.JsonArrayBuilder)177 JsonObjectBuilder (javax.json.JsonObjectBuilder)103 JsonObject (javax.json.JsonObject)36 Map (java.util.Map)29 Path (javax.ws.rs.Path)26 GET (javax.ws.rs.GET)24 HashMap (java.util.HashMap)19 JsonArray (javax.json.JsonArray)18 ArrayList (java.util.ArrayList)15 List (java.util.List)15 AuthenticatedUser (edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)12 IOException (java.io.IOException)12 Dataverse (edu.harvard.iq.dataverse.Dataverse)10 Dataset (edu.harvard.iq.dataverse.Dataset)9 User (edu.harvard.iq.dataverse.authorization.users.User)9 JsonValue (javax.json.JsonValue)9 StringWriter (java.io.StringWriter)8 JsonString (javax.json.JsonString)7 Date (java.util.Date)6 JsonException (javax.json.JsonException)6