List of usage examples for java.util SortedMap isEmpty
boolean isEmpty();
From source file:org.wrml.runtime.rest.Resource.java
/** * Generates the "href" URI used to refer to this resource from the specified referrer {@link Model} instance using * the specified {@link LinkRelation} {@link URI} value. *///from www . j av a 2s . co m public URI getHrefUri(final Model referrer, final URI referenceRelationUri) { if (referrer == null) { return null; } /* * Given the nature of the Api's ResourceTemplate metadata tree, the runtime resource can determine its own * UriTemplate (and it only needs to determine/compute this once). */ final UriTemplate uriTemplate = getUriTemplate(); if (uriTemplate == null) { return null; } /* * Get the end point id's templated parameter names, for example: a UriTemplate might have slots that look like * {teamId} or {highScoreId} or {name} appearing where legal (according to UriTemplate syntax, see: * http://tools.ietf.org/html/rfc6570). A fixed URI, meaning a UriTemplate with no variables, will return null * here. */ final String[] uriTemplateParameterNames = this._UriTemplate.getParameterNames(); Map<String, Object> parameterMap = null; if (uriTemplateParameterNames != null && uriTemplateParameterNames.length > 0) { // Get the Link slot's bindings, which may be used to provide an alternative source for one or more URI // template parameter values. final Prototype referrerPrototype = referrer.getPrototype(); final SortedMap<URI, LinkProtoSlot> linkProtoSlots = referrerPrototype.getLinkProtoSlots(); Map<String, ProtoValueSource> linkSlotBindings = null; if (linkProtoSlots != null && !linkProtoSlots.isEmpty()) { final LinkProtoSlot linkProtoSlot = linkProtoSlots.get(referenceRelationUri); if (linkProtoSlot != null) { linkSlotBindings = linkProtoSlot.getLinkSlotBindings(); } } parameterMap = new LinkedHashMap<>(uriTemplateParameterNames.length); for (final String paramName : uriTemplateParameterNames) { final Object paramValue; if (linkSlotBindings != null && linkSlotBindings.containsKey(paramName)) { // The link slot has declared a binding to an alternate source for this URI template parameter's // value. final ProtoValueSource valueSource = linkSlotBindings.get(paramName); paramValue = valueSource.getValue(referrer); } else { // By default, if the end point's UriTemplate has parameters (blanks) to fill in, then by convention // we // assume that the referrer model has the corresponding slot values to match the UriTemplate's // inputs/slots. // // Put simply, (by default) referrer model slot names "match" UriTemplate param names. // // This enforces that the model's own represented resource state is the only thing used to // (automatically) drive the link-based graph traversal (aka HATEOAS). Its also a simple convention // that // is (reasonably) easy to comprehend, hopefully even intuitive. paramValue = referrer.getSlotValue(paramName); } parameterMap.put(paramName, paramValue); } } final URI uri = this._UriTemplate.evaluate(parameterMap); return uri; }
From source file:org.jahia.services.render.scripting.bundle.BundleScriptResolver.java
/** * Returns view scripts for the specified module bundle which match the specified path. * * @param module the module bundle to perform lookup in * @param pathPrefix the resource path prefix to match * @return a set of matching view scripts ordered by the extension (script type) *///from w w w . j a va 2 s.co m private Set<ViewResourceInfo> findBundleScripts(String module, String pathPrefix) { final SortedMap<String, ViewResourceInfo> allBundleScripts = availableScripts.get(module); if (allBundleScripts == null || allBundleScripts.isEmpty()) { return Collections.emptySet(); } // get all the ViewResourceInfos which path is greater than or equal to the given prefix final SortedMap<String, ViewResourceInfo> viewInfosWithPathGTEThanPrefix = allBundleScripts .tailMap(pathPrefix); // if the tail map is empty, we won't find the path prefix in the available scripts so return an empty set if (viewInfosWithPathGTEThanPrefix.isEmpty()) { return Collections.emptySet(); } // check if the first key contains the prefix. If not, the prefix will not match any entries so return an empty set if (!viewInfosWithPathGTEThanPrefix.firstKey().startsWith(pathPrefix)) { return Collections.emptySet(); } else { SortedSet<ViewResourceInfo> sortedScripts = new TreeSet<ViewResourceInfo>(scriptExtensionComparator); for (String path : viewInfosWithPathGTEThanPrefix.keySet()) { // we should have only few values to look at if (path.startsWith(pathPrefix)) { sortedScripts.add(viewInfosWithPathGTEThanPrefix.get(path)); } else { // as soon as the path doesn't start with the given prefix anymore, we won't have a match in the remaining so return return sortedScripts; } } return sortedScripts; } }
From source file:de.faustedition.tei.TeiValidator.java
@Override public void run() { try {// ww w .ja va 2s . c o m final SortedSet<FaustURI> xmlErrors = new TreeSet<FaustURI>(); final SortedMap<FaustURI, String> teiErrors = new TreeMap<FaustURI, String>(); for (FaustURI source : xml.iterate(new FaustURI(FaustAuthority.XML, "/transcript"))) { try { final List<String> errors = validate(source); if (!errors.isEmpty()) { teiErrors.put(source, Joiner.on("\n").join(errors)); } } catch (SAXException e) { logger.debug("XML error while validating transcript: " + source, e); xmlErrors.add(source); } catch (IOException e) { logger.warn("I/O error while validating transcript: " + source, e); } } if (xmlErrors.isEmpty() && teiErrors.isEmpty()) { return; } reporter.send("TEI validation report", new ReportCreator() { public void create(PrintWriter body) { if (!xmlErrors.isEmpty()) { body.println(Strings.padStart(" XML errors", 79, '=')); body.println(); body.println(Joiner.on("\n").join(xmlErrors)); body.println(); } if (!teiErrors.isEmpty()) { body.println(Strings.padStart(" TEI errors", 79, '=')); body.println(); for (Map.Entry<FaustURI, String> teiError : teiErrors.entrySet()) { body.println(Strings.padStart(" " + teiError.getKey(), 79, '-')); body.println(); body.println(teiError.getValue()); body.println(); body.println(); } } } }); } catch (EmailException e) { e.printStackTrace(); } }
From source file:de.appsolve.padelcampus.admin.controller.events.AdminEventsController.java
@RequestMapping(method = POST, value = "event/{eventId}/groupgamesend") public ModelAndView saveEventGroupGamesEnd(@PathVariable("eventId") Long eventId, @ModelAttribute("Model") Event dummy, BindingResult result) { Event event = eventDAO.findByIdFetchWithParticipantsAndGames(eventId); try {/* ww w.jav a2 s . c om*/ SortedMap<Integer, List<Game>> roundGames = eventsUtil.getRoundGameMap(event); if (!roundGames.isEmpty()) { throw new Exception(msg.get("GroupGamesAlreadyEnded")); } SortedMap<Integer, List<Game>> groupGames = eventsUtil.getGroupGameMap(event); if (groupGames.isEmpty()) { throw new Exception(msg.get("NoGroupGames")); } List<Participant> rankedParticipants = getRankedGroupParticipants(groupGames, event.getNumberOfGroups(), event.getNumberOfWinnersPerGroup()); eventsUtil.createKnockoutGames(event, rankedParticipants); return redirectToDraws(event); } catch (Exception e) { result.addError(new ObjectError("*", e.getMessage())); return getGroupGamesEndView(dummy); } }
From source file:de.appsolve.padelcampus.admin.controller.events.AdminEventsController.java
@RequestMapping(method = POST, value = "event/{eventId}/groupgamesend/{round}") public ModelAndView saveEventGroupGamesEndForRound(@PathVariable() Long eventId, @PathVariable Integer round, @ModelAttribute("Model") Event dummy, BindingResult result) { Event event = eventDAO.findByIdFetchWithParticipantsAndGames(eventId); try {// w w w . j a va 2s . co m SortedMap<Integer, List<Game>> roundGames = eventsUtil.getRoundGameMap(event, round + 1); if (!roundGames.isEmpty()) { throw new Exception(msg.get("GroupGamesAlreadyEnded")); } SortedMap<Integer, List<Game>> groupGames = eventsUtil.getGroupGameMap(event, round); if (groupGames.isEmpty()) { throw new Exception(msg.get("NoGroupGames")); } getRankedGroupParticipants(groupGames, event.getNumberOfGroups(), event.getNumberOfWinnersPerGroup()); return redirectToGroupDrawsRound(event, round + 1); } catch (Exception e) { result.addError(new ObjectError("*", e.getMessage())); return getGroupGamesEndView(dummy, round); } }
From source file:org.wrml.runtime.format.text.html.WrmldocFormatter.java
protected ObjectNode buildLinksNode(final ObjectMapper objectMapper, final Map<URI, ObjectNode> schemaNodes, final Map<URI, LinkRelation> linkRelationCache, final ApiNavigator apiNavigator, final Resource resource, final Prototype defaultPrototype) { final Context context = getContext(); final SchemaLoader schemaLoader = context.getSchemaLoader(); final SyntaxLoader syntaxLoader = context.getSyntaxLoader(); final URI defaultSchemaUri = (defaultPrototype != null) ? defaultPrototype.getSchemaUri() : null; final ObjectNode linksNode = objectMapper.createObjectNode(); final Set<URI> responseSchemaUris = new HashSet<>(); if (defaultSchemaUri != null) { responseSchemaUris.add(defaultSchemaUri); }/*from ww w . j a va 2s . c o m*/ for (final Method method : Method.values()) { final Set<URI> methodResponseSchemaUris = resource.getResponseSchemaUris(method); if (methodResponseSchemaUris != null && !methodResponseSchemaUris.isEmpty()) { responseSchemaUris.addAll(methodResponseSchemaUris); } } final ConcurrentHashMap<URI, LinkTemplate> linkTemplates = resource.getLinkTemplates(); for (final URI schemaUri : responseSchemaUris) { final Prototype prototype = schemaLoader.getPrototype(schemaUri); final SortedMap<URI, LinkProtoSlot> linkProtoSlots = prototype.getLinkProtoSlots(); if (linkProtoSlots == null || linkProtoSlots.isEmpty()) { continue; } final ObjectNode linkTemplatesNode = objectMapper.createObjectNode(); final Set<URI> linkRelationUris = linkProtoSlots.keySet(); for (final URI linkRelationUri : linkRelationUris) { final LinkProtoSlot linkProtoSlot = linkProtoSlots.get(linkRelationUri); if (schemaLoader.getDocumentSchemaUri().equals(linkProtoSlot.getDeclaringSchemaUri())) { // Skip over the built-in system-level link relations (which are all self-referential). continue; } final ObjectNode linkTemplateNode = objectMapper.createObjectNode(); final String linkSlotName = linkProtoSlot.getName(); linkTemplatesNode.put(linkSlotName, linkTemplateNode); final LinkRelation linkRelation = getLinkRelation(linkRelationCache, linkRelationUri); final Method method = linkRelation.getMethod(); linkTemplateNode.put(PropertyName.method.name(), method.getProtocolGivenName()); linkTemplateNode.put(PropertyName.rel.name(), syntaxLoader.formatSyntaxValue(linkRelationUri)); linkTemplateNode.put(PropertyName.relationTitle.name(), linkRelation.getTitle()); final URI responseSchemaUri; final URI requestSchemaUri; if (linkTemplates.containsKey(linkRelationUri)) { final LinkTemplate linkTemplate = linkTemplates.get(linkRelationUri); responseSchemaUri = linkTemplate.getResponseSchemaUri(); requestSchemaUri = linkTemplate.getRequestSchemaUri(); final UUID endPointId = linkTemplate.getEndPointId(); if (endPointId != null) { final Resource endPointResource = apiNavigator.getResource(endPointId); final ObjectNode endPointNode = objectMapper.createObjectNode(); endPointNode.put(PropertyName.id.name(), syntaxLoader.formatSyntaxValue(endPointId)); endPointNode.put(PropertyName.pathSegment.name(), endPointResource.getPathSegment()); endPointNode.put(PropertyName.fullPath.name(), endPointResource.getPathText()); endPointNode.put(PropertyName.uriTemplate.name(), endPointResource.getUriTemplate().getUriTemplateString()); linkTemplateNode.put(PropertyName.endpoint.name(), endPointNode); } } else { responseSchemaUri = linkProtoSlot.getResponseSchemaUri(); requestSchemaUri = linkProtoSlot.getRequestSchemaUri(); } if (responseSchemaUri != null) { final ObjectNode responseSchemaNode = getSchemaNode(objectMapper, schemaNodes, responseSchemaUri, schemaLoader); linkTemplateNode.put(PropertyName.responseSchema.name(), responseSchemaNode); } if (requestSchemaUri != null) { final ObjectNode requestSchemaNode = getSchemaNode(objectMapper, schemaNodes, requestSchemaUri, schemaLoader); linkTemplateNode.put(PropertyName.requestSchema.name(), requestSchemaNode); } final String signature = buildLinkSignature(linkSlotName, responseSchemaUri, requestSchemaUri, schemaUri); linkTemplateNode.put(PropertyName.signature.name(), signature); } if (linkTemplatesNode.size() > 0) { final ObjectNode schemaNode = objectMapper.createObjectNode(); final ObjectNode schemaDetailsNode = getSchemaNode(objectMapper, schemaNodes, schemaUri, schemaLoader); schemaNode.put(PropertyName.schema.name(), schemaDetailsNode); schemaNode.put(PropertyName.linkTemplates.name(), linkTemplatesNode); linksNode.put(prototype.getUniqueName().getLocalName(), schemaNode); } } return linksNode; }
From source file:org.apache.hadoop.hbase.MetaTableAccessor.java
/** * Returns an HRegionLocationList extracted from the result. * @return an HRegionLocationList containing all locations for the region range or null if * we can't deserialize the result.//from ww w . ja va2s. c o m */ @Nullable public static RegionLocations getRegionLocations(final Result r) { if (r == null) return null; HRegionInfo regionInfo = getHRegionInfo(r, getRegionInfoColumn()); if (regionInfo == null) return null; List<HRegionLocation> locations = new ArrayList<HRegionLocation>(1); NavigableMap<byte[], NavigableMap<byte[], byte[]>> familyMap = r.getNoVersionMap(); locations.add(getRegionLocation(r, regionInfo, 0)); NavigableMap<byte[], byte[]> infoMap = familyMap.get(getCatalogFamily()); if (infoMap == null) return new RegionLocations(locations); // iterate until all serverName columns are seen int replicaId = 0; byte[] serverColumn = getServerColumn(replicaId); SortedMap<byte[], byte[]> serverMap = infoMap.tailMap(serverColumn, false); if (serverMap.isEmpty()) return new RegionLocations(locations); for (Map.Entry<byte[], byte[]> entry : serverMap.entrySet()) { replicaId = parseReplicaIdFromServerColumn(entry.getKey()); if (replicaId < 0) { break; } HRegionLocation location = getRegionLocation(r, regionInfo, replicaId); // In case the region replica is newly created, it's location might be null. We usually do not // have HRL's in RegionLocations object with null ServerName. They are handled as null HRLs. if (location == null || location.getServerName() == null) { locations.add(null); } else { locations.add(location); } } return new RegionLocations(locations); }
From source file:de.appsolve.padelcampus.admin.controller.events.AdminEventsController.java
@RequestMapping(value = { "edit/{eventId}/groupdraws" }, method = POST) public ModelAndView postGroupDraws(@PathVariable("eventId") Long eventId, @ModelAttribute("Model") @Valid EventGroups eventGroups, BindingResult bindingResult, HttpServletRequest request) {/*from ww w .j a v a2 s.c o m*/ Event event = eventDAO.findByIdFetchWithParticipantsAndGames(eventId); Iterator<Map.Entry<Integer, Set<Participant>>> iterator = eventGroups.getGroupParticipants().entrySet() .iterator(); while (iterator.hasNext()) { Map.Entry<Integer, Set<Participant>> entry = iterator.next(); if (entry.getValue() == null) { bindingResult.reject("PleaseSelectParticipantsForEachGroup"); } } //prevent modification of group draws if knockout round games have already begun if (event.getEventType().equals(EventType.Knockout)) { SortedMap<Integer, List<Game>> roundGames = eventsUtil.getRoundGameMap(event); if (!roundGames.isEmpty()) { bindingResult.reject("CannotModifyEventAfterGroupPhaseHasEnded"); } } if (bindingResult.hasErrors()) { return getGroupDrawsView(event, eventGroups); } //remove games that have not been played yet gameUtil.removeObsoleteGames(event); //remove games with teams that are no longer part of a group Iterator<Game> gameIterator = event.getGames().iterator(); while (gameIterator.hasNext()) { Game game = gameIterator.next(); Integer groupNumber = game.getGroupNumber(); if (groupNumber != null) { Set<Participant> groupParticipants = eventGroups.getGroupParticipants().get(groupNumber); if (!groupParticipants.containsAll(game.getParticipants())) { gameDAO.deleteById(game.getId()); gameIterator.remove(); } } } //create missing games for (int groupNumber = 0; groupNumber < event.getNumberOfGroups(); groupNumber++) { Set<Participant> groupParticipants = eventGroups.getGroupParticipants().get(groupNumber); Integer roundNumber = null; switch (event.getEventType()) { case GroupKnockout: //for GroupKnockout events, only knockout games have a round roundNumber = ROUND_NONE; break; case GroupTwoRounds: //for GroupTwoRound events, every round has a number roundNumber = ROUND_ONE; break; } gameUtil.createMissingGames(event, groupParticipants, groupNumber, roundNumber); } return new ModelAndView("redirect:/admin/events/edit/" + eventId + "/groupschedule"); }
From source file:com.aurel.track.fieldType.runtime.custom.select.CustomDependentSelectRT.java
/** * Loads the datasource and value for configuring the field change * @param workflowContext/*from w w w .j ava 2 s.c om*/ * @param fieldChangeValue * @param parameterCode * @param personBean * @param locale */ @Override public void loadFieldChangeDatasourceAndValue(WorkflowContext workflowContext, FieldChangeValue fieldChangeValue, Integer parameterCode, TPersonBean personBean, Locale locale) { SortedMap<Integer, Integer[]> actualValuesMap = null; try { actualValuesMap = (SortedMap<Integer, Integer[]>) fieldChangeValue.getValue(); } catch (Exception e) { LOGGER.warn("ValueModified: converting the massOperationExpression values to map failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } if (actualValuesMap == null || actualValuesMap.isEmpty()) { return; } Integer fieldID = fieldChangeValue.getFieldID(); SortedMap<Integer, List<IBeanID>> compositeDataSource = (SortedMap<Integer, List<IBeanID>>) fieldChangeValue .getPossibleValues(); Object actualParentValue = actualValuesMap.get(parentID); Integer[] parentIntArr = null; Integer parentIntValue = null; try { parentIntArr = (Integer[]) actualParentValue; if (parentIntArr != null && parentIntArr.length > 0) { parentIntValue = parentIntArr[0]; } } catch (Exception e) { LOGGER.warn("Converting the parent value to Integer[] failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } List<IBeanID> possiblePartValues = null; if (parentIntValue != null) { TOptionBean optionBean = OptionBL.loadByPrimaryKey(parentIntValue); Integer parentListID = optionBean.getList(); //get the childNumber'th child list of the parentListID TListBean childListBean = ListBL.getChildList(parentListID, childNumber); if (childListBean != null) { possiblePartValues = LocalizeUtil.localizeDropDownList( optionDAO.loadCreateDataSourceByListAndParents(childListBean.getObjectID(), parentIntArr), locale); } actualValuesMap.put(parameterCode, getBulkSelectValue(null, fieldID, parameterCode, actualValuesMap.get(parameterCode), possiblePartValues)); } if (possiblePartValues != null) { compositeDataSource.put(parameterCode, possiblePartValues); } }
From source file:fr.landel.utils.commons.MapUtils2Test.java
/** * Test method for/*from ww w . ja va 2 s . c om*/ * {@link MapUtils2#newMap(java.util.function.Supplier, java.lang.Class, java.lang.Class, java.lang.Object[])}. */ @Test public void testNewMapSupplierClass() { SortedMap<String, Long> map = MapUtils2.newMap(TreeMap::new, String.class, Long.class, "key1", 1L, "key2", 2L); assertTrue(map instanceof TreeMap); assertEquals(2, map.size()); Map<String, Long> expectedMap = new HashMap<>(); expectedMap.put("key1", 1L); expectedMap.put("key2", 2L); for (Entry<String, Long> entry : expectedMap.entrySet()) { assertTrue(map.containsKey(entry.getKey())); assertEquals(entry.getValue(), map.get(entry.getKey())); } map = MapUtils2.newMap(TreeMap::new, String.class, Long.class); assertTrue(map instanceof TreeMap); assertTrue(map.isEmpty()); map = MapUtils2.newMap(() -> new TreeMap<>(Comparators.STRING.desc()), String.class, Long.class, "key1", 1L, "key2", 2L, null, 3L, "key4", null, 2d, 5L, "key6", true); assertTrue(map instanceof TreeMap); assertEquals(4, map.size()); "key2".equals(map.firstKey()); map = MapUtils2.newMap(TreeMap::new, String.class, Long.class, new Object[0]); assertTrue(map instanceof TreeMap); assertTrue(map.isEmpty()); assertException(() -> { MapUtils2.newMap(TreeMap::new, null, Long.class, "", ""); }, NullPointerException.class); assertException(() -> { MapUtils2.newMap(TreeMap::new, String.class, null, "", ""); }, NullPointerException.class); assertException(() -> { MapUtils2.newMap(null, String.class, Long.class, "", ""); }, NullPointerException.class); assertException(() -> { MapUtils2.newMap(TreeMap::new, String.class, Long.class, (Object[]) null); }, IllegalArgumentException.class, "objects cannot be null or empty and has to contain an odd number of elements"); assertException(() -> { MapUtils2.newMap(TreeMap::new, String.class, Long.class, "key"); }, IllegalArgumentException.class, "objects cannot be null or empty and has to contain an odd number of elements"); }