protected internal UnsavedRevision(Document document, SavedRevision parentRevision
     ) : base(document)
 {
     if (parentRevision == null)
     {
         parentRevID = null;
     }
     else
     {
         parentRevID = parentRevision.GetId();
     }
     IDictionary<string, object> parentRevisionProperties;
     if (parentRevision == null)
     {
         parentRevisionProperties = null;
     }
     else
     {
         parentRevisionProperties = parentRevision.GetProperties();
     }
     if (parentRevisionProperties == null)
     {
         properties = new Dictionary<string, object>();
         properties.Put("_id", document.GetId());
         if (parentRevID != null)
         {
             properties.Put("_rev", parentRevID);
         }
     }
     else
     {
         properties = new Dictionary<string, object>(parentRevisionProperties);
     }
 }
Exemplo n.º 2
0
		internal Attachment(InputStream contentStream, string contentType)
		{
			this.body = contentStream;
			metadata = new Dictionary<string, object>();
			metadata.Put("content_type", contentType);
			metadata.Put("follows", true);
			this.gzipped = false;
		}
Exemplo n.º 3
0
		protected virtual void SetUp()
		{
			// set up a reference map
			reference = new LinkedHashMap<object, object>();
			reference.Put("a", "a");
			reference.Put("b", true);
			reference.Put("c", new Dictionary<object, object>());
			reference.Put(1, 42);
			// get a js object as map
			Context context = Context.Enter();
			ScriptableObject scope = context.InitStandardObjects();
			map = (IDictionary<object, object>)context.EvaluateString(scope, "({ a: 'a', b: true, c: new java.util.HashMap(), 1: 42});", "testsrc", 1, null);
			Context.Exit();
		}
        /// <summary>
        /// Initializes a new instance of <see cref="T:DynamicTimeRangeFacetHandler"/>.
        /// The format of range string is dddhhmmss. (ddd: days (000-999), hh : hours (00-23), mm: minutes (00-59), ss: seconds (00-59))
        /// </summary>
        /// <param name="name">The facet handler name.</param>
        /// <param name="dataFacetName">The facet handler this one depends on.</param>
        /// <param name="currentTime">The number of milliseconds since January 1, 1970 expessed in universal coordinated time (UTC). 
        /// The <see cref="M:BoboBrowse.Net.Support.DateTimeExtensions.GetTime"/> method can be used to convert the current time to 
        /// this format, e.g. DateTime.Now.GetTime().</param>
        /// <param name="ranges">A list of range strings in the format dddhhmmss. (ddd: days (000-999), hh : hours (00-23), mm: minutes (00-59), ss: seconds (00-59))</param>
        public DynamicTimeRangeFacetHandler(string name, string dataFacetName, long currentTime, IEnumerable<string> ranges)
            : base(name, dataFacetName)
        {
            if (log.IsDebugEnabled)
            {
                log.Debug(name + " " + dataFacetName + " " + currentTime);
            }
            List<string> sortedRanges = new List<string>(ranges);
            sortedRanges.Sort();

            _valueToRangeStringMap = new Dictionary<string, string>();
            _rangeStringToValueMap = new Dictionary<string, string>();
            _rangeStringList = new List<string>(ranges.Count());

            string prev = "000000000";
            foreach (string range in sortedRanges)
            {
                string rangeString = BuildRangeString(currentTime, prev, range);
                _valueToRangeStringMap.Put(range, rangeString);
                _rangeStringToValueMap.Put(rangeString, range);
                _rangeStringList.Add(rangeString);
                prev = range;

                if (log.IsDebugEnabled)
                {
                    log.Debug(range + "\t " + rangeString);
                }
            }
        }
 public MappedFacetAccessible(BrowseFacet[] facets)
 {
     _facetMap = new Dictionary<object, BrowseFacet>();
     foreach (BrowseFacet facet in facets)
     {
         _facetMap.Put(facet.Value, facet);
     }
     _facets = facets;
 }
Exemplo n.º 6
0
        /// <summary>
        ///     Add new event.
        /// </summary>
        /// <param name="newEvent">to add</param>
        public void NewEventPrepare(EventBean newEvent)
        {
            // Add new event
            newEvents.Add(newEvent);

            // Save prior index events in array
            var priorEvents = new EventBean[getter.IndexesRequestedLen];
            for (var j = 0; j < priorEvents.Length; j++) {
                int priorIndex = getter.IndexesRequested[j];
                priorEvents[j] = newEvents.Get(priorIndex);
            }

            priorEventMap?.Put(newEvent, priorEvents);

            lastNew = priorEvents;
            getter.RandomAccess = this;
        }
Exemplo n.º 7
0
 static RawParseUtils()
 {
     encodingAliases = new Dictionary<string, System.Text.Encoding>();
     encodingAliases.Put("latin-1", Sharpen.Extensions.GetEncoding("ISO-8859-1"));
     digits10 = new byte[(byte)('9') + 1];
     Arrays.Fill(digits10, unchecked((byte)-1));
     for (char i = '0'; i <= '9'; i++)
     {
         digits10[i] = unchecked((byte)(i - (byte)('0')));
     }
     digits16 = new sbyte[(byte)('f') + 1];
     Arrays.Fill(digits16, (sbyte)-1);
     for (char i_1 = '0'; i_1 <= '9'; i_1++)
     {
         digits16[i_1] = (sbyte)(i_1 - (sbyte)('0'));
     }
     for (char i_2 = 'a'; i_2 <= 'f'; i_2++)
     {
         digits16[i_2] = (sbyte)((i_2 - (sbyte)('a')) + 10);
     }
     for (char i_3 = 'A'; i_3 <= 'F'; i_3++)
     {
         digits16[i_3] = (sbyte)((i_3 - (sbyte)('A')) + 10);
     }
     footerLineKeyChars = new byte[(byte)('z') + 1];
     footerLineKeyChars[(byte)('-')] = 1;
     for (char i_4 = '0'; i_4 <= '9'; i_4++)
     {
         footerLineKeyChars[i_4] = 1;
     }
     for (char i_5 = 'A'; i_5 <= 'Z'; i_5++)
     {
         footerLineKeyChars[i_5] = 1;
     }
     for (char i_6 = 'a'; i_6 <= 'z'; i_6++)
     {
         footerLineKeyChars[i_6] = 1;
     }
 }
Exemplo n.º 8
0
        /// <summary>Add verification for a particular signature.</summary>
        /// <param name="signatureName">the signature to validate (it may be a timestamp)</param>
        /// <param name="ocsp">the interface to get the OCSP</param>
        /// <param name="crl">the interface to get the CRL</param>
        /// <param name="certOption">options as to how many certificates to include</param>
        /// <param name="level">the validation options to include</param>
        /// <param name="certInclude">certificate inclusion options</param>
        /// <returns>true if a validation was generated, false otherwise</returns>
        public virtual bool AddVerification(String signatureName, IOcspClient ocsp, ICrlClient crl, LtvVerification.CertificateOption
                                            certOption, LtvVerification.Level level, LtvVerification.CertificateInclusion certInclude)
        {
            if (used)
            {
                throw new InvalidOperationException(PdfException.VerificationAlreadyOutput);
            }
            PdfPKCS7 pk = sgnUtil.ReadSignatureData(signatureName);

            LOGGER.Info("Adding verification for " + signatureName);
            X509Certificate[] xc = pk.GetCertificates();
            X509Certificate   cert;
            X509Certificate   signingCert = pk.GetSigningCertificate();

            LtvVerification.ValidationData vd = new LtvVerification.ValidationData();
            for (int k = 0; k < xc.Length; ++k)
            {
                cert = (X509Certificate)xc[k];
                LOGGER.Info("Certificate: " + cert.SubjectDN);
                if (certOption == LtvVerification.CertificateOption.SIGNING_CERTIFICATE && !cert.Equals(signingCert))
                {
                    continue;
                }
                byte[] ocspEnc = null;
                if (ocsp != null && level != LtvVerification.Level.CRL)
                {
                    ocspEnc = ocsp.GetEncoded(cert, GetParent(cert, xc), null);
                    if (ocspEnc != null)
                    {
                        vd.ocsps.Add(BuildOCSPResponse(ocspEnc));
                        LOGGER.Info("OCSP added");
                    }
                }
                if (crl != null && (level == LtvVerification.Level.CRL || level == LtvVerification.Level.OCSP_CRL || (level
                                                                                                                      == LtvVerification.Level.OCSP_OPTIONAL_CRL && ocspEnc == null)))
                {
                    ICollection <byte[]> cims = crl.GetEncoded(cert, null);
                    if (cims != null)
                    {
                        foreach (byte[] cim in cims)
                        {
                            bool dup = false;
                            foreach (byte[] b in vd.crls)
                            {
                                if (JavaUtil.ArraysEquals(b, cim))
                                {
                                    dup = true;
                                    break;
                                }
                            }
                            if (!dup)
                            {
                                vd.crls.Add(cim);
                                LOGGER.Info("CRL added");
                            }
                        }
                    }
                }
                if (certInclude == LtvVerification.CertificateInclusion.YES)
                {
                    vd.certs.Add(cert.GetEncoded());
                }
            }
            if (vd.crls.Count == 0 && vd.ocsps.Count == 0)
            {
                return(false);
            }
            validated.Put(GetSignatureHashKey(signatureName), vd);
            return(true);
        }
Exemplo n.º 9
0
 /// <summary>
 /// Sets a specific selection property with the given key and value.
 /// </summary>
 /// <param name="key">A key for the property.</param>
 /// <param name="val">The value for the property.</param>
 public virtual void SetSelectionProperty(string key, string val)
 {
     SelectionProperties.Put(key, val);
 }
Exemplo n.º 10
0
 protected override void Put(IDictionary <int, string> collection, string value)
 {
     collection.Put(Interlocked.Increment(ref _lastKey), value);
 }
Exemplo n.º 11
0
 internal virtual Object SaveAssociatedObjectForWaitingTag(Object associatedObj, PdfStructElem structElem)
 {
     associatedObjToWaitingTag.Put(associatedObj, structElem);
     return(waitingTagToAssociatedObj.Put(structElem.GetPdfObject(), associatedObj));
 }
 public virtual IDictionary<string, object> ChangesFeedPOSTBodyMap()
 {
     if (!usePOST)
     {
         return null;
     }
     if (docIDs != null && docIDs.Count > 0)
     {
         filterName = "_doc_ids";
         filterParams = new Dictionary<string, object>();
         filterParams.Put("doc_ids", docIDs);
     }
     IDictionary<string, object> post = new Dictionary<string, object>();
     post.Put("feed", GetFeed());
     post.Put("heartbeat", GetHeartbeatMilliseconds());
     if (includeConflicts)
     {
         post.Put("style", "all_docs");
     }
     else
     {
         post.Put("style", null);
     }
     if (lastSequenceID != null)
     {
         try
         {
             post.Put("since", long.Parse(lastSequenceID.ToString()));
         }
         catch (FormatException)
         {
             post.Put("since", lastSequenceID.ToString());
         }
     }
     if (mode == ChangeTracker.ChangeTrackerMode.LongPoll && limit > 0)
     {
         post.Put("limit", limit);
     }
     else
     {
         post.Put("limit", null);
     }
     if (filterName != null)
     {
         post.Put("filter", filterName);
         post.PutAll(filterParams);
     }
     return post;
 }
Exemplo n.º 13
0
		internal SavedRevision PutProperties(IDictionary<string, object> properties, string
			 prevID, bool allowConflict)
		{
			string newId = null;
			if (properties != null && properties.ContainsKey("_id"))
			{
				newId = (string)properties.Get("_id");
			}
			if (newId != null && !Sharpen.Runtime.EqualsIgnoreCase(newId, GetId()))
			{
				Log.W(Database.Tag, string.Format("Trying to put wrong _id to this: %s properties: %s"
					, this, properties));
			}
			// Process _attachments dict, converting CBLAttachments to dicts:
			IDictionary<string, object> attachments = null;
			if (properties != null && properties.ContainsKey("_attachments"))
			{
				attachments = (IDictionary<string, object>)properties.Get("_attachments");
			}
			if (attachments != null && attachments.Count > 0)
			{
				IDictionary<string, object> updatedAttachments = Attachment.InstallAttachmentBodies
					(attachments, database);
				properties.Put("_attachments", updatedAttachments);
			}
			bool hasTrueDeletedProperty = false;
			if (properties != null)
			{
				hasTrueDeletedProperty = properties.Get("_deleted") != null && ((bool)properties.
					Get("_deleted"));
			}
			bool deleted = (properties == null) || hasTrueDeletedProperty;
			RevisionInternal rev = new RevisionInternal(documentId, null, deleted, database);
			if (properties != null)
			{
				rev.SetProperties(properties);
			}
			RevisionInternal newRev = database.PutRevision(rev, prevID, allowConflict);
			if (newRev == null)
			{
				return null;
			}
			return new SavedRevision(this, newRev);
		}
Exemplo n.º 14
0
 // Don't let failures (like a bad dc:rights form) stop other
 // cleanup.
 /// <summary>
 /// Initializes the map that contains the known arrays, that are fixed by
 /// <see cref="NormalizeDCArrays(XMPNode)"/>
 /// .
 /// </summary>
 private static void InitDCArrays()
 {
     dcArrayForms = new Hashtable();
     // Properties supposed to be a "Bag".
     PropertyOptions bagForm = new PropertyOptions();
     bagForm.SetArray(true);
     dcArrayForms.Put("dc:contributor", bagForm);
     dcArrayForms.Put("dc:language", bagForm);
     dcArrayForms.Put("dc:publisher", bagForm);
     dcArrayForms.Put("dc:relation", bagForm);
     dcArrayForms.Put("dc:subject", bagForm);
     dcArrayForms.Put("dc:type", bagForm);
     // Properties supposed to be a "Seq".
     PropertyOptions seqForm = new PropertyOptions();
     seqForm.SetArray(true);
     seqForm.SetArrayOrdered(true);
     dcArrayForms.Put("dc:creator", seqForm);
     dcArrayForms.Put("dc:date", seqForm);
     // Properties supposed to be an "Alt" in alternative-text form.
     PropertyOptions altTextForm = new PropertyOptions();
     altTextForm.SetArray(true);
     altTextForm.SetArrayOrdered(true);
     altTextForm.SetArrayAlternate(true);
     altTextForm.SetArrayAltText(true);
     dcArrayForms.Put("dc:description", altTextForm);
     dcArrayForms.Put("dc:rights", altTextForm);
     dcArrayForms.Put("dc:title", altTextForm);
 }
Exemplo n.º 15
0
 public static void RegExCollectAddSubNodesAddParentNode(RowRegexExprNode exprNode, ITree node, IDictionary <ITree, RowRegexExprNode> astRegExNodeMap)
 {
     RegExCollectAddSubNodes(exprNode, node, astRegExNodeMap);
     astRegExNodeMap.Put(node, exprNode);
 }
Exemplo n.º 16
0
 public void RegisterTable(
     string tableName,
     TableMetaData table)
 {
     _moduleTables.Put(tableName, table);
 }
Exemplo n.º 17
0
        // private string segment;

        public BlockTermsReader(TermsIndexReaderBase indexReader, Directory dir, FieldInfos fieldInfos, SegmentInfo info,
                                PostingsReaderBase postingsReader, IOContext context,
                                string segmentSuffix)
        {
            this.postingsReader = postingsReader;

            // this.segment = segment;
            input = dir.OpenInput(IndexFileNames.SegmentFileName(info.Name, segmentSuffix, BlockTermsWriter.TERMS_EXTENSION),
                                  context);

            bool success = false;

            try
            {
                version = ReadHeader(input);

                // Have PostingsReader init itself
                postingsReader.Init(input);

                // Read per-field details
                SeekDir(input, dirOffset);

                int numFields = input.ReadVInt32();
                if (numFields < 0)
                {
                    throw new CorruptIndexException("invalid number of fields: " + numFields + " (resource=" + input + ")");
                }
                for (int i = 0; i < numFields; i++)
                {
                    int  field    = input.ReadVInt32();
                    long numTerms = input.ReadVInt64();
                    if (Debugging.AssertsEnabled)
                    {
                        Debugging.Assert(numTerms >= 0);
                    }
                    long      termsStartPointer = input.ReadVInt64();
                    FieldInfo fieldInfo         = fieldInfos.FieldInfo(field);
                    long      sumTotalTermFreq  = fieldInfo.IndexOptions == IndexOptions.DOCS_ONLY ? -1 : input.ReadVInt64();
                    long      sumDocFreq        = input.ReadVInt64();
                    int       docCount          = input.ReadVInt32();
                    int       longsSize         = version >= BlockTermsWriter.VERSION_META_ARRAY ? input.ReadVInt32() : 0;
                    if (docCount < 0 || docCount > info.DocCount)
                    { // #docs with field must be <= #docs
                        throw new CorruptIndexException("invalid docCount: " + docCount + " maxDoc: " + info.DocCount + " (resource=" + input + ")");
                    }
                    if (sumDocFreq < docCount)
                    {  // #postings must be >= #docs with field
                        throw new CorruptIndexException("invalid sumDocFreq: " + sumDocFreq + " docCount: " + docCount + " (resource=" + input + ")");
                    }
                    if (sumTotalTermFreq != -1 && sumTotalTermFreq < sumDocFreq)
                    { // #positions must be >= #postings
                        throw new CorruptIndexException("invalid sumTotalTermFreq: " + sumTotalTermFreq + " sumDocFreq: " + sumDocFreq + " (resource=" + input + ")");
                    }
                    FieldReader previous = fields.Put(fieldInfo.Name, new FieldReader(this, fieldInfo, numTerms, termsStartPointer, sumTotalTermFreq, sumDocFreq, docCount, longsSize));
                    if (previous != null)
                    {
                        throw new CorruptIndexException("duplicate fields: " + fieldInfo.Name + " (resource=" + input + ")");
                    }
                }
                success = true;
            }
            finally
            {
                if (!success)
                {
                    input.Dispose();
                }
            }

            this.indexReader = indexReader;
        }
Exemplo n.º 18
0
        /// <summary>
        /// Ctor.
        /// </summary>
        /// <param name="assignments">the list of variable assignments</param>
        /// <param name="variableService">variable service</param>
        /// <param name="eventAdapterService">event adapters</param>
        /// <throws><seealso cref="ExprValidationException" /> when variables cannot be found</throws>
        public VariableReadWritePackage(IList <OnTriggerSetAssignment> assignments, VariableService variableService, EventAdapterService eventAdapterService)
        {
            _metaData             = new VariableMetaData[assignments.Count];
            _readersForGlobalVars = new VariableReader[assignments.Count];
            _mustCoerce           = new bool[assignments.Count];
            _writers = new WriteDesc[assignments.Count];

            _variableTypes       = new Dictionary <String, Object>();
            _eventAdapterService = eventAdapterService;
            _variableService     = variableService;

            IDictionary <EventTypeSPI, CopyMethodDesc> eventTypeWrittenProps = new Dictionary <EventTypeSPI, CopyMethodDesc>();
            var count = 0;
            IList <VariableTriggerSetDesc> assignmentList = new List <VariableTriggerSetDesc>();

            foreach (var expressionWithAssignments in assignments)
            {
                var possibleVariableAssignment = ExprNodeUtility.CheckGetAssignmentToVariableOrProp(expressionWithAssignments.Expression);
                if (possibleVariableAssignment == null)
                {
                    throw new ExprValidationException("Missing variable assignment expression in assignment number " + count);
                }
                assignmentList.Add(new VariableTriggerSetDesc(possibleVariableAssignment.First, possibleVariableAssignment.Second.ExprEvaluator));

                var    fullVariableName = possibleVariableAssignment.First;
                var    variableName     = fullVariableName;
                String subPropertyName  = null;

                var indexOfDot = variableName.IndexOf('.');
                if (indexOfDot != -1)
                {
                    subPropertyName = variableName.Substring(indexOfDot + 1);
                    variableName    = variableName.Substring(0, indexOfDot);
                }

                VariableMetaData variableMetadata = variableService.GetVariableMetaData(variableName);
                _metaData[count] = variableMetadata;
                if (variableMetadata == null)
                {
                    throw new ExprValidationException("Variable by name '" + variableName + "' has not been created or configured");
                }
                if (variableMetadata.IsConstant)
                {
                    throw new ExprValidationException("Variable by name '" + variableName + "' is declared constant and may not be set");
                }
                if (variableMetadata.ContextPartitionName == null)
                {
                    _readersForGlobalVars[count] = variableService.GetReader(variableName, EPStatementStartMethodConst.DEFAULT_AGENT_INSTANCE_ID);
                }

                if (subPropertyName != null)
                {
                    if (variableMetadata.EventType == null)
                    {
                        throw new ExprValidationException("Variable by name '" + variableName + "' does not have a property named '" + subPropertyName + "'");
                    }
                    var type = variableMetadata.EventType;
                    if (!(type is EventTypeSPI))
                    {
                        throw new ExprValidationException("Variable by name '" + variableName + "' event type '" + type.Name + "' not writable");
                    }
                    var spi    = (EventTypeSPI)type;
                    var writer = spi.GetWriter(subPropertyName);
                    var getter = spi.GetGetter(subPropertyName);
                    if (writer == null)
                    {
                        throw new ExprValidationException("Variable by name '" + variableName + "' the property '" + subPropertyName + "' is not writable");
                    }

                    _variableTypes.Put(fullVariableName, spi.GetPropertyType(subPropertyName));
                    var writtenProps = eventTypeWrittenProps.Get(spi);
                    if (writtenProps == null)
                    {
                        writtenProps = new CopyMethodDesc(variableName, new List <String>());
                        eventTypeWrittenProps.Put(spi, writtenProps);
                    }
                    writtenProps.PropertiesCopied.Add(subPropertyName);

                    _writers[count] = new WriteDesc(spi, variableName, writer, getter);
                }
                else
                {
                    // determine types
                    var expressionType = possibleVariableAssignment.Second.ExprEvaluator.ReturnType;

                    if (variableMetadata.EventType != null)
                    {
                        if ((expressionType != null) && (!TypeHelper.IsSubclassOrImplementsInterface(expressionType, variableMetadata.EventType.UnderlyingType)))
                        {
                            throw new VariableValueException("Variable '" + variableName
                                                             + "' of declared event type '" + variableMetadata.EventType.Name + "' underlying type '" + variableMetadata.EventType.UnderlyingType.FullName +
                                                             "' cannot be assigned a value of type '" + expressionType.FullName + "'");
                        }
                        _variableTypes.Put(variableName, variableMetadata.EventType.UnderlyingType);
                    }
                    else
                    {
                        var variableType = variableMetadata.VariableType;
                        _variableTypes.Put(variableName, variableType);

                        // determine if the expression type can be assigned
                        if (variableType != typeof(object))
                        {
                            if ((TypeHelper.GetBoxedType(expressionType) != variableType) &&
                                (expressionType != null))
                            {
                                if ((!TypeHelper.IsNumeric(variableType)) ||
                                    (!TypeHelper.IsNumeric(expressionType)))
                                {
                                    throw new ExprValidationException(VariableServiceUtil.GetAssigmentExMessage(variableName, variableType, expressionType));
                                }

                                if (!(TypeHelper.CanCoerce(expressionType, variableType)))
                                {
                                    throw new ExprValidationException(VariableServiceUtil.GetAssigmentExMessage(variableName, variableType, expressionType));
                                }

                                _mustCoerce[count] = true;
                            }
                        }
                    }
                }

                count++;
            }

            _assignments = assignmentList.ToArray();

            if (eventTypeWrittenProps.IsEmpty())
            {
                _copyMethods = new Dictionary <EventTypeSPI, EventBeanCopyMethod>();
                return;
            }

            _copyMethods = new Dictionary <EventTypeSPI, EventBeanCopyMethod>();
            foreach (var entry in eventTypeWrittenProps)
            {
                var propsWritten = entry.Value.PropertiesCopied;
                var props        = propsWritten.ToArray();
                var copyMethod   = entry.Key.GetCopyMethod(props);
                if (copyMethod == null)
                {
                    throw new ExprValidationException("Variable '" + entry.Value.VariableName
                                                      + "' of declared type " + entry.Key.UnderlyingType.GetTypeNameFullyQualPretty() +
                                                      "' cannot be assigned to");
                }
                _copyMethods.Put(entry.Key, copyMethod);
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Write new variable values and commit, evaluating assignment expressions using the given
        /// events per stream.
        /// <para />Populates an optional map of new values if a non-null map is passed.
        /// </summary>
        /// <param name="variableService">variable service</param>
        /// <param name="eventsPerStream">events per stream</param>
        /// <param name="valuesWritten">null or an empty map to populate with written values</param>
        /// <param name="exprEvaluatorContext">expression evaluation context</param>
        public void WriteVariables(VariableService variableService,
                                   EventBean[] eventsPerStream,
                                   IDictionary <String, Object> valuesWritten,
                                   ExprEvaluatorContext exprEvaluatorContext)
        {
            ISet <String> variablesBeansCopied = null;

            if (!_copyMethods.IsEmpty())
            {
                variablesBeansCopied = new HashSet <String>();
            }

            // We obtain a write lock global to the variable space
            // Since expressions can contain variables themselves, these need to be unchangeable for the duration
            // as there could be multiple statements that do "var1 = var1 + 1".
            using (variableService.ReadWriteLock.AcquireWriteLock())
            {
                try
                {
                    variableService.SetLocalVersion();

                    var count = 0;
                    foreach (var assignment in _assignments)
                    {
                        var variableMetaData = _metaData[count];
                        int agentInstanceId  = variableMetaData.ContextPartitionName == null ? EPStatementStartMethodConst.DEFAULT_AGENT_INSTANCE_ID : exprEvaluatorContext.AgentInstanceId;
                        var value            = assignment.Evaluator.Evaluate(
                            new EvaluateParams(eventsPerStream, true, exprEvaluatorContext));

                        if (_writers[count] != null)
                        {
                            var reader = variableService.GetReader(
                                variableMetaData.VariableName, exprEvaluatorContext.AgentInstanceId);
                            var current = (EventBean)reader.Value;
                            if (current == null)
                            {
                                value = null;
                            }
                            else
                            {
                                var writeDesc = _writers[count];
                                var copy      = variablesBeansCopied.Add(writeDesc.VariableName);
                                if (copy)
                                {
                                    var copied = _copyMethods.Get(writeDesc.Type).Copy(current);
                                    current = copied;
                                }
                                variableService.Write(variableMetaData.VariableNumber, agentInstanceId, current);
                                writeDesc.Writer.Write(value, current);
                            }
                        }
                        else if (variableMetaData.EventType != null)
                        {
                            var eventBean = _eventAdapterService.AdapterForType(value, variableMetaData.EventType);
                            variableService.Write(variableMetaData.VariableNumber, agentInstanceId, eventBean);
                        }
                        else
                        {
                            if ((value != null) && (_mustCoerce[count]))
                            {
                                value = CoercerFactory.CoerceBoxed(value, variableMetaData.VariableType);
                            }
                            variableService.Write(variableMetaData.VariableNumber, agentInstanceId, value);
                        }

                        count++;

                        if (valuesWritten != null)
                        {
                            valuesWritten.Put(assignment.VariableName, value);
                        }
                    }

                    variableService.Commit();
                }
                catch (Exception ex)
                {
                    Log.Error("Error evaluating on-set variable expressions: " + ex.Message, ex);
                    variableService.Rollback();
                }
            }
        }
Exemplo n.º 20
0
 static IccProfile()
 {
     cstags.Put("XYZ ", 3);
     cstags.Put("Lab ", 3);
     cstags.Put("Luv ", 3);
     cstags.Put("YCbr", 3);
     cstags.Put("Yxy ", 3);
     cstags.Put("RGB ", 3);
     cstags.Put("GRAY", 1);
     cstags.Put("HSV ", 3);
     cstags.Put("HLS ", 3);
     cstags.Put("CMYK", 4);
     cstags.Put("CMY ", 3);
     cstags.Put("2CLR", 2);
     cstags.Put("3CLR", 3);
     cstags.Put("4CLR", 4);
     cstags.Put("5CLR", 5);
     cstags.Put("6CLR", 6);
     cstags.Put("7CLR", 7);
     cstags.Put("8CLR", 8);
     cstags.Put("9CLR", 9);
     cstags.Put("ACLR", 10);
     cstags.Put("BCLR", 11);
     cstags.Put("CCLR", 12);
     cstags.Put("DCLR", 13);
     cstags.Put("ECLR", 14);
     cstags.Put("FCLR", 15);
 }
Exemplo n.º 21
0
        /* (non-Javadoc)
         * @see com.itextpdf.html2pdf.css.resolve.ICssResolver#resolveStyles(com.itextpdf.html2pdf.html.node.INode, com.itextpdf.html2pdf.css.resolve.CssContext)
         */
        private IDictionary <String, String> ResolveStyles(INode element, CssContext context)
        {
            IList <CssRuleSet> ruleSets = new List <CssRuleSet>();

            ruleSets.Add(new CssRuleSet(null, UserAgentCss.GetStyles(element)));
            if (element is IElementNode)
            {
                ruleSets.Add(new CssRuleSet(null, HtmlStylesToCssConverter.Convert((IElementNode)element)));
            }
            ruleSets.AddAll(cssStyleSheet.GetCssRuleSets(element, deviceDescription));
            if (element is IElementNode)
            {
                String styleAttribute = ((IElementNode)element).GetAttribute(AttributeConstants.STYLE);
                if (styleAttribute != null)
                {
                    ruleSets.Add(new CssRuleSet(null, CssRuleSetParser.ParsePropertyDeclarations(styleAttribute)));
                }
            }
            IDictionary <String, String> elementStyles = CssStyleSheet.ExtractStylesFromRuleSets(ruleSets);

            if (CssConstants.CURRENTCOLOR.Equals(elementStyles.Get(CssConstants.COLOR)))
            {
                // css-color-3/#currentcolor:
                // If the ‘currentColor’ keyword is set on the ‘color’ property itself, it is treated as ‘color: inherit’.
                elementStyles.Put(CssConstants.COLOR, CssConstants.INHERIT);
            }
            String parentFontSizeStr = null;

            if (element.ParentNode() is IStylesContainer)
            {
                IStylesContainer             parentNode   = (IStylesContainer)element.ParentNode();
                IDictionary <String, String> parentStyles = parentNode.GetStyles();
                if (parentStyles == null && !(element.ParentNode() is IDocumentNode))
                {
                    ILog logger = LogManager.GetLogger(typeof(iText.Html2pdf.Css.Resolve.DefaultCssResolver));
                    logger.Error(iText.Html2pdf.LogMessageConstant.ERROR_RESOLVING_PARENT_STYLES);
                }
                if (parentStyles != null)
                {
                    foreach (KeyValuePair <String, String> entry in parentStyles)
                    {
                        MergeParentCssDeclaration(elementStyles, entry.Key, entry.Value, parentStyles);
                    }
                    parentFontSizeStr = parentStyles.Get(CssConstants.FONT_SIZE);
                }
            }
            String elementFontSize = elementStyles.Get(CssConstants.FONT_SIZE);

            if (CssUtils.IsRelativeValue(elementFontSize) || CssConstants.LARGER.Equals(elementFontSize) || CssConstants
                .SMALLER.Equals(elementFontSize))
            {
                float baseFontSize;
                if (CssUtils.IsRemValue(elementFontSize))
                {
                    baseFontSize = context.GetRootFontSize();
                }
                else
                {
                    if (parentFontSizeStr == null)
                    {
                        baseFontSize = CssUtils.ParseAbsoluteFontSize(CssDefaults.GetDefaultValue(CssConstants.FONT_SIZE));
                    }
                    else
                    {
                        baseFontSize = CssUtils.ParseAbsoluteLength(parentFontSizeStr);
                    }
                }
                float absoluteFontSize = CssUtils.ParseRelativeFontSize(elementFontSize, baseFontSize);
                // Format to 4 decimal places to prevent differences between Java and C#
                elementStyles.Put(CssConstants.FONT_SIZE, DecimalFormatUtil.FormatNumber(absoluteFontSize, "0.####") + CssConstants
                                  .PT);
            }
            else
            {
                elementStyles.Put(CssConstants.FONT_SIZE, Convert.ToString(CssUtils.ParseAbsoluteFontSize(elementFontSize)
                                                                           , System.Globalization.CultureInfo.InvariantCulture) + CssConstants.PT);
            }
            // Update root font size
            if (element is IElementNode && TagConstants.HTML.Equals(((IElementNode)element).Name()))
            {
                context.SetRootFontSize(elementStyles.Get(CssConstants.FONT_SIZE));
            }
            ICollection <String> keys = new HashSet <String>();

            foreach (KeyValuePair <String, String> entry in elementStyles)
            {
                if (CssConstants.INITIAL.Equals(entry.Value) || CssConstants.INHERIT.Equals(entry.Value))
                {
                    // if "inherit" is not resolved till now, parents don't have it
                    keys.Add(entry.Key);
                }
            }
            foreach (String key in keys)
            {
                elementStyles.Put(key, CssDefaults.GetDefaultValue(key));
            }
            // This is needed for correct resolving of content property, so doing it right here
            CounterProcessorUtil.ProcessCounters(elementStyles, context, element);
            ResolveContentProperty(elementStyles, element, context);
            return(elementStyles);
        }
Exemplo n.º 22
0
		/// <exception cref="System.IO.IOException"></exception>
		private void ReadPackedRefsImpl(IDictionary<string, Ref> avail, BufferedReader br
			)
		{
			Ref last = null;
			bool peeled = false;
			for (; ; )
			{
				string line = br.ReadLine();
				if (line == null)
				{
					break;
				}
				if (line[0] == '#')
				{
					if (line.StartsWith(RefDirectory.PACKED_REFS_HEADER))
					{
						line = Sharpen.Runtime.Substring(line, RefDirectory.PACKED_REFS_HEADER.Length);
						peeled = line.Contains(RefDirectory.PACKED_REFS_PEELED);
					}
					continue;
				}
				if (line[0] == '^')
				{
					if (last == null)
					{
						throw new TransportException(JGitText.Get().peeledLineBeforeRef);
					}
					ObjectId id = ObjectId.FromString(Sharpen.Runtime.Substring(line, 1));
					last = new ObjectIdRef.PeeledTag(RefStorage.PACKED, last.GetName(), last.GetObjectId
						(), id);
					avail.Put(last.GetName(), last);
					continue;
				}
				int sp = line.IndexOf(' ');
				if (sp < 0)
				{
					throw new TransportException(MessageFormat.Format(JGitText.Get().unrecognizedRef, 
						line));
				}
				ObjectId id_1 = ObjectId.FromString(Sharpen.Runtime.Substring(line, 0, sp));
				string name = Sharpen.Runtime.Substring(line, sp + 1);
				if (peeled)
				{
					last = new ObjectIdRef.PeeledNonTag(RefStorage.PACKED, name, id_1);
				}
				else
				{
					last = new ObjectIdRef.Unpeeled(RefStorage.PACKED, name, id_1);
				}
				avail.Put(last.GetName(), last);
			}
		}
Exemplo n.º 23
0
 public static void ExprCollectAddSubNodesAddParentNode(ExprNode exprNode, ITree node, IDictionary <ITree, ExprNode> astExprNodeMap)
 {
     ExprCollectAddSubNodes(exprNode, node, astExprNodeMap);
     astExprNodeMap.Put(node, exprNode);
 }
Exemplo n.º 24
0
		public virtual string GetChangesFeedPath()
		{
			string path = "_changes?feed=";
			switch (mode)
			{
				case ChangeTracker.ChangeTrackerMode.OneShot:
				{
					path += "normal";
					break;
				}

				case ChangeTracker.ChangeTrackerMode.LongPoll:
				{
					path += "longpoll&limit=50";
					break;
				}

				case ChangeTracker.ChangeTrackerMode.Continuous:
				{
					path += "continuous";
					break;
				}
			}
			path += "&heartbeat=300000";
			if (includeConflicts)
			{
				path += "&style=all_docs";
			}
			if (lastSequenceID != null)
			{
				path += "&since=" + URLEncoder.Encode(lastSequenceID.ToString());
			}
			if (docIDs != null && docIDs.Count > 0)
			{
				filterName = "_doc_ids";
				filterParams = new Dictionary<string, object>();
				filterParams.Put("doc_ids", docIDs);
			}
			if (filterName != null)
			{
				path += "&filter=" + URLEncoder.Encode(filterName);
				if (filterParams != null)
				{
					foreach (string filterParamKey in filterParams.Keys)
					{
						object value = filterParams.Get(filterParamKey);
						if (!(value is string))
						{
							try
							{
								value = Manager.GetObjectMapper().WriteValueAsString(value);
							}
							catch (IOException e)
							{
								throw new ArgumentException(e);
							}
						}
						path += "&" + URLEncoder.Encode(filterParamKey) + "=" + URLEncoder.Encode(value.ToString
							());
					}
				}
			}
			return path;
		}
Exemplo n.º 25
0
        private void Initialize(bool isConfigured)
        {
            var propertyListBuilder = PropertyListBuilderFactory.CreateBuilder(OptionalLegacyDef);
            var properties          = propertyListBuilder.AssessProperties(UnderlyingType);

            _propertyDescriptors        = new EventPropertyDescriptor[properties.Count];
            _propertyDescriptorMap      = new Dictionary <String, EventPropertyDescriptor>();
            PropertyNames               = new String[properties.Count];
            _simpleProperties           = new Dictionary <String, SimplePropertyInfo>();
            _mappedPropertyDescriptors  = new Dictionary <String, InternalEventPropDescriptor>();
            _indexedPropertyDescriptors = new Dictionary <String, InternalEventPropDescriptor>();

            if (UsesSmartResolutionStyle)
            {
                _simpleSmartPropertyTable  = new Dictionary <String, IList <SimplePropertyInfo> >();
                _mappedSmartPropertyTable  = new Dictionary <String, IList <SimplePropertyInfo> >();
                _indexedSmartPropertyTable = new Dictionary <String, IList <SimplePropertyInfo> >();
            }

            if ((OptionalLegacyDef == null) ||
                (OptionalLegacyDef.CodeGeneration != CodeGenerationEnum.DISABLED))
            {
                // get CGLib fast class
                FastClass = null;
                try
                {
                    FastClass = FastClass.Create(UnderlyingType);
                }
                catch (Exception ex)
                {
                    Log.Warn(".initialize Unable to obtain CGLib fast class and/or method implementation for class " +
                             UnderlyingType.Name + ", error msg is " + ex.Message, ex);
                    FastClass = null;
                }
            }

            int count = 0;

            foreach (InternalEventPropDescriptor desc in properties)
            {
                String propertyName = desc.PropertyName;
                Type   underlyingType;
                Type   componentType;
                bool   isRequiresIndex;
                bool   isRequiresMapkey;
                bool   isIndexed;
                bool   isMapped;
                bool   isFragment;

                if (desc.PropertyType.GetValueOrDefault() == EventPropertyType.SIMPLE)
                {
                    EventPropertyGetter getter;
                    Type type;
                    if (desc.ReadMethod != null)
                    {
                        getter = PropertyHelper.GetGetter(desc.PropertyName, desc.ReadMethod, FastClass, _eventAdapterService);
                        type   = desc.ReadMethod.ReturnType;
                    }
                    else
                    {
                        if (desc.AccessorField == null)
                        {
                            // Ignore property
                            continue;
                        }
                        getter = new ReflectionPropFieldGetter(desc.AccessorField, _eventAdapterService);
                        type   = desc.AccessorField.FieldType;
                    }

                    underlyingType   = type;
                    componentType    = null;
                    isRequiresIndex  = false;
                    isRequiresMapkey = false;
                    isIndexed        = false;
                    isMapped         = false;

                    if (type.IsGenericDictionary())
                    {
                        isMapped = true;
                        // We do not yet allow to fragment maps entries.
                        // Class genericType = TypeHelper.GetGenericReturnTypeMap(desc.ReadMethod, desc.AccessorField);
                        isFragment = false;

                        if (desc.ReadMethod != null)
                        {
                            componentType = TypeHelper.GetGenericReturnTypeMap(desc.ReadMethod, false);
                        }
                        else if (desc.AccessorField != null)
                        {
                            componentType = TypeHelper.GetGenericFieldTypeMap(desc.AccessorField, false);
                        }
                        else
                        {
                            componentType = typeof(object);
                        }
                    }
                    else if (type.IsArray)
                    {
                        isIndexed     = true;
                        isFragment    = type.GetElementType().IsFragmentableType();
                        componentType = type.GetElementType();
                    }
                    else if (type.IsImplementsInterface(typeof(IEnumerable)))
                    {
                        isIndexed = true;
                        Type genericType = TypeHelper.GetGenericReturnType(desc.ReadMethod, desc.AccessorField, true);
                        isFragment = genericType.IsFragmentableType();
                        if (genericType != null)
                        {
                            componentType = genericType;
                        }
                        else
                        {
                            componentType = typeof(Object);
                        }
                    }
                    else
                    {
                        isMapped   = false;
                        isFragment = type.IsFragmentableType();
                    }
                    _simpleProperties.Put(propertyName, new SimplePropertyInfo(type, getter, desc));

                    // Recognize that there may be properties with overlapping case-insentitive names
                    if (UsesSmartResolutionStyle)
                    {
                        // Find the property in the smart property table
                        var smartPropertyName = propertyName.ToLower();
                        var propertyInfoList  = _simpleSmartPropertyTable.Get(smartPropertyName);
                        if (propertyInfoList == null)
                        {
                            propertyInfoList = new List <SimplePropertyInfo>();
                            _simpleSmartPropertyTable.Put(smartPropertyName, propertyInfoList);
                        }

                        // Enter the property into the smart property list
                        var propertyInfo = new SimplePropertyInfo(type, getter, desc);
                        propertyInfoList.Add(propertyInfo);
                    }
                }
                else if (desc.PropertyType.GetValueOrDefault() == EventPropertyType.MAPPED)
                {
                    _mappedPropertyDescriptors.Put(propertyName, desc);

                    underlyingType   = desc.ReturnType;
                    componentType    = typeof(object);
                    isRequiresIndex  = false;
                    isRequiresMapkey = desc.ReadMethod.GetParameterTypes().Length > 0;
                    isIndexed        = false;
                    isMapped         = true;
                    isFragment       = false;

                    // Recognize that there may be properties with overlapping case-insentitive names
                    if (UsesSmartResolutionStyle)
                    {
                        // Find the property in the smart property table
                        var smartPropertyName = propertyName.ToLower();
                        var propertyInfoList  = _mappedSmartPropertyTable.Get(smartPropertyName);
                        if (propertyInfoList == null)
                        {
                            propertyInfoList = new List <SimplePropertyInfo>();
                            _mappedSmartPropertyTable.Put(smartPropertyName, propertyInfoList);
                        }

                        // Enter the property into the smart property list
                        var propertyInfo = new SimplePropertyInfo(desc.ReturnType, null, desc);
                        propertyInfoList.Add(propertyInfo);
                    }
                }
                else if (desc.PropertyType.GetValueOrDefault() == EventPropertyType.INDEXED)
                {
                    _indexedPropertyDescriptors.Put(propertyName, desc);

                    underlyingType   = desc.ReturnType;
                    componentType    = null;
                    isRequiresIndex  = desc.ReadMethod.GetParameterTypes().Length > 0;
                    isRequiresMapkey = false;
                    isIndexed        = true;
                    isMapped         = false;
                    isFragment       = desc.ReturnType.IsFragmentableType();

                    if (UsesSmartResolutionStyle)
                    {
                        // Find the property in the smart property table
                        String smartPropertyName = propertyName.ToLower();
                        IList <SimplePropertyInfo> propertyInfoList = _indexedSmartPropertyTable.Get(smartPropertyName);
                        if (propertyInfoList == null)
                        {
                            propertyInfoList = new List <SimplePropertyInfo>();
                            _indexedSmartPropertyTable.Put(smartPropertyName, propertyInfoList);
                        }

                        // Enter the property into the smart property list
                        var propertyInfo = new SimplePropertyInfo(desc.ReturnType, null, desc);
                        propertyInfoList.Add(propertyInfo);
                    }
                }
                else
                {
                    continue;
                }

                PropertyNames[count] = desc.PropertyName;
                var descriptor = new EventPropertyDescriptor(desc.PropertyName,
                                                             underlyingType, componentType, isRequiresIndex, isRequiresMapkey, isIndexed, isMapped, isFragment);
                _propertyDescriptors[count++] = descriptor;
                _propertyDescriptorMap.Put(descriptor.PropertyName, descriptor);
            }

            // Determine event type super types
            SuperTypes = GetBaseTypes(UnderlyingType, _eventAdapterService.BeanEventTypeFactory);
            if (SuperTypes != null && SuperTypes.Length == 0)
            {
                SuperTypes = null;
            }

            if (Metadata != null && Metadata.TypeClass == TypeClass.NAMED_WINDOW)
            {
                SuperTypes = null;
            }

            // Determine deep supertypes
            // Get base types (superclasses and interfaces), deep get of all in the tree
            ICollection <Type> supers = new HashSet <Type>();

            GetSuper(UnderlyingType, supers);
            RemoveLibraryInterfaces(supers);    // Remove CLR library base types

            // Cache the supertypes of this event type for later use
            _deepSuperTypes = new HashSet <EventType>();
            foreach (Type superClass in supers)
            {
                EventType superType = _eventAdapterService.BeanEventTypeFactory.CreateBeanType(superClass.FullName, superClass, false, false, isConfigured);
                _deepSuperTypes.Add(superType);
            }

            DeepSuperTypes = _deepSuperTypes.ToArray();
        }
 public void ParseHeaders(string headersStr)
 {
     headers = new Dictionary<String, String>();
     if (!string.IsNullOrEmpty (headersStr)) {
         headersStr = headersStr.Trim ();
         var tokenizer = headersStr.Split(new[] { "\r\n" }, StringSplitOptions.None);
         foreach (var header in tokenizer) {
             if (!header.Contains (":")) {
                 throw new ArgumentException ("Missing ':' in header line: " + header);
             }
             var headerTokenizer = header.Split(':');
             var key = headerTokenizer[0].Trim ();
             var value = headerTokenizer[1].Trim ();
             headers.Put (key, value);
         }
     }
 }
Exemplo n.º 27
0
        private void RegisterAttachments()
        {
            int numAttachmentsInDoc = 0;
            IDictionary <string, object> attachments = (IDictionary <string, object>)document.Get
                                                           ("_attachments");

            if (attachments == null)
            {
                return;
            }
            foreach (string attachmentName in attachments.Keys)
            {
                IDictionary <string, object> attachment = (IDictionary <string, object>)attachments
                                                          .Get(attachmentName);
                int length = 0;
                if (attachment.ContainsKey("length"))
                {
                    length = ((int)attachment.Get("length"));
                }
                if (attachment.ContainsKey("encoded_length"))
                {
                    length = ((int)attachment.Get("encoded_length"));
                }
                if (attachment.ContainsKey("follows") && ((bool)attachment.Get("follows")) == true)
                {
                    // Check that each attachment in the JSON corresponds to an attachment MIME body.
                    // Look up the attachment by either its MIME Content-Disposition header or MD5 digest:
                    string          digest = (string)attachment.Get("digest");
                    BlobStoreWriter writer = attachmentsByName.Get(attachmentName);
                    if (writer != null)
                    {
                        // Identified the MIME body by the filename in its Disposition header:
                        string actualDigest = writer.MD5DigestString();
                        if (digest != null && !digest.Equals(actualDigest) && !digest.Equals(writer.SHA1DigestString
                                                                                                 ()))
                        {
                            string errMsg = string.Format("Attachment '%s' has incorrect MD5 digest (%s; should be %s)"
                                                          , attachmentName, digest, actualDigest);
                            throw new InvalidOperationException(errMsg);
                        }
                        attachment.Put("digest", actualDigest);
                    }
                    else
                    {
                        if (digest != null)
                        {
                            writer = attachmentsByMd5Digest.Get(digest);
                            if (writer == null)
                            {
                                string errMsg = string.Format("Attachment '%s' does not appear in MIME body (%s; should be %s)"
                                                              , attachmentName);
                                throw new InvalidOperationException(errMsg);
                            }
                        }
                        else
                        {
                            if (attachments.Count == 1 && attachmentsByMd5Digest.Count == 1)
                            {
                                // Else there's only one attachment, so just assume it matches & use it:
                                writer = attachmentsByMd5Digest.Values.GetEnumerator().Next();
                                attachment.Put("digest", writer.MD5DigestString());
                            }
                            else
                            {
                                // No digest metatata, no filename in MIME body; give up:
                                string errMsg = string.Format("Attachment '%s' has no digest metadata; cannot identify MIME body"
                                                              , attachmentName);
                                throw new InvalidOperationException(errMsg);
                            }
                        }
                    }
                    // Check that the length matches:
                    if (writer.GetLength() != length)
                    {
                        string errMsg = string.Format("Attachment '%s' has incorrect length field %d (should be %d)"
                                                      , attachmentName, length, writer.GetLength());
                        throw new InvalidOperationException(errMsg);
                    }
                    ++numAttachmentsInDoc;
                }
                else
                {
                    if (attachment.ContainsKey("data") && length > 1000)
                    {
                        string msg = string.Format("Attachment '%s' sent inline (len=%d).  Large attachments "
                                                   + "should be sent in MIME parts for reduced memory overhead.", attachmentName);
                        Log.W(Database.Tag, msg);
                    }
                }
            }
            if (numAttachmentsInDoc < attachmentsByMd5Digest.Count)
            {
                string msg = string.Format("More MIME bodies (%d) than attachments (%d) ", attachmentsByMd5Digest
                                           .Count, numAttachmentsInDoc);
                throw new InvalidOperationException(msg);
            }
            // hand over the (uninstalled) blobs to the database to remember:
            database.RememberAttachmentWritersForDigests(attachmentsByMd5Digest);
        }
Exemplo n.º 28
0
        private void AddKidsHint(TaggingHintKey parentKey, ICollection <TaggingHintKey> newKidsKeys, int insertIndex
                                 , bool skipFinishedChecks)
        {
            if (newKidsKeys.IsEmpty())
            {
                return;
            }
            if (parentKey.IsArtifact())
            {
                foreach (TaggingHintKey kid in newKidsKeys)
                {
                    MarkArtifactHint(kid);
                }
                return;
            }
            if (!skipFinishedChecks && parentKey.IsFinished())
            {
                ILog logger = LogManager.GetLogger(typeof(iText.Layout.Tagging.LayoutTaggingHelper));
                logger.Error(iText.IO.LogMessageConstant.CANNOT_ADD_HINTS_TO_FINISHED_PARENT);
                return;
            }
            IList <TaggingHintKey> kidsHint = kidsHints.Get(parentKey);

            if (kidsHint == null)
            {
                kidsHint = new List <TaggingHintKey>();
            }
            TaggingHintKey parentTagHint           = IsNonAccessibleHint(parentKey) ? GetAccessibleParentHint(parentKey) : parentKey;
            bool           parentTagAlreadyCreated = parentTagHint != null && IsTagAlreadyExistsForHint(parentTagHint);

            foreach (TaggingHintKey kidKey in newKidsKeys)
            {
                if (kidKey.IsArtifact())
                {
                    continue;
                }
                TaggingHintKey prevParent = GetParentHint(kidKey);
                if (prevParent != null)
                {
                    // TODO seems to be a legit use case to re-add hints to just ensure that hints are added
                    //                Logger logger = LoggerFactory.getLogger(LayoutTaggingHelper.class);
                    //                logger.error(LogMessageConstant.CANNOT_ADD_KID_HINT_WHICH_IS_ALREADY_ADDED_TO_ANOTHER_PARENT);
                    continue;
                }
                if (!skipFinishedChecks && kidKey.IsFinished())
                {
                    ILog logger = LogManager.GetLogger(typeof(iText.Layout.Tagging.LayoutTaggingHelper));
                    logger.Error(iText.IO.LogMessageConstant.CANNOT_ADD_FINISHED_HINT_AS_A_NEW_KID_HINT);
                    continue;
                }
                if (insertIndex > -1)
                {
                    kidsHint.Add(insertIndex++, kidKey);
                }
                else
                {
                    kidsHint.Add(kidKey);
                }
                parentHints.Put(kidKey, parentKey);
                if (parentTagAlreadyCreated)
                {
                    if (kidKey.GetAccessibleElement() is TaggingDummyElement)
                    {
                        CreateTag(kidKey, new TagTreePointer(document));
                    }
                    if (IsNonAccessibleHint(kidKey))
                    {
                        foreach (TaggingHintKey nestedKid in GetAccessibleKidsHint(kidKey))
                        {
                            if (nestedKid.GetAccessibleElement() is TaggingDummyElement)
                            {
                                CreateTag(nestedKid, new TagTreePointer(document));
                            }
                            MoveKidTagIfCreated(parentTagHint, nestedKid);
                        }
                    }
                    else
                    {
                        MoveKidTagIfCreated(parentTagHint, kidKey);
                    }
                }
            }
            if (!kidsHint.IsEmpty())
            {
                kidsHints.Put(parentKey, kidsHint);
            }
        }
Exemplo n.º 29
0
 static DigestAlgorithms() {
     digestNames.Put("1.2.840.113549.2.5", "MD5");
     digestNames.Put("1.2.840.113549.2.2", "MD2");
     digestNames.Put("1.3.14.3.2.26", "SHA1");
     digestNames.Put("2.16.840.1.101.3.4.2.4", "SHA224");
     digestNames.Put("2.16.840.1.101.3.4.2.1", "SHA256");
     digestNames.Put("2.16.840.1.101.3.4.2.2", "SHA384");
     digestNames.Put("2.16.840.1.101.3.4.2.3", "SHA512");
     digestNames.Put("1.3.36.3.2.2", "RIPEMD128");
     digestNames.Put("1.3.36.3.2.1", "RIPEMD160");
     digestNames.Put("1.3.36.3.2.3", "RIPEMD256");
     digestNames.Put("1.2.840.113549.1.1.4", "MD5");
     digestNames.Put("1.2.840.113549.1.1.2", "MD2");
     digestNames.Put("1.2.840.113549.1.1.5", "SHA1");
     digestNames.Put("1.2.840.113549.1.1.14", "SHA224");
     digestNames.Put("1.2.840.113549.1.1.11", "SHA256");
     digestNames.Put("1.2.840.113549.1.1.12", "SHA384");
     digestNames.Put("1.2.840.113549.1.1.13", "SHA512");
     digestNames.Put("1.2.840.113549.2.5", "MD5");
     digestNames.Put("1.2.840.113549.2.2", "MD2");
     digestNames.Put("1.2.840.10040.4.3", "SHA1");
     digestNames.Put("2.16.840.1.101.3.4.3.1", "SHA224");
     digestNames.Put("2.16.840.1.101.3.4.3.2", "SHA256");
     digestNames.Put("2.16.840.1.101.3.4.3.3", "SHA384");
     digestNames.Put("2.16.840.1.101.3.4.3.4", "SHA512");
     digestNames.Put("1.3.36.3.3.1.3", "RIPEMD128");
     digestNames.Put("1.3.36.3.3.1.2", "RIPEMD160");
     digestNames.Put("1.3.36.3.3.1.4", "RIPEMD256");
     digestNames.Put("1.2.643.2.2.9", "GOST3411");
     fixNames.Put("SHA256", SHA256);
     fixNames.Put("SHA384", SHA384);
     fixNames.Put("SHA512", SHA512);
     allowedDigests.Put("MD2", "1.2.840.113549.2.2");
     allowedDigests.Put("MD-2", "1.2.840.113549.2.2");
     allowedDigests.Put("MD5", "1.2.840.113549.2.5");
     allowedDigests.Put("MD-5", "1.2.840.113549.2.5");
     allowedDigests.Put("SHA1", "1.3.14.3.2.26");
     allowedDigests.Put("SHA-1", "1.3.14.3.2.26");
     allowedDigests.Put("SHA224", "2.16.840.1.101.3.4.2.4");
     allowedDigests.Put("SHA-224", "2.16.840.1.101.3.4.2.4");
     allowedDigests.Put("SHA256", "2.16.840.1.101.3.4.2.1");
     allowedDigests.Put("SHA-256", "2.16.840.1.101.3.4.2.1");
     allowedDigests.Put("SHA384", "2.16.840.1.101.3.4.2.2");
     allowedDigests.Put("SHA-384", "2.16.840.1.101.3.4.2.2");
     allowedDigests.Put("SHA512", "2.16.840.1.101.3.4.2.3");
     allowedDigests.Put("SHA-512", "2.16.840.1.101.3.4.2.3");
     allowedDigests.Put("RIPEMD128", "1.3.36.3.2.2");
     allowedDigests.Put("RIPEMD-128", "1.3.36.3.2.2");
     allowedDigests.Put("RIPEMD160", "1.3.36.3.2.1");
     allowedDigests.Put("RIPEMD-160", "1.3.36.3.2.1");
     allowedDigests.Put("RIPEMD256", "1.3.36.3.2.3");
     allowedDigests.Put("RIPEMD-256", "1.3.36.3.2.3");
     allowedDigests.Put("GOST3411", "1.2.643.2.2.9");
 }
Exemplo n.º 30
0
        public void Put(Object filterConstant, EventEvaluator evaluator)
        {
            var keys = (ExprNodeAdapterBase)filterConstant;

            _evaluatorsMap.Put(keys, evaluator);
        }
 static UnicodeBasedPasswordEncryptionTest()
 {
     // values are calculated with com.ibm.icu.text.StringPrep class in icu4j v58.2 lib
     nameToSaslPrepared = new LinkedDictionary <String, UnicodeBasedPasswordEncryptionTest.SaslPreparedString>();
     //الرحيم
     nameToSaslPrepared.Put("arabic01", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u0627\u0644\u0631\u062D\u064A\u0645"
                                                                                                  , "\u0627\u0644\u0631\u062D\u064A\u0645"));
     //ال,ر11حيم
     nameToSaslPrepared.Put("arabic02", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u0627\u0644,\u063111\u062D\u064A\u0645"
                                                                                                  , "\u0627\u0644,\u063111\u062D\u064A\u0645"));
     // لـه
     nameToSaslPrepared.Put("arabic03", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u0644\u0640\u0647"
                                                                                                  , "\u0644\u0640\u0647"));
     // ﻻ
     nameToSaslPrepared.Put("arabic04", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\ufefb", "\u0644\u0627"
                                                                                                  ));
     // لا
     nameToSaslPrepared.Put("arabic05", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u0644\u0627"
                                                                                                  , "\u0644\u0627"));
     // शांति    देवनागरी
     nameToSaslPrepared.Put("devanagari01", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u0936\u093e\u0902\u0924\u093f    \u0926\u0947\u0935\u0928\u093E\u0917\u0930\u0940"
                                                                                                      , "\u0936\u093E\u0902\u0924\u093F    \u0926\u0947\u0935\u0928\u093E\u0917\u0930\u0940"));
     // की प्राचीनतम
     nameToSaslPrepared.Put("devanagari02", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u0915\u0940 \u092A\u094D\u0930\u093E\u091A\u0940\u0928\u0924\u092E"
                                                                                                      , "\u0915\u0940 \u092A\u094D\u0930\u093E\u091A\u0940\u0928\u0924\u092E"));
     // ਗ੍ਰੰਥ ਸਾਹਿਬ
     nameToSaslPrepared.Put("gurmukhi01", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u0A17\u0A4D\u0A30\u0A70\u0A25 \u0A38\u0A3E\u0A39\u0A3F\u0A2C"
                                                                                                    , "\u0A17\u0A4D\u0A30\u0A70\u0A25 \u0A38\u0A3E\u0A39\u0A3F\u0A2C"));
     // ញ្ចូ
     nameToSaslPrepared.Put("khmer01", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u1789\u17D2\u1785\u17BC"
                                                                                                 , "\u1789\u17D2\u1785\u17BC"));
     //இலக்கிய நடை கூட மக்களால்
     nameToSaslPrepared.Put("tamil01", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u0B87\u0BB2\u0B95\u0BCD\u0B95\u0BBF\u0BAF \u0BA8\u0B9F\u0BC8 \u0B95\u0BC2\u0B9F \u0BAE\u0B95\u0BCD\u0B95\u0BB3\u0BBE\u0BB2\u0BCD"
                                                                                                 , "\u0B87\u0BB2\u0B95\u0BCD\u0B95\u0BBF\u0BAF \u0BA8\u0B9F\u0BC8 \u0B95\u0BC2\u0B9F \u0BAE\u0B95\u0BCD\u0B95\u0BB3\u0BBE\u0BB2\u0BCD"
                                                                                                 ));
     // ประเทศไทย
     nameToSaslPrepared.Put("thai01", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28\u0E44\u0E17\u0E22"
                                                                                                , "\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28\u0E44\u0E17\u0E22"));
     nameToSaslPrepared.Put("unicodeBom01", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\uFEFFab\uFEFFc"
                                                                                                      , "abc"));
     nameToSaslPrepared.Put("emoji01", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u267B", "\u267B"
                                                                                                 ));
     nameToSaslPrepared.Put("rfc4013Example01", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("I\u00ADX"
                                                                                                          , "IX"));
     nameToSaslPrepared.Put("rfc4013Example02", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("user"
                                                                                                          , "user"));
     nameToSaslPrepared.Put("rfc4013Example03", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u00AA"
                                                                                                          , "a"));
     nameToSaslPrepared.Put("rfc4013Example04", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u2168"
                                                                                                          , "IX"));
     // match rfc4013Example01
     nameToSaslPrepared.Put("nonAsciiSpace01", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u2008 \u2009 \u200A \u200B"
                                                                                                         , "       "));
     // normalization tests
     nameToSaslPrepared.Put("nfkcNormalization01", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u09C7\u09BE"
                                                                                                             , "\u09CB"));
     nameToSaslPrepared.Put("nfkcNormalization02", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u30AD\u3099\u30AB\u3099"
                                                                                                             , "\u30AE\u30AC"));
     nameToSaslPrepared.Put("nfkcNormalization03", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u3310"
                                                                                                             , "\u30AE\u30AC"));
     nameToSaslPrepared.Put("nfkcNormalization04", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\u1100\u1161\u11A8"
                                                                                                             , "\uAC01"));
     nameToSaslPrepared.Put("nfkcNormalization05", new UnicodeBasedPasswordEncryptionTest.SaslPreparedString("\uF951"
                                                                                                             , "\u964B"));
 }
Exemplo n.º 32
0
        public FixedGapTermsIndexReader(Directory dir, FieldInfos fieldInfos, string segment, int indexDivisor,
                                        IComparer <BytesRef> termComp, string segmentSuffix, IOContext context)
        {
            this.termComp = termComp;

            if (Debugging.AssertsEnabled)
            {
                Debugging.Assert(indexDivisor == -1 || indexDivisor > 0);
            }

            input = dir.OpenInput(IndexFileNames.SegmentFileName(segment, segmentSuffix, FixedGapTermsIndexWriter.TERMS_INDEX_EXTENSION), context);

            bool success = false;

            try
            {
                version = ReadHeader(input);

                if (version >= FixedGapTermsIndexWriter.VERSION_CHECKSUM)
                {
                    CodecUtil.ChecksumEntireFile(input);
                }

                indexInterval = input.ReadInt32();
                if (indexInterval < 1)
                {
                    throw new CorruptIndexException("invalid indexInterval: " + indexInterval + " (resource=" + input + ")");
                }
                this.indexDivisor = indexDivisor;

                if (indexDivisor < 0)
                {
                    totalIndexInterval = indexInterval;
                }
                else
                {
                    // In case terms index gets loaded, later, on demand
                    totalIndexInterval = indexInterval * indexDivisor;
                }
                if (Debugging.AssertsEnabled)
                {
                    Debugging.Assert(totalIndexInterval > 0);
                }

                SeekDir(input, dirOffset);

                // Read directory
                int numFields = input.ReadVInt32();
                if (numFields < 0)
                {
                    throw new CorruptIndexException("invalid numFields: " + numFields + " (resource=" + input + ")");
                }
                //System.out.println("FGR: init seg=" + segment + " div=" + indexDivisor + " nF=" + numFields);
                for (int i = 0; i < numFields; i++)
                {
                    int field         = input.ReadVInt32();
                    int numIndexTerms = input.ReadVInt32();
                    if (numIndexTerms < 0)
                    {
                        throw new CorruptIndexException("invalid numIndexTerms: " + numIndexTerms + " (resource=" + input + ")");
                    }
                    long termsStart         = input.ReadVInt64();
                    long indexStart         = input.ReadVInt64();
                    long packedIndexStart   = input.ReadVInt64();
                    long packedOffsetsStart = input.ReadVInt64();
                    if (packedIndexStart < indexStart)
                    {
                        throw new CorruptIndexException("invalid packedIndexStart: " + packedIndexStart + " indexStart: " + indexStart + "numIndexTerms: " + numIndexTerms + " (resource=" + input + ")");
                    }
                    FieldInfo      fieldInfo = fieldInfos.FieldInfo(field);
                    FieldIndexData previous  = fields.Put(fieldInfo, new FieldIndexData(this, fieldInfo, numIndexTerms, indexStart, termsStart, packedIndexStart, packedOffsetsStart));
                    if (previous != null)
                    {
                        throw new CorruptIndexException("duplicate field: " + fieldInfo.Name + " (resource=" + input + ")");
                    }
                }
                success = true;
            }
            finally
            {
                if (!success)
                {
                    IOUtils.DisposeWhileHandlingException(input);
                }
                if (indexDivisor > 0)
                {
                    input.Dispose();
                    input = null;
                    if (success)
                    {
                        indexLoaded = true;
                    }
                    termBytesReader = termBytes.Freeze(true);
                }
            }
        }
Exemplo n.º 33
0
        public virtual void Browse(
            BrowseRequest req,
            Weight weight,
            Collector collector,
            IDictionary<string, IFacetAccessible> facetMap,
            int start)
        {

            if (_reader == null)
                return;

    
            //      initialize all RuntimeFacetHandlers with data supplied by user at run-time.
            _runtimeFacetHandlers = new List<IRuntimeFacetHandler>(_runtimeFacetHandlerFactoryMap.Count());

            IEnumerable<string> runtimeFacetNames = _runtimeFacetHandlerFactoryMap.Keys;
            foreach (string facetName in runtimeFacetNames)
            {
                var sfacetHandler = this.GetFacetHandler(facetName);
                if (sfacetHandler!=null)
                {
                    logger.Warn("attempting to reset facetHandler: " + sfacetHandler);
                    continue;
                }
                IRuntimeFacetHandlerFactory factory = (IRuntimeFacetHandlerFactory)_runtimeFacetHandlerFactoryMap.Get(facetName);
      
                try
                {

                    FacetHandlerInitializerParam data = req.GetFacetHandlerData(facetName);
                    if (data == null)
                        data = FacetHandlerInitializerParam.EMPTY_PARAM;
                    if (data != FacetHandlerInitializerParam.EMPTY_PARAM || !factory.IsLoadLazily)
                    {
                        IRuntimeFacetHandler facetHandler = factory.Get(data);
                        if (facetHandler != null)
                        {
                            _runtimeFacetHandlers.Add(facetHandler); // add to a list so we close them after search
                            this.SetFacetHandler(facetHandler);
                        }
                    }
                }
                catch (Exception e)
                {
                    throw new BrowseException("error trying to set FacetHandler : " + facetName + ":" + e.Message, e);
                }
            }
            // done initialize all RuntimeFacetHandlers with data supplied by user at run-time.

            IEnumerable<string> fields = FacetNames;

            List<Filter> preFilterList = new List<Filter>();
            List<FacetHitCollector> facetHitCollectorList = new List<FacetHitCollector>();
    
            Filter baseFilter = req.Filter;
            if (baseFilter != null)
            {
                preFilterList.Add(baseFilter);
            }

            int selCount = req.SelectionCount;
            bool isNoQueryNoFilter = IsNoQueryNoFilter(req);

            bool isDefaultSearch = isNoQueryNoFilter && selCount == 0;
            try
            {
      
                foreach (string name in fields)
                {
                    BrowseSelection sel = req.GetSelection(name);
                    FacetSpec ospec = req.GetFacetSpec(name);

                    var handler = GetFacetHandler(name);
        
                    if (handler == null)
                    {
        	            logger.Error("facet handler: " + name + " is not defined, ignored.");
        	            continue;
                    }
        
                    FacetHitCollector facetHitCollector = null;

                    RandomAccessFilter filter = null;
                    if (sel != null)
                    {
                        filter = handler.BuildFilter(sel);
                    }

                    if (ospec == null)
                    {
                        if (filter != null)
                        {
                            preFilterList.Add(filter);
                        }
                    }
                    else
                    {
                        /*FacetSpec fspec = new FacetSpec(); // OrderValueAsc,
                        fspec.setMaxCount(0);
                        fspec.setMinHitCount(1);
          
                        fspec.setExpandSelection(ospec.isExpandSelection());*/
                        FacetSpec fspec = ospec;

                        facetHitCollector = new FacetHitCollector();
                        facetHitCollector.facetHandler = handler;
          
                        if (isDefaultSearch)
                        {
        	                facetHitCollector._collectAllSource = handler.GetFacetCountCollectorSource(sel, fspec);
                        }
                        else
                        {
                            facetHitCollector._facetCountCollectorSource = handler.GetFacetCountCollectorSource(sel, fspec);            
                            if (ospec.ExpandSelection)
                            {
                                if (isNoQueryNoFilter && sel != null && selCount == 1)
                                {
            	                    facetHitCollector._collectAllSource = handler.GetFacetCountCollectorSource(sel, fspec);
                                    if (filter != null)
                                    {
                                        preFilterList.Add(filter);
                                    }
                                }
                                else
                                {
                                    if (filter != null)
                                    {
                	                    facetHitCollector._filter = filter;
                                    }
                                }
                            }
                            else
                            {
                                if (filter != null)
                                {
                                    preFilterList.Add(filter);
                                }
                            }
                        }
                    }
                    if (facetHitCollector != null)
                    {
                        facetHitCollectorList.Add(facetHitCollector);
                    }
                }

                Filter finalFilter = null;
                if (preFilterList.Count > 0)
                {
                    if (preFilterList.Count == 1)
                    {
                        finalFilter = preFilterList.First();
                    }
                    else
                    {
                        finalFilter = new AndFilter(preFilterList);
                    }
                }

                this.FacetHitCollectorList = facetHitCollectorList;

                try
                {
                    if (weight == null)
                    {
                        var q = req.Query;
                        if (q == null)
                        {
                            q = new MatchAllDocsQuery();
                        }
                        weight = CreateWeight(q);
                    }
                    Search(weight, finalFilter, collector, start, req.MapReduceWrapper);
                }
                finally
                {
                    foreach (FacetHitCollector facetCollector in facetHitCollectorList)
                    {
                        string name = facetCollector.facetHandler.Name;
                        List<IFacetCountCollector> resultcollector = null;
                        resultcollector = facetCollector._countCollectorList;
                        if (resultcollector == null || resultcollector.Count == 0)
                        {
        	                resultcollector = facetCollector._collectAllCollectorList;
                        }
                        if (resultcollector != null)
                        {
        	                FacetSpec fspec = req.GetFacetSpec(name);
        	                Debug.Assert(fspec != null);
                            if(resultcollector.Count == 1)
                            {
                                facetMap.Put(name, resultcollector[0]);             
                            }
                            else
                            {
                                List<IFacetAccessible> finalList = new List<IFacetAccessible>(resultcollector.Count);
                                foreach (IFacetCountCollector fc in resultcollector)
                                {
                                    finalList.Add((IFacetAccessible)fc);
                                }
        	                    CombinedFacetAccessible combinedCollector = new CombinedFacetAccessible(fspec, finalList);
                                facetMap.Put(name, combinedCollector);
        	                }
                        }
                    }
                }
            }
            catch (Exception ioe)
            {
                throw new BrowseException(ioe.Message, ioe);
            }
        }
Exemplo n.º 34
0
 public void Provide(IDictionary<string, Type> symbols)
 {
     if (optionalSynthesizeRef != null) {
         symbols.Put(optionalSynthesizeRef.Ref, typeof(bool));
     }
 }
Exemplo n.º 35
0
 static X500Name()
 {
     // Inner classes
     DefaultSymbols.Put(C, "C");
     DefaultSymbols.Put(O, "O");
     DefaultSymbols.Put(T, "T");
     DefaultSymbols.Put(OU, "OU");
     DefaultSymbols.Put(CN, "CN");
     DefaultSymbols.Put(L, "L");
     DefaultSymbols.Put(ST, "ST");
     DefaultSymbols.Put(SN, "SN");
     DefaultSymbols.Put(EmailAddress, "E");
     DefaultSymbols.Put(DC, "DC");
     DefaultSymbols.Put(UID, "UID");
     DefaultSymbols.Put(SURNAME, "SURNAME");
     DefaultSymbols.Put(GIVENNAME, "GIVENNAME");
     DefaultSymbols.Put(INITIALS, "INITIALS");
     DefaultSymbols.Put(GENERATION, "GENERATION");
 }
Exemplo n.º 36
0
        public override void OnUpdate(EventBean[] newData, EventBean[] oldData, NamedWindowRootViewInstance namedWindowRootView, EventTableIndexRepository indexRepository)
        {
            // If new data is filled, it is not a delete
            RevisionEventBeanMerge revisionEvent;
            Object key;

            if ((newData == null) || (newData.Length == 0))
            {
                // we are removing an event
                revisionEvent = (RevisionEventBeanMerge)oldData[0];
                key           = revisionEvent.Key;
                _statePerKey.Remove(key);

                // Insert into indexes for fast deletion, if there are any
                foreach (EventTable table in indexRepository.Tables)
                {
                    table.Remove(oldData);
                }

                // make as not the latest event since its due for removal
                revisionEvent.IsLatest = false;

                namedWindowRootView.UpdateChildren(null, oldData);
                return;
            }

            revisionEvent = (RevisionEventBeanMerge)newData[0];
            EventBean underlyingEvent    = revisionEvent.UnderlyingFullOrDelta;
            EventType underyingEventType = underlyingEvent.EventType;

            // obtain key values
            key = null;
            RevisionTypeDesc typesDesc;
            Boolean          isBaseEventType = false;

            if (underyingEventType == RevisionSpec.BaseEventType)
            {
                typesDesc       = _infoFullType;
                key             = PropertyUtility.GetKeys(underlyingEvent, _infoFullType.KeyPropertyGetters);
                isBaseEventType = true;
            }
            else
            {
                typesDesc = TypeDescriptors.Get(underyingEventType);

                // if this type cannot be found, check all supertypes, if any
                if (typesDesc == null)
                {
                    EventType[] superTypes = underyingEventType.DeepSuperTypes;
                    if (superTypes != null)
                    {
                        foreach (var superType in superTypes)
                        {
                            if (superType == RevisionSpec.BaseEventType)
                            {
                                typesDesc       = _infoFullType;
                                key             = PropertyUtility.GetKeys(underlyingEvent, _infoFullType.KeyPropertyGetters);
                                isBaseEventType = true;
                                break;
                            }
                            typesDesc = TypeDescriptors.Get(superType);
                            if (typesDesc != null)
                            {
                                TypeDescriptors.Put(underyingEventType, typesDesc);
                                key = PropertyUtility.GetKeys(underlyingEvent, typesDesc.KeyPropertyGetters);
                                break;
                            }
                        }
                    }
                }
                else
                {
                    key = PropertyUtility.GetKeys(underlyingEvent, typesDesc.KeyPropertyGetters);
                }
            }

            // get the state for this key value
            RevisionStateMerge revisionState = _statePerKey.Get(key);

            // Delta event and no full
            if ((!isBaseEventType) && (revisionState == null))
            {
                return; // Ignore the event, its a delta and we don't currently have a full event for it
            }

            // New full event
            if (revisionState == null)
            {
                revisionState = new RevisionStateMerge(underlyingEvent, null, null);
                _statePerKey.Put(key, revisionState);

                // prepare revison event
                revisionEvent.LastBaseEvent = underlyingEvent;
                revisionEvent.Key           = key;
                revisionEvent.Overlay       = null;
                revisionEvent.IsLatest      = true;

                // Insert into indexes for fast deletion, if there are any
                foreach (EventTable table in indexRepository.Tables)
                {
                    table.Add(newData);
                }

                // post to data window
                revisionState.LastEvent = revisionEvent;
                namedWindowRootView.UpdateChildren(new EventBean[] { revisionEvent }, null);
                return;
            }

            // handle Update, changing revision state and event as required
            _updateStrategy.HandleUpdate(isBaseEventType, revisionState, revisionEvent, typesDesc);

            // prepare revision event
            revisionEvent.LastBaseEvent = revisionState.BaseEventUnderlying;
            revisionEvent.Overlay       = revisionState.Overlays;
            revisionEvent.Key           = key;
            revisionEvent.IsLatest      = true;

            // get prior event
            RevisionEventBeanMerge lastEvent = revisionState.LastEvent;

            lastEvent.IsLatest = false;

            // data to post
            var newDataPost = new EventBean[] { revisionEvent };
            var oldDataPost = new EventBean[] { lastEvent };

            // Update indexes
            foreach (EventTable table in indexRepository.Tables)
            {
                table.Remove(oldDataPost);
                table.Add(newDataPost);
            }

            // keep reference to last event
            revisionState.LastEvent = revisionEvent;

            namedWindowRootView.UpdateChildren(newDataPost, oldDataPost);
        }
Exemplo n.º 37
0
        // LUCENENET NOTE: Sourced from Apache Harmony:

        /// <summary>
        /// Loads properties from the specified <see cref="Stream"/>. The encoding is
        /// ISO8859-1.
        /// </summary>
        /// <remarks>
        /// The Properties file is interpreted according to the
        /// following rules:
        /// <list type="bullet">
        ///     <item><description>
        ///         Empty lines are ignored.
        ///     </description></item>
        ///     <item><description>
        ///         Lines starting with either a "#" or a "!" are comment lines and are
        ///         ignored.
        ///     </description></item>
        ///     <item><description>
        ///         A backslash at the end of the line escapes the following newline
        ///         character ("\r", "\n", "\r\n"). If there's a whitespace after the
        ///         backslash it will just escape that whitespace instead of concatenating
        ///         the lines. This does not apply to comment lines.
        ///     </description></item>
        ///     <item><description>
        ///         A property line consists of the key, the space between the key and
        ///         the value, and the value. The key goes up to the first whitespace, "=" or
        ///         ":" that is not escaped. The space between the key and the value contains
        ///         either one whitespace, one "=" or one ":" and any number of additional
        ///         whitespaces before and after that character. The value starts with the
        ///         first character after the space between the key and the value.
        ///     </description></item>
        ///     <item><description>
        ///         Following escape sequences are recognized: "\ ", "\\", "\r", "\n",
        ///         "\!", "\#", "\t", "\b", "\f", and "&#92;uXXXX" (unicode character).
        ///     </description></item>
        /// </list>
        /// <para/>
        /// This method is to mimic and interoperate with the Properties class in Java, which
        /// is essentially a string dictionary that natively supports importing and exporting to this format.
        /// </remarks>
        /// <param name="dict">This dictionary.</param>
        /// <param name="input">The <see cref="Stream"/>.</param>
        /// <exception cref="IOException">If error occurs during reading from the <see cref="Stream"/>.</exception>
        public static void Load(this IDictionary <string, string> dict, Stream input)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }
            lock (dict)
            {
                int    mode = NONE, unicode = 0, count = 0;
                char   nextChar;
                char[] buf = new char[40];
                int    offset = 0, keyLength = -1, intVal;
                bool   firstChar = true;
                Stream bis       = input;

                while (true)
                {
                    intVal = bis.ReadByte();
                    if (intVal == -1)
                    {
                        // if mode is UNICODE but has less than 4 hex digits, should
                        // throw an IllegalArgumentException
                        // luni.08=Invalid Unicode sequence: expected format \\uxxxx
                        if (mode == UNICODE && count < 4)
                        {
                            throw new ArgumentException("Invalid Unicode sequence: expected format \\uxxxx"); //$NON-NLS-1$
                        }
                        // if mode is SLASH and no data is read, should append '\u0000'
                        // to buf
                        if (mode == SLASH)
                        {
                            buf[offset++] = '\u0000';
                        }
                        break;
                    }
                    nextChar = (char)(intVal & 0xff);

                    if (offset == buf.Length)
                    {
                        char[] newBuf = new char[buf.Length * 2];
                        System.Array.Copy(buf, 0, newBuf, 0, offset);
                        buf = newBuf;
                    }
                    if (mode == UNICODE)
                    {
                        int digit = Character.Digit(nextChar, 16);
                        if (digit >= 0)
                        {
                            unicode = (unicode << 4) + digit;
                            if (++count < 4)
                            {
                                continue;
                            }
                        }
                        else if (count <= 4)
                        {
                            // luni.09=Invalid Unicode sequence: illegal character
                            throw new ArgumentException("Invalid Unicode sequence: illegal character"); //$NON-NLS-1$
                        }
                        mode          = NONE;
                        buf[offset++] = (char)unicode;
                        if (nextChar != '\n')
                        {
                            continue;
                        }
                    }
                    if (mode == SLASH)
                    {
                        mode = NONE;
                        switch (nextChar)
                        {
                        case '\r':
                            mode = CONTINUE;     // Look for a following \n
                            continue;

                        case '\n':
                            mode = IGNORE;     // Ignore whitespace on the next line
                            continue;

                        case 'b':
                            nextChar = '\b';
                            break;

                        case 'f':
                            nextChar = '\f';
                            break;

                        case 'n':
                            nextChar = '\n';
                            break;

                        case 'r':
                            nextChar = '\r';
                            break;

                        case 't':
                            nextChar = '\t';
                            break;

                        case 'u':
                            mode    = UNICODE;
                            unicode = count = 0;
                            continue;
                        }
                    }
                    else
                    {
                        switch (nextChar)
                        {
                        case '#':
                        case '!':
                            if (firstChar)
                            {
                                while (true)
                                {
                                    intVal = bis.ReadByte();
                                    if (intVal == -1)
                                    {
                                        break;
                                    }
                                    // & 0xff not required
                                    nextChar = (char)intVal;
                                    if (nextChar == '\r' || nextChar == '\n')
                                    {
                                        break;
                                    }
                                }
                                continue;
                            }
                            break;

                        case '\n':
                            if (mode == CONTINUE)
                            {                  // Part of a \r\n sequence
                                mode = IGNORE; // Ignore whitespace on the next line
                                continue;
                            }
                            // fall into the next case
                            mode      = NONE;
                            firstChar = true;
                            if (offset > 0 || (offset == 0 && keyLength == 0))
                            {
                                if (keyLength == -1)
                                {
                                    keyLength = offset;
                                }
                                string temp = new string(buf, 0, offset);
                                dict.Put(temp.Substring(0, keyLength), temp
                                         .Substring(keyLength));
                            }
                            keyLength = -1;
                            offset    = 0;
                            continue;

                        case '\r':
                            mode      = NONE;
                            firstChar = true;
                            if (offset > 0 || (offset == 0 && keyLength == 0))
                            {
                                if (keyLength == -1)
                                {
                                    keyLength = offset;
                                }
                                string temp = new string(buf, 0, offset);
                                dict.Put(temp.Substring(0, keyLength), temp
                                         .Substring(keyLength));
                            }
                            keyLength = -1;
                            offset    = 0;
                            continue;

                        case '\\':
                            if (mode == KEY_DONE)
                            {
                                keyLength = offset;
                            }
                            mode = SLASH;
                            continue;

                        case ':':
                        case '=':
                            if (keyLength == -1)
                            {     // if parsing the key
                                mode      = NONE;
                                keyLength = offset;
                                continue;
                            }
                            break;
                        }
                        if (nextChar < 256 && char.IsWhiteSpace(nextChar))
                        {
                            if (mode == CONTINUE)
                            {
                                mode = IGNORE;
                            }
                            // if key length == 0 or value length == 0
                            if (offset == 0 || offset == keyLength || mode == IGNORE)
                            {
                                continue;
                            }
                            if (keyLength == -1)
                            { // if parsing the key
                                mode = KEY_DONE;
                                continue;
                            }
                        }
                        if (mode == IGNORE || mode == CONTINUE)
                        {
                            mode = NONE;
                        }
                    }
                    firstChar = false;
                    if (mode == KEY_DONE)
                    {
                        keyLength = offset;
                        mode      = NONE;
                    }
                    buf[offset++] = nextChar;
                }
                if (keyLength == -1 && offset > 0)
                {
                    keyLength = offset;
                }
                if (keyLength >= 0)
                {
                    string temp = new string(buf, 0, offset);
                    dict.Put(temp.Substring(0, keyLength), temp.Substring(keyLength));
                }
            }
        }
Exemplo n.º 38
0
 public override void Put(Object filterConstant, EventEvaluator evaluator)
 {
     ConstantsMap.Put(filterConstant, evaluator);
 }
Exemplo n.º 39
0
 public void AssignService(
     int num,
     SubordTableLookupStrategy subselectStrategy)
 {
     services.Put(num, subselectStrategy);
 }
Exemplo n.º 40
0
		internal static object InitHash(IDictionary<object, object> h, object key, object initialValue)
		{
			lock (h)
			{
				object current = h.Get(key);
				if (current == null)
				{
					h.Put(key, initialValue);
				}
				else
				{
					initialValue = current;
				}
			}
			return initialValue;
		}
Exemplo n.º 41
0
		private static void DiscoverAccessibleMethods(Type clazz, IDictionary<JavaMembers.MethodSignature, MethodInfo> map, bool includeProtected, bool includePrivate)
		{
			if (Modifier.IsPublic(clazz.Attributes) || includePrivate)
			{
				try
				{
					if (includeProtected || includePrivate)
					{
						while (clazz != null)
						{
							try
							{
								MethodInfo[] methods = Sharpen.Runtime.GetDeclaredMethods(clazz);
								foreach (MethodInfo method in methods)
								{
									int mods = method.Attributes;
									if (Modifier.IsPublic(mods) || Modifier.IsProtected(mods) || includePrivate)
									{
										JavaMembers.MethodSignature sig = new JavaMembers.MethodSignature(method);
										if (!map.ContainsKey(sig))
										{
											if (includePrivate && !method.IsAccessible())
											{
											}
											map.Put(sig, method);
										}
									}
								}
								clazz = clazz.BaseType;
							}
							catch (SecurityException)
							{
								// Some security settings (i.e., applets) disallow
								// access to Class.getDeclaredMethods. Fall back to
								// Class.getMethods.
								MethodInfo[] methods = clazz.GetMethods();
								foreach (MethodInfo method in methods)
								{
									JavaMembers.MethodSignature sig = new JavaMembers.MethodSignature(method);
									if (!map.ContainsKey(sig))
									{
										map.Put(sig, method);
									}
								}
								break;
							}
						}
					}
					else
					{
						// getMethods gets superclass methods, no
						// need to loop any more
						MethodInfo[] methods = clazz.GetMethods();
						foreach (MethodInfo method in methods)
						{
							JavaMembers.MethodSignature sig = new JavaMembers.MethodSignature(method);
							// Array may contain methods with same signature but different return value!
							if (!map.ContainsKey(sig))
							{
								map.Put(sig, method);
							}
						}
					}
					return;
				}
				catch (SecurityException)
				{
					Context.ReportWarning("Could not discover accessible methods of class " + clazz.FullName + " due to lack of privileges, " + "attemping superclasses/interfaces.");
				}
			}
			// Fall through and attempt to discover superclass/interface
			// methods
			Type[] interfaces = clazz.GetInterfaces();
			foreach (Type intface in interfaces)
			{
				DiscoverAccessibleMethods(intface, map, includeProtected, includePrivate);
			}
			Type superclass = clazz.BaseType;
			if (superclass != null)
			{
				DiscoverAccessibleMethods(superclass, map, includeProtected, includePrivate);
			}
		}
Exemplo n.º 42
0
        public string GetChangesFeedPath()
        {
            if (UsePost)
            {
                return "_changes";
            }

            var path = new StringBuilder("_changes?feed=");
            path.Append(GetFeed());

            if (mode == ChangeTrackerMode.LongPoll)
            {
                path.Append(string.Format("&limit={0}", LongPollModeLimit));
            }
            path.Append(string.Format("&heartbeat={0}", _heartbeatMilliseconds));
            if (includeConflicts)
            {
                path.Append("&style=all_docs");
            }
            if (lastSequenceID != null)
            {
                path.Append("&since=");
                path.Append(Uri.EscapeUriString(lastSequenceID.ToString()));
            }
            if (docIDs != null && docIDs.Count > 0)
            {
                filterName = "_doc_ids";
                filterParams = new Dictionary<string, object>();
                filterParams.Put("doc_ids", docIDs);
            }
            if (filterName != null)
            {
                path.Append("&filter=");
                path.Append(Uri.EscapeUriString(filterName));
                if (filterParams != null)
                {
                    foreach (string filterParamKey in filterParams.Keys)
                    {
                        var value = filterParams.Get(filterParamKey);
                        if (!(value is string))
                        {
                            try
                            {
                                value = Manager.GetObjectMapper().WriteValueAsString(value);
                            }
                            catch (IOException e)
                            {
                                throw new InvalidOperationException("Unable to JSON-serialize a filter parameter value.", e);
                            }
                        }
                        path.Append("&");
                        path.Append(Uri.EscapeUriString(filterParamKey));
                        path.Append("=");
                        path.Append(Uri.EscapeUriString(value.ToString()));
                    }
                }
            }
            return path.ToString();
        }
Exemplo n.º 43
0
		public virtual void ParseHeaders(string headersStr)
		{
			headers = new Dictionary<string, string>();
			if (headersStr != null && headersStr.Length > 0)
			{
				headersStr = headersStr.Trim();
				StringTokenizer tokenizer = new StringTokenizer(headersStr, "\r\n");
				while (tokenizer.HasMoreTokens())
				{
					string header = tokenizer.NextToken();
					if (!header.Contains(":"))
					{
						throw new ArgumentException("Missing ':' in header line: " + header);
					}
					StringTokenizer headerTokenizer = new StringTokenizer(header, ":");
					string key = headerTokenizer.NextToken().Trim();
					string value = headerTokenizer.NextToken().Trim();
					headers.Put(key, value);
				}
			}
		}
        internal IDictionary<string, object> GetChangesFeedParams()
        {
            if (docIDs != null && docIDs.Count > 0) {
                filterName = "_doc_ids";
                filterParams = new Dictionary<string, object>();
                filterParams.Put("doc_ids", docIDs);
            }

            var bodyParams = new Dictionary<string, object>();
            bodyParams["feed"] = GetFeed();
            bodyParams["heartbeat"] = _heartbeatMilliseconds;

            if (includeConflicts) {
                bodyParams["style"] = "all_docs";
            } else {
                bodyParams["style"] = null;
            }

            if (lastSequenceID != null) {
                Int64 sequenceAsLong;
                var success = Int64.TryParse(lastSequenceID.ToString(), out sequenceAsLong);
                bodyParams["since"] = success ? sequenceAsLong : lastSequenceID;
            }

            if (mode == ChangeTrackerMode.LongPoll) {
                bodyParams["limit"] = LongPollModeLimit;
            }

            if (filterName != null) {
                bodyParams["filter"] = filterName;
                bodyParams.PutAll(filterParams);
            }

            return bodyParams;
        }
Exemplo n.º 45
0
 public void AssignService(
     int serviceId,
     AggregationService aggregationService)
 {
     services.Put(serviceId, aggregationService);
 }
Exemplo n.º 46
0
 internal Digest(string hdr)
 {
     @params = Parse(hdr);
     string qop = @params.Get("qop");
     if ("auth".Equals(qop))
     {
         byte[] bin = new byte[8];
         PRNG.NextBytes(bin);
         @params.Put("cnonce", Base64.EncodeBytes(bin));
     }
 }
Exemplo n.º 47
0
        /// <summary>
        /// Ctor.
        /// </summary>
        /// <param name="viewChain">views</param>
        /// <param name="matchRecognizeSpec">specification</param>
        /// <param name="agentInstanceContext">The agent instance context.</param>
        /// <param name="isUnbound">true for unbound stream</param>
        /// <param name="annotations">annotations</param>
        /// <exception cref="ExprValidationException">
        /// Variable ' + defineItem.Identifier + ' has already been defined
        /// or
        /// An aggregate function may not appear in a DEFINE clause
        /// or
        /// Failed to validate condition expression for variable ' + defineItem.Identifier + ':  + ex.Message
        /// or
        /// Aggregation functions in the measure-clause must only refer to properties of exactly one group variable returning multiple events
        /// or
        /// Aggregation functions in the measure-clause must refer to one or more properties of exactly one group variable returning multiple events
        /// or
        /// The measures clause requires that each expression utilizes the AS keyword to assign a column name
        /// </exception>
        /// <throws>ExprValidationException if validation fails</throws>
        public EventRowRegexNFAViewFactory(
            ViewFactoryChain viewChain,
            MatchRecognizeSpec matchRecognizeSpec,
            AgentInstanceContext agentInstanceContext,
            bool isUnbound,
            Attribute[] annotations,
            ConfigurationEngineDefaults.MatchRecognize matchRecognizeConfig)
        {
            var parentViewType = viewChain.EventType;

            _matchRecognizeSpec   = matchRecognizeSpec;
            _isUnbound            = isUnbound;
            _isIterateOnly        = HintEnum.ITERATE_ONLY.GetHint(annotations) != null;
            _matchRecognizeConfig = matchRecognizeConfig;

            var statementContext = agentInstanceContext.StatementContext;

            // Expand repeats and permutations
            _expandedPatternNode = RegexPatternExpandUtil.Expand(matchRecognizeSpec.Pattern);

            // Determine single-row and multiple-row variables
            _variablesSingle = new LinkedHashSet <string>();
            ISet <string> variablesMultiple = new LinkedHashSet <string>();

            EventRowRegexHelper.RecursiveInspectVariables(_expandedPatternNode, false, _variablesSingle, variablesMultiple);

            // each variable gets associated with a stream number (multiple-row variables as well to hold the current event for the expression).
            var streamNum = 0;

            _variableStreams = new LinkedHashMap <string, Pair <int, bool> >();
            foreach (var variableSingle in _variablesSingle)
            {
                _variableStreams.Put(variableSingle, new Pair <int, bool>(streamNum, false));
                streamNum++;
            }
            foreach (var variableMultiple in variablesMultiple)
            {
                _variableStreams.Put(variableMultiple, new Pair <int, bool>(streamNum, true));
                streamNum++;
            }

            // mapping of stream to variable
            _streamVariables = new SortedDictionary <int, string>();
            foreach (var entry in _variableStreams)
            {
                _streamVariables.Put(entry.Value.First, entry.Key);
            }

            // determine visibility rules
            var visibility = EventRowRegexHelper.DetermineVisibility(_expandedPatternNode);

            // assemble all single-row variables for expression validation
            var allStreamNames = new string[_variableStreams.Count];
            var allTypes       = new EventType[_variableStreams.Count];

            streamNum = 0;
            foreach (var variableSingle in _variablesSingle)
            {
                allStreamNames[streamNum] = variableSingle;
                allTypes[streamNum]       = parentViewType;
                streamNum++;
            }
            foreach (var variableMultiple in variablesMultiple)
            {
                allStreamNames[streamNum] = variableMultiple;
                allTypes[streamNum]       = parentViewType;
                streamNum++;
            }

            // determine type service for use with DEFINE
            // validate each DEFINE clause expression
            ISet <string>             definedVariables = new HashSet <string>();
            IList <ExprAggregateNode> aggregateNodes   = new List <ExprAggregateNode>();
            var exprEvaluatorContext = new ExprEvaluatorContextStatement(statementContext, false);

            _isExprRequiresMultimatchState = new bool[_variableStreams.Count];

            for (var defineIndex = 0; defineIndex < matchRecognizeSpec.Defines.Count; defineIndex++)
            {
                var defineItem = matchRecognizeSpec.Defines[defineIndex];
                if (definedVariables.Contains(defineItem.Identifier))
                {
                    throw new ExprValidationException("Variable '" + defineItem.Identifier + "' has already been defined");
                }
                definedVariables.Add(defineItem.Identifier);

                // stream-type visibilities handled here
                var typeServiceDefines = EventRowRegexNFAViewFactoryHelper.BuildDefineStreamTypeServiceDefine(statementContext, _variableStreams, defineItem, visibility, parentViewType);

                var exprNodeResult    = HandlePreviousFunctions(defineItem.Expression);
                var validationContext = new ExprValidationContext(
                    typeServiceDefines,
                    statementContext.MethodResolutionService, null,
                    statementContext.SchedulingService,
                    statementContext.VariableService,
                    statementContext.TableService, exprEvaluatorContext,
                    statementContext.EventAdapterService,
                    statementContext.StatementName,
                    statementContext.StatementId,
                    statementContext.Annotations,
                    statementContext.ContextDescriptor,
                    statementContext.ScriptingService,
                    true, false, true, false, null, false);

                ExprNode validated;
                try {
                    // validate
                    validated = ExprNodeUtility.GetValidatedSubtree(ExprNodeOrigin.MATCHRECOGDEFINE, exprNodeResult, validationContext);

                    // check aggregates
                    defineItem.Expression = validated;
                    ExprAggregateNodeUtil.GetAggregatesBottomUp(validated, aggregateNodes);
                    if (!aggregateNodes.IsEmpty())
                    {
                        throw new ExprValidationException("An aggregate function may not appear in a DEFINE clause");
                    }
                }
                catch (ExprValidationException ex) {
                    throw new ExprValidationException("Failed to validate condition expression for variable '" + defineItem.Identifier + "': " + ex.Message, ex);
                }

                // determine access to event properties from multi-matches
                var visitor = new ExprNodeStreamRequiredVisitor();
                validated.Accept(visitor);
                var streamsRequired = visitor.StreamsRequired;
                foreach (var streamRequired in streamsRequired)
                {
                    if (streamRequired >= _variableStreams.Count)
                    {
                        var streamNumIdent = _variableStreams.Get(defineItem.Identifier).First;
                        _isExprRequiresMultimatchState[streamNumIdent] = true;
                        break;
                    }
                }
            }
            _isDefineAsksMultimatches  = CollectionUtil.IsAnySet(_isExprRequiresMultimatchState);
            _defineMultimatchEventBean = _isDefineAsksMultimatches ? EventRowRegexNFAViewFactoryHelper.GetDefineMultimatchBean(statementContext, _variableStreams, parentViewType) : null;

            // assign "prev" node indexes
            // Since an expression such as "prior(2, price), prior(8, price)" translates into {2, 8} the relative index is {0, 1}.
            // Map the expression-supplied index to a relative index
            var countPrev = 0;

            foreach (var entry in _callbacksPerIndex)
            {
                foreach (var callback in entry.Value)
                {
                    callback.AssignedIndex = countPrev;
                }
                countPrev++;
            }

            // determine type service for use with MEASURE
            IDictionary <string, object> measureTypeDef = new LinkedHashMap <string, object>();

            foreach (var variableSingle in _variablesSingle)
            {
                measureTypeDef.Put(variableSingle, parentViewType);
            }
            foreach (var variableMultiple in variablesMultiple)
            {
                measureTypeDef.Put(variableMultiple, new EventType[] { parentViewType });
            }
            var outputEventTypeName = statementContext.StatementId + "_rowrecog";

            _compositeEventType = (ObjectArrayEventType)statementContext.EventAdapterService.CreateAnonymousObjectArrayType(outputEventTypeName, measureTypeDef);
            StreamTypeService typeServiceMeasure = new StreamTypeServiceImpl(_compositeEventType, "MATCH_RECOGNIZE", true, statementContext.EngineURI);

            // find MEASURE clause aggregations
            var measureReferencesMultivar = false;
            IList <ExprAggregateNode> measureAggregateExprNodes = new List <ExprAggregateNode>();

            foreach (var measureItem in matchRecognizeSpec.Measures)
            {
                ExprAggregateNodeUtil.GetAggregatesBottomUp(measureItem.Expr, measureAggregateExprNodes);
            }
            if (!measureAggregateExprNodes.IsEmpty())
            {
                var isIStreamOnly = new bool[allStreamNames.Length];
                CompatExtensions.Fill(isIStreamOnly, true);
                var typeServiceAggregateMeasure  = new StreamTypeServiceImpl(allTypes, allStreamNames, isIStreamOnly, statementContext.EngineURI, false);
                var measureExprAggNodesPerStream = new Dictionary <int, IList <ExprAggregateNode> >();

                foreach (var aggregateNode in measureAggregateExprNodes)
                {
                    // validate absence of group-by
                    aggregateNode.ValidatePositionals();
                    if (aggregateNode.OptionalLocalGroupBy != null)
                    {
                        throw new ExprValidationException("Match-recognize does not allow aggregation functions to specify a group-by");
                    }

                    // validate node and params
                    var count   = 0;
                    var visitor = new ExprNodeIdentifierVisitor(true);

                    var validationContext = new ExprValidationContext(
                        typeServiceAggregateMeasure,
                        statementContext.MethodResolutionService, null,
                        statementContext.SchedulingService,
                        statementContext.VariableService,
                        statementContext.TableService,
                        exprEvaluatorContext,
                        statementContext.EventAdapterService,
                        statementContext.StatementName,
                        statementContext.StatementId,
                        statementContext.Annotations,
                        statementContext.ContextDescriptor,
                        statementContext.ScriptingService,
                        false, false, true, false, null, false);
                    foreach (var child in aggregateNode.ChildNodes)
                    {
                        var validated = ExprNodeUtility.GetValidatedSubtree(ExprNodeOrigin.MATCHRECOGMEASURE, child, validationContext);
                        validated.Accept(visitor);
                        aggregateNode.SetChildNode(count++, new ExprNodeValidated(validated));
                    }
                    validationContext = new ExprValidationContext(
                        typeServiceMeasure, statementContext.MethodResolutionService, null,
                        statementContext.SchedulingService,
                        statementContext.VariableService,
                        statementContext.TableService,
                        exprEvaluatorContext,
                        statementContext.EventAdapterService,
                        statementContext.StatementName,
                        statementContext.StatementId,
                        statementContext.Annotations,
                        statementContext.ContextDescriptor,
                        statementContext.ScriptingService,
                        false, false, true, false, null, false);
                    aggregateNode.Validate(validationContext);

                    // verify properties used within the aggregation
                    var aggregatedStreams = new HashSet <int>();
                    foreach (var pair in visitor.ExprProperties)
                    {
                        aggregatedStreams.Add(pair.First);
                    }

                    int?multipleVarStream = null;
                    foreach (int streamNumAggregated in aggregatedStreams)
                    {
                        var variable = _streamVariables.Get(streamNumAggregated);
                        if (variablesMultiple.Contains(variable))
                        {
                            measureReferencesMultivar = true;
                            if (multipleVarStream == null)
                            {
                                multipleVarStream = streamNumAggregated;
                                continue;
                            }
                            throw new ExprValidationException("Aggregation functions in the measure-clause must only refer to properties of exactly one group variable returning multiple events");
                        }
                    }

                    if (multipleVarStream == null)
                    {
                        throw new ExprValidationException("Aggregation functions in the measure-clause must refer to one or more properties of exactly one group variable returning multiple events");
                    }

                    var aggNodesForStream = measureExprAggNodesPerStream.Get(multipleVarStream.Value);
                    if (aggNodesForStream == null)
                    {
                        aggNodesForStream = new List <ExprAggregateNode>();
                        measureExprAggNodesPerStream.Put(multipleVarStream.Value, aggNodesForStream);
                    }
                    aggNodesForStream.Add(aggregateNode);
                }

                var factoryDesc = AggregationServiceFactoryFactory.GetServiceMatchRecognize(_streamVariables.Count, measureExprAggNodesPerStream, typeServiceAggregateMeasure.EventTypes);
                _aggregationService     = factoryDesc.AggregationServiceFactory.MakeService(agentInstanceContext);
                _aggregationExpressions = factoryDesc.Expressions;
            }
            else
            {
                _aggregationService     = null;
                _aggregationExpressions = Collections.GetEmptyList <AggregationServiceAggExpressionDesc>();
            }

            // validate each MEASURE clause expression
            IDictionary <string, object> rowTypeDef = new LinkedHashMap <string, object>();
            var streamRefVisitor = new ExprNodeStreamUseCollectVisitor();

            foreach (var measureItem in matchRecognizeSpec.Measures)
            {
                if (measureItem.Name == null)
                {
                    throw new ExprValidationException("The measures clause requires that each expression utilizes the AS keyword to assign a column name");
                }
                var validated = ValidateMeasureClause(measureItem.Expr, typeServiceMeasure, variablesMultiple, _variablesSingle, statementContext);
                measureItem.Expr = validated;
                rowTypeDef.Put(measureItem.Name, validated.ExprEvaluator.ReturnType);
                validated.Accept(streamRefVisitor);
            }

            // Determine if any of the multi-var streams are referenced in the measures (non-aggregated only)
            foreach (var @ref in streamRefVisitor.Referenced)
            {
                var rootPropName = @ref.RootPropertyNameIfAny;
                if (rootPropName != null)
                {
                    if (variablesMultiple.Contains(rootPropName))
                    {
                        measureReferencesMultivar = true;
                        break;
                    }
                }

                var streamRequired = @ref.StreamReferencedIfAny;
                if (streamRequired != null)
                {
                    var streamVariable = _streamVariables.Get(streamRequired.Value);
                    if (streamVariable != null)
                    {
                        var def = _variableStreams.Get(streamVariable);
                        if (def != null && def.Second)
                        {
                            measureReferencesMultivar = true;
                            break;
                        }
                    }
                }
            }
            _isCollectMultimatches = measureReferencesMultivar || _isDefineAsksMultimatches;

            // create rowevent type
            var rowEventTypeName = statementContext.StatementId + "_rowrecogrow";

            _rowEventType = statementContext.EventAdapterService.CreateAnonymousMapType(rowEventTypeName, rowTypeDef, true);

            // validate partition-by expressions, if any
            if (!matchRecognizeSpec.PartitionByExpressions.IsEmpty())
            {
                var typeServicePartition = new StreamTypeServiceImpl(parentViewType, "MATCH_RECOGNIZE_PARTITION", true, statementContext.EngineURI);
                var validated            = new List <ExprNode>();
                var validationContext    = new ExprValidationContext(
                    typeServicePartition, statementContext.MethodResolutionService, null,
                    statementContext.SchedulingService, statementContext.VariableService, statementContext.TableService,
                    exprEvaluatorContext, statementContext.EventAdapterService, statementContext.StatementName,
                    statementContext.StatementId, statementContext.Annotations, statementContext.ContextDescriptor,
                    statementContext.ScriptingService,
                    false, false, true, false, null, false);
                foreach (var partitionExpr in matchRecognizeSpec.PartitionByExpressions)
                {
                    validated.Add(ExprNodeUtility.GetValidatedSubtree(ExprNodeOrigin.MATCHRECOGPARTITION, partitionExpr, validationContext));
                }
                matchRecognizeSpec.PartitionByExpressions = validated;
            }

            // validate interval if present
            if (matchRecognizeSpec.Interval != null)
            {
                var validationContext =
                    new ExprValidationContext(
                        new StreamTypeServiceImpl(statementContext.EngineURI, false),
                        statementContext.MethodResolutionService, null, statementContext.SchedulingService,
                        statementContext.VariableService, statementContext.TableService, exprEvaluatorContext,
                        statementContext.EventAdapterService, statementContext.StatementName, statementContext.StatementId,
                        statementContext.Annotations, statementContext.ContextDescriptor, statementContext.ScriptingService,
                        false, false, true, false, null, false);
                matchRecognizeSpec.Interval.Validate(validationContext);
            }
        }
Exemplo n.º 48
0
        private EventPropertyGetter DoResolvePropertyGetter(String propertyExpression, bool allowSimpleProperties)
        {
            EventPropertyGetter getter = _propertyGetterCache.Get(propertyExpression);

            if (getter != null)
            {
                return(getter);
            }

            if (!allowSimpleProperties)
            {
                // see if this is an indexed property
                int index = ASTUtil.UnescapedIndexOfDot(propertyExpression);
                if (index == -1)
                {
                    // parse, can be an indexed property
                    Property property = PropertyParser.ParseAndWalk(propertyExpression);
                    if (!property.IsDynamic)
                    {
                        if (!(property is IndexedProperty))
                        {
                            return(null);
                        }
                        var indexedProp = (IndexedProperty)property;
                        getter = PropertyGetters.Get(indexedProp.PropertyNameAtomic);
                        if (null == getter)
                        {
                            return(null);
                        }
                        EventPropertyDescriptor descriptor = PropertyDescriptorMap.Get(indexedProp.PropertyNameAtomic);
                        if (descriptor == null)
                        {
                            return(null);
                        }
                        if (!descriptor.IsIndexed)
                        {
                            return(null);
                        }
                        if (descriptor.PropertyType == typeof(XmlNodeList))
                        {
                            FragmentFactory fragmentFactory = new FragmentFactoryDOMGetter(
                                EventAdapterService, this, indexedProp.PropertyNameAtomic);
                            return(new XPathPropertyArrayItemGetter(getter, indexedProp.Index, fragmentFactory));
                        }
                        if (descriptor.PropertyType == typeof(string))
                        {
                            FragmentFactory fragmentFactory = new FragmentFactoryDOMGetter(
                                EventAdapterService, this, indexedProp.PropertyNameAtomic);
                            return(new XPathPropertyArrayItemGetter(getter, indexedProp.Index, fragmentFactory));
                        }
                    }
                }
            }

            if (!_isPropertyExpressionXPath)
            {
                Property prop      = PropertyParser.ParseAndWalk(propertyExpression);
                bool     isDynamic = prop.IsDynamic;

                if (!isDynamic)
                {
                    SchemaItem item = prop.GetPropertyTypeSchema(_schemaModelRoot, EventAdapterService);
                    if (item == null)
                    {
                        return(null);
                    }

                    getter = prop.GetGetterDOM(_schemaModelRoot, EventAdapterService, this, propertyExpression);
                    if (getter == null)
                    {
                        return(null);
                    }

                    Type returnType = SchemaUtil.ToReturnType(item);
                    if ((returnType != typeof(XmlNode)) && (returnType != typeof(XmlNodeList)))
                    {
                        if (!returnType.IsArray)
                        {
                            getter = new DOMConvertingGetter(propertyExpression, (DOMPropertyGetter)getter, returnType);
                        }
                        else
                        {
                            getter = new DOMConvertingArrayGetter((DOMPropertyGetter)getter, returnType.GetElementType());
                        }
                    }
                }
                else
                {
                    return(prop.GetGetterDOM());
                }
            }
            else
            {
                bool allowFragments = !ConfigurationEventTypeXMLDOM.IsXPathPropertyExpr;
                getter = SchemaXMLPropertyParser.GetXPathResolution(
                    propertyExpression,
                    NamespaceContext,
                    RootElementName,
                    _rootElementNamespace,
                    _schemaModel,
                    EventAdapterService,
                    this,
                    allowFragments,
                    ConfigurationEventTypeXMLDOM.DefaultNamespace);
            }

            _propertyGetterCache.Put(propertyExpression, getter);
            return(getter);
        }
 public virtual string GetChangesFeedPath()
 {
     if (usePOST)
     {
         return "_changes";
     }
     string path = "_changes?feed=";
     path += GetFeed();
     if (mode == ChangeTracker.ChangeTrackerMode.LongPoll)
     {
         path += string.Format("&limit=%s", limit);
     }
     path += string.Format("&heartbeat=%s", GetHeartbeatMilliseconds());
     if (includeConflicts)
     {
         path += "&style=all_docs";
     }
     if (lastSequenceID != null)
     {
         path += "&since=" + URLEncoder.Encode(lastSequenceID.ToString());
     }
     if (docIDs != null && docIDs.Count > 0)
     {
         filterName = "_doc_ids";
         filterParams = new Dictionary<string, object>();
         filterParams.Put("doc_ids", docIDs);
     }
     if (filterName != null)
     {
         path += "&filter=" + URLEncoder.Encode(filterName);
         if (filterParams != null)
         {
             foreach (string filterParamKey in filterParams.Keys)
             {
                 object value = filterParams.Get(filterParamKey);
                 if (!(value is string))
                 {
                     try
                     {
                         value = Manager.GetObjectMapper().WriteValueAsString(value);
                     }
                     catch (IOException e)
                     {
                         throw new ArgumentException(e);
                     }
                 }
                 path += "&" + URLEncoder.Encode(filterParamKey) + "=" + URLEncoder.Encode(value.ToString
                     ());
             }
         }
     }
     return path;
 }
Exemplo n.º 50
0
		/// <summary>Helper method to map arbitrary objects to user-defined names.</summary>
		/// <remarks>
		/// Helper method to map arbitrary objects to user-defined names. This can be
		/// used create short names for objects to produce small and stable debug
		/// output. It is guaranteed that when you lookup the same object multiple
		/// times even with different nameTemplates this method will always return
		/// the same name which was derived from the first nameTemplate.
		/// nameTemplates can contain "%n" which will be replaced by a running number
		/// before used as a name.
		/// </remarks>
		/// <param name="l">the object to lookup</param>
		/// <param name="nameTemplate">
		/// the name for that object. Can contain "%n" which will be
		/// replaced by a running number before used as a name. If the
		/// lookup table already contains the object this parameter will
		/// be ignored
		/// </param>
		/// <param name="lookupTable">a table storing object-name mappings.</param>
		/// <returns>
		/// a name of that object. Is not guaranteed to be unique. Use
		/// nameTemplates containing "%n" to always have unique names
		/// </returns>
		public static string Lookup(object l, string nameTemplate, IDictionary<object, string
			> lookupTable)
		{
			string name = lookupTable.Get(l);
			if (name == null)
			{
				name = nameTemplate.ReplaceAll("%n", Sharpen.Extensions.ToString(lookupTable.Count
					));
				lookupTable.Put(l, name);
			}
			return name;
		}
Exemplo n.º 51
0
        public static void Put <T>(this IDictionary dictionary, T item)
        {
            var key = typeof(T).FullName;

            dictionary.Put(key, item);
        }