List of usage examples for java.util SortedSet first
E first();
From source file:org.commoncrawl.io.internal.NIODNSCache.java
private void setCannonicalNameForNode(Node node, String cName) { SortedSet<String> subset = _cannonicalNames.subSet(cName, cName + "\0"); if (!subset.isEmpty()) { node._cannonicalName = subset.first(); } else {//from w w w .ja v a2 s . com node._cannonicalName = cName; _cannonicalNames.add(cName); } }
From source file:org.apache.hadoop.hdfs.server.namenode.JournalSet.java
/** * Return a manifest of what finalized edit logs are available. All available * edit logs are returned starting from the transaction id passed. If * 'fromTxId' falls in the middle of a log, that log is returned as well. * //from w w w. j a v a 2s . c om * @param fromTxId Starting transaction id to read the logs. * @return RemoteEditLogManifest object. */ public synchronized RemoteEditLogManifest getEditLogManifest(long fromTxId) { // Collect RemoteEditLogs available from each FileJournalManager List<RemoteEditLog> allLogs = Lists.newArrayList(); for (JournalAndStream j : journals) { if (j.getManager() instanceof FileJournalManager) { FileJournalManager fjm = (FileJournalManager) j.getManager(); try { allLogs.addAll(fjm.getRemoteEditLogs(fromTxId, false)); } catch (Throwable t) { LOG.warn("Cannot list edit logs in " + fjm, t); } } } // Group logs by their starting txid ImmutableListMultimap<Long, RemoteEditLog> logsByStartTxId = Multimaps.index(allLogs, RemoteEditLog.GET_START_TXID); long curStartTxId = fromTxId; List<RemoteEditLog> logs = Lists.newArrayList(); while (true) { ImmutableList<RemoteEditLog> logGroup = logsByStartTxId.get(curStartTxId); if (logGroup.isEmpty()) { // we have a gap in logs - for example because we recovered some old // storage directory with ancient logs. Clear out any logs we've // accumulated so far, and then skip to the next segment of logs // after the gap. SortedSet<Long> startTxIds = Sets.newTreeSet(logsByStartTxId.keySet()); startTxIds = startTxIds.tailSet(curStartTxId); if (startTxIds.isEmpty()) { break; } else { if (LOG.isDebugEnabled()) { LOG.debug("Found gap in logs at " + curStartTxId + ": " + "not returning previous logs in manifest."); } logs.clear(); curStartTxId = startTxIds.first(); continue; } } // Find the one that extends the farthest forward RemoteEditLog bestLog = Collections.max(logGroup); logs.add(bestLog); // And then start looking from after that point curStartTxId = bestLog.getEndTxId() + 1; } RemoteEditLogManifest ret = new RemoteEditLogManifest(logs); if (LOG.isDebugEnabled()) { LOG.debug("Generated manifest for logs since " + fromTxId + ":" + ret); } return ret; }
From source file:net.sf.jasperreports.engine.export.tabulator.Tabulator.java
protected boolean placeElement(Table table, FrameCell parentCell, int xOffset, int yOffset, JRPrintElement element, PrintElementIndex parentIndex, int elementIndex, boolean allowOverlap) { DimensionRange<Column> colRange = table.columns.getRange(element.getX() + xOffset, element.getX() + element.getWidth() + xOffset); DimensionRange<Row> rowRange = table.rows.getRange(element.getY() + yOffset, element.getY() + element.getHeight() + yOffset); if (log.isTraceEnabled()) { log.trace("placing element " + element.getUUID() + " at " + colRange.start + ", " + colRange.end + ", " + rowRange.start + ", " + rowRange.end); }//from w ww .j a va 2 s. c o m boolean overlap = false; Bounds overlapBounds = new Bounds(colRange.start, colRange.end, rowRange.start, rowRange.end); JROrigin elementOrigin = element.getOrigin(); if (parentCell == null // top level element && elementOrigin != null && elementOrigin.getReportName() == null // master background element // TODO lucianc do something for subreport background bands as well && elementOrigin.getBandTypeValue() == BandTypeEnum.BACKGROUND) { // create a layer as big as the table for the master background band SortedSet<Column> userColumns = table.columns.getUserEntries(); SortedSet<Row> userRows = table.rows.getUserEntries(); // check if we have something in the table if (!userColumns.isEmpty() && !userRows.isEmpty()) { overlapBounds.grow(userColumns.first().startCoord, userColumns.last().endCoord, userRows.first().startCoord, userRows.last().endCoord); // TODO lucianc avoid the following cell overlap checks } } Bounds covered = null; Bounds originalBounds; overlapLoop: do { originalBounds = overlapBounds.cloneBounds(); if (rowRange.start != overlapBounds.getStartY() || rowRange.end != overlapBounds.getEndY()) { rowRange = table.rows.getRange(overlapBounds.getStartY(), overlapBounds.getEndY()); } if (colRange.start != overlapBounds.getStartX() || colRange.end != overlapBounds.getEndX()) { colRange = table.columns.getRange(overlapBounds.getStartX(), overlapBounds.getEndX()); } for (Row row : rowRange.rangeSet) { for (Column col : colRange.rangeSet) { if (covered != null && covered.contains(col.startCoord, col.endCoord, row.startCoord, row.endCoord)) { //we've been here before continue; } Cell cell = row.getCell(col); if (!canOverwrite(cell, parentCell)) { overlap = true; if (!allowOverlap) { break overlapLoop; } // TODO lucianc see if we can avoid some of these checks Cell overlapParentCell = overlapParentCell(cell, parentCell); Pair<Column, Column> colSpanRange = getColumnSpanRange(table, col, row, overlapParentCell); Pair<Row, Row> rowSpanRange = getRowSpanRange(table, col, row, overlapParentCell); if (log.isTraceEnabled()) { log.trace("found overlap with cell " + cell + ", overlap parent " + overlapParentCell + ", column span range " + colSpanRange.first().startCoord + " to " + colSpanRange.second().startCoord + ", row span range " + rowSpanRange.first().startCoord + " to " + rowSpanRange.second().startCoord); } overlapBounds.grow(colSpanRange.first().startCoord, colSpanRange.second().startCoord, rowSpanRange.first().startCoord, rowSpanRange.second().startCoord); } } } covered = originalBounds; } while (!originalBounds.equals(overlapBounds)); if (!overlap) { setElementCells(table, parentCell, xOffset, yOffset, element, parentIndex, elementIndex, colRange, rowRange); return true; } if (!allowOverlap) { return false; } placeOverlappedElement(table, parentCell, xOffset, yOffset, element, parentIndex, elementIndex, overlapBounds); return true; }
From source file:org.wrml.runtime.schema.Prototype.java
/** * Creates a new Prototype to represent the identified schema. * * @param schemaLoader The schema loader for this prototype's schema. * @param schemaUri The schema identifier. * @throws PrototypeException Thrown if there are problems with the initial prototyping of the schema. *///from w w w .j av a 2s . c o m Prototype(final SchemaLoader schemaLoader, final URI schemaUri) throws PrototypeException { LOGGER.debug("Creating Prototype for schema ID: {}", new Object[] { schemaUri }); _SchemaLoader = schemaLoader; if (_SchemaLoader == null) { throw new PrototypeException("The SchemaLoader parameter value cannot be *null*.", null, this); } _SchemaUri = schemaUri; if (_SchemaUri == null) { throw new PrototypeException("The undefined (aka *null*) schema can not be prototyped.", null, this); } if (schemaUri.equals(schemaLoader.getResourceTemplateSchemaUri())) { LOGGER.debug("Creating Prototype for ResourceTemplate"); } _UniqueName = new UniqueName(_SchemaUri); // // Use the SchemaLoader and the schema uri to get the schema's Java Class // representation. // final Class<?> schemaInterface = getSchemaInterface(); if (ValueType.JAVA_TYPE_ABSTRACT.equals(schemaInterface)) { _IsAbstract = true; } else if (Document.class.equals(schemaInterface)) { _IsDocument = true; } // // Introspect the associated class, extracting metadata from the parent // schema's Java interfaces (up to but not including the Model // interface). // _SchemaBean = new JavaBean(schemaInterface, ValueType.JAVA_TYPE_MODEL, LinkSlot.class); _AllBaseSchemaUris = new LinkedHashSet<>(); _BaseSchemaUris = new LinkedHashSet<>(); _AllSlotNames = new TreeSet<>(); _ProtoSlots = new TreeMap<>(); _CollectionPropertyProtoSlots = new TreeMap<>(); _LinkRelationUris = new TreeMap<>(); _LinkProtoSlots = new TreeMap<>(); _SlotAliases = new TreeMap<>(); _SearchableSlots = new TreeSet<>(); // initBaseSchemas(...) { // // Use Java reflection to get all implemented interfaces and then turn // them into schema ids. With reflection we get de-duplication and // recursive traversal for free. // final List<Class<?>> allBaseInterfaces = ClassUtils.getAllInterfaces(schemaInterface); // Loop backwards to achieve desired key mapping precedence/overriding for (final Class<?> baseInterface : allBaseInterfaces) { if (ValueType.isSchemaInterface(baseInterface) && (baseInterface != ValueType.JAVA_TYPE_MODEL)) { final URI baseSchemaUri = _SchemaLoader.getTypeUri(baseInterface); _AllBaseSchemaUris.add(baseSchemaUri); if (Document.class.equals(baseInterface)) { _IsDocument = true; } if (AggregateDocument.class.equals(baseInterface)) { _IsAggregate = true; } } } // Store the immediate base schemas as well final Class<?>[] baseInterfaces = schemaInterface.getInterfaces(); if (baseInterfaces != null) { for (final Class<?> baseInterface : baseInterfaces) { if (ValueType.isSchemaInterface(baseInterface) && (baseInterface != ValueType.JAVA_TYPE_MODEL)) { final URI baseSchemaUri = _SchemaLoader.getTypeUri(baseInterface); _BaseSchemaUris.add(baseSchemaUri); } if (ValueType.JAVA_TYPE_ABSTRACT.equals(baseInterface)) { _IsAbstract = true; } } } } // End of base schema init // initKeys(...) { final WRML wrml = schemaInterface.getAnnotation(WRML.class); if (wrml != null) { final String[] keySlotNameArray = wrml.keySlotNames(); if ((keySlotNameArray != null) && (keySlotNameArray.length > 0)) { _KeySlotNames = new TreeSet<>(Arrays.asList(keySlotNameArray)); if (_KeySlotNames.size() == 1) { final String keySlotName = _KeySlotNames.first(); final Property property = _SchemaBean.getProperties().get(keySlotName); if (property != null) { _KeyType = property.getType(); } else { throw new PrototypeException("The named key slot, \"" + keySlotName + "\", is not defined for Schema: " + schemaUri + ".", null, this); } } else { // Schemas with Keys that use more than one slot value to // determine uniqueness use the CompositeKey type (at // runtime) as their key object. // _KeyType = ValueType.JAVA_TYPE_COMPOSITE_KEY; } } final String[] comparableSlotNameArray = wrml.comparableSlotNames(); if ((comparableSlotNameArray != null) && (comparableSlotNameArray.length > 0)) { _ComparableSlotNames = new LinkedHashSet<String>(Arrays.asList(comparableSlotNameArray)); } final String titleSlotName = wrml.titleSlotName(); if (StringUtils.isNotBlank(titleSlotName)) { _TitleSlotName = titleSlotName; } } } // End of the key initialization // initMiscAnnotations(...) { final Description schemaDescription = schemaInterface.getAnnotation(Description.class); if (schemaDescription != null) { _Description = schemaDescription.value(); } else { _Description = null; } final Title schemaTitle = schemaInterface.getAnnotation(Title.class); if (schemaTitle != null) { _Title = schemaTitle.value(); } else { _Title = schemaInterface.getSimpleName(); } final ThumbnailImage thumbnailImage = schemaInterface.getAnnotation(ThumbnailImage.class); if (thumbnailImage != null) { _ThumbnailLocation = URI.create(thumbnailImage.value()); } else { _ThumbnailLocation = null; } _ReadOnly = (schemaInterface.getAnnotation(ReadOnly.class) != null) ? true : false; final Version schemaVersion = schemaInterface.getAnnotation(Version.class); if (schemaVersion != null) { _Version = schemaVersion.value(); } else { // TODO: Look for the "static final long serialVersionUID" ? _Version = 1L; } final Tags tags = schemaInterface.getAnnotation(Tags.class); if (tags != null) { final String[] tagArray = tags.value(); if ((tagArray != null) && (tagArray.length > 0)) { _Tags = new TreeSet<String>(Arrays.asList(tagArray)); } } } // End of annotation-based initialization // initPropertySlots(...) { final Map<String, Property> properties = _SchemaBean.getProperties(); for (final String slotName : properties.keySet()) { final Property property = properties.get(slotName); final PropertyProtoSlot propertyProtoSlot; final CollectionSlot collectionSlot = property.getAnnotation(CollectionSlot.class); if (collectionSlot != null) { propertyProtoSlot = new CollectionPropertyProtoSlot(this, slotName, property); } else { propertyProtoSlot = new PropertyProtoSlot(this, slotName, property); } addProtoSlot(propertyProtoSlot); } } // initLinkSlots(...) { // // Map the the schema bean's "other" (non-Property) methods. // final SortedMap<String, SortedSet<JavaMethod>> otherMethods = _SchemaBean.getOtherMethods(); final Set<String> otherMethodNames = otherMethods.keySet(); for (final String methodName : otherMethodNames) { final SortedSet<JavaMethod> methodSet = otherMethods.get(methodName); if (methodSet.size() != 1) { throw new PrototypeException("The link method: " + methodName + " cannot be overloaded.", this); } final JavaMethod javaMethod = methodSet.first(); final Method method = javaMethod.getMethod(); final LinkSlot linkSlot = method.getAnnotation(LinkSlot.class); if (linkSlot == null) { throw new PrototypeException("The method: " + javaMethod + " is not a link method", null, this); } final String relationUriString = linkSlot.linkRelationUri(); final URI linkRelationUri = URI.create(relationUriString); if (_LinkProtoSlots.containsKey(linkRelationUri)) { throw new PrototypeException( "A schema cannot use the same link relation for more than one method. Duplicate link relation: " + linkRelationUri + " found in link method: " + javaMethod, this); } final org.wrml.model.rest.Method relMethod = linkSlot.method(); String slotName = methodName; if (relMethod == org.wrml.model.rest.Method.Get && slotName.startsWith(JavaBean.GET)) { slotName = slotName.substring(3); slotName = Character.toLowerCase(slotName.charAt(0)) + slotName.substring(1); } _LinkRelationUris.put(slotName, linkRelationUri); if (_ProtoSlots.containsKey(slotName)) { throw new PrototypeException( "A schema cannot use the same name for more than one slot. Duplicate slot name: " + slotName + " found in link method: " + javaMethod, this); } final LinkProtoSlot linkProtoSlot = new LinkProtoSlot(this, slotName, javaMethod); if ((linkProtoSlot.isEmbedded() || isAggregate()) && (relMethod == org.wrml.model.rest.Method.Get)) { _ContainsEmbeddedLink = true; } _LinkProtoSlots.put(linkRelationUri, linkProtoSlot); addProtoSlot(linkProtoSlot); } } // End of link slot init if (!_SlotAliases.isEmpty()) { for (final String alias : _SlotAliases.keySet()) { final ProtoSlot protoSlot = _ProtoSlots.get(alias); protoSlot.setAlias(true); final String realName = _SlotAliases.get(alias); protoSlot.setRealName(realName); } } }
From source file:org.orcid.persistence.adapter.impl.Jpa2JaxbAdapterImpl.java
private Applications getApplications(ProfileEntity profileEntity) { Set<OrcidOauth2TokenDetail> tokenDetails = profileEntity.getTokenDetails(); if (tokenDetails != null && !tokenDetails.isEmpty()) { Applications applications = new Applications(); for (OrcidOauth2TokenDetail tokenDetail : tokenDetails) { if (tokenDetail.getTokenDisabled() == null || !tokenDetail.getTokenDisabled()) { ApplicationSummary applicationSummary = new ApplicationSummary(); ClientDetailsEntity acceptedClient = tokenDetail.getClientDetailsEntity(); ProfileEntity acceptedClientProfileEntity = acceptedClient != null ? acceptedClient.getProfileEntity() : null;//from w w w. j a va 2 s.c o m if (acceptedClientProfileEntity != null) { applicationSummary.setApplicationOrcid(new ApplicationOrcid(acceptedClient.getClientId())); applicationSummary.setApplicationName( new ApplicationName(acceptedClientProfileEntity.getCreditName())); SortedSet<ResearcherUrlEntity> researcherUrls = acceptedClient.getProfileEntity() .getResearcherUrls(); if (researcherUrls != null && !researcherUrls.isEmpty()) { applicationSummary .setApplicationWebsite(new ApplicationWebsite(researcherUrls.first().getUrl())); } applicationSummary.setApprovalDate(new ApprovalDate( DateUtils.convertToXMLGregorianCalendar(tokenDetail.getDateCreated()))); // Scopes Set<ScopePathType> scopesGrantedToClient = ScopePathType .getScopesFromSpaceSeparatedString(tokenDetail.getScope()); if (scopesGrantedToClient != null && !scopesGrantedToClient.isEmpty()) { ScopePaths scopePaths = new ScopePaths(); for (ScopePathType scopesForClient : scopesGrantedToClient) { scopePaths.getScopePath().add(new ScopePath(scopesForClient)); } applicationSummary.setScopePaths(scopePaths); } applications.getApplicationSummary().add(applicationSummary); } } } return applications; } return null; }
From source file:nl.b3p.viewer.config.services.WMSService.java
/** * Set feature types for layers in the WMSService from the given WFS according * to the DescribeLayer response. When errors occur these are logged but no * exception is thrown. Note: DescribeLayer may return multiple type names * for a layer, this is not supported - only the first one is used. * @param wfsUrl the WFS URL//from w w w . j av a2 s .c o m * @param layerDescriptions description of which feature types of the WFS are * used in layers of this service according to DescribeLayer */ public void loadLayerFeatureTypes(String wfsUrl, List<LayerDescription> layerDescriptions) { Map p = new HashMap(); p.put(WFSDataStoreFactory.URL.key, wfsUrl); p.put(WFSDataStoreFactory.USERNAME.key, getUsername()); p.put(WFSDataStoreFactory.PASSWORD.key, getPassword()); try { WFSFeatureSource wfsFs = new WFSFeatureSource(p); wfsFs.loadFeatureTypes(); boolean used = false; for (LayerDescription ld : layerDescriptions) { Layer l = getLayer(ld.getName()); if (l != null) { // Prevent warning when multiple queries for all the same type name // by removing duplicates, but keeping sort order to pick the first SortedSet<String> uniqueQueries = new TreeSet(Arrays.asList(ld.getQueries())); if (uniqueQueries.size() != 1) { // Allowed by spec but not handled by this application log.warn("Cannot handle multiple typeNames for layer " + l.getName() + ", only using the first. Type names: " + Arrays.toString(ld.getQueries())); } // Queries is not empty, checked before this method is called SimpleFeatureType sft = wfsFs.getFeatureType(uniqueQueries.first()); if (sft != null) { // Type name may not exist in the referenced WFS l.setFeatureType(sft); log.debug("Feature type for layer " + l.getName() + " set to feature type " + sft.getTypeName()); used = true; } else { log.warn("Type name " + uniqueQueries.first() + " in WFS for described layer " + l.getName() + " does not exist!"); } } } if (used) { log.debug("Type from WFSFeatureSource with url " + wfsUrl + " used by layer of WMS"); wfsFs.setLinkedService(this); } else { log.debug("No type from WFSFeatureSource with url " + wfsUrl + " used!"); } } catch (Exception e) { log.error("Error loading WFS from url " + wfsUrl, e); } }
From source file:net.sourceforge.fenixedu.domain.Lesson.java
private Summary getLastSummary() { SortedSet<Summary> summaries = getSummariesSortedByNewestDate(); return (summaries.isEmpty()) ? null : summaries.first(); }
From source file:org.marketcetera.marketdata.core.manager.impl.MarketDataManagerImpl.java
@Override public Event requestMarketDataSnapshot(Instrument inInstrument, Content inContent, String inProvider) { if (inProvider == null) { SortedSet<Pair<FeedType, Event>> snapshotCandidates = Sets.newTreeSet(SnapshotComparator.INSTANCE); for (MarketDataProvider provider : getActiveMarketDataProviders()) { Event snapshotCandidate = provider.getSnapshot(inInstrument, inContent); if (snapshotCandidate != null) { snapshotCandidates.add(Pair.create(provider.getFeedType(), snapshotCandidate)); }/*from www. j ava 2s . c o m*/ } if (snapshotCandidates.isEmpty()) { return null; } return snapshotCandidates.first().getSecondMember(); } else { MarketDataProvider provider = getMarketDataProviderForName(inProvider); if (provider == null) { throw new MarketDataProviderNotAvailable(); } return provider.getSnapshot(inInstrument, inContent); } }
From source file:org.commoncrawl.util.ArcFileWriter.java
/** * append a pre-generated arcfile entry directly into the arc file writer * //from ww w . java 2 s . c o m * @param arcFileData * - the compressed arc file entry * @param dataBufferLength * - the entry length * @throws IOException */ public void writeRawArcFileItem(String contentType, byte[] arcFileData, int dataBufferLength) throws IOException { // check to see if we need to start a new underlying file checkSize(0, dataBufferLength); // update stats getActiveFile()._totalContentBytesWritten += dataBufferLength; getActiveFile()._itemsWritten++; SortedSet<Integer> counts = _mimeTypeCounts.get(contentType); if (counts.size() == 0) { counts.add(1); } else { int count = counts.first() + 1; counts.clear(); counts.add(count); } // record start position of this item _lastItemPos = getActiveFile().getFileSize(); // write out data _out.write(arcFileData, 0, dataBufferLength); // record size of last item _lastItemCompressedSize = (getActiveFile().getFileSize() - _lastItemPos); // update stats getActiveFile()._compressedBytesWritten += _lastItemCompressedSize; }
From source file:org.commoncrawl.util.ArcFileWriter.java
private void preWriteRecordTasks(int headerBytesLength, int contentBytesLength, String contentType) throws IOException { checkSize(headerBytesLength, contentBytesLength); // update stats getActiveFile()._totalHeaderBytesWritten += headerBytesLength; getActiveFile()._totalContentBytesWritten += contentBytesLength; getActiveFile()._itemsWritten++;/*from ww w . j ava2 s . c om*/ SortedSet<Integer> counts = _mimeTypeCounts.get(contentType); if (counts.size() == 0) { counts.add(1); } else { int count = counts.first() + 1; counts.clear(); counts.add(count); } // record start position of this item _lastItemPos = getActiveFile().getFileSize(); // Wrap stream in GZIP Writer. // The below construction immediately writes the GZIP 'default' // header out on the underlying stream. _out = new CompressedStream(_out); }