How to fix Race-condition, created duplicate class Error - java

When I start my tomcat server I get this error:
2015 10:25:50 PM org.mongodb.morphia.mapping.MappedClass getOrCreateInstance
SEVERE: Race-condition, created duplicate class: class com.calendar.model.watchers.AccountWatcher
From what I can tell it is coming from Morphia, but I'm unsure why it's happening or how to fix it.
The code in Morphia that the error appears to be coming from is this:
private Object getOrCreateInstance(Class<?> clazz) {
if (mapr.instanceCache.containsKey(clazz))
return mapr.instanceCache.get(clazz);
Object o = mapr.getOptions().objectFactory.createInstance(clazz);
Object nullO = mapr.instanceCache.put(clazz, o);
if (nullO != null)
if(log.isErrorEnabled())
log.error("Race-condition, created duplicate class: " + clazz);
return o;
}
The code for AccountWatcher is:
package com.calendar.model.watchers;
import java.util.Date;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.mongodb.morphia.annotations.PreLoad;
import org.mongodb.morphia.annotations.PrePersist;
import com.calendar.exception.DataAccessException;
import com.calendar.model.Account;
import com.calendar.model.Partner;
import com.calendar.util.MongoUtils;
public class AccountWatcher {
final static Logger log = LoggerFactory.getLogger(AccountWatcher.class);
#PrePersist
void prePersist(Account account) {
if (account.getId() == null) {// This is for create
account.setId(MongoUtils.getGuid());
account.setDateCreated(new Date());
Partner owner = account.getOwner();
if (owner == null || StringUtils.isEmpty(owner.getId())) {
throw new DataAccessException("Owner :" + owner
+ " doesn't exist for account :" + account);
}
} else { // This is for update
}
account.setDateModified(new Date());
}
#PreLoad
void preLoad(Account account) {
if (log.isDebugEnabled()) {
log.debug("Account watcher #PreLoad executing ...");
}
}
}
And the code for the Account class is:
package com.calendar.model;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import lombok.Data;
import lombok.ToString;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonFormat.Shape;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize.Typing;
import org.mongodb.morphia.annotations.Entity;
import org.mongodb.morphia.annotations.EntityListeners;
import org.mongodb.morphia.annotations.Id;
import org.mongodb.morphia.annotations.Indexed;
import org.mongodb.morphia.annotations.Reference;
import com.calendar.model.serializers.PartnerDeSerializer;
import com.calendar.model.serializers.PartnerListSerializer;
import com.calendar.model.serializers.PartnerSerializer;
import com.calendar.model.watchers.AccountWatcher;
#ToString
#EntityListeners(AccountWatcher.class)
#Entity("accounts")
#Data
public class Account {
#Id
private String id;
private String name;
private String timezone;
#JsonSerialize(using = PartnerSerializer.class, typing = Typing.STATIC)
#JsonDeserialize(using = PartnerDeSerializer.class)
#Reference
private Partner owner;
#JsonSerialize(using = PartnerListSerializer.class, typing = Typing.STATIC)
#Reference
private List<Partner> associatedPartners;
#JsonFormat(shape = Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ssZ")
private Date dateCreated;
#JsonFormat(shape = Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ssZ")
private Date dateModified;
#Indexed(unique = true, dropDups = true)
private String externalId;
private Integer externalVersionNumber;
private List<EList> elists;
public Account() {
associatedPartners = new ArrayList<Partner>();
}
}
Thanks in advance for any help that can be provided.

ah, i see. I'm not sure why the decision was made to log that as an error (and conversely, why that logic isn't synchronized) but it's just a logging message. It's not a real problem unless, of course, your listener is mutable and having two instances is an actual problem.

Related

ReactiveCosmosRepository delete functions not working

I'm building a Spring Boot app using CosmosDB as my database. All functions work (creating an item, updating one, get all, get by id,...), apart from delete functions. They don't do anything and since their output is void, it doesn't give me any logs either.
The DAO class:
package projects.trashcanapplication.trashcan.dao;
import com.azure.spring.data.cosmos.core.mapping.Container;
import com.azure.spring.data.cosmos.core.mapping.GeneratedValue;
import com.azure.spring.data.cosmos.core.mapping.PartitionKey;
import org.springframework.data.annotation.Id;
import projects.trashcanapplication.trashcan.models.Address;
import projects.trashcanapplication.trashcan.models.FillStatus;
#Container(containerName = "trashcanData")
public class TrashcanDao{
#GeneratedValue
private String attachments;
private FillStatus fillStatus;
#GeneratedValue
private String rid;
private Address address;
#Id
#PartitionKey
#GeneratedValue
private String id;
#GeneratedValue
private String self;
#GeneratedValue
private String etag;
#GeneratedValue
private int ts;
public TrashcanDao(Address address, FillStatus fillStatus) {
this.fillStatus = fillStatus;
this.address = address;
}
public String getAttachments(){
return attachments;
}
public FillStatus getFillStatus(){
return fillStatus;
}
public String getRid(){
return rid;
}
public Address getAddress(){
return address;
}
public String getId(){
return id;
}
public String getSelf(){
return self;
}
public String getEtag(){
return etag;
}
public int getTs(){
return ts;
}
}
The repository
package projects.trashcanapplication.trashcan.repositories;
import com.azure.spring.data.cosmos.repository.ReactiveCosmosRepository;
import projects.trashcanapplication.trashcan.dao.TrashcanDao;
public interface TrashcanRepository extends ReactiveCosmosRepository<TrashcanDao, String> {
}
The service calling the repository
package projects.trashcanapplication.trashcan.services;
import com.azure.cosmos.models.PartitionKey;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import projects.trashcanapplication.trashcan.dao.TrashcanDao;
import projects.trashcanapplication.trashcan.models.Trashcan;
import projects.trashcanapplication.trashcan.repositories.TrashcanRepository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
#Slf4j
#Service
#AllArgsConstructor
public class TrashcanServiceImpl implements TrashcanService {
private final TrashcanRepository trashcanRepository;
private final TrashcanMapper trashcanMapper;
public Flux<Trashcan> getAllTrashcans() {
return trashcanRepository.findAll().map(trashcanMapper::fromDaoToTrashcan);
}
public Mono<Trashcan> getTrashcanById(String id) {
return trashcanRepository.findById(id).map(trashcanMapper::fromDaoToTrashcan);
}
public String createTrashcan(Trashcan trashcan) {
TrashcanDao saveTrashcan = trashcanMapper.fromTrashcanToDao(trashcan);
trashcanRepository.save(saveTrashcan).subscribe();
return saveTrashcan.getId();
}
public void deleteTrashcan(String id) {
trashcanRepository.deleteById(id, new PartitionKey(id));
log.info(String.format("Deleted trashcan %s", id));
}
}
I have a dataloader temporarily set up to populate my DB with an item upon running the app. The deleteAll() function doesn't work here either.
package projects.trashcanapplication.trashcan.services;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import projects.trashcanapplication.trashcan.dao.TrashcanDao;
import projects.trashcanapplication.trashcan.models.Address;
import projects.trashcanapplication.trashcan.models.FillStatus;
import projects.trashcanapplication.trashcan.repositories.TrashcanRepository;
import javax.annotation.PostConstruct;
#Slf4j
#Component
#AllArgsConstructor
public class DataLoader {
private final TrashcanRepository trashcanRepository;
#PostConstruct
void loadData() {
Address address1 = new Address("Begijnendijk", "3130", "Liersesteenweg", "181");
trashcanRepository.deleteAll();
trashcanRepository.save(new TrashcanDao(address1, FillStatus.EMPTY))
.flatMap(trashcanRepository::save)
.thenMany(trashcanRepository.findAll())
.subscribe(trashcan -> log.info(trashcan.getId().toString()))
;
}
}
You're not subscribing anywhere, so the reactive stream isn't executed.
You could solve that by subscribing manually:
trashcanRepository.deleteAll().subscribe()
However, this is not a good practice, and certainly not in your DataLoader as you can't guarantee the order in which the save/delete-logic is executed (maybe the TrashcanDao is saved before you delete everything).
To solve this, you should create a proper reactive stream:
trashcanRepository
.deleteAll()
.then(trashcanRepository.save(new TrashcanDao(address1, FillStatus.EMPTY)))
.thenMany(trashcanRepository.findAll())
// Your previous subscribe() shouldn't compile since it should contain List<TrashcanDao>
.subscribe(trashcans -> log.info(trashcans.size()));

Why is "this.Repo“ null when invoking methods in SongRepo in Spring Boot Project?

The goal of this method is to provide functionality to a service layer method that will find all songs within a PostgreSQL database. I have implemented an interface "SongServiceInterface" in the service layer and in the event I utilize this SongService via instantiation in the main method or even by sending Http Requests via "/songs" endpoint, I receive this error:
Caused by: java.lang.NullPointerException: Cannot invoke "com.techm.react.Wasteland.repository.SongRepo.findAll()" because "this.songRepo" is null.
Please note upon startup the application will persist the objects to database, but using endpoints or methods within this repo/service cause null field error.
I can provide the code below:
Model
package com.techm.react.Wasteland.models;
import lombok.*;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import javax.persistence.*;
import java.sql.Time;
#Entity
#Table(name = "song")
#NoArgsConstructor
#AllArgsConstructor
#Getter #Setter
#EqualsAndHashCode
#ToString
public class Song {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "title")
private String title;
#JoinColumn(name = "album")
#ManyToOne
#OnDelete(action = OnDeleteAction.CASCADE)
private Album album;
#Column(name = "artists")
private String artists;
#Column(name = "track")
private int track;
#Column(name = "track_length")
private Time length;
}
DTO
package com.techm.react.Wasteland.dto;
import com.techm.react.Wasteland.models.Album;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.sql.Time;
#Data
#NoArgsConstructor
#AllArgsConstructor
public class SongDTO {
private String title;
private AlbumDTO album;
private String artists;
private int track;
private Time length;
}
Repo
package com.techm.react.Wasteland.repository;
import com.techm.react.Wasteland.models.Song;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository
public interface SongRepo extends JpaRepository<Song, Integer> {
public abstract List<Song> findAll();
public abstract List<Song> findByArtist();
public abstract Song findByTrack();
}
Service
package com.techm.react.Wasteland.service;
import com.techm.react.Wasteland.dto.SongDTO;
import com.techm.react.Wasteland.models.Song;
import com.techm.react.Wasteland.repository.SongRepo;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
#Service #Configurable
public class SongService implements SongServiceInterface{
#Autowired
SongRepo songRepo;
#Autowired
private ModelMapper modelMapper;
public List<SongDTO> findAllSongs() {
List<SongDTO> songDTOS = new ArrayList<>();
List<Song> songs = songRepo.findAll();
for(Song s: songs) {
songDTOS.add(modelMapper.map(s, SongDTO.class));
}
return songDTOS;
}
public SongDTO getSongByTitle(String title) throws NoSuchFieldException {
SongDTO song = new SongDTO();
if(title == song.getTitle()){
return song;
}
else throw new NoSuchFieldException("The song by that title does not exist");
}
public SongDTO findByTrack(int track) {
SongDTO song = new SongDTO();
if(song.getTrack() == track) {
return song;
}
return null;
}
}
Main
package com.techm.react.Wasteland;
import com.techm.react.Wasteland.controller.AlbumController;
import com.techm.react.Wasteland.controller.SongController;
import com.techm.react.Wasteland.service.SongService;
import org.modelmapper.ModelMapper;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#SpringBootApplication
#ComponentScan({"com.server", "com.server.config"})
#EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class WastelandApplication {
#Bean
public ModelMapper modelMapper() {
ModelMapper modelMapper = new ModelMapper();
return modelMapper;
}
public static void main(String[] args) {
SpringApplication.run(WastelandApplication.class, args);
SongService songService = new SongService();
System.out.println(songService.findAllSongs());
}
}
When you use new to create an object, it's outside of Spring's context. It won't have the autowired dependencies. Also, you won't be able to use autowired beans in your main (nor should you) as it's a static method. If you want to do this in your app startup, autowire the bean and put the logic in a PostConstruct method.
Here is an example:
public class WastelandApplication {
#Autowired
private SongService songService;
#Bean
public ModelMapper modelMapper() {
ModelMapper modelMapper = new ModelMapper();
return modelMapper;
}
public static void main(String[] args) {
SpringApplication.run(WastelandApplication.class, args);
}
#PostConstruct
public void doSomethingIProbablyShouldNotBeDoing() {
System.out.println(songService.findAllSongs());
}
}

Spring mongo projection doesnt work as expected. Returns all keys

Im trying to use projection to not get all data from the document, but still it always returns all data. Only excluding id is working but the values of the other keys are still returned.
Im trying to get the projection in the service class with mongotemplate.
Also tried it with repository like explained in docs but same result.
Does someone why it doesnt work and could please help.
Using example from https://www.baeldung.com/spring-data-mongodb-projections-aggregations
Service class
package root.uima_document;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import java.util.*;
#Service
public class UimaDocumentService {
#Autowired
private MongoTemplate mongoTemplate;
#Autowired
private UimaDocumentRepository repository;
/**
* all documents in db
* #return
*/
public List<UimaDocument> findAll() {
return repository.findAll();
}
/**
* document with specific id
* #param id
* #return
*/
public List<UimaDocument> findById(String id){
return repository.findAllById(id);
}
public List something() {
Query query = new Query();
query.fields().exclude("testId", "pos", "_id", "testType");
return mongoTemplate.find(query, UimaDocument.class);
}
}
Controller
package root.uima_document;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
* Rest controller class
*/
#NoArgsConstructor
#Data
#RestController
#RequestMapping("/documents")
public class UimaDocumentControlller {
#Autowired
private UimaDocumentService uimaDocumentService;
#GetMapping("/something")
public List something(){
return uimaDocumentService.something();
}
}
package root.entities;
import com.fasterxml.jackson.annotation.JsonIgnore;
import de.tudarmstadt.ukp.dkpro.core.api.ner.type.NamedEntity;
import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token;
import lombok.*;
import org.apache.uima.fit.factory.JCasFactory;
import org.apache.uima.fit.util.JCasUtil;
import org.apache.uima.jcas.JCas;
import org.apache.uima.util.XmlCasDeserializer;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
import org.apache.uima.UIMAException;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.mapping.Document;
import org.xml.sax.SAXException;
#Data
#Document(collection = "uimadocuments")
public class UimaDocument {
#JsonIgnore
#Transient // ignoriere jcas in api und mongodb
private JCas jCas;
#Id
private String id;
private String testId;
private String andereId;
private List<TypeEntity> entities = new ArrayList<>();
private List<TypeEntity> pos = new ArrayList<>();
/**
* #throws UIMAException
* #throws IOException
* #throws SAXException
*/
public UimaDocument(String testId, String andereId) throws UIMAException, IOException, SAXException {
this.testId = testId;
this.andereId = andereId;
this.jCas = JCasFactory.createJCas();
// extract all information
this.extractTest();
this.extractPos();
}
public void extractTest() {
for (NamedEntity namedEntity : JCasUtil.select(jCas, NamedEntity.class)) {
TypeEntity typeEntity = new TypeEntity(
namedEntity.getValue(),
namedEntity.getCoveredText(),
namedEntity.getBegin(),
namedEntity.getEnd()
);
this.entities.add(typeEntity);
}
}
public void extractPos() {
for (Token token : JCasUtil.select(jCas, Token.class)) {
TypeEntity typeEntity = new TypeEntity(
token.getPosValue(),
token.getCoveredText(),
token.getBegin(),
token.getEnd()
);
this.pos.add(typeEntity);
}
}
}

Is there a way to make spring boot mongodb not changing your id attribute value to his object_id?

I am working in a project to learn spring boot, i have a problem where i have a attribute actor_id stored in mongodb with a value x but when i do mongoRepository.findall(), he changes the value of my actor_id to the value of the object_id generated automatically by mongodb, so even if i want to find a value by id i have to put the object_id value instead of the value of actor_id stored in database. Image below to better help understand.
I wanted that the returned value of a get http://localhost:8093/actors in actor_id be = 1 instead of 61634ad37e775d4b87635129.
Below is my code.
Actor.java:
package com.film.SpringAplication.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import org.springframework.data.mongodb.core.mapping.MongoId;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
#Document(collection="actor")
#AllArgsConstructor
#Data
public class Actor {
#Id
String actor_id;
String first_name;
String last_name;
}
ActorController.java
package com.film.SpringAplication.controller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.film.SpringAplication.model.Actor;
import com.film.SpringAplication.service.ActorService;
#RestController
#RequestMapping("/actors")
public class ActorController {
#Autowired
ActorService actorService;
#PostMapping
public String addActor(#RequestBody Actor actor) {
return actorService.addActor(actor);
}
#GetMapping
public List<Actor> getActors() {
return actorService.getActors();
}
#GetMapping("/{id}")
public List<Actor> getActor(#PathVariable String id) {
return actorService.getActor(id);
}
#DeleteMapping("/{id}")
public String deleteActor(#PathVariable String id) {
return actorService.deleteActor(id);
}
}
ActorService.java:
package com.film.SpringAplication.service;
import java.util.List;
import java.util.Optional;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import com.film.SpringAplication.model.Actor;
import com.film.SpringAplication.repository.ActorRepository;
import lombok.RequiredArgsConstructor;
#Service
#RequiredArgsConstructor
public class ActorService {
private final ActorRepository actorRepository;
private final MongoTemplate mongoTemplate;
public String addActor(Actor actor) {
actorRepository.save(actor);
return "Actor Added";
}
public List<Actor> getActors() {
List<Actor> lista = actorRepository.findAll();
return lista;
}
public List<Actor> getActor(String id) {
Query query=new Query()
.addCriteria(Criteria.where("actor_id").is(id));
return mongoTemplate.find(query,Actor.class);
//return actorRepository.findById(id);
}
public String deleteActor(String id) {
actorRepository.deleteById(id);
return "User deleted";
}
}
ActorRepository.java:
package com.film.SpringAplication.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.film.SpringAplication.model.Actor;
public interface ActorRepository extends MongoRepository<Actor,String>{
}
What you can do is, you can use #Field. You annotate #Id to actor_id. So basically it takes as the default primary key. You can do two things. You can annotate _id as default primary key.
#Document(collection="actor")
#AllArgsConstructor
#Data
public class Actor {
#Id
ObjectId _id;
String actor_id;
String first_name;
String last_name;
}
Else you can annotate #Field
#Document(collection="actor")
#AllArgsConstructor
#Data
public class Actor {
#Id
#Field("actor_id")
String actor_id;
String first_name;
String last_name;
}
Related answer

Jersey REST-API returns a HTTP Error 500 (but only client-side)

I am currently working on a REST-API. I am using Jersey for that.
I programmed a couple of interfaces before, and they all worked fine. Now, I'm doing it exactly the same way (in my opinion), but it somehow won't work.
The Problem is that userGet() does not log any error (the error does not occur inside the TRY-CATCH), and it SEEMS like the method is executed successfully. But the client receives only "500 Internal Server Error"-responses.
Do you have any idea how to find out where the error occures? Or do you already know what I've done wrong?
This is my class which should be returned by the API:
package myproject.model;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class UserModel {
#XmlElement(name = "id")
private long id = -1;
#XmlElement(name = "strUsername")
private String username = null;
#XmlTransient
private String encryptedPassword = null;
#XmlElement(name = "Consultant", nillable = true)
private Consultant consultant = null;
public UserModel(long id, String username, String encPw, Consultant co) {
this.id = id;
this.username = username;
this.encryptedPassword = encPw;
this.consultant = co;
}
public static UserModel fromUser(User u) {
return new UserModel(u.getId(), u.getName(), u.getEncryptedPassword(), u.getConsultant());
}
public User toUser() {
return User.fromUserModel(this);
}
public long getId() {
return id;
}
public String getUsername() {
return username;
}
public String getEncryptedPassword() {
return encryptedPassword;
}
public Consultant getConsultant() {
return consultant;
}
public String toString() {
return "id=" + id + ";username=" + username + ";encPw=" + encryptedPassword;
}
}
My REST-API:
package myproject.rest;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import myproject.User;
import myproject.UserModel;
import myproject.DBUtil;
import myproject.SecurityUtil;
#Path("/app/user")
public class HandlerUser extends RestEndpoint {
private static Logger log = Logger.getLogger(HandlerUser.class);
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response userGet() {
Connection con = null;
try {
con = DBUtil.getDBConnection();
//SecurityUtil.checkRight(request);
log.info("Collect all Users");
List<UserModel> usermodels = new ArrayList<UserModel>();
Iterator<User> it = User.getAll(con).iterator();
while(it.hasNext()) {
usermodels.add(it.next().toUserModel());
}
GenericEntity<List<UserModel>> entity = new GenericEntity<List<UserModel>>(usermodels) {};
return Response.ok().entity(entity).build();
}
catch(Exception e) {
log.error("An error occured: " + e.toString());
return Response.status(401).entity(e.toString()).build();
}
finally {
DBUtil.close(null, null, con);
}
}
}
EDIT: User.toUserModel() converts a User-Object to a UserModel-Object (which works fine)

Categories