Using SolrNet to query Solr from a console application? - solr

I'm trying to use SolrNet in a command line application (or more accurately, from LINQPad) to test some queries, and when trying to initialize the library, I get the following error:
Key 'SolrNet.Impl.SolrConnection.UserQuery+Resource.SolrNet.Impl.SolrConnection' already registered in container
However, if I catch this error and continue, the ServiceLocator gives me the following error:
Activation error occured while trying to get instance of type ISolrOperations`1, key ""
With the inner exception:
The given key was not present in the dictionary.
My full code looks like this:
try
{
Startup.Init<Resource>("http://localhost:8080/solr/");
Console.WriteLine("Initialized\n");
}
catch (Exception ex)
{
Console.WriteLine("Already Initialized: " + ex.Message);
}
// This line causes the error if Solr is already initialized
var solr = ServiceLocator.Current.GetInstance<ISolrOperations<Resource>>();
// Do the search
var results = solr.Query(new SolrQuery("title:test"));
I'm running Tomcat 7 on Windows 7x64 with Solr 3.4.0 installed.
There's another message about the same problem on StackOverflow, though the accepted answer of putting the Startup.Init code in Global.asax is only relevant to ASP.NET.
Restarting the Tomcat7 service resolves the problem, but having to do this after every query is a pain.
What is the correct way to use the SolrNet library to interact with Solr from a C# console application?

The correct way to use SolrNet in a console application is to only execute the line
Startup.Init<Resource>("http://localhost:8080/solr/");
once for the life of your console application. I typically put it as the first line in my Main method as shown below...
static void Main(string[] args)
{
Startup.Init<Resource>("http://localhost:8080/solr/");
//Call method or do work to query from solr here...
//Using your code in a method...
QuerySolr();
}
private static void QuerySolr()
{
var solr = ServiceLocator.Current.GetInstance<ISolrOperations<Resource>>();
// Do the search
var results = solr.Query(new SolrQuery("title:test"));
}
Your error is coming from the fact that you are trying to initialize the SolrNet connection multiple times. You only need to initialize it once when the console application starts and then reference (look up) via the ServiceLocator when needed.

My Solution is clear Startup before Init
Startup.Container.Clear();
Startup.InitContainer();
Startup.Init<Resource>("http://localhost:8080/solr/");

Related

How to Execute (Vector) Storage.getInstance().readObject(filePath); in Java 8 Swing Package

Windows 10 Pro
Latest Simulator
Java Swing Project
I would like to execute "Vector a1 = (Vector) Storage.getInstance().readObject(filePath);"
In a Java Swing Application running on Windows 10 platform, I tried import CodenameOne.jar in Swing package, however when executing above code, get null pointer exception in Storage.getInstance()
Is there a way to execute this in Swing?
Thoughts?
Best Regards.
Thanks, I did not init the Display, however "Display.init(Object m)" requires an Object Argument and the Init method is deprecated.
Can you please provide me the codenameone Display dependencies?
And perhaps a java Swing snippet of code to initialize Display in order to execute Storage.getInstance().readObject(filePath)
Thoughts?
Best Regards
Thanks, Passing init(working directory) solved the Exception thrown.
Here is the Code snippet used to allow me to execute:
Storage.getInstance().readObject(filePath).
String filePath = incSrv.Pwd();// gets working directory
try {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
Display.init(filePath);
String fileName = "A1-MMA.properties";
Vector a1 = (Vector) Storage.getInstance().readObject(filePath);
}
});
} catch (Exception e) {
}
And it does appear to work,
However I am left with a blacked out form that appears modal.
How can I avoid this or dispose it?.
FYI: What I am creating here is a work around for serializing Vector in Codenameone. I Save Vector to file using "Storage.getInstance().writeObject(Path, Vector)"
I convert the file to bytes and write it to the Swing Server VIA socket.
Using Storage.getInstance().readObject(file) on the Swing Server I have deserialize the object into the Vector from my app.
This appears to work well and is more efficient than the current method I use to deliver complex Vectors from the app to the Swing Server.
Can you please let me know if you see a red flag with this workaround?
Like The ability to Storage.getInstance().readObject(file) on the Swing Server may go away?
This method will save a lot of time in movind Vector data to and from the App/Server.
Thoughts Best Regards
Storage.getInstance().readObject(file) // (A1ServiceSrv.java:571)
Caused this Exception:
java.lang.NullPointerException
at com.codename1.io.Storage.init(Storage.java:89)
at com.codename1.io.Storage.getInstance(Storage.java:112)
at Main.A1ServiceSrv.loadVectorFromFile(A1ServiceSrv.java:571)
Regards
12/11/2021:
Thanks Shai,
I am including in my classpath CodenameOne.jar with update date of 12/11/2021 after CN1 refresh.
Getting Same null pointer exception.
Passing in Path "C:\Src1\A1-Arms\A1-Server\A1-MMA.properties" (Absolute Path)
Also Tried "A1-MMA.properties", however I don't think Codenameone knows where my home path is since we are not initializing it as we did with
Display.init("Current Working Directory where files reside");
This is the Fresh Stack Trace w/o calling Display.init (12-20-2021)
java.lang.NullPointerException at
com.codename1.ui.Display.getResourceAsStream(Display.java:3086)
at com.codename1.io.Log.print(Log.java:327)
at com.codename1.io.Log.logThrowable(Log.java:299)
at com.codename1.io.Log.e(Log.java:285)
at com.codename1.io.Storage.readObject(Storage.java:271)
at Main.A1ServiceSrv.loadVectorFromFile(A1ServiceSrv.java:596)
vector = (Vector) Storage.getInstance().readObject(filePath); // (A1ServiceSrv.java:596)
This is hopefully fixed by this commit: https://github.com/codenameone/CodenameOne/commit/72bf283bdaaefe5207bb9fd6787578e3ef61522c if not let me know with a fresh stack

Playing regular and looping sounds with JDK 11?

I am using Java JDK 11.0.8 ("Installed JREs" under Eclipse is set to jdk-11.0.8), Eclipse 2020-06, and Codename One 6.0.0.
I have recently switched from JDK 8 to JDK 11 and noticed that playing sounds option in my app does not work anymore...
Note that I uncheck "Java 8" when I create my app and I am only trying to work things out in the simulator (I am not trying to deploy the app to an actual mobile device).
I want to play a "regular sound" (I want to play a sound from beginning to end, and when it ends I do not need to replay it from the beginning) and also a "looping sound" (the sound should come to its beginning when it ends and hence, I can continuously play it in the background).
Hence I have two questions:
Question1 - About "regular sounds"
I would like to create Media object just once and then re-use it whenever I need to play the same regular sound.
For that purpose I am encapsulating a Media creation inside a class as follows:
public class RegularSound {
private Media m;
public RegularSound(String fileName) {
try{
InputStream is = Display.getInstance().getResourceAsStream(getClass(), "/"+fileName);
m = MediaManager.createMedia(is, "audio/wav");
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void play() {
m.setTime(0);
m.play();
}
}
Then I instantiate the RegularSound object and play it as follows:
mySound = new RegularSound("example.wav");
mySound.play();
Please note that example.wav is copied directly under the "src" directory of my project.
This code used to work with JDK 8, but with JDK 11, I get the following build errors:
Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: javax/media/ControllerListener
at com.codename1.impl.javase.JavaJMFSEPort$1.run(JavaJMFSEPort.java:67)
at java.desktop/java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:313)
at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:770)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:740)
at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
Caused by: java.lang.ClassNotFoundException: javax.media.ControllerListener
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
at java.base/java.lang.ClassLoader.findSystemClass(ClassLoader.java:1247)
at com.codename1.impl.javase.ClassPathLoader.findClass(ClassPathLoader.java:269)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:588)
at com.codename1.impl.javase.ClassPathLoader.loadClass(ClassPathLoader.java:115)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
at com.codename1.impl.javase.ClassPathLoader.loadClass(ClassPathLoader.java:107)
... 14 more
Question2- About "looping sounds"
For looping sound I have created another class as follows:
public class LoopingSound implements Runnable{
private Media m;
String fileName;
public LoopingSound(String fileName){
try{
InputStream is = Display.getInstance().getResourceAsStream(getClass(), "/"+fileName);
m = MediaManager.createMedia(is, "audio/wav",this);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void pause()
{
m.pause();
}
public void play()
{
m.play();
}
public void run() {
m.setTime(0);
m.play();
}
}
But I again get build errors when I instantiate an object of LoopingSound and try to play it...
So could you please let me know how to change code for regular and looping sounds so that I do not receive above-mentioned errors when using JDK 11?
UPDATE
Thanks for the reply #shai-almog. I have installed CEF. But I am receiving some messages on the console in runtime and I can't hear the sound playing... I run the following code:
try {
InputStream is = Display.getInstance().getResourceAsStream(getClass(), "/example.wav");
Media m = MediaManager.createMedia(is, "audio/wav");
m.play();
} catch (IOException e) {
e.printStackTrace();
}
and I receive the following messages on console when I run this code (it throws an exception at the end):
Adding CEF to classpath
Retina Scale: 2.0
CEF Args: [--disable-gpu, --disable-software-rasterizer, --disable-gpu-compositing, --touch-events=enabled, --enable-media-stream, --device-scale-factor=4, --force-device-scale-factor=4, --autoplay-policy=no-user-gesture-required, --enable-usermedia-screen-capturing]
Using:
JCEF Version = 83.4.0.260
CEF Version = 83.4.0
Chromium Version = 83.0.4103.106
AppHandler.stateHasChanged: INITIALIZING
initialize on Thread[AWT-EventQueue-0,6,main] with library path C:\Users\pmuyan\.codenameone\cef\lib\win64
Added scheme search://
Added scheme client://
Added scheme cn1stream://
DevTools listening on ws://127.0.0.1:8088/devtools/browser/591d3502-6fd6-4997-9131-9a2a352e47b1
AppHandler.stateHasChanged: INITIALIZED
Running ready callbacks
Exception in thread "AWT-EventQueue-0" Address changed to data:text/html,%3C!doctype%20html%3E%3Chtml%3E%3Chead%3E%3Cstyle%20type%3D'text%2Fcss'%3Edocument%2C%20body%20%7Bpadding%3A0%3Bmargin%3A0%3B%20width%3A100%25%3B%20height%3A%20100%25%7D%20video%2C%20audio%20%7Bmargin%3A0%3B%20padding%3A0%3B%20width%3A100%25%3B%20height%3A%20100%25%7D%3C%2Fstyle%3E%3C%2Fhead%3E%3Cbody%3E%3Caudio%20id%3D'cn1Media'%20width%3D'640'%20height%3D'480'%20style%3D'width%3A100%25%3Bheight%3A100%25'%20src%3D'https%3A%2F%2Fcn1app%2Fstreams%2F1'%2F%3E%3Cscript%3Ewindow.cn1Media%20%3D%20document.getElementById('cn1Media')%3Bfunction%20callback(data)%7B%20cefQuery(%7Brequest%3A'shouldNavigate%3A'%2BJSON.stringify(data)%2C%20onSuccess%3A%20function(response)%7B%7D%2C%20onFailure%3Afunction(error_code%2C%20error_message)%20%7B%20console.log(error_message)%7D%7D)%3B%7Dcn1Media.addEventListener('pause'%2C%20function()%7B%20callback(%7B'state'%3A'paused'%7D)%7D)%3Bcn1Media.addEventListener('play'%2C%20function()%7B%20callback(%7B'state'%3A'playing'%7D)%7D)%3Bcn1Media.addEventListener('ended'%2C%20function()%7B%20callback(%7B'state'%3A'ended'%7D)%7D)%3Bcn1Media.addEventListener('durationchange'%2C%20function()%7B%20callback(%7B'duration'%3A%20Math.floor(cn1Media.duration%20*%201000)%7D)%7D)%3Bcn1Media.addEventListener('timeupdate'%2C%20function()%7B%20callback(%7B'time'%3A%20Math.floor(cn1Media.currentTime%20*%201000)%7D)%7D)%3Bcn1Media.addEventListener('volumechange'%2C%20function()%7B%20callback(%7B'volume'%3A%20Math.round(cn1Media.volume%20*%20100)%7D)%7D)%3Bcn1Media.addEventListener('error'%2C%20function()%7B%20var%20msg%20%3D%20'Unknown%20Error'%3B%20try%20%7Bmsg%20%3D%20cn1Media.error.message%20%2B%20'.%20Code%3D'%2Bcn1Media.error.code%3B%7Dcatch(e)%7B%7D%20callback(%7B'error'%3A%20msg%7D)%7D)%3B%3C%2Fscript%3E%20%3C%2Fbody%3E%3C%2Fhtml%3E
UPDATE 2
I could manually add Open JavaFX 11 to Eclipse and to Codename One app running under Eclipse while using JDK 11 as follows:
Step1) Create JavaFX11 user library under Eclipse
Download JavaFX 11 from https://gluonhq.com/products/javafx/
unzip it -> creates javafx-sdk-11.0.2 folder
Create a User Library: Eclipse -> Window -> Preferences -> Java -> Build Path -> User Libraries -> New.
Name it JavaFX11.
Hit "Add External JARs" and include all the jars under javafx-sdk-11.0.2\lib
Step 2) Add the JavaFX11 library to the project:
Right click on project.
Select Build path -> Configure Build Path
Goto Library tab->Add Library->User Library->Check JavaFX11->Apply and Close
Now, I can hear sounds playing in my Codename One application.
However, I need to run my application from command prompt and regular command line to run the apps does not work anymore (the app cannot find the JavaFX related classes from the command prompt and I get the same errors listed above). So could you please tell me how to modify the command line so that Codename One project that uses JavaFX would run from command prompt?
Here is the regular command line I use:
java -cp dist\Proj.jar;JavaSE.jar com.codename1.impl.javase.Simulator com.mycompany.hi.Main
BTW, I have tried to add javafx.media.jar under javafx-sdk-11.0.2\lib to the classpath (-cp) in the command line, but this did not work...
UPDATE 3
We have solved the issue by using the following command line:
java --module-path C:\javafx-sdk-11.0.2\lib\ --add-modules= ALL-MODULE-PATH -cp dist\Proj.jar;JavaSE.jar com.codename1.impl.javase.Simulator com.mycompany.hi.Main
(where C:\javafx-sdk-11.0.2\lib\ is our )
Thanks!
The TL;DR
Either install CEF as explained here or switch to ZuluFX 11 for your VM.
The explanation:
This used to work until we integrated CEF support we would download JavaFX dynamically for JDK 11 installs but this caused a lot of related problems. So we decided to migrate to CEF, this is still in progress and while it's ongoing JavaFX dynamic download is broken. Once it's done CEF will be auto-installed and this will be seamless again.
This impacts browser component and media which are the two components implemented by JavaFX.

Solr - How to trigger the DIH from SolrNet API with C# code

Solr version :: 6.6.1
SolrNet API with the C# based application
I wish to invoke or trigger the data import handler from the C# code with
the help of SolrNet. But i am unable to locate any tutorial in the SolrNet
API. I can easily invoke the DIH from the solr admin UI, but my need is to invoke it from an external application.
Please suggest the code snippet how do i invoke the data import action from the C# based
application ?
I don't think it's possible to do completely from Solr.NET, a brief look gives me an idea, that currently there is only class responsible for DIH status page, which is good, but not covering the initial process. I think this was discarded recently, since this functionality wasn't needed.
In the SolrBasicServer class you have:
public SolrDIHStatus GetDIHStatus(KeyValuePair<string, string> options) {
var response = connection.Get("/dataimport", null);
var dihstatus = XDocument.Parse(response);
return dihStatusParser.Parse(dihstatus);
}
which is getting the DIH. Most likely, you need to extend this class and do something similar (I'm not C# developer, so not 100% sure about the code):
connection.Post("/dataimport?command=full-import", null);
or something similar with delta-import command and then later get the status part.
If updating Solr.NET is not the case for you, you still could just trigger it via usual HTTP call with some preferable C# library and do POST request to http://host:port/solr/collection-name/dataimport?command=full-import
string solrTargetDIHUrl = "http://localhost:8983/solr/dih/dataimport?command=delta-import";
try
{
using (var solrClient = new HttpClient())
{
var resultObj = solrClient.GetAsync(new Uri(solrTargetDIHUrl)).Result;
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("\t\t Data Import Triggered Successfully !");
Console.ResetColor();
}
}
catch(Exception ex)
{
Console.WriteLine("ERROR in DIH Trigger >>>>> " + ex.Message + "||" + ex.StackTrace);
}

dart dartdap exception when parsing search result

I'm using the dartdap library to connect to an LDAP server on Win 2008. The bind operation works fine. As soon as I perform any search I get an exception while the result is parsed by dartdap.
Exception while processing message. Exception RangeError: Value not in range (158)
The stack trace points here:
package:dartdap/src/connection/connection_manager.dart:297:21
Here is the code I use:
var filter = Filter.substring("CN=ma*");
var attrs = ["dn", "cn", "objectClass"];
LDAPConfiguration ldapConfig = new LDAPConfiguration("ldap.yaml","default");
LDAPConnection ldap;
ldapConfig.getConnection(false).then((LDAPConnection ldap){
ldap.bind(/*bindDN*/"CN=CP LDAP,OU=Contract Program,DC=mydomain,DC=de",/*password*/"xxxxx").then((_){
ldap.search("DC=mydomain,DC=de", filter, attrs).stream.forEach((item)=>print(item)).catchError((err) =>print(err));
}).catchError((err)=>print(err));
}).catchError((err)=>print(err));
For my project I need to authenticate users using data from an Active Directory. Any help would be appreciated.

Windows Phone 7 App Quits when I attempt to deserialize JSON

I'm developing my first windows phone 7 app, and I've hit a snag. basically it's just reading a json string of events and binding that to a list (using the list app starting point)
public void Load()
{
// form the URI
UriBuilder uri = new UriBuilder("http://mysite.com/events.json");
WebClient proxy = new WebClient();
proxy.OpenReadCompleted += new OpenReadCompletedEventHandler(OnReadCompleted);
proxy.OpenReadAsync(uri.Uri);
}
void OnReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
var serializer = new DataContractJsonSerializer(typeof(EventList));
var events = (EventList)serializer.ReadObject(e.Result);
foreach (var ev in events)
{
Items.Add(ev);
}
}
}
public ObservableCollection<EventDetails> Items { get; private set; }
EventDetails is my class that wraps the json string. this class has to be correct because it is an exact copy of the class used by that website internally from which the json is generated...
I get the json string correctly from the webclient call (I read the memorystream and the json is indeed there) but as soon as I attempt to deserialize the string, the application exits and the debugger stops.
I get no error message or any indication that anything happen, it just stops. This happens if I type the deserialize method into the watch window as well...
I have already tried using JSON.net in fact I thought maybe it was a problem with JSON.net so I converted it to use the native deserializer in the .net framework but the error is the same either way.
why would the application just quit? shouldn't it give me SOME kind of error message?
what could I be doing wrong?
many thanks!
Firstly, the fact that you have some string there that looks like JSON does not mean that you have a valid JSON. Try converting a simple one.
If your JSON is valid, it might be that your JSON implementation does not know how to convert a list to EventList. Give it a try with ArrayList instead and let me know.
The application closes because an unhandled exception happens. If check the App.xaml.cs file you will find the code that closes your app. What you need to do is try catch your deserialization process and handle it locally. So most likely you have some JSON the DataContractJsonSerializer does not like. I have been having issue with it deserializing WCF JSON and have had to go other routes.
You may want to check to ensure your JSON is valid, just because your website likes it does not mean it is actually valid, the code on your site may be helping to correct the issue. Drop a copy of your JSON object (the string) in http://jsonlint.com/ to see if it is valid or not. Crokford (the guy who created JSON) wrote this site to validate JSON, so I would rely on it more than your site ;) This little site has really helped me out of some issues over the past year.
I ran into this same kind of problem when trying to migrate some existing WM code to run on WP7. I believe that the WP7 app crashes whenever it loads an assembly (or class?) that references something that's not available in WP7. In my case, I think it was Assembly.Load or something in the System.IO namespace, related to file access via paths.
While your case might be something completely different, the symptoms were exactly the same.
The only thing I can recommend is to go through the JSON library and see if it's referencing base classes that are not allowed in WP7. Note that it doesn't even have to hit the line of code that's causing the issue - it'll crash as soon as it tries to hit the class that contains the bad reference.
If you can step into the JSON library, you can get a better idea of which class is causing the problem, because as soon as the code references it, the whole app will crash and the debugger will stop.

Resources