Trouble using M2Doc core generation API and SiriusServices - m2doc

I am trying to generate documentation using the core generation API (as described here https://www.m2doc.org/ref-doc/3.1.0/index.html#core-generation-api). But I have the following error:
Couldn't find the 'isRepresentationDescriptionName()' service.
(It works fine when I use the genconf not programmatically).
I tried to add the SiriusServices using SiriusServiceConfigurator, but didn't manage to solve this issue.
Or maybe is it because I didn't add the SiriusSession option that refers to the .aird file?
I have looked at how new services are added in the newEnvironmentWithDefaultServices work but it is seems not applicable for SiriusServices.
final IQueryEnvironment queryEnvironment = org.eclipse.acceleo.query.runtime.Query
.newEnvironmentWithDefaultServices(null);
final Monitor monitor = new BasicMonitor.Printing(System.out);
final ResourceSet resourceSetForModels = session.getTransactionalEditingDomain().getResourceSet();
resourceSetForModels.createResource(modelUri);
try (DocumentTemplate template = M2DocUtils.parse(resourceSetForModels.getURIConverter(), templateURI,
queryEnvironment, classProvider, monitor)) {
final Map<String, Object> variable = new HashMap<>();
M2DocUtils.generate(template, queryEnvironment, variable, resourceSetForModels, outputURI, monitor);
...
Thanks

The Sirius related services need the Sirius Session. The Session is initialized using the SiriusSession option in the .genconf file. It should be set to an URI referencing the .aird file. In the class M2DocUtils you have several methods to create an IQueryEnvironment that take a Map of String where you can add the SiriusSession option, for instance:
M2DocUtils.getQueryEnvironment(ResourceSet, URI, Map<String, String>)
Note that your code needs to be ran inside of Eclipse, not a standalone java program.

Related

Can log4j and java util logging coexist

My application uses log4j but OkHttpClient uses java util logging. So apart from log4j.properties, I created a logging.properties file with the following contents:
handlers=java.util.logging.FileHandler
.level=FINE
okhttp3.internal.http2.level=FINE
java.util.logging.FileHandler.pattern = logs/%hjava%u.log
java.util.logging.FileHandler.limit = 50000
java.util.logging.FileHandler.count = 1
java.util.logging.FileHandler.formatter = java.util.logging.XMLFormatter
java.util.logging.ConsoleHandler.level = FINE
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
I then added this to jvm params used for starting the application -Djava.util.logging.config.file="file://${BASE_DIR}/logging.properties"
But I don't see any new folders being created as indicated by the Filehandler. Any one know why?
But I don't see any new folders being created as indicated by the Filehandler. Any one know why?
The FileHandler will not create any new folders. A directory must be created before the FileHandler will create a file.
The system property requires a path to file that is located on the filesystem It will not expand system properties or environment variables by using the dollar sign syntax.
You can use a relative path based off of the working directory or you have to use an absolute path to the logging.properties. The logging properties can not be packaged inside of an archive.
If you want to work around this limitation then you want to create a custom config class and use the java.util.logging.config.class property in conjunction with the java.util.logging.config.file property. You then write a class that reads the file://${BASE_DIR}/logging.properties and performs the needed transformation into a path to a file. Then update the configuration if you are using JDK9 or newer. On older versions you need to use readConfiguration and add code to work work around limitations of the LogManager

Dataflow - how to create a PCollectionView to use with DoFnTester?

This question is about Google Dataflow. I would like to test a do function with side inputs. The Google manuals list that you need code like this:
static class MyDoFn extends DoFn<String, Integer> { ... }
MyDoFn myDoFn = ...;
DoFnTester<String, Integer> fnTester = DoFnTester.of(myDoFn);
PCollectionView<List<Integer>> sideInput = ...;
Iterable<Integer> value = ...;
fnTester.setSideInputInGlobalWindow(sideInput, value);
I wonder how the code to create the PCollectionView instance looks like. When using DoFnTester you do not have a pipeline, and I do not see how to create PCollectionView instances without a pipeline. Can you tell me how to create a PCollectionView instance for use with DoFnTester?
Thanks for your time.
With kind regards,
Martijn Dirkse
I found the answer myself. You can just create a TestPipeline instance and use it to build the PCollectionView you need. It is no problem that the TestPipeline does not have any other purpose in your code.
Dataflow 2.1 sdk sample here . There is no setSideInputInGlobalWindow in 2.X use setSideInput instead.

Sitecore: Glass Mapper Code First

It is possible to automatically generate Sitecore templates just coding models? I'm using Sitecore 8.0 and I saw Glass Mapper Code First approach but I cant find more information about that.
Not sure why there isn't much info about it, but you can definitely model/code first!. I do it alot using the attribute configuration approach like so:
[SitecoreType(true, "{generated guid}")]
public class ExampleModel
{
[SitecoreField("{generated guid}", SitecoreFieldType.SingleLineText)]
public virtual string Title { get; set; }
}
Now how this works. The SitecoreType 'true' value for the first parameter indicates it may be used for codefirst. There is a GlassCodeFirstDataprovider which has an Initialize method, executed in Sitecore's Initialize pipeline. This method will collect all configurations marked for codefirst and create it in the sql dataprovider. The sections and fields are stored in memory. It also takes inheritance into account (base templates).
I think you first need to uncomment some code in the GlassMapperScCustom class you get when you install the project via Nuget. The PostLoad method contains the few lines that execute the Initialize method of each CodeFirstDataprovider.
var dbs = global::Sitecore.Configuration.Factory.GetDatabases();
foreach (var db in dbs)
{
var provider = db.GetDataProviders().FirstOrDefault(x => x is GlassDataProvider) as GlassDataProvider;
if (provider != null)
{
using (new SecurityDisabler())
{
provider.Initialise(db);
}
}
}
Furthermore I would advise to use code first on development only. You can create packages or serialize the templates as usual and deploy them to other environment so you dont need the dataprovider (and potential risks) there.
You can. But it's not going to be Glass related.
Code first is exactly what Sitecore.PathFinder is looking to achieve. There's not a lot of info publicly available on this yet however.
Get started here: https://github.com/JakobChristensen/Sitecore.Pathfinder

How can I create a JSON webservice to store and retrieve data from a simple properties file?

How can I create a Java or Javascript JSON webservice to retrieve data from a simple properties file? My intention is to uses this as a global property storage for a Jenkins instance that runs many Unit tests. The master property file also needs to be capable of being manually edited and stored in source control.
I am just wondering what method people would recommend that would be the easiest for a junior level programmer like me. I need read capability at miniumum but, and if its not too hard, write capability also. Therefore, that means it is not required to be REST.
If something like this already exists in Java or Groovy, a link to that resource would be appreciated. I am a SoapUI expert but I am unsure if a mock service could do this sort of thing.
I found something like this in Ruby but I could not get it to work as I am not a Ruby programmer at all.
There are a multitude of Java REST frameworks, but I'm most familiar with Jersey so here's a Groovy script that gives a simple read capability to a properties file.
#Grapes([
#Grab(group='org.glassfish.jersey.containers', module='jersey-container-grizzly2-http', version='2.0'),
#Grab(group='org.glassfish.jersey.core', module='jersey-server', version='2.0'),
#Grab(group='org.glassfish.jersey.media', module='jersey-media-json-jackson', version='2.0')
])
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory
import org.glassfish.jersey.jackson.JacksonFeature
import javax.ws.rs.GET
import javax.ws.rs.Path
import javax.ws.rs.Produces
#Path("properties")
class PropertiesResource {
#GET
#Produces("application/json")
Properties get() {
new File("test.properties").withReader { Reader reader ->
Properties p = new Properties()
p.load(reader)
return p
}
}
}
def rc = new org.glassfish.jersey.server.ResourceConfig(PropertiesResource, JacksonFeature);
GrizzlyHttpServerFactory.createHttpServer('http://localhost:8080/'.toURI(), rc).start()
System.console().readLine("Press any key to exit...")
Unfortunately, since Jersey uses the 3.1 version of the asm library, there are conflicts with Groovy's 4.0 version of asm unless you run the script using the groovy-all embeddable jar (it won't work by just calling groovy on the command-line and passing the script). I also had to supply an Apache Ivy dependency. (Hopefully the Groovy team will resolve these in the next release--the asm one in particular has caused me grief in the past.) So you can call it like this (supply the full paths to the classpath jars):
java -cp ivy-2.2.0.jar:groovy-all-2.1.6.jar groovy.lang.GroovyShell restProperties.groovy
All you have to do is create a properties file named test.properties, then copy the above script into a file named restProperties.groovy, then run via the above command line. Then you can run the following in Unix to try it out.
curl http://localhost:8080/properties
And it will return a JSON map of your properties file.

Generic WebService (SOAP) client library for C++

I'm looking for a simple C++ WebService Client Library that can be easily linked into my application.
Preferably this library:
can be used to access any SOAP WebService (so I can pass the URL, the WebService name, the WebService method and all the arguments as arguments to a function call)
can be linked statically in a C++ application (so no DLL's)
is freeware or available at a low cost
can be used royalty-free in my application
can query the Web service for its WSDL and return me the available method names, arguments of the methods and their data types
Before anyone of you answers .NET: been there, tried it. My major objections against .NET are:
you can generate the proxy but it's impossible to change the WebService name in the generated proxy code afterwards, since .NET uses reflection to check the WebService name (see Dynamically call SOAP service from own scripting language for my question regarding that problem)
generating the proxy class on the fly doesn't always seem to work correctly
I already used Google to look up this information, but I couldn't find one.
Thanks
EDIT:
To clarify this further, I really want something where I can write code like this (or something in this style):
SoapClient mySoapClient;
mySoapClient.setURL("http://someserver/somewebservice");
mySoapClient.setMethod("DoSomething");
mySoapClient.setParameter(1,"Hello");
mySoapClient.setParameter(2,12345);
mySoapClient.sendRequest();
string result;
mySoapClient.getResult(result);
No dynamic code generation.
Have you looked at gSOAP? I think it will be suitable for your needs.
http://gsoap2.sourceforge.net/
I found a solution using on-the-fly-generated assemblies (which I couldn't get working the previous time). Starting point is http://refact.blogspot.com/2007_05_01_archive.html.
E.g. This is the code to use the PeriodicTable web service:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Web;
using System.Web.Services;
using System.Web.Services.Description;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Xml.Serialization;
using System.IO;
using System.Reflection;
namespace GenericSoapClient
{
class Program
{
static void method1()
{
Uri uri = new Uri("http://www.webservicex.net/periodictable.asmx?WSDL");
WebRequest webRequest = WebRequest.Create(uri);
System.IO.Stream requestStream = webRequest.GetResponse().GetResponseStream();
// Get a WSDL
ServiceDescription sd = ServiceDescription.Read(requestStream);
string sdName = sd.Services[0].Name;
// Initialize a service description servImport
ServiceDescriptionImporter servImport = new ServiceDescriptionImporter();
servImport.AddServiceDescription(sd, String.Empty, String.Empty);
servImport.ProtocolName = "Soap";
servImport.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties;
CodeNamespace nameSpace = new CodeNamespace();
CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
codeCompileUnit.Namespaces.Add(nameSpace);
// Set Warnings
ServiceDescriptionImportWarnings warnings = servImport.Import(nameSpace, codeCompileUnit);
if (warnings == 0)
{
StringWriter stringWriter =
new StringWriter(System.Globalization.CultureInfo.CurrentCulture);
Microsoft.CSharp.CSharpCodeProvider prov =
new Microsoft.CSharp.CSharpCodeProvider();
prov.GenerateCodeFromNamespace(nameSpace,
stringWriter,
new CodeGeneratorOptions());
string[] assemblyReferences =
new string[2] { "System.Web.Services.dll", "System.Xml.dll" };
CompilerParameters param = new CompilerParameters(assemblyReferences);
param.GenerateExecutable = false;
param.GenerateInMemory = true;
param.TreatWarningsAsErrors = false;
param.WarningLevel = 4;
CompilerResults results = new CompilerResults(new TempFileCollection());
results = prov.CompileAssemblyFromDom(param, codeCompileUnit);
Assembly assembly = results.CompiledAssembly;
Type service = assembly.GetType(sdName);
//MethodInfo[] methodInfo = service.GetMethods();
List<string> methods = new List<string>();
// only find methods of this object type (the one we generated)
// we don't want inherited members (this type inherited from SoapHttpClientProtocol)
foreach (MethodInfo minfo in service.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly))
{
methods.Add(minfo.Name);
Console.WriteLine (minfo.Name + " returns " + minfo.ReturnType.ToString());
ParameterInfo[] parameters = minfo.GetParameters();
foreach (ParameterInfo pinfo in parameters)
{
Console.WriteLine(" " + pinfo.Name + " " + pinfo.ParameterType.ToString());
}
}
// Create instance of created web service client proxy
object obj = assembly.CreateInstance(sdName);
Type type = obj.GetType();
object[] args0 = new object[] { };
string result0 = (string)type.InvokeMember(methods[0], BindingFlags.InvokeMethod, null, obj, args0);
Console.WriteLine(result0);
object[] args1 = new object[] { "Oxygen" };
string result1 = (string)type.InvokeMember(methods[1], BindingFlags.InvokeMethod, null, obj, args1);
Console.WriteLine(result1);
}
}
}
}
In this code I explicitly use methods[0] and methods[1] but in reality you would check the method names of course. In this example I get the names of all elements in the periodic table, then get the atomic weight of oxygen.
This example does not yet contain logic to support a proxy. I still need to add this, but for the moment, it solves my biggest problem, namely, having a generic SOAP client.
EDIT:
I know this code is C# and I was originally asking for a C++ solution, but this code proves that it can work in a .NET environment (which I can still use in limited parts of my application), and I will probably rewrite this code into C++/.NET, which solves my problem.
Axis2C : http://axis.apache.org/axis2/c/core/index.html
Axis2C ticks most of the above , please check for static linking. .
EDIT: As per last few messages on the list, static linking is incomplete. The below still holds:
Perhaps I do not understand the question correctly. Any web service you call you need to specify the endpoint URL and the operation & parameters.
Are you referring to dynamically "discovering" the services & presenting the option to call them...? If so I doubt this is possible.
If you are referring to generic framework, SOAP messages are client end responsibility any way... You should not have a problem wrapping them under some of the toolkit API's. WSDL code generation is not mandatory. I have written a few services from scratch, i.e. You can set endpoint, service and craft the SOAP message, parameters, headers etc. as you feel.
Cheers!