Example usage for java.util Map getOrDefault

List of usage examples for java.util Map getOrDefault

Introduction

In this page you can find the example usage for java.util Map getOrDefault.

Prototype

default V getOrDefault(Object key, V defaultValue) 

Source Link

Document

Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.

Usage

From source file:org.keycloak.testsuite.admin.client.authorization.ClaimInformationPointProviderTest.java

private Request createHttpRequest(Map<String, List<String>> headers, InputStream requestBody) {
    Map<String, List<String>> queryParameter = new HashMap<>();

    queryParameter.put("a", Arrays.asList("parameter-a"));

    headers.put("b", Arrays.asList("header-b"));

    Map<String, Cookie> cookies = new HashMap<>();

    cookies.put("c", new Cookie("c", "cookie-c", 1, "localhost", "/"));

    return new Request() {

        private InputStream inputStream;

        @Override//from  w w w.ja  v a  2s .co  m
        public String getMethod() {
            return "GET";
        }

        @Override
        public String getURI() {
            return "/app/request-uri";
        }

        @Override
        public String getRelativePath() {
            return "/request-relative-path";
        }

        @Override
        public boolean isSecure() {
            return true;
        }

        @Override
        public String getFirstParam(String param) {
            List<String> values = queryParameter.getOrDefault(param, Collections.emptyList());

            if (!values.isEmpty()) {
                return values.get(0);
            }

            return null;
        }

        @Override
        public String getQueryParamValue(String param) {
            return getFirstParam(param);
        }

        @Override
        public Cookie getCookie(String cookieName) {
            return cookies.get(cookieName);
        }

        @Override
        public String getHeader(String name) {
            List<String> headers = getHeaders(name);

            if (!headers.isEmpty()) {
                return headers.get(0);
            }

            return null;
        }

        @Override
        public List<String> getHeaders(String name) {
            return headers.getOrDefault(name, Collections.emptyList());
        }

        @Override
        public InputStream getInputStream() {
            return getInputStream(false);
        }

        @Override
        public InputStream getInputStream(boolean buffer) {
            if (requestBody == null) {
                return new ByteArrayInputStream(new byte[] {});
            }

            if (inputStream != null) {
                return inputStream;
            }

            if (buffer) {
                return inputStream = new BufferedInputStream(requestBody);
            }

            return requestBody;
        }

        @Override
        public String getRemoteAddr() {
            return "user-remote-addr";
        }

        @Override
        public void setError(AuthenticationError error) {

        }

        @Override
        public void setError(LogoutError error) {

        }
    };
}

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  www . j a  va  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:io.dockstore.webservice.helpers.GitHubSourceCodeRepo.java

@Override
public Workflow getNewWorkflow(String repositoryId, Optional<Workflow> existingWorkflow) {
    //TODO: need to add pass-through when paths are custom
    RepositoryId id = RepositoryId.createFromId(repositoryId);
    try {/*from  w  ww  . j ava  2s. c  o m*/
        final Repository repository = service.getRepository(id);
        LOG.info(gitUsername + ": Looking at repo: " + repository.getGitUrl());
        Workflow workflow = new Workflow();
        workflow.setOrganization(repository.getOwner().getLogin());
        workflow.setRepository(repository.getName());
        workflow.setGitUrl(repository.getGitUrl());
        workflow.setLastUpdated(new Date());
        // make sure path is constructed

        if (!existingWorkflow.isPresent()) {
            // when there is no existing workflow at all, just return a stub workflow. Also set descriptor type to default cwl.
            workflow.setDescriptorType("cwl");
            return workflow;
        }
        if (existingWorkflow.get().getMode() == WorkflowMode.STUB) {
            // when there is an existing stub workflow, just return the new stub as well
            return workflow;
        }
        workflow.setMode(WorkflowMode.FULL);

        // if it exists, extract paths from the previous workflow entry
        Map<String, String> existingDefaults = new HashMap<>();
        if (existingWorkflow.isPresent()) {
            existingWorkflow.get().getWorkflowVersions().forEach(existingVersion -> existingDefaults
                    .put(existingVersion.getReference(), existingVersion.getWorkflowPath()));
            copyWorkflow(existingWorkflow.get(), workflow);
        }

        // when getting a full workflow, look for versions and check each version for valid workflows
        List<String> references = new ArrayList<>();
        service.getBranches(id).forEach(branch -> references.add(branch.getName()));
        service.getTags(id).forEach(tag -> references.add(tag.getName()));
        for (String ref : references) {
            LOG.info(gitUsername + ": Looking at reference: " + ref);
            WorkflowVersion version = new WorkflowVersion();
            version.setName(ref);
            version.setReference(ref);
            version.setValid(false);

            // determine workflow version from previous
            String calculatedPath = existingDefaults.getOrDefault(ref,
                    existingWorkflow.get().getDefaultWorkflowPath());
            version.setWorkflowPath(calculatedPath);

            // Get relative path of main workflow descriptor to find relative paths
            String[] path = calculatedPath.split("/");
            String basepath = "";
            for (int i = 0; i < path.length - 1; i++) {
                basepath += path[i] + "/";
            }

            ArrayList<String> importPaths;
            Set<SourceFile> sourceFileSet = new HashSet<>();

            //TODO: is there a case-insensitive endsWith?
            if (calculatedPath.endsWith(".cwl") || calculatedPath.endsWith(".CWL")) {
                // look for workflow file
                try {
                    final List<RepositoryContents> cwlContents = cService.getContents(id, calculatedPath, ref);
                    if (cwlContents != null && cwlContents.size() > 0) {
                        String content = extractGitHubContents(cwlContents);
                        if (content.contains("class: Workflow")) {
                            // if we have a valid workflow document
                            SourceFile file = new SourceFile();
                            file.setType(SourceFile.FileType.DOCKSTORE_CWL);
                            file.setContent(content);
                            file.setPath(calculatedPath);
                            version.getSourceFiles().add(file);
                            final File tempDesc = File.createTempFile("temp", ".cwl", Files.createTempDir());
                            Files.write(content, tempDesc, StandardCharsets.UTF_8);
                            importPaths = getCwlImports(tempDesc);
                            for (String importPath : importPaths) {
                                LOG.info(gitUsername + ": Grabbing file " + basepath + importPath);
                                SourceFile importFile = new SourceFile();
                                importFile.setContent(extractGitHubContents(
                                        cService.getContents(id, basepath + importPath, ref)));
                                importFile.setPath(basepath + importPath);
                                importFile.setType(SourceFile.FileType.DOCKSTORE_CWL);
                                sourceFileSet.add(importFile);
                            }
                        }
                    }

                } catch (IOException ex) {
                    LOG.info(gitUsername + ": Error getting contents of file.");
                } catch (Exception ex) {
                    LOG.info(gitUsername + ": " + workflow.getDefaultWorkflowPath() + " on " + ref
                            + " was not valid CWL workflow");
                }
            } else {
                try {
                    final List<RepositoryContents> wdlContents = cService.getContents(id, calculatedPath, ref);
                    if (wdlContents != null && wdlContents.size() > 0) {
                        String content = extractGitHubContents(wdlContents);

                        final NamespaceWithWorkflow nameSpaceWithWorkflow = NamespaceWithWorkflow.load(content);
                        if (nameSpaceWithWorkflow != null) {
                            // if we have a valid workflow document
                            SourceFile file = new SourceFile();
                            file.setType(SourceFile.FileType.DOCKSTORE_WDL);
                            file.setContent(content);
                            file.setPath(calculatedPath);
                            version.getSourceFiles().add(file);
                            final File tempDesc = File.createTempFile("temp", ".wdl", Files.createTempDir());
                            Files.write(content, tempDesc, StandardCharsets.UTF_8);
                            importPaths = getWdlImports(tempDesc);
                            for (String importPath : importPaths) {
                                LOG.info(gitUsername + ": Grabbing file " + importPath);
                                SourceFile importFile = new SourceFile();
                                importFile.setContent(extractGitHubContents(
                                        cService.getContents(id, basepath + importPath, ref)));
                                importFile.setPath(basepath + importPath);
                                importFile.setType(SourceFile.FileType.DOCKSTORE_WDL);
                                sourceFileSet.add(importFile);
                            }
                        }
                    }
                } catch (Exception ex) {
                    LOG.info(
                            gitUsername + ": " + calculatedPath + " on " + ref + " was not valid WDL workflow");
                }
            }

            if (version.getSourceFiles().size() > 0) {
                version.setValid(true);
            }

            // add extra source files here
            if (sourceFileSet.size() > 0) {
                version.getSourceFiles().addAll(sourceFileSet);
            }

            workflow.addWorkflowVersion(version);
        }
        return workflow;
    } catch (IOException e) {
        LOG.info(gitUsername + ": Cannot getNewWorkflow {}");
        return null;
    }
}

From source file:com.baifendian.swordfish.common.utils.graph.Graph.java

/**
 *  topological ?//from w  w  w.  j  a  v  a 2 s. c  om
 *
 * @return key ?, ? true, () false, value  topology sort
 */
private Map.Entry<Boolean, List<VK>> topologicalSortImpl() {
    List<VK> sort = new ArrayList<>();
    Queue<VK> zeroVertex = new LinkedList<>();
    Map<VK, Integer> indegrees = new HashMap<>();

    synchronized (this) {
        // ? vertex , ??
        for (Map.Entry<VK, VD> id2Vertex : vertices.entrySet()) {
            VK key = id2Vertex.getKey();
            int inDegree = getIndegree(key);

            if (inDegree == 0) {
                sort.add(key);
                zeroVertex.add(key);
            } else {
                indegrees.put(key, inDegree);
            }
        }

        //  topology ,  0 , ??
        while (!zeroVertex.isEmpty()) {
            VK key = zeroVertex.poll();
            Collection<VK> postNodes = getPostNode(key);

            for (VK postKey : postNodes) {
                int d = indegrees.getOrDefault(postKey, 0);

                if (d <= 1) {
                    sort.add(postKey);
                    indegrees.remove(postKey);
                    zeroVertex.add(postKey);
                } else {
                    indegrees.put(postKey, d - 1);
                }
            }
        }
    }

    // indegrees , , ?
    return new AbstractMap.SimpleEntry(indegrees.isEmpty(), sort);
}

From source file:org.kie.server.services.jbpm.JbpmKieServerExtension.java

@Override
public void disposeContainer(String id, KieContainerInstance kieContainerInstance,
        Map<String, Object> parameters) {
    if (!deploymentService.isDeployed(id)) {
        logger.info("No container with id {} found", id);
        return;/*from   w  ww  .j ava2 s . c om*/
    }

    KModuleDeploymentUnit unit = (KModuleDeploymentUnit) deploymentService.getDeployedUnit(id)
            .getDeploymentUnit();

    if (kieServer.getInfo().getResult().getMode().equals(KieServerMode.PRODUCTION)) {
        deploymentService.undeploy(new CustomIdKmoduleDeploymentUnit(id, unit.getGroupId(),
                unit.getArtifactId(), unit.getVersion()));
    } else {
        // Checking if we are disposing or updating the container. We must only keep process instances only when updating.
        Boolean isDispose = (Boolean) parameters.getOrDefault(IS_DISPOSE_CONTAINER_PARAM, Boolean.TRUE);

        // Checking if we need to abort the existing process instances before disposing container, by default it should be false
        Boolean abortInstances = (Boolean) parameters
                .getOrDefault(KieServerConstants.KIE_SERVER_PARAM_RESET_BEFORE_UPDATE, Boolean.FALSE);

        if (isDispose || abortInstances) {
            deploymentService.undeploy(
                    new CustomIdKmoduleDeploymentUnit(id, unit.getGroupId(), unit.getArtifactId(),
                            unit.getVersion()),
                    PreUndeployOperations.abortUnitActiveProcessInstances(runtimeDataService,
                            deploymentService));
        } else {
            deploymentService.undeploy(new CustomIdKmoduleDeploymentUnit(id, unit.getGroupId(),
                    unit.getArtifactId(), unit.getVersion()), PreUndeployOperations.doNothing());
        }
    }

    // remove any query result mappers for container
    List<String> addedMappers = containerMappers.get(id);
    if (addedMappers != null && !addedMappers.isEmpty()) {

        for (String mapper : addedMappers) {
            QueryMapperRegistry.get().removeMapper(mapper);
        }
    }
    // remove any query param builder factories
    QueryParamBuilderManager.get().removeQueryFactories(id);
    logger.debug("Container {} disposed successfully by extension {}", id, this);

    // remove any container specific queries
    List<String> queries = containerQueries.remove(id);
    if (queries != null) {
        logger.debug("Removing queries {} that comes from container {} that is being disposed", queries, id);
        queries.forEach(q -> {
            try {
                queryService.unregisterQuery(q);
            } catch (QueryNotFoundException e) {
                logger.debug("Query {} not found when being removed on container dispose", q);
            }
        });
    }
}

From source file:aiai.ai.launchpad.experiment.ExperimentService.java

private List<Task> findTaskWithFilter(Experiment experiment, long featureId, String[] params) {
    final Set<String> paramSet = new HashSet<>();
    final Set<String> paramFilterKeys = new HashSet<>();
    for (String param : params) {
        if (StringUtils.isBlank(param)) {
            continue;
        }//from ww  w.j  a  v  a 2s .c om
        paramSet.add(param);
        paramFilterKeys.add(ParamFilter.of(param).key);
    }
    final Map<String, Map<String, Integer>> paramByIndex = experiment.getHyperParamsAsMap();

    if (true)
        throw new IllegalStateException("Not implemented yet");
    List<Task> list = null;
    //        List<Task> list = taskRepository.findByIsCompletedIsTrueAndFeatureId(featureId);

    List<Task> selected = new ArrayList<>();
    for (Task sequence : list) {
        final TaskParamYaml taskParamYaml = taskParamYamlUtils.toTaskYaml(sequence.getParams());
        boolean[] isOk = new boolean[taskParamYaml.hyperParams.size()];
        int idx = 0;
        for (Map.Entry<String, String> entry : taskParamYaml.hyperParams.entrySet()) {
            try {
                if (!paramFilterKeys.contains(entry.getKey())) {
                    isOk[idx] = true;
                    continue;
                }
                final Map<String, Integer> map = paramByIndex.getOrDefault(entry.getKey(), HASH_MAP);
                if (map.isEmpty()) {
                    continue;
                }
                if (map.size() == 1) {
                    isOk[idx] = true;
                    continue;
                }

                boolean isFilter = paramSet.contains(entry.getKey() + "-"
                        + paramByIndex.get(entry.getKey()).get(entry.getKey() + "-" + entry.getValue()));
                if (isFilter) {
                    isOk[idx] = true;
                }
            } finally {
                idx++;
            }
        }
        if (isInclude(isOk)) {
            selected.add(sequence);
        }
    }
    //noinspection UnnecessaryLocalVariable
    return selected;
}

From source file:com.devnexus.ting.core.service.impl.BusinessServiceImpl.java

@Override
public Dashboard generateDashBoardForSignUp(EventSignup signUp) {
    Dashboard dashboard = new Dashboard();

    List<RegistrationDetails> orders = registrationDao.findPurchasedForEvent(signUp.getEvent());
    orders.sort((order1, order2) -> {
        return order1.getCreatedDate().compareTo(order2.getCreatedDate());
    });/*w w  w.ja  v  a 2  s .c  om*/

    orders.stream().forEach((order) -> {
        dashboard.addOrder(order);
    });

    orders = registrationDao.findIncompletePaypalOrdersForEvent(signUp.getEvent());
    orders.sort((order1, order2) -> {
        return order1.getCreatedDate().compareTo(order2.getCreatedDate());
    });

    orders.stream().forEach((order) -> {
        dashboard.addInCompletePaypalOrders(order);
    });

    orders = registrationDao.findOrdersRequestingInvoiceForEvent(signUp.getEvent());
    orders.sort((order1, order2) -> {
        return order1.getCreatedDate().compareTo(order2.getCreatedDate());
    });

    orders.stream().forEach((order) -> {
        dashboard.addOrdersRequestingInvoice(order);
    });

    Map<Long, TicketGroup> ticketIdToGroup = new HashMap<>();
    Map<TicketGroup, Integer> ticketGroupCount = new HashMap<>();

    for (RegistrationDetails order : dashboard.getOrders()) {
        for (TicketOrderDetail ticketOrder : order.getOrderDetails()) {
            Long ticketGroupId = ticketOrder.getTicketGroup();
            ticketIdToGroup.computeIfAbsent(ticketGroupId, (id) -> {
                return getTicketGroup(id);
            });
            TicketGroup group = ticketIdToGroup.get(ticketGroupId);
            int count = ticketGroupCount.getOrDefault(group, 0);
            ticketGroupCount.put(group, count + 1);
        }
    }

    for (Map.Entry<TicketGroup, Integer> entry : ticketGroupCount.entrySet()) {
        dashboard.addSale(entry.getKey(), entry.getValue());
    }

    return dashboard;
}

From source file:alfio.controller.api.support.TicketHelper.java

public List<TicketFieldConfigurationDescriptionAndValue> findTicketFieldConfigurationAndValue(int eventId,
        Ticket ticket, Locale locale) {

    List<Ticket> ticketsInReservation = ticketRepository
            .findTicketsInReservation(ticket.getTicketsReservationId());
    //WORKAROUND: we only add the additionalServiceItems related fields only if it's the _first_ ticket of the reservation
    boolean isFirstTicket = ticketsInReservation.get(0).getId() == ticket.getId();

    Map<Integer, TicketFieldDescription> descriptions = ticketFieldRepository.findTranslationsFor(locale,
            eventId);//from w w w. j  a  v a2  s.c  om
    Map<String, TicketFieldValue> values = ticketFieldRepository.findAllByTicketIdGroupedByName(ticket.getId());
    Function<TicketFieldConfiguration, String> extractor = (f) -> Optional.ofNullable(values.get(f.getName()))
            .map(TicketFieldValue::getValue).orElse("");
    List<AdditionalServiceItem> additionalServiceItems = isFirstTicket
            ? additionalServiceItemRepository.findByReservationUuid(ticket.getTicketsReservationId())
            : Collections.emptyList();
    Set<Integer> additionalServiceIds = additionalServiceItems.stream()
            .map(AdditionalServiceItem::getAdditionalServiceId).collect(Collectors.toSet());
    return ticketFieldRepository
            .findAdditionalFieldsForEvent(eventId).stream().filter(f -> f.getContext() == ATTENDEE || Optional
                    .ofNullable(f.getAdditionalServiceId()).filter(additionalServiceIds::contains).isPresent())
            .map(f -> {
                int count = Math
                        .max(1, Optional
                                .ofNullable(f.getAdditionalServiceId()).map(id -> (int) additionalServiceItems
                                        .stream().filter(i -> i.getAdditionalServiceId() == id).count())
                                .orElse(1));
                return new TicketFieldConfigurationDescriptionAndValue(f,
                        descriptions.getOrDefault(f.getId(), TicketFieldDescription.MISSING_FIELD), count,
                        extractor.apply(f));
            }).collect(Collectors.toList());
}

From source file:com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.distributed.kubernetes.v2.KubernetesV2Service.java

default List<ConfigSource> stageConfig(AccountDeploymentDetails<KubernetesAccount> details,
        GenerateService.ResolvedConfiguration resolvedConfiguration) {
    Map<String, Profile> profiles = resolvedConfiguration.getProfilesForService(getService().getType());
    String stagingPath = getSpinnakerStagingPath(details.getDeploymentName());
    SpinnakerRuntimeSettings runtimeSettings = resolvedConfiguration.getRuntimeSettings();

    Map<String, Set<Profile>> profilesByDirectory = new HashMap<>();
    List<String> requiredFiles = new ArrayList<>();
    List<ConfigSource> configSources = new ArrayList<>();
    String secretNamePrefix = getServiceName() + "-files";
    String namespace = getNamespace(resolvedConfiguration.getServiceSettings(getService()));
    KubernetesAccount account = details.getAccount();

    for (SidecarService sidecarService : getSidecars(runtimeSettings)) {
        for (Profile profile : sidecarService.getSidecarProfiles(resolvedConfiguration, getService())) {
            if (profile == null) {
                throw new HalException(Problem.Severity.FATAL,
                        "Service " + sidecarService.getService().getCanonicalName()
                                + " is required but was not supplied for deployment.");
            }/*  ww w . j av a  2  s .  c  om*/

            profiles.put(profile.getName(), profile);
            requiredFiles.addAll(profile.getRequiredFiles());
        }
    }

    for (Entry<String, Profile> entry : profiles.entrySet()) {
        Profile profile = entry.getValue();
        String outputFile = profile.getOutputFile();
        String mountPoint = Paths.get(outputFile).getParent().toString();

        Set<Profile> profilesInDirectory = profilesByDirectory.getOrDefault(mountPoint, new HashSet<>());
        profilesInDirectory.add(profile);

        requiredFiles.addAll(profile.getRequiredFiles());
        profilesByDirectory.put(mountPoint, profilesInDirectory);
    }

    for (Entry<String, Set<Profile>> entry : profilesByDirectory.entrySet()) {
        Set<Profile> profilesInDirectory = entry.getValue();
        String mountPath = entry.getKey();
        List<SecretMountPair> files = profilesInDirectory.stream().map(p -> {
            File input = new File(p.getStagedFile(stagingPath));
            File output = new File(p.getOutputFile());
            return new SecretMountPair(input, output);
        }).collect(Collectors.toList());

        Map<String, String> env = profilesInDirectory.stream().map(Profile::getEnv).map(Map::entrySet)
                .flatMap(Collection::stream).collect(Collectors.toMap(Entry::getKey, Entry::getValue));

        String name = KubernetesV2Utils.createSecret(account, namespace, getService().getCanonicalName(),
                secretNamePrefix, files);
        configSources.add(new ConfigSource().setId(name).setMountPath(mountPath).setEnv(env));
    }

    if (!requiredFiles.isEmpty()) {
        List<SecretMountPair> files = requiredFiles.stream().map(File::new).map(SecretMountPair::new)
                .collect(Collectors.toList());

        String name = KubernetesV2Utils.createSecret(account, namespace, getService().getCanonicalName(),
                secretNamePrefix, files);
        configSources.add(new ConfigSource().setId(name).setMountPath(files.get(0).getContents().getParent()));
    }

    return configSources;
}