Type Initialization Exception on pipeline definition - stanford-nlp

Integrating Stanford-NLP into ASP.Net Core C# application getting the following error message:
System.TypeInitializationException
HResult=0x80131534
Message=The type initializer for 'edu.stanford.nlp.util.Timing' threw an exception.
Source=stanford-corenlp-3.9.1
StackTrace:
at edu.stanford.nlp.util.Timing..ctor()
at edu.stanford.nlp.pipeline.StanfordCoreNLP.construct(Properties , Boolean , AnnotatorImplementations )
at edu.stanford.nlp.pipeline.StanfordCoreNLP..ctor(Properties props, Boolean enforceRequirements, AnnotatorPool annotatorPool)
at edu.stanford.nlp.pipeline.StanfordCoreNLP..ctor(Properties props, Boolean enforceRequirements)
at edu.stanford.nlp.pipeline.StanfordCoreNLP..ctor(Properties props)
at _3x32018.Utility.SearchNLP.ParseNLG(String sent2) in G:\VSProjects\3x32018\3x32018\Utility\SearchNLP.cs:line 52
Inner Exception 1:
TypeInitializationException: The type initializer for 'java.util.ResourceBundle' threw an exception.
Inner Exception 2:
MissingMethodException: Method not found: 'Void System.IO.FileStream..ctor(System.String, System.IO.FileMode, System.Security.AccessControl.FileSystemRights, System.IO.FileShare, Int32, System.IO.FileOptions)'.
Here's my simple code::
using edu.stanford.nlp.pipeline;
using java.util;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
namespace _3x32018.Utility
{
public class SearchNLP
{
public HashSet<string> ParseNLG(string sent2)
{
CultureInfo ci = new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
Properties props = new Properties();
props.setProperty("annotators", "tokenize, ssplit, pos, lemma,
ner, parse, dcoref");
StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
Annotation document = new Annotation(sent2);
pipeline.annotate(document);
}
}
}
Any ideas why this is failing?
-Lester

You are using ASP.NET Core which doesn't have the constructor for FileStream that the corenlp.net is using (IKVM to be exact). Check this page out, https://learn.microsoft.com/en-us/dotnet/api/system.io.filestream.-ctor?view=netcore-2.0.

Related

Xamarin Forms with WorkManger

I am trying to use the Xamarin implementation of WorkManager, in the nuget package Xamarin.Android.Arch.Work.Runtime.
The questions is: how to pass "complex" parameters to the worker class?
I have a Xamarin Forms application with DI and others classes, but the job only receives a Java.Lang.Object.
My code:
// Method to Schedule the Job
// See the dataParam? That line throw an exception
// I can manage to pass a simple string or int to the job this way, but not
// complex classes
public void ScheduleAppJobs(IContainerProvider containerRegistry)
{
//here the code throw an exception
var dataParam = new Data.Builder().Put("param", new JobParameter());
var syncWorkerReuest = PeriodicWorkRequest.Builder.From<SyncChecklistWorker>(TimeSpan.FromMinutes(5))
.SetInputData(dataParam.Build())
.Build();
WorkManager.Instance.Enqueue(syncWorkerReuest);
}
//this was my try to create a custom class and populate with my objects
//But didn't worked
public class JobParameter : Java.Lang.Object
{
}
//my job implementation
public class SyncChecklistWorker : Worker
{
public SyncChecklistWorker(Context context, WorkerParameters workerParameters) : base(context, workerParameters)
{
}
public override Result DoWork()
{
if (InputData.KeyValueMap.TryGetValue("param", out Java.Lang.Object #object))
{
var jobParam = (JobParameter)#object;
// here I would like to get my DI container to resolve services and execute business logic
// var diResolver = jobParam.GetDIContainer();
return Result.InvokeSuccess();
}
return Result.InvokeRetry();
}
}
}
The problem is:
The only way to pass input data to a jobs the Data.Builder only accepts Java.Lang.Object. Even trying to approach of having JobParameter : Java.Lang.Object I get the following error when trying to execute the: new Data.Builder().Put("param", new JobParameter()); Error: Java.Lang.IllegalArgumentException: 'Key param has invalid type class crc648d221dddf00bc7fb.JobParameter'
On the official Microsoft Docs the FireBase Job Dispatcher nuget is deprecated. So how to work with the new WorkManager one?
FireBase Job Dispatcher Doc:
https://learn.microsoft.com/en-us/xamarin/android/platform/firebase-job-dispatcher
Deprecated nuget:
https://www.nuget.org/packages/Xamarin.Firebase.JobDispatcher
Any idea of how to solve this?
Work request from Data builder accepts only the premitive types. You can pass the object by serializing to JSON string format and in DoWork() you can deserialize it.
public void ScheduleAppJobs(IContainerProvider containerRegistry)
{
var dataParam = new Data.Builder().PutString("param",serializeToJson(new
MyClass()));
var syncWorkerReuest = PeriodicWorkRequest.Builder.From<SyncChecklistWorker>
(TimeSpan.FromMinutes(5))
.SetInputData(dataParam.Build())
.Build();
WorkManager.Instance.Enqueue(syncWorkerReuest);
}
public override Result DoWork()
{
var jsonString = InputData.GetString("param");
var myClassObj = deserializeFromJson(jsonString );
}
using Newtonsoft.Json;
public string serializeToJson(MyClass myClassObj)
{
var resultString = JsonConvert.SerializeObject(myClassObj);
return resultString;
}
// Deserialize to single object.
public MyClass deserializeFromJson(string jsonString)
{
var serializer = new JsonSerializer();
var resultObject = serializer.Deserialize<MyClass>(jsonString);
}

AUTOFAC THROWIN EXCEPTION ON DBCONTEXT CONSTRUCTOR PARAMETER IN WINDOWS CONSOLE APP

I am using reverse poco to create entities from an sql database. The tt script I am using is from the on the plural website on the tutorial on EF. In a windows console app I am using Autofac to dependency injection of the the ddbcontext interface ISCDInnoPRDDataLayerDbContext:
public partial class SCDInnoPRDDataLayerDbContext : Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext, ISCDInnoPRDDataLayerDbContext
and of a class that will takes that interface as an input.
public class DLScdHopDataNarRepository :
DLScdBaseRepository<Read_Only_HopDataNar>,
IDLScdHopDataNarRepository
{
public DLScdHopDataNarRepository(ISCDInnoPRDDataLayerDbContext dataLayerDbContext)
: base(dataLayerDbContext)
{
}
Autofac is throwing an exception when I resolve the DLScdHopDataNarRepository class. The exception is on the constructor parameter to the SCDInnoPRDDataLayerDbContext class.
Exceptions:
An exception was thrown while invoking the constructor 'Void .ctor(System.String)' on type 'SCDInnoPRDDataLayerDbContext'.
at SCDInnoPRD.DataLayer.Context.SCDInnoPRDDataLayerDbContext..ctor(String connectionString)
at lambda_method(Closure , Object[] )
at Autofac.Core.Activators.Reflection.ConstructorParameterBinding.Instantiate()
+ InnerException {"The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception."}
System.Exception {System.TypeInitializationException}
Below is the autofac registration and the code that resolves the DLScdHopDataNarRepository .
Registration code:
public class SCDInnoPRDModule :Module
{
public string ConnectionString { get; private set; }
public SCDInnoPRDModule(string connectionString)
{
ConnectionString = connectionString;
}
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<SCDInnoPRDDataLayerDbContext>()
.As<ISCDInnoPRDDataLayerDbContext>()
.Keyed<ISCDInnoPRDDataLayerDbContext>("scdb")
.WithParameter((pi, ctx) => pi.ParameterType == typeof(string)
&& pi.Name == "connectionString",
(pi, ctx) => getConnectionString(ConnectionString))
.InstancePerLifetimeScope();
builder.RegisterType<DLScdHopDataNarRepository>()
.As<IDLScdHopDataNarRepository>()
.Keyed<IDLScdHopDataNarRepository>("sdhopres")
.InstancePerLifetimeScope();
builder.RegisterType<DLScdNarsService>()
.As<IDLScdNarsService>()
.Keyed<IDLScdNarsService>("sddlser")
.InstancePerLifetimeScope();
}
private Func< string,string> getConnectionString = delegate (string connectionString)
{
string retVal = connectionString;
return retVal;
};
Resolve code:
using (var config= new ContainerConfig())
{
// register dependency injectopn
var container = config.Configure();
using (var scope = container.BeginLifetimeScope())
try
{ // exception occurs here
var dlscd = container.ResolveNamed("sdhopres");
I have to a point where I can solve this problem. Any suggestion to fix the problem would be appreciated.
Any example source code project that use autofac to do di of a dbcontext in a windows console application would be helpful. I can not find any such project on line.
I can post the entire source code project on GitHub or a website for download if anyone would like to view the code

Registring CustomPropertyEditors for using in BeanWrapper

I am trying to register custom property editors using the following configuration in my spring boot application.Reffered the following documentation link section 5.4.2.1.
#Bean
public static CustomEditorConfigurer customEditorConfigurer() {
CustomEditorConfigurer configurer = new CustomEditorConfigurer();
configurer.setPropertyEditorRegistrars(new PropertyEditorRegistrar[] {
(registry) -> registry.registerCustomEditor(Instant.class, new CustomInstantEditor()) });
return configurer;
}
When I created a BeanWrapper and using it I am getting the following error
Code:
BeanWrapper newAccountWrapper = new BeanWrapperImpl(newAccount);
newAccountWrapper.setPropertyValue("chardate", value);
Error is:
Exception is Failed to convert property value of type [java.lang.String] to required type [java.time.Instant] for property 'chardate'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.time.Instant] for property 'chardate': no matching editors or conversion strategy found
But the above code works if I register the CustomEditor for the BeanWrapper
BeanWrapper newAccountWrapper = new BeanWrapperImpl(newAccount);
newAccountWrapper.registerCustomEditor(Instant.class, new
CustomInstantEditor());
So can I not register customPropertyEditors using CustomEditorConfigurer BeanFactoryPostProcessor ?
Additional Info:
BeanWrapper newAccountWrapper = new BeanWrapperImpl(newAccount);
newAccountWrapper.registerCustomEditor(Instant.class, new CustomInstantEditor());
newAccountWrapper.registerCustomEditor(Money.class, new CustomMoneyEditor());
newAccountWrapper.setAutoGrowNestedPaths(true);
accountDomainElements.forEach((accountElement, value) -> {
newAccountWrapper.setPropertyValue(accountElement, value);
Give a try
#Bean
public CustomEditorConfigurer customEditorConfigurer() {
CustomEditorConfigurer configurer = new CustomEditorConfigurer();
Map<Class<?>, Class<? extends PropertyEditor>> customEditors = new HashMap<>();
customEditors.put(Instant.class, CustomInstantEditor.class);
configurer.setCustomEditors(customEditors);
return configurer;
}

spring mvc processing xml with relative path to dtd

My webservice receives an xml from a third-party source, which contains a !DOCTYPE declaration. Therefore I must use the second method in my controller to parse the xml document, the first one gives me this exception:
Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not unmarshal to [class com.example.MeterBusXml]: null; nested exception is javax.xml.bind.UnmarshalException
- with linked exception:
[org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 48; DOCTYPE is disallowed when the feature "http://apache.org/xml/features/disallow-doctype-decl" set to true.]
I have no control over the application which posts the xml, so I must adapt my webservice to parse it with the dtd.
My question is, what is the spring framework's way of injecting the EntityResolver into every XMLReader instance?
#RestController
public class MeterBusDataController {
#RequestMapping (
consumes = APPLICATION_XML_VALUE,
method = POST,
path = "/meterbus1"
)
public void method1(#RequestBody MeterBusXml xml) {
System.out.println(xml);
}
#RequestMapping(
method = POST,
path = "/meterbus2"
)
public void method2(HttpServletRequest rq) throws IOException, ParserConfigurationException, SAXException, JAXBException {
JAXBContext jc = newInstance(MeterBusXml.class);
Unmarshaller um = jc.createUnmarshaller();
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setValidating(true);
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
xr.setEntityResolver(new EntityResolver() {
#Override
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
return new InputSource(new StringReader(""));
}
});
BufferedReader reader = rq.getReader();
InputSource inputSource = new InputSource(reader);
SAXSource saxSource = new SAXSource(xr, inputSource);
MeterBusXml xml = (MeterBusXml)um.unmarshal(saxSource);
System.out.println(xml);
}
}
See the following document for an example of the mbus.xml I'm trying to unmarshal.
http://prevodniky.sk/products/product_EthMBus_common/download/Ethernet_converters_exports_v1_02_EN.pdf
I've found the root of the problem. First I tried to create and configure a Jaxb2Marshaller bean, but that did not work out. Then I realized, I need a HttpMessageConverter, so I had to override the extendMessageConverters method in the WebMvcConfigurerAdapter class, and set the required properties on Jaxb2RootElementHttpMessageConverter. This message converter does not use a Jaxb2Marshaller, but it's internal workings are very similar.
setSupportDtd(true) is required, to force the parser to accept the !DOCTYPE declaration.
setProcessExternalEntities(false) is required, because if this property is false, then the converter uses a blank EntityResolver, just as I did in method2.
#Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter {
#Override
public void extendMessageConverters(List<HttpMessageConverter<Jaxb2RootElementHttpMessageConverter?>> converters) {
for (final Iterator<HttpMessageConverter<?>> iterator = converters.iterator(); iterator.hasNext();) {
HttpMessageConverter<?> next = iterator.next();
if (next instanceof Jaxb2RootElementHttpMessageConverter) {
Jaxb2RootElementHttpMessageConverter jaxbConverter = (Jaxb2RootElementHttpMessageConverter) next;
jaxbConverter.setProcessExternalEntities(false);
jaxbConverter.setSupportDtd(true);
}
}
}
}

Spring 3.1 basic usage of Envirionment and PropertySource

I want to inject property values into the Spring context when it is started.
I am trying to do this using the new Environment and PropertySource features of Spring 3.1.
In the class in which loads the Spring context, I define my own PropertySource class as follows:
private static class CustomPropertySource extends PropertySource<String> {
public CustomPropertySource() {super("custom");}
#Override
public String getProperty(String name) {
if (name.equals("region")) {
return "LONDON";
}
return null;
}
Then, I add this property source to the application context:
ClassPathXmlApplicationContext springIntegrationContext =
new ClassPathXmlApplicationContext("classpath:META-INF/spring/ds-spring-intg-context.xml");
context.getEnvironment().getPropertySources().addLast( new CustomPropertySource());
context.refresh();
context.start();
In one of my beans, I try to access the property value:
#Value("${region}")
public void setRegion(String v){
...
}
bur recieve the folowing error:
java.lang.IllegalArgumentException: Caused by:
java.lang.IllegalArgumentException: Could not resolve placeholder
'region' in string value [${region}]
Any help is greatly appreciated
when you pass an XML file location as a constructor argument to ClassPathXmlApplicationContext(..) it straight away does the context.refresh()/context.start() methods. so by passing in your XML locations, you're essentially doing it all in one pass and the context is already started/loaded by the time you get to call context.getEnvironment().getPropertySources....
try this;
ClassPathXmlApplicationContext springIntegrationContext =
new ClassPathXmlApplicationContext();
context.getEnvironment().getPropertySources().addLast( new CustomPropertySource());
context.setLocations("classpath:META-INF/spring/ds-spring-intg-context.xml");
context.refresh();
it will set your sources, then your xml, then start the app context.

Resources