I've instances of Person (nodes) who writes (relationships) instances of Status (nodes). This is a bit far-fetched I know, but I wanted to train.
Whenever, I try to persist a Person, here is what I get:
org.springframework.data.neo4j.mapping.InvalidEntityTypeException: Type class org.springframework.data.neo4j.fieldaccess.GraphBackedEntityIterableWrapper is neither a #NodeEntity nor a #RelationshipEntity
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.createPersistentEntity(Neo4jMappingContext.java:48)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.createPersistentEntity(Neo4jMappingContext.java:38)
at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:235)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:165)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:140)
at org.springframework.data.neo4j.support.mapping.EntityStateHandler.getId(EntityStateHandler.java:67)
at org.springframework.data.neo4j.support.mapping.EntityStateHandler.getPersistentState(EntityStateHandler.java:84)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityFetchHandler.fetch(Neo4jEntityFetchHandler.java:58)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityConverterImpl$1.doWithAssociation(Neo4jEntityConverterImpl.java:116)
at org.springframework.data.mapping.model.BasicPersistentEntity.doWithAssociations(BasicPersistentEntity.java:185)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityConverterImpl.cascadeFetch(Neo4jEntityConverterImpl.java:106)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityConverterImpl.loadEntity(Neo4jEntityConverterImpl.java:100)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityConverterImpl.read(Neo4jEntityConverterImpl.java:90)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister$CachedConverter.read(Neo4jEntityPersister.java:168)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister.createEntityFromState(Neo4jEntityPersister.java:186)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister.persist(Neo4jEntityPersister.java:239)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister.persist(Neo4jEntityPersister.java:227)
at org.springframework.data.neo4j.support.Neo4jTemplate.save(Neo4jTemplate.java:295)
at org.springframework.data.neo4j.repository.AbstractGraphRepository.save(AbstractGraphRepository.java:106)
at sun.reflect.GeneratedMethodAccessor19.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:322)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:307)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:155)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy29.save(Unknown Source)
at sun.reflect.GeneratedMethodAccessor18.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy30.save(Unknown Source)
at com.lateralthoughts.devinlove.framework.GraphPopulator.loadABunchOfPeopleIntoTheMatrix(GraphPopulator.java:84)
Here come the entities:
#NodeEntity
public class Person {
public enum ProfoundIdentity {
DEVELOPER, ARCHITECT, SYSADMIN, MANAGER, BOSS;
}
#GraphId
private Long id;
private String firstName;
private String lastName;
private String favoriteColor;
private Mascot mascot;
#RelatedTo(elementClass = Person.class, type = "IS_FRIEND_WITH", direction = BOTH)
private final Set<Person> friends = new LinkedHashSet<Person>();
#RelatedTo(elementClass = Tool.class, type = "WORKS_WITH", direction = OUTGOING)
private final Set<Tool> tools = new LinkedHashSet<Tool>();
/**
* Simplistic European-formatted shoe size
*/
private int shoeSize;
#Fetch
#RelatedToVia(elementClass = StatusRedaction.class, type = "WRITES", direction = OUTGOING)
private final Collection<StatusRedaction> statuses = new LinkedList<StatusRedaction>();
private ProfoundIdentity profoundIdentity;
public Long getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void setFavoriteColor(final String favoriteColor) {
checkNotNull(favoriteColor);
this.favoriteColor = favoriteColor.toUpperCase();
}
public String getFavoriteColor() {
return favoriteColor;
}
public void setMascot(final Mascot mascot) {
this.mascot = mascot;
}
public Mascot getMascot() {
return mascot;
}
public Set<Person> getFriends() {
return unmodifiableSet(friends);
}
public void addFriend(final Person friend) {
checkNotNull(friend);
friends.add(friend);
}
public void addTool(final Tool tool) {
checkNotNull(tool);
tools.add(tool);
}
public Set<Tool> getTools() {
return unmodifiableSet(tools);
}
public void setShoeSize(final int shoeSize) {
checkArgument(shoeSize > 0 && shoeSize < 80);
this.shoeSize = shoeSize;
}
public int getShoeSize() {
return shoeSize;
}
public Iterable<StatusRedaction> getStatuses() {
return statuses;
}
public StatusRedaction addStatus(final Status message, final Date creationDate) {
final StatusRedaction statusRedaction = new StatusRedaction(this, message, creationDate);
statuses.add(statusRedaction);
return statusRedaction;
}
public void setProfoundIdentity(final ProfoundIdentity profoundIdentity) {
checkNotNull(profoundIdentity);
this.profoundIdentity = profoundIdentity;
}
public ProfoundIdentity getProfoundIdentity() {
return profoundIdentity;
}
public void setFirstName(final String firstName) {
this.firstName = firstName;
}
public void setLastName(final String lastName) {
this.lastName = lastName;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getFirstName() == null) ? 0 : getFirstName().hashCode());
result = prime * result + ((getLastName() == null) ? 0 : getLastName().hashCode());
return result;
}
#Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (getFirstName() == null) {
if (other.getFirstName() != null)
return false;
}
else if (!getFirstName().equals(other.getFirstName()))
return false;
if (getLastName() == null) {
if (other.getLastName() != null)
return false;
}
else if (!getLastName().equals(other.getLastName()))
return false;
return true;
}
}
Here is the status:
#NodeEntity
public class Status {
#GraphId
private Long id;
private String message = "";
public Status() {}
public Status(final String message) {
this.message = message;
}
public void setMessage(final String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public Long getId() {
return id;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
#Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Status other = (Status) obj;
if (id == null) {
if (other.id != null)
return false;
}
else if (!id.equals(other.id))
return false;
return true;
}
}
And here is the relationship:
#RelationshipEntity(type = "WRITES")
public class StatusRedaction {
#GraphId
private Long id;
#StartNode
private Person author;
#EndNode
private Status status = new Status("");
private Date creationDate = new Date();
public StatusRedaction() {}
public StatusRedaction(final Person author, final Status status, final Date creationDate) {
this.author = author;
this.status = status;
this.creationDate = creationDate;
}
public Long getId() {
return id;
}
public Person getAuthor() {
return author;
}
public void setAuthor(final Person author) {
this.author = author;
}
public Status getStatus() {
return status;
}
public String getStatusMessage() {
return status.getMessage();
}
public void setStatus(final Status status) {
this.status = status;
}
public Date getCreationDate() {
return creationDate;
}
// shouldnt be here, I know...
public String getFormattedDate() {
PrettyTime prettyTime = new PrettyTime(new Locale("en"));
return prettyTime.format(creationDate);
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
#Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
StatusRedaction other = (StatusRedaction) obj;
if (id == null) {
if (other.id != null)
return false;
}
else if (!id.equals(other.id))
return false;
return true;
}
}
And finally, the code in charge of persisting users:
public class GraphPopulator implements ApplicationListener<ContextRefreshedEvent> {
#Autowired
private MascotRepository mascotRepository;
#Autowired
private PersonRepository personRepository;
#Autowired
private ToolRepository toolRepository;
#Autowired
private CategoryRepository categoryRepository;
#Override
public void onApplicationEvent(final ContextRefreshedEvent event) {
loadData();
}
public void loadData() {
/* [...] inserting other entities [...] */
loadABunchOfPeopleIntoTheMatrix();
}
/**
* [...]
*/
private void loadABunchOfPeopleIntoTheMatrix() {
personRepository.save(person("John", "Doe", "blue", "Tux", DEVELOPER, 42, "Hello world", "Java Standard Edition"));
personRepository.save(person("Jane", "Doe", "green", "Django Pony", DEVELOPER, 45, "A World Appart (Info)", "Python"));
}
private Person person(final String firstName, final String lastName, final String color, final String mascotName, final Person.ProfoundIdentity profoundIdentity, final int shoeSize, final String firstStatus, final String toolName) {
Person person = new Person();
person.setFavoriteColor(color);
person.setFirstName(firstName);
person.setLastName(lastName);
person.setMascot(findMascot(mascotName));
person.setProfoundIdentity(profoundIdentity);
person.setShoeSize(shoeSize);
person.addStatus(new Status("Hello world"), new Date());
return person;
}
private Tool findTool(final String toolname) {
return toolRepository.findByPropertyValue("name", toolname);
}
private Mascot findMascot(final String mascotName) {
return mascotRepository.findByPropertyValue("name", mascotName);
} }
And the corresponding repository:
import org.springframework.data.neo4j.repository.GraphRepository;
import ***.domain.Person;
public interface PersonRepository extends GraphRepository<Person> {}
I'm not sure what's wrong. The exception message is just too weird and my debug sessions didn't lead me anywhere.
Can anybody tell me what's wrong with my code?
Related
I'm getting the following error when I tried to processing the data from hazelcast jet.
Caused by: java.lang.IllegalArgumentException: Invalid lambda deserialization
at com.example.LearnJet.joins.LeftJoins.$deserializeLambda$(LeftJoins.java:1)
... 59 more
Here is the code:-
AddToCart1 instance
public class AddToCart1 implements Serializable {
private int number;
private String cart;
public AddToCart1() {
super();
// TODO Auto-generated constructor stub
}
public int getNumber() {
return number;
}
public AddToCart1(int number, String cart) {
super();
this.number = number;
this.cart = cart;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((cart == null) ? 0 : cart.hashCode());
result = prime * result + number;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AddToCart1 other = (AddToCart1) obj;
if (cart == null) {
if (other.cart != null)
return false;
} else if (!cart.equals(other.cart))
return false;
if (number != other.number)
return false;
return true;
}
public void setNumber(int number) {
this.number = number;
}
public String getCart() {
return cart;
}
public void setCart(String cart) {
this.cart = cart;
}
}
PageVisit1 instance
public class PageVisit1 implements Serializable {
/**
*
*/
private int number;
private String pageName;
public PageVisit1() {
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + number;
result = prime * result + ((pageName == null) ? 0 : pageName.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PageVisit1 other = (PageVisit1) obj;
if (number != other.number)
return false;
if (pageName == null) {
if (other.pageName != null)
return false;
} else if (!pageName.equals(other.pageName))
return false;
return true;
}
public PageVisit1(int number, String pageName) {
super();
this.number = number;
this.pageName = pageName;
}
/**
* #return the number
*/
public int getNumber() {
return number;
}
/**
* #param number the number to set
*/
public void setNumber(int number) {
this.number = number;
}
/**
* #return the pageName
*/
public String getPageName() {
return pageName;
}
/**
* #param pageName the pageName to set
*/
public void setPageName(String pageName) {
this.pageName = pageName;
}
}
Here is the main class
public class LeftJoins {
public static void main(String[] args) throws InvocationTargetException {
JetInstance jet = Jet.bootstrappedInstance();
IList<AddToCart1> addToCartList = jet.getList("cart");
IList<PageVisit1> paymentList = jet.getList("page");
// AddToCartData
AddToCart1 ad1 = new AddToCart1();
ad1.setNumber(1);
ad1.setCart("lulu bazar");
AddToCart1 ad2 = new AddToCart1();
ad2.setNumber(2);
ad2.setCart("krishna bazar");
AddToCart1 ad3 = new AddToCart1();
ad3.setNumber(3);
ad3.setCart("ram bazar");
addToCartList.add(ad1);
addToCartList.add(ad2);
addToCartList.add(ad3);
// Page Data
PageVisit1 pg1 = new PageVisit1();
pg1.setNumber(1);
pg1.setPageName("k login");
PageVisit1 pg2 = new PageVisit1();
pg2.setNumber(2);
pg2.setPageName("plogin");
paymentList.add(pg1);
paymentList.add(pg2);
// creating a piple-line here
Pipeline p = Pipeline.create();
BatchStageWithKey<AddToCart1, Object> cart = p.readFrom(Sources.<AddToCart1>list("cart"))
.groupingKey(cart1 -> cart1.getNumber());
BatchStageWithKey<PageVisit1, Object> page = p.readFrom(Sources.<PageVisit1>list("page"))
.groupingKey(page1 -> page1.getNumber());
BatchStage<Tuple2<List<PageVisit1>, List<AddToCart1>>> joinedLists1 = page.aggregate2(toList(), cart, toList())
.map(Entry::getValue);
BatchStage<Tuple2<List<PageVisit1>, List<AddToCart1>>> m = joinedLists1.filter(pair -> !pair.f0().isEmpty());
m.writeTo(Sinks.logger());
jet.newJob(p).join();
// joinedLists.filter(pair -> !pair.isEmpty());
}
The code is obviously incomplete, because there's no page variable so that page.aggregate2(...) shouldn't compile.
For this reason, I'm unable to point you to the exact line where the issue occurs. However, the error message tells you're using a "standard" lambda from the JDK that isn't Serializable, whereas you should use the ones from Jet, which are.
Please check this package.
EDIT:
I've created a dedicated GitHub project with the above code.
Everything works as expected. The 2 tuples are displayed correctly in the log:
09:33:59.974 [ INFO] [c.h.j.i.c.WriteLoggerP] [05d8-7d0a-e3c0-0001/loggerSink#0] ([ch.frankel.so.PageVisit1#c544b8f8], [ch.frankel.so.AddToCart1#41c722ed])
09:33:59.974 [ INFO] [c.h.j.i.c.WriteLoggerP] [05d8-7d0a-e3c0-0001/loggerSink#0] ([ch.frankel.so.PageVisit1#58fbcb54], [ch.frankel.so.AddToCart1#c666a2c4])
Hello folks this may be dumb question but as a beginner am struggling with this how to group values based on id in list, Now let me clarify you briefly am having set of objects like this :
ID:1,UserID:330
ID:2,UserID:303
ID:3,UserID:090
ID:1,UserID:302
ID:2,UserID:306
How my list should look like is(Json Format):
[{"ID":1,"UserID":[330,302]},{"ID":2,"UserID":[303,306]},{"ID":3,"UserID":[090]}]
Now let me post what i have tried so far:
final List<Integer>list=new ArrayList<>();
final List<SpareReturnModel>lisobj=new ArrayList<>();
int duplicate=0;
for(int i=0;i<tView.getSelected().size();i++){
Object o= tView.getSelected().get(i).getValue();
SpareReturnModel asset=(SpareReturnModel) o;
int flag=asset.getFlag();
if(flag==2) {
int warehouseid = asset.getWareHouseID();
asset.setWareHouseID(warehouseid);
int partid = asset.getSerialNoID();
list.add(partid);
}
else {
Log.d("s","no value for header");
}
if(duplicate!=asset.getWareHouseID()){
asset.setParlist(list);
asset.setWareHouseID(asset.getWareHouseID());
lisobj.add(asset);
list.clear();
}
duplicate=asset.getWareHouseID();
}
Gson gson=new Gson();
//this will convert list to json
String value=gson.toJson(listobj);
SpareReturn Model Class:
public class SpareReturnModel {
private Integer SerialNoID;
private String SerialNumber;
private List<Integer>parlist;
public List<Integer> getParlist() {
return parlist;
}
public void setParlist(List<Integer> parlist) {
this.parlist = parlist;
}
public Integer getFlag() {
return flag;
}
public void setFlag(Integer flag) {
this.flag = flag;
}
private Integer flag;
public Integer getWareHouseID() {
return WareHouseID;
}
public void setWareHouseID(Integer wareHouseID) {
WareHouseID = wareHouseID;
}
private Integer WareHouseID;
public Integer getSerialNoID() {
return SerialNoID;
}
public void setSerialNoID(Integer serialNoID) {
SerialNoID = serialNoID;
}
public String getSerialNumber() {
return SerialNumber;
}
public void setSerialNumber(String serialNumber) {
SerialNumber = serialNumber;
}
}
Can someone let me know how to achieve this am struggling with this.
I simplify your class to make solution clearer:
public class SpareReturnModel implements Comparable<SpareReturnModel> {
private Integer id;
private String userId;
public SpareReturnModel(Integer id, String userId) {
this.id = id;
this.userId = userId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
#Override
public int compareTo(SpareReturnModel other) {
return this.getId().compareTo(other.getId());
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SpareReturnModel model = (SpareReturnModel) o;
if (id != null ? !id.equals(model.id) : model.id != null) return false;
return userId != null ? userId.equals(model.userId) : model.userId == null;
}
#Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (userId != null ? userId.hashCode() : 0);
return result;
}
}
and add JsonSpareReturnModel
public class JsonSpareRuturnModel implements Comparable<JsonSpareRuturnModel> {
private final List<SpareReturnModel> modelList;
private final Integer id;
public JsonSpareRuturnModel(List<SpareReturnModel> modelList) {
this.modelList = modelList;
this.id = modelList.get(0).getId();
}
private final String toJson() {
return String.format("{\"ID\":%s,\"UserID\":%s}", id, formatUserIdList());
}
private String formatUserIdList() {
StringBuilder builder = new StringBuilder("[");
Iterator<SpareReturnModel> modelIterator = modelList.iterator();
while (modelIterator.hasNext()) {
builder.append(modelIterator.next().getUserId());
if (modelIterator.hasNext()) {
builder.append(",");
}
}
builder.append("]");
return builder.toString();
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
JsonSpareRuturnModel that = (JsonSpareRuturnModel) o;
return id != null ? id.equals(that.id) : that.id == null;
}
#Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
#Override
public int compareTo(JsonSpareRuturnModel other) {
return this.id.compareTo(other.id);
}
#Override
public String toString() {
return toJson();
}
if you need to group by user id you need to sort your models according to id's
and place them to json format model:
public class Main {
public static void main(String[] args) {
List<SpareReturnModel> models = new ArrayList<>(Arrays.asList(
new SpareReturnModel(1, "330"),
new SpareReturnModel(2, "303"),
new SpareReturnModel(3, "090"),
new SpareReturnModel(1, "302"),
new SpareReturnModel(2, "306")
));
Map<Integer, List<SpareReturnModel>> groupById = new HashMap<>();
for (SpareReturnModel model : models) {
List<SpareReturnModel> listById = groupById.get(model.getId());
if (listById == null) {
groupById.put(model.getId(), new ArrayList<>(Arrays.asList(model)));
} else {
listById.add(model);
}
}
List<JsonSpareRuturnModel> jsonList = new ArrayList<>();
for (Map.Entry<Integer, List<SpareReturnModel>> pair : groupById.entrySet()) {
jsonList.add(new JsonSpareRuturnModel(pair.getValue()));
}
System.out.println(jsonList);
final String expected = "[{\"ID\":1,\"UserID\":[330,302]}, {\"ID\":2,\"UserID\":[303,306]}, {\"ID\":3,\"UserID\":[090]}]";
System.out.println(jsonList.toString().equals(expected));
}
}
I have a REST endpoint as shown below.
#Path("/consumers")
#Produces("application/x.com.abc.pqr.audit.v2+json")
#Consumes("application/x.com.abc.pqr.audit.v2+json")
public interface ConsumerEndpoint {
#GET
#Path("paged")
Page<Module> getConsumersOfDependencyByPage(#BeanParam ConsumerQueryParams params);
}
As you can see above, I am using #BeanParam to map the query parameters passed from the front end side.
The ConsumerQueryParams class is shown below.
public class ConsumerQueryParams implements Serializable{
private static final long serialVersionUID = 6440255704974023223L;
#QueryParam("pageNum") #DefaultValue("1") private int pageNum;
#QueryParam("pageSize") #DefaultValue("25") private int pageSize;
#QueryParam("groupId") private String groupId;
#QueryParam("artifactId") private String artifactId;
#QueryParam("version") private String version;
#QueryParam("groupIdFilter") private String groupIdFilter;
#QueryParam("artifactIdFilter") private String artifactIdFilter;
#QueryParam("versionFilter") private String versionFilter;
public ConsumerQueryParams() {
}
private ConsumerQueryParams(Builder builder) {
this.pageNum = builder.pageNum;
this.pageSize = builder.pageSize;
this.groupId = builder.groupId;
this.artifactId = builder.artifactId;
this.version = builder.version;
this.groupIdFilter = builder.groupIdFilter;
this.artifactIdFilter = builder.artifactIdFilter;
this.versionFilter = builder.versionFilter;
}
public int getPageNum() {
return pageNum;
}
public int getPageSize() {
return pageSize;
}
public String getGroupId() {
return groupId;
}
public String getArtifactId() {
return artifactId;
}
public String getVersion() {
return version;
}
public String getGroupIdFilter() {
return groupIdFilter;
}
public String getArtifactIdFilter() {
return artifactIdFilter;
}
public String getVersionFilter() {
return versionFilter;
}
#Override
public boolean equals(Object obj) {
if(this == obj)
return true;
if(!(obj instanceof ConsumerQueryParams))
return false;
ConsumerQueryParams other = (ConsumerQueryParams) obj;
return Objects.equals(pageNum, other.pageNum) &&
Objects.equals(pageSize, other.pageSize) &&
Objects.equals(groupId, other.groupId) &&
Objects.equals(artifactId, other.artifactId) &&
Objects.equals(version, other.version) &&
Objects.equals(groupIdFilter, other.groupIdFilter) &&
Objects.equals(artifactIdFilter, other.artifactIdFilter) &&
Objects.equals(versionFilter, other.versionFilter);
}
#Override
public int hashCode() {
return Objects.hash(pageNum, pageSize, groupId, artifactId, version, groupIdFilter, artifactIdFilter, versionFilter);
}
public static class Builder {
private int pageNum;
private int pageSize;
private String groupId;
private String artifactId;
private String version;
private String groupIdFilter;
private String artifactIdFilter;
private String versionFilter;
public Builder(int pageNum, int pageSize, String groupId, String artifactId) {
Preconditions.checkArgument(pageNum > 0, "pageNum must be greater than 0.");
Preconditions.checkArgument(pageSize > 0, "pageSize must be greater than 0.");
Preconditions.checkNotNull(groupId, "groupId is null");
Preconditions.checkNotNull(artifactId, "artifactId is null");
this.pageNum = pageNum;
this.pageSize = pageSize;
this.groupId = groupId;
this.artifactId = artifactId;
}
public Builder setVersion(String version) {
this.version = version;
return this;
}
public Builder setGroupIdFilter(String groupIdFilter) {
this.groupIdFilter = groupIdFilter;
return this;
}
public Builder setArtifactIdFilter(String artifactIdFilter) {
this.artifactIdFilter = artifactIdFilter;
return this;
}
public Builder setVersionFilter(String versionFilter) {
this.versionFilter = versionFilter;
return this;
}
public ConsumerQueryParams build() {
return new ConsumerQueryParams(this);
}
}
}
You can see that I am using the Builder pattern to set the variables.
I am using the below url to access the above specified endpoint.
http://localhost:8080/rest/api/consumers/paged?groupId=org.slf4j&artifactId=slf4j-api&groupIdFilter=sdlc
Everything works fine. I am able to get the data on Postman successfully.
Now I have a requirement where I need to rename the groupIdFilter, artifactIdFilter, versionFilter query params in ConsumerQueryParams class to consumerGroupIdFilter, consumerArtifactIdFilter and consumerVersionFilter respectively.
After changing the variable names in ConsumerQueryParams class, it looks like this:
public class ConsumerQueryParams implements Serializable{
private static final long serialVersionUID = 6440255704974023223L;
#QueryParam("pageNum") #DefaultValue("1") private int pageNum;
#QueryParam("pageSize") #DefaultValue("25") private int pageSize;
#QueryParam("groupId") private String groupId;
#QueryParam("artifactId") private String artifactId;
#QueryParam("version") private String version;
#QueryParam("groupIdFilter") private String consumerGroupIdFilter;
#QueryParam("artifactIdFilter") private String consumerArtifactIdFilter;
#QueryParam("versionFilter") private String consumerVersionFilter;
public ConsumerQueryParams() {
}
private ConsumerQueryParams(Builder builder) {
this.pageNum = builder.pageNum;
this.pageSize = builder.pageSize;
this.groupId = builder.groupId;
this.artifactId = builder.artifactId;
this.version = builder.version;
this.consumerGroupIdFilter = builder.consumerGroupIdFilter;
this.consumerArtifactIdFilter = builder.consumerArtifactIdFilter;
this.consumerVersionFilter = builder.consumerVersionFilter;
}
public int getPageNum() {
return pageNum;
}
public int getPageSize() {
return pageSize;
}
public String getGroupId() {
return groupId;
}
public String getArtifactId() {
return artifactId;
}
public String getVersion() {
return version;
}
public String getConsumerGroupIdFilter() {
return consumerGroupIdFilter;
}
public String getConsumerArtifactIdFilter() {
return consumerArtifactIdFilter;
}
public String getConsumerVersionFilter() {
return consumerVersionFilter;
}
#Override
public boolean equals(Object obj) {
if(this == obj)
return true;
if(!(obj instanceof ConsumerQueryParams))
return false;
ConsumerQueryParams other = (ConsumerQueryParams) obj;
return Objects.equals(pageNum, other.pageNum) &&
Objects.equals(pageSize, other.pageSize) &&
Objects.equals(groupId, other.groupId) &&
Objects.equals(artifactId, other.artifactId) &&
Objects.equals(version, other.version) &&
Objects.equals(consumerGroupIdFilter, other.consumerGroupIdFilter) &&
Objects.equals(consumerArtifactIdFilter, other.consumerArtifactIdFilter) &&
Objects.equals(consumerVersionFilter, other.consumerVersionFilter);
}
#Override
public int hashCode() {
return Objects.hash(pageNum, pageSize, groupId, artifactId, version, consumerGroupIdFilter, consumerArtifactIdFilter, consumerVersionFilter);
}
public static class Builder {
private int pageNum;
private int pageSize;
private String groupId;
private String artifactId;
private String version;
private String consumerGroupIdFilter;
private String consumerArtifactIdFilter;
private String consumerVersionFilter;
public Builder(int pageNum, int pageSize, String groupId, String artifactId) {
Preconditions.checkArgument(pageNum > 0, "pageNum must be greater than 0.");
Preconditions.checkArgument(pageSize > 0, "pageSize must be greater than 0.");
Preconditions.checkNotNull(groupId, "groupId is null");
Preconditions.checkNotNull(artifactId, "artifactId is null");
this.pageNum = pageNum;
this.pageSize = pageSize;
this.groupId = groupId;
this.artifactId = artifactId;
}
public Builder setVersion(String version) {
this.version = version;
return this;
}
public Builder setConsumerGroupIdFilter(String consumerGroupIdFilter) {
this.consumerGroupIdFilter = consumerGroupIdFilter;
return this;
}
public Builder setConsumerArtifactIdFilter(String consumerArtifactIdFilter) {
this.consumerArtifactIdFilter = consumerArtifactIdFilter;
return this;
}
public Builder setConsumerVersionFilter(String consumerVersionFilter) {
this.consumerVersionFilter = consumerVersionFilter;
return this;
}
public ConsumerQueryParams build() {
return new ConsumerQueryParams(this);
}
}
}
Now I am trying to access the same endpoint with the url:
http://localhost:8080/rest/api/consumers/paged?groupId=org.slf4j&artifactId=slf4j-api&consumerGroupIdFilter=sdlc
But this is not working. The consumerGroupIdFilter query param in the url is not being mapped to the consumerGroupIdFilter variable of the ConsumerQueryParams object, whereas groupId and artifactId gets mapped.
I am not sure why this is happening. As far as I know, the ConsumerQueryParams class has the correct code. All that I did was to change the variable names and updated the getters and setters in the Builder class.
Can anyone help me here.
The problem is that the url has the new name and the annotation has the old one
#QueryParam("groupIdFilter")
consumerGroupIdFilter
I want to get my profile in class Tournee (profil_tournee) list based on my tours ("tournee"). However, I have an exception. Can anyone help me?
Exception in thread "AWT-EventQueue-0"
java.lang.IllegalArgumentException: Type specified for TypedQuery
[fr.galettedebroons.domain.Profil] is incompatible with query return
type [interface java.util.Collection]
Request:
List<List<Profil>> listProfil = Arrays.asList(manager_.createQuery("select t.profil_tournee "
+ "FROM Tournee t WHERE t.nom LIKE :tournee", Profil.class)
.setParameter("tournee", tournee)
.getResultList());
Model :
#Entity
public class Tournee {
private int id;
private String nom;
private boolean lundi = false;
private boolean mardi = false;
private boolean mercredi = false;
private boolean jeudi = false;
private boolean vendredi = false;
private boolean samedi = false;
private boolean dimanche = false;
private List<Profil> profil_tournee;
public Tournee(){}
public Tournee(String nom, boolean lundi, boolean mardi, boolean mercredi, boolean jeudi,
boolean vendredi, boolean samedi, boolean dimanche, List<Profil> profil_tournee) {
this.nom = nom;
this.lundi = lundi;
this.mardi = mardi;
this.mercredi = mercredi;
this.jeudi = jeudi;
this.vendredi = vendredi;
this.samedi = samedi;
this.dimanche = dimanche;
this.profil_tournee = profil_tournee;
}
public Tournee(String nom, boolean lundi, boolean mardi, boolean mercredi, boolean jeudi,
boolean vendredi, boolean samedi, boolean dimanche) {
this.nom = nom;
this.lundi = lundi;
this.mardi = mardi;
this.mercredi = mercredi;
this.jeudi = jeudi;
this.vendredi = vendredi;
this.samedi = samedi;
this.dimanche = dimanche;
}
#Id #GeneratedValue(strategy = GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(int id_tournee) {
this.id = id_tournee;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public boolean isLundi() {
return lundi;
}
public void setLundi(boolean lundi) {
this.lundi = lundi;
}
public boolean isMardi() {
return mardi;
}
public void setMardi(boolean mardi) {
this.mardi = mardi;
}
public boolean isMercredi() {
return mercredi;
}
public void setMercredi(boolean mercredi) {
this.mercredi = mercredi;
}
public boolean isJeudi() {
return jeudi;
}
public void setJeudi(boolean jeudi) {
this.jeudi = jeudi;
}
public boolean isVendredi() {
return vendredi;
}
public void setVendredi(boolean vendredi) {
this.vendredi = vendredi;
}
public boolean isSamedi() {
return samedi;
}
public void setSamedi(boolean samedi) {
this.samedi = samedi;
}
public boolean isDimanche() {
return dimanche;
}
public void setDimanche(boolean dimanche) {
this.dimanche = dimanche;
}
#OneToMany(mappedBy="profil_tournee", cascade=CascadeType.PERSIST)
public List<Profil> getProfil_tournee() {
return profil_tournee;
}
public void setProfil_tournee(List<Profil> profil_tournee) {
this.profil_tournee = profil_tournee;
}
}
#Entity
public class Profil {
private String code_client;
private Client client_profil;
private Gamme gamme_profil;
private List<Livraison> livraison_profil;
private Boolean actif;
private Tournee profil_tournee;
private List<MargeLivraison> marge_profil;
private List<Prevision> prevision_profil;
public Profil(){}
public Profil(Gamme code_gamme, List<Livraison> livraison, Boolean actif) {
this.gamme_profil = code_gamme;
this.livraison_profil = livraison;
this.actif = actif;
}
#Id
public String getCode_client() {
return code_client;
}
public void setCode_client(String code_client) {
this.code_client = code_client;
}
public Boolean getActif() {
return actif;
}
public void setActif(Boolean actif) {
this.actif = actif;
}
#ManyToOne
public Gamme getGamme_profil() {
return gamme_profil;
}
public void setGamme_profil(Gamme gamme_profil) {
this.gamme_profil = gamme_profil;
}
#OneToMany(mappedBy="livraison_profil", cascade=CascadeType.PERSIST)
public List<Livraison> getLivraison_profil() {
return livraison_profil;
}
public void setLivraison_profil(List<Livraison> livraison_profil) {
this.livraison_profil = livraison_profil;
}
#ManyToOne
public Client getClient_profil() {
return client_profil;
}
public void setClient_profil(Client client) {
this.client_profil = client;
}
#ManyToOne
public Tournee getProfil_tournee() {
return profil_tournee;
}
public void setProfil_tournee(Tournee profil_tournee) {
this.profil_tournee = profil_tournee;
}
#OneToMany(mappedBy="marge_profil", cascade=CascadeType.PERSIST)
public List<MargeLivraison> getMarge_profil() {
return marge_profil;
}
public void setMarge_profil(List<MargeLivraison> marge_profil) {
this.marge_profil = marge_profil;
}
#OneToMany(mappedBy="prevision_profil", cascade=CascadeType.PERSIST)
public List<Prevision> getPrevision_profil() {
return prevision_profil;
}
public void setPrevision_profil(List<Prevision> prevision_profil) {
this.prevision_profil = prevision_profil;
}
Your expected result list will contain elements that are list of profiles, not profiles.
I would replace Profil.class by List.class for the Query creation :
List<List<Profil>> listProfil = Arrays.asList(manager_.createQuery("select t.profil_tournee "
+ "FROM Tournee t WHERE t.nom LIKE :tournee", List.class)
.setParameter("tournee", tournee)
.getResultList());
Your error gives you a hint that the returning type should be consistent with declared type when invoking EntityManager.createQuery(query, Type) method:
List<SomeType> em.createQuery("SELECT s FROM SomeType", SomeType.class);
However your real problem is that your query is illegal. In JPA collection-valued expressions cannot be part of SELECT clause. Please see another answer of mine https://stackoverflow.com/a/25890863/3796586.
The solution in your case would be to reverse the query like this:
List<Profil> result = em.createQuery("SELECT p FROM Profil p WHERE" +
"p.profil_tournee.norm LIKE :tournee", Profil.class)
.setParameter("tournee", tournee)
.getResultList());
I have created simple web application with JAAS auth, all works fine, but I need get user's roles list in the servlet, I get subject but it is not return any roles list and related principals. It return only first added principal? Why so?How get roles?
here my sources:
AccLoginModule.java
public class AccLoginModule implements LoginModule {
public Subject subject;
private CallbackHandler callbackHandler;
private Map<String, ?> sharedState;
private Map<String, ?> options;
private AccPrincipal principal;
private boolean committed = false;
#Override
public boolean abort() throws LoginException {
System.out.println("abort");
if (!committed)
return false;
if (principal != null) {
logout();
principal = null;
}
return true;
}
#Override
public boolean commit() throws LoginException {
try {
if (subject.getPrincipals().size() == 0) {
subject.getPrincipals().add(new AccPrincipal("principal 1"));
subject.getPrincipals().add(new AccPrincipal("principal 2"));
subject.getPrincipals().add(new AccRole("Acc User"));
subject.getPrincipals().add(new AccRole("Acc User1"));
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
#Override
public boolean login() throws LoginException {
// System.out.println("login");
if (callbackHandler == null)
throw new LoginException("No CallbackHandler specified");
Callback callbacks[] = new Callback[2];
callbacks[0] = new NameCallback("Username: ");
callbacks[1] = new PasswordCallback("Password: ", false);
// Interact with the user to retrieve the username and password
String username = null;
String password = null;
try {
callbackHandler.handle(callbacks);
username = ((NameCallback) callbacks[0]).getName();
password = new String(((PasswordCallback) callbacks[1]).getPassword());
return true;
} catch (Exception e) {
throw new LoginException(e.toString());
}
}
#Override
public boolean logout() throws LoginException {
System.out.println("logout");
committed = false;
subject.getPrincipals().remove(principal);
return false;
}
#Override
public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options) {
this.subject = subject;
this.callbackHandler = callbackHandler;
this.sharedState = sharedState;
this.options = options;
}
public Subject getSubject() {
return subject;
}
public void setSubject(Subject subject) {
this.subject = subject;
}
}
AccPrincipal
public class AccPrincipal implements Principal, Serializable {
/**
*
*/
private static final long serialVersionUID = 5002820876845306935L;
private final String loginResponse;
public AccPrincipal(String lr) {
this.loginResponse=lr;
}
#Override
public String getName() {
return loginResponse;
}
public String getLoginResponse() {
return loginResponse;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((loginResponse == null) ? 0 : loginResponse.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AccPrincipal other = (AccPrincipal) obj;
if (loginResponse == null) {
if (other.loginResponse != null)
return false;
} else if (!loginResponse.equals(other.loginResponse))
return false;
return true;
}
}
AccRole
public class AccRole implements Principal, Serializable {
/**
*
*/
private static final long serialVersionUID = 2764250372647034496L;
private String name;
public AccRole(String name){
this.name = name;
}
#Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AccRole other = (AccRole) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
context.xml
<Context>
<Realm className="org.apache.catalina.realm.JAASRealm" appName="acczk"
userClassNames="com.laws.acc.jaas.AccPrincipal"
roleClassNames="com.laws.acc.jaas.AccRole">
</Realm>
</Context>
MyServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
final Subject subject = Subject.getSubject(AccessController.getContext());
for (Principal princ : subject.getPrincipals()) {
System.out.println(princ.getName());
}
}
Console:
09.04.2012 17:11:29 org.apache.catalina.startup.Catalina start
INFO: Server startup in 1385 ms
principal 1
How I can get all entity principals (principals+roles)? What I am doing wrong?
Tomcat and Java EE in general doesn't work like that. You can't access the Subject in the way you are doing it.
See this answer for a full explanation: Tomcat-Jaas - How to retrieve subject?