I'm programming an application Web (Semantic Web) and for storing the triples, using sesame, and for mapping of data alibaba. My question is, that way I have to implement the classes,to that at the base of triplets is store an object as a subclass of another , try interfaces but I got no results , below I present the "entities":
the parent class:
import java.math.BigInteger;
import org.openrdf.annotations.Iri;
#Iri(Parent.NS + "Parent")
public interface Parent {
public static final String NS = "http://www.spelta.ec/ontology/example#";
#Iri(Parent.NS +"code")
BigInteger getCode();
#Iri(Parent.NS +"code")
void setCode(BigInteger code);
#Iri(Parent.NS+"description")
String getDescription();
#Iri(Parent.NS+"description")
void setDescription(String description);
}
The child class:
import java.math.BigInteger;
public class Child implements Parent {
private BigInteger code;
private String description;
#Override
public BigInteger getCode() {
return code;
}
#Override
public void setCode(BigInteger code) {
this.code = code;
}
#Override
public String getDescription() {
return description;
}
#Override
public void setDescription(String description) {
this.description = description;
}
}
to consult the store of triples, should define an instance of the Children class is a subclass of Parent
many thanks
Related
I am trying to build a custom sink for unzipping files.
Having this simple code:
public static class ZipIO{
public static class Sink extends com.google.cloud.dataflow.sdk.io.Sink<String> {
private static final long serialVersionUID = -7414200726778377175L;
private final String unzipTarget;
public Sink withDestinationPath(String s){
if(s!=""){
return new Sink(s);
}
else {
throw new IllegalArgumentException("must assign destination path");
}
}
protected Sink(String path){
this.unzipTarget = path;
}
#Override
public void validate(PipelineOptions po){
if(unzipTarget==null){
throw new RuntimeException();
}
}
#Override
public ZipFileWriteOperation createWriteOperation(PipelineOptions po){
return new ZipFileWriteOperation(this);
}
}
private static class ZipFileWriteOperation extends WriteOperation<String, UnzipResult>{
private static final long serialVersionUID = 7976541367499831605L;
private final ZipIO.Sink sink;
public ZipFileWriteOperation(ZipIO.Sink sink){
this.sink = sink;
}
#Override
public void initialize(PipelineOptions po) throws Exception{
}
#Override
public void finalize(Iterable<UnzipResult> writerResults, PipelineOptions po) throws Exception {
long totalFiles = 0;
for(UnzipResult r:writerResults){
totalFiles +=r.filesUnziped;
}
LOG.info("Unzipped {} Files",totalFiles);
}
#Override
public ZipIO.Sink getSink(){
return sink;
}
#Override
public ZipWriter createWriter(PipelineOptions po) throws Exception{
return new ZipWriter(this);
}
}
private static class ZipWriter extends Writer<String, UnzipResult>{
private final ZipFileWriteOperation writeOp;
public long totalUnzipped = 0;
ZipWriter(ZipFileWriteOperation writeOp){
this.writeOp = writeOp;
}
#Override
public void open(String uID) throws Exception{
}
#Override
public void write(String p){
System.out.println(p);
}
#Override
public UnzipResult close() throws Exception{
return new UnzipResult(this.totalUnzipped);
}
#Override
public ZipFileWriteOperation getWriteOperation(){
return writeOp;
}
}
private static class UnzipResult implements Serializable{
private static final long serialVersionUID = -8504626439217544799L;
public long filesUnziped=0;
public UnzipResult(long filesUnziped){
this.filesUnziped=filesUnziped;
}
}
}
}
The processing fails with error:
Exception in thread "main" java.lang.IllegalArgumentException: Cannot setCoder(null)
at com.google.cloud.dataflow.sdk.values.TypedPValue.setCoder(TypedPValue.java:67)
at com.google.cloud.dataflow.sdk.values.PCollection.setCoder(PCollection.java:150)
at com.google.cloud.dataflow.sdk.io.Write$Bound.createWrite(Write.java:380)
at com.google.cloud.dataflow.sdk.io.Write$Bound.apply(Write.java:112)
at com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner$BatchWrite.apply(DataflowPipelineRunner.java:2118)
at com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner$BatchWrite.apply(DataflowPipelineRunner.java:2099)
at com.google.cloud.dataflow.sdk.runners.PipelineRunner.apply(PipelineRunner.java:75)
at com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner.apply(DataflowPipelineRunner.java:465)
at com.google.cloud.dataflow.sdk.runners.BlockingDataflowPipelineRunner.apply(BlockingDataflowPipelineRunner.java:169)
at com.google.cloud.dataflow.sdk.Pipeline.applyInternal(Pipeline.java:368)
at com.google.cloud.dataflow.sdk.Pipeline.applyTransform(Pipeline.java:275)
at com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner.apply(DataflowPipelineRunner.java:463)
at com.google.cloud.dataflow.sdk.runners.BlockingDataflowPipelineRunner.apply(BlockingDataflowPipelineRunner.java:169)
at com.google.cloud.dataflow.sdk.Pipeline.applyInternal(Pipeline.java:368)
at com.google.cloud.dataflow.sdk.Pipeline.applyTransform(Pipeline.java:291)
at com.google.cloud.dataflow.sdk.values.PCollection.apply(PCollection.java:174)
at com.mcd.de.tlogdataflow.StarterPipeline.main(StarterPipeline.java:93)
Any help is appreciated.
Thanks & BR
Philipp
This crash is caused by a bug in the Dataflow Java SDK (specifically, this line) which was also present in the Apache Beam (incubating) Java SDK.
The method Sink.WriterOperation#getWriterResultCoder() must always be overridden, but we failed to mark it abstract. It is fixed in Beam, but unchanged in the Dataflow SDK. You should override this method and return an appropriate coder.
You have some options to come up with the coder:
Write your own small coder class, wrapping one of VarLongCoder or BigEndianLongCoder
Just use a long instead of the UnzipResult structure so you can use those as-is.
Less advisable due to the excess size, you could use SerializableCoder.of(UnzipResult.class)
I'm trying to follow the new Cineasts app with SDN 4.0.0.M1 and SpringBoot to learn Spring and Neo4j but I have an error when I try to access the movie url with
curl http://localhost:8080/movies
MappingException: Error mapping GraphModel to instance
I implemented the minimum to get something working so the code is simple but I probably forgot something
the movie class
#NodeEntity
public class Movie {
#GraphId
private Long nodeId;
private String id;
private String title;
public Movie() {
}
public Movie(String id, String title) {
this.id = id;
this.title = title;
}
}
the associated MovieRepository is empty at the moment
public interface MovieRepository extends GraphRepository<Movie> {
}
the MovieController
#Autowired
private MovieRepository movieRepository;
#Autowired
private Session session;
#RequestMapping(value = "/movies/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
public
#ResponseBody
Movie getMovie(#PathVariable String id) {
return IteratorUtil.firstOrNull(findMovieByProperty("id", id));
}
public Iterable<Movie> findMovieByProperty(String propertyName, Object propertyValue) {
return session.loadByProperty(Movie.class, new Property(propertyName, propertyValue));
}
and the main class with database connection
#SpringBootApplication
#EnableNeo4jRepositories("cineasts.repository")
#EnableTransactionManagement
public class CineastsApplication extends Neo4jConfiguration {
public static final int NEO4J_PORT = 7474;
#Bean
public Neo4jServer neo4jServer() {
return new RemoteServer("http://localhost:" + NEO4J_PORT);
}
#Override
public SessionFactory getSessionFactory() {
return new SessionFactory("org.neo4j.cineasts.domain");
}
#Override
#Bean
#Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public Session getSession() throws Exception {
return super.getSession();
}
public static void main(String[] args) {
SpringApplication.run(CineastsApplication.class, args);
}
}
I started Neo4j and added one record with Neo4j browser
CREATE (m:Movie {id:1, name:'The Matrix'}) return m
when I go to localhost:8080 I can see the json response
{
"_links" : {
"movies" : {
"href" : "http://localhost:8080/movies"
},
"profile" : {
"href" : "http://localhost:8080/alps"
}
}
but it fails to display the movies or http://localhost:8080/movies/1 record I just created. Any idea to fix this or get a more relevant message?
Thanks!
The problem could be the fact that your entity definition does not match that of the node you've created.
The Movie class defines a property id of data type String, and a property title of type String.
The Cypher you used however
CREATE (m:Movie {id:1, name:'The Matrix'}) return m
creates a node with a number id instead of a String id and a name property instead of a title property.
Changing the above to
CREATE (m:Movie {id:'1', title:'The Matrix'}) return m
should fix it.
Is it possible to add #NodeEntity (or even #RelationshipEntity) annotation from SpringData Neo4j on an interface or abstact class or their fields? If not, how do you manage these situations?
Definitely you can do that on Abstract classes, and I think it's a good practice in some common cases. Let me give you an example that I'm using in my graph model:
#NodeEntity
public abstract class BasicNodeEntity implements Serializable {
#GraphId
private Long nodeId;
public Long getNodeId() {
return nodeId;
}
#Override
public abstract boolean equals(Object o);
#Override
public abstract int hashCode();
}
public abstract class IdentifiableEntity extends BasicNodeEntity {
#Indexed(unique = true)
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof IdentifiableEntity)) return false;
IdentifiableEntity entity = (IdentifiableEntity) o;
if (id != null ? !id.equals(entity.id) : entity.id != null) return false;
return true;
}
#Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
}
Example of entity idenifiable.
public class User extends IdentifiableEntity {
private String firstName;
// ...
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
OTOH, as far as I know, if you annotate an interface with #NodeEntity, those classes who implement the interface DON'T inherite the annotation. To be sure I've made a test to check it and definately spring-data-neo4j throws an Exception because don't recognize the inherited class neither an NodeEntity nor a RelationshipEntity.
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'neo4jMappingContext' defined in class org.springframework.data.neo4j.config.Neo4jConfiguration: Invocation of init method failed; nested exception is org.springframework.data.neo4j.mapping.InvalidEntityTypeException: Type class com.xxx.yyy.rest.user.domain.User is neither a #NodeEntity nor a #RelationshipEntity
Hope it helps
#NodeEntity or #RelationshipEntity needs to be defined on POJO or concrete classes. Think it same as #Entity in Hibernate.
But do you see any valid use case for annotating Interfaces or Abstract Classes?
I encountered some difficulties during playing with neo4j. Firstly, when I try to delete defined #EntityModel, I get an exception (Please, forgive me the quality of pics, the exception messages are also in question title):
My Controller (this is just for testing purpouse):
#Controller
public class HomeController {
#Autowired
PersonRepository personRepository;
#RequestMapping(value="/", method = RequestMethod.GET)
public String loadPage(final Model model, final HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
Person person = new Person("My person");
personRepository.save(person);
personRepository.findOne(person.getId());
return "home";
}
}
And model:
#NodeEntity
public class Person {
#GraphId
private Long id;
private String name;
public Person() {}
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public Long getId() {
return id;
}
}
Configuration file:
#Configuration
#EnableTransactionManagement
#EnableNeo4jRepositories(basePackages = "com.springapp.mvc.repository")
#ComponentScan({"com.springapp.mvc"})
public class PersistenceConfig extends Neo4jConfiguration {
#Bean
public GraphDatabaseService graphDatabaseService() {
return new SpringRestGraphDatabase("http://localhost:7474/db/data");
}
}
My Repository:
public interface PersonRepository extends GraphRepository<Person> {
#Query("MATCH (n:Person{name: \"{namveValue}\"}) RETURN n;")
Person findByName(#Param("nameValue") final String name);
}
What am I doing wrong? I figured out that perhaps Person should implement org.neo4j.graphdb.Node and this is the source of these exceptions. However, having searched github repos I see that people do not implement this interface in their models. I have not found solution on stackoverflow so far.
Node exists in database but I cannot either delete it or save it. Please, help.
You are trying to see if a node with ID '0' exists as a person. Since the root node hasn't got a '__type__' property, the call will fail. SDN uses this property to determine the entity type of a node.
That being said, the exception seems to be caused by the following line:
if(! personRepository.exists(0L)) {
I want to get the instance of the Entity from SelectOneMenu so i can assign the entity variables to some other method. But it is pointing to null.
xhtml code
<h:selectOneMenu value="#{statusReport.projectDetID}" converter="ObjectStringConv" onchange="#{statusReport.retrieveReport()}" >
<f:selectItems value="#{statusReport.listOfProjectDetail}"
var="projectDetail" itemLabel="#{projectDetail.project} #{projectDetail.startDate} - #{projectDetail.endDate}"
itemValue="#{projectDetail}" noSelectionValue="Select the Saved Project"/>
</h:selectOneMenu>
statusReport bean
public class StatusReport implements Serializable {
private ProjectDetail projectDetID;
private List<ProjectDetail> listOfProjectDetail;
public List<ProjectDetail> getListOfProjectDetail() {
listOfProjectDetail = projectDetailFacade.findAll();
return listOfProjectDetail;
}
public void setListOfProjectDetail(List<ProjectDetail> listOfProjectDetail) {
this.listOfProjectDetail = listOfProjectDetail;
}
public ProjectDetail getProjectDetID() {
return projectDetID;
}
public void setProjectDetID(ProjectDetail projectDetID) {
this.projectDetID = projectDetID;
}
public void retrieveReport(){
System.out.println(" Processing .....");
if ( projectDetID == null )
{
System.out.println("The object from Select null");
}
else
{
System.out.println("The object from Select menu" + projectDetID.toString());
}
System.out.println("Generated Data:Completed");
}}
ProjectDetail Entity Bean
package com.jira.entity;
import java.io.Serializable;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
/**
* The persistent class for the PROJECT_DETAIL database table.
*
*/
#Entity
#Table(name="PROJECT_DETAIL",schema="weeklyrep")
public class ProjectDetail implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="projectdetail_seq")
#SequenceGenerator(name="projectdetail_seq",schema="weeklyrep",sequenceName="projectdetail_seq", allocationSize=1)
#Column(name="PDETAIL_ID")
private long pdetailId;
private Boolean completed;
#Temporal( TemporalType.DATE)
#Column(name="END_DATE")
private Date endDate;
private Long project;
#Temporal( TemporalType.DATE)
#Column(name="START_DATE")
private Date startDate;
//bi-directional many-to-one association to MajorEvent
#OneToMany(mappedBy="projectDetail",cascade=CascadeType.ALL)
private List<MajorEvent> majorEvents;
//bi-directional one-to-one association to ExecSummary
#OneToOne(mappedBy="projectDetailExec",cascade=CascadeType.ALL)
private ExecSummary execSummary;
public ProjectDetail() {
}
public long getPdetailId() {
return this.pdetailId;
}
public void setPdetailId(Long pdetailId) {
this.pdetailId = pdetailId;
}
public Boolean getCompleted() {
return this.completed;
}
public void setCompleted(Boolean completed) {
this.completed = completed;
}
public Date getEndDate() {
return this.endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public long getProject() {
return this.project;
}
public void setProject(long project) {
this.project = project;
}
public Date getStartDate() {
return this.startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public List<MajorEvent> getMajorEvents() {
return this.majorEvents;
}
public void setMajorEvents(List<MajorEvent> majorEvents) {
this.majorEvents = majorEvents;
}
public ExecSummary getExecSummary() {
return execSummary;
}
public void setExecSummary(ExecSummary execSummary) {
this.execSummary = execSummary;
}
}
Converter
I don't know if it needs converter, however i don't know how code it.
package com.weeklyreport.converters;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import com.jira.entity.ProjectDetail;
#FacesConverter(value="ObjectStringConv")
public class ObjectStringConv implements Converter {
#Override
public Object getAsObject(FacesContext context, UIComponent component, String svalue) {
System.out.print("String version of object is:" + svalue);
return "test";
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object ovalue) {
return ovalue.toString();
}
}
Please help me figure this out. Is there a way we get instance of the entity object like this?
Your converter needs to be written that way so that it can convert between ProjectDetail and String based on an unique identifier of ProjectDetail. Usually entities have an id. You need to use this as String value. Here's a kickoff example without any trivial checks like null and instanceof:
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
// Convert ProjectDetail to its unique String representation.
ProjectDetail projectDetail = (ProjectDetail) value;
String idAsString = String.valueOf(projectDetail.getId())
return idAsString;
}
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
// Convert unique String representation of ProjectDetail back to ProjectDetail object.
Long id = Long.valueOf(value);
ProjectDetail projectDetail = someProjectDetailService.find(id);
return projectDetail;
}
Note that using EJBs in JSF converters (and validators) needs some hackery. See also How to inject #EJB, #PersistenceContext, #Inject, #Autowired, etc in #FacesConverter?