mongodb auditing in spring boot for saving createdDate, lastModifiedDate, createdBy, lastModifiedBy - java

I am using spring boot, therefore I am not using any xml files for configurations.
What I have to do is to EnableMongoAuditing for saving createdDate, lastModifiedDate etc while saving data using MongoRepositories.
My model class
#Component
#Document(collection = "CAPPING")
public class TemporaryCapping extends BaseEntity {
#Field("contract_id")
private BigInteger contractId;
#Field("period_id")
private BigInteger periodId;
#Field("user_id")
private BigInteger userId;
#Field("amount")
private Double amount;
#Field("type_of_capping")
private TypeOfCapping typeOfCapping;
public BigInteger getContractId() {
return contractId;
}
public void setContractId(BigInteger contractId) {
this.contractId = contractId;
}
public BigInteger getPeriodId() {
return periodId;
}
public void setPeriodId(BigInteger periodId) {
this.periodId = periodId;
}
public BigInteger getUserId() {
return userId;
}
public void setUserId(BigInteger userId) {
this.userId = userId;
}
public Double getAmount() {
return amount;
}
public void setAmount(Double amount) {
this.amount = amount;
}
public TypeOfCapping getTypeOfCapping() {
return typeOfCapping;
}
public void setTypeOfCapping(TypeOfCapping typeOfCapping) {
this.typeOfCapping = typeOfCapping;
}
}
public class BaseEntity implements Serializable{
#Id
#Indexed(unique = true)
private BigInteger id;
#CreatedDate
private DateTime createdDate;
#Field("modified_date")
private BigInteger modifiedDate;
public BigInteger getId() {
return id;
}
public void setId(BigInteger id) {
this.id = id;
}
public DateTime getCreatedDate() {
return createdDate;
}
public void setCreatedDate(DateTime createdDate) {
this.createdDate = createdDate;
}
public BigInteger getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(BigInteger modifiedDate) {
this.modifiedDate = modifiedDate;
}
I have used #CreateDate annotation for saving createDate.
and I have used jodatime dependency for DateTime
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.7</version>
</dependency>
spring-data-mongodb is also added in the dependencies.
This is my main application class
#SpringBootApplication
#EnableMongoAuditing
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Where I am wrong in this impelmentation as the date is not getting saved in database?
Also I know that for saving #createdBy you need to write AuditorAware bean but for now I am just trying to save createdBy.
Where should #EnableMongoAuditing be used?

In my application I configure through Java code. I use #EnableMongAuditing this way and also create convertes for ZonedDateTime.
#Configuration
#EnableMongoAuditing
#EnableMongoRepositories(basePackages = { BASE_PACKAGE })
public class MongoConfiguration extends AbstractMongoConfiguration {
public static final String BASE_PACKAGE = "package.with.aggregates";
#Value("${spring.data.mongodb.uri}")
private String mongoUri;
#Value("${spring.data.mongodb.database}")
private String databaseName;
#Override
protected String getDatabaseName() {
return databaseName;
}
#Override
public Mongo mongo() throws Exception {
return new MongoClient(new MongoClientURI(mongoUri));
}
// Here you must add converters to Joda datetypes. In my solution is ZonedDateTime
#Override
public CustomConversions customConversions() {
List<Converter<?, ?>> converterList = new ArrayList<>();
converterList.add(new DateToZonedDateTimeConverter());
converterList.add(new ZonedDateTimeToDateConverter());
return new CustomConversions(converterList);
}
#Override
protected String getMappingBasePackage() {
return BASE_PACKAGE;
}
}

#EnableMongoAuditing can actually be placed anywhere in configurations (next to #Configuration annotation)

Related

How to dump the current state of the mongodatabase in SpringBoot/Java code?

How can we delete the entire database from the code and not the commands??
For example, model class testapi:
public class testapi {
#Id
private int id;
private String status;
private ArrayList<SpotsStatus> cam_reports;
private long date;
// Constructors
public testapi(int id, String status, ArrayList<SpotsStatus> cam_reports, long date) {
this.id = id;
this.status = status;
this.cam_reports = cam_reports;
this.date = date;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public ArrayList<SpotsStatus> getCam_reports() {
return cam_reports;
}
public void setCam_reports(ArrayList<SpotsStatus> cam_reports) {
this.cam_reports = cam_reports;
}
public long getDate() {
return date;
}
public void setDate(long date) {
this.date = date;
}
}
This is my model class; my repository is:
public interface testRepository extends MongoRepository <testapi, Integer> {
}
In my controller, I have to write code to dump the database, restore a database and to delete the database.
My controller class is:
#Rest Controller
#Request Mapping("/testapi")
public class testapiController {
#Autowired
private testRepository repo;
#Request Mapping(value = "/", method = RequestMethod.GET)
public List<testapi> getAllspots() {
return repo.findAll();
How can I dump? What should be the code?
You can use the solutions discussed here:
Use MongoRepository's deleteAll() for remove all data: testRepository.deleteAll()
Use MongoRepository's dropCollection() and createCollection() for re-creating the whole collection:
testRepository.dropCollection(testapi.class);
testRepository.createCollection(testapi.class);

Annotation based Auditing for spring-data-elasticsearch?

I am trying to use the annotation based approach to audit my elasticsearch document using spring-data-elasticsearch. I followed the JPA guide while implementing my classes/setup.
My code looks like this:
#Configuration
#EnableJpaAuditing
public class SpringSecurityAuditorAwareConfiguration {
#Bean
public AuditorAware<String> auditorProvider() {
return new SpringSecurityAuditorAware();
}
}
public class SpringSecurityAuditorAware implements AuditorAware<String> {
public Optional<String> getCurrentAuditor() {
return Optional.ofNullable(SecurityContextHolder.getContext())
.map(SecurityContext::getAuthentication)
.filter(Authentication::isAuthenticated)
.map(Authentication::getPrincipal)
.map(User.class::cast)
.map(User::getUsername);
}
}
#Document(indexName = "myEntity", type = "myEntityType")
public class MyEntity {
#Id
private String id;
#CreatedBy
protected String createdBy;
#CreatedDate
protected OffsetDateTime createdDate;
#LastModifiedBy
protected String lastModifiedBy;
#LastModifiedDate
protected OffsetDateTime lastModifiedDate;
public void setDictionaryId(DictionaryId dictionaryId) {
this.dictionaryId = dictionaryId;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public OffsetDateTime getCreatedDate() {
return createdDate;
}
public void setCreatedDate(OffsetDateTime createdDate) {
this.createdDate = createdDate;
}
public String getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public OffsetDateTime getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(OffsetDateTime lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
}
Unfortunately it when I save a new instance the properties are always set to null. Does spring-data-elasticsearch support the annotation based approach?
Edit:
This is implemented since version 4.0 which has been released in May 2020.
Original answer:
No, this is currently not supported in Spring Data Elasticsearch.
Please create a ticket to add support for this, this is definitely a feature worth to have.

Crudrepository findBy function only works when nothing is found

The first time I implemented the findByContentContaining function in the repository everyting worked fine. But now when I call the function and if it finds something, it gives me an error. If it doesn't find anything it returns an empty list.
This is my repository (everyting works except the findByContentContaining function):
public interface KweetRepo extends CrudRepository<Kweet, Integer> {
Kweet getById(Integer id);
List<Kweet> findTop10ByPosterId(int id);
List<Kweet> findByContentContaining(String content);
List<Kweet> findByPosterId(int id);
}
This is the model for my Kweet class
#Entity
public class Kweet implements Comparable<Kweet>{
#Id
#GeneratedValue
private int id;
#Column(name="content")
private String content;
#JsonFormat(shape = JsonFormat.Shape.STRING)
private Date dateTime;
#ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinColumn(name = "user_id")
private User poster;
#OneToMany(cascade = CascadeType.ALL)
#JoinTable(name="KweetLikedBy")
private List<User> likedBy;
public Kweet() {
}
public Kweet(String content, Date dateTime, User poster, List<User> likedBy) {
this.content = content;
this.dateTime = dateTime;
this.poster = poster;
this.likedBy = likedBy;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getDateTime() {
return dateTime;
}
public void setDateTime(Date dateTime) {
this.dateTime = dateTime;
}
public int getPoster() {
return poster.getId();
}
public void setPoster(User poster) {
this.poster = poster;
}
public List<User> getLikedBy() {
return likedBy;
}
public void addLikedBy(User user) {
this.likedBy.add(user);
}
public void removeLikedBy(User user) {
this.likedBy.remove(user);
}
#Override
public int compareTo(Kweet o) {
return getDateTime().compareTo(o.getDateTime());
}
}

Spring Boot Mongodb search by ID returns null

I have created a spring boot project with mongodb , when i insert data into collection it get inserted but when i try to fetch from findOne by id the inserted value based on id it always returns null, I have given my model class and inserting method below,please tell me whats wrong
Account.java
#Document(collection = "account")
public class Account {
#Id
private long _id;
#Field("account_name")
private String accountName;
#Field("connector_type")
private String connectorType;
#Field("xsiURI1")
private String xsiURI1;
#Field("xsiURI2")
private String xsiURI2;
#Field("oci1")
private String OCI1;
#Field("oci2")
private String OCI2;
#Field("telcomadmin_username")
private String telcomadminUsername;
#Field("telcomadmin_password")
private String telcomadminPassword;
#Field("password_expdays")
private String passwordExpdays;
#Field("account_email_address")
private String accountEmailAddress;
#DateTimeFormat(iso = ISO.DATE_TIME)
#Field("inserted_date")
private Date insertedDate;
#DateTimeFormat(iso = ISO.DATE_TIME)
#Field("updated_date")
private Date updatedDate;
#Field("isActive")
private Boolean isActive;
public long get_id() {
return _id;
}
public void set_id(long _id) {
this._id = _id;
}
public String getXsiURI1() {
return xsiURI1;
}
public void setXsiURI1(String xsiURI1) {
this.xsiURI1 = xsiURI1;
}
public String getXsiURI2() {
return xsiURI2;
}
public void setXsiURI2(String xsiURI2) {
this.xsiURI2 = xsiURI2;
}
public String getOCI1() {
return OCI1;
}
public void setOCI1(String oCI1) {
OCI1 = oCI1;
}
public String getOCI2() {
return OCI2;
}
public void setOCI2(String oCI2) {
OCI2 = oCI2;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public String getConnectorType() {
return connectorType;
}
public void setConnectorType(String connectorType) {
this.connectorType = connectorType;
}
public String getTelcomadminUsername() {
return telcomadminUsername;
}
public void setTelcomadminUsername(String telcomadminUsername) {
this.telcomadminUsername = telcomadminUsername;
}
public String getTelcomadminPassword() {
return telcomadminPassword;
}
public void setTelcomadminPassword(String telcomadminPassword) {
this.telcomadminPassword = telcomadminPassword;
}
public String getPasswordExpdays() {
return passwordExpdays;
}
public void setPasswordExpdays(String passwordExpdays) {
this.passwordExpdays = passwordExpdays;
}
public String getAccountEmailAddress() {
return accountEmailAddress;
}
public void setAccountEmailAddress(String accountEmailAddress) {
this.accountEmailAddress = accountEmailAddress;
}
public Date getInsertedDate() {
return insertedDate;
}
public void setInsertedDate(Date insertedDate) {
this.insertedDate = insertedDate;
}
public Date getUpdatedDate() {
return updatedDate;
}
public void setUpdatedDate(Date updatedDate) {
this.updatedDate = updatedDate;
}
public Boolean getIsActive() {
return isActive;
}
public void setIsActive(Boolean isActive) {
this.isActive = isActive;
}
}
AccountsController.java
#RestController
#RequestMapping("/accounts")
#CrossOrigin("*")
public class AccountsController {
#Autowired
AccountsRepository accountsRepository;
#Autowired
SequenceRepository sequenceRepository;
private static final String ACCOUNT_SEQ_KEY = "accountsequence";
#PostMapping("/create")
public Account createAccount(#Valid #RequestBody Account account) {
account.set_id(sequenceRepository.getNextSequenceId(ACCOUNT_SEQ_KEY));
account.setIsActive(true);
return accountsRepository.save(account);
}
#GetMapping(value = "/findByID/{id}")
public ResponseEntity<Account> getAccountById(#PathVariable("id") String id) {
Account account = accountsRepository.findOne(id);
if (account == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
} else {
return new ResponseEntity<>(account, HttpStatus.OK);
}
}
}
AccountsRepository
public interface AccountsRepository {
List<Account> findAll(Sort sortByCreatedAtDesc);
Account save(Account account);
Account findOne(String id);
void delete(String id);
}
AccountsRepositoryIMPL
#Repository
public class AccountsRepositoryImpl implements AccountsRepository {
DBOperations dbOperations = new DBOperations();
#Override
public List<Account> findAll(Sort sortByCreatedAtDesc) {
Query q = new Query().with(new Sort(Sort.Direction.ASC, "inserted_date"));
List<Account> accountList = dbOperations.getMongoOpertion().findAllAndRemove(q, Account.class);
return accountList;
}
#Override
public Account save(Account account) {
try {
dbOperations.getMongoOpertion().save(account);
} catch (Exception e) {
e.printStackTrace();
}
return account;
}
#Override
public Account fin**strong text**dOne(String id) {
Account account = dbOperations.getMongoOpertion().findOne(Query.query(Criteria.where("_id").is(id)),
Account.class, "account");
return account;
}
#Override
public void delete(String id) {
Query query = new Query();
query.addCriteria(Criteria.where("id").is(id));
Account account = dbOperations.getMongoOpertion().findOne(query, Account.class);
dbOperations.getMongoOpertion().remove(account);
}
}
DBOperations.java
public class DBOperations {
ApplicationContext ctx = new GenericXmlApplicationContext("SpringConfig.xml");
public MongoOperations getMongoOpertion() {
MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");
return mongoOperation;
}
}
Look at your code.
You have declared _id as Long type.
#Id
private long _id;
But in your below methods you are passing String id to match the criteria.
So it is not working.
#Override
public Account findOne(String id) {
Account account = dbOperations.getMongoOpertion().findOne(Query.query(Criteria.where("_id").is(id)),
Account.class, "account");
return account;
}
#Override
public void delete(String id) {
Query query = new Query();
query.addCriteria(Criteria.where("id").is(id));
Account account = dbOperations.getMongoOpertion().findOne(query, Account.class);
dbOperations.getMongoOpertion().remove(account);
}

Realm database issue. -No default Realm Configuration was found-

This is my model class for my reminds
public class Remind extends RealmObject {
#Required
private String descripcion;
#Required
private String fecha;
#Required
private String hora;
#Required
private String titulo;
#PrimaryKey
private String id;
public Remind() {}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public String getFecha() {
return fecha;
}
public void setFecha(String fecha) {
this.fecha = fecha;
}
public String getHora() {
return hora;
}
public void setHora(String hora) {
this.hora = hora;
}
}
this is my config class for obtain context 'cause i don't know what is the
problem with this class :(
public class RemindMe extends Application {
#RealmModule(classes = {Remind.class})
public class SimpleRealmModule {}
private static RemindMe instance;
#Override
public void onCreate() {
super.onCreate();
RealmConfiguration config = new RealmConfiguration.Builder(this).name("RemindMe.DB").build();
Realm.setDefaultConfiguration(config);
}
and this is a part of mi DAO for add some reminds
//this is so problematic class 'cause the Realm object don't find the
database context
public class RemindsDAO {
static boolean flag = false;
public boolean agregarRecordatorio(final Remind remind){
final Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
Remind rem = realm.createObject(Remind.class);
rem.setId(UUID.randomUUID().toString());
rem.setTitulo(remind.getTitulo());
rem.setDescripcion(remind.getDescripcion());
rem.setHora(remind.getHora());
rem.setFecha(remind.getFecha());
}
}, new Realm.Transaction.Callback() {
#Override
public void onSuccess() {
realm.commitTransaction();
RemindsDAO.flag = true;
}
#Override
public void onError(Exception e) {
flag = false;
}
});
return flag;
}
}
You need to register your Application class in the Manifest:
<application
android:name=".RemindMe">
your activities go here...
</application>
Once done you should be able to use Realm.getDefaultInstance() throughout the app with no hassle.

Categories

Resources