change root node label of xtext outline - jface

The default label text of root node is filename. If I created a filename called test.mydsl, it will show test as label. But I want to change is to full filename test.mydsl.
First I override createRoot(IXtextDocument document) to get a IXtextDocument type object, but seems filename information doesn't exist in it.
Second try is simply appending .mydsl in the end of original text. the weird thing is if I override _text(Model model) in the subclass
def _xtext(Model model) { return super._xtext(model) }
Will give original label test as expected. However, if I try to append a string with it, it will fail
def _xtext(Model model) {
val filename = super._xtext(model)
// or cast it to a string
val filename = super._xtext(model) as String
return filename + ".mydsl"
The value of filename is always null. Is the return value of _xtext() something else than String?

You can use a readOnly operation to query the document for the resource and ask that one for its URI. Something like this will do the trick:
myXtextDocument.readOnly(new IUnitOfWork<String, XtextResource>() {
public String exec(XtextResource resource) {
return resource.getURI().lastSegment();
}
});

Nice! Here is my xtend code snippet in outline provider class
override createRoot(IXtextDocument doc) {
filename = doc.readOnly([res|
return res.URI.lastSegment
]);
super.createRoot(doc)
}
and return class member variable filename in def _text(ROOT_NODE_TYPE)

Related

Vue.JS object attribute has 2 values

I'm working on a Vue.JS project and I'm facing a strange error.
I got a WidgetDTO object filled by an axios.get request, it contains a WidgetParametersDTO object and it's defined like so:
export class WidgetParametersDTO {
[...]
public coverage: number = 0;
public colorOK: string = "";
public colorKO: string = "";
public constructor(parameters: any) {
this.coverage = parameters.coverage
this.colorOK = parameters.colorOK;
this.colorKO = parameters.colorKO;
}
}
export class WidgetDTO {
[...]
public id: string = null!;
public parameters: WidgetParametersDTO = null!;
public constructor(widgetDTO: any) {
this.id = widgetDTO.id;
this.parameters = new WidgetParametersDTO(widgetDTO.parameters);
}
When I print the full object widget.parameters, all attributes are correct, when I use widget.parameters.colorOK or widget.parameters.colorKO it works properly, but if I try to use widget.parameters.coverage, it shows 0 instead of the value printed earlier.
The type is correct (number) and I already tried several things to ensure the presence and correctness of the data, it's only acting like that when I use the attribute directly.
There's even more, I'm using npm run dev to be able to hot reload the changes as things progress. When I change some code and save, it reloads the page and prints the right value, but not when I'm hitting F5.
I tried to build the files and run the server with npm start but it didn't work.
Any advice ?
Thanks.

How can the Repast file sink filename be set programmatically?

Does anybody know if there is a simple way to make the filename element path of an file sink variable according to one field in the model?
So instead of using a fix path like :
fixed_path/filename.csv
{variable_path}/filename.csv
The attached ModelInitializer shows how to do this. I also copied the code below in case attachments doesn’t go through. To enable the ModelInitializer, you need to add the following to the scenario.xml file:
<model.initializer class="PredatorPrey.MyInitializer" />
I tested this in the Predator Prey demo so you should change the class package name. In the ModelInitializer example, you need to specify the root context ID which is the same as the context ID in the context.xml file. And you should specify the variable output folder name. This example requires a file name to be specified in the file sink as you would normally do and it inserts the variable path. On caveat is that the variable folder path will be saved in the scenario if the scenario is saved in the GUI, however this code will check for any existing path and simply replace the path with the outputFolder string. So you should put the entire path in the outputFolder string and not just part of it, or change the code behavior as needed.
package PredatorPrey;
import java.io.File;
import repast.simphony.data2.engine.FileSinkComponentControllerAction;
import repast.simphony.data2.engine.FileSinkDescriptor;
import repast.simphony.engine.controller.NullAbstractControllerAction;
import repast.simphony.engine.environment.ControllerAction;
import repast.simphony.engine.environment.RunEnvironmentBuilder;
import repast.simphony.engine.environment.RunState;
import repast.simphony.scenario.ModelInitializer;
import repast.simphony.scenario.Scenario;
import repast.simphony.util.collections.Tree;
public class MyInitializer implements ModelInitializer {
#Override
public void initialize(final Scenario scen, RunEnvironmentBuilder builder) {
scen.addMasterControllerAction(new NullAbstractControllerAction() {
String rootContextID = "Predator Prey";
String outputFolder = "testoutfolder";
#Override
public void batchInitialize(RunState runState, Object contextId) {
Tree<ControllerAction> scenarioTree = scen.getControllerRegistry().getActionTree(rootContextID);
findFileSinkTreeChildren(scenarioTree, scenarioTree.getRoot(), outputFolder);
// Reset the scenario dirty flag so the changes made to the file sink
// descriptors don't prompt a scenario save in the GUI
scen.setDirty(false);
}
});
}
public static void findFileSinkTreeChildren(Tree<ControllerAction> tree,
ControllerAction parent, String outputFolder){
// Check each ControllerAction in the scenario and if it is a FileSink,
// modify the output path to include the folder
for (ControllerAction act : tree.getChildren(parent)){
if (act instanceof FileSinkComponentControllerAction){
FileSinkDescriptor descriptor = ((FileSinkComponentControllerAction)act).getDescriptor();
String fileName = descriptor.getFileName();
// remove any prefix directories from the file name
int lastSeparatorIndex = fileName.lastIndexOf(File.separator);
// Check for backslash separator
if (fileName.lastIndexOf('\\') > lastSeparatorIndex)
lastSeparatorIndex = fileName.lastIndexOf('\\');
// Check for forward slash operator
if (fileName.lastIndexOf('/') > lastSeparatorIndex)
lastSeparatorIndex = fileName.lastIndexOf('/');
if (lastSeparatorIndex > 0){
fileName = fileName.substring(lastSeparatorIndex+1, fileName.length());
}
descriptor.setFileName(outputFolder + File.separator + fileName);
}
else findFileSinkTreeChildren(tree, act, outputFolder);
}
}
}

Akka-http custom 404 page

I'd like to create a custom 404 page in akka-http (high level DSL). This basically means:
Return a page from my static folder (e.g. resources/www/404.html)
Set the result code to ResultCodes.NOT_FOUND
What I tried so far:
getFromResource - I can return the entity, but I can't figure out how to override the HTTP result code for the response, so I can set it to '404'.
complete() - I can return the right code, but I need to read the html page in manually, and build the HttpResponse from ground up. It eventually works, but it's a bit cumbersome.
Am I missing something? Is there an easier way to return a page and customize the result code?
The static page can be returned as the entity of an HttpResponse.
Assuming you have some function of the form
def someFunctionThatCanFail() : Try[HttpResponse] = ???
You will want to use your static page in the event of a failure. You'll first need to create a Source that is based on the static page:
import akka.stream.scaladsl._
import akka.http.scaladsl.model.HttpEntity.Chunked
def createStaticSource(fileName : String) =
FileIO
.fromPath(Paths get fileName)
.map(ChunkStreamPart.apply)
def createChunkedSource(fileName : String) =
Chunked(ContentTypes.`text/html(UTF-8)`, createStaticSource(fileName))
This source can then be placed inside of a response:
def staticResponse =
HttpResponse(status = StatusCodes.NotFound,
entity = createChunkedSource("resources/www/404.html"))
The only thing left to do is to either return the result of the function if it was valid or the static response in the case of a failure:
val route =
get {
complete(someFunctionThatCanFail() getOrElse staticResponse)
}
To expand on Ramon's excellent answer, this works inside a jar file as well:
def createChunkedSource(fileName : String): Chunked = {
def createStaticSource(fileName : String) : Source[ChunkStreamPart, Any] = {
val classLoader = getClass.getClassLoader
StreamConverters.fromInputStream(() => classLoader.getResourceAsStream(fileName)).map(ChunkStreamPart.apply)
}
Chunked(ContentTypes.`text/html(UTF-8)`, createStaticSource(fileName))
}

RazorEngine Error trying to send email

I have an MVC 4 application that sends out multiple emails. For example, I have an email template for submitting an order, a template for cancelling an order, etc...
I have an Email Service with multiple methods. My controller calls the Send method which looks like this:
public virtual void Send(List<string> recipients, string subject, string template, object data)
{
...
string html = GetContent(template, data);
...
}
The Send method calls GetContent, which is the method causing the problem:
private string GetContent(string template, object data)
{
string path = Path.Combine(BaseTemplatePath, string.Format("{0}{1}", template, ".html.cshtml"));
string content = File.ReadAllText(path);
return Engine.Razor.RunCompile(content, "htmlTemplate", null, data);
}
I am receiving the error:
The same key was already used for another template!
In my GetContent method should I add a new parameter for the TemplateKey and use that variable instead of always using htmlTemplate? Then the new order email template could have newOrderKey and CancelOrderKey for the email template being used to cancel an order?
Explanation
This happens because you use the same template key ("htmlTemplate") for multiple different templates.
Note that the way you currently have implemented GetContent you will run into multiple problems:
Even if you use a unique key, for example the template variable, you will trigger the exception when the templates are edited on disk.
Performance: You are reading the template file every time even when the template is already cached.
Solution:
Implement the ITemplateManager interface to manage your templates:
public class MyTemplateManager : ITemplateManager
{
private readonly string baseTemplatePath;
public MyTemplateManager(string basePath) {
baseTemplatePath = basePath;
}
public ITemplateSource Resolve(ITemplateKey key)
{
string template = key.Name;
string path = Path.Combine(baseTemplatePath, string.Format("{0}{1}", template, ".html.cshtml"));
string content = File.ReadAllText(path);
return new LoadedTemplateSource(content, path);
}
public ITemplateKey GetKey(string name, ResolveType resolveType, ITemplateKey context)
{
return new NameOnlyTemplateKey(name, resolveType, context);
}
public void AddDynamic(ITemplateKey key, ITemplateSource source)
{
throw new NotImplementedException("dynamic templates are not supported!");
}
}
Setup on startup:
var config = new TemplateServiceConfiguration();
config.Debug = true;
config.TemplateManager = new MyTemplateManager(BaseTemplatePath);
Engine.Razor = RazorEngineService.Create(config);
And use it:
// You don't really need this method anymore.
private string GetContent(string template, object data)
{
return Engine.Razor.RunCompile(template, null, data);
}
RazorEngine will now fix all the problems mentioned above internally. Notice how it is perfectly fine to use the name of the template as key, if in your scenario the name is all you need to identify a template (otherwise you cannot use NameOnlyTemplateKey and need to provide your own implementation).
Hope this helps.
(Disclaimer: Contributor of RazorEngine)

My Nintex Custom Action not reading in Workflow Variable in SingleLineInput

I've written a custom workflow action that takes in several values, mostly using the SingleLineInput control.
When I assign literal values, I have no issues, but when I try to assign a Workflow Variable, I don't get the actual value of the variable, I get the literal text - something like {WorkflowVariable:XmlValue} - assuming my variable was names XmlValue.
I'm not sure what I could possibly be doing wrong. Any ideas?
Here's code snippets:
The javascript for retrieving the value from the SingleLineInput
function TPAWriteConfig() {
configXml.selectSingleNode("/NWActionConfig/Parameters/Parameter[#Name='FieldValue']/PrimitiveValue/#Value").text = getRTEValue('<%=fieldValue.ClientID%>');
SaveErrorHandlingSection();
return true;
}
The server control:
<Nintex:ConfigurationProperty ID="ConfigurationProperty3" runat="server" FieldTitle="Field Value" RequiredField="True">
<TemplateControlArea>
<Nintex:SingleLineInput runat="server" id="fieldValue"></Nintex:SingleLineInput>
</TemplateControlArea>
</Nintex:ConfigurationProperty>
From my adapter class:
private const string FieldValueProperty = "FieldValue";
NWActionConfig config = new NWActionConfig(this);
config.Parameters[2] = new ActivityParameter();
config.Parameters[2].Name = FieldValueProperty;
config.Parameters[2].PrimitiveValue = new PrimitiveValue();
config.Parameters[2].PrimitiveValue.Value = string.Empty;
config.Parameters[2].PrimitiveValue.ValueType = SPFieldType.Text.ToString();
From the activity class:
public static DependencyProperty FieldValueProperty = DependencyProperty.Register("FieldValue", typeof (string),
typeof (
WriteOnePdfFieldActivity));
public string FieldValue
{
get { return (string) GetValue(FieldValueProperty); }
set { SetValue(FieldValueProperty, value); }
}
I feel a little silly answering my own question, but for the sake of anyone else having the same issues. Here's how it works:
If you're putting a literal value in the field, just use the value
If you're using any other kind of assignment, do a lookup based on the value.
The code below demonstrates:
var fieldValue = FieldValue.StartsWith("{") ? ctx.AddContextDataToString(FieldValue, true) : FieldValue;
This extract the value from the workflow context. Hope this helps.