/// <summary> /// Produces a formatted string as specified by the conversion pattern. /// </summary> /// <param name="loggingEvent">the event being logged</param> /// <returns>the formatted string</returns> override public string Format(LoggingEvent loggingEvent) { if (loggingEvent == null) { throw new ArgumentNullException("loggingEvent"); } // Reset working string buffer if (m_sbuf.Capacity > MAX_CAPACITY) { m_sbuf = new StringBuilder(BUF_SIZE); } else { m_sbuf.Length = 0; } PatternConverter c = m_head; // loop through the chain of pattern converters while (c != null) { c.Format(m_sbuf, loggingEvent); c = c.Next; } return(m_sbuf.ToString()); }
/// <summary> /// Write the exception text to the output /// </summary> /// <param name="writer"><see cref="T:System.IO.TextWriter" /> that will receive the formatted result.</param> /// <param name="loggingEvent">the event being logged</param> /// <remarks> /// <para> /// If an exception object is stored in the logging event /// it will be rendered into the pattern output with a /// trailing newline. /// </para> /// <para> /// If there is no exception or the exception property specified /// by the Option value does not exist then nothing will be output /// and no trailing newline will be appended. /// It is typical to put a newline before the exception /// and to have the exception as the last data in the pattern. /// </para> /// <para> /// Recognized values for the Option parameter are: /// </para> /// <list type="bullet"> /// <item> /// <description>Message</description> /// </item> /// <item> /// <description>Source</description> /// </item> /// <item> /// <description>StackTrace</description> /// </item> /// <item> /// <description>TargetSite</description> /// </item> /// <item> /// <description>HelpLink</description> /// </item> /// </list> /// </remarks> protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) { if (loggingEvent.ExceptionObject != null && Option != null && Option.Length > 0) { string text = Option.ToLower(); switch (text) { case "message": PatternConverter.WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.Message); return; case "source": PatternConverter.WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.Source); return; case "stacktrace": PatternConverter.WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.StackTrace); return; } if (text == "helplink") { PatternConverter.WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.HelpLink); } } else { string exceptionString = loggingEvent.GetExceptionString(); if (exceptionString != null && exceptionString.Length > 0) { writer.WriteLine(exceptionString); } } }
public void Init() { patternsConverter = new PatternConverter(); patternsRepository = new MemoryPatternsRepository(); sourceCodeRep = new MemoryCodeRepository( "<?php \n" + "test_call_0();\n" + "test_call_1(a);\n" + "test_call_2(a, e);\n" + "test_call_3(c, d, a);\n" + "test_call_4(c, d, a, e);\n" + "\n" + "$password = a;\n" + "call_with_password_param(1, $password, 2);\n" + "\n" + "$password2 = \"1234\";\n" + "if ($password2->Length > 0) { }\n" + "test_call_5(1, $password2, 2);\n" + "$concat = \"111\" .\n" + " \"222222222\" . \n" + " \"333\";", "samples.php" ); workflow = new Workflow(sourceCodeRep, patternsRepository) { Logger = new LoggerMessageCounter() }; }
public static MatchingResultDto[] GetMatchings(string code, string pattern, LanguageFlags analyzedLanguages, LanguageFlags?patternLanguages = null) { var sourceCodeRep = new MemoryCodeRepository(code); var patternsRep = new MemoryPatternsRepository(); var workflow = new Workflow(sourceCodeRep, analyzedLanguages, patternsRep) { Logger = new LoggerMessageCounter() }; var processor = new DslProcessor(); var patternNode = (PatternNode)processor.Deserialize(pattern, patternLanguages ?? LanguageExt.AllPatternLanguages); var p = new Pattern { Data = patternNode, DebugInfo = pattern }; var patternsConverter = new PatternConverter( new JsonUstNodeSerializer(typeof(UstNode), typeof(PatternVarDef))); patternsRep.Add(patternsConverter.ConvertBack(new List <Pattern>() { p })); WorkflowResult workflowResult = workflow.Process(); MatchingResultDto[] matchingResults = workflowResult.MatchingResults.ToDto(workflow.SourceCodeRepository) .OrderBy(r => r.PatternKey) .ToArray(); return(matchingResults); }
public void Init() { patternsConverter = new PatternConverter( new JsonUstNodeSerializer(typeof(UstNode), typeof(PatternVarDef))); patternsRep = new MemoryPatternsRepository(); sourceCodeRep = new MemoryCodeRepository( "<?php \n" + "test_call_0();\n" + "test_call_1(a);\n" + "test_call_2(a, e);\n" + "test_call_3(c, d, a);\n" + "test_call_4(c, d, a, e);\n" + "\n" + "$password = a;\n" + "call_with_password_param(1, $password, 2);\n" + "\n" + "$password2 = \"1234\";\n" + "if ($password2->Length > 0) { }\n" + "test_call_5(1, $password2, 2);" ); workflow = new Workflow(sourceCodeRep, Language.Php, patternsRep) { Logger = new LoggerMessageCounter() }; }
/// <summary> /// Write the property value to the output /// </summary> /// <param name="writer"><see cref="T:System.IO.TextWriter" /> that will receive the formatted result.</param> /// <param name="state">null, state is not set</param> /// <remarks> /// <para> /// Writes out the value of a named property. The property name /// should be set in the <see cref="P:log4net.Util.PatternConverter.Option" /> /// property. /// </para> /// <para> /// If the <see cref="P:log4net.Util.PatternConverter.Option" /> is set to <c>null</c> /// then all the properties are written as key value pairs. /// </para> /// </remarks> protected override void Convert(TextWriter writer, object state) { CompositeProperties compositeProperties = new CompositeProperties(); PropertiesDictionary properties = LogicalThreadContext.Properties.GetProperties(create: false); if (properties != null) { compositeProperties.Add(properties); } PropertiesDictionary properties2 = ThreadContext.Properties.GetProperties(create: false); if (properties2 != null) { compositeProperties.Add(properties2); } compositeProperties.Add(GlobalContext.Properties.GetReadOnlyProperties()); if (Option != null) { PatternConverter.WriteObject(writer, null, compositeProperties[Option]); } else { PatternConverter.WriteDictionary(writer, null, compositeProperties.Flatten()); } }
public void Init() { patternsRepository = new DefaultPatternRepository(); var patternsConverter = new PatternConverter(new JsonUstNodeSerializer(typeof(UstNode), typeof(PatternVarDef))); patterns = patternsConverter.Convert(patternsRepository.GetAll()); }
public static MatchResultDto[] GetMatches(TextFile source, string pattern, IEnumerable <Language> analyzedLanguages, IEnumerable <Language> patternLanguages = null) { var sourceRep = new MemorySourceRepository(source.Data, source.FullName) { Languages = new HashSet <Language>(analyzedLanguages) }; var patternsRep = new MemoryPatternsRepository(); var logger = new TestLogger(); var workflow = new Workflow(sourceRep, patternsRep) { Logger = logger }; var processor = new DslProcessor(); PatternRoot patternNode = processor.Deserialize(new TextFile(pattern) { PatternKey = pattern }); patternNode.Languages = new HashSet <Language>(patternLanguages ?? LanguageUtils.PatternLanguages); patternNode.DebugInfo = pattern; var patternsConverter = new PatternConverter(); patternsRep.Add(patternsConverter.ConvertBack(new List <PatternRoot> { patternNode })); workflow.Process(); MatchResultDto[] matchResults = logger.Matches.ToDto() .OrderBy(r => r.PatternKey) .ToArray(); return(matchResults); }
protected Task GetConvertPatternsTask(TWorkflowResult workflowResult) { Task convertPatternsTask = null; if (stageHelper.IsPatterns || stageHelper.IsContainsMatch) { convertPatternsTask = new Task(() => { try { var stopwatch = Stopwatch.StartNew(); IEnumerable <PatternDto> patternDtos = PatternsRepository.GetAll(); UstPatternMatcher.Patterns = PatternConverter.Convert(patternDtos); stopwatch.Stop(); workflowResult.AddPatternsTime(stopwatch.ElapsedTicks); workflowResult.AddResultEntity(UstPatternMatcher.Patterns); } catch (Exception ex) { Logger.LogError(new ParsingException("", ex, "Patterns can not be deserialized") { IsPattern = true }); } }); convertPatternsTask.Start(); } return(convertPatternsTask); }
protected override List <PatternDto> InitPatterns() { var patterns = new List <Pattern>(); var commonPatterns = CreateCommonPatterns(); patterns.AddRange(commonPatterns); var cSharpPatterns = CreateCSharpPatterns(); patterns.AddRange(cSharpPatterns); var javaPatterns = CreateJavaPatterns(); patterns.AddRange(javaPatterns); var phpPatterns = CreatePhpPatterns(); patterns.AddRange(phpPatterns); var plSqlPatterns = CreatePlSqlPatterns(); patterns.AddRange(plSqlPatterns); var tSqlPatterns = CreateTSqlPatterns(); patterns.AddRange(tSqlPatterns); var javaScriptPatterns = CreateJavaScriptPatterns(); patterns.AddRange(javaScriptPatterns); var htmpPatterns = CreateHtmlPatterns(); patterns.AddRange(htmpPatterns); var patternsConverter = new PatternConverter(new JsonUstNodeSerializer(typeof(UstNode), typeof(PatternVarDef))); List <PatternDto> result = patternsConverter.ConvertBack(patterns.ToArray()).ToList(); return(result); }
protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) { if (HttpContext.Current == null) { writer.Write(SystemInfo.NotAvailableText); } else { HttpRequest request = null; try { request = HttpContext.Current.Request; } catch (HttpException) { } if (request != null) { if (this.Option != null) { PatternConverter.WriteObject(writer, loggingEvent.Repository, request.Form[this.Option]); } else { PatternConverter.WriteObject(writer, loggingEvent.Repository, request.Form.ToString()); } } else { writer.Write(SystemInfo.NotAvailableText); } } }
/// <summary> /// Helper method to call the <see cref="PatternConverter.Format"/> /// </summary> /// <param name="conv">converter to call</param> /// <param name="loggingEvent">event to render</param> /// <returns>value retrieved</returns> public static Object Format(PatternConverter conv, LoggingEvent loggingEvent) { var sw = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); conv.Format(sw, loggingEvent); return(sw.ToString()); }
public void Init() { patternsRepository = new DefaultPatternRepository(); var patternsConverter = new PatternConverter(); patterns = patternsConverter.Convert(patternsRepository.GetAll()); }
/// <summary> /// Activate the options that were previously set with calls to properties. /// </summary> /// <remarks> /// <para> /// This allows an object to defer activation of its options until all /// options have been set. This is required for components which have /// related options that remain ambiguous until all are set. /// </para> /// <para> /// If a component implements this interface then this method must be called /// after its properties have been set before the component can be used. /// </para> /// <para> /// The strange constructor call to this method is suspended using /// <see cref="m_constructed"/>. /// </para> /// </remarks> public override void ActivateOptions() { if (!m_constructed) { return; } // pass control to parent in case we do not get a serializer :o[ base.ActivateOptions(); // just to get those converters var parser = CreatePatternParser(String.Empty); // Extract discovered converters var converters = Enumerable.ToArray( Enumerable.Cast <ConverterInfo>( parser.PatternConverters.Values ) ); var arrangement = new MultipleArrangement(); if (m_arrangement.Arrangements.Count != 0) { arrangement.AddArrangement(m_arrangement); } var patternArrangement = ArrangementConverter.GetArrangement(ConversionPattern, converters); if (patternArrangement != null) { arrangement.AddArrangement(patternArrangement); } if (arrangement.Arrangements.Count == 0) { // cater for bare defaults arrangement.AddArrangement(new DefaultArrangement()); } var serconv = SerializingConverter; if (serconv == null) { var name = SerializerName ?? DefaultSerializerName; var info = (parser.PatternConverters.ContainsKey(name) ? parser.PatternConverters[name] as ConverterInfo : null ) ?? CreateSerializingConverterInfo(name, typeof(JsonPatternConverter)); SerializingConverter = serconv = CreateSerializingConverter(info); } if (serconv != null) { SetUpSerializingConverter(serconv, converters, arrangement, m_fetcher, m_renderer, m_decorators.ToArray()); } }
public override PatternConverter SetNext(PatternConverter patternConverter) { LiteralPatternConverter literalPc = patternConverter as LiteralPatternConverter; if (literalPc != null) { Option += literalPc.Option; return(this); } return(base.SetNext(patternConverter)); }
protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) { if (this.Option != null) { PatternConverter.WriteObject(writer, loggingEvent.Repository, this.LookupProperty(this.Option, loggingEvent)); } else { PatternConverter.WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties()); } }
/// <summary> /// Set the next converter in the chain /// </summary> /// <param name="pc">The next pattern converter in the chain</param> /// <returns>The next pattern converter</returns> /// <remarks> /// <para> /// Special case the building of the pattern converter chain /// for <see cref="T:log4net.Util.PatternStringConverters.LiteralPatternConverter" /> instances. Two adjacent /// literals in the pattern can be represented by a single combined /// pattern converter. This implementation detects when a /// <see cref="T:log4net.Util.PatternStringConverters.LiteralPatternConverter" /> is added to the chain /// after this converter and combines its value with this converter's /// literal value. /// </para> /// </remarks> public override PatternConverter SetNext(PatternConverter pc) { LiteralPatternConverter literalPatternConverter = pc as LiteralPatternConverter; if (literalPatternConverter != null) { Option += literalPatternConverter.Option; return(this); } return(base.SetNext(pc)); }
/// <summary> /// Create a named instance from a <see cref="PatternConverter"/> /// </summary> /// <param name="name">conversion name</param> /// <param name="converter">pattern converter</param> public RawCallLayout(string name, PatternConverter converter) { Name = name; if (converter is IOptionHandler) { ((IOptionHandler)converter).ActivateOptions(); } m_getter = (e) => Format(converter, e); }
public void UnAmbiguousProtienPatternTest() { IPatternConverter patternConverter = PatternConverter.GetInstanace(ProteinAlphabet.Instance); IList <string> actual = patternConverter.Convert("ACDEFGH"); HashSet <string> expected = new HashSet <string>(); expected.Add("ACDEFGH"); Assert.IsTrue(Compare(expected, actual)); }
public override PatternConverter SetNext(PatternConverter pc) { LiteralPatternConverter converter = pc as LiteralPatternConverter; if (converter == null) { return(base.SetNext(pc)); } this.Option = this.Option + converter.Option; return(this); }
/// <summary> /// Set the next converter in the chain /// </summary> /// <param name="pc">The next pattern converter in the chain</param> /// <returns>The next pattern converter</returns> /// <remarks> /// <para> /// Special case the building of the pattern converter chain /// for <see cref="LiteralPatternConverter"/> instances. Two adjacent /// literals in the pattern can be represented by a single combined /// pattern converter. This implementation detects when a /// <see cref="LiteralPatternConverter"/> is added to the chain /// after this converter and combines its value with this converter's /// literal value. /// </para> /// </remarks> public override PatternConverter SetNext(PatternConverter pc) { var literalPc = pc as LiteralPatternConverter; if (literalPc != null) { // Combine the two adjacent literals together Option = Option + literalPc.Option; // We are the next converter now return this; } return base.SetNext(pc); }
public void EmptyPatternTest() { try { IPatternConverter patternConverter = PatternConverter.GetInstanace(DnaAlphabet.Instance); patternConverter.Convert(string.Empty); } catch (Exception ex) { Assert.AreEqual(ex.Message, "Value cannot be null.\r\nParameter name: pattern"); } }
public void RepeatDnaPatternTest() { IPatternConverter patternConverter = PatternConverter.GetInstanace(DnaAlphabet.Instance); IList <string> actual = patternConverter.Convert("AG*CTR"); HashSet <string> expected = new HashSet <string>(); expected.Add("AG*CTG"); expected.Add("AG*CTA"); Assert.IsTrue(Compare(expected, actual)); }
public void CurlyBracketDnaPatternTest() { IPatternConverter patternConverter = PatternConverter.GetInstanace(DnaAlphabet.Instance); IList <string> actual = patternConverter.Convert("A{GCT}R"); HashSet <string> expected = new HashSet <string>(); expected.Add("AAG"); expected.Add("AAA"); Assert.IsTrue(Compare(expected, actual)); }
public void AmbiguousRnaPatternTest() { IPatternConverter patternConverter = PatternConverter.GetInstanace(RnaAlphabet.Instance); IList <string> actual = patternConverter.Convert("AGCUM"); HashSet <string> expected = new HashSet <string>(); expected.Add("AGCUA"); expected.Add("AGCUC"); Assert.IsTrue(Compare(expected, actual)); }
/// <summary> /// Set the next converter in the chain /// </summary> /// <param name="pc">The next pattern converter in the chain</param> /// <returns>The next pattern converter</returns> /// <remarks> /// <para> /// Special case the building of the pattern converter chain /// for <see cref="LiteralPatternConverter"/> instances. Two adjacent /// literals in the pattern can be represented by a single combined /// pattern converter. This implementation detects when a /// <see cref="LiteralPatternConverter"/> is added to the chain /// after this converter and combines its value with this converter's /// literal value. /// </para> /// </remarks> public override PatternConverter SetNext(PatternConverter pc) { LiteralPatternConverter literalPc = pc as LiteralPatternConverter; if (literalPc != null) { // Combine the two adjacent literals together Option = Option + literalPc.Option; // We are the next converter now return(this); } return(base.SetNext(pc)); }
public Workflow(ISourceCodeRepository sourceCodeRepository, LanguageFlags languages, IPatternsRepository patternsRepository = null, Stage stage = Stage.Match) : base(stage) { SourceCodeRepository = sourceCodeRepository; PatternsRepository = patternsRepository ?? new DefaultPatternRepository(); ParserConverterSets = ParserConverterBuilder.GetParserConverterSets(languages); UstPatternMatcher = new BruteForcePatternMatcher(); IUstNodeSerializer jsonNodeSerializer = new JsonUstNodeSerializer(typeof(UstNode), typeof(PatternVarDef)); IUstNodeSerializer dslNodeSerializer = new DslProcessor(); PatternConverter = new PatternConverter(new IUstNodeSerializer[] { jsonNodeSerializer, dslNodeSerializer }); Stage = stage; ThreadCount = 1; }
public override void ActivateOptions() { // NB: this piece of code is taken from log4net source for PatternLayout _patternConverter = CreatePatternParser(ConversionPattern).Parse(); for (var current = _patternConverter; current != null; current = current.Next) { if (!(current is PatternLayoutConverter patternLayoutConverter) || patternLayoutConverter.IgnoresException) { continue; } IgnoresException = false; break; } }
public Workflow(SourceRepository sourceRepository = null, IPatternsRepository patternsRepository = null, Stage stage = Stage.Match) : base(stage) { LogsDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "PT.PM"); DumpDir = LogsDir; TempDir = Path.Combine(Path.GetTempPath(), "PT.PM"); SourceRepository = sourceRepository; PatternsRepository = patternsRepository ?? new DefaultPatternRepository(); IPatternSerializer jsonNodeSerializer = new JsonPatternSerializer(); IPatternSerializer dslNodeSerializer = new DslProcessor(); PatternConverter = new PatternConverter(jsonNodeSerializer, dslNodeSerializer); Stage = stage; }
/// <summary> /// Produces a formatted string as specified by the conversion pattern. /// </summary> /// <param name="loggingEvent">the event being logged</param> /// <param name="writer">The TextWriter to write the formatted event to</param> /// <remarks> /// <para> /// Parse the <see cref="T:log4net.Core.LoggingEvent" /> using the patter format /// specified in the <see cref="P:log4net.Layout.PatternLayout.ConversionPattern" /> property. /// </para> /// </remarks> public override void Format(TextWriter writer, LoggingEvent loggingEvent) { if (writer == null) { throw new ArgumentNullException("writer"); } if (loggingEvent == null) { throw new ArgumentNullException("loggingEvent"); } for (PatternConverter patternConverter = m_head; patternConverter != null; patternConverter = patternConverter.Next) { patternConverter.Format(writer, loggingEvent); } }
/// <summary> /// Add <see cref="PatternConverter.Properties"/>, /// call <see cref="IOptionHandler.ActivateOptions"/> /// </summary> /// <param name="conv">serializer to be set up</param> /// <param name="converters">converters to be used collected from parent class</param> /// <param name="arrangement">arrangement to be used collected from parent class</param> /// <param name="fetcher">fetcher to use</param> /// <param name="renderer">renderer to use</param> /// <param name="decorators">decorators to use</param> /// <remarks> /// <para> /// Please note that properties are only supported with log4net 1.2.11 and above. /// </para> /// </remarks> protected virtual void SetUpSerializingConverter(PatternConverter conv, ConverterInfo[] converters, IArrangement arrangement, IRawLayout fetcher, IObjectRenderer renderer, IDecorator[] decorators) { conv.Properties["arrangement"] = arrangement; conv.Properties["converters"] = converters; conv.Properties["fetcher"] = fetcher; conv.Properties["renderer"] = renderer; conv.Properties["decorators"] = decorators; IOptionHandler optionHandler = conv as IOptionHandler; if (optionHandler != null) { optionHandler.ActivateOptions(); } }