List of usage examples for java.util List sort
@SuppressWarnings({ "unchecked", "rawtypes" }) default void sort(Comparator<? super E> c)
From source file:org.codice.ddf.admin.core.impl.AdminAlertImpl.java
@Override public List<Map<String, Object>> getAlerts() { List<Map<String, Object>> alerts = new ArrayList<>(); try {/*from w w w. j a va2 s. c o m*/ List<Map<String, Object>> results = persistentStore.get("alerts", activeAlertQuery); if (!results.isEmpty()) { for (Map<String, Object> item : results) { item = PersistentItem.stripSuffixes(item); // this check and type change is needed because of how the persistent store handles // strings/sets of strings. Single value sets will come back as strings. if (item.get(SystemNotice.SYSTEM_NOTICE_DETAILS_KEY) instanceof String) { item.put(SystemNotice.SYSTEM_NOTICE_DETAILS_KEY, Collections.singleton(item.get(SystemNotice.SYSTEM_NOTICE_DETAILS_KEY))); } escapeStrings(item); alerts.add(item); } } } catch (PersistenceException pe) { LOGGER.debug("Error retrieving system alert.", pe); return Collections.singletonList(new Alert("unable_to_retrieve_alerts", NoticePriority.CRITICAL, "Persistent Storage Not Responding. Could Not Retrieve Alerts.", Collections.singleton( "Critical alerts may be present, but not displayed because the persistent storage is not responding.")) .getProperties()); } alerts.sort((map1, map2) -> new Alert(map1).getPriority().value() >= new Alert(map2).getPriority().value() ? -1 : 1); return alerts; }
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 ww . j av a 2 s . co 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.apache.pulsar.broker.admin.v1.Namespaces.java
@GET @Path("/{property}/{cluster}") @ApiOperation(hidden = true, value = "Get the list of all the namespaces for a certain property on single cluster.", response = String.class, responseContainer = "Set") @ApiResponses(value = { @ApiResponse(code = 403, message = "Don't have admin permission"), @ApiResponse(code = 404, message = "Property or cluster doesn't exist") }) public List<String> getNamespacesForCluster(@PathParam("property") String property, @PathParam("cluster") String cluster) { validateAdminAccessForTenant(property); List<String> namespaces = Lists.newArrayList(); if (!clusters().contains(cluster)) { log.warn("[{}] Failed to get namespace list for property: {}/{} - Cluster does not exist", clientAppId(), property, cluster); throw new RestException(Status.NOT_FOUND, "Cluster does not exist"); }//from w ww .jav a 2 s . c om try { for (String namespace : globalZk().getChildren(path(POLICIES, property, cluster), false)) { namespaces.add(String.format("%s/%s/%s", property, cluster, namespace)); } } catch (KeeperException.NoNodeException e) { // NoNode means there are no namespaces for this property on the specified cluster, returning empty list } catch (Exception e) { log.error("[{}] Failed to get namespaces list: {}", clientAppId(), e); throw new RestException(e); } namespaces.sort(null); return namespaces; }
From source file:org.opencb.opencga.app.cli.main.OpenCGAMainOld.java
private StringBuilder listFiles(List<File> files, long studyId, int level, String indent, boolean showUries, StringBuilder sb, String sessionId) throws CatalogException { if (level > 0) { files.sort((file1, file2) -> file1.getName().compareTo(file2.getName())); // files.sort((file1, file2) -> file1.getModificationDate().compareTo(file2.getModificationDate())); for (Iterator<File> iterator = files.iterator(); iterator.hasNext();) { File file = iterator.next(); // System.out.printf("%s%d - %s \t\t[%s]\n", indent + (iterator.hasNext()? "+--" : "L--"), file.getId(), file.getName(), file.getName()); sb.append(String.format("%s (%d) - %s [%s, %s]%s\n", indent.isEmpty() ? "" : indent + (iterator.hasNext() ? "" : ""), file.getId(), file.getName(), file.getStatus().getName(), humanReadableByteCount(file.getDiskUsage(), false), showUries && file.getUri() != null ? " --> " + file.getUri() : "")); if (file.getType() == File.Type.DIRECTORY) { listFiles(studyId, file.getPath(), level - 1, indent + (iterator.hasNext() ? " " : " "), showUries, sb, sessionId); // listFiles(studyId, file.getPath(), level - 1, indent + (iterator.hasNext()? "| " : " "), sessionId); }//from w w w. j av a 2 s.c om } } return sb; }
From source file:com.cloudbees.jenkins.plugins.bitbucket.client.BitbucketCloudApiClient.java
/** * The role parameter only makes sense when the request is authenticated, so * if there is no auth information ({@link #authenticator}) the role will be omitted. *//*from w ww . j a v a 2 s . c om*/ @NonNull @Override public List<BitbucketCloudRepository> getRepositories(@CheckForNull UserRoleInRepository role) throws InterruptedException, IOException { StringBuilder cacheKey = new StringBuilder(); cacheKey.append(owner); if (authenticator != null) { cacheKey.append("::").append(authenticator.getId()); } else { cacheKey.append("::<anonymous>"); } final UriTemplate template = UriTemplate.fromTemplate(V2_API_BASE_URL + "{/owner}{?role,page,pagelen}") .set("owner", owner).set("pagelen", 50); if (role != null && authenticator != null) { template.set("role", role.getId()); cacheKey.append("::").append(role.getId()); } Callable<List<BitbucketCloudRepository>> request = () -> { List<BitbucketCloudRepository> repositories = new ArrayList<>(); Integer pageNumber = 1; String url, response; PaginatedBitbucketRepository page; do { response = getRequest(url = template.set("page", pageNumber).expand()); try { page = JsonParser.toJava(response, PaginatedBitbucketRepository.class); repositories.addAll(page.getValues()); } catch (IOException e) { throw new IOException("I/O error when parsing response from URL: " + url, e); } pageNumber++; } while (page.getNext() != null); repositories.sort(Comparator.comparing(BitbucketCloudRepository::getRepositoryName)); return repositories; }; try { if (enableCache) { return cachedRepositories.get(cacheKey.toString(), request); } else { return request.call(); } } catch (Exception ex) { throw new IOException("Error while loading repositories from cache", ex); } }
From source file:com.oneops.controller.cms.CmsWoProvider.java
void addComponentConfig(CmsWorkOrder wo) { CmsRfcCI rfc = wo.getRfcCi();/*from w w w . j ava 2 s . com*/ if (rfc.getCiClassName().matches(BOM_FQDN) && isTorbitService(rfc)) { String logKey = "Fqdn workorder " + wo.getDeploymentId() + ":" + rfc.getCiId() + ":: "; //send weights only when enabled if (isWeightsEnabled(wo.getRfcCi().getNsPath())) { logger.info(logKey + "finding weights for clouds"); List<CmsCIRelation> deployedToRelations = cmProcessor .getCIRelationsWithToCIAndNoAttrs(rfc.getNsPath(), DEPLOYED_TO, null, "Compute", null); Set<String> clouds = getPrimaryClouds(wo); logger.info(logKey + "primary clouds " + clouds); Map<String, Long> cloudInstancesMap = deployedToRelations.stream() .filter(r -> (r.getToCi() != null) && clouds.contains(r.getToCi().getCiName())) .collect(groupingBy(r -> r.getToCi().getCiName(), counting())); if (cloudInstancesMap.isEmpty()) { logger.info(logKey + "no active cloud compute instance found"); return; } Long totalComputes = 0L; List<CloudWeight> cloudWeights = new ArrayList<>(); for (Entry<String, Long> entry : cloudInstancesMap.entrySet()) { totalComputes = totalComputes + entry.getValue(); cloudWeights.add(new CloudWeight(entry.getKey(), entry.getValue())); } logger.info(logKey + "total active computes " + totalComputes); cloudWeights.sort((c1, c2) -> Long.compare(c2.computes, c1.computes)); if (totalComputes > 0) { int totalPercent = 0; for (CloudWeight cloudWeight : cloudWeights) { cloudWeight.weight = (int) ((cloudWeight.computes * 100.0) / totalComputes); totalPercent += cloudWeight.weight; } //bring the total percent to 100 int remainingPercent = 100 - totalPercent; for (int i = 0; i < remainingPercent; i++) { cloudWeights.get(i).weight++; } Map<String, String> config = configMap(wo); Map<String, Integer> weights = cloudWeights.stream() .collect(Collectors.toMap(c -> c.name, c -> c.weight)); logger.info(logKey + "weight map " + weights); config.put("weights", gson.toJson(weights)); } } else { logger.info(logKey + "not using weights for gslb. gslb weights not enabled."); } } }
From source file:net.sf.jabref.openoffice.OOBibBase.java
/** * This method inserts a cite marker in the text for the given BibEntry, * and may refresh the bibliography.//from w ww. ja va 2 s . com * @param entries The entries to cite. * @param database The database the entry belongs to. * @param style The bibliography style we are using. * @param inParenthesis Indicates whether it is an in-text citation or a citation in parenthesis. * This is not relevant if numbered citations are used. * @param withText Indicates whether this should be a normal citation (true) or an empty * (invisible) citation (false). * @param sync Indicates whether the reference list should be refreshed. * @throws Exception */ public void insertEntry(List<BibEntry> entries, BibDatabase database, List<BibDatabase> allBases, OOBibStyle style, boolean inParenthesis, boolean withText, String pageInfo, boolean sync) throws Exception { try { XTextViewCursor xViewCursor = xViewCursorSupplier.getViewCursor(); if (entries.size() > 1) { if (style.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL)) { entries.sort(yearAuthorTitleComparator); } else { entries.sort(entryComparator); } } String keyString = String.join(",", entries.stream().map(entry -> entry.getCiteKey()).collect(Collectors.toList())); // Insert bookmark: String bName = getUniqueReferenceMarkName(keyString, withText ? inParenthesis ? OOBibBase.AUTHORYEAR_PAR : OOBibBase.AUTHORYEAR_INTEXT : OOBibBase.INVISIBLE_CIT); // If we should store metadata for page info, do that now: if (pageInfo != null) { LOGGER.info("Storing page info: " + pageInfo); setCustomProperty(bName, pageInfo); } xViewCursor.getText().insertString(xViewCursor, " ", false); if (style.isFormatCitations()) { XPropertySet xCursorProps = UnoRuntime.queryInterface(XPropertySet.class, xViewCursor); String charStyle = style.getCitationCharacterFormat(); try { xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); } catch (UnknownPropertyException | PropertyVetoException | IllegalArgumentException | WrappedTargetException ex) { // Setting the character format failed, so we throw an exception that // will result in an error message for the user. Before that, // delete the space we inserted: xViewCursor.goLeft((short) 1, true); xViewCursor.setString(""); throw new UndefinedCharacterFormatException(charStyle); } } xViewCursor.goLeft((short) 1, false); Map<BibEntry, BibDatabase> databaseMap = new HashMap<>(); for (BibEntry entry : entries) { databaseMap.put(entry, database); } String citeText = style.isNumberEntries() ? "-" : style.getCitationMarker(entries, databaseMap, inParenthesis, null, null); insertReferenceMark(bName, citeText, xViewCursor, withText, style); xViewCursor.collapseToEnd(); xViewCursor.goRight((short) 1, false); XTextRange position = xViewCursor.getEnd(); if (sync) { // To account for numbering and for uniqiefiers, we must refresh the cite markers: updateSortedReferenceMarks(); refreshCiteMarkers(allBases, style); // Insert it at the current position: rebuildBibTextSection(allBases, style); } // Go back to the relevant position: xViewCursor.gotoRange(position, false); } catch (DisposedException ex) { // We need to catch this one here because the OpenOfficePanel class is // loaded before connection, and therefore cannot directly reference // or catch a DisposedException (which is in a OO jar file). throw new ConnectionLostException(ex.getMessage()); } }
From source file:com.bgh.myopeninvoice.jsf.jsfbeans.InvoiceBean.java
public String onFlowProcessTimesheet(FlowEvent event) { //this is to reset position and adjust based on the size of data RequestContext.getCurrentInstance().execute("PF('invoice-items-timesheet-form-dialog').initPosition();"); if ("select-date".equalsIgnoreCase(event.getOldStep()) && selectedInvoiceItemsEntity != null) { //need to reset in case we changed something selectedInvoiceItemsEntity = invoiceDAO.getInvoiceItemsRepository() .findOne(selectedInvoiceItemsEntity.getInvoiceItemId()); final List<TimeSheetEntity> timeSheetsByInvoiceItemId = (List<TimeSheetEntity>) selectedInvoiceItemsEntity .getTimeSheetsByInvoiceItemId(); int days = Days.daysBetween(dateFromTimesheet, dateToTimesheet).getDays() + 1; for (int i = 0; i < days; i++) { LocalDate potentialLocalDate = dateFromTimesheet.withFieldAdded(DurationFieldType.days(), i); TimeSheetEntity e = new TimeSheetEntity(); e.setInvoiceItemId(selectedInvoiceItemsEntity.getInvoiceItemId()); e.setInvoiceItemsByInvoiceItemId(selectedInvoiceItemsEntity); e.setItemDate(potentialLocalDate.toDate()); if (timeSheetsByInvoiceItemId.stream() .noneMatch(p -> p.getItemDate().equals(potentialLocalDate.toDate()))) { timeSheetsByInvoiceItemId.add(e); }//from w ww .j av a2s . c om } //need to sort here because we added some values - they will be displayed in order timeSheetsByInvoiceItemId.sort((l1, l2) -> l1.getItemDate().compareTo(l2.getItemDate())); } return event.getNewStep(); }
From source file:io.sinistral.proteus.server.tools.swagger.Reader.java
@SuppressWarnings("deprecation") private Swagger read(Class<?> cls, String parentPath, String parentMethod, boolean isSubresource, String[] parentConsumes, String[] parentProduces, Map<String, Tag> parentTags, List<Parameter> parentParameters, Set<Class<?>> scannedResources) { Map<String, Tag> tags = new TreeMap<>(); List<SecurityRequirement> securities = new ArrayList<>(); String[] consumes = new String[0]; String[] produces = new String[0]; final Set<Scheme> globalSchemes = EnumSet.noneOf(Scheme.class); Api api = ReflectionUtils.getAnnotation(cls, Api.class); boolean hasPathAnnotation = (ReflectionUtils.getAnnotation(cls, javax.ws.rs.Path.class) != null); boolean hasApiAnnotation = (api != null); boolean isApiHidden = hasApiAnnotation && api.hidden(); // class readable only if annotated with ((@Path and @Api) or isSubresource ) - and @Api not hidden boolean classReadable = ((hasPathAnnotation && hasApiAnnotation) || isSubresource) && !isApiHidden; // with scanAllResources true in config and @Api not hidden scan only if it has also @Path annotation or is subresource boolean scanAll = !isApiHidden && config.isScanAllResources() && (hasPathAnnotation || isSubresource); // readable if classReadable or scanAll boolean readable = classReadable || scanAll; if (!readable) { return swagger; }//from w w w . j av a 2 s. c o m // api readable only if @Api present; cannot be hidden because checked in classReadable. if (hasApiAnnotation) { // the value will be used as a tag for 2.0 UNLESS a Tags annotation is present Set<String> tagStrings = extractTags(api); for (String tagString : tagStrings) { Tag tag = new Tag().name(tagString); tags.put(tagString, tag); } for (String tagName : tags.keySet()) { swagger.tag(tags.get(tagName)); } if (!api.produces().isEmpty()) { produces = ReaderUtils.splitContentValues(new String[] { api.produces() }); } if (!api.consumes().isEmpty()) { consumes = ReaderUtils.splitContentValues(new String[] { api.consumes() }); } globalSchemes.addAll(parseSchemes(api.protocols())); for (Authorization auth : api.authorizations()) { if (auth.value() != null && !auth.value().isEmpty()) { SecurityRequirement security = new SecurityRequirement(); security.setName(auth.value()); for (AuthorizationScope scope : auth.scopes()) { if (scope.scope() != null && !scope.scope().isEmpty()) { security.addScope(scope.scope()); } } securities.add(security); } } } if (readable) { if (isSubresource) { if (parentTags != null) { tags.putAll(parentTags); } } // merge consumes, produces if (consumes.length == 0 && cls.getAnnotation(Consumes.class) != null) { consumes = ReaderUtils.splitContentValues(cls.getAnnotation(Consumes.class).value()); } if (produces.length == 0 && cls.getAnnotation(Produces.class) != null) { produces = ReaderUtils.splitContentValues(cls.getAnnotation(Produces.class).value()); } // look for method-level annotated properties // handle sub-resources by looking at return type final List<Parameter> globalParameters = new ArrayList<Parameter>(); // look for constructor-level annotated properties globalParameters.addAll(ReaderUtils.collectConstructorParameters(cls, swagger)); // look for field-level annotated properties globalParameters.addAll(ReaderUtils.collectFieldParameters(cls, swagger)); // build class/interface level @ApiResponse list ApiResponses classResponseAnnotation = ReflectionUtils.getAnnotation(cls, ApiResponses.class); List<ApiResponse> classApiResponses = new ArrayList<ApiResponse>(); if (classResponseAnnotation != null) { classApiResponses.addAll(Arrays.asList(classResponseAnnotation.value())); } // parse the method final javax.ws.rs.Path apiPath = ReflectionUtils.getAnnotation(cls, javax.ws.rs.Path.class); JavaType classType = TypeFactory.defaultInstance().constructType(cls); BeanDescription bd = new ObjectMapper().getSerializationConfig().introspect(classType); Method methods[] = cls.getMethods(); for (Method method : methods) { AnnotatedMethod annotatedMethod = bd.findMethod(method.getName(), method.getParameterTypes()); if (ReflectionUtils.isOverriddenMethod(method, cls)) { continue; } javax.ws.rs.Path methodPath = ReflectionUtils.getAnnotation(method, javax.ws.rs.Path.class); String operationPath = getPath(apiPath, methodPath, parentPath); Map<String, String> regexMap = new LinkedHashMap<>(); operationPath = PathUtils.parsePath(operationPath, regexMap); if (operationPath != null) { if (isIgnored(operationPath)) { continue; } List<String> pathParamNames = new ArrayList<>(); Matcher m = PATH_PATTERN.matcher(operationPath); while (m.find()) { String pathParamName = m.group(1); int bracketIndex = pathParamName.indexOf('['); if (bracketIndex > -1) { pathParamName = pathParamName.substring(0, bracketIndex); } pathParamNames.add(pathParamName); } final ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class); String httpMethod = extractOperationMethod(apiOperation, method, SwaggerExtensions.chain()); Operation operation = null; if (apiOperation != null || config.isScanAllResources() || httpMethod != null || methodPath != null) { operation = parseMethod(cls, method, annotatedMethod, globalParameters, classApiResponses, pathParamNames); } if (operation == null) { continue; } if (parentParameters != null) { for (Parameter param : parentParameters) { operation.parameter(param); } } for (Parameter param : operation.getParameters()) { if (regexMap.get(param.getName()) != null) { String pattern = regexMap.get(param.getName()); param.setPattern(pattern); } } if (apiOperation != null) { for (Scheme scheme : parseSchemes(apiOperation.protocols())) { operation.scheme(scheme); } } if (operation.getSchemes() == null || operation.getSchemes().isEmpty()) { for (Scheme scheme : globalSchemes) { operation.scheme(scheme); } } String[] apiConsumes = consumes; if (parentConsumes != null) { Set<String> both = new LinkedHashSet<>(Arrays.asList(apiConsumes)); both.addAll(new LinkedHashSet<>(Arrays.asList(parentConsumes))); if (operation.getConsumes() != null) { both.addAll(new LinkedHashSet<String>(operation.getConsumes())); } apiConsumes = both.toArray(new String[both.size()]); } String[] apiProduces = produces; if (parentProduces != null) { Set<String> both = new LinkedHashSet<>(Arrays.asList(apiProduces)); both.addAll(new LinkedHashSet<>(Arrays.asList(parentProduces))); if (operation.getProduces() != null) { both.addAll(new LinkedHashSet<String>(operation.getProduces())); } apiProduces = both.toArray(new String[both.size()]); } final Class<?> subResource = getSubResourceWithJaxRsSubresourceLocatorSpecs(method); if (subResource != null && !scannedResources.contains(subResource)) { scannedResources.add(subResource); read(subResource, operationPath, httpMethod, true, apiConsumes, apiProduces, tags, operation.getParameters(), scannedResources); // remove the sub resource so that it can visit it later in another path // but we have a room for optimization in the future to reuse the scanned result // by caching the scanned resources in the reader instance to avoid actual scanning // the the resources again scannedResources.remove(subResource); } // can't continue without a valid http method httpMethod = (httpMethod == null) ? parentMethod : httpMethod; if (httpMethod != null) { if (apiOperation != null) { for (String tag : apiOperation.tags()) { if (!"".equals(tag)) { operation.tag(tag); swagger.tag(new Tag().name(tag)); } } operation.getVendorExtensions() .putAll(BaseReaderUtils.parseExtensions(apiOperation.extensions())); } if (operation.getConsumes() == null) { for (String mediaType : apiConsumes) { operation.consumes(mediaType); } } if (operation.getProduces() == null) { for (String mediaType : apiProduces) { operation.produces(mediaType); } } if (operation.getTags() == null) { for (String tagString : tags.keySet()) { operation.tag(tagString); } } // Only add global @Api securities if operation doesn't already have more specific securities if (operation.getSecurity() == null) { for (SecurityRequirement security : securities) { operation.security(security); } } Path path = swagger.getPath(operationPath); if (path == null) { path = new Path(); swagger.path(operationPath, path); } path.set(httpMethod, operation); readImplicitParameters(method, operation); readExternalDocs(method, operation); } } } } List<Tag> swaggerTags = new ArrayList<Tag>(swagger.getTags()); swaggerTags.sort((a, b) -> { return a.getName().compareTo(b.getName()); }); swagger.setTags(swaggerTags); return swagger; }
From source file:org.optaplanner.examples.conferencescheduling.persistence.ConferenceSchedulingCfpDevoxxImporter.java
private void importRoomList() { this.roomIdToRoomMap = new HashMap<>(); List<Room> roomList = new ArrayList<>(); String roomsUrl = conferenceBaseUrl + "/rooms/"; LOGGER.debug("Sending a request to: " + roomsUrl); JsonObject rootObject = readJson(roomsUrl, JsonReader::readObject); JsonArray roomArray = rootObject.getJsonArray("rooms"); for (int i = 0; i < roomArray.size(); i++) { JsonObject roomObject = roomArray.getJsonObject(i); String id = roomObject.getString("id"); int capacity = roomObject.getInt("capacity"); if (!Arrays.asList(IGNORED_ROOM_IDS).contains(id)) { Room room = new Room((long) i); room.setName(id);//from w w w .j av a 2s .c om room.setCapacity(capacity); room.setTalkTypeSet(getTalkTypeSetForCapacity(capacity)); for (TalkType talkType : room.getTalkTypeSet()) { talkType.getCompatibleRoomSet().add(room); } room.setTagSet(new HashSet<>()); room.setUnavailableTimeslotSet(new HashSet<>()); roomList.add(room); roomIdToRoomMap.put(id, room); } } roomList.sort(Comparator.comparing(Room::getName)); solution.setRoomList(roomList); }