Rest Services - Tomcat able to start , homepage working fine but can't do any GET - rest

`
https://www.pegaxchange.com/2016/08/11/jax-rs-java-rest-service-eclipse-tomcat/
I was trying to build working rest service by this guide.
And so far I am struggling.
I'm able to see Tomcat homepage via http://localhost:8080
But can't see any GET searches etc.
Tried to get by below URL
http://localhost:8080/SampleWebProject/search?name=
http://localhost:8080/SampleWebProject/productcatalog/search?name=
http://localhost:8080/SampleWebProject/myRestServices/search?name=
I'm still getting 404
Type Status Report
Message /SampleWebProject/search
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
What am I doing wrong?
Tried to build it 4 times from scratch, on different PC, doubled checked libraries, used Postman and Insomnia.
package com.pegaxchange.java.web.rest;
import javax.ws.rs.ApplicationPath;
import org.glassfish.jersey.server.ResourceConfig;
#ApplicationPath("restservices")
public class MyRESTServices extends ResourceConfig {
public MyRESTServices() {
packages("com.fasterxml.jackson.jaxrs.json");
packages("com.pegaxchange.java.web.rest");
}
}
----------
package com.pegaxchange.java.web.rest;
import java.util.*;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import com.pegaxchange.java.bean.Product;
import com.pegaxchange.java.bean.Status;
#Path("productcatalog")
public class ProductCatalogResource {
private static List<Product> productCatalog;
public ProductCatalogResource() {
initializeProductCatalog();
}
#GET
#Path("search")
#Produces(MediaType.APPLICATION_JSON)
public Product[] searchByName(#QueryParam("name") String name) {
List<Product> products = new ArrayList<Product>();
for (Product p : productCatalog) {
if (name != null && p.getName().toLowerCase().startsWith(name.toLowerCase())) {
products.add(p);
}
}
return products.toArray(new Product[products.size()]);
}
#POST
#Path("insert")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Status insert(Product product) {
productCatalog.add(product);
return new Status("SUCCESS", "Inserted " + product.getName());
}
#GET
#Path("getId")
#Produces(MediaType.APPLICATION_JSON)
public Product get(#QueryParam("id") int id) {
Product product = null;
for (Product p: productCatalog) {
if (id == p.getId() ) {
product = p;
break;
}
}
return product;
}
#POST
#Path("update")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Status update(Product product) {
Status stat = new Status("ERROR", "No ID " + product.getId());
Product prod = get(product.getId());
if (prod != null) {
if (product.getName() != null) {
prod.setName(product.getName());
}
if (product.getUnitPrice() != null) {
prod.setUnitPrice(product.getUnitPrice());
}
stat = new Status("Success", "updated ID " + product.getId());
}
return stat;
}
#DELETE
#Path("delete")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Status delete(#QueryParam("id") int id) {
Status stat = new Status("ERROR", "No ID " + id);
Product product = get(id);
if (product != null) {
productCatalog.remove(product);
stat = new Status("Success", "deleted" + product.getId());
}
return stat;
}
private void initializeProductCatalog() {
if (productCatalog == null) {
productCatalog = new ArrayList<Product>();
productCatalog.add(new Product(1, "Keyboard", 29.99D));
productCatalog.add(new Product(2, "Mouse", 9.95D));
productCatalog.add(new Product(3, "17\" Monitor", 159.49D));
productCatalog.add(new Product(4, "Hammer", 9.95D));
productCatalog.add(new Product(5, "Screwdriver", 7.95D));
productCatalog.add(new Product(6, "English Dictionary", 11.39D));
productCatalog.add(new Product(7, "A House in Bali", 15.99D));
productCatalog.add(new Product(8, "An Alaskan Odyssey", 799.99D));
productCatalog.add(new Product(9, "LCD Projector", 1199.19D));
productCatalog.add(new Product(10, "Smart Thermostat", 1199.19D));
}
}
}
---
package com.pegaxchange.java.bean;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Status implements Serializable {
private static final long serialVersionUID = -9130603850117689481L;
private String status;
private String message;
public Status() {} // needed for JAXB
public Status(String status, String message) {
this.status = status;
this.message = message;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
--
package com.pegaxchange.java.bean;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Product implements Serializable {
private static final long serialVersionUID = 6826191735682596960L;
private int id;
private String name;
private Double unitPrice;
public Product() {} // needed for JAXB
public Product(int id, String name, double unitPrice) {
this.id = id;
this.name = name;
this.unitPrice = unitPrice;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getUnitPrice() {
return unitPrice;
}`enter code here`
public void setUnitPrice(double unitPrice) {
this.unitPrice = unitPrice;
}
}

Just after i posted i founded a solution.
Because its clearly visible...
Wrong URLs
http://localhost:8080/SampleWebProject/restservices/productcatalog/search?name=Hammer
and now working fine.

Related

Post get data from request body, and return json Jakarta.ws.rs

I am tasked with creating a simple web api using JAVA EE and I cant use other external frameworks such as Spring Boot.
I got the get requests to work that was simple, however when I try to return a JSON to the api all I see is {} in postman or browser even though I created a user.
here is my current code
package ab.service;
import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.Application;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
#Path("/MyRestService")
#ApplicationPath("resources")
public class RestService extends Application {
// http://localhosts:8080/BankTaskV1/ressources/MyRestService/sayHello
#GET
#Path("/sayHello")
public String getHelloMsg() {
return "Hello World";
}
#GET
#Path("/echo")
public Response getEchoMsg(#QueryParam("message") String msg) {
return Response.ok("you message was: " + msg).build();
}
#GET
#Path("/User")
public Response getUser() {
// Gson gson = new Gson();
User user = new User(1, "Ahmad");
return Response.status(Response.Status.OK).entity(user).type(MediaType.APPLICATION_JSON).build();
// return gson.toJson(user);
}
#POST
#Path("/CreateUser")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public void createUser(UserRequest requestBody) {
System.out.println("create ran");
System.out.println(requestBody.UserName);
}
}
as you can see in the User endpoint I used GSON to convert user object to a json string and that worked, however I read online that it should work without it if I did it by returning an entity, something called POJO?
but that just gives me an empty {}
furthermore in the endpoint CreateUser I set it to consume json and gave it a request body with class that i defined. but when I try to print the username it gives me null, andd the create ran system output shows that the function ran.
here is my User class
package ab.service;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class User {
private int id;
private String name;
public User() {
}
public User(int id, String name) {
super();
this.id = id;
this.name = name;
}
String getName() {
return name;
}
void setName(String name) {
this.name = name;
}
int getId() {
return id;
}
void setId(int id) {
this.id = id;
}
}
and my userrequest class
package ab.service;
import javax.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlElement;
#XmlRootElement
public class UserRequest {
#XmlElement
String UserName;
#XmlElement
int Id;
}

Multiple MongoDB Connectors with SpringBoot REST api

I have three databases and I used MongoTemplate to have possibility connect to these databases from my application.
but when I use for example POST Method in Postman, I have error 404, not found.
In the console anything is fine and when I try http://localhost:8080/, also I have this error There was an unexpected error (type=Not Found, status=404).
No message available.
I searched too much and read so many things for example like https://dzone.com/articles/multiple-mongodb-connectors-with-spring-boot, but I could not undesrtood how can I define multiple MongoDB Connectors and fix this problem.
The MultipleMongoConfige:
package spring.mongo.thesis.config;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import com.mongodb.MongoClient;
import lombok.RequiredArgsConstructor;
#Configuration
#RequiredArgsConstructor
#EnableConfigurationProperties(MultipleMongoProperties.class)
public class MultipleMongoConfig {
private final MultipleMongoProperties mongoProperties = new MultipleMongoProperties();
#Primary
#Bean(name = "primaryMongoTemplate")
public MongoTemplate primaryMongoTemplate() throws Exception {
return new MongoTemplate(primaryFactory(this.mongoProperties.getPrimary()));
}
#Bean(name = "secondaryMongoTemplate")
public MongoTemplate secondaryMongoTemplate() throws Exception {
return new MongoTemplate(secondaryFactory(this.mongoProperties.getSecondary()));
}
#Bean(name = "thirdMongoTemplate")
public MongoTemplate thirdMongoTemplate() throws Exception {
return new MongoTemplate(thirdFactory(this.mongoProperties.getThird()));
}
#Bean
#Primary
public MongoDbFactory primaryFactory(final MongoProperties mongo) throws Exception {
return new SimpleMongoDbFactory(new MongoClient(mongo.getHost(), mongo.getPort()),
mongo.getDatabase());
}
#Bean
public MongoDbFactory secondaryFactory(final MongoProperties mongo) throws Exception {
return new SimpleMongoDbFactory(new MongoClient(mongo.getHost(), mongo.getPort()),
mongo.getDatabase());
}
#Bean
public MongoDbFactory thirdFactory(final MongoProperties mongo) throws Exception {
return new SimpleMongoDbFactory(new MongoClient(mongo.getHost(), mongo.getPort()),
mongo.getDatabase());
}
}
The PrimaryMongoConfig:
package spring.mongo.thesis.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
#Configuration
#EnableMongoRepositories(basePackages = "spring.mongo.thesis.repository.primary",
mongoTemplateRef = "primaryMongoTemplate")
public class PrimaryMongoConfig {
}
The MultipleMongoProperty:
package spring.mongo.thesis.config;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
#ConfigurationProperties(prefix = "mongodb")
public class MultipleMongoProperties {
private MongoProperties primary = new MongoProperties();
private MongoProperties secondary = new MongoProperties();
private MongoProperties third = new MongoProperties();
public MongoProperties getPrimary() {
return primary;
}
public void setPrimary(MongoProperties primary) {
this.primary = primary;
}
public MongoProperties getSecondary() {
return secondary;
}
public void setSecondary(MongoProperties secondary) {
this.secondary = secondary;
}
public MongoProperties getThird() {
return third;
}
public void setThird(MongoProperties third) {
this.third = third;
}
}
The PlayerController:
package spring.mongo.thesis.controller.primary;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import spring.mongo.thesis.repository.primary.PlayerModel;
import spring.mongo.thesis.repository.primary.PlayerRepository;
#RestController
#RequestMapping("/player")
public class PlayerController {
#Autowired
private PlayerRepository repo;
//Getting Player ID
#GetMapping("/{nickname}")
public ResponseEntity<?> getPlayerByID(#PathVariable String nickname){
try {
PlayerModel p = repo.findById(nickname).get();
return ResponseEntity.ok(p);
} catch (Exception e) {
return ResponseEntity.status(404).body("Not Found!");
}
}
//Get All Players
#GetMapping
public List<PlayerModel> getAllPlayers() {
return repo.findAll();
}
//Delete Players
#DeleteMapping
public String deleteAllPlayers(){
repo.deleteAll();
return "Deleted!";
}
//#ExceptionHandler(MethodArgumentNotValidException.class)
//public void handleMissingParams(MissingServletRequestParameterException ex) {
// String name = ex.getParameterName();
//System.out.println(name + " parameter is missing");
// Actual exception handling
//}
//Create Player
#PostMapping
public ResponseEntity<?> createPlayer(#RequestBody #Valid PlayerModel player) {
PlayerModel findplayer = repo.findByNickname(player.getNickname());
if(findplayer != null) {
return ResponseEntity.status(409).body("Conflict!");
}
repo.save(player);
return ResponseEntity.status(201).body("Created!");
}
//Delete player By ID
#DeleteMapping("/{nickname}")
public ResponseEntity<?> deletePlayerByID(#PathVariable String nickname){
try {
PlayerModel p = repo.findById(nickname).get();
repo.deleteById(nickname);
return ResponseEntity.ok(p);
} catch (Exception e) {
return ResponseEntity.status(404).body("Not Found!");
}
}
//Update Player By ID
#PutMapping("/{nickname}")
public ResponseEntity<?> updatePlayerByID(
#PathVariable("nickname")String nickname,
#RequestBody #Valid PlayerModel player){
PlayerModel findplayer = repo.findByNickname(player.getNickname());
if(findplayer == null)
return ResponseEntity.status(404).
body("There is not Player with indicated Nickname!");
else
player.setNickname(nickname);
repo.save(player);
return ResponseEntity.ok(player);
}
}
The PlayerRepository:
package spring.mongo.thesis.repository.primary;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface PlayerRepository extends MongoRepository<PlayerModel, String>{
PlayerModel findByNickname(String nickname);
}
The PrimaryMongoConfig:
package spring.mongo.thesis.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
#Configuration
#EnableMongoRepositories(basePackages = "spring.mongo.thesis.repository.primary",
mongoTemplateRef = "primaryMongoTemplate")
public class PrimaryMongoConfig {
}
and my Application:
package spring.mongo.thesis.application;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
System.out.println("Hello World!");
}
}
The Player Class:
package spring.mongo.thesis.repository.primary;
import javax.validation.constraints.NotBlank;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
#Data
#AllArgsConstructor
#NoArgsConstructor
#Document(collection = "player")
public class PlayerModel {
#Id
#NotBlank
private String nickname;
#NotBlank
private String firstname;
#NotBlank
private String lastname;
#NotBlank
private String email;
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "PlayerModel [nickname=" + nickname + ", firstname=" + firstname + ", lastname=" + lastname + ", email="
+ email + "]";
}
}
The application.yml:
spring:
autoconfigure:
exclude: org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration
mongodb:
primary:
host: localhost
port: 27017
database: player-db
secondary:
host: localhost
port: 27017
database: game-db
third:
host: localhost
port: 27017
database: score-db

Spring Boot - Bean named entityManagerFactory

I am trying to make a simple Spring Boot application generated with jHipster to get from a postgresql a list of articles from a postreSQL database and display it using a rest controller, but when i run it i get
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in org.adi.security.DomainUserDetailsService required a bean named 'entityManagerFactory' that could not be found.
Action:
Consider defining a bean named 'entityManagerFactory' in your configuration.
But the thing is that that `DomainUserDetailsService is something generated by jhipster which stopped working after i added my classes. So i will write below my classes:
Article Entity:
package org.adi.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="articles")
public class Article implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="article_id")
private int articleId;
#Column(name="title")
private String title;
#Column(name="category")
private String category;
public int getArticleId() {
return articleId;
}
public void setArticleId(int articleId) {
this.articleId = articleId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
ArticleDAO (Repository):
#Transactional
#Repository
public class ArticleDAO implements IArticleDAO {
#PersistenceContext
private EntityManager entityManager;
#Override
public Article getArticleById(int articleId) {
return entityManager.find(Article.class, articleId);
}
#SuppressWarnings("unchecked")
#Override
public List<Article> getAllArticles() {
String hql = "FROM Article as atcl ORDER BY atcl.articleId DESC";
return (List<Article>) entityManager.createQuery(hql).getResultList();
}
#Override
public void createArticle(Article article) {
entityManager.persist(article);
}
#Override
public void updateArticle(Article article) {
Article artcl = getArticleById(article.getArticleId());
artcl.setTitle(article.getTitle());
artcl.setCategory(article.getCategory());
entityManager.flush();
}
#Override
public void deleteArticle(int articleId) {
entityManager.remove(getArticleById(articleId));
}
#Override
public boolean articleExists(String title, String category) {
String hql = "FROM Article as atcl WHERE atcl.title = ? and atcl.category = ?";
int count = entityManager.createQuery(hql).setParameter(1, title)
.setParameter(2, category).getResultList().size();
return count > 0 ? true : false;
}
}
ArticleService:
#Service
public class ArticleService implements IArticleService {
#Autowired
private IArticleDAO articleDAO;
#Override
public Article getArticleById(int articleId) {
Article obj = articleDAO.getArticleById(articleId);
return obj;
}
#Override
public List<Article> getAllArticles(){
return articleDAO.getAllArticles();
}
#Override
public synchronized boolean createArticle(Article article){
if (articleDAO.articleExists(article.getTitle(), article.getCategory())) {
return false;
} else {
articleDAO.createArticle(article);
return true;
}
}
#Override
public void updateArticle(Article article) {
articleDAO.updateArticle(article);
}
#Override
public void deleteArticle(int articleId) {
articleDAO.deleteArticle(articleId);
}
}
and finally my REST controller:
#Controller
#RequestMapping("user")
#CrossOrigin(origins = {"http://localhost:4200"})
public class ArticleController {
#Autowired
private IArticleService articleService;
#GetMapping("article")
public ResponseEntity<Article> getArticleById(#RequestParam("id") String id) {
Article article = articleService.getArticleById(Integer.parseInt(id));
return new ResponseEntity<Article>(article, HttpStatus.OK);
}
#GetMapping("all-articles")
public ResponseEntity<List<Article>> getAllArticles() {
List<Article> list = articleService.getAllArticles();
return new ResponseEntity<List<Article>>(list, HttpStatus.OK);
}
#PostMapping("article")
public ResponseEntity<Void> createArticle(#RequestBody Article article, UriComponentsBuilder builder) {
boolean flag = articleService.createArticle(article);
if (flag == false) {
return new ResponseEntity<Void>(HttpStatus.CONFLICT);
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(builder.path("/article?id={id}").buildAndExpand(article.getArticleId()).toUri());
return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}
#PutMapping("article")
public ResponseEntity<Article> updateArticle(#RequestBody Article article) {
articleService.updateArticle(article);
return new ResponseEntity<Article>(article, HttpStatus.OK);
}
#DeleteMapping("article")
public ResponseEntity<Void> deleteArticle(#RequestParam("id") String id) {
articleService.deleteArticle(Integer.parseInt(id));
return new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
}
}
Did you create a Persistence Unit?
[Reference]=> https://docs.oracle.com/cd/E19798-01/821-1841/bnbrj/index.html
Once you already have the persistence-unit's tag defined you are able to create your entity manager like this:
private final String PERSISTENCE_UNIT_NAME = "PUName";
private EntityManagerFactory eMFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager entityManager=eMFactory.createEntityManager();

Error in annoting camel swagger Rest Service

I have created a rest Service using Apache Camel Swagger component. The rest service works fine but the request and response schema is not what i intended of.
The schema that i am trying to create is :
{
"GetStudentData": [
{
"RollNumber": "1",
"Name": "ABC",
"ClassName": "VII",
"Grade": "A"
}]
}
For this i have created a model as:
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
#XmlRootElement(name = "GetStudentData")
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name="", propOrder={"studentInfo"})
public class StudentInfoWrapper {
#XmlElement(required=true)
private List<Student> studentInfo;
private double visiteddate;
public double getVisiteddate() {
return visiteddate;
}
public void setVisiteddate(double visiteddate) {
this.visiteddate = visiteddate;
}
public List<Student> getStudentInfo() {
return studentInfo;
}
public void setStudentInfo(List<Student> studentInfo) {
studentInfo = studentInfo;
}
}
And my student class is:
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name="", propOrder={"RollNumber", "Name", "ClassName", "Grade"})
public class Student {
private String RollNumber;
private String Name;
private String ClassName;
private String Grade;
public String getRollNumber() {
return RollNumber;
}
public void setRollNumber(String rollNumber) {
RollNumber = rollNumber;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getClassName() {
return ClassName;
}
public void setClassName(String className) {
ClassName = className;
}
public String getGrade() {
return Grade;
}
public void setGrade(String grade) {
Grade = grade;
}
}
So when i load the above service into the swaggerUI it doesn't show the schema that i want.
How can i i get the desired schema. Looking forward to your answers.
Thanks in advance.

Property access of the returned object throws ODatabaseException: Database not set in current thread

I'm using orientdb-object-2.1.9 and trying to setup a basic repository to save and find objects.
But when accessing any property of the returned object from the database, it throws an ODatabaseException, that Database is not set in current thread.
Here is a failing test, showing my usage of the API.
import javax.persistence.Id;
import javax.persistence.Version;
import com.orientechnologies.orient.core.db.OPartitionedDatabasePool;
import com.orientechnologies.orient.object.db.OObjectDatabaseTx;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class ObjectDatabaseTest {
private MyObjectAuthorRepository repository;
#Before
public void setUp() {
repository = new MyObjectAuthorRepository();
}
#After
public void tearDown() {
repository.close();
}
#Test
public void testAuthor() {
Author savedAuthor = repository.saveAuthor(new Author("Author Name"));
// a detached object also fails when accessing the property
// Assert.assertEquals("Author Name", savedAuthor.getAuthorName());
Author author = repository.findAuthor();
Assert.assertEquals("Author Name", author.getAuthorName());
}
class MyObjectAuthorRepository {
private final OPartitionedDatabasePool pool;
public MyObjectAuthorRepository() {
pool = new OPartitionedDatabasePool("memory:test", "admin", "admin");
pool.setAutoCreate(true);
try (OObjectDatabaseTx db = new OObjectDatabaseTx(pool.acquire())) {
db.setAutomaticSchemaGeneration(true);
db.getEntityManager().registerEntityClass(Author.class);
}
}
private Author saveAuthor(Author author) {
OObjectDatabaseTx db = new OObjectDatabaseTx(pool.acquire());
try {
db.begin();
Author savedAuthor = db.save(author);
db.commit();
return db.detach(savedAuthor);
} catch (Exception ex) {
db.rollback();
throw ex;
} finally {
db.close();
}
}
public Author findAuthor() {
try (OObjectDatabaseTx db = new OObjectDatabaseTx(pool.acquire())) {
return db.browseClass(Author.class).next();
}
}
public void close() {
pool.close();
}
}
#javax.persistence.Entity
public class Author {
#Id
private String id;
#Version
private Long version;
private String authorName;
public Author() {
}
public Author(String authorName) {
this.authorName = authorName;
}
public String getId() {
return id;
}
public Long getVersion() {
return version;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
}
}
Please let me know, if the API should be used in a different way or if any other configuration I'm missing here above. It'll be really helpful. Thanks.