Modifying strings with source_span package in dartlang? - dart

I want to transform some parts of my source files with an own transformer in dart.
I have a dart file as input and i want to edit this file.
I know that I can get the contents of the file with:
var content = transform.primaryInput.readAsString(encoding: UTF8);
from inside transformers.
I know also how to find the offset in my source where I want to apply some changes.
Is there some kind of "Cursor"-Style editing Package for strings in Dart?
I want to do some kind of (Pseudo-Code!):
String sourceString = transform.primaryInput.readAsString(encoding: UTF8);
//SourceFile comes from source_span package, could be wrapped by cursor implementation
SourceFile source = new SourceFile(sourceString);
var cursor = new Cursor(sourceFile);
//.jumpTo(int lineNumber, [int columnNumber])
cursor.jumpTo(30);
//deletes the next two chars
cursor.delete(2);
//adds new text after cursor
cursor.write("Hello World!");
//accept sourceSpans for deletion
cursor.delete(sourceSpanObject)
Or is there a better way to change contents of source files in transfomers in dart?

Related

Reading the file lines as locs in Rascal

In the file IO module there is a function that reads the lines from the file.
list[str] fileLines = readFileLines(fileLoc);
The function neatly returns the strings. Each of these strings are also denotable as a loc with the fileLoc(O, L, <BL, BC> , <EL,EC>) format. How can I load the lines from the file as loc resources?
Short answer: The library function readFiles takes a source location as argument and reads the contents of the file. If that source location contains position information then it will only read the part of the file corresponding to that position information.
Somewhat longer answer:
Here is an illustration:
module Example
void main() {
str text = "a\nbc\ndef\n";
loc tmpLoc = |home:///tmp.txt|;
writeFile(tmpLoc, text); // write example text to file
// Read lines back and print them
println("Using readFileLines:");
for(s <- readFileLines(tmpLoc)) println(s);
// Add position information to tmpLoc that corresponds to each of the lines,
// read it back and print it:
println("Using source location with position info:");
println(readFile(tmpLoc[offset=0][length=1]));
println(readFile(tmpLoc[offset=2][length=2]));
println(readFile(tmpLoc[offset=5][length=3]));
}
the expected output is:
Using readFileLines:
a
bc
def
Using source location with position info:
a
bc
def
Final remarks:
Usually position information is generated automatically
by tools (for example a parser); programmers mostly use that information, they don't have to create it (but they can).
Parsers usually generate full line and column information, here we only use offset and length.

How to parse an unconventional file with Talend?

I have a file shape like this :
How can I parse a file like this with Talend Open Studio ?
Here's what I tried :
In the tJavaRow, the input is the whole file in a single row. I split it and parse it manually. But I can't figure out how to create an output row for each OBJ in the file.
Is this the "Right" way of doing it ? Or is there a specific component for this type of files ?
But I can't figure out how to create an output row for each OBJ in the file
You can do this by using the tJavaFlex component:
Put your raw content in the globalMap by connecting it to tFlowToIterate
Put your split-and-parse logic in the "Start Code" part of tJavaFlex, using the contents you made available in step 1
Start a loop in the "Start Code" part of tJavaFlex (e.g. for each object)
Define your output schema in tJavaFlex
In the "Main Code" part of tJavaFlex, map your parsed object to the columns of your output row
Dont forget to close your loop in the "End Code" part of tJavaFlex
I layed out a quick example, with no parsing logic. But since you already got this down, I think it should be sufficient:
Start Code
String[] lines = ((String)globalMap.get("row1.content")).split("\r\n");
for(String line : lines) { // starts the "generating" loop
Main Code
row2.key = line; // uses the "generating" loop
End Code
} // closes the "generating" loop

How to create a DXL attribute using a #included file

I have a file containing attribute dxl. I have created a template that creates a module exactly the way I want it, with new attributes and views and such. One of the attributes needs to be a dxl attribute,but I cannot find a good way to create a new dxl attribute from a dxl script using code contained in a separate file. I thought I might try something like this:
String s = #include "filepath"
But that obviously doesn't work. Is there a way to get the contents of a separate file into a string?
Thanks
You can do this using a Stream.
Stream inFile = read "filepath"
String s, sContent = ""
while(true) {
inFile >> s
sContent = sContent "\n" s
if(end of inFile) break
}
close inFile
This will fill the string sContent with your DXL file contents. Then you can use it to create the attribute.
Updated Code based on feedback.

Create and download word file from template in MVC

I have kept a word document (.docx) in one of the project folders which I want to use as a template.
This template contains custom header and footer lines for user. I want to facilitate user to download his own data in word format. For this, I want to write a function which will accept user data and referring the template it will create a new word file replacing the place-holders in the template and then return the new file for download (without saving it to server). That means the template needs to be intact as template.
Following is what I am trying. I was able to replace the placeholder. However, I am not aware of how to give the created content as downloadable file to user. I do not want to save the new content again in the server as another word file.
public void GenerateWord(string userData)
{
string templateDoc = HttpContext.Current.Server.MapPath("~/App_Data/Template.docx");
// Open the new Package
Package pkg = Package.Open(templateDoc, FileMode.Open, FileAccess.ReadWrite);
// Specify the URI of the part to be read
Uri uri = new Uri("/word/document.xml", UriKind.Relative);
PackagePart part = pkg.GetPart(uri);
XmlDocument xmlMainXMLDoc = new XmlDocument();
xmlMainXMLDoc.Load(part.GetStream(FileMode.Open, FileAccess.Read));
xmlMainXMLDoc.InnerXml = ReplacePlaceHoldersInTemplate(userData, xmlMainXMLDoc.InnerXml);
// Open the stream to write document
StreamWriter partWrt = new StreamWriter(part.GetStream(FileMode.Open, FileAccess.Write));
xmlMainXMLDoc.Save(partWrt);
partWrt.Flush();
partWrt.Close();
pkg.Close();
}
private string ReplacePlaceHoldersInTemplate(string toReplace, string templateBody)
{
templateBody = templateBody.Replace("#myPlaceHolder#", toReplace);
return templateBody;
}
I believe that the below line is saving the contents in the template file itself, which I don't want.
xmlMainXMLDoc.Save(partWrt);
How should I modify this code which can return the new content as downloadable word file to user?
I found the solution Here!
This code allows me to read the template file and modify it as I want and then to send response as downloadable attachment.

Getting list of files

I have a directory named 'import' and would like to get all files and their corresponding date (based on filename). Sample content of the directory is this:
input_02202010.xls
input_02212010.xls
input_02222010.xls
I would like to have a Map that contains the path of the file and a Date variable.
Can anyone show me how Groovy will solve this?
Use new File("/foo/bar/import").list() to get the file names, just like you would in Java. Then create file objects from the strings and check lastModified() for the last modification date.
EDIT:
Groovy adds eachFile() methods to java.io.File, we can use that to make it a bit more groovy...
To extract the date from the filename, use
Date d = new java.text.SimpleDateFormat("MMddyyyy").parse(filename.substring(6,14))
To make it all into a map (using the filename as key and the date as value, though redundant):
def df = new java.text.SimpleDateFormat("MMddyyyy")
def results = [:]
new File("/foo/bar/import").eachFile() { file ->
results.put(file.getName(), df.parse(file.getName().substring(6,14)))
}
results

Resources