Example usage for java.util Comparator comparing

List of usage examples for java.util Comparator comparing

Introduction

In this page you can find the example usage for java.util Comparator comparing.

Prototype

public static <T, U extends Comparable<? super U>> Comparator<T> comparing(
        Function<? super T, ? extends U> keyExtractor) 

Source Link

Document

Accepts a function that extracts a java.lang.Comparable Comparable sort key from a type T , and returns a Comparator that compares by that sort key.

Usage

From source file:org.thingsboard.server.dao.device.DeviceServiceImpl.java

@Override
public ListenableFuture<List<EntitySubtype>> findDeviceTypesByTenantId(TenantId tenantId) {
    log.trace("Executing findDeviceTypesByTenantId, tenantId [{}]", tenantId);
    validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
    ListenableFuture<List<EntitySubtype>> tenantDeviceTypes = deviceDao
            .findTenantDeviceTypesAsync(tenantId.getId());
    return Futures.transform(tenantDeviceTypes, deviceTypes -> {
        deviceTypes.sort(Comparator.comparing(EntitySubtype::getType));
        return deviceTypes;
    });//  w  ww .j a  v  a  2s . co m
}

From source file:org.keycloak.models.jpa.JpaRealmProvider.java

@Override
public List<GroupModel> getTopLevelGroups(RealmModel realm, Integer first, Integer max) {
    List<String> groupIds = em.createNamedQuery("getTopLevelGroupIds", String.class)
            .setParameter("realm", realm.getId()).setFirstResult(first).setMaxResults(max).getResultList();
    List<GroupModel> list = new ArrayList<>();
    if (Objects.nonNull(groupIds) && !groupIds.isEmpty()) {
        for (String id : groupIds) {
            GroupModel group = getGroupById(id, realm);
            list.add(group);/* ww w. j av  a  2s.  c o  m*/
        }
    }

    list.sort(Comparator.comparing(GroupModel::getName));

    return Collections.unmodifiableList(list);
}

From source file:com.netflix.spinnaker.halyard.cli.command.v1.NestableCommand.java

private void commandDocs(StringBuilder result) {
    List<ParameterDescription> parameters = commander.getParameters();
    parameters.sort(Comparator.comparing(ParameterDescription::getNames));

    int parameterCount = 0;
    for (ParameterDescription parameter : parameters) {
        if (GlobalOptions.isGlobalOption(parameter.getLongestName())) {
            parameterCount++;/* www.j  a  va2s  . co  m*/
        }
    }

    String longDescription = getLongDescription() != null ? getLongDescription() : getDescription();
    result.append("## ").append(fullCommandName).append("\n\n").append(longDescription).append("\n\n")
            .append("#### Usage").append("\n```\n").append(fullCommandName);

    ParameterDescription mainParameter = commander.getMainParameter();
    if (mainParameter != null) {
        result.append(" ").append(getMainParameter().toUpperCase());

    }

    if (parameters.size() > parameterCount) {
        result.append(" [parameters]");
    }

    if (!subcommands.isEmpty()) {
        result.append(" [subcommands]");
    }

    result.append("\n```\n");

    if (!parameters.isEmpty()) {
        if (getCommandName() == "hal") {
            result.append("#### Global Parameters\n");
        }

        for (ParameterDescription parameter : parameters) {
            if (GlobalOptions.isGlobalOption(parameter.getLongestName())) {
                // Omit printing global parameters for everything but the top-level command
                if (getCommandName() == "hal") {
                    parameterDoc(result, parameter);
                }
            }
        }

        result.append("\n");
    }

    if (parameters.size() > parameterCount) {
        result.append("#### Parameters\n");

        if (mainParameter != null) {
            result.append('`').append(getMainParameter().toUpperCase()).append('`').append(": ")
                    .append(mainParameter.getDescription()).append("\n");
        }

        for (ParameterDescription parameter : parameters) {
            if (!GlobalOptions.isGlobalOption(parameter.getLongestName())) {
                parameterDoc(result, parameter);
            }
        }

        result.append("\n");
    }

    if (!subcommands.isEmpty()) {
        result.append("#### Subcommands\n");

        List<String> keys = new ArrayList<>(subcommands.keySet());
        keys.sort(String::compareTo);

        for (String key : keys) {
            NestableCommand subcommand = subcommands.get(key);
            String modifiers = "";
            if (subcommand instanceof DeprecatedCommand) {
                modifiers += " _(Deprecated)_ ";
            }
            String shortDescription = subcommand.getShortDescription() != null
                    ? subcommand.getShortDescription()
                    : subcommand.getDescription();

            result.append(" * ").append("`").append(key).append("`").append(modifiers).append(": ")
                    .append(shortDescription).append("\n");
        }
    }

    result.append("\n---\n");
}

From source file:com.netflix.genie.web.services.impl.JobDirectoryServerServiceImpl.java

private void handleRequest(final URI baseUri, final String relativePath, final HttpServletRequest request,
        final HttpServletResponse response, final JobDirectoryManifest manifest, final URI jobDirectoryRoot)
        throws IOException, ServletException {
    log.debug("Handle request, baseUri: '{}', relpath: '{}', jobRootUri: '{}'", baseUri, relativePath,
            jobDirectoryRoot);/* w w  w. j av a2 s  .  com*/
    final JobDirectoryManifest.ManifestEntry entry;
    final Optional<JobDirectoryManifest.ManifestEntry> entryOptional = manifest.getEntry(relativePath);
    if (entryOptional.isPresent()) {
        entry = entryOptional.get();
    } else {
        log.error("No such entry in job manifest: {}", relativePath);
        response.sendError(HttpStatus.NOT_FOUND.value(), "Not found: " + relativePath);
        return;
    }

    if (entry.isDirectory()) {
        // For now maintain the V3 structure
        // TODO: Once we determine what we want for V4 use v3/v4 flags or some way to differentiate
        // TODO: there's no unit test covering this section
        final DefaultDirectoryWriter.Directory directory = new DefaultDirectoryWriter.Directory();
        final List<DefaultDirectoryWriter.Entry> files = Lists.newArrayList();
        final List<DefaultDirectoryWriter.Entry> directories = Lists.newArrayList();
        try {
            entry.getParent().ifPresent(parentPath -> {
                final JobDirectoryManifest.ManifestEntry parentEntry = manifest.getEntry(parentPath)
                        .orElseThrow(IllegalArgumentException::new);
                directory.setParent(createEntry(parentEntry, baseUri));
            });

            for (final String childPath : entry.getChildren()) {
                final JobDirectoryManifest.ManifestEntry childEntry = manifest.getEntry(childPath)
                        .orElseThrow(IllegalArgumentException::new);

                if (childEntry.isDirectory()) {
                    directories.add(this.createEntry(childEntry, baseUri));
                } else {
                    files.add(this.createEntry(childEntry, baseUri));
                }
            }
        } catch (final IllegalArgumentException iae) {
            log.error("Encountered unexpected problem traversing the manifest for directory entry {}", entry,
                    iae);
            response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value());
            return;
        }

        directories.sort(Comparator.comparing(DefaultDirectoryWriter.Entry::getName));
        files.sort(Comparator.comparing(DefaultDirectoryWriter.Entry::getName));

        directory.setDirectories(directories);
        directory.setFiles(files);

        final String accept = request.getHeader(HttpHeaders.ACCEPT);
        if (accept != null && accept.contains(MediaType.TEXT_HTML_VALUE)) {
            response.setContentType(MediaType.TEXT_HTML_VALUE);
            response.getOutputStream().write(DefaultDirectoryWriter.directoryToHTML(entry.getName(), directory)
                    .getBytes(StandardCharsets.UTF_8));
        } else {
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            GenieObjectMapper.getMapper().writeValue(response.getOutputStream(), directory);
        }
    } else {
        final URI location = jobDirectoryRoot.resolve(entry.getPath());
        log.debug("Get resource: {}", location);
        final Resource jobResource = this.resourceLoader.getResource(location.toString());
        // Every file really should have a media type but if not use text/plain
        final String mediaType = entry.getMimeType().orElse(MediaType.TEXT_PLAIN_VALUE);
        final ResourceHttpRequestHandler handler = this.genieResourceHandlerFactory.get(mediaType, jobResource);
        handler.handleRequest(request, response);
    }
}

From source file:org.fenixedu.qubdocs.ui.documenttemplates.AcademicServiceRequestTemplateController.java

@RequestMapping(value = _CREATECUSTOMTEMPLATE_URI, method = RequestMethod.GET)
public String createcustomtemplate(Model model) {
    model.addAttribute("AcademicServiceRequestTemplate_language_options", CoreConfiguration.supportedLocales());
    model.addAttribute("AcademicServiceRequestTemplate_serviceRequestType_options",
            org.fenixedu.academic.domain.serviceRequests.ServiceRequestType.findActive()
                    .sorted(Comparator.comparing(ServiceRequestType::getName)).collect(Collectors.toList()));

    return "qubdocsreports/documenttemplates/academicservicerequesttemplate/createcustomtemplate";
}

From source file:org.sleuthkit.autopsy.timeline.ui.detailview.EventDetailsChart.java

@Override
protected synchronized void layoutPlotChildren() {
    setCursor(Cursor.WAIT);// www  . ja v  a2  s .  co m
    maxY.set(0);
    if (bandByType.get()) {
        stripeNodeMap.values().stream().collect(Collectors.groupingBy(EventStripeNode::getEventType)).values()
                .forEach(inputNodes -> {
                    List<EventStripeNode> stripeNodes = inputNodes.stream()
                            .sorted(Comparator.comparing(EventStripeNode::getStartMillis))
                            .collect(Collectors.toList());

                    maxY.set(layoutEventBundleNodes(stripeNodes, maxY.get()));
                });
    } else {
        List<EventStripeNode> stripeNodes = stripeNodeMap.values().stream()
                .sorted(Comparator.comparing(EventStripeNode::getStartMillis)).collect(Collectors.toList());
        maxY.set(layoutEventBundleNodes(stripeNodes, 0));
    }
    layoutProjectionMap();
    setCursor(null);
}

From source file:uk.ac.cam.cl.dtg.isaac.api.managers.AssignmentManager.java

/**
 * Helper to build up the list of tokens for addToGroup email.
 *
 * @param userDTO - identity of user/*from   w w  w .  j a v  a 2  s  .  c  o  m*/
 * @param userGroup - group being added to.
 * @param groupOwner - Owner of the group
 * @param existingAssignments - Any existing assignments that have been set.
 * @return a map of string to string, with some values that may want to be shown in the email.
 * @throws SegueDatabaseException if we can't get the gameboard details.
 */
private Map<String, Object> prepareGroupWelcomeEmailTokenMap(final RegisteredUserDTO userDTO,
        final UserGroupDTO userGroup, final RegisteredUserDTO groupOwner,
        final List<AssignmentDTO> existingAssignments) throws SegueDatabaseException {
    Validate.notNull(userDTO);
    String groupOwnerName = "Unknown";

    if (groupOwner != null && groupOwner.getFamilyName() != null) {
        groupOwnerName = groupOwner.getFamilyName();
    }

    if (groupOwner != null && groupOwner.getGivenName() != null && !groupOwner.getGivenName().isEmpty()) {
        groupOwnerName = groupOwner.getGivenName().substring(0, 1) + ". " + groupOwnerName;
    }

    if (existingAssignments != null) {
        Collections.sort(existingAssignments, Comparator.comparing(AssignmentDTO::getCreationDate));
    }

    final DateFormat DATE_FORMAT = new SimpleDateFormat("dd/MM/yy HH:mm");
    StringBuilder htmlSB = new StringBuilder();
    StringBuilder plainTextSB = new StringBuilder();
    final String accountURL = String.format("https://%s/account", properties.getProperty(HOST_NAME));

    if (existingAssignments != null && existingAssignments.size() > 0) {
        htmlSB.append("Your teacher has assigned the following assignments:<br>");
        plainTextSB.append("Your teacher has assigned the following assignments:\n");

        for (int i = 0; i < existingAssignments.size(); i++) {
            GameboardDTO gameboard = gameManager.getGameboard(existingAssignments.get(i).getGameboardId());
            String gameboardName = existingAssignments.get(i).getGameboardId();
            if (gameboard != null && gameboard.getTitle() != null && !gameboard.getTitle().isEmpty()) {
                gameboardName = gameboard.getTitle();
            }

            String gameboardUrl = String.format("https://%s/#%s", properties.getProperty(HOST_NAME),
                    existingAssignments.get(i).getGameboardId());

            htmlSB.append(String.format("%d. <a href='%s'>%s</a> (set on %s)<br>", i + 1, gameboardUrl,
                    gameboardName, DATE_FORMAT.format(existingAssignments.get(i).getCreationDate())));

            plainTextSB.append(String.format("%d. %s (set on %s)\n", i + 1, gameboardName,
                    DATE_FORMAT.format(existingAssignments.get(i).getCreationDate())));
        }
    } else if (existingAssignments != null && existingAssignments.size() == 0) {
        htmlSB.append("No assignments have been set yet.<br>");
        plainTextSB.append("No assignments have been set yet.\n");
    }

    return new ImmutableMap.Builder<String, Object>()
            .put("teacherName", groupOwnerName == null ? "" : groupOwnerName).put("accountURL", accountURL)
            .put("assignmentsInfo", plainTextSB.toString()).put("assignmentsInfo_HTML", htmlSB.toString())
            .build();
}

From source file:org.codice.ddf.catalog.ui.metacard.MetacardApplication.java

@Override
public void init() {
    get("/metacardtype", (req, res) -> util.getJson(util.getMetacardTypeMap()));

    get("/metacard/:id", (req, res) -> {
        String id = req.params(":id");
        return util.metacardToJson(id);
    });/*from  w w w.j  a v  a  2 s  . c  o  m*/

    get("/metacard/:id/attribute/validation", (req, res) -> {
        String id = req.params(":id");
        return util.getJson(validator.getValidation(util.getMetacardById(id)));
    });

    get("/metacard/:id/validation", (req, res) -> {
        String id = req.params(":id");
        return util.getJson(validator.getFullValidation(util.getMetacardById(id)));
    });

    post("/prevalidate", APPLICATION_JSON, (req, res) -> {
        Map<String, Object> stringObjectMap = GSON.fromJson(util.safeGetBody(req), MAP_STRING_TO_OBJECT_TYPE);
        MetacardImpl metacard = new MetacardImpl();
        stringObjectMap.keySet().stream()
                .map(s -> new AttributeImpl(s, (List<Serializable>) stringObjectMap.get(s)))
                .forEach(metacard::setAttribute);
        return util.getJson(validator.getValidation(metacard));
    });

    post("/metacards", APPLICATION_JSON, (req, res) -> {
        List<String> ids = GSON.fromJson(util.safeGetBody(req), LIST_STRING);
        List<Metacard> metacards = util.getMetacardsWithTagById(ids, "*").entrySet().stream()
                .map(Map.Entry::getValue).map(Result::getMetacard).collect(Collectors.toList());

        return util.metacardsToJson(metacards);
    });

    delete("/metacards", APPLICATION_JSON, (req, res) -> {
        List<String> ids = GSON.fromJson(util.safeGetBody(req), LIST_STRING);
        DeleteResponse deleteResponse = catalogFramework
                .delete(new DeleteRequestImpl(new ArrayList<>(ids), Metacard.ID, null));
        if (deleteResponse.getProcessingErrors() != null && !deleteResponse.getProcessingErrors().isEmpty()) {
            res.status(500);
            return ImmutableMap.of("message", "Unable to archive metacards.");
        }

        return ImmutableMap.of("message", "Successfully archived metacards.");
    }, util::getJson);

    patch("/metacards", APPLICATION_JSON, (req, res) -> {
        String body = util.safeGetBody(req);
        List<MetacardChanges> metacardChanges = GSON.fromJson(body, METACARD_CHANGES_LIST_TYPE);

        UpdateResponse updateResponse = patchMetacards(metacardChanges, getSubjectIdentifier());
        if (updateResponse.getProcessingErrors() != null && !updateResponse.getProcessingErrors().isEmpty()) {
            res.status(500);
            return updateResponse.getProcessingErrors();
        }

        return body;
    });

    put("/validate/attribute/:attribute", TEXT_PLAIN, (req, res) -> {
        String attribute = req.params(":attribute");
        String value = util.safeGetBody(req);
        return util.getJson(validator.validateAttribute(attribute, value));
    });

    get("/history/:id", (req, res) -> {
        String id = req.params(":id");
        List<Result> queryResponse = getMetacardHistory(id);
        if (queryResponse.isEmpty()) {
            res.status(204);
            return "[]";
        }
        List<HistoryResponse> response = queryResponse.stream().map(Result::getMetacard)
                .map(mc -> new HistoryResponse(mc.getId(),
                        (String) mc.getAttribute(MetacardVersion.EDITED_BY).getValue(),
                        (Date) mc.getAttribute(MetacardVersion.VERSIONED_ON).getValue()))
                .sorted(Comparator.comparing(HistoryResponse::getVersioned)).collect(Collectors.toList());
        return util.getJson(response);
    });

    get("/history/revert/:id/:revertid", (req, res) -> {
        String id = req.params(":id");
        String revertId = req.params(":revertid");

        Metacard versionMetacard = util.getMetacardById(revertId);

        List<Result> queryResponse = getMetacardHistory(id);
        if (queryResponse == null || queryResponse.isEmpty()) {
            throw new NotFoundException("Could not find metacard with id: " + id);
        }

        Optional<Metacard> contentVersion = queryResponse.stream().map(Result::getMetacard)
                .filter(mc -> getVersionedOnDate(mc).isAfter(getVersionedOnDate(versionMetacard))
                        || getVersionedOnDate(mc).equals(getVersionedOnDate(versionMetacard)))
                .filter(mc -> CONTENT_ACTIONS.contains(Action.ofMetacard(mc)))
                .filter(mc -> mc.getResourceURI() != null)
                .filter(mc -> ContentItem.CONTENT_SCHEME.equals(mc.getResourceURI().getScheme()))
                .sorted(Comparator.comparing((Metacard mc) -> util
                        .parseToDate(mc.getAttribute(MetacardVersion.VERSIONED_ON).getValue())))
                .findFirst();

        if (!contentVersion.isPresent()) {
            /* no content versions, just restore metacard */
            revertMetacard(versionMetacard, id, false);
        } else {
            revertContentandMetacard(contentVersion.get(), versionMetacard, id);
        }
        return util.metacardToJson(MetacardVersionImpl.toMetacard(versionMetacard, types));
    });

    get("/associations/:id", (req, res) -> {
        String id = req.params(":id");
        return util.getJson(associated.getAssociations(id));
    });

    put("/associations/:id", (req, res) -> {
        String id = req.params(":id");
        String body = util.safeGetBody(req);
        List<Associated.Edge> edges = GSON.fromJson(body, ASSOCIATED_EDGE_LIST_TYPE);
        associated.putAssociations(id, edges);
        return body;
    });

    post("/subscribe/:id", (req, res) -> {
        String userid = getSubjectIdentifier();
        String email = getSubjectEmail();
        if (isEmpty(email)) {
            throw new NotFoundException(
                    "Unable to subscribe to workspace, " + userid + " has no email address.");
        }
        String id = req.params(":id");
        subscriptions.addEmail(id, email);
        return ImmutableMap.of("message", String.format("Successfully subscribed to id = %s.", id));
    }, util::getJson);

    post("/unsubscribe/:id", (req, res) -> {
        String userid = getSubjectIdentifier();
        String email = getSubjectEmail();
        if (isEmpty(email)) {
            throw new NotFoundException(
                    "Unable to un-subscribe from workspace, " + userid + " has no email address.");
        }
        String id = req.params(":id");
        if (StringUtils.isEmpty(req.body())) {
            subscriptions.removeEmail(id, email);
            return ImmutableMap.of("message", String.format("Successfully un-subscribed to id = %s.", id));
        } else {
            String body = req.body();
            AttributeChange attributeChange = GSON.fromJson(body, ATTRIBUTE_CHANGE_TYPE);
            subscriptions.removeEmails(id, new HashSet<>(attributeChange.getValues()));
            return ImmutableMap.of("message", String.format("Successfully un-subscribed emails %s id = %s.",
                    attributeChange.getValues().toString(), id));
        }
    }, util::getJson);

    get("/workspaces/:id", (req, res) -> {
        String id = req.params(":id");
        String email = getSubjectEmail();
        Metacard metacard = util.getMetacardById(id);

        // NOTE: the isEmpty is to guard against users with no email (such as guest).
        boolean isSubscribed = !isEmpty(email) && subscriptions.getEmails(metacard.getId()).contains(email);

        return ImmutableMap.builder().putAll(transformer.transform(metacard)).put("subscribed", isSubscribed)
                .build();
    }, util::getJson);

    get("/workspaces", (req, res) -> {
        String email = getSubjectEmail();
        // NOTE: the isEmpty is to guard against users with no email (such as guest).
        Set<String> ids = isEmpty(email) ? Collections.emptySet() : subscriptions.getSubscriptions(email);

        return util.getMetacardsByTag(WorkspaceConstants.WORKSPACE_TAG).entrySet().stream()
                .map(Map.Entry::getValue).map(Result::getMetacard).map(metacard -> {
                    boolean isSubscribed = ids.contains(metacard.getId());
                    try {
                        return ImmutableMap.builder().putAll(transformer.transform(metacard))
                                .put("subscribed", isSubscribed).build();
                    } catch (RuntimeException e) {
                        LOGGER.debug(
                                "Could not transform metacard. WARNING: This indicates there is invalid data in the system. Metacard title: '{}', id:'{}'",
                                metacard.getTitle(), metacard.getId(), e);
                    }
                    return null;
                }).filter(Objects::nonNull).collect(Collectors.toList());
    }, util::getJson);

    post("/workspaces", APPLICATION_JSON, (req, res) -> {
        Map<String, Object> incoming = GSON.fromJson(util.safeGetBody(req), MAP_STRING_TO_OBJECT_TYPE);

        List<Metacard> queries = ((List<Map<String, Object>>) incoming
                .getOrDefault(WorkspaceConstants.WORKSPACE_QUERIES, Collections.emptyList())).stream()
                        .map(transformer::transform).collect(Collectors.toList());

        queryMetacardsHandler.create(Collections.emptyList(), queries);

        Metacard saved = saveMetacard(transformer.transform(incoming));
        Map<String, Object> response = transformer.transform(saved);

        res.status(201);
        return util.getJson(response);
    });

    put("/workspaces/:id", APPLICATION_JSON, (req, res) -> {
        String id = req.params(":id");

        WorkspaceMetacardImpl existingWorkspace = workspaceService.getWorkspaceMetacard(id);
        List<String> existingQueryIds = existingWorkspace.getQueries();

        Map<String, Object> updatedWorkspace = GSON.fromJson(util.safeGetBody(req), MAP_STRING_TO_OBJECT_TYPE);

        List<Metacard> updatedQueryMetacards = ((List<Map<String, Object>>) updatedWorkspace
                .getOrDefault("queries", Collections.emptyList())).stream().map(transformer::transform)
                        .collect(Collectors.toList());

        List<String> updatedQueryIds = updatedQueryMetacards.stream().map(Metacard::getId)
                .collect(Collectors.toList());

        List<QueryMetacardImpl> existingQueryMetacards = workspaceService.getQueryMetacards(existingWorkspace);

        queryMetacardsHandler.create(existingQueryIds, updatedQueryMetacards);
        queryMetacardsHandler.delete(existingQueryIds, updatedQueryIds);
        queryMetacardsHandler.update(existingQueryIds, existingQueryMetacards, updatedQueryMetacards);

        List<Map<String, String>> queryIdModel = updatedQueryIds.stream()
                .map(queryId -> ImmutableMap.of("id", queryId)).collect(Collectors.toList());

        updatedWorkspace.put("queries", queryIdModel);
        Metacard metacard = transformer.transform(updatedWorkspace);
        metacard.setAttribute(new AttributeImpl(Core.ID, id));
        Metacard updated = updateMetacard(id, metacard);

        return transformer.transform(updated);
    }, util::getJson);

    delete("/workspaces/:id", APPLICATION_JSON, (req, res) -> {
        String id = req.params(":id");
        WorkspaceMetacardImpl workspace = workspaceService.getWorkspaceMetacard(id);

        String[] queryIds = workspace.getQueries().toArray(new String[0]);

        if (queryIds.length > 0) {
            catalogFramework.delete(new DeleteRequestImpl(queryIds));
        }

        catalogFramework.delete(new DeleteRequestImpl(id));

        subscriptions.removeSubscriptions(id);
        return ImmutableMap.of("message", "Successfully deleted.");
    }, util::getJson);

    get("/workspaces/:id/queries", (req, res) -> {
        String workspaceId = req.params(":id");
        WorkspaceMetacardImpl workspace = workspaceService.getWorkspaceMetacard(workspaceId);

        List<String> queryIds = workspace.getQueries();

        return util.getMetacardsWithTagById(queryIds, QUERY_TAG).values().stream().map(Result::getMetacard)
                .map(transformer::transform).collect(Collectors.toList());
    }, util::getJson);

    get("/enumerations/metacardtype/:type", APPLICATION_JSON, (req, res) -> {
        return util.getJson(enumExtractor.getEnumerations(req.params(":type")));
    });

    get("/enumerations/attribute/:attribute", APPLICATION_JSON, (req, res) -> {
        return util.getJson(enumExtractor.getAttributeEnumerations(req.params(":attribute")));
    });

    get("/localcatalogid", (req, res) -> {
        return String.format("{\"%s\":\"%s\"}", "local-catalog-id", catalogFramework.getId());
    });

    post("/transform/csv", APPLICATION_JSON, (req, res) -> {
        String body = util.safeGetBody(req);
        CsvTransform queryTransform = GSON.fromJson(body, CsvTransform.class);
        Map<String, Object> transformMap = GSON.fromJson(body, MAP_STRING_TO_OBJECT_TYPE);
        queryTransform.setMetacards((List<Map<String, Object>>) transformMap.get("metacards"));

        List<Result> metacards = queryTransform.getTransformedMetacards(types, attributeRegistry).stream()
                .map(ResultImpl::new).collect(Collectors.toList());

        Set<String> matchedHiddenFields = Collections.emptySet();
        if (queryTransform.isApplyGlobalHidden()) {
            matchedHiddenFields = getHiddenFields(metacards);
        }

        SourceResponseImpl response = new SourceResponseImpl(null, metacards, Long.valueOf(metacards.size()));

        Map<String, Serializable> arguments = ImmutableMap.<String, Serializable>builder()
                .put("hiddenFields",
                        new HashSet<>(Sets.union(matchedHiddenFields, queryTransform.getHiddenFields())))
                .put("columnOrder", new ArrayList<>(queryTransform.getColumnOrder()))
                .put("aliases", new HashMap<>(queryTransform.getColumnAliasMap())).build();

        BinaryContent content = csvQueryResponseTransformer.transform(response, arguments);

        String acceptEncoding = req.headers("Accept-Encoding");
        // Very naive way to handle accept encoding, does not respect full spec
        boolean shouldGzip = StringUtils.isNotBlank(acceptEncoding)
                && acceptEncoding.toLowerCase().contains("gzip");

        // Respond with content
        res.type("text/csv");
        String attachment = String.format("attachment;filename=export-%s.csv", Instant.now().toString());
        res.header("Content-Disposition", attachment);
        if (shouldGzip) {
            res.raw().addHeader("Content-Encoding", "gzip");
        }

        try ( //
                OutputStream servletOutputStream = res.raw().getOutputStream();
                InputStream resultStream = content.getInputStream()) {
            if (shouldGzip) {
                try (OutputStream gzipServletOutputStream = new GZIPOutputStream(servletOutputStream)) {
                    IOUtils.copy(resultStream, gzipServletOutputStream);
                }
            } else {
                IOUtils.copy(resultStream, servletOutputStream);
            }
        }
        return "";
    });

    post("/annotations", (req, res) -> {
        Map<String, Object> incoming = GSON.fromJson(util.safeGetBody(req), MAP_STRING_TO_OBJECT_TYPE);
        String workspaceId = incoming.get("workspace").toString();
        String queryId = incoming.get("parent").toString();
        String annotation = incoming.get("note").toString();
        String user = getSubjectIdentifier();
        if (user == null) {
            res.status(401);
            return util.getResponseWrapper(ERROR_RESPONSE_TYPE,
                    "You are not authorized to create notes! A user email is required. "
                            + "Please ensure you are logged in and/or have a valid email registered in the system.");
        }
        if (StringUtils.isBlank(annotation)) {
            res.status(400);
            return util.getResponseWrapper(ERROR_RESPONSE_TYPE, "No annotation!");
        }
        NoteMetacard noteMetacard = new NoteMetacard(queryId, user, annotation);

        Metacard workspaceMetacard = util.findWorkspace(workspaceId);

        if (workspaceMetacard == null) {
            res.status(404);
            return util.getResponseWrapper(ERROR_RESPONSE_TYPE, "Cannot find the workspace metacard!");
        }

        util.copyAttributes(workspaceMetacard, SECURITY_ATTRIBUTES, noteMetacard);

        Metacard note = saveMetacard(noteMetacard);

        SecurityLogger.auditWarn("Attaching an annotation to a resource: resource={} annotation={}",
                SecurityUtils.getSubject(), workspaceId, noteMetacard.getId());

        Map<String, String> responseNote = noteUtil.getResponseNote(note);
        if (responseNote == null) {
            res.status(500);
            return util.getResponseWrapper(ERROR_RESPONSE_TYPE, "Cannot serialize note metacard to json!");
        }
        return util.getResponseWrapper(SUCCESS_RESPONSE_TYPE, util.getJson(responseNote));
    });

    get("/annotations/:queryid", (req, res) -> {
        String queryId = req.params(":queryid");

        List<Metacard> retrievedMetacards = noteUtil.getAssociatedMetacardsByTwoAttributes(
                NoteConstants.PARENT_ID, Core.METACARD_TAGS, queryId, "note");
        ArrayList<String> getResponse = new ArrayList<>();
        retrievedMetacards.sort(Comparator.comparing(Metacard::getCreatedDate));
        for (Metacard metacard : retrievedMetacards) {
            Map<String, String> responseNote = noteUtil.getResponseNote(metacard);
            if (responseNote != null) {
                getResponse.add(util.getJson(responseNote));
            }
        }
        return util.getResponseWrapper(SUCCESS_RESPONSE_TYPE, getResponse.toString());
    });

    put("/annotations/:id", APPLICATION_JSON, (req, res) -> {
        Map<String, Object> incoming = GSON.fromJson(util.safeGetBody(req), MAP_STRING_TO_OBJECT_TYPE);
        String noteMetacardId = req.params(":id");
        String note = incoming.get("note").toString();
        Metacard metacard;
        try {
            metacard = util.getMetacardById(noteMetacardId);
        } catch (NotFoundException e) {
            LOGGER.debug("Note metacard was not found for updating. id={}", noteMetacardId);
            res.status(404);
            return util.getResponseWrapper(ERROR_RESPONSE_TYPE, "Note metacard was not found!");
        }

        Attribute attribute = metacard.getAttribute(Core.METACARD_OWNER);
        if (attribute != null && attribute.getValue() != null
                && !attribute.getValue().equals(getSubjectEmail())) {
            res.status(401);
            return util.getResponseWrapper(ERROR_RESPONSE_TYPE, "Owner of note metacard is invalid!");
        }
        metacard.setAttribute(new AttributeImpl(NoteConstants.COMMENT, note));
        metacard = updateMetacard(metacard.getId(), metacard);
        Map<String, String> responseNote = noteUtil.getResponseNote(metacard);
        return util.getResponseWrapper(SUCCESS_RESPONSE_TYPE, util.getJson(responseNote));
    });

    delete("/annotations/:id", (req, res) -> {
        String noteToDeleteMetacardId = req.params(":id");
        Metacard metacard;
        try {
            metacard = util.getMetacardById(noteToDeleteMetacardId);
        } catch (NotFoundException e) {
            LOGGER.debug("Note metacard was not found for deleting. id={}", noteToDeleteMetacardId);
            res.status(404);
            return util.getResponseWrapper(ERROR_RESPONSE_TYPE, "Note metacard was not found!");
        }
        Attribute attribute = metacard.getAttribute(Core.METACARD_OWNER);
        if (attribute != null && attribute.getValue() != null
                && !attribute.getValue().equals(getSubjectEmail())) {
            res.status(401);
            return util.getResponseWrapper(ERROR_RESPONSE_TYPE, "Owner of note metacard is invalid!");
        }
        DeleteResponse deleteResponse = catalogFramework.delete(new DeleteRequestImpl(noteToDeleteMetacardId));
        if (deleteResponse.getDeletedMetacards() != null && !deleteResponse.getDeletedMetacards().isEmpty()) {
            Map<String, String> responseNote = noteUtil
                    .getResponseNote(deleteResponse.getDeletedMetacards().get(0));
            return util.getResponseWrapper(SUCCESS_RESPONSE_TYPE, util.getJson(responseNote));
        }
        res.status(500);
        return util.getResponseWrapper(ERROR_RESPONSE_TYPE, "Could not delete note metacard!");
    });

    after((req, res) -> {
        res.type(APPLICATION_JSON);
    });

    exception(IngestException.class, (ex, req, res) -> {
        LOGGER.debug("Failed to ingest metacard", ex);
        res.status(404);
        res.header(CONTENT_TYPE, APPLICATION_JSON);
        res.body(util.getJson(ImmutableMap.of("message", UPDATE_ERROR_MESSAGE)));
    });

    exception(NotFoundException.class, (ex, req, res) -> {
        LOGGER.debug("Failed to find metacard.", ex);
        res.status(404);
        res.header(CONTENT_TYPE, APPLICATION_JSON);
        res.body(util.getJson(ImmutableMap.of("message", ex.getMessage())));
    });

    exception(NumberFormatException.class, (ex, req, res) -> {
        res.status(400);
        res.header(CONTENT_TYPE, APPLICATION_JSON);
        res.body(util.getJson(ImmutableMap.of("message", "Invalid values for numbers")));
    });

    exception(EntityTooLargeException.class, util::handleEntityTooLargeException);

    exception(IOException.class, util::handleIOException);

    exception(RuntimeException.class, util::handleRuntimeException);
}

From source file:org.cgiar.ccafs.marlo.action.powb.ToCAdjustmentsAction.java

@Override
public void prepare() throws Exception {
    // Get current CRP
    loggedCrp = (GlobalUnit) this.getSession().get(APConstants.SESSION_CRP);
    loggedCrp = crpManager.getGlobalUnitById(loggedCrp.getId());
    Phase phase = this.getActualPhase();

    // If there is a history version being loaded
    if (this.getRequest().getParameter(APConstants.TRANSACTION_ID) != null) {
        transaction = StringUtils.trim(this.getRequest().getParameter(APConstants.TRANSACTION_ID));
        PowbSynthesis history = (PowbSynthesis) auditLogManager.getHistory(transaction);
        if (history != null) {
            powbSynthesis = history;/*from   www .j a  v a 2 s . c o  m*/
            powbSynthesisID = powbSynthesis.getId();
        } else {
            this.transaction = null;
            this.setTransaction("-1");
        }
    } else {
        // Get Liaison institution ID Parameter
        try {
            liaisonInstitutionID = Long.parseLong(StringUtils
                    .trim(this.getRequest().getParameter(APConstants.LIAISON_INSTITUTION_REQUEST_ID)));
        } catch (NumberFormatException e) {
            User user = userManager.getUser(this.getCurrentUser().getId());
            if (user.getLiasonsUsers() != null || !user.getLiasonsUsers().isEmpty()) {
                List<LiaisonUser> liaisonUsers = new ArrayList<>(user.getLiasonsUsers().stream()
                        .filter(lu -> lu.isActive() && lu.getLiaisonInstitution().isActive()
                                && lu.getLiaisonInstitution().getCrp().getId() == loggedCrp.getId()
                                && lu.getLiaisonInstitution().getInstitution() == null)
                        .collect(Collectors.toList()));
                if (!liaisonUsers.isEmpty()) {
                    boolean isLeader = false;
                    for (LiaisonUser liaisonUser : liaisonUsers) {
                        LiaisonInstitution institution = liaisonUser.getLiaisonInstitution();
                        if (institution.isActive()) {
                            if (institution.getCrpProgram() != null) {
                                if (institution.getCrpProgram()
                                        .getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue()) {
                                    liaisonInstitutionID = institution.getId();
                                    isLeader = true;
                                    break;
                                }
                            } else {
                                if (institution.getAcronym().equals("PMU")) {
                                    liaisonInstitutionID = institution.getId();
                                    isLeader = true;
                                    break;
                                }
                            }
                        }
                    }
                    if (!isLeader) {
                        liaisonInstitutionID = this.firstFlagship();
                    }
                } else {
                    liaisonInstitutionID = this.firstFlagship();
                }
            } else {
                liaisonInstitutionID = this.firstFlagship();
            }
        }

        try {
            powbSynthesisID = Long
                    .parseLong(StringUtils.trim(this.getRequest().getParameter(APConstants.POWB_SYNTHESIS_ID)));
            powbSynthesis = powbSynthesisManager.getPowbSynthesisById(powbSynthesisID);

            if (!powbSynthesis.getPhase().equals(phase)) {
                powbSynthesis = powbSynthesisManager.findSynthesis(phase.getId(), liaisonInstitutionID);
                if (powbSynthesis == null) {
                    powbSynthesis = this.createPowbSynthesis(phase.getId(), liaisonInstitutionID);
                }
                powbSynthesisID = powbSynthesis.getId();
            }
        } catch (Exception e) {

            powbSynthesis = powbSynthesisManager.findSynthesis(phase.getId(), liaisonInstitutionID);
            if (powbSynthesis == null) {
                powbSynthesis = this.createPowbSynthesis(phase.getId(), liaisonInstitutionID);
            }
            powbSynthesisID = powbSynthesis.getId();

        }
    }

    if (powbSynthesis != null) {

        PowbSynthesis powbSynthesisDB = powbSynthesisManager.getPowbSynthesisById(powbSynthesisID);
        powbSynthesisID = powbSynthesisDB.getId();
        liaisonInstitutionID = powbSynthesisDB.getLiaisonInstitution().getId();
        liaisonInstitution = liaisonInstitutionManager.getLiaisonInstitutionById(liaisonInstitutionID);

        Path path = this.getAutoSaveFilePath();
        // Verify if there is a Draft file
        if (path.toFile().exists() && this.getCurrentUser().isAutoSave()) {
            BufferedReader reader;
            reader = new BufferedReader(new FileReader(path.toFile()));
            Gson gson = new GsonBuilder().create();
            JsonObject jReader = gson.fromJson(reader, JsonObject.class);
            AutoSaveReader autoSaveReader = new AutoSaveReader();
            powbSynthesis = (PowbSynthesis) autoSaveReader.readFromJson(jReader);
            powbSynthesisID = powbSynthesis.getId();
            this.setDraft(true);
            reader.close();
        } else {
            this.setDraft(false);
            // Check if ToC relation is null -create it
            if (powbSynthesis.getPowbToc() == null) {
                PowbToc toc = new PowbToc();
                // create one to one relation
                powbSynthesis.setPowbToc(toc);
                toc.setPowbSynthesis(powbSynthesis);
                // save the changes
                powbSynthesis = powbSynthesisManager.savePowbSynthesis(powbSynthesis);
            }
        }
    }

    // Check if the pow toc has file
    if (this.isPMU()) {
        if (powbSynthesis.getPowbToc().getFile() != null) {
            if (powbSynthesis.getPowbToc().getFile().getId() != null) {
                powbSynthesis.getPowbToc()
                        .setFile(fileDBManager.getFileDBById(powbSynthesis.getPowbToc().getFile().getId()));
            } else {
                powbSynthesis.getPowbToc().setFile(null);
            }
        }
    } else {
        powbSynthesis.getPowbToc().setFile(null);
    }

    // Get the list of liaison institutions Flagships and PMU.
    liaisonInstitutions = loggedCrp.getLiaisonInstitutions().stream()
            .filter(c -> c.getCrpProgram() != null && c.isActive()
                    && c.getCrpProgram().getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue())
            .collect(Collectors.toList());
    liaisonInstitutions.sort(Comparator.comparing(LiaisonInstitution::getAcronym));

    // Setup the PUM ToC Table
    if (this.isPMU()) {
        this.tocList(phase.getId());
    }
    // ADD PMU as liasion Institutio too
    liaisonInstitutions.addAll(loggedCrp.getLiaisonInstitutions().stream()
            .filter(c -> c.getCrpProgram() == null && c.isActive() && c.getAcronym().equals("PMU"))
            .collect(Collectors.toList()));

    // Base Permission
    String params[] = { loggedCrp.getAcronym(), powbSynthesis.getId() + "" };
    this.setBasePermission(this.getText(Permission.POWB_SYNTHESIS_TOC_BASE_PERMISSION, params));

    if (this.isHttpPost()) {
        powbSynthesis.getPowbToc().setFile(null);
    }
}

From source file:sbu.srl.rolextract.SpockDataReader.java

public static void generateSEMAFORFrameAnnotation(ArrayList<Sentence> arrSentence, String frameElementsFileName,
        String rawSentencesFileName, int offset) throws FileNotFoundException {
    Set<String> roles = getRoleLabels(arrSentence); // without NONE!
    PrintWriter writer = new PrintWriter(frameElementsFileName);
    PrintWriter sentWriter = new PrintWriter(rawSentencesFileName);
    int sentCounter = 0;
    //int offset = 2780;
    System.out.println("Generating semafor frame annotation , size :" + arrSentence.size());
    for (int i = 0; i < arrSentence.size(); i++) {
        Sentence currentSentence = arrSentence.get(i);
        if (currentSentence.isAnnotated()) {
            // Is there a positive role?
            int cntRole = 0; // Number of roles
            String frame = currentSentence.getProcessName();
            String lexicalUnitFrames = currentSentence.getLexicalUnitFrame();
            String lexicalUnitIndexRange = currentSentence.getLexicalUnitFrameRange();
            String formLexicalUnitFrame = currentSentence.getLexicalUnitFormFrame();

            StringBuilder roleSpanStrBuilder = new StringBuilder();
            for (String role : roles) {
                ArrayList<ArgumentSpan> spans = currentSentence.getMultiClassAnnotatedArgumentSpan(role, -1);
                if (!spans.isEmpty()) {
                    cntRole++;//  w  ww. j  a  va 2s .  c  o m
                    ArgumentSpan maxSpan = spans.stream()
                            .max(Comparator.comparing(arg -> arg.getEndIdx() - arg.getStartIdx() + 1)).get();
                    if (maxSpan.getStartIdx() != maxSpan.getEndIdx()) {
                        roleSpanStrBuilder.append(role).append("\t")
                                .append((maxSpan.getStartIdx() - 1) + ":" + (maxSpan.getEndIdx() - 1))
                                .append("\t");
                    } else {
                        roleSpanStrBuilder.append(role).append("\t").append((maxSpan.getStartIdx() - 1))
                                .append("\t");
                    }
                }
                // if there is more than one then select the longer one
                // group by start + end id
                // count number of roles
                // lexical unit == process name
                // sentence number
                // role span pairs
            }
            if (cntRole > 0) {
                StringBuilder frameElementsStrB = new StringBuilder();
                frameElementsStrB.append(cntRole + +1).append("\t").append(frame).append("\t")
                        .append(lexicalUnitFrames).append("\t").append(lexicalUnitIndexRange).append("\t")
                        .append(formLexicalUnitFrame).append("\t").append((sentCounter + offset)).append("\t")
                        .append(roleSpanStrBuilder.toString().trim());
                writer.println(frameElementsStrB.toString());
                sentWriter.println(currentSentence.getRawText().trim());
                sentCounter++;
            }
        }
    }
    writer.close();
    sentWriter.close();
}