Querying Solr via Solrj: Basics - java

I am trying to query solr via solrj in Eclipse.
I have tried the latest solrj wiki example:
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.params.ModifiableSolrParams;
import java.net.MalformedURLException;
public class SolrQuery2 {
public static void main(String[] args) throws MalformedURLException, SolrServerException {
SolrServer solr = new CommonsHttpSolrServer("http://localhost:8080/solr");
// http://localhost:8080/solr/select/?q=outside
ModifiableSolrParams params = new ModifiableSolrParams();
params.set("qt", "/select");
params.set("q", "outside");
QueryResponse response = solr.query(params);
System.out.println("response = " + response);
}
}
However, I cant get past this error no matter what I do:
Exception in thread "main" java.lang.NoSuchMethodError:
org.slf4j.spi.LocationAwareLogger.log(Lorg/slf4j/Marker;Ljava/lang/String;ILjava/lang/String;[Ljava/lang/Object;Ljava/lang/Throwable;)V
Next, I tried the cookbook example:
import java.util.Iterator;
import org.apache.solr.client.solrj.SolrQuery; //Error: The import org.apache.solr.client.solrj.SolrQuery conflicts with a type defined in the same file
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
public class SolrQuery {
public static void main(String[] args) throws Exception {
CommonsHttpSolrServer server = new CommonsHttpSolrServer("http://localhost:8080/solr");
server.setParser(new XMLResponseParser());
SolrQuery query = new SolrQuery();
query.setQuery("document"); //Error: The method setQuery(String) is undefined for the type SolrQuery
query.setStart(0); //Error: The method setStart(int) is undefined for the type SolrQuery
query.setRows(10); //Error: The method setRows(int) is undefined for the type SolrQuery
QueryResponse response = server.query(query); //Error: The method query(SolrParams) in the type SolrServer is not applicable for the arguments (SolrQuery)
SolrDocumentList documents = response.getResults();
Iterator<SolrDocument> itr = documents.iterator();
System.out.println("DOCUMENTS");
while(itr.hasNext()){
SolrDocument doc = itr.next();
System.out.println(doc.getFieldValue("id")+":"+doc.getFieldValue("content"));
}
}
}
However, that example might be dated for the current api as I cant even import the SolrQuery library.
Does anyone have a quick boilerplate example that works?
Thank you in advance.
PS. I am running windows7 with tomcat7 and solr 3.5. All I am trying to do at this point is a basic query and get the results back in some kind of list, array, whatever. When I query: http://localhost:8080/solr/select/?q=outside in firefox, the results come back just fine.

Here is how I got Solrj (Solr 3.6) working on my Windows7 box with eclipse:
import java.net.MalformedURLException;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.params.ModifiableSolrParams;
public class SolrQuery {
public static void main(String[] args) throws MalformedURLException, SolrServerException {
SolrServer server = new HttpSolrServer("http://localhost:8080/solr");
ModifiableSolrParams params = new ModifiableSolrParams();
params.set("q", "1");
QueryResponse response = server.query(params);
System.out.println("response = " + response);
}
}
I had to download additional jars (outside Solr of 3.6) for this to work: httpcomponents-client-4.2-beta1
In total, I needed 4 jars to get this working :
apache-solr-solrj-3.6.0.jar
httpclient-4.2-beta1.jar
httpcore-4.2-beta1.jar
httpmime-4.2-beta1.jar
Im not sure if my solution is considered a best practice in terms of boilercode, but it solves the issue of getting up on solrj w/ eclipse.

The org.slf4j.spi.LocationAwareLogger class is provided by the slf4j-api jar. What version are you running? Solr 3.5 requires version 1.6.1, I suspect you're using an eariler version.
If you're looking for a Solrj quick-start I'd recommend switching to Groovy. It can download the jar dependencies at run-time using Grab annotations. Example:
parse Solr xml files to SolrInputDocument

Related

mongodb Java Driver build error : cannot access com.mongodb.client.result.InsertOneResult, class file not found

I'm following the Installation and Quick Start on the latest (4.2.2) Mongodb Java drivers.
I'm getting this compile error:
Error:(29, 29) java: cannot access com.mongodb.client.result.InsertOneResult
class file for com.mongodb.client.result.InsertOneResult not found
This is part of a larger project, so could there be another version of mongo somewhere on the class path?
There is only one the pom, and it is this, straight from the Installation page:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.2.2</version>
</dependency>
I'm using IntelliJ, and in it's External Dependencies for mongo, it has these:
org.mongodb:bson:3.8.2
org.mongodb:mongodb-driver-core:3.8.2
org.mongodb:mongodb-driver-sync:4.2.2
Here's the code :
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.Arrays;
public class MongoTest {
public static void main(String[] args) {
MongoTest mongoTest = new MongoTest();
mongoTest.init();
}
public void init() {
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
MongoDatabase myTestDb = mongoClient.getDatabase("myTestDb");
MongoCollection<Document> collection = myTestDb.getCollection("test");
Document doc = new Document("name", "MongoDB")
.append("type", "database")
.append("count", 1)
.append("versions", Arrays.asList("v3.2", "v3.0", "v2.6"))
.append("info", new Document("x", 203).append("y", 102));
collection.insertOne(doc);
}
}
You need all three dependencies, but they should all be the same version, e.g.
org.mongodb:bson:4.2.2
org.mongodb:mongodb-driver-core:4.2.2
org.mongodb:mongodb-driver-sync:4.2.2
If you take a dependency only on mongodb-driver-sync, the others should be picked up transitively. But it sounds like there is a conflict somewhere which is causing you to pick up older versions of bson and mongodb-driver-core. You will need to determine where that conflict is coming from and address it.

Deploy a pod using Java Kubernetes client Api

What is the clean way to deploy a pod using kubernetes client api in Java ?
import io.kubernetes.client.ApiClient;
import io.kubernetes.client.ApiClient;
import io.kubernetes.client.ApiException;
import io.kubernetes.client.Configuration;
import io.kubernetes.client.apis.CoreV1Api;
import io.kubernetes.client.models.V1Pod;
import io.kubernetes.client.models.V1PodList;
import io.kubernetes.client.util.Config;
import java.io.IOException;
public class Example {
public static void main(String[] args) throws IOException, ApiException{
ApiClient client = Config.defaultClient();
Configuration.setDefaultApiClient(client);
CoreV1Api api = new CoreV1Api();
V1Pod podTemplate = init_pod;
V1Pod pod = api.createNamespacedPod(pod creation arguments and podTemplate)
System.out.println("pod status : " + pod.getStatus().getPhase());
}
}
The above code might not be accurate. But this code might give you a gist of getting started.
A sample medium post that describes using java client of kubernetes is here

Neo4j Java API, how to specify the path of creating database

According to the document of Neo4j, I tried below to create the database using Neo4j Java APIs in Eclipse:
GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase("D:/Eclipse/Workplace/test");
and also tried to set the path under the Neo4j folder("D:\Neo4j3.0.1\workplace3"). But I got the same error:
The method newEmbeddedDatabase(File) in the type GraphDatabaseFactory is not applicable for the arguments (String)
Then I tried to import java.io.File; and add:
File dbpath = new File("D:/Neo4j3.0.1/workplace3");
org.neo4j.graphdb.GraphDatabaseService db = dbFactory.newEmbeddedDatabase(dbpath);
then the previous two packages are not used: org.neo4j.graphdb.GraphDatabaseService;, org.neo4j.graphdb.Transaction; But I can compile the program and show "Done successfully" in the Eclipse console.
When I tried to connect to the database using neo4j-ce.exe, it gave me below Alert:
Starting Neo4j failed: Component org.neo4j.server.database.LifecycleManagingDatabase#397b7f" was successfully initialized, but failed to start. Please see attached cause exception.
My code:
package com.peterlan522.neo4j.java.example;
import java.io.File;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.RelationshipType;
public class Neo4jJavaAPIDBOperation {
public enum Tutorials implements Label { JAVA, SCALA, SQL, NEO4J,}
public enum TutorialRelationships implements RelationshipType { JVM_LANGIAGES, NON_JVM_LANGIAGES,}
public static void main(String[] args) {
org.neo4j.graphdb.factory.GraphDatabaseFactory dbFactory = new GraphDatabaseFactory();
File dbpath = new File("D:/Neo4j3.0.1/workplace3");
//GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase("D:/Eclipse/Workplace/test");
org.neo4j.graphdb.GraphDatabaseService db = dbFactory.newEmbeddedDatabase(dbpath);
try (org.neo4j.graphdb.Transaction tx = db.beginTx()) {
Node javaNode = db.createNode(Tutorials.JAVA);
javaNode.setProperty("TutorialID", "JAVA001");
javaNode.setProperty("Title", "Learn Java");
javaNode.setProperty("NoOfChapters", "25");
javaNode.setProperty("Status", "Completed");
Node scalaNode = db.createNode(Tutorials.SCALA);
scalaNode.setProperty("TutorialID", "SCALA001");
scalaNode.setProperty("Title", "Learn Scala");
scalaNode.setProperty("NoOfChapters", "20");
scalaNode.setProperty("Status", "Completed");
Relationship relationship = javaNode.createRelationshipTo
(scalaNode,TutorialRelationships.JVM_LANGIAGES);
relationship.setProperty("Id","1234");
relationship.setProperty("OOPS","YES");
relationship.setProperty("FP","YES");
tx.success();
}
System.out.print("Done successfully");
}
}
Could anyone help on this? And give executable examples on this. Thank you so much!
Below are the softwares version:
Neo4j community version 3.0.1,
Eclipse Mars(4.5.0),
Java 1.8.0_91,
JRE System Library: JavaSE-1.8
And please get in below link to see the log.txt:
https://drive.google.com/file/d/0B2xDq3--mwK4a0FoanlDengzVWs/view?usp=sharing

Java Rest API client - GET method - Error 415

I am new to writing Java client for Restful API using Apache CXF.
On running below code I am getting error 415 returned which when I looked online shows as "unsupported media type". In order to fix it I changed the code to "target.request(MediaType.APPLICATION_XML)" from original target.request(). However this didn't fix the code.
What is the best way to debug this issue?
Thanks a lot in advance for your time.
Update: After discussion with the Rest API developer I came to know that I need to add a header "("Content-Type", "application/x-www-form-urlencoded");". but I am not sure how to add a header. Does anyone know how to add this header here?
package com.blackhawk.ivr.restAPI.client;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
public class BlissRestAPI {
public static final String BLISS_SERVICRE_URL = "http://x.x.x.x:9090/services";
public static void main(String[] args) {
Client client = ClientBuilder.newClient();
WebTarget target = client.target(BLISS_SERVICRE_URL);
target = target.path("/cardmanagementservices/v3/card/status").queryParam("ani", "xxxxxxxxxx").queryParam("card.expiration", "xxxxxx").queryParam("card.number", "xxxxxxxxxxxxxxxx").queryParam("channel.id", "xyz");
Invocation.Builder builder = target.request(MediaType.APPLICATION_XML);
Response response = builder.get();
System.out.println(response.getStatus());
response.close();
client.close();
}
}
First you can change the media type as given below.
Client: MediaType.APPLICATION_XML
Rest: MediaType.APPLICATION_JSON
JAX-WS are Java standard to build web service. So you have used it here, As my knowledge it is easy to use axis 2 to this kind of web services and clients since there are more implementations of JAX-WS. So i will give you a solution using apache axis technology.
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import javax.xml.rpc.ParameterMode;
public class axisClient {
public static void main(String [] args) throws Exception {
String endpoint = "http://localhost:8090/archive_name/service_name.jws";
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress( new java.net.URL(endpoint) );
call.setOperationName( "service_method_name" );
call.addParameter("parameter_name", XMLType.XSD_STRING, ParameterMode.IN );
call.setReturnType( XMLType.XSD_STRING );
call.setProperty(Call.CHARACTER_SET_ENCODING, "UTF-8");
String jsonString = (String) call.invoke( new Object [] { "parameter_value"});
System.out.println("Got result : " + jsonString);
}
}
I got it working by using below code (got 200 status returned)
WebClient client = WebClient.create(BLISS_SERVICRE_URL);
client.path("/cardmanagementservices/v3/card/status").query("ani", "xxxxxxxxxx").query("card.expiration", "xxxxxx").query("card.number", "xxxxxxxxxxxxxx").query("channel.id", "xxxxx");
client.type(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_XML);
client.header("Content-Type","application/x-www-form-urlencoded");
Response response = client.get();
System.out.println(response.getStatus());

example of stardog sparql insert query in java

Can somebody give one java example of sparql insert/Delete query in Stardog.
there is only queryExecution.execSelect() method available.
there is no queryExecution.execInsert() or queryExecution.execDelete() available.
Please give one working example.
EDIT
I've found this this from stardog docs page.
http://stardog.com/docs/#notes
As of 1.1.5, Stardog's SPARQL 1.1 support does not include: UPDATE query language
does that means no way out for editing a tuple once entered?
Stardog does not yet support SPARQL update, but as was pointed out to you on the mailing list, there are 5 ways you can modify the data once it's loaded. You can use our HTTP protocol directly, any of the 3 Java API's we support, or you can use the command line interface.
Below one is a sample program of inserting a graph and removing it.
package com.query;
import java.util.List;
import org.openrdf.model.Graph;
import org.openrdf.model.Statement;
import org.openrdf.model.URI;
import org.openrdf.model.impl.GraphImpl;
import org.openrdf.model.impl.ValueFactoryImpl;
import org.openrdf.query.QueryEvaluationException;
import com.clarkparsia.stardog.StardogDBMS;
import com.clarkparsia.stardog.StardogException;
import com.clarkparsia.stardog.api.Connection;
import com.clarkparsia.stardog.api.ConnectionConfiguration;
import com.clarkparsia.stardog.jena.SDJenaFactory;
import com.hp.hpl.jena.query.ParameterizedSparqlString;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.query.ResultSetFormatter;
import com.hp.hpl.jena.rdf.model.Model;
public class test {
public static void main(String[] args) throws StardogException, QueryEvaluationException {
String appDbName ="memDb";
String selectQuery="SELECT DISTINCT ?s ?p ?o WHERE { ?s ?p ?o }";
StardogDBMS dbms = StardogDBMS.toServer("snarl://localhost:5820/")
.credentials("admin", "admin".toCharArray()).login();
List<String> dbList = (List<String>) dbms.list();
if (dbList.contains(appDbName)) {
System.out.println("droping " + appDbName);
dbms.drop(appDbName);
}
dbms.createMemory(appDbName);
dbms.logout();
Connection aConn = ConnectionConfiguration
.to("memDb") // the name of the db to connect to
.credentials("admin", "admin") // credentials to use while connecting
.url("snarl://localhost:5820/")
.connect();
Model aModel = SDJenaFactory.createModel(aConn);
System.out.println("################ GRAPH IS EMPTY B4 SUBMITTING ="+aModel.getGraph()+ "################");
URI order = ValueFactoryImpl.getInstance().createURI("RDF:president1");
URI givenName = ValueFactoryImpl.getInstance().createURI("RDF:lincoln");
URI predicate = ValueFactoryImpl.getInstance().createURI("RDF:GivenNane");
Statement aStmt = ValueFactoryImpl.getInstance().createStatement(order,predicate,givenName);
Graph aGraph = new GraphImpl();
aGraph.add(aStmt);
insert(aConn, aGraph);
ParameterizedSparqlString paraQuery = new ParameterizedSparqlString(selectQuery);
QueryExecution qExecution = QueryExecutionFactory.create(paraQuery.asQuery(),aModel);
ResultSet queryResult = qExecution.execSelect();
System.out.println("############### 1 TUPPLE CAME AFTER INSERT ################");
ResultSetFormatter.out(System.out, queryResult);
aGraph.add(aStmt);
remove(aConn, aGraph);
paraQuery = new ParameterizedSparqlString(selectQuery);
qExecution = QueryExecutionFactory.create(paraQuery.asQuery(),aModel);
queryResult = qExecution.execSelect();
System.out.println("################ DB AGAIN EMPTY AFTER REMOVE ################");
ResultSetFormatter.out(System.out, queryResult);
System.out.println("closing connection and model");
aModel.close();
aConn.close();
}
private static void insert(final Connection theConn, final Graph theGraph) throws StardogException {
theConn.begin();
theConn.add().graph(theGraph);
theConn.commit();
}
private static void remove(final Connection theConn, final Graph theGraph) throws StardogException {
theConn.begin();
theConn.remove().graph(theGraph);
theConn.commit();
}
}

Categories