Spring Boot Cassandra Error connecting to Node(endPoint=localhost:1234, hostId=null, hashCode=37hfeouh3), - spring-data

In my Spring Boot Cassandra build I am getting the following error: s0-admin-1] c.d.o.d.i.c.control.ControlConnection : [s0] Error connecting to Node(endPoint=localhost:1234, hostId=null, hashCode=37hfeouh3), trying next node (ConnectionInitException: [s0|control|connecting...] Protocol initialization request, step 1 (OPTIONS): failed to send request (io.netty.channel.StacklessClosedChannelException))
Entity type of
#Data
#Builder
#Table
public class Class1 {
#Id
private String id;
private String data;
private Class2 data2;
private Integer data3;
...
}
public class2 Class2 {
#Id
#JasonProperty
private String id;
#Indexed
#JasonProperty
private String data;
#JasonProperty
private String data2;
#JasonProperty
private Integer data3;
...
}
#Configuration
#EnableCassandraRepositories
#ConfigurationProperties(prefix = "DBProperties")
public class ApplicationConfig extends AbstractCassandraConfiguration {
private String DBKEYSPACE;
#Override
protected String getKeyspaceName() {
return DBKEYSPACE;
}
public String[] getEntityBasePackages() {
return new String[] { "com.oreilly.springdata.cassandra" };
}
}
#ConfigurationProperties(prefix = "DBPROPERTIES")
#Slf4j
public class FactoryBeanAppConfig {
private String contactPoints;
private String keySpace;
private Integer port;
private String password;
private String username;
private String dataCenter;
/*
* Factory bean that creates the com.datastax.oss.driver.api.core.CqlSession instance
*/
#Bean
public CqlSessionFactoryBean session() {
//log it we made it.
log.info("I made it to CqlSessionFactoryBean");
CqlSessionFactoryBean session = new CqlSessionFactoryBean();
session.setContactPoints(URLINFO);
log.info("Contact Points: " +URLINFO);
session.setKeyspaceName(DBKEYSPACE);
//session.setPort(OURPORT);
session.setUsername(username);
session.setPassword(password);
session.setLocalDatacenter(LOCALDCENTER INFORMATION);
return session;
}
}
I am unable to find a good example or even a get it to work correctly. Looking at this documentation: https://docs.spring.io/spring-data/cassandra/docs/current/reference/html/#cassandra.core thats the only thing I should have to do to implement example 55

For the spring boot run your application, it need to load the DB when your server application (the tomcat for example) is starting. So, your schema should be created first. If it is ok, you could change the "localhost" to "127.0.0.1" in your cassandra.yaml file.
Important: "[s0] Error connecting to Node(endPoint=localhost:1234,..." please check the cassandra's port. The correct is 9042.
It will solve your problem. However, others errors can be happen, because the others classes.
Then, you could correct the classes below:
#SpringBootApplication
#EnableCassandraRepositories(basePackages = { "<package's path>" })
#EntityScan(basePackages = { "<package's path>" })
#ComponentScan(basePackages = { "<package's path>" })
public class ApplicationConfig extends SpringBootServletInitializer
{
SpringApplication.run(ApplicationConfig.class, args);
}
Entity:
#Table("<table name>")
public class Class1 {
#PrimaryKeyColumn(name = "<field name id>", type = PrimaryKeyType.PARTITIONED)
private String id;
#Column("<field name data>")
private String data;
private Class2 data2; //I think this declaretion can cause error
#Column("<field name data3>")
private Integer data3;
...
}
This FactoryBeanAppConfig's class is not sound good. I created a class to read the application.properties and inject this class to connect with the db datas like keyspace's name, port, and so one. This link will help you to creat this class: https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.external-config . And then, you use this class in your FactoryBeanAppConfig's class to get DBKEYSPACE, OURPORT, ... .
This is a example to helps you to understand what I'm saying: https://www.baeldung.com/spring-data-cassandra-tutorial .

Related

InvalidDefinitionException: Cannot construct instance of `com.vehicle.datatransferobject.VehicleDTO`

In the REST endpoint I'm building in Spring Boot, I'm trying to pass my vehicleDTO to my controller. But before it reaches my controller, there is an error.
InvalidDefinitionException: Cannot construct instance of
com.vehicle.datatransferobject.VehicleDTO (no Creators, like default
construct, exist): cannot deserialize from Object value (no delegate-
or property-based Creator)
vehicleDTO
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.myvehicle.EngineType;
#JsonInclude(JsonInclude.Include.NON_NULL)
public class VehicleDTO {
#JsonIgnore
private Long id;
#NotNull(message = "vehiclenumber can not be null!")
private String vehiclenumber;
#Min(2)
#NotNull(message = "Seat count can not be less than 2!")
private Integer vehicleseatcount;
#NotNull(message = "Engine Type can not be null!")
private EngineType enginetype;
#Max(5)
private Integer vehiclerating;
private VehicleDTO(Long id, String vehiclenumber, Integer vehicleseatcount, EngineType enginetype,Integer vehiclerating){
this.vehiclenumber=vehiclenumber;
this.vehicleseatcount=vehicleseatcount;
this.enginetype=enginetype;
this.vehiclerating=vehiclerating;
this.id=id;
}
public static VehicleDTOBuilder newBuilder()
{
return new VehicleDTOBuilder();
}
#JsonProperty
public Long getId() {
return id;
}
public String getvehiclenumber() {
return vehiclenumber;
}
public Integer getvehicleseatcount() {
return vehicleseatcount;
}
public EngineType getEnginetype() {
return enginetype;
}
public Integer getvehiclerating() {
return vehiclerating;
}
public static class VehicleDTOBuilder{
private Long id;
private String vehiclenumber;
private Integer vehicleseatcount;
private EngineType enginetype;
private Integer vehiclerating;
public VehicleDTOBuilder setId(Long id) {
this.id = id;
return this;
}
public VehicleDTOBuilder setvehiclenumber(String vehiclenumber) {
this.vehiclenumber = vehiclenumber;
return this;
}
public VehicleDTOBuilder setvehicleseatcount(Integer vehicleseatcount) {
this.vehicleseatcount = vehicleseatcount;
return this;
}
public VehicleDTOBuilder setEnginetype(EngineType enginetype) {
this.enginetype = enginetype;
return this;
}
public VehicleDTOBuilder setvehiclerating(Integer vehiclerating) {
this.vehiclerating = vehiclerating;
return this;
}
public VehicleDTO createVehicleDTO()
{
return new VehicleDTO(id, vehiclenumber, vehicleseatcount, enginetype,vehiclerating);
}
}
}
My DTO has an Enum type called EngineType
public enum EngineType {
ELECTRIC, DIESEL
}
My controller looks like this
#PostMapping
#ResponseStatus(HttpStatus.CREATED)
public VehicleDTO addvehicle(#Valid #RequestBody VehicleDTO vehicleDTO)
{
VehicleDO vehicleDO = Mapper.VehicleDO(vehicleDTO);
return Mapper.makeVehicleDTO(Service.addvehicle(vehicleDO));
}
This exception :
InvalidDefinitionException: Cannot construct instance of
com.vehicle.datatransferobject.VehicleDTO (no Creators, like default
construct, exist): cannot deserialize from Object value (no delegate-
or property-based Creator)
means that Jackson didn't find a way to instantiate VehicleDTO that is the default constructor (no arg constructor) or a JsonCreator.
As you use a builder pattern you will configure the VehicleDTO class to make Jackson to instantiate VehicleDTO with the VehicleDTOBuilder such as :
#JsonDeserialize(builder = VehicleDTO.VehicleDTOBuilder.class)
public class VehicleDTO {
...
}
And annotate your builder with JsonPOJOBuilder as :
#JsonPOJOBuilder(buildMethodName = "createVehicleDTO", withPrefix = "set")
public static class VehicleDTOBuilder{
...
}
According to the javadoc, JsonPOJOBuilder is :
used to configure details of a Builder class: instances of which are
used as Builders for deserialized POJO values, instead of POJOs being
instantiated using constructors or factory methods. Note that this
annotation is NOT used to define what is the Builder class for a POJO:
rather, this is determined by JsonDeserialize.builder() property of
JsonDeserialize.
I faced this error when I used Lombok's #Builder and #Data annotations together on a POJO class that is used for connecting to an API (either for consuming or for providing response)
I removed the #Builder annotation and then it is working fine
In my case:
InvalidDefinitionException: Cannot construct instance of com.vehicle.datatransferobject.VehicleDTO (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
for the above exception, I just write Default Constructor which instantiates class and solved the problem.
Default Constructor:
public VehicleDTO() {
super();
// TODO Auto-generated constructor stub
}
If you are using Lombok - the best thing is to add these annotations to your DTO:
#AllArgsConstructor
#RequiredArgsConstructor
#Data
#Builder (optional)
In addition to davidxxx`s answer. I used Lombok. And in my case it looked like this:
#Data
#JsonDeserialize(builder = SomeClass.SomeClassBuilder.class)
#Builder(builderClassName = "SomeClassBuilder")
public class SomeClass {
// ...
#JsonPOJOBuilder(withPrefix = "")
public static class SomeClassBuilder {
}
}

Rest API with Spring Data MongoDB - Repository method not working

I am reading and learning Spring Boot data with MongoDB. I have about 10 records in my database in the following format:
{
"_id" : ObjectId("5910c7fed6df5322243c36cd"),
name: "car"
}
When I open the url:
http://localhost:8090/items
I get an exhaustive list of all items. However, I want to use the methods of MongoRepository such as findById, count etc. When I use them as such:
http://localhost:8090/items/count
http://localhost:8090/items/findById/5910c7fed6df5322243c36cd
http://localhost:8090/items/findById?id=5910c7fed6df5322243c36cd
I get a 404.
My setup is as so:
#SpringBootApplication
public class Application {
public static void main(String[] args) throws IOException {
SpringApplication.run(Application.class, args);
}
}
#Document
public class Item implements Serializable {
private static final long serialVersionUID = -4343106526681673638L;
#Id
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
#RepositoryRestResource(collectionResourceRel = "item", path = "items")
public interface ItemRepository<T, ID extends Serializable> extends MongoRepository<Item, String>, ItemRepositoryCustom {
}
What am I doing wrong? Do I need to implement the methods as defined by MongoRepository or will they be automatically implemented? I am lost and have been trying to figure this out for so long. I do not have any methods in my controller, its empty.
You have to declare the findById method in order for it to be exposed.
Item findById(String id);
Item findByName(String name);
Note that you don't need to implement the methods. SpringBoot will analyse the method name and provide the proper implementation
I had same issue,
After removing #Configuration,#ComponentScan everything worked fine.

Spring Boot store data with WebSockets

I have a simple WebSocket set up and try to save data. Somehow the data gets not persisted. I don't get any error messages and the object gets returned correct to the client. If I try to store the object with a REST controller and a REST request it works.
Here are the dependencies of my build.gradle file:
dependencies {
compile 'org.springframework.boot:spring-boot-starter-web'
compile 'org.springframework.boot:spring-boot-starter-data-jpa'
compile 'org.springframework.boot:spring-boot-starter-websocket'
compile 'org.springframework:spring-messaging'
compile 'com.google.code.gson:gson:1.7.2'
compile 'org.postgresql:postgresql:9.4-1200-jdbc41'
compile 'commons-dbcp:commons-dbcp:1.4'
testCompile('org.springframework.boot:spring-boot-startet-test')
}
PersonController
#Controller
public class PersonController {
#Autowired
PersonRepository personRepository;
#MessageMapping("/test")
#SendTo("/response/test")
public Person test() throws Exception {
Person person = new Person();
person.setName("John Doe");
return personRepository.save(person);
}
}
Configuration for STOMP messaging
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
#Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/response");
config.setApplicationDestinationPrefixes("/app");
}
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/websocket")
.setAllowedOrigins("*")
.withSockJS();
}
Person entity
#Entity
public class Person {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return getName;
}
public void setName(String name) {
this.name = name;
}
}
Base Repository
#NoRepositoryBean
public interface BaseRepository<T, ID extends Serializable> extends Repository<T, ID> {
void delete(T deleted);
void delete(ID id);
Iterable<T> findAll();
T findOne(ID id);
T save(T persisted);
Iterable<T> save(Iterable<T> persited);
}
Person Repository
public interface PersonRepository extends
BaseRepository<Person, Serializable> {
}
Is there a problem in my code?
Is there an issue with caching? Do I have to force flushing?
Is storing data with WebSockets supported by SpringBoot?
Do you know any examples with storing data? I could only find basic examples without storing data.
The problem was in my persistence configuration. I changed the configuration from a Java implementation to the application.properties file. I think there was a problem with my transaction manager.
To be complete, here is my current application.properties file:
spring.datasource.url = jdbc:postgresql://localhost:5432/test
spring.datasource.username = test
spring.datasource.password = test
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = create
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect

Spring Data MongoDB No property get found for type at org.springframework.data.mapping.PropertyPath

I am using Spring Data MongodB 1.4.2.Release version. For Spring Data MongoDB, I have created the custom repository interface and implementation in one location and create custom query function getUsersName(Users users).
However I am still getting below exception:
Caused by: org.springframework.data.mapping.PropertyReferenceException:
No property get found for type Users! at org.springframework.data.mapping.PropertyPath. (PropertyPath.java:75) at
org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:327) at
org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:359) at
org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:359) at
org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:307) at
org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:270) at
org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:241) at
org.springframework.data.repository.query.parser.Part.(Part.java:76) at
org.springframework.data.repository.query.parser.PartTree$OrPart.(PartTree.java:201) at
org.springframework.data.repository.query.parser.PartTree$Predicate.buildTree(PartTree.java:291) at
org.springframework.data.repository.query.parser.PartTree$Predicate.(PartTree.java:271) at
org.springframework.data.repository.query.parser.PartTree.(PartTree.java:80) at
org.springframework.data.mongodb.repository.query.PartTreeMongoQuery.(PartTreeMongoQuery.java:47)
Below is my Spring Data MongoDB structure:
/* Users Domain Object */
#Document(collection = "users")
public class Users {
#Id
private ObjectId id;
#Field ("last_name")
private String last_name;
#Field ("first_name")
private String first_name;
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
}
/* UsersRepository.java main interface */
#Repository
public interface UsersRepository extends MongoRepository<Users,String>, UsersRepositoryCustom {
List findUsersById(String id);
}
/* UsersRepositoryCustom.java custom interface */
#Repository
public interface UsersRepositoryCustom {
List<Users> getUsersName(Users users);
}
/* UsersRepositoryImpl.java custom interface implementation */
#Component
public class UsersRepositoryImpl implements UsersRepositoryCustom {
#Autowired
MongoOperations mongoOperations;
#Override
public List<Users> getUsersName(Users users) {
return mongoOperations.find(
Query.query(Criteria.where("first_name").is(users.getFirst_name()).and("last_name").is(users.getLast_name())), Users.class);
}
/* Mongo Test function inside Spring JUnit Test class calling custom function with main UsersRepository interface */
#Autowired
private UsersRepository usersRepository;
#Test
public void getUsersName() {
Users users = new Users();
users.setFirst_name("James");`enter code here`
users.setLast_name("Oliver");
List<Users> usersDetails = usersRepository.getUsersName(users);
System.out.println("users List" + usersDetails.size());
Assert.assertTrue(usersDetails.size() > 0);
}
The query method declaration in your repository interface is invalid. As clearly stated in the reference documentation, query methods need to start with get…By, read_By, find…By or query…by.
With custom repositories, there shouldn't be a need for method naming conventions as Oliver stated. I have mine working with a method named updateMessageCount
Having said that, I can't see the problem with the code provided here.
I resolved this issue with the help of this post here, where I wasn't naming my Impl class correctly :
No property found for type error when try to create custom repository with Spring Data JPA

No mapping available for role reference with sessionContext.isCallerInRole()

I have a method that can be called if the person has a specific role and they are associated with a particular group in JIRA. Since the groups in JIRA are dynamic, I can't have a role per JIRA group.
#DeclareRoles({
FileServerRoles.FILE_ADDER,
FileServerRoles.FILE_ADDER_ALL,
FileServerRoles.FILE_VIEWER,
FileServerRoles.FILE_VIEWER_ALL})
public final class FileServerRoles {
/**
* A user that can add files to the system.
*/
public static final String FILE_ADDER = "file-adder";
/**
* A user that can add any files to the system.
*/
public static final String FILE_ADDER_ALL = "file-adder-all";
/**
* A user that can view files in the system.
*/
public static final String FILE_VIEWER = "file-viewer";
/**
* A user that can view all files in the system.
*/
public static final String FILE_VIEWER_ALL = "file-viewer-all";
}
I am declaring all of the roles using #DeclareRoles.
#Decorator
public class FileServerServiceProjectAuthorizationDecorator implements FileServerService {
private static Logger LOGGER = LoggerFactory.getLogger(FileServerServiceProjectAuthorizationDecorator.class);
#Inject
#Delegate
#Any
FileServerService delagate;
#Inject
#CurrentUser
Set<JiraProjectReference> currentUserProjectReferences;
#Resource
SessionContext sessionContext;
void verifyProjectKey(final String projectKey) {
for (final JiraProjectReference projectReference : currentUserProjectReferences) {
if (projectReference.getKey().equalsIgnoreCase(projectKey)) {
return;
}
}
throw new IllegalArgumentException("user not in the project");
}
#RolesAllowed({FileServerRoles.FILE_ADDER, FileServerRoles.FILE_ADDER_ALL})
#Override
public FileAddStatus addFileToRepository(final String projectKey, final String issueKey, final String fileName, final String mimeType, final File file) {
if (!sessionContext.isCallerInRole(FileServerRoles.FILE_ADDER_ALL)) {
verifyProjectKey(projectKey);
}
return delagate.addFileToRepository(projectKey, issueKey, fileName, mimeType, file);
}
#RolesAllowed({FileServerRoles.FILE_VIEWER, FileServerRoles.FILE_VIEWER_ALL})
#Override
public FileDescriptor retrieveFileFromRepository(final String projectKey, final String issueKey, final UUID uuid, final String fileName) {
if (!sessionContext.isCallerInRole(FileServerRoles.FILE_VIEWER_ALL)) {
verifyProjectKey(projectKey);
}
return delagate.retrieveFileFromRepository(projectKey, issueKey, uuid, fileName);
}
}
!sessionContext.isCallerInRole(FileServerRoles.FILE_VIEWER_ALL) always throws IllegalStateException:
Caused by: java.lang.IllegalStateException: No mapping available for role reference file-viewer-all
at com.sun.ejb.containers.EJBContextImpl.isCallerInRole(EJBContextImpl.java:458)
at edu.wvu.esd.swordfish.web.service.FileServerServiceProjectAuthorizationDecorator.retrieveFileFromRepository(FileServerServiceProjectAuthorizationDecorator.java:59)
... 89 more
I have had no problem with any of the roles when that are referenced in #RolesAllowed. I have also tried moving the roles declaration into web.xml. There aren't many references to the error on google.
Has anyone seen this? What was your solution?
I was receiving the same "No mapping available for role reference" error when calling the isCallerInRole(roleName) method within an EJB in GlassFish 3.1. What fixed it for me was adding the appropriate #DeclareRoles annotation to my EJB. If the role name passed to isCallerInRole is not in #DeclareRoles, an IllegalStateException gets thrown. I'm not sure how security works within a decorator but #DeclareRoles was the key for me.
Here is a simple example:
#Stateless
#LocalBean
#DeclareRoles({"user", "admin"})
public class ExampleEJB {
#Resource
private SessionContext sessionContext;
public boolean isUserInRole(String roleName) {
return sessionContext.isCallerInRole(roleName);
}
}