private void WriteReplaceOperation(BinaryWriter writer, IOperation operation) { ReplaceOperation opr = (ReplaceOperation)operation; KeyPersist.Write(writer, opr.FromKey); RecordPersist.Write(writer, opr.Record); }
private bool Replace(IOrderedSet <IData, IData> set, ReplaceOperation operation) { Debug.Assert(operation.Scope == OperationScope.Point); long from = ((Data <long>)operation.FromKey).Value; int localFrom = (int)(from % BLOCK_SIZE); long baseFrom = from - localFrom; Data <long> baseKey = new Data <long>(baseFrom); byte[] src = ((Data <byte[]>)operation.Record).Value; Debug.Assert(src.Length <= BLOCK_SIZE); Debug.Assert(baseFrom == BLOCK_SIZE * ((from + src.Length - 1) / BLOCK_SIZE)); IData tmp; if (set.TryGetValue(baseKey, out tmp)) { Data <byte[]> rec = (Data <byte[]>)tmp; if (localFrom == 0 && src.Length >= rec.Value.Length) { rec.Value = src; } else { Debug.Assert(src.Length < BLOCK_SIZE); byte[] dst = rec.Value; if (dst.Length > localFrom + src.Length) { src.CopyTo(dst, localFrom); } else { byte[] buffer = new byte[localFrom + src.Length]; dst.CopyTo(buffer, 0); src.CopyTo(buffer, localFrom); rec.Value = buffer; } } } else // if element with baseKey is not found { if (localFrom == 0) { set[baseKey] = new Data <byte[]>(src); } else { byte[] values = new byte[localFrom + src.Length]; src.CopyTo(values, localFrom); set[baseKey] = new Data <byte[]>(values); } } return(true); }
/// <summary> /// Check if the current tokens match with the comparison tokens of the current replace operation /// </summary> private bool TryMatchReplaceOperation(Token originalToken, ReplaceOperation replaceOperation, out IList <Token> originalMatchingTokens) { // Check if the first token matches the replace pattern if (originalToken.CompareForReplace(replaceOperation.ComparisonToken)) { // Multiple tokens pattern => check if the following tokens returned by the underlying iterator all match the pattern if (replaceOperation.Type == ReplaceOperationType.MultipleTokens) { MultipleTokensReplaceOperation multipleTokensReplaceOperation = (MultipleTokensReplaceOperation)replaceOperation; originalMatchingTokens = new List <Token>(); originalMatchingTokens.Add(originalToken); sourceIterator.SaveCurrentPositionSnapshot(); bool comparisonInterrupted = false; foreach (Token comparisonToken in multipleTokensReplaceOperation.FollowingComparisonTokens) { Token nextCandidateToken = sourceIterator.NextToken(); if (!comparisonToken.CompareForReplace(nextCandidateToken)) { comparisonInterrupted = true; break; } else { originalMatchingTokens.Add(nextCandidateToken); } } // The following tokens did not match if (comparisonInterrupted) { // Restore the uderlying iterator position sourceIterator.ReturnToLastPositionSnapshot(); // Match failed originalMatchingTokens = null; return(false); } // Multiple tokens match OK else { return(true); } } // Single token comparison => match OK else { originalMatchingTokens = null; return(true); } } // First token does not match else { originalMatchingTokens = null; return(false); } }
//Methods View private void ReplaceMethodWindowButton_Click(object sender, RoutedEventArgs e) { var screen = new ReplaceMethodWindow(); if (screen.ShowDialog() == true) { var action = new ReplaceOperation() { Args = new ReplaceArgs() { From = ReplaceMethodWindow.replaceFrom, To = ReplaceMethodWindow.replaceTo } }; actions.Add(action.Clone()); } }
/// <summary> /// Replaces an existing value with a new value. /// </summary> /// <typeparam name="V">Data type of Value</typeparam> /// <typeparam name="K">Data type of Key</typeparam> /// <param name="key">key</param> /// <param name="val">value</param> /// <param name="lifespaninMillis">Lifespan in milliseconds</param> /// <param name="maxIdleTimeinMillis">Maximum idle time in milliseconds</param> public V replace <V, K>(K key, V val, int lifespaninMillis, int maxIdleTimeinMillis) { int lifespanSecs = TimeSpan.FromMilliseconds(lifespaninMillis).Seconds; int maxIdleSecs = TimeSpan.FromMilliseconds(maxIdleTimeinMillis).Seconds; ReplaceOperation op = operationsFactory.newReplaceOperation(serializer.serialize(key), serializer.serialize(val), lifespanSecs, maxIdleSecs); transport = transportFactory.getTransport(); try { } finally { transportFactory.releaseTransport(transport); } byte[] bytes = (byte[])op.executeOperation(transport); return((V)serializer.deserialize(bytes)); }
private ReplaceStatus TryAndReplace(Token nextToken, ReplaceOperation replaceOperation) { ReplaceStatus status = new ReplaceStatus(); IList <Token> originalMatchingTokens; #if EUROINFO_RULES if (CompilerOptions.UseEuroInformationLegacyReplacingSyntax) { // Support for legacy replacing syntax semantics : // Insert Suffix before the first '-' in all user defined words found in the COPY text // before copying it into the main program if (CopyReplacingDirective != null && CopyReplacingDirective.InsertSuffixChar && nextToken.TokenType == TokenType.UserDefinedWord) { string originalText = nextToken.Text; if (originalText.Contains(CopyReplacingDirective.PreSuffix)) { string replacedText = originalText.Replace(CopyReplacingDirective.PreSuffix, CopyReplacingDirective.PreSuffix.Insert(3, CopyReplacingDirective.Suffix)); TokensLine virtualTokensLine = TokensLine.CreateVirtualLineForInsertedToken(0, replacedText); Token replacementToken = new Token(TokenType.UserDefinedWord, 0, replacedText.Length - 1, virtualTokensLine); status.replacedToken = new ReplacedToken(replacementToken, nextToken); currentPosition.CurrentToken = status.replacedToken; } } } #endif if (replaceOperation != null && TryMatchReplaceOperation(nextToken, replaceOperation, out originalMatchingTokens)) { status.replacedToken = CreateReplacedTokens(nextToken, replaceOperation, originalMatchingTokens); if (status.replacedToken != null) { // REPLACE pattern matched => return the first replaced token currentPosition.CurrentToken = status.replacedToken; } else { // If the replacement token set is empty (REPLACE == ... = BY == ==), get next token and try again status.tryAgain = true; } } return(status); }
private void Window_Loaded(object sender, RoutedEventArgs e) { var _prototype1 = new ReplaceOperation() { Args = new ReplaceArgs() { From = "origin string", To = "new string" } }; _prototype.Add(_prototype1); prototypeMethodCobobox.ItemsSource = _prototype; operationListBox.ItemsSource = _action; var _prototype2 = new ISBNOperation() { Args = new ISBNArgs() { Direction = "before" } }; _prototype.Add(_prototype2); prototypeMethodCobobox.ItemsSource = _prototype; operationListBox.ItemsSource = _action; var _prototype3 = new UniqueOperation() { }; _prototype.Add(_prototype3); prototypeMethodCobobox.ItemsSource = _prototype; operationListBox.ItemsSource = _action; // ADD file fileView.ItemsSource = _fileName; // ADD folder folderView.ItemsSource = _folderName; presetComboBox.ItemsSource = _preset; }
public void executeOperationTest() { TCPTransport trans = new TCPTransport(System.Net.IPAddress.Loopback, 11222); Codec codec = new Codec(); Serializer s = new DefaultSerializer(); byte[] key = s.serialize("key10"); byte[] value = s.serialize("trinitrotoluene"); byte[] cacheName = null; int topologyId = 0; Flag[] flags = null; int lifespan = 0; int maxIdle = 0; ReplaceOperation target = new ReplaceOperation(codec, key, cacheName, topologyId, flags, value, lifespan, maxIdle); Transport transport = trans; byte[] expected = null; byte[] actual; actual = target.executeOperation(transport); Assert.AreEqual(expected, actual); }
protected abstract TDoc Replace(ReplaceOperation operation, TDoc target);
private void LoadListMethods_Click(object sender, RoutedEventArgs e) { string text = ""; OpenFileDialog openFileDialog = new OpenFileDialog(); if (openFileDialog.ShowDialog() == true) { text = System.IO.File.ReadAllText(openFileDialog.FileName); string[] textpart = text.Split('\n'); int numberofMethods = int.Parse(textpart[0]); for (int i = 1; i <= numberofMethods; i++) { string[] textpartoftextpart = textpart[i].Split(' '); if (textpartoftextpart[0] == "Replace") { var action = new ReplaceOperation() { Args = new ReplaceArgs() { From = textpartoftextpart[1], To = textpartoftextpart[2] } }; actions.Add(action.Clone()); } if (textpartoftextpart[0] == "NewCase") { var action = new NewCaseOperation() { Args = new NewCaseArgs() { From = textpartoftextpart[1], To = textpartoftextpart[2] } }; actions.Add(action.Clone()); } if (textpartoftextpart[0] == "FullNameNormalize") { var action = new FullNameOperation() { Args = new FullNameArgs() { From = textpartoftextpart[1], To = textpartoftextpart[2] } }; actions.Add(action.Clone()); } if (textpartoftextpart[0] == "Move") { var action = new MoveOperation() { Args = new MoveArgs() { From = textpartoftextpart[1], To = textpartoftextpart[2] } }; actions.Add(action.Clone()); } if (textpartoftextpart[0] == "UniqueName") { var action = new UniqueNameOperation() { Args = new UniqueNameArgs() { From = textpartoftextpart[1], To = textpartoftextpart[2] } }; actions.Add(action.Clone()); } } } }
private void ApplyPatch(int patchIndex, AssetLocation patchSourcefile, JsonPatch jsonPatch, ref int applied, ref int notFound, ref int errorCount) { EnumAppSide targetSide = jsonPatch.Side == null ? jsonPatch.File.Category.SideType : (EnumAppSide)jsonPatch.Side; if (targetSide != EnumAppSide.Universal && jsonPatch.Side != api.Side) { return; } var loc = jsonPatch.File.Clone(); if (jsonPatch.File.Path.EndsWith("*")) { List <IAsset> assets = api.Assets.GetMany(jsonPatch.File.Path.TrimEnd('*'), jsonPatch.File.Domain, false); foreach (var val in assets) { jsonPatch.File = val.Location; ApplyPatch(patchIndex, patchSourcefile, jsonPatch, ref applied, ref notFound, ref errorCount); } jsonPatch.File = loc; return; } if (!loc.Path.EndsWith(".json")) { loc.Path += ".json"; } var asset = api.Assets.TryGet(loc); if (asset == null) { if (jsonPatch.File.Category == null) { api.World.Logger.VerboseDebug("Patch {0} in {1}: File {2} not found. Wrong asset category", patchIndex, patchSourcefile, loc); } else { EnumAppSide catSide = jsonPatch.File.Category.SideType; if (catSide != EnumAppSide.Universal && api.Side != catSide) { api.World.Logger.VerboseDebug("Patch {0} in {1}: File {2} not found. Hint: This asset is usually only loaded {3} side", patchIndex, patchSourcefile, loc, catSide); } else { api.World.Logger.VerboseDebug("Patch {0} in {1}: File {2} not found", patchIndex, patchSourcefile, loc); } } notFound++; return; } Operation op = null; switch (jsonPatch.Op) { case EnumJsonPatchOp.Add: if (jsonPatch.Value == null) { api.World.Logger.Error("Patch {0} in {1} failed probably because it is an add operation and the value property is not set or misspelled", patchIndex, patchSourcefile); errorCount++; return; } op = new AddOperation() { Path = new Tavis.JsonPointer(jsonPatch.Path), Value = jsonPatch.Value.Token }; break; case EnumJsonPatchOp.Remove: op = new RemoveOperation() { Path = new Tavis.JsonPointer(jsonPatch.Path) }; break; case EnumJsonPatchOp.Replace: if (jsonPatch.Value == null) { api.World.Logger.Error("Patch {0} in {1} failed probably because it is a replace operation and the value property is not set or misspelled", patchIndex, patchSourcefile); errorCount++; return; } op = new ReplaceOperation() { Path = new Tavis.JsonPointer(jsonPatch.Path), Value = jsonPatch.Value.Token }; break; case EnumJsonPatchOp.Copy: op = new CopyOperation() { Path = new Tavis.JsonPointer(jsonPatch.Path), FromPath = new JsonPointer(jsonPatch.FromPath) }; break; case EnumJsonPatchOp.Move: op = new MoveOperation() { Path = new Tavis.JsonPointer(jsonPatch.Path), FromPath = new JsonPointer(jsonPatch.FromPath) }; break; } PatchDocument patchdoc = new PatchDocument(op); JToken token = null; try { token = JToken.Parse(asset.ToText()); } catch (Exception e) { api.World.Logger.Error("Patch {0} (target: {3}) in {1} failed probably because the syntax of the value is broken: {2}", patchIndex, patchSourcefile, e, loc); errorCount++; return; } try { patchdoc.ApplyTo(token); } catch (Tavis.PathNotFoundException p) { api.World.Logger.Error("Patch {0} (target: {4}) in {1} failed because supplied path {2} is invalid: {3}", patchIndex, patchSourcefile, jsonPatch.Path, p.Message, loc); errorCount++; return; } catch (Exception e) { api.World.Logger.Error("Patch {0} (target: {3}) in {1} failed, following Exception was thrown: {2}", patchIndex, patchSourcefile, e.Message, loc); errorCount++; return; } string text = token.ToString(); asset.Data = System.Text.Encoding.UTF8.GetBytes(text); applied++; }
private void ApplyPatch(int patchIndex, AssetLocation patchSourcefile, JsonPatch jsonPatch, ref int applied, ref int notFound, ref int errorCount) { if (jsonPatch.SideType != EnumAppSide.Universal && jsonPatch.SideType != api.Side) { return; } var path = jsonPatch.File.Path; if (!path.EndsWith(".json")) { path += ".json"; } var asset = api.Assets.TryGet(path); if (asset == null) { api.World.Logger.VerboseDebug("Patch {0} in {1}: File {2} not found", patchIndex, patchSourcefile, path); notFound++; return; } Operation op = null; switch (jsonPatch.Op) { case EnumJsonPatchOp.Add: if (jsonPatch.Value == null) { api.World.Logger.Error("Patch {0} in {1} failed probably because it is an add operation and the value property is not set or misspelled", patchIndex, patchSourcefile); errorCount++; return; } op = new AddOperation() { Path = new Tavis.JsonPointer(jsonPatch.Path), Value = jsonPatch.Value.Token }; break; case EnumJsonPatchOp.Remove: op = new RemoveOperation() { Path = new Tavis.JsonPointer(jsonPatch.Path) }; break; case EnumJsonPatchOp.Replace: if (jsonPatch.Value == null) { api.World.Logger.Error("Patch {0} in {1} failed probably because it is a replace operation and the value property is not set or misspelled", patchIndex, patchSourcefile); errorCount++; return; } op = new ReplaceOperation() { Path = new Tavis.JsonPointer(jsonPatch.Path), Value = jsonPatch.Value.Token }; break; case EnumJsonPatchOp.Copy: op = new CopyOperation() { Path = new Tavis.JsonPointer(jsonPatch.Path), FromPath = new JsonPointer(jsonPatch.FromPath) }; break; case EnumJsonPatchOp.Move: op = new MoveOperation() { Path = new Tavis.JsonPointer(jsonPatch.Path), FromPath = new JsonPointer(jsonPatch.FromPath) }; break; } PatchDocument patchdoc = new PatchDocument(op); JToken token = null; try { token = JToken.Parse(asset.ToText()); } catch (Exception e) { api.World.Logger.Error("Patch {0} in {1} failed probably because the syntax of the value is broken: {2}", patchIndex, patchSourcefile, e); errorCount++; return; } try { patchdoc.ApplyTo(token); } catch (Tavis.PathNotFoundException p) { api.World.Logger.Error("Patch {0} in {1} failed because supplied path {2} is invalid: {3}", patchIndex, patchSourcefile, jsonPatch.Path, p.Message); errorCount++; return; } catch (Exception e) { api.World.Logger.Error("Patch {0} in {1} failed, following Exception was thrown: {2}", patchIndex, patchSourcefile, e.Message); errorCount++; return; } string text = token.ToString(); asset.Data = System.Text.Encoding.UTF8.GetBytes(text); applied++; }
/// <summary> /// Create replaced tokens for all matched tokens /// (a ReplacedToken references both the original token and the replacement token) /// </summary> private Token CreateReplacedTokens(Token originalToken, ReplaceOperation replaceOperation, IList <Token> originalMatchingTokens) { switch (replaceOperation.Type) { // One comparison token => zero or one replacement token case ReplaceOperationType.SingleToken: SingleTokenReplaceOperation singleTokenReplaceOperation = (SingleTokenReplaceOperation)replaceOperation; if (singleTokenReplaceOperation.ReplacementToken != null) { ReplacedToken replacedToken = new ReplacedToken(singleTokenReplaceOperation.ReplacementToken, originalToken); return(replacedToken); } else { return(null); } // One pure partial word => one replacement token case ReplaceOperationType.PartialWord: PartialWordReplaceOperation partialWordReplaceOperation = (PartialWordReplaceOperation)replaceOperation; string originalTokenText = originalToken.Text; string partToReplace = partialWordReplaceOperation.ComparisonToken.Text; //#258 - PartialReplacementToken can be null. In this case, we consider that it's an empty replacement var replacementPart = partialWordReplaceOperation.PartialReplacementToken != null ? partialWordReplaceOperation.PartialReplacementToken.Text : ""; // The index below is always >= 0 because CompareForReplace() above was true int indexOfPartToReplace = originalTokenText.IndexOf(partToReplace, StringComparison.OrdinalIgnoreCase); string replacedTokenText = (indexOfPartToReplace > 0 ? originalTokenText.Substring(0, indexOfPartToReplace) : String.Empty) + replacementPart + ((indexOfPartToReplace + partToReplace.Length) < (originalTokenText.Length) ? originalTokenText.Substring(indexOfPartToReplace + partToReplace.Length) : String.Empty); // TO DO : find a way to transfer the scanner context the of original token to the call below Diagnostic error = null; Token generatedToken = Scanner.Scanner.ScanIsolatedTokenInDefaultContext(replacedTokenText, out error); // TO DO : find a way to report the error above ... if (originalToken.PreviousTokenType != null) //In case orignal token was previously an other type of token reset it back to it's orignal type. { generatedToken.TokenType = originalToken.PreviousTokenType.Value; } ReplacedPartialCobolWord replacedPartialCobolWord = new ReplacedPartialCobolWord(generatedToken, partialWordReplaceOperation.PartialReplacementToken, originalToken); return(replacedPartialCobolWord); // One comparison token => more than one replacement tokens case ReplaceOperationType.SingleToMultipleTokens: SingleToMultipleTokensReplaceOperation singleToMultipleTokensReplaceOperation = (SingleToMultipleTokensReplaceOperation)replaceOperation; currentPosition.ReplacementTokensBeingReturned = new Token[singleToMultipleTokensReplaceOperation.ReplacementTokens.Length]; int i = 0; foreach (Token replacementToken in singleToMultipleTokensReplaceOperation.ReplacementTokens) { currentPosition.ReplacementTokensBeingReturned[i] = new ReplacedToken(replacementToken, originalToken); i++; } currentPosition.ReplacementTokenIndexLastReturned = 0; return(currentPosition.ReplacementTokensBeingReturned[currentPosition.ReplacementTokenIndexLastReturned]); // One first + several following comparison tokens => zero to many replacement tokens //case ReplaceOperationType.MultipleTokens: default: MultipleTokensReplaceOperation multipleTokensReplaceOperation = (MultipleTokensReplaceOperation)replaceOperation; if (multipleTokensReplaceOperation.ReplacementTokens != null) { if (multipleTokensReplaceOperation.ReplacementTokens.Length == 1) { ReplacedTokenGroup replacedTokenGroup = new ReplacedTokenGroup(multipleTokensReplaceOperation.ReplacementTokens[0], originalMatchingTokens); return(replacedTokenGroup); } else { currentPosition.ReplacementTokensBeingReturned = new Token[multipleTokensReplaceOperation.ReplacementTokens.Length]; i = 0; foreach (Token replacementToken in multipleTokensReplaceOperation.ReplacementTokens) { currentPosition.ReplacementTokensBeingReturned[i] = new ReplacedTokenGroup(replacementToken, originalMatchingTokens); i++; } currentPosition.ReplacementTokenIndexLastReturned = 0; return(currentPosition.ReplacementTokensBeingReturned[currentPosition.ReplacementTokenIndexLastReturned]); } } else { return(null); } } }
private static void BuildReplaceOperation(IList <ReplaceOperation> replaceOperations, ref Token comparisonToken, ref Token[] followingComparisonTokens, ref Token replacementToken, ref Token[] replacementTokens, ref int pseudoTextIndex, IList <IToken> operandTokens) { // Comparison tokens if (pseudoTextIndex % 2 == 0) { if (operandTokens != null && operandTokens.Count > 0) { comparisonToken = (Token)operandTokens[0]; if (operandTokens.Count > 1) { followingComparisonTokens = new Token[operandTokens.Count - 1]; for (int i = 1; i < operandTokens.Count; i++) { followingComparisonTokens[i - 1] = (Token)operandTokens[i]; } } } pseudoTextIndex++; } // Replacement tokens else { if (operandTokens != null && operandTokens.Count > 0) { if (followingComparisonTokens == null && operandTokens.Count == 1) { replacementToken = (Token)operandTokens[0]; } else { replacementTokens = new Token[operandTokens.Count]; for (int i = 0; i < operandTokens.Count; i++) { replacementTokens[i] = (Token)operandTokens[i]; } } } // Build replace operation ReplaceOperation replaceOperation = null; if (followingComparisonTokens == null) { if (replacementTokens == null) { if (comparisonToken == null || comparisonToken.TokenType != TokenType.PartialCobolWord) { replaceOperation = new SingleTokenReplaceOperation(comparisonToken, replacementToken); } else { replaceOperation = new PartialWordReplaceOperation(comparisonToken, replacementToken); } } else { replaceOperation = new SingleToMultipleTokensReplaceOperation(comparisonToken, replacementTokens); } } else { replaceOperation = new MultipleTokensReplaceOperation(comparisonToken, followingComparisonTokens, replacementTokens); } replaceOperations.Add(replaceOperation); // Reset everything for the next replace operation pseudoTextIndex = 0; comparisonToken = null; followingComparisonTokens = null; replacementToken = null; replacementTokens = null; } }
protected abstract void Replace(ReplaceOperation operation);
private void WriteReplaceOperation(BinaryWriter writer, ReplaceOperation operation) { KeyPersist.Write(writer, operation.FromKey); RecordPersist.Write(writer, operation.Record); }