Exemple #1
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldRegisterAndUnregisterValues()
        public virtual void ShouldRegisterAndUnregisterValues()
        {
            InFlightMap <object> entries = new InFlightMap <object>();

            entries.Enable();

            IDictionary <long, object> logEntryList = new Dictionary <long, object>();

            logEntryList[1L] = new object();

            foreach (KeyValuePair <long, object> entry in logEntryList.SetOfKeyValuePairs())
            {
                entries.Put(entry.Key, entry.Value);
            }

            foreach (KeyValuePair <long, object> entry in logEntryList.SetOfKeyValuePairs())
            {
                object retrieved = entries.Get(entry.Key);
                assertEquals(entry.Value, retrieved);
            }

            long?  unexpected   = 2L;
            object shouldBeNull = entries.Get(unexpected);

            assertNull(shouldBeNull);

            foreach (KeyValuePair <long, object> entry in logEntryList.SetOfKeyValuePairs())
            {
                bool wasThere = entries.Remove(entry.Key);
                assertTrue(wasThere);
            }
        }
Exemple #2
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldFailWhenTryingToPackAndUnpackMapContainingNullKeys() throws java.io.IOException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldFailWhenTryingToPackAndUnpackMapContainingNullKeys()
        {
            // Given
            PackedOutputArray output = new PackedOutputArray();

            Org.Neo4j.Bolt.messaging.Neo4jPack_Packer packer = _neo4jPack.newPacker(output);

            IDictionary <string, AnyValue> map = new Dictionary <string, AnyValue>();

            map[null]  = longValue(42L);
            map["foo"] = longValue(1337L);
            packer.PackMapHeader(map.Count);
            foreach (KeyValuePair <string, AnyValue> entry in map.SetOfKeyValuePairs())
            {
                packer.pack(entry.Key);
                packer.pack(entry.Value);
            }

            // When
            try
            {
                PackedInputArray input = new PackedInputArray(output.Bytes());
                Org.Neo4j.Bolt.messaging.Neo4jPack_Unpacker unpacker = _neo4jPack.newUnpacker(input);
                unpacker.Unpack();

                fail("exception expected");
            }
            catch (BoltIOException ex)
            {
                assertEquals(Neo4jError.from(Org.Neo4j.Kernel.Api.Exceptions.Status_Request.Invalid, "Value `null` is not supported as key in maps, must be a non-nullable string."), Neo4jError.from(ex));
            }
        }
        internal virtual void pauseAllSubscriptions()
        {
            //NOTE calling onPause on a two level subscriptions triggers doRemove calls
            //for second-level subscriptions.
            //To avoid unexpected behavior caused by remove calls while iterating
            //we either clone the list of subscriptions before iterating, or we
            //iterate first to remove second-level subscriptions from the collection
            //and then iterate again to call the onPause on first-level subscriptions.
            //In the second case we should also avoid calling remove on the doRemove
            //methods.
            //To avoid complications I chose to go down the clone path.

            Dictionary <int, Subscription> copy = new Dictionary <int, Subscription>(subscriptions);

            foreach (KeyValuePair <int, Subscription> subscriptionPair in copy.SetOfKeyValuePairs())
            {
                Subscription subscription = subscriptionPair.Value;

                if (subscription.SubTable)
                {
                    //no need to pause these, will be removed soon
                    return;
                }

                subscription.onPause();
            }
        }
Exemple #4
0
        static TimeZones()
        {
            string  latestVersion = "";
            Pattern version       = Pattern.compile("# tzdata([0-9]{4}[a-z])");
            IDictionary <string, string> oldToNewName = new Dictionary <string, string>(1024);

            try
            {
                using (StreamReader reader = new StreamReader(typeof(TimeZones).getResourceAsStream("/TZIDS")))
                {
                    for (string line; (line = reader.ReadLine()) != null;)
                    {
                        if (line.StartsWith("//") || line.Trim().Empty)
                        {
                            continue;
                        }
                        else if (line.StartsWith("#"))
                        {
                            Matcher matcher = version.matcher(line);
                            if (matcher.matches())
                            {
                                latestVersion = matcher.group(1);
                            }
                            continue;
                        }
                        int sep = line.IndexOf(' ');
                        if (sep != -1)
                        {
                            string oldName = line.substring(0, sep);
                            string newName = line.substring(sep + 1);
                            _timeZoneShortToString.Add(newName);
                            oldToNewName[oldName] = newName;
                        }
                        else
                        {
                            _timeZoneShortToString.Add(line);
                            _timeZoneStringToShort[line] = ( short )(_timeZoneShortToString.Count - 1);
                        }
                    }
                    LatestSupportedIanaVersion = latestVersion;
                }
            }
            catch (IOException)
            {
                throw new Exception("Failed to read time zone id file.");
            }

            foreach (KeyValuePair <string, string> entry in oldToNewName.SetOfKeyValuePairs())
            {
                string oldName   = entry.Key;
                string newName   = entry.Value;
                short? newNameId = _timeZoneStringToShort[newName];
                _timeZoneStringToShort[oldName] = newNameId.Value;
            }
        }
Exemple #5
0
        private void GenerateReadReplicaAttributes(System.Guid hzId, MemberId memberId, ReadReplicaInfo readReplicaInfo, ISet <string> missingAttrsMaps, ISet <string> nullAttrs)
        {
            IDictionary <string, System.Func <MemberId, ReadReplicaInfo, string> > attributeFactories = new Dictionary <string, System.Func <MemberId, ReadReplicaInfo, string> >();

            attributeFactories[READ_REPLICAS_DB_NAME_MAP] = (ignored, rr) => rr.DatabaseName;
            attributeFactories[READ_REPLICA_TRANSACTION_SERVER_ADDRESS_MAP] = (ignored, rr) => rr.CatchupServer.ToString();
            attributeFactories[READ_REPLICA_MEMBER_ID_MAP]    = (mId, ignored) => mId.Uuid.ToString();
            attributeFactories[READ_REPLICA_BOLT_ADDRESS_MAP] = (ignored, rr) => rr.connectors().ToString();

            attributeFactories.SetOfKeyValuePairs().Where(e => !missingAttrsMaps.Contains(e.Key)).ForEach(e =>
            {
                string attrValue = nullAttrs.Contains(e.Key) ? null : e.Value.apply(memberId, readReplicaInfo);
                MockReadReplicaAttribute(e.Key, hzId, attrValue);
            });
        }
Exemple #6
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void testRandomRealisticWhiteSpace() throws java.io.IOException
        public virtual void testRandomRealisticWhiteSpace()
        {
            IDictionary <string, string> map = new Dictionary <string, string>();
            int numTerms = atLeast(50);

            for (int i = 0; i < numTerms; i++)
            {
                string        randomRealisticUnicodeString = TestUtil.randomRealisticUnicodeString(random());
                char[]        charArray = randomRealisticUnicodeString.ToCharArray();
                StringBuilder builder   = new StringBuilder();
                for (int j = 0; j < charArray.Length;)
                {
                    int cp = char.codePointAt(charArray, j, charArray.Length);
                    if (!char.IsWhiteSpace(cp))
                    {
                        builder.appendCodePoint(cp);
                    }
                    j += char.charCount(cp);
                }
                if (builder.Length > 0)
                {
                    string value = TestUtil.randomSimpleString(random());
                    map[builder.ToString()] = value.Length == 0 ? "a" : value;
                }
            }
            if (map.Count == 0)
            {
                map["booked"] = "books";
            }
            StemmerOverrideFilter.Builder         builder  = new StemmerOverrideFilter.Builder(random().nextBoolean());
            ISet <KeyValuePair <string, string> > entrySet = map.SetOfKeyValuePairs();
            StringBuilder  input  = new StringBuilder();
            IList <string> output = new List <string>();

            foreach (KeyValuePair <string, string> entry in entrySet)
            {
                builder.add(entry.Key, entry.Value);
                if (random().nextBoolean() || output.Count == 0)
                {
                    input.Append(entry.Key).Append(" ");
                    output.Add(entry.Value);
                }
            }
            Tokenizer   tokenizer = new WhitespaceTokenizer(TEST_VERSION_CURRENT, new StringReader(input.ToString()));
            TokenStream stream    = new PorterStemFilter(new StemmerOverrideFilter(tokenizer, builder.build()));

            assertTokenStreamContents(stream, output.ToArray());
        }
        public virtual void check_equivalent_notional()
        {
            ImmutableRatesProvider multicurve = CALIBRATOR.calibrate(GROUP_DEFINITION_PV_SENSI, MARKET_QUOTES, REF_DATA);
            // Create notional equivalent for a basis trade
            ResolvedSwapTrade              trade = ThreeLegBasisSwapConventions.EUR_FIXED_1Y_EURIBOR_3M_EURIBOR_6M.createTrade(VALUATION_DATE, Period.ofMonths(7), Tenor.TENOR_6Y, BuySell.SELL, 1_000_000, 0.03, REF_DATA).resolve(REF_DATA);
            PointSensitivities             pts   = PRICER_SWAP_TRADE.presentValueSensitivity(trade, multicurve);
            CurrencyParameterSensitivities ps    = multicurve.parameterSensitivity(pts);
            CurrencyParameterSensitivities mqs   = MQSC.sensitivity(ps, multicurve);
            CurrencyParameterSensitivities notionalEquivalent = NEC.notionalEquivalent(mqs, multicurve);

            // Check metadata are same as market quote sensitivities.
            foreach (CurrencyParameterSensitivity sensi in mqs.Sensitivities)
            {
                assertEquals(notionalEquivalent.getSensitivity(sensi.MarketDataName, sensi.Currency).ParameterMetadata, sensi.ParameterMetadata);
            }
            // Check sensitivity: trade sensitivity = sum(notional equivalent sensitivities)
            int totalNbParameters = 0;
            IDictionary <CurveName, IList <ResolvedTrade> > equivalentTrades = new Dictionary <CurveName, IList <ResolvedTrade> >();
            ImmutableList <CurveDefinition> curveGroups = GROUP_DEFINITION.CurveDefinitions;

            ImmutableList.Builder <CurveParameterSize> builder = ImmutableList.builder();
            foreach (CurveDefinition entry in curveGroups)
            {
                totalNbParameters += entry.ParameterCount;
                DoubleArray notionalCurve       = notionalEquivalent.getSensitivity(entry.Name, Currency.EUR).Sensitivity;
                ImmutableList <CurveNode> nodes = entry.Nodes;
                IList <ResolvedTrade>     resolvedTradesCurve = new List <ResolvedTrade>();
                for (int i = 0; i < nodes.size(); i++)
                {
                    resolvedTradesCurve.Add(nodes.get(i).resolvedTrade(notionalCurve.get(i), MARKET_QUOTES, REF_DATA));
                }
                equivalentTrades[entry.Name] = resolvedTradesCurve;
                builder.add(entry.toCurveParameterSize());
            }
            ImmutableList <CurveParameterSize> order = builder.build();    // order of the curves
            DoubleArray totalSensitivity             = DoubleArray.filled(totalNbParameters);

            foreach (KeyValuePair <CurveName, IList <ResolvedTrade> > entry in equivalentTrades.SetOfKeyValuePairs())
            {
                foreach (ResolvedTrade t in entry.Value)
                {
                    totalSensitivity = totalSensitivity.plus(PV_MEASURES.derivative(t, multicurve, order));
                }
            }
            DoubleArray instrumentSensi = PV_MEASURES.derivative(trade, multicurve, order);

            assertTrue(totalSensitivity.equalWithTolerance(instrumentSensi, TOLERANCE_PV_DELTA));
        }
Exemple #8
0
        public static ICollection <NumberArrayTestData> Arrays()
        {
            PageCache pageCache = _fixture.pageCache;
            File      dir       = _fixture.directory;
            ICollection <NumberArrayTestData>        list      = new List <NumberArrayTestData>();
            IDictionary <string, NumberArrayFactory> factories = new Dictionary <string, NumberArrayFactory>();

            factories["HEAP"]     = HEAP;
            factories["OFF_HEAP"] = OFF_HEAP;
            factories["AUTO_WITHOUT_PAGECACHE"]       = AUTO_WITHOUT_PAGECACHE;
            factories["CHUNKED_FIXED_SIZE"]           = CHUNKED_FIXED_SIZE;
            factories["autoWithPageCacheFallback"]    = auto(pageCache, dir, true, NO_MONITOR);
            factories["PageCachedNumberArrayFactory"] = new PageCachedNumberArrayFactory(pageCache, dir);
            foreach (KeyValuePair <string, NumberArrayFactory> entry in factories.SetOfKeyValuePairs())
            {
                string             name    = entry.Key + " => ";
                NumberArrayFactory factory = entry.Value;
//JAVA TO C# CONVERTER TODO TASK: Method reference arbitrary object instance method syntax is not converted by Java to C# Converter:
                list.Add(ArrayData(name + "IntArray", factory.NewIntArray(INDEXES, -1), _random => _random.Next(1_000_000_000), (array, index, value) => array.set(index, ( int? )value), IntArray::get));
//JAVA TO C# CONVERTER TODO TASK: Method reference arbitrary object instance method syntax is not converted by Java to C# Converter:
                list.Add(ArrayData(name + "DynamicIntArray", factory.NewDynamicIntArray(_chunkSize, -1), _random => _random.Next(1_000_000_000), (array, index, value) => array.set(index, ( int? )value), IntArray::get));

//JAVA TO C# CONVERTER TODO TASK: Method reference arbitrary object instance method syntax is not converted by Java to C# Converter:
                list.Add(ArrayData(name + "LongArray", factory.NewLongArray(INDEXES, -1), _random => _random.nextLong(1_000_000_000), (array, index, value) => array.set(index, ( long? )value), LongArray::get));
//JAVA TO C# CONVERTER TODO TASK: Method reference arbitrary object instance method syntax is not converted by Java to C# Converter:
                list.Add(ArrayData(name + "DynamicLongArray", factory.NewDynamicLongArray(_chunkSize, -1), _random => _random.nextLong(1_000_000_000), (array, index, value) => array.set(index, ( long? )value), LongArray::get));

                list.Add(ArrayData(name + "ByteArray5", factory.NewByteArray(INDEXES, DefaultByteArray(5)), _random => _random.Next(1_000_000_000), (array, index, value) => array.setInt(index, 1, ( int? )value), (array, index) => array.getInt(index, 1)));
                list.Add(ArrayData(name + "DynamicByteArray5", factory.NewDynamicByteArray(_chunkSize, DefaultByteArray(5)), _random => _random.Next(1_000_000_000), (array, index, value) => array.setInt(index, 1, ( int? )value), (array, index) => array.getInt(index, 1)));

                System.Func <RandomRule, object> valueGenerator = _random => new long[] { _random.nextLong(), _random.Next(), (short)_random.Next(), (sbyte)_random.Next() };
                Writer <ByteArray> writer = (array, index, value) =>
                {
                    long[] values = ( long[] )value;
                    array.setLong(index, 0, values[0]);
                    array.setInt(index, 8, ( int )values[1]);
                    array.setShort(index, 12, ( short )values[2]);
                    array.setByte(index, 14, ( sbyte )values[3]);
                };
                Reader <ByteArray> reader = (array, index) => new long[] { array.getLong(index, 0), array.getInt(index, 8), array.getShort(index, 12), array.getByte(index, 14) };
                list.Add(ArrayData(name + "ByteArray15", factory.NewByteArray(INDEXES, DefaultByteArray(15)), valueGenerator, writer, reader));
                list.Add(ArrayData(name + "DynamicByteArray15", factory.NewDynamicByteArray(_chunkSize, DefaultByteArray(15)), valueGenerator, writer, reader));
            }
            return(list);
        }
Exemple #9
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldListAllProperties()
        public virtual void ShouldListAllProperties()
        {
            // Given
            IDictionary <string, object> properties = new Dictionary <string, object>();

            properties["boolean"]      = true;
            properties["short_string"] = "abc";
            properties["string"]       = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVW" + "XYZabcdefghijklmnopqrstuvwxyz";
            properties["long"]         = long.MaxValue;
            properties["short_array"]  = new long[] { 1, 2, 3, 4 };
            properties["array"]        = new long[] { long.MaxValue - 1, long.MaxValue - 2, long.MaxValue - 3, long.MaxValue - 4, long.MaxValue - 5, long.MaxValue - 6, long.MaxValue - 7, long.MaxValue - 8, long.MaxValue - 9, long.MaxValue - 10, long.MaxValue - 11 };

            long containerId;

            using (Transaction tx = Db.beginTx())
            {
                containerId = CreatePropertyContainer();
                PropertyContainer container = LookupPropertyContainer(containerId);

                foreach (KeyValuePair <string, object> entry in properties.SetOfKeyValuePairs())
                {
                    container.SetProperty(entry.Key, entry.Value);
                }

                tx.Success();
            }

            // When
            IDictionary <string, object> listedProperties;

            using (Transaction tx = Db.beginTx())
            {
                listedProperties = LookupPropertyContainer(containerId).AllProperties;
                tx.Success();
            }

            // Then
            assertEquals(properties.Count, listedProperties.Count);
            foreach (string key in properties.Keys)
            {
                assertObjectOrArrayEquals(properties[key], listedProperties[key]);
            }
        }
Exemple #10
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void createFakeStoreDirectory() throws java.io.IOException
        private void CreateFakeStoreDirectory()
        {
            IDictionary <File, int> dummyStore = new Dictionary <File, int>();
            DatabaseLayout          layout     = _testDirectory.databaseLayout();

            dummyStore[layout.NodeStore()]                         = 1;
            dummyStore[layout.IdNodeStore()]                       = 2;
            dummyStore[layout.NodeLabelStore()]                    = 3;
            dummyStore[layout.IdNodeLabelStore()]                  = 4;
            dummyStore[layout.PropertyStore()]                     = 5;
            dummyStore[layout.IdPropertyStore()]                   = 6;
            dummyStore[layout.PropertyKeyTokenStore()]             = 7;
            dummyStore[layout.IdPropertyKeyTokenStore()]           = 8;
            dummyStore[layout.PropertyKeyTokenNamesStore()]        = 9;
            dummyStore[layout.IdPropertyKeyTokenNamesStore()]      = 10;
            dummyStore[layout.PropertyStringStore()]               = 11;
            dummyStore[layout.IdPropertyStringStore()]             = 12;
            dummyStore[layout.PropertyArrayStore()]                = 13;
            dummyStore[layout.IdPropertyArrayStore()]              = 14;
            dummyStore[layout.RelationshipStore()]                 = 15;
            dummyStore[layout.IdRelationshipStore()]               = 16;
            dummyStore[layout.RelationshipGroupStore()]            = 17;
            dummyStore[layout.IdRelationshipGroupStore()]          = 18;
            dummyStore[layout.RelationshipTypeTokenStore()]        = 19;
            dummyStore[layout.IdRelationshipTypeTokenStore()]      = 20;
            dummyStore[layout.RelationshipTypeTokenNamesStore()]   = 21;
            dummyStore[layout.IdRelationshipTypeTokenNamesStore()] = 22;
            dummyStore[layout.LabelTokenStore()]                   = 23;
            dummyStore[layout.IdLabelTokenStore()]                 = 24;
            dummyStore[layout.LabelTokenNamesStore()]              = 25;
            dummyStore[layout.IdLabelTokenNamesStore()]            = 26;
            dummyStore[layout.SchemaStore()]                       = 27;
            dummyStore[layout.IdSchemaStore()]                     = 28;
            dummyStore[layout.CountStoreB()]                       = 29;
            // COUNTS_STORE_B is created in the test

            foreach (KeyValuePair <File, int> fileEntry in dummyStore.SetOfKeyValuePairs())
            {
                CreateFileOfSize(fileEntry.Key, fileEntry.Value);
            }
        }
        internal virtual void sendAllSubscriptions()
        {
            //we clone just to avoid unexpected issues as in the pauseAllSubscriptions case
            //(see comment there for details)
            Dictionary <int, Subscription> copy = new Dictionary <int, Subscription>(subscriptions);

            foreach (KeyValuePair <int, Subscription> subscriptionPair in copy.SetOfKeyValuePairs())
            {
                Subscription subscription = subscriptionPair.Value;

                if (subscription.SubTable)
                {
                    log.Error("Second level subscriptions should not be in the list of paused subscriptions");
                    return;
                }

                subscription.onStart(); //wake up

                subscribe(subscription);
            }
        }
Exemple #12
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void testVariableMapCompatibility()
        public virtual void testVariableMapCompatibility()
        {
            // test compatibility with Map<String, Object>
            VariableMap map1 = createVariables().putValue("foo", 10).putValue("bar", 20);

            // assert the map is assignable to Map<String,Object>
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @SuppressWarnings("unused") java.util.Map<String, Object> assignable = map1;
            IDictionary <string, object> assignable = map1;

            VariableMap map2 = createVariables().putValueTyped("foo", integerValue(10)).putValueTyped("bar", integerValue(20));

            IDictionary <string, object> map3 = new Dictionary <string, object>();

            map3["foo"] = 10;
            map3["bar"] = 20;

            // equals()
            assertEquals(map1, map2);
            assertEquals(map2, map3);
            assertEquals(map1, fromMap(map1));
            assertEquals(map1, fromMap(map3));

            // hashCode()
            assertEquals(map1.GetHashCode(), map2.GetHashCode());
            assertEquals(map2.GetHashCode(), map3.GetHashCode());

            // values()
            VariableMap.ValueCollection values1 = map1.Values;
            VariableMap.ValueCollection values2 = map2.Values;
            IDictionary <string, object> .ValueCollection values3 = map3.Values;
            assertTrue(values1.containsAll(values2));
            assertTrue(values2.containsAll(values1));
            assertTrue(values2.containsAll(values3));
            assertTrue(values3.containsAll(values2));

            // entry set
            assertEquals(map1.SetOfKeyValuePairs(), map2.SetOfKeyValuePairs());
            assertEquals(map2.SetOfKeyValuePairs(), map3.SetOfKeyValuePairs());
        }
Exemple #13
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void testRandomRealisticKeyword() throws java.io.IOException
        public virtual void testRandomRealisticKeyword()
        {
            IDictionary <string, string> map = new Dictionary <string, string>();
            int numTerms = atLeast(50);

            for (int i = 0; i < numTerms; i++)
            {
                string randomRealisticUnicodeString = TestUtil.randomRealisticUnicodeString(random());
                if (randomRealisticUnicodeString.Length > 0)
                {
                    string value = TestUtil.randomSimpleString(random());
                    map[randomRealisticUnicodeString] = value.Length == 0 ? "a" : value;
                }
            }
            if (map.Count == 0)
            {
                map["booked"] = "books";
            }
            StemmerOverrideFilter.Builder         builder  = new StemmerOverrideFilter.Builder(random().nextBoolean());
            ISet <KeyValuePair <string, string> > entrySet = map.SetOfKeyValuePairs();

            foreach (KeyValuePair <string, string> entry in entrySet)
            {
                builder.add(entry.Key, entry.Value);
            }
            StemmerOverrideMap build = builder.build();

            foreach (KeyValuePair <string, string> entry in entrySet)
            {
                if (random().nextBoolean())
                {
                    Tokenizer   tokenizer = new KeywordTokenizer(new StringReader(entry.Key));
                    TokenStream stream    = new PorterStemFilter(new StemmerOverrideFilter(tokenizer, build));
                    assertTokenStreamContents(stream, new string[] { entry.Value });
                }
            }
        }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void testRandomMaps2() throws Exception
        public virtual void testRandomMaps2()
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.Random random = random();
            Random random = random();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int numIterations = atLeast(3);
            int numIterations = atLeast(3);

            for (int iter = 0; iter < numIterations; iter++)
            {
                if (VERBOSE)
                {
                    Console.WriteLine("\nTEST iter=" + iter);
                }

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final char endLetter = (char) org.apache.lucene.util.TestUtil.nextInt(random, 'b', 'z');
                char endLetter = (char)TestUtil.Next(random, 'b', 'z');

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.Map<String,String> map = new java.util.HashMap<>();
                IDictionary <string, string> map = new Dictionary <string, string>();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final NormalizeCharMap.Builder builder = new NormalizeCharMap.Builder();
                NormalizeCharMap.Builder builder = new NormalizeCharMap.Builder();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int numMappings = atLeast(5);
                int numMappings = atLeast(5);
                if (VERBOSE)
                {
                    Console.WriteLine("  mappings:");
                }
                while (map.Count < numMappings)
                {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final String key = org.apache.lucene.util.TestUtil.randomSimpleStringRange(random, 'a', endLetter, 7);
                    string key = TestUtil.randomSimpleStringRange(random, 'a', endLetter, 7);
                    if (key.Length != 0 && !map.ContainsKey(key))
                    {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final String value = org.apache.lucene.util.TestUtil.randomSimpleString(random);
                        string value = TestUtil.randomSimpleString(random);
                        map[key] = value;
                        builder.add(key, value);
                        if (VERBOSE)
                        {
                            Console.WriteLine("    " + key + " -> " + value);
                        }
                    }
                }

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final NormalizeCharMap charMap = builder.build();
                NormalizeCharMap charMap = builder.build();

                if (VERBOSE)
                {
                    Console.WriteLine("  test random documents...");
                }

                for (int iter2 = 0; iter2 < 100; iter2++)
                {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final String content = org.apache.lucene.util.TestUtil.randomSimpleStringRange(random, 'a', endLetter, atLeast(1000));
                    string content = TestUtil.randomSimpleStringRange(random, 'a', endLetter, atLeast(1000));

                    if (VERBOSE)
                    {
                        Console.WriteLine("  content=" + content);
                    }

                    // Do stupid dog-slow mapping:

                    // Output string:
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final StringBuilder output = new StringBuilder();
                    StringBuilder output = new StringBuilder();

                    // Maps output offset to input offset:
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.List<Integer> inputOffsets = new java.util.ArrayList<>();
                    IList <int?> inputOffsets = new List <int?>();

                    int cumDiff = 0;
                    int charIdx = 0;
                    while (charIdx < content.Length)
                    {
                        int    matchLen  = -1;
                        string matchRepl = null;

                        foreach (KeyValuePair <string, string> ent in map.SetOfKeyValuePairs())
                        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final String match = ent.getKey();
                            string match = ent.Key;
                            if (charIdx + match.Length <= content.Length)
                            {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int limit = charIdx+match.length();
                                int  limit   = charIdx + match.Length;
                                bool matches = true;
                                for (int charIdx2 = charIdx; charIdx2 < limit; charIdx2++)
                                {
                                    if (match[charIdx2 - charIdx] != content[charIdx2])
                                    {
                                        matches = false;
                                        break;
                                    }
                                }

                                if (matches)
                                {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final String repl = ent.getValue();
                                    string repl = ent.Value;
                                    if (match.Length > matchLen)
                                    {
                                        // Greedy: longer match wins
                                        matchLen  = match.Length;
                                        matchRepl = repl;
                                    }
                                }
                            }
                        }

                        if (matchLen != -1)
                        {
                            // We found a match here!
                            if (VERBOSE)
                            {
                                Console.WriteLine("    match=" + content.Substring(charIdx, matchLen) + " @ off=" + charIdx + " repl=" + matchRepl);
                            }
                            output.Append(matchRepl);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int minLen = Math.min(matchLen, matchRepl.length());
                            int minLen = Math.Min(matchLen, matchRepl.Length);

                            // Common part, directly maps back to input
                            // offset:
                            for (int outIdx = 0; outIdx < minLen; outIdx++)
                            {
                                inputOffsets.Add(output.Length - matchRepl.Length + outIdx + cumDiff);
                            }

                            cumDiff += matchLen - matchRepl.Length;
                            charIdx += matchLen;

                            if (matchRepl.Length < matchLen)
                            {
                                // Replacement string is shorter than matched
                                // input: nothing to do
                            }
                            else if (matchRepl.Length > matchLen)
                            {
                                // Replacement string is longer than matched
                                // input: for all the "extra" chars we map
                                // back to a single input offset:
                                for (int outIdx = matchLen; outIdx < matchRepl.Length; outIdx++)
                                {
                                    inputOffsets.Add(output.Length + cumDiff - 1);
                                }
                            }
                            else
                            {
                                // Same length: no change to offset
                            }

                            Debug.Assert(inputOffsets.Count == output.Length, "inputOffsets.size()=" + inputOffsets.Count + " vs output.length()=" + output.Length);
                        }
                        else
                        {
                            inputOffsets.Add(output.Length + cumDiff);
                            output.Append(content[charIdx]);
                            charIdx++;
                        }
                    }

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final String expected = output.toString();
                    string expected = output.ToString();
                    if (VERBOSE)
                    {
                        Console.Write("    expected:");
                        for (int charIdx2 = 0; charIdx2 < expected.Length; charIdx2++)
                        {
                            Console.Write(" " + expected[charIdx2] + "/" + inputOffsets[charIdx2]);
                        }
                        Console.WriteLine();
                    }

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final MappingCharFilter mapFilter = new MappingCharFilter(charMap, new java.io.StringReader(content));
                    MappingCharFilter mapFilter = new MappingCharFilter(charMap, new StringReader(content));

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final StringBuilder actualBuilder = new StringBuilder();
                    StringBuilder actualBuilder = new StringBuilder();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.List<Integer> actualInputOffsets = new java.util.ArrayList<>();
                    IList <int?> actualInputOffsets = new List <int?>();

                    // Now consume the actual mapFilter, somewhat randomly:
                    while (true)
                    {
                        if (random.nextBoolean())
                        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int ch = mapFilter.read();
                            int ch = mapFilter.read();
                            if (ch == -1)
                            {
                                break;
                            }
                            actualBuilder.Append((char)ch);
                        }
                        else
                        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final char[] buffer = new char[org.apache.lucene.util.TestUtil.nextInt(random, 1, 100)];
                            char[] buffer = new char[TestUtil.Next(random, 1, 100)];
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int off = buffer.length == 1 ? 0 : random.nextInt(buffer.length-1);
                            int off = buffer.Length == 1 ? 0 : random.Next(buffer.Length - 1);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int count = mapFilter.read(buffer, off, buffer.length-off);
                            int count = mapFilter.read(buffer, off, buffer.Length - off);
                            if (count == -1)
                            {
                                break;
                            }
                            else
                            {
                                actualBuilder.Append(buffer, off, count);
                            }
                        }

                        if (random.Next(10) == 7)
                        {
                            // Map offsets
                            while (actualInputOffsets.Count < actualBuilder.Length)
                            {
                                actualInputOffsets.Add(mapFilter.correctOffset(actualInputOffsets.Count));
                            }
                        }
                    }

                    // Finish mappping offsets
                    while (actualInputOffsets.Count < actualBuilder.Length)
                    {
                        actualInputOffsets.Add(mapFilter.correctOffset(actualInputOffsets.Count));
                    }

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final String actual = actualBuilder.toString();
                    string actual = actualBuilder.ToString();

                    // Verify:
                    assertEquals(expected, actual);
                    assertEquals(inputOffsets, actualInputOffsets);
                }
            }
        }
        public ConfiguredSpaceFillingCurveSettingsCache(Config config)
        {
            this._maxBits = config.Get(SpatialIndexSettings.SpaceFillingCurveMaxBits);
            Dictionary <CoordinateReferenceSystem, EnvelopeSettings> env = EnvelopeSettings.EnvelopeSettingsFromConfig(config);

            foreach (KeyValuePair <CoordinateReferenceSystem, EnvelopeSettings> entry in env.SetOfKeyValuePairs())
            {
                CoordinateReferenceSystem crs = entry.Key;
                _settings[crs] = SpaceFillingCurveSettingsFactory.FromConfig(this._maxBits, entry.Value);
            }
        }
        //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
        //ORIGINAL LINE: public void testRandomMaps2() throws Exception
        public virtual void testRandomMaps2()
        {
            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final java.util.Random random = random();
            Random random = random();
            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final int numIterations = atLeast(3);
            int numIterations = atLeast(3);
            for (int iter = 0;iter < numIterations;iter++)
            {

              if (VERBOSE)
              {
            Console.WriteLine("\nTEST iter=" + iter);
              }

            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final char endLetter = (char) org.apache.lucene.util.TestUtil.nextInt(random, 'b', 'z');
              char endLetter = (char) TestUtil.Next(random, 'b', 'z');

            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final java.util.Map<String,String> map = new java.util.HashMap<>();
              IDictionary<string, string> map = new Dictionary<string, string>();
            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final NormalizeCharMap.Builder builder = new NormalizeCharMap.Builder();
              NormalizeCharMap.Builder builder = new NormalizeCharMap.Builder();
            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final int numMappings = atLeast(5);
              int numMappings = atLeast(5);
              if (VERBOSE)
              {
            Console.WriteLine("  mappings:");
              }
              while (map.Count < numMappings)
              {
            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final String key = org.apache.lucene.util.TestUtil.randomSimpleStringRange(random, 'a', endLetter, 7);
            string key = TestUtil.randomSimpleStringRange(random, 'a', endLetter, 7);
            if (key.Length != 0 && !map.ContainsKey(key))
            {
            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final String value = org.apache.lucene.util.TestUtil.randomSimpleString(random);
              string value = TestUtil.randomSimpleString(random);
              map[key] = value;
              builder.add(key, value);
              if (VERBOSE)
              {
                Console.WriteLine("    " + key + " -> " + value);
              }
            }
              }

            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final NormalizeCharMap charMap = builder.build();
              NormalizeCharMap charMap = builder.build();

              if (VERBOSE)
              {
            Console.WriteLine("  test random documents...");
              }

              for (int iter2 = 0;iter2 < 100;iter2++)
              {
            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final String content = org.apache.lucene.util.TestUtil.randomSimpleStringRange(random, 'a', endLetter, atLeast(1000));
            string content = TestUtil.randomSimpleStringRange(random, 'a', endLetter, atLeast(1000));

            if (VERBOSE)
            {
              Console.WriteLine("  content=" + content);
            }

            // Do stupid dog-slow mapping:

            // Output string:
            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final StringBuilder output = new StringBuilder();
            StringBuilder output = new StringBuilder();

            // Maps output offset to input offset:
            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final java.util.List<Integer> inputOffsets = new java.util.ArrayList<>();
            IList<int?> inputOffsets = new List<int?>();

            int cumDiff = 0;
            int charIdx = 0;
            while (charIdx < content.Length)
            {

              int matchLen = -1;
              string matchRepl = null;

              foreach (KeyValuePair<string, string> ent in map.SetOfKeyValuePairs())
              {
            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final String match = ent.getKey();
                string match = ent.Key;
                if (charIdx + match.Length <= content.Length)
                {
            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final int limit = charIdx+match.length();
                  int limit = charIdx + match.Length;
                  bool matches = true;
                  for (int charIdx2 = charIdx;charIdx2 < limit;charIdx2++)
                  {
                    if (match[charIdx2 - charIdx] != content[charIdx2])
                    {
                      matches = false;
                      break;
                    }
                  }

                  if (matches)
                  {
            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final String repl = ent.getValue();
                    string repl = ent.Value;
                    if (match.Length > matchLen)
                    {
                      // Greedy: longer match wins
                      matchLen = match.Length;
                      matchRepl = repl;
                    }
                  }
                }
              }

              if (matchLen != -1)
              {
                // We found a match here!
                if (VERBOSE)
                {
                  Console.WriteLine("    match=" + content.Substring(charIdx, matchLen) + " @ off=" + charIdx + " repl=" + matchRepl);
                }
                output.Append(matchRepl);
            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final int minLen = Math.min(matchLen, matchRepl.length());
                int minLen = Math.Min(matchLen, matchRepl.Length);

                // Common part, directly maps back to input
                // offset:
                for (int outIdx = 0;outIdx < minLen;outIdx++)
                {
                  inputOffsets.Add(output.Length - matchRepl.Length + outIdx + cumDiff);
                }

                cumDiff += matchLen - matchRepl.Length;
                charIdx += matchLen;

                if (matchRepl.Length < matchLen)
                {
                  // Replacement string is shorter than matched
                  // input: nothing to do
                }
                else if (matchRepl.Length > matchLen)
                {
                  // Replacement string is longer than matched
                  // input: for all the "extra" chars we map
                  // back to a single input offset:
                  for (int outIdx = matchLen;outIdx < matchRepl.Length;outIdx++)
                  {
                    inputOffsets.Add(output.Length + cumDiff - 1);
                  }
                }
                else
                {
                  // Same length: no change to offset
                }

                Debug.Assert(inputOffsets.Count == output.Length, "inputOffsets.size()=" + inputOffsets.Count + " vs output.length()=" + output.Length);
              }
              else
              {
                inputOffsets.Add(output.Length + cumDiff);
                output.Append(content[charIdx]);
                charIdx++;
              }
            }

            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final String expected = output.toString();
            string expected = output.ToString();
            if (VERBOSE)
            {
              Console.Write("    expected:");
              for (int charIdx2 = 0;charIdx2 < expected.Length;charIdx2++)
              {
                Console.Write(" " + expected[charIdx2] + "/" + inputOffsets[charIdx2]);
              }
              Console.WriteLine();
            }

            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final MappingCharFilter mapFilter = new MappingCharFilter(charMap, new java.io.StringReader(content));
            MappingCharFilter mapFilter = new MappingCharFilter(charMap, new StringReader(content));

            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final StringBuilder actualBuilder = new StringBuilder();
            StringBuilder actualBuilder = new StringBuilder();
            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final java.util.List<Integer> actualInputOffsets = new java.util.ArrayList<>();
            IList<int?> actualInputOffsets = new List<int?>();

            // Now consume the actual mapFilter, somewhat randomly:
            while (true)
            {
              if (random.nextBoolean())
              {
            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final int ch = mapFilter.read();
                int ch = mapFilter.read();
                if (ch == -1)
                {
                  break;
                }
                actualBuilder.Append((char) ch);
              }
              else
              {
            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final char[] buffer = new char[org.apache.lucene.util.TestUtil.nextInt(random, 1, 100)];
                char[] buffer = new char[TestUtil.Next(random, 1, 100)];
            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final int off = buffer.length == 1 ? 0 : random.nextInt(buffer.length-1);
                int off = buffer.Length == 1 ? 0 : random.Next(buffer.Length - 1);
            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final int count = mapFilter.read(buffer, off, buffer.length-off);
                int count = mapFilter.read(buffer, off, buffer.Length - off);
                if (count == -1)
                {
                  break;
                }
                else
                {
                  actualBuilder.Append(buffer, off, count);
                }
              }

              if (random.Next(10) == 7)
              {
                // Map offsets
                while (actualInputOffsets.Count < actualBuilder.Length)
                {
                  actualInputOffsets.Add(mapFilter.correctOffset(actualInputOffsets.Count));
                }
              }
            }

            // Finish mappping offsets
            while (actualInputOffsets.Count < actualBuilder.Length)
            {
              actualInputOffsets.Add(mapFilter.correctOffset(actualInputOffsets.Count));
            }

            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final String actual = actualBuilder.toString();
            string actual = actualBuilder.ToString();

            // Verify:
            assertEquals(expected, actual);
            assertEquals(inputOffsets, actualInputOffsets);
              }
            }
        }
Exemple #17
0
        protected internal virtual void populateChildInstances(IDictionary <string, ActivityInstanceImpl> activityInstances, IDictionary <string, TransitionInstanceImpl> transitionInstances)
        {
            IDictionary <ActivityInstanceImpl, IList <ActivityInstanceImpl> >   childActivityInstances   = new Dictionary <ActivityInstanceImpl, IList <ActivityInstanceImpl> >();
            IDictionary <ActivityInstanceImpl, IList <TransitionInstanceImpl> > childTransitionInstances = new Dictionary <ActivityInstanceImpl, IList <TransitionInstanceImpl> >();

            foreach (ActivityInstanceImpl instance in activityInstances.Values)
            {
                if (!string.ReferenceEquals(instance.ParentActivityInstanceId, null))
                {
                    ActivityInstanceImpl parentInstance = activityInstances[instance.ParentActivityInstanceId];
                    if (parentInstance == null)
                    {
                        throw new ProcessEngineException("No parent activity instance with id " + instance.ParentActivityInstanceId + " generated");
                    }
                    putListElement(childActivityInstances, parentInstance, instance);
                }
            }

            foreach (TransitionInstanceImpl instance in transitionInstances.Values)
            {
                if (!string.ReferenceEquals(instance.ParentActivityInstanceId, null))
                {
                    ActivityInstanceImpl parentInstance = activityInstances[instance.ParentActivityInstanceId];
                    if (parentInstance == null)
                    {
                        throw new ProcessEngineException("No parent activity instance with id " + instance.ParentActivityInstanceId + " generated");
                    }
                    putListElement(childTransitionInstances, parentInstance, instance);
                }
            }

            foreach (KeyValuePair <ActivityInstanceImpl, IList <ActivityInstanceImpl> > entry in childActivityInstances.SetOfKeyValuePairs())
            {
                ActivityInstanceImpl         instance       = entry.Key;
                IList <ActivityInstanceImpl> childInstances = entry.Value;
                if (childInstances != null)
                {
                    instance.ChildActivityInstances = childInstances.ToArray();
                }
            }

            foreach (KeyValuePair <ActivityInstanceImpl, IList <TransitionInstanceImpl> > entry in childTransitionInstances.SetOfKeyValuePairs())
            {
                ActivityInstanceImpl           instance       = entry.Key;
                IList <TransitionInstanceImpl> childInstances = entry.Value;
                if (childTransitionInstances != null)
                {
                    instance.ChildTransitionInstances = childInstances.ToArray();
                }
            }
        }
Exemple #18
0
        /// <summary>
        /// Remove all entries for legacy non-scopes given that the assigned scope execution is also responsible for another scope
        /// </summary>
        public static void removeLegacyNonScopesFromMapping(IDictionary <ScopeImpl, PvmExecutionImpl> mapping)
        {
            IDictionary <PvmExecutionImpl, IList <ScopeImpl> > scopesForExecutions = new Dictionary <PvmExecutionImpl, IList <ScopeImpl> >();

            foreach (KeyValuePair <ScopeImpl, PvmExecutionImpl> mappingEntry in mapping.SetOfKeyValuePairs())
            {
                IList <ScopeImpl> scopesForExecution = scopesForExecutions[mappingEntry.Value];
                if (scopesForExecution == null)
                {
                    scopesForExecution = new List <ScopeImpl>();
                    scopesForExecutions[mappingEntry.Value] = scopesForExecution;
                }

                scopesForExecution.Add(mappingEntry.Key);
            }

            foreach (KeyValuePair <PvmExecutionImpl, IList <ScopeImpl> > scopesForExecution in scopesForExecutions.SetOfKeyValuePairs())
            {
                IList <ScopeImpl> scopes = scopesForExecution.Value;

                if (scopes.Count > 1)
                {
                    ScopeImpl topMostScope = getTopMostScope(scopes);

                    foreach (ScopeImpl scope in scopes)
                    {
                        if (scope != scope.ProcessDefinition && scope != topMostScope)
                        {
                            mapping.Remove(scope);
                        }
                    }
                }
            }
        }
Exemple #19
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldRunDistinctTransactionsAndDiverge() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldRunDistinctTransactionsAndDiverge()
        {
            int numNodes = 1;
            IDictionary <CoreClusterMember, IList <CoreClusterMember> > leaderMap = new Dictionary <CoreClusterMember, IList <CoreClusterMember> >();

            foreach (string dbName in _dbNames)
            {
                int i = 0;
                CoreClusterMember leader;

                do
                {
                    leader = _cluster.coreTx(dbName, (db, tx) =>
                    {
                        Node node = Db.createNode(label("database"));
                        node.setProperty("name", dbName);
                        tx.success();
                    });
                    i++;
                } while (i < numNodes);

                int leaderId = leader.ServerId();
                IList <CoreClusterMember> notLeaders = _cluster.coreMembers().Where(m => m.dbName().Equals(dbName) && m.serverId() != leaderId).ToList();

                leaderMap[leader] = notLeaders;
                numNodes++;
            }

//JAVA TO C# CONVERTER TODO TASK: Most Java stream collectors are not converted by Java to C# Converter:
            ISet <long> nodesPerDb = leaderMap.Keys.Select(DataCreator.countNodes).collect(Collectors.toSet());

            assertEquals("Each logical database in the multicluster should have a unique number of nodes.", nodesPerDb.Count, _dbNames.Count);
            foreach (KeyValuePair <CoreClusterMember, IList <CoreClusterMember> > subCluster in leaderMap.SetOfKeyValuePairs())
            {
                dataMatchesEventually(subCluster.Key, subCluster.Value);
            }
        }
Exemple #20
0
        public virtual ActivityInstance execute(CommandContext commandContext)
        {
            ensureNotNull("processInstanceId", processInstanceId);
            IList <ExecutionEntity> executionList = loadProcessInstance(processInstanceId, commandContext);

            if (executionList.Count == 0)
            {
                return(null);
            }

            checkGetActivityInstance(processInstanceId, commandContext);

            IList <ExecutionEntity> nonEventScopeExecutions = filterNonEventScopeExecutions(executionList);
            IList <ExecutionEntity> leaves = filterLeaves(nonEventScopeExecutions);

            // Leaves must be ordered in a predictable way (e.g. by ID)
            // in order to return a stable execution tree with every repeated invocation of this command.
            // For legacy process instances, there may miss scope executions for activities that are now a scope.
            // In this situation, there may be multiple scope candidates for the same instance id; which one
            // can depend on the order the leaves are iterated.
            orderById(leaves);

            ExecutionEntity processInstance = filterProcessInstance(executionList);

            if (processInstance.Ended)
            {
                return(null);
            }

            // create act instance for process instance
            ActivityInstanceImpl processActInst = createActivityInstance(processInstance, processInstance.getProcessDefinition(), processInstanceId, null);
            IDictionary <string, ActivityInstanceImpl> activityInstances = new Dictionary <string, ActivityInstanceImpl>();

            activityInstances[processInstanceId] = processActInst;

            IDictionary <string, TransitionInstanceImpl> transitionInstances = new Dictionary <string, TransitionInstanceImpl>();

            foreach (ExecutionEntity leaf in leaves)
            {
                // skip leafs without activity, e.g. if only the process instance exists after cancellation
                // it will not have an activity set
                if (leaf.getActivity() == null)
                {
                    continue;
                }

                IDictionary <ScopeImpl, PvmExecutionImpl> activityExecutionMapping = leaf.createActivityExecutionMapping();
                IDictionary <ScopeImpl, PvmExecutionImpl> scopeInstancesToCreate   = new Dictionary <ScopeImpl, PvmExecutionImpl>(activityExecutionMapping);

                // create an activity/transition instance for each leaf that executes a non-scope activity
                // and does not throw compensation
                if (!string.ReferenceEquals(leaf.ActivityInstanceId, null))
                {
                    if (!CompensationBehavior.isCompensationThrowing(leaf) || LegacyBehavior.isCompensationThrowing(leaf, activityExecutionMapping))
                    {
                        string parentActivityInstanceId = null;

                        parentActivityInstanceId = activityExecutionMapping[leaf.getActivity().FlowScope].ParentActivityInstanceId;

                        ActivityInstanceImpl leafInstance = createActivityInstance(leaf, leaf.getActivity(), leaf.ActivityInstanceId, parentActivityInstanceId);
                        activityInstances[leafInstance.Id] = leafInstance;

                        scopeInstancesToCreate.Remove(leaf.getActivity());
                    }
                }
                else
                {
                    TransitionInstanceImpl transitionInstance = createTransitionInstance(leaf);
                    transitionInstances[transitionInstance.Id] = transitionInstance;

                    scopeInstancesToCreate.Remove(leaf.getActivity());
                }

                LegacyBehavior.removeLegacyNonScopesFromMapping(scopeInstancesToCreate);
                scopeInstancesToCreate.Remove(leaf.getProcessDefinition());

                // create an activity instance for each scope (including compensation throwing executions)
                foreach (KeyValuePair <ScopeImpl, PvmExecutionImpl> scopeExecutionEntry in scopeInstancesToCreate.SetOfKeyValuePairs())
                {
                    ScopeImpl        scope          = scopeExecutionEntry.Key;
                    PvmExecutionImpl scopeExecution = scopeExecutionEntry.Value;

                    string activityInstanceId       = null;
                    string parentActivityInstanceId = null;

                    activityInstanceId       = scopeExecution.ParentActivityInstanceId;
                    parentActivityInstanceId = activityExecutionMapping[scope.FlowScope].ParentActivityInstanceId;

                    if (activityInstances.ContainsKey(activityInstanceId))
                    {
                        continue;
                    }
                    else
                    {
                        // regardless of the tree structure (compacted or not), the scope's activity instance id
                        // is the activity instance id of the parent execution and the parent activity instance id
                        // of that is the actual parent activity instance id
                        ActivityInstanceImpl scopeInstance = createActivityInstance(scopeExecution, scope, activityInstanceId, parentActivityInstanceId);
                        activityInstances[activityInstanceId] = scopeInstance;
                    }
                }
            }

            LegacyBehavior.repairParentRelationships(activityInstances.Values, processInstanceId);
            populateChildInstances(activityInstances, transitionInstances);

            return(processActInst);
        }
Exemple #21
0
        private OSMTagMapping(URL tagConf)
        {
            try
            {
                sbyte defaultZoomAppear;

                // ---- Parse XML file ----
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder        builder = factory.newDocumentBuilder();
                Document document = builder.parse(tagConf.openStream());

                XPath xpath = XPathFactory.newInstance().newXPath();

                XPathExpression xe = xpath.compile(XPATH_EXPRESSION_DEFAULT_ZOOM);
                defaultZoomAppear = sbyte.Parse((string)xe.evaluate(document, XPathConstants.STRING));

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.HashMap<Nullable<short>, java.util.Set<String>> tmpPoiZoomOverrides = new java.util.HashMap<>();
                Dictionary <short?, ISet <string> > tmpPoiZoomOverrides = new Dictionary <short?, ISet <string> >();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.HashMap<Nullable<short>, java.util.Set<String>> tmpWayZoomOverrides = new java.util.HashMap<>();
                Dictionary <short?, ISet <string> > tmpWayZoomOverrides = new Dictionary <short?, ISet <string> >();

                // ---- Get list of poi nodes ----
                xe = xpath.compile(XPATH_EXPRESSION_POIS);
                NodeList pois = (NodeList)xe.evaluate(document, XPathConstants.NODESET);

                for (int i = 0; i < pois.Length; i++)
                {
                    NamedNodeMap attributes = pois.item(i).Attributes;
                    string       key        = attributes.getNamedItem("key").TextContent;
                    string       value      = attributes.getNamedItem("value").TextContent;

                    string[] equivalentValues = null;
                    if (attributes.getNamedItem("equivalent-values") != null)
                    {
                        equivalentValues = attributes.getNamedItem("equivalent-values").TextContent.Split(",");
                    }

                    sbyte zoom = attributes.getNamedItem("zoom-appear") == null ? defaultZoomAppear : sbyte.Parse(attributes.getNamedItem("zoom-appear").TextContent);

                    bool renderable = attributes.getNamedItem("renderable") == null ? true : bool.Parse(attributes.getNamedItem("renderable").TextContent);

                    bool forcePolygonLine = attributes.getNamedItem("force-polygon-line") == null ? false : bool.Parse(attributes.getNamedItem("force-polygon-line").TextContent);

                    OSMTag osmTag = new OSMTag(this.poiID, key, value, zoom, renderable, forcePolygonLine);
                    if (this.stringToPoiTag.ContainsKey(osmTag.tagKey()))
                    {
                        LOGGER.warning("duplicate osm-tag found in tag-mapping configuration (ignoring): " + osmTag);
                        continue;
                    }
                    LOGGER.finest("adding poi: " + osmTag);
                    this.stringToPoiTag[osmTag.tagKey()] = osmTag;
                    if (equivalentValues != null)
                    {
                        foreach (string equivalentValue in equivalentValues)
                        {
                            this.stringToPoiTag[OSMTag.tagKey(key, equivalentValue)] = osmTag;
                        }
                    }
                    this.idToPoiTag[Convert.ToInt16(this.poiID)] = osmTag;

                    // also fill optimization mapping with identity
                    this.optimizedPoiIds[Convert.ToInt16(this.poiID)] = Convert.ToInt16(this.poiID);

                    // check if this tag overrides the zoom level spec of another tag
                    NodeList zoomOverrideNodes = pois.item(i).ChildNodes;
                    for (int j = 0; j < zoomOverrideNodes.Length; j++)
                    {
                        Node overriddenNode = zoomOverrideNodes.item(j);
                        if (overriddenNode is Element)
                        {
                            string        keyOverridden   = overriddenNode.Attributes.getNamedItem("key").TextContent;
                            string        valueOverridden = overriddenNode.Attributes.getNamedItem("value").TextContent;
                            ISet <string> s = tmpPoiZoomOverrides[Convert.ToInt16(this.poiID)];
                            if (s == null)
                            {
                                s = new HashSet <>();
                                tmpPoiZoomOverrides[Convert.ToInt16(this.poiID)] = s;
                            }
                            s.Add(OSMTag.tagKey(keyOverridden, valueOverridden));
                        }
                    }

                    this.poiID++;
                }

                // ---- Get list of way nodes ----
                xe = xpath.compile(XPATH_EXPRESSION_WAYS);
                NodeList ways = (NodeList)xe.evaluate(document, XPathConstants.NODESET);

                for (int i = 0; i < ways.Length; i++)
                {
                    NamedNodeMap attributes = ways.item(i).Attributes;
                    string       key        = attributes.getNamedItem("key").TextContent;
                    string       value      = attributes.getNamedItem("value").TextContent;

                    string[] equivalentValues = null;
                    if (attributes.getNamedItem("equivalent-values") != null)
                    {
                        equivalentValues = attributes.getNamedItem("equivalent-values").TextContent.Split(",");
                    }

                    sbyte zoom = attributes.getNamedItem("zoom-appear") == null ? defaultZoomAppear : sbyte.Parse(attributes.getNamedItem("zoom-appear").TextContent);

                    bool renderable = attributes.getNamedItem("renderable") == null ? true : bool.Parse(attributes.getNamedItem("renderable").TextContent);

                    bool forcePolygonLine = attributes.getNamedItem("force-polygon-line") == null ? false : bool.Parse(attributes.getNamedItem("force-polygon-line").TextContent);

                    OSMTag osmTag = new OSMTag(this.wayID, key, value, zoom, renderable, forcePolygonLine);
                    if (this.stringToWayTag.ContainsKey(osmTag.tagKey()))
                    {
                        LOGGER.warning("duplicate osm-tag found in tag-mapping configuration (ignoring): " + osmTag);
                        continue;
                    }
                    LOGGER.finest("adding way: " + osmTag);
                    this.stringToWayTag[osmTag.tagKey()] = osmTag;
                    if (equivalentValues != null)
                    {
                        foreach (string equivalentValue in equivalentValues)
                        {
                            this.stringToWayTag[OSMTag.tagKey(key, equivalentValue)] = osmTag;
                        }
                    }
                    this.idToWayTag[Convert.ToInt16(this.wayID)] = osmTag;

                    // also fill optimization mapping with identity
                    this.optimizedWayIds[Convert.ToInt16(this.wayID)] = Convert.ToInt16(this.wayID);

                    // check if this tag overrides the zoom level spec of another tag
                    NodeList zoomOverrideNodes = ways.item(i).ChildNodes;
                    for (int j = 0; j < zoomOverrideNodes.Length; j++)
                    {
                        Node overriddenNode = zoomOverrideNodes.item(j);
                        if (overriddenNode is Element)
                        {
                            string        keyOverridden   = overriddenNode.Attributes.getNamedItem("key").TextContent;
                            string        valueOverridden = overriddenNode.Attributes.getNamedItem("value").TextContent;
                            ISet <string> s = tmpWayZoomOverrides[Convert.ToInt16(this.wayID)];
                            if (s == null)
                            {
                                s = new HashSet <>();
                                tmpWayZoomOverrides[Convert.ToInt16(this.wayID)] = s;
                            }
                            s.Add(OSMTag.tagKey(keyOverridden, valueOverridden));
                        }
                    }

                    this.wayID++;
                }

                // copy temporary values from zoom-override data sets
                foreach (KeyValuePair <short?, ISet <string> > entry in tmpPoiZoomOverrides.SetOfKeyValuePairs())
                {
                    ISet <OSMTag> overriddenTags = new HashSet <OSMTag>();
                    foreach (string tagString in entry.Value)
                    {
                        OSMTag tag = this.stringToPoiTag[tagString];
                        if (tag != null)
                        {
                            overriddenTags.Add(tag);
                        }
                    }
                    if (overriddenTags.Count > 0)
                    {
                        this.poiZoomOverrides[entry.Key] = overriddenTags;
                    }
                }

                foreach (KeyValuePair <short?, ISet <string> > entry in tmpWayZoomOverrides.SetOfKeyValuePairs())
                {
                    ISet <OSMTag> overriddenTags = new HashSet <OSMTag>();
                    foreach (string tagString in entry.Value)
                    {
                        OSMTag tag = this.stringToWayTag[tagString];
                        if (tag != null)
                        {
                            overriddenTags.Add(tag);
                        }
                    }
                    if (overriddenTags.Count > 0)
                    {
                        this.wayZoomOverrides[entry.Key] = overriddenTags;
                    }
                }

                // ---- Error handling ----
            }
            catch (SAXParseException spe)
            {
                LOGGER.severe("\n** Parsing error, line " + spe.LineNumber + ", uri " + spe.SystemId);
                throw new System.InvalidOperationException(spe);
            }
            catch (SAXException sxe)
            {
                throw new System.InvalidOperationException(sxe);
            }
            catch (ParserConfigurationException pce)
            {
                throw new System.InvalidOperationException(pce);
            }
            catch (IOException ioe)
            {
                throw new System.InvalidOperationException(ioe);
            }
            catch (XPathExpressionException e)
            {
                throw new System.InvalidOperationException(e);
            }
        }
 //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
 //ORIGINAL LINE: public void testRandomRealisticKeyword() throws java.io.IOException
 public virtual void testRandomRealisticKeyword()
 {
     IDictionary<string, string> map = new Dictionary<string, string>();
     int numTerms = atLeast(50);
     for (int i = 0; i < numTerms; i++)
     {
       string randomRealisticUnicodeString = TestUtil.randomRealisticUnicodeString(random());
       if (randomRealisticUnicodeString.Length > 0)
       {
     string value = TestUtil.randomSimpleString(random());
     map[randomRealisticUnicodeString] = value.Length == 0 ? "a" : value;
       }
     }
     if (map.Count == 0)
     {
       map["booked"] = "books";
     }
     StemmerOverrideFilter.Builder builder = new StemmerOverrideFilter.Builder(random().nextBoolean());
     ISet<KeyValuePair<string, string>> entrySet = map.SetOfKeyValuePairs();
     foreach (KeyValuePair<string, string> entry in entrySet)
     {
       builder.add(entry.Key, entry.Value);
     }
     StemmerOverrideMap build = builder.build();
     foreach (KeyValuePair<string, string> entry in entrySet)
     {
       if (random().nextBoolean())
       {
     Tokenizer tokenizer = new KeywordTokenizer(new StringReader(entry.Key));
     TokenStream stream = new PorterStemFilter(new StemmerOverrideFilter(tokenizer, build));
     assertTokenStreamContents(stream, new string[] {entry.Value});
       }
     }
 }
Exemple #23
0
        //-------------------------------------------------------------------------
        /// <summary>
        /// Parses one or more CSV format quote files.
        /// <para>
        /// A predicate is specified that is used to filter the dates that are returned.
        /// This could match a single date, a set of dates or all dates.
        /// </para>
        /// <para>
        /// If the files contain a duplicate entry an exception will be thrown.
        ///
        /// </para>
        /// </summary>
        /// <param name="datePredicate">  the predicate used to select the dates </param>
        /// <param name="charSources">  the CSV character sources </param>
        /// <returns> the loaded quotes, mapped by <seealso cref="LocalDate"/> and <seealso cref="QuoteId quote ID"/> </returns>
        /// <exception cref="IllegalArgumentException"> if the files contain a duplicate entry </exception>
        public static ImmutableMap <LocalDate, ImmutableMap <QuoteId, double> > parse(System.Predicate <LocalDate> datePredicate, ICollection <CharSource> charSources)
        {
            // builder ensures keys can only be seen once
            IDictionary <LocalDate, ImmutableMap.Builder <QuoteId, double> > mutableMap = new Dictionary <LocalDate, ImmutableMap.Builder <QuoteId, double> >();

            foreach (CharSource charSource in charSources)
            {
                parseSingle(datePredicate, charSource, mutableMap);
            }
            ImmutableMap.Builder <LocalDate, ImmutableMap <QuoteId, double> > builder = ImmutableMap.builder();
            foreach (KeyValuePair <LocalDate, ImmutableMap.Builder <QuoteId, double> > entry in mutableMap.SetOfKeyValuePairs())
            {
                builder.put(entry.Key, entry.Value.build());
            }
            return(builder.build());
        }
Exemple #24
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void index_objects_can_be_reused_after_role_switch() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void IndexObjectsCanBeReusedAfterRoleSwitch()
        {
            // GIVEN
            // -- an existing index
            string key   = "key";
            string value = "value";
            HighlyAvailableGraphDatabase master = Cluster.Master;
            long nodeId = CreateNode(master, key, value, true);

            Cluster.sync();
            // -- get Index and IndexManager references to all dbs
            IDictionary <HighlyAvailableGraphDatabase, IndexManager>  indexManagers = new Dictionary <HighlyAvailableGraphDatabase, IndexManager>();
            IDictionary <HighlyAvailableGraphDatabase, Index <Node> > indexes       = new Dictionary <HighlyAvailableGraphDatabase, Index <Node> >();

            foreach (HighlyAvailableGraphDatabase db in Cluster.AllMembers)
            {
                using (Transaction transaction = Db.beginTx())
                {
                    indexManagers[db] = Db.index();
                    indexes[db]       = Db.index().forNodes(key);
                    transaction.Success();
                }
            }

            // WHEN
            // -- there's a master switch
            ClusterManager.RepairKit repair = Cluster.shutdown(master);
            indexManagers.Remove(master);
            indexes.Remove(master);

            Cluster.await(ClusterManager.masterAvailable(master));
            Cluster.await(ClusterManager.masterSeesSlavesAsAvailable(1));

            // THEN
            // -- the index instances should still be viable to use
            foreach (KeyValuePair <HighlyAvailableGraphDatabase, IndexManager> entry in indexManagers.SetOfKeyValuePairs())
            {
                HighlyAvailableGraphDatabase db = entry.Key;
                using (Transaction transaction = Db.beginTx())
                {
                    IndexManager indexManager = entry.Value;
                    assertTrue(indexManager.ExistsForNodes(key));
                    assertEquals(nodeId, indexManager.ForNodes(key).get(key, value).Single.Id);
                }
            }

            foreach (KeyValuePair <HighlyAvailableGraphDatabase, Index <Node> > entry in indexes.SetOfKeyValuePairs())
            {
                HighlyAvailableGraphDatabase db = entry.Key;
                using (Transaction transaction = Db.beginTx())
                {
                    Index <Node> index = entry.Value;
                    assertEquals(nodeId, index.get(key, value).Single.Id);
                }
            }
            repair.Repair();
        }
        //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
        //ORIGINAL LINE: public void testRandomRealisticWhiteSpace() throws java.io.IOException
        public virtual void testRandomRealisticWhiteSpace()
        {
            IDictionary<string, string> map = new Dictionary<string, string>();
            int numTerms = atLeast(50);
            for (int i = 0; i < numTerms; i++)
            {
              string randomRealisticUnicodeString = TestUtil.randomRealisticUnicodeString(random());
              char[] charArray = randomRealisticUnicodeString.ToCharArray();
              StringBuilder builder = new StringBuilder();
              for (int j = 0; j < charArray.Length;)
              {
            int cp = char.codePointAt(charArray, j, charArray.Length);
            if (!char.IsWhiteSpace(cp))
            {
              builder.appendCodePoint(cp);
            }
            j += char.charCount(cp);
              }
              if (builder.Length > 0)
              {
            string value = TestUtil.randomSimpleString(random());
            map[builder.ToString()] = value.Length == 0 ? "a" : value;

              }
            }
            if (map.Count == 0)
            {
              map["booked"] = "books";
            }
            StemmerOverrideFilter.Builder builder = new StemmerOverrideFilter.Builder(random().nextBoolean());
            ISet<KeyValuePair<string, string>> entrySet = map.SetOfKeyValuePairs();
            StringBuilder input = new StringBuilder();
            IList<string> output = new List<string>();
            foreach (KeyValuePair<string, string> entry in entrySet)
            {
              builder.add(entry.Key, entry.Value);
              if (random().nextBoolean() || output.Count == 0)
              {
            input.Append(entry.Key).Append(" ");
            output.Add(entry.Value);
              }
            }
            Tokenizer tokenizer = new WhitespaceTokenizer(TEST_VERSION_CURRENT, new StringReader(input.ToString()));
            TokenStream stream = new PorterStemFilter(new StemmerOverrideFilter(tokenizer, builder.build()));
            assertTokenStreamContents(stream, output.ToArray());
        }
Exemple #26
0
        public override void performOperationStep(DeploymentOperation operationContext)
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.camunda.bpm.container.impl.spi.PlatformServiceContainer serviceContainer = operationContext.getServiceContainer();
            PlatformServiceContainer serviceContainer = operationContext.ServiceContainer;
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.camunda.bpm.application.AbstractProcessApplication processApplication = operationContext.getAttachment(Attachments.PROCESS_APPLICATION);
            AbstractProcessApplication processApplication = operationContext.getAttachment(Attachments.PROCESS_APPLICATION);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final ClassLoader processApplicationClassloader = processApplication.getProcessApplicationClassloader();
            ClassLoader processApplicationClassloader = processApplication.ProcessApplicationClassloader;

            ProcessEngine processEngine = getProcessEngine(serviceContainer, processApplication.DefaultDeployToEngineName);

            // start building deployment map
            IDictionary <string, sbyte[]> deploymentMap = new Dictionary <string, sbyte[]>();

            // add all processes listed in the processes.xml
            IList <string> listedProcessResources = processArchive.ProcessResourceNames;

            foreach (string processResource in listedProcessResources)
            {
                Stream resourceAsStream = null;
                try
                {
                    resourceAsStream = processApplicationClassloader.getResourceAsStream(processResource);
                    sbyte[] bytes = IoUtil.readInputStream(resourceAsStream, processResource);
                    deploymentMap[processResource] = bytes;
                }
                finally
                {
                    IoUtil.closeSilently(resourceAsStream);
                }
            }

            // scan for additional process definitions if not turned off
            if (PropertyHelper.getBooleanProperty(processArchive.Properties, org.camunda.bpm.application.impl.metadata.spi.ProcessArchiveXml_Fields.PROP_IS_SCAN_FOR_PROCESS_DEFINITIONS, true))
            {
                string   paResourceRoot             = processArchive.Properties[org.camunda.bpm.application.impl.metadata.spi.ProcessArchiveXml_Fields.PROP_RESOURCE_ROOT_PATH];
                string[] additionalResourceSuffixes = StringUtil.Split(processArchive.Properties[org.camunda.bpm.application.impl.metadata.spi.ProcessArchiveXml_Fields.PROP_ADDITIONAL_RESOURCE_SUFFIXES], org.camunda.bpm.application.impl.metadata.spi.ProcessArchiveXml_Fields.PROP_ADDITIONAL_RESOURCE_SUFFIXES_SEPARATOR);
//JAVA TO C# CONVERTER TODO TASK: There is no .NET Dictionary equivalent to the Java 'putAll' method:
                deploymentMap.putAll(findResources(processApplicationClassloader, paResourceRoot, additionalResourceSuffixes));
            }

            // perform process engine deployment
            RepositoryService repositoryService = processEngine.RepositoryService;
            ProcessApplicationDeploymentBuilder deploymentBuilder = repositoryService.createDeployment(processApplication.Reference);

            // set the name for the deployment
            string deploymentName = processArchive.Name;

            if (string.ReferenceEquals(deploymentName, null) || deploymentName.Length == 0)
            {
                deploymentName = processApplication.Name;
            }
            deploymentBuilder.name(deploymentName);

            // set the tenant id for the deployment
            string tenantId = processArchive.TenantId;

            if (!string.ReferenceEquals(tenantId, null) && tenantId.Length > 0)
            {
                deploymentBuilder.tenantId(tenantId);
            }

            // enable duplicate filtering
            deploymentBuilder.enableDuplicateFiltering(PropertyHelper.getBooleanProperty(processArchive.Properties, org.camunda.bpm.application.impl.metadata.spi.ProcessArchiveXml_Fields.PROP_IS_DEPLOY_CHANGED_ONLY, false));

            if (PropertyHelper.getBooleanProperty(processArchive.Properties, org.camunda.bpm.application.impl.metadata.spi.ProcessArchiveXml_Fields.PROP_IS_RESUME_PREVIOUS_VERSIONS, true))
            {
                enableResumingOfPreviousVersions(deploymentBuilder);
            }

            // add all resources obtained through the processes.xml and through scanning
            foreach (KeyValuePair <string, sbyte[]> deploymentResource in deploymentMap.SetOfKeyValuePairs())
            {
                deploymentBuilder.addInputStream(deploymentResource.Key, new MemoryStream(deploymentResource.Value));
            }

            // allow the process application to add additional resources to the deployment
            processApplication.createDeployment(processArchive.Name, deploymentBuilder);

            ICollection <string> deploymentResourceNames = deploymentBuilder.ResourceNames;

            if (deploymentResourceNames.Count > 0)
            {
                LOG.deploymentSummary(deploymentResourceNames, deploymentName);

                // perform the process engine deployment
                deployment = deploymentBuilder.deploy();

                // add attachment
                IDictionary <string, DeployedProcessArchive> processArchiveDeploymentMap = operationContext.getAttachment(Attachments.PROCESS_ARCHIVE_DEPLOYMENT_MAP);
                if (processArchiveDeploymentMap == null)
                {
                    processArchiveDeploymentMap = new Dictionary <string, DeployedProcessArchive>();
                    operationContext.addAttachment(Attachments.PROCESS_ARCHIVE_DEPLOYMENT_MAP, processArchiveDeploymentMap);
                }
                processArchiveDeploymentMap[processArchive.Name] = new DeployedProcessArchive(deployment);
            }
            else
            {
                LOG.notCreatingPaDeployment(processApplication.Name);
            }
        }
Exemple #27
0
 public virtual ISet <KeyValuePair <DataSetName, SetStats> > listSets()
 {
     return(stats.SetOfKeyValuePairs());
 }
Exemple #28
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void add(java.util.Collection<? extends org.neo4j.kernel.api.index.IndexEntryUpdate<?>> updates) throws org.neo4j.kernel.api.exceptions.index.IndexEntryConflictException
        public override void Add <T1>(ICollection <T1> updates) where T1 : Org.Neo4j.Kernel.Api.Index.IndexEntryUpdate <T1>
        {
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.Map<org.neo4j.values.storable.ValueGroup,java.util.List<org.neo4j.kernel.api.index.IndexEntryUpdate<?>>> batchMap = new java.util.HashMap<>();
            IDictionary <ValueGroup, IList <IndexEntryUpdate <object> > > batchMap = new Dictionary <ValueGroup, IList <IndexEntryUpdate <object> > >();

//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: for (org.neo4j.kernel.api.index.IndexEntryUpdate<?> update : updates)
            foreach (IndexEntryUpdate <object> update in updates)
            {
                ValueGroup valueGroup = update.Values()[0].valueGroup();
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.List<org.neo4j.kernel.api.index.IndexEntryUpdate<?>> batch = batchMap.computeIfAbsent(valueGroup, k -> new java.util.ArrayList<>());
                IList <IndexEntryUpdate <object> > batch = batchMap.computeIfAbsent(valueGroup, k => new List <IndexEntryUpdate <object> >());
                batch.Add(update);
            }
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: for (java.util.Map.Entry<org.neo4j.values.storable.ValueGroup,java.util.List<org.neo4j.kernel.api.index.IndexEntryUpdate<?>>> entry : batchMap.entrySet())
            foreach (KeyValuePair <ValueGroup, IList <IndexEntryUpdate <object> > > entry in batchMap.SetOfKeyValuePairs())
            {
                Select(entry.Key).add(entry.Value);
            }
        }
Exemple #29
0
        private void onInputControllerChanged()
        {
            buttonComponents = new Dictionary <Component.Identifier, int>();
            foreach (KeyValuePair <keyCode, string> entry in controllerComponents.SetOfKeyValuePairs())
            {
                keyCode   key            = entry.Key;
                string    controllerName = entry.Value;
                Component component      = getControllerComponentByName(controllerName);
                if (component != null)
                {
                    Component.Identifier identifier = component.Identifier;
                    bool isAxis = identifier is Component.Identifier.Axis;

                    if (isAxis && identifier == Component.Identifier.Axis.POV)
                    {
                        povArrows = identifier;
                    }
                    else
                    {
                        int keyCode = -1;
                        switch (key)
                        {
                        //
                        // PSP directional buttons can be mapped
                        // to a controller Axis or to a controller Button
                        //
                        case pspsharp.Controller.keyCode.DOWN:
                            if (isAxis)
                            {
                                digitalYAxis = identifier;
                            }
                            else
                            {
                                keyCode = PSP_CTRL_DOWN;
                            }
                            break;

                        case pspsharp.Controller.keyCode.UP:
                            if (isAxis)
                            {
                                digitalYAxis = identifier;
                            }
                            else
                            {
                                keyCode = PSP_CTRL_UP;
                            }
                            break;

                        case pspsharp.Controller.keyCode.LEFT:
                            if (isAxis)
                            {
                                digitalXAxis = identifier;
                            }
                            else
                            {
                                keyCode = PSP_CTRL_LEFT;
                            }
                            break;

                        case pspsharp.Controller.keyCode.RIGHT:
                            if (isAxis)
                            {
                                digitalXAxis = identifier;
                            }
                            else
                            {
                                keyCode = PSP_CTRL_RIGHT;
                            }
                            break;

                        //
                        // PSP analog controller can only be mapped to a controller Axis
                        //
                        case pspsharp.Controller.keyCode.LANDOWN:
                        case pspsharp.Controller.keyCode.LANUP:
                            if (isAxis)
                            {
                                analogLYAxis = identifier;
                            }
                            break;

                        case pspsharp.Controller.keyCode.LANLEFT:
                        case pspsharp.Controller.keyCode.LANRIGHT:
                            if (isAxis)
                            {
                                analogLXAxis = identifier;
                            }
                            break;

                        case pspsharp.Controller.keyCode.RANDOWN:
                        case pspsharp.Controller.keyCode.RANUP:
                            if (isAxis)
                            {
                                analogRYAxis = identifier;
                            }
                            break;

                        case pspsharp.Controller.keyCode.RANLEFT:
                        case pspsharp.Controller.keyCode.RANRIGHT:
                            if (isAxis)
                            {
                                analogRXAxis = identifier;
                            }
                            break;

                        //
                        // PSP buttons can be mapped either to a controller Button
                        // or to a controller Axis (e.g. a foot pedal)
                        //
                        case pspsharp.Controller.keyCode.TRIANGLE:
                            keyCode = PSP_CTRL_TRIANGLE;
                            break;

                        case pspsharp.Controller.keyCode.SQUARE:
                            keyCode = PSP_CTRL_SQUARE;
                            break;

                        case pspsharp.Controller.keyCode.CIRCLE:
                            keyCode = PSP_CTRL_CIRCLE;
                            break;

                        case pspsharp.Controller.keyCode.CROSS:
                            keyCode = PSP_CTRL_CROSS;
                            break;

                        case pspsharp.Controller.keyCode.L1:
                            keyCode = PSP_CTRL_LTRIGGER;
                            break;

                        case pspsharp.Controller.keyCode.R1:
                            keyCode = PSP_CTRL_RTRIGGER;
                            break;

                        case pspsharp.Controller.keyCode.START:
                            keyCode = PSP_CTRL_START;
                            break;

                        case pspsharp.Controller.keyCode.SELECT:
                            keyCode = PSP_CTRL_SELECT;
                            break;

                        case pspsharp.Controller.keyCode.HOME:
                            keyCode = PSP_CTRL_HOME;
                            break;

                        case pspsharp.Controller.keyCode.HOLD:
                            keyCode = PSP_CTRL_HOLD;
                            break;

                        case pspsharp.Controller.keyCode.VOLMIN:
                            keyCode = PSP_CTRL_VOLDOWN;
                            break;

                        case pspsharp.Controller.keyCode.VOLPLUS:
                            keyCode = PSP_CTRL_VOLUP;
                            break;

                        case pspsharp.Controller.keyCode.SCREEN:
                            keyCode = PSP_CTRL_SCREEN;
                            break;

                        case pspsharp.Controller.keyCode.MUSIC:
                            keyCode = PSP_CTRL_NOTE;
                            break;

                        case pspsharp.Controller.keyCode.RELEASED:
                            break;
                        }
                        if (keyCode != -1)
                        {
                            buttonComponents[component.Identifier] = keyCode;
                        }
                    }
                }
            }
        }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void add(java.util.Collection<? extends org.neo4j.kernel.api.index.IndexEntryUpdate<?>> updates) throws org.neo4j.kernel.api.exceptions.index.IndexEntryConflictException
        public override void Add <T1>(ICollection <T1> updates) where T1 : Org.Neo4j.Kernel.Api.Index.IndexEntryUpdate <T1>
        {
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.Map<org.neo4j.values.storable.CoordinateReferenceSystem,java.util.List<org.neo4j.kernel.api.index.IndexEntryUpdate<?>>> batchMap = new java.util.HashMap<>();
            IDictionary <CoordinateReferenceSystem, IList <IndexEntryUpdate <object> > > batchMap = new Dictionary <CoordinateReferenceSystem, IList <IndexEntryUpdate <object> > >();

//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: for (org.neo4j.kernel.api.index.IndexEntryUpdate<?> update : updates)
            foreach (IndexEntryUpdate <object> update in updates)
            {
                PointValue point = ( PointValue )update.Values()[0];
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.List<org.neo4j.kernel.api.index.IndexEntryUpdate<?>> batch = batchMap.computeIfAbsent(point.getCoordinateReferenceSystem(), k -> new java.util.ArrayList<>());
                IList <IndexEntryUpdate <object> > batch = batchMap.computeIfAbsent(point.CoordinateReferenceSystem, k => new List <IndexEntryUpdate <object> >());
                batch.Add(update);
            }
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: for (java.util.Map.Entry<org.neo4j.values.storable.CoordinateReferenceSystem,java.util.List<org.neo4j.kernel.api.index.IndexEntryUpdate<?>>> entry : batchMap.entrySet())
            foreach (KeyValuePair <CoordinateReferenceSystem, IList <IndexEntryUpdate <object> > > entry in batchMap.SetOfKeyValuePairs())
            {
                IndexPopulator partPopulator = Select(entry.Key);
                partPopulator.Add(entry.Value);
            }
        }