/// <summary> /// Assesses all the possible containment relations between collections A and /// B with one call.<br> /// Returns an int with bits set, according to a "Venn Diagram" view of A vs /// B.<br> /// NOT_A_SUPERSET_B: a - b != {}<br> /// NOT_A_DISJOINT_B: a/// b != {} ///// is intersects<br> /// NOT_A_SUBSET_B: b - a != {}<br> /// Thus the bits can be used to get the following relations:<br> /// for A_SUPERSET_B, use (x & CollectionUtilities.NOT_A_SUPERSET_B) == 0<br> /// for A_SUBSET_B, use (x & CollectionUtilities.NOT_A_SUBSET_B) == 0<br> /// for A_EQUALS_B, use (x & CollectionUtilities.NOT_A_EQUALS_B) == 0<br> /// for A_DISJOINT_B, use (x & CollectionUtilities.NOT_A_DISJOINT_B) == 0<br> /// for A_OVERLAPS_B, use (x & CollectionUtilities.NOT_A_DISJOINT_B) != 0<br> /// </summary> /// public static int GetContainmentRelation(ICollection a, ICollection b) { if (a.Count == 0) { return((b.Count == 0) ? ALL_EMPTY : NOT_A_SUPERSET_B); } else if (b.Count == 0) { return(NOT_A_SUBSET_B); } int result = 0; // WARNING: one might think that the following can be short-circuited, // by looking at // the sizes of a and b. However, this would fail in general, where a // different comparator is being // used in the two collections. Unfortunately, there is no failsafe way // to test for that. for (IIterator it = new ILOG.J2CsMapping.Collections.IteratorAdapter(a.GetEnumerator()); result != 6 && it.HasNext();) { result |= (ILOG.J2CsMapping.Collections.Collections.Contains(it.Next(), b)) ? NOT_A_DISJOINT_B : NOT_A_SUBSET_B; } for (IIterator it_0 = new ILOG.J2CsMapping.Collections.IteratorAdapter(b.GetEnumerator()); (result & 3) != 3 && it_0.HasNext();) { result |= (ILOG.J2CsMapping.Collections.Collections.Contains(it_0.Next(), a)) ? NOT_A_DISJOINT_B : NOT_A_SUPERSET_B; } return(result); }
// for subclassing protected internal void DoAt(ICollection c) { if (c.Count == 0) { DoBefore(c, null); } IIterator it = new ILOG.J2CsMapping.Collections.IteratorAdapter(c.GetEnumerator()); bool first = true; Object last = null; while (it.HasNext()) { Object item = it.Next(); if (first) { DoBefore(c, item); first = false; } else { DoBetween(c, last, item); } DoAt(last = item); } DoAfter(c, last); }
/// <summary> /// Stop notifying this listener. The listener must not be null. Attemps to /// remove a listener that is not registered will be silently ignored. /// </summary> /// public void RemoveListener(IEventListener l) { if (l == null) { throw new NullReferenceException(); } lock (notifyLock) { if (listeners != null) { // identity equality check IIterator iter = new ILOG.J2CsMapping.Collections.IteratorAdapter(listeners.GetEnumerator()); while (iter.HasNext()) { if (iter.Next() == (Object)l) { iter.Remove(); if (listeners.Count == 0) { listeners = null; } return; } } } } }
static internal void TestLocales() { CultureInfo[] locales = System.Globalization.ComparatorInfo.GetAvailableLocales(); ILOG.J2CsMapping.Collections.ISet s = new SortedSet(System.Globalization.ComparatorInfo.GetInstance()); for (int i = 0; i < locales.Length; ++i) { String lang = locales[i].TwoLetterISOLanguageName; String dlang = locales[i].GetDisplayLanguage(); String country = ILOG.J2CsMapping.Util.Culture.CultureInfoHelper.GetCountry(locales[i]); String dcountry = locales[i].GetDisplayCountry(); if (country.Equals("")) { continue; } ILOG.J2CsMapping.Collections.Generics.Collections.Add(s, "" + "\t" + dcountry + "\t" + country + "\t" + dlang + "\t" + lang); } // CollectionFormatter cf = new CollectionFormatter(); StreamWriter pw = IBM.ICU.Charset.BagFormatter.OpenUTF8Writer("", "countries.txt"); IIterator it = new ILOG.J2CsMapping.Collections.IteratorAdapter(s.GetEnumerator()); while (it.HasNext()) { pw.WriteLine(it.Next()); } pw.Close(); }
/// <summary> /// A helper function to calculate black interval results or white interval /// results. /// </summary> /// /// <param name="list"></param> /// <param name="timeStamp">The time stamp as milliseconds since Jan 1, 1970 UTC.</param> /// <param name="positiveResult">The positive result which is updated.</param> /// <param name="negativeResult">The negative result which is updated.</param> private static void calculateIntervalResult(SortedSet list, double timeStamp, Interval positiveResult, Interval negativeResult) { for (IIterator i = new ILOG.J2CsMapping.Collections.IteratorAdapter(list.GetEnumerator()); i.HasNext();) { RepetitiveInterval element = (RepetitiveInterval)i.Next(); RepetitiveInterval.Result result = element.getInterval(timeStamp); Interval tempInterval = result.interval; if (result.isPositive == true) { try { positiveResult.unionWith(tempInterval); } catch (Interval.Error ex) { // We don't expect to get this error. throw new Exception("Error in Interval.unionWith: " + ex.Message); } } else { if (!negativeResult.isValid()) { negativeResult.set(tempInterval); } else { negativeResult.intersectWith(tempInterval); } } } }
/// <summary> /// Return a snapshot of the mapping from display names to visible IDs for /// this service. This set will not change as factories are added or removed, /// but the supported ids will, so there is no guarantee that all and only /// the ids in the returned map will be visible and supported by the service /// in subsequent calls, nor is there any guarantee that the current display /// names match those in the set. The display names are sorted based on the /// comparator provided. /// </summary> /// public SortedList GetDisplayNames(ULocale locale, IComparer com, String matchID) { SortedList dncache = null; ICUService.LocaleRef xref = dnref; if (xref != null) { dncache = xref.Get(locale, com); } while (dncache == null) { lock (this) { if (xref == dnref || dnref == null) { dncache = new SortedList(com); // sorted IDictionary m = GetVisibleIDMap(); IIterator ei = new ILOG.J2CsMapping.Collections.IteratorAdapter(m.GetEnumerator()); while (ei.HasNext()) { DictionaryEntry e = (DictionaryEntry)ei.Next(); String id_0 = (String)((DictionaryEntry)e).Key; ICUService.Factory f = (ICUService.Factory)((DictionaryEntry)e).Value; ILOG.J2CsMapping.Collections.Collections.Put(dncache, f.GetDisplayName(id_0, locale), id_0); } dncache = /*ILOG.J2CsMapping.Collections.Generics.Collections.UnmodifiableSortedMap(*/ dncache /*)*/; dnref = new ICUService.LocaleRef(dncache, locale, com); } else { xref = dnref; dncache = xref.Get(locale, com); } } } ICUService.Key matchKey = CreateKey(matchID); if (matchKey == null) { return(dncache); } SortedList result = new SortedList(dncache); IIterator iter = new ILOG.J2CsMapping.Collections.IteratorAdapter(result.GetEnumerator()); while (iter.HasNext()) { DictionaryEntry e_1 = (DictionaryEntry)iter.Next(); if (!matchKey.IsFallbackOf((String)((DictionaryEntry)e_1).Value)) { iter.Remove(); } } return(result); }
/// <summary> /// Utility that ought to be on Map /// </summary> /// public static IDictionary RemoveAll(IDictionary m, ICollection itemsToRemove) { for (IIterator it = new ILOG.J2CsMapping.Collections.IteratorAdapter(itemsToRemove.GetEnumerator()); it.HasNext();) { Object item = it.Next(); ILOG.J2CsMapping.Collections.Collections.Remove(m, item); } return(m); }
private ICUPropertyFactory() { ICollection c = GetInternalAvailablePropertyAliases(new ArrayList()); IIterator it = new ILOG.J2CsMapping.Collections.IteratorAdapter(c.GetEnumerator()); while (it.HasNext()) { Add(GetInternalProperty((String)it.Next())); } }
public Object GetFirst(ICollection c) { IIterator it = new ILOG.J2CsMapping.Collections.IteratorAdapter(c.GetEnumerator()); if (!it.HasNext()) { return(null); } return(it.Next()); }
public static String Show(ICollection c) { StringBuilder buffer = new StringBuilder(); for (IIterator it = new ILOG.J2CsMapping.Collections.IteratorAdapter(c.GetEnumerator()); it.HasNext();) { buffer.Append(it.Next() + "\r\n"); } return(buffer.ToString()); }
public virtual Object[] ToArray(Object[] a) { int count = 0; for (IIterator it = new ILOG.J2CsMapping.Collections.IteratorAdapter(this.GetEnumerator()); it.HasNext();) { a[count++] = it.Next(); } return(a); }
public static String Show(IDictionary m) { StringBuilder buffer = new StringBuilder(); for (IIterator it = new ILOG.J2CsMapping.Collections.IteratorAdapter(new ILOG.J2CsMapping.Collections.ListSet(m.Keys).GetEnumerator()); it.HasNext();) { Object key = it.Next(); buffer.Append(key + "=>" + ILOG.J2CsMapping.Collections.Collections.Get(m, key) + "\r\n"); } return(buffer.ToString()); }
public virtual bool ContainsAll(ICollection c) { for (IIterator it = new ILOG.J2CsMapping.Collections.IteratorAdapter(c.GetEnumerator()); it.HasNext();) { if (!ILOG.J2CsMapping.Collections.Collections.Contains(it.Next(), this)) { return(false); } } return(true); }
public ILOG.J2CsMapping.Collections.ISet GetEquivalenceSets() { ILOG.J2CsMapping.Collections.ISet result = new HashedSet(); for (IIterator it = new ILOG.J2CsMapping.Collections.IteratorAdapter(new ILOG.J2CsMapping.Collections.ListSet(toPartitionSet.Keys).GetEnumerator()); it.HasNext();) { Object item = it.Next(); ILOG.J2CsMapping.Collections.ISet partition = (ISet)ILOG.J2CsMapping.Collections.Collections.Get(toPartitionSet, item); ILOG.J2CsMapping.Collections.Generics.Collections.Add(result, ILOG.J2CsMapping.Collections.Generics.Collections.UnmodifiableSet(partition)); } return(result); }
// ----------------------------------------------------------------------------- // // printSet Debug function. Print the contents of a set of Nodes // // ----------------------------------------------------------------------------- internal void PrintSet(ICollection s) { IIterator it = new ILOG.J2CsMapping.Collections.IteratorAdapter(s.GetEnumerator()); while (it.HasNext()) { RBBINode n = (RBBINode)it.Next(); IBM.ICU.Text.RBBINode.PrintInt(n.fSerialNum, 8); } System.Console.Out.WriteLine(); }
public static ICollection RetainAll(ICollection c, CollectionUtilities.ObjectMatcher f) { for (IIterator it = new ILOG.J2CsMapping.Collections.IteratorAdapter(c.GetEnumerator()); it.HasNext();) { Object item = it.Next(); if (!f.Matches(item)) { it.Remove(); } } return(c); }
// TODO Fix to serialize more than just strings. // Only if all the items are strings will we do the following compression // Otherwise we'll just use Java Serialization, bulky as it is /*public void WriteExternal(ObjectOutput out1) { * DataOutputCompressor sc = new DataOutputCompressor(out1); * // if all objects are strings * ICollection availableVals = GetAvailableValues(); * bool allStrings = AllAreString(availableVals); * sc.WriteBoolean(allStrings); * IDictionary object_index = new Hashtable(); * if (AllAreString(availableVals)) { * sc.WriteStringSet(new SortedSet(availableVals), object_index); * } else { * sc.WriteCollection(availableVals, object_index); * } * sc.WriteUInt(length); * int lastTransition = -1; * int lastValueNumber = 0; * if (DEBUG_WRITE) * System.Console.Out.WriteLine("Trans count: " + length); * for (int i = 0; i < length; ++i) { * int valueNumber = ((Int32) ILOG.J2CsMapping.Collections.Collections.Get(object_index,values[i])); * if (DEBUG_WRITE) * System.Console.Out.WriteLine("Trans: " + transitions[i] + ",\t" + valueNumber); + + int deltaTransition = transitions[i] - lastTransition; + lastTransition = transitions[i]; + int deltaValueNumber = valueNumber - lastValueNumber; + lastValueNumber = valueNumber; + + deltaValueNumber <<= 1; // make room for one bit + bool canCombine = deltaTransition == 1; + if (canCombine) + deltaValueNumber |= 1; + sc.WriteInt(deltaValueNumber); + if (DEBUG_WRITE) + System.Console.Out.WriteLine("deltaValueNumber: " + deltaValueNumber); + if (!canCombine) { + sc.WriteUInt(deltaTransition); + if (DEBUG_WRITE) + System.Console.Out.WriteLine("deltaTransition: " + deltaTransition); + } + } + sc.Flush(); + }*/ private bool AllAreString(ICollection availableValues2) { // if (true) return false; for (IIterator it = new ILOG.J2CsMapping.Collections.IteratorAdapter(availableValues2.GetEnumerator()); it.HasNext();) { if (!(it.Next() is String)) { return(false); } } return(true); }
/// <summary> /// Override of superclass method. /// </summary> /// public override void UpdateVisibleIDs(IDictionary result) { ILOG.J2CsMapping.Collections.ISet visibleIDs = IBM.ICU.Impl.ICUResourceBundle .GetAvailableLocaleNameSet(bundleName); // only visible ids IIterator iter = new ILOG.J2CsMapping.Collections.IteratorAdapter(visibleIDs.GetEnumerator()); while (iter.HasNext()) { String id_0 = (String)iter.Next(); ILOG.J2CsMapping.Collections.Collections.Put(result, id_0, this); } }
/// <exclude/> /// <summary> /// Simple implementation of permutation. <br> /// <b>Warning: The strings are not guaranteed to be in any particular /// order.</b> /// </summary> /// /// <param name="source">the string to find permutations for</param> /// <param name="skipZeros">set to true to skip characters with canonical combining classzero</param> /// <param name="output">the set to add the results to</param> public static void Permute(String source, bool skipZeros, ILOG.J2CsMapping.Collections.ISet output) { // TODO: optimize // if (PROGRESS) System.out.println("Permute: " + source); // optimization: // if zero or one character, just return a set with it // we check for length < 2 to keep from counting code points all the // time if (source.Length <= 2 && IBM.ICU.Text.UTF16.CountCodePoint(source) <= 1) { ILOG.J2CsMapping.Collections.Generics.Collections.Add(output, source); return; } // otherwise iterate through the string, and recursively permute all the // other characters ILOG.J2CsMapping.Collections.ISet subpermute = new HashedSet(); int cp; for (int i = 0; i < source.Length; i += IBM.ICU.Text.UTF16.GetCharCount(cp)) { cp = IBM.ICU.Text.UTF16.CharAt(source, i); // optimization: // if the character is canonical combining class zero, // don't permute it if (skipZeros && i != 0 && IBM.ICU.Lang.UCharacter.GetCombiningClass(cp) == 0) { // System.out.println("Skipping " + // Utility.hex(UTF16.valueOf(source, i))); continue; } // see what the permutations of the characters before and after this // one are ILOG.J2CsMapping.Collections.Collections.Clear(subpermute); Permute(source.Substring(0, (i) - (0)) + source.Substring(i + IBM.ICU.Text.UTF16.GetCharCount(cp)), skipZeros, subpermute); // prefix this character to all of them String chStr = IBM.ICU.Text.UTF16.ValueOf(source, i); IIterator it = new ILOG.J2CsMapping.Collections.IteratorAdapter(subpermute.GetEnumerator()); while (it.HasNext()) { String piece = chStr + (String)it.Next(); // if (PROGRESS) System.out.println(" Piece: " + piece); ILOG.J2CsMapping.Collections.Generics.Collections.Add(output, piece); } } }
public virtual bool RemoveAll(ICollection c) { bool result = false; for (IIterator it = new ILOG.J2CsMapping.Collections.IteratorAdapter(c.GetEnumerator()); it.HasNext();) { if (ILOG.J2CsMapping.Collections.Generics.Collections.Remove(this, it.Next())) { result = true; } } return(result); }
static internal void GeneratePropertyAliases(bool showValues, UnicodeProperty.Factory ups) { ComparatorInfo order = System.Globalization.ComparatorInfo.GetInstance(System.Globalization.CultureInfo.CreateSpecificCulture("en")); SortedSet props = new SortedSet(order); SortedSet values = new SortedSet(order); BagFormatter bf = new BagFormatter(); ILOG.J2CsMapping.Collections.Generics.Collections.AddAll(ups.GetAvailableNames(), props); for (int i = IBM.ICU.Charset.UnicodeProperty.BINARY; i < IBM.ICU.Charset.UnicodeProperty.LIMIT_TYPE; ++i) { System.Console.Out.WriteLine(IBM.ICU.Charset.UnicodeProperty.GetTypeName(i)); IIterator it = new ILOG.J2CsMapping.Collections.IteratorAdapter(props.GetEnumerator()); while (it.HasNext()) { String propAlias = (String)it.Next(); UnicodeProperty up = ups.GetProperty(propAlias); int type = up.GetType(); if (type != i) { continue; } System.Console.Out.WriteLine(); System.Console.Out.WriteLine(propAlias + "\t" + bf.Join(up.GetNameAliases())); if (!showValues) { continue; } ILOG.J2CsMapping.Collections.Collections.Clear(values); if (type == IBM.ICU.Charset.UnicodeProperty.NUMERIC || type == IBM.ICU.Charset.UnicodeProperty.EXTENDED_NUMERIC) { UnicodeMap um = new UnicodeMap(); um.PutAll(up); System.Console.Out.WriteLine(um.ToString(new TestBagFormatter.NumberComparator())); continue; } ILOG.J2CsMapping.Collections.Collections.Clear(values); ILOG.J2CsMapping.Collections.Generics.Collections.AddAll(up.GetAvailableValues(), values); IIterator it2 = new ILOG.J2CsMapping.Collections.IteratorAdapter(values.GetEnumerator()); while (it2.HasNext()) { String valueAlias = (String)it2.Next(); System.Console.Out.WriteLine("\t" + bf.Join(valueAlias + "\t" + up.GetValueAliases(valueAlias))); } } } }
// we have a segment, in NFD. Find all the strings that are canonically // equivalent to it. private String[] GetEquivalents(String segment) { ILOG.J2CsMapping.Collections.ISet result = new HashedSet(); ILOG.J2CsMapping.Collections.ISet basic = GetEquivalents2(segment); ILOG.J2CsMapping.Collections.ISet permutations = new HashedSet(); // now get all the permutations // add only the ones that are canonically equivalent // TODO: optimize by not permuting any class zero. IIterator it = new ILOG.J2CsMapping.Collections.IteratorAdapter(basic.GetEnumerator()); while (it.HasNext()) { String item = (String)it.Next(); ILOG.J2CsMapping.Collections.Collections.Clear(permutations); Permute(item, SKIP_ZEROS, permutations); IIterator it2 = new ILOG.J2CsMapping.Collections.IteratorAdapter(permutations.GetEnumerator()); while (it2.HasNext()) { String possible = (String)it2.Next(); /* * String attempt = Normalizer.normalize(possible, * Normalizer.DECOMP, 0); if (attempt.equals(segment)) { */ if (IBM.ICU.Text.Normalizer.Compare(possible, segment, 0) == 0) { if (PROGRESS) { System.Console.Out.WriteLine("Adding Permutation: " + IBM.ICU.Impl.Utility.Hex(possible)); } ILOG.J2CsMapping.Collections.Generics.Collections.Add(result, possible); } else { if (PROGRESS) { System.Console.Out.WriteLine("-Skipping Permutation: " + IBM.ICU.Impl.Utility.Hex(possible)); } } } } // convert into a String[] to clean up storage String[] finalResult = new String[result.Count]; ILOG.J2CsMapping.Collections.Generics.Collections.ToArray(result, finalResult); return(finalResult); }
/// <summary> /// Convenience method for callers using locales. This returns the standard /// ULocale list, built from the Set of visible ids. /// </summary> /// public ULocale[] GetAvailableULocales() { ILOG.J2CsMapping.Collections.ISet visIDs = GetVisibleIDs(); IIterator iter = new ILOG.J2CsMapping.Collections.IteratorAdapter(visIDs.GetEnumerator()); ULocale[] locales = new ULocale[visIDs.Count]; int n = 0; while (iter.HasNext()) { locales[n++] = new ULocale((String)iter.Next()); } return(locales); }
public override bool First(AbstractSet set) { if (children != null) { for (IIterator i = new ILOG.J2CsMapping.Collections.IteratorAdapter(children.GetEnumerator()); i.HasNext();) { if (((AbstractSet)i.Next()).First(set)) { return(true); } } } return(false); }
public static Object GetBest(ICollection c, IComparer comp, int direction) { IIterator it = new ILOG.J2CsMapping.Collections.IteratorAdapter(c.GetEnumerator()); if (!it.HasNext()) { return(null); } Object bestSoFar = it.Next(); if (direction < 0) { while (it.HasNext()) { Object item = it.Next(); int compValue = comp.Compare(item, bestSoFar); if (compValue < 0) { bestSoFar = item; } } } else { while (it.HasNext()) { Object item_0 = it.Next(); int compValue_1 = comp.Compare(item_0, bestSoFar); if (compValue_1 > 0) { bestSoFar = item_0; } } } return(bestSoFar); }
public void WriteStringSet(SortedSet c, IDictionary object_index) { if (SHOW) { System.Console.Out.WriteLine("writeStringSet"); } WriteUInt(c.Count); int i = 0; ILOG.J2CsMapping.Collections.Collections.Put(object_index, null, ((int)(i++))); DataOutputCompressor.WritePool trailingPool = new DataOutputCompressor.WritePool(); String lastString = ""; for (IIterator it = new ILOG.J2CsMapping.Collections.IteratorAdapter(c.GetEnumerator()); it.HasNext();) { String s = (String)it.Next(); ILOG.J2CsMapping.Collections.Collections.Put(object_index, s, ((int)(i++))); int common = IBM.ICU.Charset.UnicodeMap.FindCommon(lastString, s); // runlength // encode lastString = s; String piece = s.Substring(common); if (SHOW) { System.Console.Out.WriteLine(common); } common <<= 1; int inPool = trailingPool.GetIndex(piece); if (inPool < 0) { WriteUInt(common); WriteUTF(piece); trailingPool.Put(piece); } else { WriteUInt(common | 1); WriteUInt(inPool); if (SHOW) { System.Console.Out.WriteLine("\t" + inPool); } } if (SHOW) { System.Console.Out.WriteLine("\t\t" + lastString); } } }
public static UnicodeSet GetSet(IDictionary m, Object value_ren) { UnicodeSet result = new UnicodeSet(); for (IIterator it = new ILOG.J2CsMapping.Collections.IteratorAdapter(new ILOG.J2CsMapping.Collections.ListSet(m.Keys).GetEnumerator()); it.HasNext();) { Object key = it.Next(); Object val = ILOG.J2CsMapping.Collections.Collections.Get(m, key); if (!val.Equals(value_ren)) { continue; } result.Add(((Int32)key)); } return(result); }
/// <exception cref="IOException"></exception> public void WriteCollection(ICollection c, IDictionary object_index) { WriteUInt(c.Count); int i = 0; ILOG.J2CsMapping.Collections.Collections.Put(object_index, null, ((int)(i++))); for (IIterator it = new ILOG.J2CsMapping.Collections.IteratorAdapter(c.GetEnumerator()); it.HasNext();) { Object s = it.Next(); dataOutput.WriteObject(s); if (object_index != null) { ILOG.J2CsMapping.Collections.Collections.Put(object_index, s, ((int)(i++))); } } }
public String Replace(String source) { String oldSource; do { oldSource = source; for (IIterator it = new ILOG.J2CsMapping.Collections.IteratorAdapter(new ILOG.J2CsMapping.Collections.ListSet(m.Keys).GetEnumerator()); it.HasNext();) { String variable = (String)it.Next(); String value_ren = (String)ILOG.J2CsMapping.Collections.Collections.Get(m, variable); source = ReplaceAll(source, variable, value_ren); } } while (!source.Equals(oldSource)); return(source); }
static internal void TestIsRTL() { CultureInfo[] locales = System.Globalization.CultureInfo.GetCultures(CultureTypes.AllCultures); ILOG.J2CsMapping.Collections.ISet s = new SortedSet(); for (int i = 0; i < locales.Length; ++i) { ILOG.J2CsMapping.Collections.Generics.Collections.Add(s, ((IsRTL(locales[i])) ? "R " : "L ") + locales[i].DisplayName); } IIterator it = new ILOG.J2CsMapping.Collections.IteratorAdapter(s.GetEnumerator()); while (it.HasNext()) { System.Console.Out.WriteLine(it.Next()); } }
/// <summary> /// Create a group key for the interval into which timeSlot falls. This creates /// a group key if it doesn't exist, and encrypts the key using the public key /// of each eligible member. /// </summary> /// /// <param name="timeSlot">The time slot to cover as milliseconds since Jan 1, 1970 UTC.</param> /// <returns>A List of Data packets where the first is the E-KEY data packet /// with the group's public key and the rest are the D-KEY data packets with /// the group's private key encrypted with the public key of each eligible /// member. (Use List without generics so it works with older Java compilers.)</returns> /// <exception cref="GroupManagerDb.Error">for a database error.</exception> /// <exception cref="System.Security.SecurityException">for an error using the security KeyChain.</exception> public IList getGroupKey(double timeSlot) { IDictionary memberKeys = new SortedList(); IList result = new ArrayList(); // Get the time interval. Interval finalInterval = calculateInterval(timeSlot, memberKeys); if (finalInterval.isValid() == false) return result; String startTimeStamp = net.named_data.jndn.encrypt.Schedule.toIsoString(finalInterval .getStartTime()); String endTimeStamp = net.named_data.jndn.encrypt.Schedule.toIsoString(finalInterval.getEndTime()); // Generate the private and public keys. Blob[] privateKeyBlob = { null }; Blob[] publicKeyBlob = { null }; generateKeyPair(privateKeyBlob, publicKeyBlob); // Add the first element to the result. // The E-KEY (public key) data packet name convention is: // /<data_type>/E-KEY/[start-ts]/[end-ts] Data data = createEKeyData(startTimeStamp, endTimeStamp, publicKeyBlob[0]); ILOG.J2CsMapping.Collections.Collections.Add(result,data); // Encrypt the private key with the public key from each member's certificate. for (IIterator i = new ILOG.J2CsMapping.Collections.IteratorAdapter(memberKeys.GetEnumerator()); i.HasNext();) { DictionaryEntry entry = (DictionaryEntry) i.Next(); Name keyName = (Name) ((DictionaryEntry) entry).Key; Blob certificateKey = (Blob) ((DictionaryEntry) entry).Value; // Generate the name of the packet. // The D-KEY (private key) data packet name convention is: // /<data_type>/D-KEY/[start-ts]/[end-ts]/[member-name] data = createDKeyData(startTimeStamp, endTimeStamp, keyName, privateKeyBlob[0], certificateKey); ILOG.J2CsMapping.Collections.Collections.Add(result,data); } return result; }
/// <summary> /// Create the content key corresponding to the timeSlot. This first checks if /// the content key exists. For an existing content key, this returns the /// content key name directly. If the key does not exist, this creates one and /// encrypts it using the corresponding E-KEYs. The encrypted content keys are /// passed to the onEncryptedKeys callback. /// </summary> /// /// <param name="timeSlot_0">The time slot as milliseconds since Jan 1, 1970 UTC.</param> /// <param name="onEncryptedKeys_1">content key Data packets. If onEncryptedKeys is null, this does not use it. NOTE: The library will log any exceptions thrown by this callback, but for better error handling the callback should catch and properly handle any exceptions.</param> /// <param name="onError_2">better error handling the callback should catch and properly handle any exceptions.</param> /// <returns>The content key name.</returns> public Name createContentKey(double timeSlot_0, Producer.OnEncryptedKeys onEncryptedKeys_1, net.named_data.jndn.encrypt.EncryptError.OnError onError_2) { double hourSlot = getRoundedTimeSlot(timeSlot_0); // Create the content key name. Name contentKeyName = new Name(namespace_); contentKeyName.append(net.named_data.jndn.encrypt.algo.Encryptor.NAME_COMPONENT_C_KEY); contentKeyName.append(net.named_data.jndn.encrypt.Schedule.toIsoString(hourSlot)); Blob contentKeyBits; // Check if we have created the content key before. if (database_.hasContentKey(timeSlot_0)) // We have created the content key. Return its name directly. return contentKeyName; // We haven't created the content key. Create one and add it into the database. AesKeyParams aesParams = new AesKeyParams(128); contentKeyBits = net.named_data.jndn.encrypt.algo.AesAlgorithm.generateKey(aesParams).getKeyBits(); database_.addContentKey(timeSlot_0, contentKeyBits); // Now we need to retrieve the E-KEYs for content key encryption. double timeCount = Math.Round(timeSlot_0,MidpointRounding.AwayFromZero); ILOG.J2CsMapping.Collections.Collections.Put(keyRequests_,timeCount,new Producer.KeyRequest (eKeyInfo_.Count)); Producer.KeyRequest keyRequest = (Producer.KeyRequest ) ILOG.J2CsMapping.Collections.Collections.Get(keyRequests_,timeCount); // Check if the current E-KEYs can cover the content key. Exclude timeRange = new Exclude(); excludeAfter(timeRange, new Name.Component(net.named_data.jndn.encrypt.Schedule.toIsoString(timeSlot_0))); new ILOG.J2CsMapping.Collections.IteratorAdapter(eKeyInfo_.GetEnumerator()); for (IIterator i = new ILOG.J2CsMapping.Collections.IteratorAdapter(eKeyInfo_.GetEnumerator()); i.HasNext();) { // For each current E-KEY. DictionaryEntry entry = (DictionaryEntry) i.Next(); Producer.KeyInfo keyInfo = (Producer.KeyInfo ) ((DictionaryEntry) entry).Value; if (timeSlot_0 < keyInfo.beginTimeSlot || timeSlot_0 >= keyInfo.endTimeSlot) { // The current E-KEY cannot cover the content key, so retrieve one. ILOG.J2CsMapping.Collections.Collections.Put(keyRequest.repeatAttempts,((DictionaryEntry) entry).Key,0); sendKeyInterest( new Interest((Name) ((DictionaryEntry) entry).Key).setExclude( timeRange).setChildSelector(1), timeSlot_0, onEncryptedKeys_1, onError_2); } else { // The current E-KEY can cover the content key. // Encrypt the content key directly. Name eKeyName = new Name((Name) ((DictionaryEntry) entry).Key); eKeyName.append(net.named_data.jndn.encrypt.Schedule.toIsoString(keyInfo.beginTimeSlot)); eKeyName.append(net.named_data.jndn.encrypt.Schedule.toIsoString(keyInfo.endTimeSlot)); encryptContentKey(keyInfo.keyBits, eKeyName, timeSlot_0, onEncryptedKeys_1, onError_2); } } return contentKeyName; }