When I try to load my application in Vaadin 14 I see a blank screen like this...
It appears that the servlet container is in fact running but it cannot host some static resources...
When I look in the network tab in the Chrome inspector I see it cannot find a few files such as
http://localhost:8080/VAADIN/static/client/client-122CE29AC0B9685B4DC485343E774096.cache.js
I am unsure why this would be. Any ideas?
UPDATE:
It appears I have to manually ensure all of my .jar files get added as resources in jetty so the static content can be served. I tried doing this like so and it works fine on my laptop but not on the server...
public class App {
public static void main(String[] args) throws Exception {
final var server = new Server(8080);
// Specifies the order in which the configurations are scanned.
Configuration.ClassList classlist = Configuration.ClassList.setServerDefault(server);
classlist.addAfter("org.eclipse.jetty.webapp.FragmentConfiguration", "org.eclipse.jetty.plus.webapp.EnvConfiguration", "org.eclipse.jetty.plus.webapp.PlusConfiguration");
classlist.addBefore("org.eclipse.jetty.webapp.JettyWebXmlConfiguration", "org.eclipse.jetty.annotations.AnnotationConfiguration");
// Creation of a temporal directory.
File tempDir = new File(System.getProperty("java.io.tmpdir"), "JettyTest");
if (tempDir.exists()) {
if (!tempDir.isDirectory()) {
throw new RuntimeException("Not a directory: " + tempDir);
}
} else if (!tempDir.mkdirs()) {
throw new RuntimeException("Could not make: " + tempDir);
}
WebAppContext context = new WebAppContext();
context.setInitParameter("productionMode", "false");
// Context path of the application.
context.setContextPath("");
// Exploded war or not.
context.setExtractWAR(false);
context.setTempDirectory(tempDir);
// It pulls the respective config from the VaadinServlet.
context.addServlet(GuiceVaadinServlet.class, "/*").setInitOrder(1);
context.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", ".*");
context.setParentLoaderPriority(true);
server.setHandler(context);
// This add jars to the jetty classpath in a certain syntax and the pattern makes sure to load all of them.
final var classpathEntries = ClassPathHelper.getAllClassPathEntries();
final var ideMode = classpathEntries.size() > 1;
final var resourceList = new ArrayList<Resource>();
final var jarFiles = new ArrayList<File>();
if (ideMode) {
System.out.println("Starting in IDE Mode");
for (String entry : ClassPathHelper.getAllClassPathEntries()) {
if (entry.endsWith(".jar")) {
final var file = new File(entry);
jarFiles.add(file);
}
}
} else {
final var baseInstallDir = System.getProperty("user.dir");
System.out.println("Starting in Server WebJar Mode");
final var libsDirectory = new File(baseInstallDir, "lib");
System.out.println("Scanning for jars in " + libsDirectory.getPath());
for (File file : Objects.requireNonNull(libsDirectory.listFiles())) {
if (file.getPath().endsWith(".jar")) {
jarFiles.add(file);
}
}
final var sferionJar = new File(baseInstallDir, "sferion.jar");
jarFiles.add(sferionJar);
System.out.println("Found " + jarFiles.size() + " jar files");
}
for (File jarFile : jarFiles) {
resourceList.add(Resource.newResource("jar:" + jarFile.toURI().toURL() + "!/"));
}
if (ideMode) {
// It adds the web application resources. Styles, client-side components, ...
//TODO: make this property dynamic somehow?
resourceList.add(Resource.newResource("/usr/local/code/sferion/planglobal/src/main/webapp"));
}
// The base resource is where jetty serves its static content from.
context.setBaseResource(new ResourceCollection(resourceList.toArray(new Resource[0])));
server.start();
server.join();
}
}
Related
I am creating an azure function application to validate xml files using a zip folder of schematron files.
I have run into a compatibility issue with how the URI's for the files are being created between mac and windows.
The files are downloaded from a zip on azure blob storage and then extracted to the functions local storage.
When the a colleague runs the transform method of the saxon cs api on a windows machine the method is able to run the first transformation and produce the stage 1.out file, however on the second transformation the transform method throws an exception stating that it cannot find the file even though it is present on the temp directory.
On mac the URI is /var/folders/6_/3x594vpn6z1fjclc0vx4v89m0000gn/T and on windows it is trying to find it at file:///C:/Users/44741/AppData/Local/Temp/ but the library is unable to find the file on the windows machine even if it is moved out of temp storage.
Unable to retrieve URI file:///C:/Users/44741/Desktop/files/stage1.out
The file is present at this location but for some reason the library cannot pick it up on the windows machine but it works fine on my mac. I am using Path.Combine to build the URI.
Has anyone else ran into this issue before?
The code being used for the transformations is below.
{
try
{
var transform = new Transform();
transform.doTransform(GetTransformArguments(arguments[Constants.InStage1File],
arguments[Constants.SourceDir] + "/" + schematronFile, arguments[Constants.Stage1Out]));
transform.doTransform(GetTransformArguments(arguments[Constants.InStage2File], arguments[Constants.Stage1Out],
arguments[Constants.Stage2Out]));
transform.doTransform(GetFinalTransformArguments(arguments[Constants.InStage3File], arguments[Constants.Stage2Out],
arguments[Constants.Stage3Out]));
Log.Information("Stage 3 out file written to : " + arguments[Constants.Stage3Out]);;
return true;
}
catch (FileNotFoundException ex)
{
Log.Warning("Cannot find files" + ex);
return false;
}
}
private static string[] GetTransformArguments(string xslFile, string inputFile, string outputFile)
{
return new[]
{
"-xsl:" + xslFile,
"-s:" + inputFile,
"-o:" + outputFile
};
}
private static string[] GetFinalTransformArguments(string xslFile, string inputFile, string outputFile)
{
return new[]
{
"-xsl:" + xslFile,
"-s:" + inputFile,
"-o:" + outputFile,
"allow-foreign=true",
"generate-fired-rule=true"
};
}```
So assuming the intermediary results are not needed as files but you just want the result (I assume that is the Schematron schema compiled to XSLT) you could try to run XSLT 3.0 using the API of SaxonCS (using Saxon.Api) by compiling and chaining your three stylesheets with e.g.
using Saxon.Api;
string isoSchematronDir = #"C:\SomePath\SomeDir\iso-schematron-xslt2";
string[] isoSchematronXslts = { "iso_dsdl_include.xsl", "iso_abstract_expand.xsl", "iso_svrl_for_xslt2.xsl" };
Processor processor = new(true);
var xsltCompiler = processor.NewXsltCompiler();
var baseUri = new Uri(Path.Combine(isoSchematronDir, isoSchematronXslts[2]));
xsltCompiler.BaseUri = baseUri;
var isoSchematronStages = isoSchematronXslts.Select(xslt => xsltCompiler.Compile(new Uri(baseUri, xslt)).Load30()).ToList();
isoSchematronStages[2].SetStylesheetParameters(new Dictionary<QName, XdmValue>() { { new QName("allow-foreign"), new XdmAtomicValue(true) } });
using (var schematronIs = File.OpenRead("price.sch"))
{
using (var compiledOs = File.OpenWrite("price.sch.xsl"))
{
isoSchematronStages[0].ApplyTemplates(
schematronIs,
isoSchematronStages[1].AsDocumentDestination(
isoSchematronStages[2].AsDocumentDestination(processor.NewSerializer(compiledOs)
)
);
}
}
If you only need the compiled Schematron to apply it further to validate an XML instance document against that Schematron you could even store the Schematron as an XdmDestination whose XdmNode you feed to XsltCompiler e.g.
using Saxon.Api;
string isoSchematronDir = #"C:\SomePath\SomeDir\iso-schematron-xslt2";
string[] isoSchematronXslts = { "iso_dsdl_include.xsl", "iso_abstract_expand.xsl", "iso_svrl_for_xslt2.xsl" };
Processor processor = new(true);
var xsltCompiler = processor.NewXsltCompiler();
var baseUri = new Uri(Path.Combine(isoSchematronDir, isoSchematronXslts[2]));
xsltCompiler.BaseUri = baseUri;
var isoSchematronStages = isoSchematronXslts.Select(xslt => xsltCompiler.Compile(new Uri(baseUri, xslt)).Load30()).ToList();
isoSchematronStages[2].SetStylesheetParameters(new Dictionary<QName, XdmValue>() { { new QName("allow-foreign"), new XdmAtomicValue(true) } });
var compiledSchematronXslt = new XdmDestination();
using (var schematronIs = File.OpenRead("price.sch"))
{
isoSchematronStages[0].ApplyTemplates(
schematronIs,
isoSchematronStages[1].AsDocumentDestination(
isoSchematronStages[2].AsDocumentDestination(compiledSchematronXslt)
)
);
}
var schematronValidator = xsltCompiler.Compile(compiledSchematronXslt.XdmNode).Load30();
using (var sampleIs = File.OpenRead("books.xml"))
{
schematronValidator.ApplyTemplates(sampleIs, processor.NewSerializer(Console.Out));
}
The last example writes the XSLT/Schematron validation SVRL output to the console but could of course also write it to a file.
I want to add files to a list and then access them in a for loop. This is how I try to do it:
private get_app_list () {
var file = new File.new_for_path (/usr/share/applications);
List<File> app_list = new List<File> ();
foreach (File desktop_file in app_list) {
// other code here
}
}
What is the right way to access files stored in a directory and then add them to a list??
using Posix;
...
List<File> app_list = new List<File> ();
//Open directory. Returns null on error
var dirHandle = Posix.opendir("/usr/share/applications");
unowned DirEnt entry;
//While there is an entry to read in the directory
while((entry = readdir(dir)) != null) {
//Get the name
var name = (string) entry.d_name;
//And add a new file to the app_list
app_list.add(new File.new_for_path("/usr/share/applications"+name);
}
If you want to merely display the available apps on system, you could use the utilities supplied by the Gio-2.0 lib. After adding dependency ('gio-2.0'), to your meson.build file you could use code similar to the following:
/* We use a `GListStore` here, which is a simple array-like list implementation
* for manual management.
* List models need to know what type of data they provide, so we need to
* provide the type here. As we want to do a list of applications, `GAppInfo`
* is the object we provide.
*/
var app_list = new GLib.ListStore (typeof (GLib.AppInfo));
var apps = GLib.AppInfo.get_all ();
foreach (var app in apps) {
app_list.append (app);
}
If however you need to list files inside a directory, it's possible also to use the higher level API provided by the same gio-2.0 library. Here is a sample code to enumerate files inside "/usr/share/applications/"
void main () {
var app_dir = GLib.File.new_for_path ("/usr/share/applications");
try {
var cancellable = new Cancellable ();
GLib.FileEnumerator enumerator = app_dir.enumerate_children (
GLib.FileAttribute.STANDARD_DISPLAY_NAME,
GLib.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,
cancellable
);
FileInfo ? file_info = null;
while (!cancellable.is_cancelled () &&
((file_info = enumerator.next_file (cancellable)) != null)) {
// Ignore directories
if (file_info.get_file_type () == GLib.FileType.DIRECTORY) {
continue;
}
// files could be added to a list_store here.
/*
* var files_list = new GLib.ListStore (typeof (GLib.FileInfo));
* files_list.append (file_info);
*/
print (file_info.get_display_name () + "\n");
}
} catch (GLib.Error err) {
info ("%s\n", err.message);
}
}
I hope this could be of any help.
ASP.NET 5 MVC Core application serves multiple sites using LigerShark WebOptimizer ( https://github.com/ligershark/WebOptimizer )
https://example.com/store1
https://example.com/store2
https://example2.com
All those sites should served from wwwroot directory containing same files for those urls.
Sites are defined in hosts.json file:
{
"EevaHosts": {
"example.com/store1": {}
"example.com/store2": {}
"example2.com": {}
}
}
I tried code below to force WebOptimizer to use same wwwwroot directory for every site in Debian Linux but got exception for https://example.com/store1/site.js
No files found matching "/store1/js/site.js" exist in
"/var/www/appbasedir/wwwroot/"
How to force web optimizer to use same wwwwroot directory for all sites ?
If Weboptimizer middleware is removed, static files are serverd properly.
In StartUp.cs:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{ ...
var eevakonf = new ConfigurationBuilder().AddJsonFile("hosts.json").Build();
foreach (var host1 in eevakonf.GetSection("EevaHosts").GetChildren())
{
if (!host1.Key.Contains("/"))
app.UseWebOptimizer();
else
app.UseWebOptimizer(env, new FileProviderOptions[] { new FileProviderOptions()
{
// example.com/store1 -> /store1
RequestPath = new PathString(RequestPathExtract(host1)),
FileProvider = env.WebRootFileProvider
}
});
}
// Using single call causes the same exception:
//HashSet<FileProviderOptions> fp = new();
//foreach (var host1 in eevakonf.GetSection("EevaHosts").GetChildren())
//{
// if (host1.Key.Contains("/"))
// fp.Add(new FileProviderOptions() {
// RequestPath = new PathString(RequestPathExtract(host1)) ,
// FileProvider = env.WebRootFileProvider
// });
//}
//app.UseWebOptimizer(env, fp.ToArray());
foreach (var host in eevakonf.GetSection("EevaHosts").GetChildren())
{
if (!host.Key.Contains("/"))
app.UseStaticFiles();
else
{
app.UseStaticFiles(new StaticFileOptions
{
RequestPath = new PathString(RequestPathExtract(host))
});
}
}
}
static string RequestPathExtract(IConfigurationSection host)
{
return "/" + StrExtract(host.Key, "/");
}
static string StrExtract(string cSearchExpression, string cBeginDelim)
{
int nbpos = At(cBeginDelim, cSearchExpression);
return cSearchExpression[(nbpos + cBeginDelim.Length - 1)..];
}
I need to display the result of a custom build task in summary tab (“ms.vss-build-web.build-results-section”). In order to do this I need to retain some data from build task and use it to call a web service from summary section. Is it possible to store data in a variable using Extension Data Service and use it in summary page? What should be the best approach for this?
Thanks in advance.
I have attached my build task data using a Logging command
https://github.com/Microsoft/vsts-tasks/blob/986f8f5112017474962affe58c9ebaf394fb9354/docs/authoring/commands.md
//Build Task
class TestClass {
_name: string;
_age: number;
constructor(name: string, age:number) {
this._name = name;
this._age = age;
}
}
var data = new TestClass(TinTin,100);
//Create a folder
tl.mkdirP("c:/myfolder/");
//Write data to a file
tl.writeFile("c:/myfolder/mydata.txt",JSON.stringify(data));
//Executes command to attach the file to build
console.log("##vso[task.addattachment type=myAttachmentType;name=myAttachmentName;]c:/myfolder/mydata.txt");
Retrieve the attachment from summary page.
https://github.com/Microsoft/vsts-extension-samples/blob/master/build-results-enhancer/src/enhancer/tab.ts
//Summary Page
/// <reference path="../definitions/Q.d.ts" />
/// <reference path="../definitions/vss.d.ts" />
/// <reference path="../definitions/tfs.d.ts" />
/// <reference path="../definitions/jquery.d.ts" />
import VSS_Service = require("VSS/Service");
import Controls = require("VSS/Controls");
import TFS_Build_Contracts = require("TFS/Build/Contracts");
import TFS_Build_Extension_Contracts = require("TFS/Build/ExtensionContracts");
import DT_Client = require("TFS/DistributedTask/TaskRestClient");
export class StatusSection extends Controls.BaseControl {
constructor() {
super();
}
public initialize(): void {
super.initialize();
// Get configuration that's shared between extension and the extension host
var sharedConfig: TFS_Build_Extension_Contracts.IBuildResultsViewExtensionConfig = VSS.getConfiguration();
var vsoContext = VSS.getWebContext();
if(sharedConfig) {
// register your extension with host through callback
sharedConfig.onBuildChanged((build: TFS_Build_Contracts.Build) => {
var taskClient = DT_Client.getClient();
taskClient.getPlanAttachments(vsoContext.project.id, "build", build.orchestrationPlan.planId, "myAttachmentType").then((taskAttachments)=> {
if (taskAttachments.length === 1) {
var recId = taskAttachments[0].recordId;
var timelineId = taskAttachments[0].timelineId;
taskClient.getAttachmentContent(vsoContext.project.id, "build", build.orchestrationPlan.planId,timelineId,recId,"myAttachmentType","myAttachmentName").then((attachementContent)=> {
function arrayBufferToString(buffer){
var arr = new Uint8Array(buffer);
var str = String.fromCharCode.apply(String, arr);
if(/[\u0080-\uffff]/.test(str)){
throw new Error("this string seems to contain (still encoded) multibytes");
}
return str;
}
var summaryPageData = arrayBufferToString(attachementContent);
//Deserialize data
var ob = JSON.parse(summaryPageData);
console.log("Name: " + ob._name);
console.log("Age: " + ob._age);
});
}
});
});
}
}
}
StatusSection.enhance(StatusSection, $(".build-status"), {});
// Notify the parent frame that the host has been loaded
VSS.notifyLoadSucceeded();
You can do it but the issue is that the those values are always the values from the latest build, the information in summary page would be incorrect for old builds. So I would recommend to the get the build task result via BuildHttpClient2_2 and then show it in the summary page directly.
I need to add some tag in a app.config file for implement a dll (xmlsoccer).
I have to add something like
<system.serviceModel>
<bindings>
<basicHttpBinding>
in a configuration node, but I don't know where it is.
I tried to create an app.config file and set DotNetConfig.xsd as scheme, but during compile, I have this errors:
WARNING: failed to load endpoint configuration for *
SyStem.InvalidOperationException: A Binding must be configured for this channel factory
can anyone help me?
I tried to write this:
` public class MainActivity : FormsApplicationActivity
{
public static readonly EndpointAddress EndPoint = new EndpointAddress("http://www.xmlsoccer.com/FootballDataDemo.asmx");
App application;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
// LoadApplication(new App(binding, EndPoint));
CreateBasicHttp();
LoadApplication(application);
}
private void CreateBasicHttp()
{
var binding = new BasicHttpBinding()
{
Name = "basicHttpBinding",
MaxReceivedMessageSize = 1000000,
};
binding.ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas()
{
MaxArrayLength = 2147483646,
MaxStringContentLength = 5242880,
};
var timeout = new TimeSpan(0, 1, 0);
binding.SendTimeout = timeout;
binding.OpenTimeout = timeout;
binding.ReceiveTimeout = timeout;
application = new App(binding, new EndpointAddress("http://www.xmlsoccer.com/FootballDataDemo.asmx"));
}`
in my MainActivity.cs, but obviously it isn't enough.
Still looking for answer?
Take a look here:
https://forums.xamarin.com/discussion/19303/how-to-consume-wcf-service-in-xamarin-forms-pcl
Steps:
1.- Opening a command prompt in Windows and using the SLSvcUtil.exe tool
from the Silverlight SDK to generate a proxy from a WSDL file. slsvcutil http://www.yourserver.com/WebServices/YourServiceSoapClient.asmx?WSDL /out:YourService.cs That utility is located at C:\Program Files (x86)\Microsoft SDKs\Silverlight\v5.0\Tools\ on my computer.
2.- Adding the resulting YourService.cs file to my project.
3.- Adding the following code to access the service:
// Create the WCF client (created using SLSvcUtil.exe on Windows)
YourServiceSoapClient client = new YourServiceSoapClient(
new BasicHttpBinding(),
new EndpointAddress("hhttp://www.yourserver.com/WebServices/YourServiceSoapClient.asmx"));
// Call the proxy - this should use the async versions
client.ServiceFunctionCompleted += OnGotResult;
client.ServiceFunctionAsync(parameter);
And the OnGotResult function:
void OnGotResult(object sender, ServiceFunctionCompletedEventArgs e)
{
Device.BeginInvokeOnMainThread(async () => {
string error = null;
if (e.Error != null)
error = e.Error.Message;
else if (e.Cancelled)
error = "Cancelled";
if (!string.IsNullOrEmpty(error))
{
await DisplayAlert("Error", error, "OK", "Cancel");
}
else
{
resultsLabel.Text = e.Result;
}
});
}