Java Code Examples for java.util.SortedMap
The following code examples are extracted from open source projects. You can click to
vote up the examples that are useful to you.
Example 1
From project collections-generic, under directory /src/test/org/apache/commons/collections15/map/.
Source file: TestLazySortedMap.java

public void testSortOrder(){ SortedMap map=makeTestSortedMap(oneFactory); map.put("A","a"); map.get("B"); map.put("C","c"); assertEquals("First key should be A",map.firstKey(),"A"); assertEquals("Last key should be C",map.lastKey(),"C"); assertEquals("First key in tail map should be B",map.tailMap("B").firstKey(),"B"); assertEquals("Last key in head map should be B",map.headMap("C").lastKey(),"B"); assertEquals("Last key in submap should be B",map.subMap("A","C").lastKey(),"B"); Comparator c=map.comparator(); assertTrue("natural order, so comparator should be null",c == null); }
Example 2
From project jboss-jstl-api_spec, under directory /src/main/java/javax/servlet/jsp/jstl/sql/.
Source file: ResultImpl.java

/** * This constructor reads the ResultSet and saves a cached copy. It's important to note that this object will be serializable only if the objects returned by the ResultSet are serializable too. * @param rs an open <tt>ResultSet</tt>, positioned before the firstrow * @param startRow beginning row to be cached * @param maxRows query maximum rows limit * @exception java.sql.SQLException if a database error occurs */ public ResultImpl(ResultSet rs,int startRow,int maxRows) throws SQLException { rowMap=new ArrayList(); rowByIndex=new ArrayList(); ResultSetMetaData rsmd=rs.getMetaData(); int noOfColumns=rsmd.getColumnCount(); columnNames=new String[noOfColumns]; for (int i=1; i <= noOfColumns; i++) { columnNames[i - 1]=rsmd.getColumnName(i); } for (int i=0; i < startRow; i++) { rs.next(); } int processedRows=0; while (rs.next()) { if ((maxRows != -1) && (processedRows == maxRows)) { isLimited=true; break; } Object[] columns=new Object[noOfColumns]; SortedMap columnMap=new TreeMap(String.CASE_INSENSITIVE_ORDER); for (int i=1; i <= noOfColumns; i++) { Object value=rs.getObject(i); if (rs.wasNull()) { value=null; } columns[i - 1]=value; columnMap.put(columnNames[i - 1],value); } rowMap.add(columnMap); rowByIndex.add(columns); processedRows++; } }
Example 3
From project AChartEngine, under directory /achartengine/src/org/achartengine/model/.
Source file: XYSeries.java

/** * Returns submap of x and y values according to the given start and end * @param start start x value * @param stop stop x value * @return */ public synchronized SortedMap<Double,Double> getRange(double start,double stop,int beforeAfterPoints){ SortedMap<Double,Double> headMap=mXY.headMap(start); if (!headMap.isEmpty()) { start=headMap.lastKey(); } SortedMap<Double,Double> tailMap=mXY.tailMap(stop); if (!tailMap.isEmpty()) { Iterator<Double> tailIterator=tailMap.keySet().iterator(); Double next=tailIterator.next(); if (tailIterator.hasNext()) { stop=tailIterator.next(); } else { stop+=next; } } return mXY.subMap(start,stop); }
Example 4
From project agileBase, under directory /gtpb_server/src/com/gtwm/pb/model/manageData/.
Source file: ViewMethods.java

public SortedMap<TableInfo,SortedSet<BaseField>> adminGetRelationCandidates() throws DisallowedException, ObjectNotFoundException { TableInfo table=this.sessionData.getTable(); if (!(getAuthenticator().loggedInUserAllowedTo(this.request,PrivilegeType.MANAGE_TABLE,table))) { throw new DisallowedException(this.getLoggedInUser(),PrivilegeType.MANAGE_TABLE,table); } CompanyInfo company=this.databaseDefn.getAuthManager().getCompanyForLoggedInUser(this.request); SortedSet<TableInfo> companyTables=company.getTables(); SortedMap<TableInfo,SortedSet<BaseField>> relationCandidates=new TreeMap<TableInfo,SortedSet<BaseField>>(); for ( TableInfo testTable : companyTables) { if (!(testTable.equals(table))) { if (this.getAuthenticator().loggedInUserAllowedTo(this.request,PrivilegeType.VIEW_TABLE_DATA,table)) { SortedSet<BaseField> uniqueFieldsForTable=new TreeSet<BaseField>(); for ( BaseField testField : testTable.getFields()) { if (testField.getUnique()) { uniqueFieldsForTable.add(testField); } } if (uniqueFieldsForTable.size() > 0) { relationCandidates.put(testTable,uniqueFieldsForTable); } } } } return relationCandidates; }
Example 5
From project android_external_guava, under directory /src/com/google/common/collect/.
Source file: ImmutableSortedMap.java

private static <K,V>ImmutableSortedMap<K,V> copyOfInternal(Map<? extends K,? extends V> map,Comparator<? super K> comparator){ boolean sameComparator=false; if (map instanceof SortedMap) { SortedMap<?,?> sortedMap=(SortedMap<?,?>)map; Comparator<?> comparator2=sortedMap.comparator(); sameComparator=(comparator2 == null) ? comparator == NATURAL_ORDER : comparator.equals(comparator2); } if (sameComparator && (map instanceof ImmutableSortedMap)) { @SuppressWarnings("unchecked") ImmutableSortedMap<K,V> kvMap=(ImmutableSortedMap<K,V>)map; return kvMap; } List<Entry<?,?>> list=Lists.newArrayListWithCapacity(map.size()); for ( Entry<? extends K,? extends V> entry : map.entrySet()) { list.add(entryOf(entry.getKey(),entry.getValue())); } Entry<?,?>[] entryArray=list.toArray(new Entry<?,?>[list.size()]); if (!sameComparator) { sortEntries(entryArray,comparator); validateEntries(entryArray,comparator); } return new ImmutableSortedMap<K,V>(entryArray,comparator); }
Example 6
From project android_external_libphonenumber, under directory /java/src/com/android/i18n/phonenumbers/geocoding/.
Source file: AreaCodeMap.java

/** * Gets the size of the provided area code map storage. The map storage passed-in will be filled as a result. */ private static int getSizeOfAreaCodeMapStorage(AreaCodeMapStorageStrategy mapStorage,SortedMap<Integer,String> areaCodeMap) throws IOException { mapStorage.readFromSortedMap(areaCodeMap); ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream=new ObjectOutputStream(byteArrayOutputStream); mapStorage.writeExternal(objectOutputStream); objectOutputStream.flush(); int sizeOfStorage=byteArrayOutputStream.size(); objectOutputStream.close(); return sizeOfStorage; }
Example 7
From project android_packages_apps_Gallery2, under directory /src/com/android/gallery3d/data/.
Source file: LocalMergeAlbum.java

@Override public ArrayList<MediaItem> getMediaItem(int start,int count){ SortedMap<Integer,int[]> head=mIndex.headMap(start + 1); int markPos=head.lastKey(); int[] subPos=head.get(markPos).clone(); MediaItem[] slot=new MediaItem[mSources.length]; int size=mSources.length; for (int i=0; i < size; i++) { slot[i]=mFetcher[i].getItem(subPos[i]); } ArrayList<MediaItem> result=new ArrayList<MediaItem>(); for (int i=markPos; i < start + count; i++) { int k=-1; for (int j=0; j < size; j++) { if (slot[j] != null) { if (k == -1 || mComparator.compare(slot[j],slot[k]) < 0) { k=j; } } } if (k == -1) break; subPos[k]++; if (i >= start) { result.add(slot[k]); } slot[k]=mFetcher[k].getItem(subPos[k]); if ((i + 1) % PAGE_SIZE == 0) { mIndex.put(i + 1,subPos.clone()); } } return result; }
Example 8
From project anidroid, under directory /anidroid/src/com/github/anidroid/.
Source file: FrameAnimator.java

/** * Create and return animation drawable * @param assetsFramesPath Path to folder with animation framesrelative to "assets" folder of android application * @param defaultDuration How long in milliseconds a single frameshould appear * @param oneShot Play once (true) or repeat (false) * @return AnimationDrawable instance */ public AnimationDrawable create(final String assetsFramesPath,final int defaultDuration,final boolean oneShot){ final List<String> files=assetUtil.getFileList(assetsFramesPath); final SortedMap<Integer,String> frames=frameUtil.extractFrames(files); final AnimationDrawable animationDrawable=new AnimationDrawable(); animationDrawable.setOneShot(oneShot); for ( final Integer key : frames.keySet()) { final Bitmap frame=BitmapFactory.decodeStream(assetUtil.open(frames.get(key))); animationDrawable.addFrame(new BitmapDrawable(frame),defaultDuration); } return animationDrawable; }
Example 9
From project ANNIS, under directory /annis-interfaces/src/main/java/annis/model/.
Source file: DataObject.java

@Override public int hashCode(){ final SortedMap<String,Object> fieldValues=new TreeMap<String,Object>(); final Object _this=this; forEachFieldDo(new FieldCallBack(){ public void doForField( Field field) throws IllegalAccessException { fieldValues.put(field.getName(),field.get(_this)); } } ); HashCodeBuilder hashCodeBuilder=new HashCodeBuilder(); for ( Object fieldValue : fieldValues.values()) hashCodeBuilder.append(fieldValue); return hashCodeBuilder.toHashCode(); }
Example 10
From project apb, under directory /modules/test-tasks/src/apb/tests/utils/.
Source file: NameTest.java

public void testIdFromClass(){ String str=NameUtils.idFromClass(String.class); assertEquals("java.lang.string",str); SortedMap<String,String> m=new TreeMap<String,String>(); m.put("a","b"); str=NameUtils.idFromClass(m.entrySet().toArray()[0].getClass()); assertEquals("java.util.tree-map.entry",str); str=NameUtils.idFromClass(StringBuilder.class); assertEquals("java.lang.string-builder",str); str=NameUtils.idFromClass(AClassWith$And_Inside.class); assertEquals("apb.tests.utils.name-test.aclass-with-and-inside",str); }
Example 11
From project ardverk-commons, under directory /src/main/java/org/ardverk/version/.
Source file: VectorClock.java

@SafeVarargs public static <K>VectorClock<K> create(Comparator<? super K> c,K... keys){ long creationTime=System.currentTimeMillis(); SortedMap<K,Vector> dst=new TreeMap<K,Vector>(c); for ( K key : keys) { Vector vector=dst.get(key); if (vector == null) { vector=Vector.INIT; } dst.put(key,vector.increment()); } return create(creationTime,dst); }
Example 12
From project ardverk-dht, under directory /components/core/src/main/java/org/ardverk/dht/codec/bencode/.
Source file: MessageInputStream.java

public VectorClock<KUID> readVectorClock() throws IOException { int count=readUnsignedShort(); if (count == 0) { return null; } long creationTime=readLong(); SortedMap<KUID,Vector> dst=new TreeMap<KUID,Vector>(); while (0 < count--) { KUID contactId=readKUID(); Vector vector=readVector(); if (!vector.isEmpty()) { dst.put(contactId,vector); } } return VectorClock.create(creationTime,dst); }
Example 13
From project Arecibo, under directory /agent/src/main/java/com/ning/arecibo/agent/datasource/snmp/.
Source file: SNMPClient.java

public SortedMap<Integer,Object> getTableColumnValues(String tableColumnOidString){ TreeMap<Integer,Object> resMap=new TreeMap<Integer,Object>(); SnmpOID tableColumnOID=this.snmpTarget.getMibOperations().getSnmpOID(tableColumnOidString); this.snmpTarget.setMaxRepetitions(100); this.snmpTarget.setObjectIDList(new String[]{tableColumnOidString}); boolean done=false; do { SnmpVarBind[][] resultArray=this.snmpTarget.snmpGetBulkVariableBindings(); if (resultArray == null || resultArray.length == 0) break; for ( SnmpVarBind[] results : resultArray) { for ( SnmpVarBind result : results) { SnmpOID oid=result.getObjectID(); if (oid == null || tableColumnOID == null || !SnmpTarget.isInSubTree(tableColumnOID,oid)) { done=true; break; } int[] oidNumbers=oid.toIntArray(); Integer rowNum=oidNumbers[oidNumbers.length - 1]; SnmpVar var=result.getVariable(); Object resultObj=convertToStandardJavaObject(var); resMap.put(rowNum,resultObj); } if (done) break; } } while (!done); return resMap; }
Example 14
From project astyanax, under directory /src/main/java/com/netflix/astyanax/impl/.
Source file: AstyanaxCheckpointManager.java

@Override public SortedMap<String,String> getCheckpoints() throws ConnectionException { SortedMap<String,String> checkpoints=Maps.newTreeMap(tokenComparator); for ( Column<String> column : keyspace.prepareQuery(columnFamily).getKey(bbKey).execute().getResult()) { checkpoints.put(column.getName(),column.getStringValue()); } return checkpoints; }
Example 15
public static <K,K2,V2>SortedMap<K2,V2> ensureSortedMap(Map<K,SortedMap<K2,V2>> parent,K key){ return ensureAny(parent,key,new Morph<Void,SortedMap<K2,V2>>(){ public SortedMap<K2,V2> doIt( Void input){ return new TreeMap<K2,V2>(); } } ); }
Example 16
From project big-data-plugin, under directory /shims/common/src/org/pentaho/hbase/shim/fake/.
Source file: FakeHBaseConnection.java

public SortedMap<byte[],NavigableMap<byte[],NavigableMap<byte[],NavigableMap<Long,byte[]>>>> getRows(byte[] startKey,byte[] stopKey){ SortedMap<byte[],NavigableMap<byte[],NavigableMap<byte[],NavigableMap<Long,byte[]>>>> subMap=null; if (startKey == null && stopKey == null) { return m_table; } if (stopKey == null) { Map.Entry<byte[],NavigableMap<byte[],NavigableMap<byte[],NavigableMap<Long,byte[]>>>> lastE=m_table.lastEntry(); byte[] upperKey=lastE.getKey(); subMap=m_table.subMap(startKey,true,upperKey,true); } else { BytesComparator comp=new BytesComparator(); if (comp.compare(startKey,stopKey) == 0) { subMap=m_table.subMap(startKey,true,stopKey,true); } else { subMap=m_table.subMap(startKey,stopKey); } } return subMap; }
Example 17
From project bioclipse.seneca, under directory /plugins/net.bioclipse.seneca/src/net/bioclipse/seneca/ga/.
Source file: MoleculeCandidateFactory.java

/** * Sorts atoms like Cs-other heavy atoms om alphabetical order-Hs. * @param mol The molecule to rearrange. * @return The new molecule as mdl file. * @exception Exception Problems writing mdl. */ public static IMolecule rearangeAtoms(IMolecule mol){ Iterator<IAtom> atomsold=mol.atoms().iterator(); IAtom[] atomsnew=new IAtom[mol.getAtomCount()]; int k=0; while (atomsold.hasNext()) { IAtom atom=atomsold.next(); if (atom.getSymbol().equals("C")) { atomsnew[k++]=atom; } } SortedMap<String,List<IAtom>> map=new TreeMap<String,List<IAtom>>(); atomsold=mol.atoms().iterator(); while (atomsold.hasNext()) { IAtom atom=(IAtom)atomsold.next(); if (!atom.getSymbol().equals("C") && !atom.getSymbol().equals("H")) { if (map.get(atom.getSymbol()) == null) map.put(atom.getSymbol(),new ArrayList<IAtom>()); map.get(atom.getSymbol()).add(atom); } } Iterator<String> symbolit=map.keySet().iterator(); while (symbolit.hasNext()) { List<IAtom> atoms=map.get(symbolit.next()); for (int i=0; i < atoms.size(); i++) { atomsnew[k++]=atoms.get(i); } } atomsold=mol.atoms().iterator(); while (atomsold.hasNext()) { IAtom atom=atomsold.next(); if (atom.getSymbol().equals("H")) { atomsnew[k++]=atom; } } mol.setAtoms(atomsnew); return (mol); }
Example 18
From project blueprint-namespaces, under directory /blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/di/.
Source file: MapRecipe.java

public static Class getMap(Class type){ if (ReflectionUtils.hasDefaultConstructor(type)) { return type; } else if (SortedMap.class.isAssignableFrom(type)) { return TreeMap.class; } else if (ConcurrentMap.class.isAssignableFrom(type)) { return ConcurrentHashMap.class; } else { return LinkedHashMap.class; } }
Example 19
From project bndtools, under directory /bndtools.jareditor/src/bndtools/jareditor/internal/.
Source file: JAREntryPart.java

public JAREntryPart(IEditorPart editor,Composite composite,FormToolkit toolkit){ this.editor=editor; SortedMap<String,Charset> charsetMap=Charset.availableCharsets(); charsets=new String[charsetMap.size()]; int i=0; for (Iterator<String> iter=charsetMap.keySet().iterator(); iter.hasNext(); i++) { charsets[i]=iter.next(); } setSelectedCharset(DEFAULT_CHARSET); createContent(composite,toolkit); }
Example 20
From project CIShell, under directory /core/org.cishell.utilities/src/org/cishell/utilities/database/.
Source file: ForeignKey.java

private Map<String,Object> translateToForeignNames(Map<String,Object> from){ SortedMap<String,Object> to=Maps.newTreeMap(); for ( ColumnPair pair : pairs) { to.put(pair.foreign,from.get(pair.local)); } return to; }
Example 21
From project closure-templates, under directory /java/src/com/google/template/soy/msgs/restricted/.
Source file: SoyMsgBundleImpl.java

/** * Note: If there exist duplicate message ids in the {@code msgs} list, the first one wins.However, the source paths from subsequent duplicates will be added to the source paths for the message. * @param localeString The language/locale string of this bundle of messages, or null if unknown.Should only be null for bundles newly extracted from source files. Should always be set for bundles parsed from message files/resources. * @param msgs The list of messages. List order will become the iteration order. */ public SoyMsgBundleImpl(@Nullable String localeString,List<SoyMsg> msgs){ this.localeString=localeString; SortedMap<Long,SoyMsg> tempMsgMap=Maps.newTreeMap(); for ( SoyMsg msg : msgs) { checkArgument(Objects.equal(msg.getLocaleString(),localeString)); long msgId=msg.getId(); if (!tempMsgMap.containsKey(msgId)) { tempMsgMap.put(msgId,msg); } else { SoyMsg existingMsg=tempMsgMap.get(msgId); for ( String source : msg.getSourcePaths()) { existingMsg.addSourcePath(source); } } } msgMap=ImmutableMap.copyOf(tempMsgMap); }
Example 22
From project Cloud9, under directory /src/dist/edu/umd/cloud9/io/.
Source file: SequenceFileUtils.java

public static <K extends Writable,V extends Writable>SortedMap<K,V> readFileIntoMap(Path path){ FileSystem fs; try { fs=FileSystem.get(new Configuration()); } catch ( IOException e) { throw new RuntimeException("Unable to access the file system!"); } return readFileIntoMap(path,fs,Integer.MAX_VALUE); }
Example 23
From project cloudhopper-smpp, under directory /src/main/java/com/cloudhopper/smpp/util/.
Source file: ConcurrentCommandStatusCounter.java

public SortedMap<Integer,Integer> createSortedMapSnapshot(){ SortedMap<Integer,Integer> sortedMap=new TreeMap<Integer,Integer>(); for ( Map.Entry<Integer,AtomicInteger> entry : this.map.entrySet()) { sortedMap.put(entry.getKey(),new Integer(entry.getValue().get())); } return sortedMap; }
Example 24
From project cloudify, under directory /tools/src/main/java/org/cloudifysource/restDoclet/generation/.
Source file: Generator.java

private static SortedMap<String,DocMethod> generateMethods(MethodDoc[] methods){ SortedMap<String,DocMethod> docMethods=new TreeMap<String,DocMethod>(); for ( MethodDoc methodDoc : methods) { List<DocAnnotation> annotations=generateAnnotations(methodDoc.annotations()); DocRequestMappingAnnotation requestMappingAnnotation=Utils.getRequestMappingAnnotation(annotations); if (requestMappingAnnotation == null) continue; DocHttpMethod httpMethod=generateHttpMethod(methodDoc,requestMappingAnnotation.getMethod(),annotations); String uri=requestMappingAnnotation.getValue(); if (StringUtils.isBlank(uri)) throw new IllegalArgumentException("method " + methodDoc.name() + " is missing request mapping annotation's value (uri)."); DocMethod docMethod=docMethods.get(uri); if (docMethod != null) docMethod.addHttpMethod(httpMethod); else { docMethod=new DocMethod(httpMethod); docMethod.setUri(uri); } docMethods.put(docMethod.getUri(),docMethod); } return docMethods; }
Example 25
From project clustermeister, under directory /provisioning/src/main/java/com/github/nethad/clustermeister/provisioning/ec2/.
Source file: AmazonConfigurationLoader.java

public Map<String,AWSInstanceProfile> getConfiguredProfiles(){ List<Object> profilesList=configuration.getList(PROFILES,Collections.EMPTY_LIST); Map<String,Map<String,String>> profileSpecifications=ConfigurationUtil.reduceObjectList(profilesList,"Profiles must be specified as a list of objects."); SortedMap<String,AWSInstanceProfile> profiles=Maps.newTreeMap(); for ( Map.Entry<String,Map<String,String>> entry : profileSpecifications.entrySet()) { String profileName=entry.getKey(); Map<String,String> profileValues=entry.getValue(); AWSInstanceProfile profile=AWSInstanceProfile.newBuilder().profileName(profileName).region(profileValues.get(REGION)).zone(profileValues.get(ZONE)).type(profileValues.get(TYPE)).amiId(profileValues.get(AMI_ID)).keypairName(profileValues.get(KEYPAIR)).shutdownState(profileValues.get(SHUTDOWN_STATE)).group(profileValues.get(GROUP)).spotPrice(profileValues.get(SPOT_PRICE)).spotRequestType(profileValues.get(SPOT_REQUEST_TYPE)).spotRequestValidFrom(profileValues.get(SPOT_REQUEST_VALID_FROM)).spotRequestValidTo(profileValues.get(SPOT_REQUEST_VALID_TO)).placementGroup(profileValues.get(PLACEMENT_GROUP)).build(); profiles.put(profileName,profile); } return profiles; }
Example 26
From project codjo-broadcast, under directory /codjo-broadcast-gui/src/main/java/net/codjo/broadcast/gui/.
Source file: BroadcastSectionsDetailWindow.java

private String[] getFamiliesSortedByLabel(){ String[] familyIds=guiPrefManager.getFamilies(); SortedMap<String,String> familyMap=new TreeMap<String,String>(); for ( String id : familyIds) { GuiPreference guiPreference=guiPrefManager.getPreferenceFor(id); String label=guiPreference.getFamilyLabel(); familyMap.put(label,id); } String[] sortedFamilyIds=new String[familyIds.length]; int index=0; for ( Map.Entry<String,String> entry : familyMap.entrySet()) { sortedFamilyIds[index++]=entry.getValue(); } return sortedFamilyIds; }
Example 27
From project cogroo4, under directory /cogroo-eval/GramEval/src/main/java/cogroo/uima/eval/.
Source file: Stats.java

public Map<String,Data> getData(){ SortedMap<String,Data> res=new TreeMap<String,Stats.Data>(new Comp()); res.put("TOTAL",new Data("TOTAL",mGeneralFMeasure,target,tp,fp)); SortedSet<String> set=new TreeSet<String>(new Comp()); set.addAll(targetForOutcome.keySet()); set.addAll(fpForOutcome.keySet()); for ( String type : set) { res.put(type,new Data(type,mFMeasureForOutcome.get(type),zeroOrValue(targetForOutcome.get(type)),zeroOrValue(tpForOutcome.get(type)),zeroOrValue(fpForOutcome.get(type)))); } return res; }
Example 28
From project com.idega.content, under directory /src/java/com/idega/content/themes/business/.
Source file: TemplatesLoader.java

@SuppressWarnings("unchecked") public void addSiteTemplatesFromDocument(Document siteTemplateDocument){ SortedMap<String,SiteTemplate> siteMap=null; Map<String,SortedMap<String,SiteTemplate>> siteTemplatesFromCache=IWCacheManager2.getInstance(iwma).getCache(SITE_TEMPLATES_CACHE_KEY); if (siteTemplatesFromCache.containsKey(ContentConstants.SITE_MAP_KEY)) { siteMap=siteTemplatesFromCache.get(ContentConstants.SITE_MAP_KEY); } else { siteMap=Collections.synchronizedSortedMap(new TreeMap<String,SiteTemplate>()); } Element root=siteTemplateDocument.getRootElement(); Collection<Element> siteRoot=root.getChildren(); if (siteRoot == null) { return; } Element siteTemplate=null; for (Iterator<Element> it=siteRoot.iterator(); it.hasNext(); ) { SiteTemplate siteStruct=new SiteTemplate(); siteTemplate=it.next(); String panelName=siteTemplate.getAttributeValue("name"); Element structure=(Element)siteTemplate.getChildren().get(0); siteStruct=getNode(structure); siteMap.put(panelName,siteStruct); } siteTemplatesFromCache.put(ContentConstants.SITE_MAP_KEY,siteMap); }
Example 29
From project CommunityCase, under directory /src/org/community/intellij/plugins/communitycase/update/.
Source file: SkippedCommits.java

/** * The constructor * @param contentManager content manager * @param project the context project * @param skippedCommits the map with skipped commits */ public SkippedCommits(@NotNull ContentManager contentManager,Project project,SortedMap<VirtualFile,List<RebaseUtils.CommitInfo>> skippedCommits){ super(contentManager,null); myProject=project; DefaultMutableTreeNode treeRoot=new DefaultMutableTreeNode("ROOT",true); for ( Map.Entry<VirtualFile,List<RebaseUtils.CommitInfo>> e : skippedCommits.entrySet()) { DefaultMutableTreeNode vcsRoot=new DefaultMutableTreeNode(new VcsRoot(e.getKey())); int missed=0; for ( RebaseUtils.CommitInfo c : e.getValue()) { if (c != null) { vcsRoot.add(new DefaultMutableTreeNode(new Commit(e.getKey(),c))); } else { missed++; } } treeRoot.add(vcsRoot); if (missed > 0) { vcsRoot.add(new DefaultMutableTreeNode("The " + missed + " commit(s) were not parsed due to unsupported rebase directory format")); } } myTree=new Tree(treeRoot); myTree.setCellRenderer(createTreeCellRenderer()); myTree.setRootVisible(false); myCenterComponent=new JBScrollPane(myTree); init(); TreeUtil.expandAll(myTree); }
Example 30
From project crawler4j, under directory /src/main/java/edu/uci/ics/crawler4j/url/.
Source file: URLCanonicalizer.java

/** * Takes a query string, separates the constituent name-value pairs, and stores them in a SortedMap ordered by lexicographical order. * @return Null if there is no query string. */ private static SortedMap<String,String> createParameterMap(final String queryString){ if (queryString == null || queryString.isEmpty()) { return null; } final String[] pairs=queryString.split("&"); final Map<String,String> params=new HashMap<String,String>(pairs.length); for ( final String pair : pairs) { if (pair.length() == 0) { continue; } String[] tokens=pair.split("=",2); switch (tokens.length) { case 1: if (pair.charAt(0) == '=') { params.put("",tokens[0]); } else { params.put(tokens[0],""); } break; case 2: params.put(tokens[0],tokens[1]); break; } } return new TreeMap<String,String>(params); }
Example 31
From project culvert, under directory /culvert-main/src/test/java/com/bah/culvert/inmemory/.
Source file: InMemoryTable.java

@Override public SeekingCurrentIterator get(Get get){ if (this.table.size() == 0) return new DecoratingCurrentIterator(new ArrayList<Result>(0).iterator()); CRange range=get.getRange(); Bytes start=range.getStart().length == 0 ? this.table.firstKey() : new Bytes(range.getStart()); Bytes end=range.getEnd().length == 0 ? this.table.lastKey() : new Bytes(range.getEnd()); List<Result> results=new ArrayList<Result>(); SortedMap<Bytes,InMemoryFamily> submap; if (LexicographicBytesComparator.INSTANCE.compare(start.getBytes(),end.getBytes()) == 0) { InMemoryFamily family=this.table.get(start); if (family == null) return new DecoratingCurrentIterator(((List<Result>)Collections.EMPTY_LIST).iterator()); submap=new TreeMap<Bytes,InMemoryFamily>(); submap.put(start,family); } else { submap=new TreeMap<Bytes,InMemoryFamily>(this.table.subMap(start,end)); if (!range.isStartInclusive()) submap.remove(start); if (range.isEndInclusive()) { InMemoryFamily endFamily=this.table.get(end); if (endFamily != null) { submap.put(end,endFamily); } } } return new DecoratingCurrentIterator(filteredLookup(submap,get).iterator()); }
Example 32
From project dawn-isenciaui, under directory /com.teaminabox.eclipse.wiki/src/com/teaminabox/eclipse/wiki/editors/completion/.
Source file: PluginCompletionProcessor.java

private String[] collectPlugIDs(String path){ if (path == null) { path=""; } Set<String> plugIds=gatherPluginIds(path); SortedMap<String,String> selectedIDs=new TreeMap<String,String>(); for ( String currPluginID : plugIds) { addWikiFromPlugin(path,currPluginID,selectedIDs); } return selectedIDs.values().toArray(new String[selectedIDs.size()]); }
Example 33
From project db2triples, under directory /src/main/java/net/antidot/sql/model/db/.
Source file: Row.java

public Row(SortedMap<String,byte[]> values,StdBody parentBody,int index) throws UnsupportedEncodingException { this.values=new TreeMap<String,byte[]>(); if (values != null) for ( String key : values.keySet()) { byte[] bytesResult=values.get(key); this.values.put(key,bytesResult); } this.parentBody=parentBody; this.index=index; }
Example 34
From project DeliciousDroid, under directory /src/com/deliciousdroid/providers/.
Source file: BookmarkContentProvider.java

private Cursor getSearchSuggestions(String query){ Log.d("getSearchSuggestions",query); mAccountManager=AccountManager.get(getContext()); mAccount=mAccountManager.getAccountsByType(Constants.ACCOUNT_TYPE)[0]; Map<String,SearchSuggestionContent> tagSuggestions=new TreeMap<String,SearchSuggestionContent>(); Map<String,SearchSuggestionContent> bookmarkSuggestions=new TreeMap<String,SearchSuggestionContent>(); tagSuggestions=getTagSearchSuggestions(query); bookmarkSuggestions=getBookmarkSearchSuggestions(query); SortedMap<String,SearchSuggestionContent> s=new TreeMap<String,SearchSuggestionContent>(); s.putAll(tagSuggestions); s.putAll(bookmarkSuggestions); return getSearchCursor(s); }
Example 35
From project dmix, under directory /LastFM-java/src/de/umass/lastfm/cache/.
Source file: Cache.java

/** * Creates a unique entry name string for a request. It consists of the method name and all the parameter names and values concatenated in alphabetical order. It is used to identify cache entries in the backend storage. If <code>hashCacheEntryNames</code> is set to <code>true</code> this method will return a MD5 hash of the generated name. * @param method The request method * @param params The request parameters * @return a cache entry name */ public static String createCacheEntryName(String method,Map<String,String> params){ if (!(params instanceof SortedMap)) { params=new TreeMap<String,String>(params); } StringBuilder b=new StringBuilder(100); b.append(method.toLowerCase()); b.append('.'); for ( Map.Entry<String,String> e : params.entrySet()) { b.append(e.getKey()); b.append(e.getValue()); } String name=b.toString(); if (hashCacheEntryNames) return StringUtilities.md5(name); return StringUtilities.cleanUp(name); }
Example 36
From project drools-planner, under directory /drools-planner-benchmark/src/main/java/org/drools/planner/benchmark/core/.
Source file: DefaultPlannerBenchmark.java

private List<List<SolverBenchmark>> createSameRankingListList(List<SolverBenchmark> rankableSolverBenchmarkList){ List<List<SolverBenchmark>> sameRankingListList=new ArrayList<List<SolverBenchmark>>(rankableSolverBenchmarkList.size()); if (solverBenchmarkRankingComparator != null) { Comparator<SolverBenchmark> comparator=Collections.reverseOrder(solverBenchmarkRankingComparator); Collections.sort(rankableSolverBenchmarkList,comparator); List<SolverBenchmark> sameRankingList=null; SolverBenchmark previousSolverBenchmark=null; for ( SolverBenchmark solverBenchmark : rankableSolverBenchmarkList) { if (previousSolverBenchmark == null || comparator.compare(previousSolverBenchmark,solverBenchmark) != 0) { sameRankingList=new ArrayList<SolverBenchmark>(); sameRankingListList.add(sameRankingList); } sameRankingList.add(solverBenchmark); previousSolverBenchmark=solverBenchmark; } } else if (solverBenchmarkRankingWeightFactory != null) { SortedMap<Comparable,List<SolverBenchmark>> rankedMap=new TreeMap<Comparable,List<SolverBenchmark>>(new ReverseComparator()); for ( SolverBenchmark solverBenchmark : rankableSolverBenchmarkList) { Comparable rankingWeight=solverBenchmarkRankingWeightFactory.createRankingWeight(rankableSolverBenchmarkList,solverBenchmark); List<SolverBenchmark> sameRankingList=rankedMap.get(rankingWeight); if (sameRankingList == null) { sameRankingList=new ArrayList<SolverBenchmark>(); rankedMap.put(rankingWeight,sameRankingList); } sameRankingList.add(solverBenchmark); } for ( Map.Entry<Comparable,List<SolverBenchmark>> entry : rankedMap.entrySet()) { sameRankingListList.add(entry.getValue()); } } else { throw new IllegalStateException("Ranking is impossible" + " because solverBenchmarkRankingComparator and solverBenchmarkRankingWeightFactory are null."); } return sameRankingListList; }
Example 37
From project Dual-Battery-Widget, under directory /lib/AChartEngine/src/org/achartengine/model/.
Source file: XYSeries.java

/** * Returns submap of x and y values according to the given start and end * @param start start x value * @param stop stop x value * @return a submap of x and y values */ public synchronized SortedMap<Double,Double> getRange(double start,double stop,int beforeAfterPoints){ SortedMap<Double,Double> headMap=mXY.headMap(start); if (!headMap.isEmpty()) { start=headMap.lastKey(); } SortedMap<Double,Double> tailMap=mXY.tailMap(stop); if (!tailMap.isEmpty()) { Iterator<Double> tailIterator=tailMap.keySet().iterator(); Double next=tailIterator.next(); if (tailIterator.hasNext()) { stop=tailIterator.next(); } else { stop+=next; } } return mXY.subMap(start,stop); }
Example 38
From project Eclipse, under directory /com.mobilesorcery.sdk.core/src/com/mobilesorcery/sdk/core/.
Source file: BuildVariant.java

/** * <p>Returns an <code>IBuildVariant</code> object from a given string of this format: <code>profile, cfgid, finalize|normal</code></p> * @param string * @return <code>null</code> if there was no profile with the given id, or if<code>variantStr</code> was null, or if the given string was otherwise malformed */ public static IBuildVariant parse(String variantStr){ if (variantStr == null) { return null; } String[] variantComponents=PropertyUtil.toStrings(variantStr); int profileManagerType=MoSyncTool.DEFAULT_PROFILE_TYPE; if (variantStr.startsWith("*")) { variantStr=variantStr.substring(1); profileManagerType=MoSyncTool.LEGACY_PROFILE_TYPE; } if (variantComponents.length == 2 || variantComponents.length == 3) { String profileStr=variantComponents[0]; IProfile profile=MoSyncTool.getDefault().getProfileManager(profileManagerType).getProfile(profileStr); String cfgId=variantComponents[1]; if (NULL_CFG.equals(cfgId)) { cfgId=null; } SortedMap<String,String> specifiers=parseSpecifiers(variantComponents.length > 2 ? variantComponents[2] : null); if (profile != null) { return new BuildVariant(profile,cfgId,specifiers); } } return null; }
Example 39
From project eclipse-integration-cloudfoundry, under directory /org.cloudfoundry.ide.eclipse.server.core/src/org/cloudfoundry/ide/eclipse/internal/uaa/.
Source file: UaaAwareCloudFoundryClient.java

private void flushToUaa(){ for ( String appName : discoveredAppNames) { uaaService.registerProductUsage(PRODUCT,appName); } String ccType="Cloud Controller: Custom"; if (VCLOUD_URL.equals(cloudControllerUrl.toExternalForm())) { ccType="Cloud Controller: Public Cloud"; } else if (VCLOUD_SECURE_URL.equals(cloudControllerUrl.toExternalForm())) { ccType="Cloud Controller: Public Cloud"; } else if (cloudControllerUrl.getHost().equals("localhost")) { ccType="Cloud Controller: Localhost"; } else if (cloudControllerUrl.getHost().equals("127.0.0.1")) { ccType="Cloud Controller: Localhost"; } String ccUrlHashed=sha256(cloudControllerUrl.getHost()); Map<String,Object> ccJson=new HashMap<String,Object>(); ccJson.put("type","cc_info"); ccJson.put("cc_hostname_sha256",JSONObject.escape(ccUrlHashed)); registerFeatureUse(ccType,ccJson); for ( String methodName : methodToResponses.keySet()) { SortedMap<Integer,Integer> resultCounts=methodToResponses.get(methodName); Map<String,Object> methodCallInfo=new HashMap<String,Object>(); methodCallInfo.put("type","method_call_info"); methodCallInfo.put("cc_hostname_sha256",JSONObject.escape(ccUrlHashed)); methodCallInfo.put("http_results_to_counts",resultCounts); registerFeatureUse(methodName,methodCallInfo); } }
Example 40
public void setFileType(SortedMap<String,FileType> fileType){ this.fileType.clear(); if (fileType != null) { this.fileType.putAll(fileType); } }
Example 41
From project ExperienceMod, under directory /ExperienceMod/src/com/comphenix/xp/extra/.
Source file: IntervalTree.java

/** * Removes every interval that intersects with the given range. * @param lowerBound - lowest value to remove. * @param upperBound - highest value to remove. */ public void remove(TKey lowerBound,TKey upperBound){ SortedMap<TKey,EndPoint> range=bounds.subMap(lowerBound,true,upperBound,true); TKey first=range.firstKey(); TKey last=range.lastKey(); if (range.get(first).state == State.CLOSE) { removeIfNonNull(bounds.floorKey(first)); } if (range.get(last).state == State.OPEN) { removeIfNonNull(bounds.ceilingKey(last)); } range.clear(); }
Example 42
From project fastjson, under directory /src/test/java/com/alibaba/json/bvt/parser/deser/.
Source file: DefaultObjectDeserializerTest2.java

public void test_1() throws Exception { String input="{'map':{}}"; DefaultExtJSONParser parser=new DefaultExtJSONParser(input,ParserConfig.getGlobalInstance(),JSON.DEFAULT_PARSER_FEATURE); SortedMap<String,SortedMap> map=JSON.parseObject(input,new TypeReference<SortedMap<String,SortedMap>>(){ } .getType()); Assert.assertEquals(TreeMap.class,map.get("map").getClass()); }
Example 43
From project Flume-Hive, under directory /src/java/com/cloudera/flume/core/.
Source file: EventImpl.java

public String toString(){ String mbody=StringEscapeUtils.escapeJava(new String(getBody())); StringBuilder attrs=new StringBuilder(); SortedMap<String,byte[]> sorted=new TreeMap<String,byte[]>(this.fields); for ( Entry<String,byte[]> e : sorted.entrySet()) { attrs.append("{ " + e.getKey() + " : "); String o=Attributes.toString(this,e.getKey()); attrs.append(o + " } "); } return getHost() + " [" + getPriority().toString()+ " "+ new Date(getTimestamp())+ "] "+ attrs.toString()+ mbody; }
Example 44
From project flume_1, under directory /flume-core/src/main/java/com/cloudera/flume/core/.
Source file: EventImpl.java

public String toString(){ String mbody=StringEscapeUtils.escapeJava(new String(getBody())); StringBuilder attrs=new StringBuilder(); SortedMap<String,byte[]> sorted=new TreeMap<String,byte[]>(this.fields); for ( Entry<String,byte[]> e : sorted.entrySet()) { attrs.append("{ " + e.getKey() + " : "); String o=Attributes.toString(this,e.getKey()); attrs.append(o + " } "); } return getHost() + " [" + getPriority().toString()+ " "+ new Date(getTimestamp())+ "] "+ attrs.toString()+ mbody; }
Example 45
From project frameworks_opt, under directory /vcard/tests/src/com/android/vcard/tests/testutils/.
Source file: ImportTestProvider.java

/** * Utility method to print ContentValues whose content is printed with sorted keys. */ private String convertToEasilyReadableString(ContentValues contentValues){ if (contentValues == null) { return "null"; } String mimeTypeValue=""; SortedMap<String,String> sortedMap=new TreeMap<String,String>(); for ( Entry<String,Object> entry : contentValues.valueSet()) { final String key=entry.getKey(); final Object value=entry.getValue(); final String valueString=(value != null ? value.toString() : null); if (Data.MIMETYPE.equals(key)) { mimeTypeValue=valueString; } else { TestCase.assertNotNull(key); sortedMap.put(key,valueString); } } StringBuilder builder=new StringBuilder(); builder.append(Data.MIMETYPE); builder.append('='); builder.append(mimeTypeValue); for ( Entry<String,String> entry : sortedMap.entrySet()) { final String key=entry.getKey(); final String value=entry.getValue(); builder.append(' '); builder.append(key); builder.append("=\""); builder.append(value); builder.append('"'); } return builder.toString(); }
Example 46
From project FunctionalTestsPortlet, under directory /src/main/java/org/jasig/portlet/test/mvc/.
Source file: TestDelegatingSelectorController.java

/** * @param testControllers the testControllers to set */ @Required public void setTestControllers(Map<String,Controller> testControllers){ Validate.notNull(testControllers); if (testControllers instanceof SortedMap) { this.testControllers=(SortedMap<String,Controller>)testControllers; } else { this.testControllers=new TreeMap<String,Controller>(testControllers); } }
Example 47
From project Gaggle, under directory /src/com/geeksville/location/parse/.
Source file: Parse.java

protected void Save(){ SortedMap<String,ExtendedWaypoint> names=db.getNameCache(); if (description != null) { if (type == Waypoint.Type.Unknown) { String descname=description.toLowerCase() + name.toLowerCase(); if (descname.contains("lz") || descname.contains("landing") || descname.contains("lp")) type=Waypoint.Type.Landing; else if (descname.contains("launch") || descname.contains("sp")) type=Waypoint.Type.Launch; } ExtendedWaypoint existingWaypoint; if (name.length() != 0 && (existingWaypoint=names.get(name)) != null) { existingWaypoint.latitude=latitude; existingWaypoint.longitude=longitude; existingWaypoint.altitude=(int)altitude; existingWaypoint.type=type; if (!description.equals(name) && description.length() != 0) existingWaypoint.description=description; existingWaypoint.commit(); } else { ExtendedWaypoint w=new ExtendedWaypoint(name,latitude,longitude,(int)altitude,type.ordinal()); if (!description.equals(name) && description.length() != 0) w.description=description; db.add(w); } } }
Example 48
From project galaxy, under directory /src/co/paralleluniverse/galaxy/core/.
Source file: ClusterMonitor.java

private List<SortedMap<String,String>> toMapList(Collection<NodeInfo> nis){ SortedSet<NodeInfo> nis1=new TreeSet<NodeInfo>(new Comparator<NodeInfo>(){ @Override public int compare( NodeInfo o1, NodeInfo o2){ return o1.getNodeId() - o2.getNodeId(); } } ); nis1.addAll(nis); List<SortedMap<String,String>> list=new ArrayList<SortedMap<String,String>>(nis.size()); for ( NodeInfo ni : nis1) list.add(toMap(ni)); return list; }
Example 49
From project Gemini-Blueprint, under directory /core/src/main/java/org/eclipse/gemini/blueprint/blueprint/container/support/.
Source file: BlueprintEditorRegistrar.java

public void registerCustomEditors(PropertyEditorRegistry registry){ registry.registerCustomEditor(Date.class,new DateEditor()); registry.registerCustomEditor(Stack.class,new BlueprintCustomCollectionEditor(Stack.class)); registry.registerCustomEditor(Vector.class,new BlueprintCustomCollectionEditor(Vector.class)); registry.registerCustomEditor(Collection.class,new BlueprintCustomCollectionEditor(Collection.class)); registry.registerCustomEditor(Set.class,new BlueprintCustomCollectionEditor(Set.class)); registry.registerCustomEditor(SortedSet.class,new BlueprintCustomCollectionEditor(SortedSet.class)); registry.registerCustomEditor(List.class,new BlueprintCustomCollectionEditor(List.class)); registry.registerCustomEditor(SortedMap.class,new CustomMapEditor(SortedMap.class)); registry.registerCustomEditor(HashSet.class,new BlueprintCustomCollectionEditor(HashSet.class)); registry.registerCustomEditor(LinkedHashSet.class,new BlueprintCustomCollectionEditor(LinkedHashSet.class)); registry.registerCustomEditor(TreeSet.class,new BlueprintCustomCollectionEditor(TreeSet.class)); registry.registerCustomEditor(ArrayList.class,new BlueprintCustomCollectionEditor(ArrayList.class)); registry.registerCustomEditor(LinkedList.class,new BlueprintCustomCollectionEditor(LinkedList.class)); registry.registerCustomEditor(HashMap.class,new CustomMapEditor(HashMap.class)); registry.registerCustomEditor(LinkedHashMap.class,new CustomMapEditor(LinkedHashMap.class)); registry.registerCustomEditor(Hashtable.class,new CustomMapEditor(Hashtable.class)); registry.registerCustomEditor(TreeMap.class,new CustomMapEditor(TreeMap.class)); registry.registerCustomEditor(Properties.class,new PropertiesEditor()); registry.registerCustomEditor(ConcurrentMap.class,new CustomMapEditor(ConcurrentHashMap.class)); registry.registerCustomEditor(ConcurrentHashMap.class,new CustomMapEditor(ConcurrentHashMap.class)); registry.registerCustomEditor(Queue.class,new BlueprintCustomCollectionEditor(LinkedList.class)); registry.registerCustomEditor(Dictionary.class,new CustomMapEditor(Hashtable.class)); }
Example 50
From project geronimo-xbean, under directory /xbean-reflect/src/main/java/org/apache/xbean/recipe/.
Source file: MapRecipe.java

public MapRecipe(Map<?,?> map){ if (map == null) throw new NullPointerException("map is null"); entries=new ArrayList<Object[]>(map.size()); if (RecipeHelper.hasDefaultConstructor(map.getClass())) { this.typeClass=map.getClass(); } else if (map instanceof SortedMap) { this.typeClass=TreeMap.class; } else if (map instanceof ConcurrentMap) { this.typeClass=ConcurrentHashMap.class; } else { this.typeClass=LinkedHashMap.class; } putAll(map); }
Example 51
From project giraph, under directory /src/main/java/org/apache/giraph/comm/messages/.
Source file: SequentialFileMessageStore.java

@Override public void addMessages(Map<I,Collection<M>> messages) throws IOException { SortedMap<I,Collection<M>> map; if (!(messages instanceof SortedMap)) { map=Maps.newTreeMap(); map.putAll(messages); } else { map=(SortedMap)messages; } writeToFile(map); }
Example 52
From project goldenorb, under directory /src/main/java/org/goldenorb/util/.
Source file: CommandLineUtils.java

/** * Provides a "help" command in the CLI. * @param args - String[] */ public static void help(String[] args){ initializeHelpMaps(); Set<String> commandsSet=helpMap.keySet(); if (args.length == 1) { for ( String command : commandsSet) { System.out.print(command + "\t" + helpMap.get(command)); if (!command.equalsIgnoreCase("Help")) { System.out.println(" Use 'Help -" + command + "' to view a list of valid arguments"); } } } else { String command=args[1].replaceFirst("-",""); if (commandsSet.contains(command)) { System.out.println("Help for command '" + command + "'."); System.out.println(command + "\t" + helpMap.get(command)); System.out.println("List of valid arguments for command '" + command + "' : "); SortedMap<String,String> argMap=validArguments.get(command); Set<String> arguments=argMap.keySet(); for ( String arg : arguments) { System.out.println(command + "\t" + argMap.get(arg)); } } else { System.out.println(args[0] + " is not a valid command."); } } }
Example 53
From project gradle-msbuild-plugin, under directory /src/main/groovy/org/gradle/api/reporting/internal/.
Source file: DefaultReportContainer.java

public T getFirstEnabled(){ SortedMap<String,T> map=enabled.getAsMap(); if (map.isEmpty()) { return null; } else { return map.get(map.firstKey()); } }
Example 54
From project ha-jdbc, under directory /src/main/java/net/sf/hajdbc/balancer/load/.
Source file: LoadBalancer.java

/** * Constructs a new LoadBalancer * @param databases */ public LoadBalancer(Set<D> databases){ if (databases.isEmpty()) { this.databaseMap=Collections.emptySortedMap(); } else if (databases.size() == 1) { this.databaseMap=Collections.singletonSortedMap(databases.iterator().next(),new AtomicInteger(1)); } else { SortedMap<D,AtomicInteger> map=new TreeMap<D,AtomicInteger>(); for ( D database : databases) { map.put(database,new AtomicInteger(1)); } this.databaseMap=map; } }
Example 55
From project hbase-transactional-tableindexed, under directory /src/main/java/org/apache/hadoop/hbase/client/tableindexed/.
Source file: IndexedTableAdmin.java

private void reIndexTable(final byte[] baseTableName,final IndexSpecification indexSpec) throws IOException { HTable baseTable=new HTable(baseTableName); HTable indexTable=new HTable(indexSpec.getIndexedTableName(baseTableName)); Scan scan=new Scan(); scan.addColumns(indexSpec.getAllColumns()); for ( Result rowResult : baseTable.getScanner(scan)) { SortedMap<byte[],byte[]> columnValues=new TreeMap<byte[],byte[]>(Bytes.BYTES_COMPARATOR); for ( Entry<byte[],NavigableMap<byte[],byte[]>> familyEntry : rowResult.getNoVersionMap().entrySet()) { for ( Entry<byte[],byte[]> cellEntry : familyEntry.getValue().entrySet()) { columnValues.put(Bytes.add(familyEntry.getKey(),Bytes.toBytes(":"),cellEntry.getKey()),cellEntry.getValue()); } } if (IndexMaintenanceUtils.doesApplyToIndex(indexSpec,columnValues)) { Put indexUpdate=IndexMaintenanceUtils.createIndexUpdate(indexSpec,rowResult.getRow(),columnValues); indexTable.put(indexUpdate); } } }
Example 56
From project heritrix3, under directory /commons/src/main/java/org/apache/commons/httpclient/cookie/.
Source file: CookieSpecBase.java

/** * Return an array of {@link Cookie}s that should be submitted with a request with given attributes, <tt>false</tt> otherwise. If the SortedMap comes from an HttpState and is not itself thread-safe, it may be necessary to synchronize on the HttpState instance to protect against concurrent modification. * @param host the host to which the request is being submitted * @param port the port to which the request is being submitted (currentlyignored) * @param path the path to which the request is being submitted * @param secure <tt>true</tt> if the request is using a secure protocol * @param cookies SortedMap of <tt>Cookie</tt>s to be matched * @return an array of <tt>Cookie</tt>s matching the criterium */ @Override public Cookie[] match(String host,int port,String path,boolean secure,final SortedMap<String,Cookie> cookies){ LOG.trace("enter CookieSpecBase.match(" + "String, int, String, boolean, SortedMap)"); if (cookies == null) { return null; } List<Cookie> matching=new LinkedList<Cookie>(); InternetDomainName domain; try { domain=InternetDomainName.fromLenient(host); } catch ( IllegalArgumentException e) { domain=null; } String candidate=(domain != null) ? domain.name() : host; while (candidate != null) { Iterator<Cookie> iter=cookies.subMap(candidate,candidate + Cookie.DOMAIN_OVERBOUNDS).values().iterator(); while (iter.hasNext()) { Cookie cookie=(Cookie)(iter.next()); if (match(host,port,path,secure,cookie)) { addInPathOrder(matching,cookie); } } StoredIterator.close(iter); if (domain != null && domain.isUnderPublicSuffix()) { domain=domain.parent(); candidate=domain.name(); } else { candidate=null; } } return (Cookie[])matching.toArray(new Cookie[matching.size()]); }
Example 57
From project hibernate-commons-annotations, under directory /src/main/java/org/hibernate/annotations/common/reflection/java/.
Source file: JavaXCollectionType.java

public XClass getElementClass(){ return new TypeSwitch<XClass>(){ @Override public XClass caseParameterizedType( ParameterizedType parameterizedType){ Type[] args=parameterizedType.getActualTypeArguments(); Type componentType; Class<? extends Collection> collectionClass=getCollectionClass(); if (Map.class.isAssignableFrom(collectionClass) || SortedMap.class.isAssignableFrom(collectionClass)) { componentType=args[1]; } else { componentType=args[0]; } return toXClass(componentType); } } .doSwitch(approximate()); }
Example 58
From project hibernate-validator, under directory /engine/src/test/java/org/hibernate/validator/test/internal/util/.
Source file: ReflectionHelperTest.java

@Test public void testIsMap() throws Exception { assertTrue(ReflectionHelper.isMap(Map.class)); assertTrue(ReflectionHelper.isMap(SortedMap.class)); Type type=TestTypes.class.getField("objectMap").getGenericType(); assertTrue(ReflectionHelper.isMap(type)); assertFalse(ReflectionHelper.isMap(null)); assertFalse(ReflectionHelper.isMap(Object.class)); }
Example 59
From project Hphoto, under directory /src/test/org/apache/hadoop/hbase/.
Source file: MultiRegionTable.java

private static void compact(final MiniHBaseCluster cluster,final HRegionInfo r) throws IOException { LOG.info("Starting compaction"); for ( MiniHBaseCluster.RegionServerThread thread : cluster.regionThreads) { SortedMap<Text,HRegion> regions=thread.getRegionServer().onlineRegions; for (int i=0; i < 10; i++) { try { for ( HRegion online : regions.values()) { if (online.getRegionName().toString().equals(r.getRegionName().toString())) { online.compactStores(); } } break; } catch ( ConcurrentModificationException e) { LOG.warn("Retrying because ..." + e.toString() + " -- one or "+ "two should be fine"); continue; } } } }
Example 60
From project huiswerk, under directory /print/zxing-1.6/javase/src/com/google/zxing/.
Source file: StringsResourceTranslator.java

private static SortedMap<String,String> readLines(File file) throws IOException { SortedMap<String,String> entries=new TreeMap<String,String>(); BufferedReader reader=null; try { reader=new BufferedReader(new InputStreamReader(new FileInputStream(file),UTF8)); String line; while ((line=reader.readLine()) != null) { Matcher m=ENTRY_PATTERN.matcher(line); if (m.find()) { String key=m.group(1); String value=m.group(2); entries.put(key,value); } } return entries; } finally { quietClose(reader); } }
Example 61
From project indextank-engine, under directory /cojen-2.2.1-sources/org/cojen/util/.
Source file: BeanPropertyMapFactory.java

/** * Returns a fixed-size map backed by the given bean. Map remove operations are unsupported, as is access to excluded properties. * @throws IllegalArgumentException if bean is null */ public static SortedMap<String,Object> asMap(Object bean){ if (bean == null) { throw new IllegalArgumentException(); } BeanPropertyMapFactory factory=forClass(bean.getClass()); return factory.createMap(bean); }
Example 62
From project Ivory_1, under directory /src/java/main/ivory/core/preprocess/.
Source file: BuildIntDocVectors.java

@Override public void map(IntWritable key,TermDocVector doc,Context context) throws IOException, InterruptedException { long startTime=System.currentTimeMillis(); SortedMap<Integer,int[]> positions=DocumentProcessingUtils.integerizeTermDocVector(doc,dictionary); context.getCounter(MapTime.DecodingAndIdMapping).increment(System.currentTimeMillis() - startTime); startTime=System.currentTimeMillis(); docVector.setTermPositionsMap(positions); context.write(key,docVector); context.getCounter(MapTime.EncodingAndSpilling).increment(System.currentTimeMillis() - startTime); context.getCounter(Docs.Total).increment(1); }
Example 63
From project james-mailbox, under directory /maildir/src/main/java/org/apache/james/mailbox/maildir/mail/.
Source file: MaildirMessageMapper.java

private List<Message<Integer>> findMessagesInMailboxBetweenUIDs(Mailbox<Integer> mailbox,FilenameFilter filter,long from,long to,int max) throws MailboxException { MaildirFolder folder=maildirStore.createMaildirFolder(mailbox); int cur=0; SortedMap<Long,MaildirMessageName> uidMap=null; try { if (filter != null) uidMap=folder.getUidMap(mailboxSession,filter,from,to); else uidMap=folder.getUidMap(mailboxSession,from,to); ArrayList<Message<Integer>> messages=new ArrayList<Message<Integer>>(); for ( Entry<Long,MaildirMessageName> entry : uidMap.entrySet()) { messages.add(new MaildirMessage(mailbox,entry.getKey(),entry.getValue())); if (max != -1) { cur++; if (cur >= max) break; } } return messages; } catch ( IOException e) { throw new MailboxException("Failure while search for Messages in Mailbox " + mailbox,e); } }
Example 64
From project java_binding_v1, under directory /src/com/tripit/auth/.
Source file: OAuthCredential.java

public boolean validateSignature(URI requestUri) throws URISyntaxException, UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException { List<NameValuePair> argList=URLEncodedUtils.parse(requestUri,"UTF-8"); SortedMap<String,String> args=new TreeMap<String,String>(); for ( NameValuePair arg : argList) { args.put(arg.getName(),arg.getValue()); } String signature=args.remove("oauth_signature"); String baseUrl=new URI(requestUri.getScheme(),requestUri.getUserInfo(),requestUri.getAuthority(),requestUri.getPort(),requestUri.getPath(),null,requestUri.getFragment()).toString(); return (signature != null && signature.equals(generateSignature(baseUrl,args))); }
Example 65
From project jboss-jsf-api_spec, under directory /src/main/java/javax/faces/model/.
Source file: ResultDataModel.java

/** * <p>If row data is available, return the <code>SortedMap</code> array element at the index specified by <code>rowIndex</code> of the array returned by calling <code>getRows()</code> on the underlying <code>Result</code>. If no wrapped data is available, return <code>null</code>.</p> <p>Note that, if a non-<code>null</code> <code>Map</code> is returned by this method, it will contain the values of the columns for the current row, keyed by column name. Column name comparisons must be performed in a case-insensitive manner.</p> * @throws FacesException if an error occurs getting the row data * @throws IllegalArgumentException if now row data is availableat the currently specified row index */ public SortedMap<String,Object> getRowData(){ if (result == null) { return (null); } else if (!isRowAvailable()) { throw new NoRowAvailableException(); } else { return ((SortedMap<String,Object>)rows[index]); } }