I use a Room database class on Android Studio.
I have the following entities:
User, Address, Geo, Company, Album, Photo, AlbumPhotoCrossRef (there's many-to-many relationship between Album and Photo). And I added Word too just to test.
The code for these entities are added below.
When I use only Word (comment out other classes in the entities = part, it works, I can see the table via DatabaseInspector.
But when include all entities, the database don't even open, I can't even see name of the database on DatabaseInspector.
And I get the following error:
E/AndroidRuntime: FATAL EXCEPTION: pool-2-thread-1
Process: com.example.lab8_2_room_albums, PID: 8775
java.lang.IllegalStateException: Room cannot verify the data integrity. Looks like you've changed schema but forgot to update the version number. You can simply fix this by increasing the version number.
at androidx.room.RoomOpenHelper.checkIdentity(RoomOpenHelper.java:154)
at androidx.room.RoomOpenHelper.onOpen(RoomOpenHelper.java:135)
at androidx.sqlite.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.onOpen(FrameworkSQLiteOpenHelper.java:142)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:427)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:316)
at androidx.sqlite.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.getWritableSupportDatabase(FrameworkSQLiteOpenHelper.java:92)
at androidx.sqlite.db.framework.FrameworkSQLiteOpenHelper.getWritableDatabase(FrameworkSQLiteOpenHelper.java:53)
at androidx.room.RoomDatabase.inTransaction(RoomDatabase.java:476)
at androidx.room.RoomDatabase.assertNotSuspendingTransaction(RoomDatabase.java:281)
at com.example.lab8_2_room_albums.dao.WordDao_Impl.insert(WordDao_Impl.java:57)
at com.example.lab8_2_room_albums.MainActivity.lambda$onCreate$0(MainActivity.java:59)
at com.example.lab8_2_room_albums.-$$Lambda$MainActivity$h9d6n2GFmqhE1uxj4ezb0-bRXOU.run(Unknown Source:2)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:923)
I/Process: Sending signal. PID: 8775 SIG: 9
It refers to the line in the MainActivity where I run dao.insert(word) also where I insert a word. into database.
I did clean the project, rebuld the project too, but I still get the same error. Why? How to figure out what's wrong? And how can I fix this?
The database class is like below:
package com.example.lab8_2_room_albums.db;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SupportSQLiteDatabase;
import com.example.lab8_2_room_albums.dao.PhotoDAO;
import com.example.lab8_2_room_albums.dao.UserDAO;
import com.example.lab8_2_room_albums.dao.WordDao;
import com.example.lab8_2_room_albums.entities.Address;
import com.example.lab8_2_room_albums.entities.Album;
import com.example.lab8_2_room_albums.entities.AlbumPhotoCrossRef;
import com.example.lab8_2_room_albums.entities.Company;
import com.example.lab8_2_room_albums.entities.Geo;
import com.example.lab8_2_room_albums.entities.Photo;
import com.example.lab8_2_room_albums.entities.User;
import com.example.lab8_2_room_albums.entities.Word;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
#Database(entities = {Word.class, User.class, Address.class, Geo.class, Company.class, Album.class, Photo.class, AlbumPhotoCrossRef.class}, version = 1, exportSchema = true)
public abstract class UserRoomDatabase extends RoomDatabase {
//public abstract UserDAO userDAO();
// public abstract PhotoDAO photoDAO();
public abstract WordDao wordDao();
// volatile: har sammenheng med multithreading. Sikrer at alle trĂ¥der ser samme kopi av INSTANCE.
private static volatile UserRoomDatabase INSTANCE;
private static final int NUMBER_OF_THREADS = 4;
public static final ExecutorService databaseWriteExecutor =
Executors.newFixedThreadPool(NUMBER_OF_THREADS);
public static UserRoomDatabase getDatabase(final Context context) {
if (INSTANCE == null) {
synchronized (UserRoomDatabase.class) {
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
UserRoomDatabase.class, "mydaaatabase")
.addCallback(sRoomDatabaseCallback)
.build();
}
}
return INSTANCE;
}
private static RoomDatabase.Callback sRoomDatabaseCallback = new RoomDatabase.Callback() {
/**
* Called when the database is created for the first time.
* This is called after all the tables are created.
* #param db
*/
#Override
public void onCreate(#NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
// If you want to keep data through app restarts,
// comment out the following block
databaseWriteExecutor.execute(() -> {
// Populate the database in the background.
WordDao wordDao = INSTANCE.wordDao();
//wordDao.deleteAll();
wordDao.insert(new Word("asd"));
wordDao.insert(new Word("adsds"));
wordDao.getAlphabetizedWords();
});
}
#Override
public void onOpen(#NonNull SupportSQLiteDatabase db) {
super.onOpen(db);
}
};
/*
static final Migration MIGRATION_1_2 = new Migration(1, 2) {
#Override
public void migrate(SupportSQLiteDatabase database) {
database.execSQL("ALTER TABLE user "
+ " ADD COLUMN birth_year INTEGER");
}
};*/
}
And here's the Main Activity:
package com.example.lab8_2_room_albums;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.room.Room;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;
import com.example.lab8_2_room_albums.dao.PhotoDAO;
import com.example.lab8_2_room_albums.dao.UserDAO;
import com.example.lab8_2_room_albums.dao.WordDao;
import com.example.lab8_2_room_albums.databinding.ActivityMainBinding;
import com.example.lab8_2_room_albums.db.UserRoomDatabase;
import com.example.lab8_2_room_albums.entities.Address;
import com.example.lab8_2_room_albums.entities.Album;
import com.example.lab8_2_room_albums.entities.AlbumWithPhotos;
import com.example.lab8_2_room_albums.entities.Company;
import com.example.lab8_2_room_albums.entities.Geo;
import com.example.lab8_2_room_albums.entities.Photo;
import com.example.lab8_2_room_albums.entities.User;
import com.example.lab8_2_room_albums.entities.UserWithAlbums;
import com.example.lab8_2_room_albums.entities.UserWithCompanyWithAddressWithGeo;
import com.example.lab8_2_room_albums.entities.Word;
import com.example.lab8_2_room_albums.viewmodel.UserAlbumsViewModel;
public class MainActivity extends AppCompatActivity {
private UserAlbumsViewModel userAlbumsViewModel;
private ActivityMainBinding activityMainBinding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ViewBinding:
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
activityMainBinding = ActivityMainBinding.inflate(layoutInflater);
setContentView(activityMainBinding.getRoot());
// userAlbumsViewModel = new ViewModelProvider(this).get(UserAlbumsViewModel.class);
UserRoomDatabase db = UserRoomDatabase.getDatabase(this);
WordDao dao = db.wordDao();
UserRoomDatabase.databaseWriteExecutor.execute(() -> {
// Populate the database in the background.
// If you want to start with more words, just add them.
Word word = new Word("Helloooo");
dao.insert(word);
word = new Word("Woooorld");
dao.insert(word);
dao.getAlphabetizedWords();
});
}
}
I add some words into the words table in database. It works without any problem.
Word class:
package com.example.lab8_2_room_albums.entities;
import androidx.annotation.NonNull;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
#Entity(tableName = "word_table")
public class Word {
#PrimaryKey
#NonNull
#ColumnInfo(name = "word")
private String mWord;
public Word(#NonNull String word) {this.mWord = word;}
public String getWord(){return this.mWord;}
}
WordDAO:
package com.example.lab8_2_room_albums.dao;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import com.example.lab8_2_room_albums.entities.Word;
import java.util.List;
#Dao
public interface WordDao {
// allowing the insert of the same word multiple times by passing a
// conflict resolution strategy
#Insert(onConflict = OnConflictStrategy.IGNORE)
void insert(Word word);
#Query("DELETE FROM word_table")
void deleteAll();
#Query("SELECT * FROM word_table ORDER BY word ASC")
LiveData<List<Word>> getAlphabetizedWords();
}
User class:
package com.example.lab8_2_room_albums.entities;
import androidx.annotation.NonNull;
import androidx.room.Entity;
import androidx.room.ForeignKey;
import androidx.room.PrimaryKey;
#Entity(foreignKeys = {
#ForeignKey(entity = Address.class, parentColumns = "addressId", childColumns = "fk_addressId", onDelete = ForeignKey.CASCADE),
#ForeignKey(entity = Company.class, parentColumns = "companyId", childColumns = "fk_companyId", onDelete = ForeignKey.CASCADE)
})
public class User {
#PrimaryKey(autoGenerate = true)
public long userId;
public String name;
public String username;
public String email;
public long fk_addressId;
public String phone;
public String website;
public long fk_companyId;
public User(#NonNull String name, #NonNull String username, #NonNull String email, long fk_addressId,
#NonNull String phone, #NonNull String website, long fk_companyId) {
this.name = name;
this.username = username;
this.email = email;
this.fk_addressId = fk_addressId;
this.phone = phone;
this.website = website;
this.fk_companyId = fk_companyId;
}
}
Address:
package com.example.lab8_2_room_albums.entities;
import androidx.annotation.NonNull;
import androidx.room.Entity;
import androidx.room.ForeignKey;
import androidx.room.PrimaryKey;
#Entity(foreignKeys = {
#ForeignKey(entity = Geo.class, parentColumns = "geoId", childColumns = "fk_geoId", onDelete = ForeignKey.CASCADE)
})
public class Address {
#PrimaryKey(autoGenerate = true)
public long addressId;
public String street;
public String suite;
public String city;
public String zipCode;
public long fk_geoId;
public Address(#NonNull String street, #NonNull String suite, #NonNull String city,
#NonNull String zipCode, long fk_geoId) {
this.street = street;
this.suite = suite;
this.city = city;
this.zipCode = zipCode;
this.fk_geoId = fk_geoId;
}
}
Geo:
package com.example.lab8_2_room_albums.entities;
import androidx.annotation.NonNull;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
#Entity
public class Geo {
#PrimaryKey(autoGenerate = true)
public long geoId;
public double lat;
public double lng;
public Geo(#NonNull double lat, #NonNull double lng) {
this.lat = lat;
this.lng = lng;
}
}
Company:
package com.example.lab8_2_room_albums.entities;
import androidx.annotation.NonNull;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
#Entity
public class Company {
#PrimaryKey(autoGenerate = true)
public long companyId;
public String name;
public String catchPhrase;
public String bs;
public Company(#NonNull String name, #NonNull String catchPhrase, #NonNull String bs) {
this.name = name;
this.catchPhrase = catchPhrase;
this.bs = bs;
}
}
Album:
package com.example.lab8_2_room_albums.entities;
import androidx.annotation.NonNull;
import androidx.room.Entity;
import androidx.room.ForeignKey;
import androidx.room.PrimaryKey;
#Entity(foreignKeys = {
#ForeignKey(entity = User.class, parentColumns="userId", childColumns = "fk_userId", onDelete = ForeignKey.CASCADE)
})
public class Album {
#PrimaryKey(autoGenerate = true)
public long albumId;
public long fk_userId;
public String title;
public Album(#NonNull String title, long fk_userId) {
this.title = title;
this.fk_userId = fk_userId;
}
}
Photo:
package com.example.lab8_2_room_albums.entities;
import androidx.annotation.NonNull;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
#Entity
public class Photo {
#PrimaryKey(autoGenerate = true)
public long photoId;
public String title;
public String url;
public String thumbnailUrl;
public Photo(#NonNull String title, #NonNull String url, #NonNull String thumbnailUrl) {
this.title = title;
this.url = url;
this.thumbnailUrl = thumbnailUrl;
}
}
AlbumPhotoCrossRef:
package com.example.lab8_2_room_albums.entities;
import androidx.room.Entity;
import androidx.room.ForeignKey;
#Entity(primaryKeys = {"albumId", "photoId"},
foreignKeys = {
#ForeignKey(entity = Album.class, parentColumns="albumId", childColumns = "albumId", onDelete = ForeignKey.CASCADE),
#ForeignKey(entity = Photo.class, parentColumns="photoId", childColumns = "photoId", onDelete = ForeignKey.CASCADE)
}
)
public class AlbumPhotoCrossRef {
public long albumId;
public long photoId;
}
You've changed the schema (structure) without changing the version number. Room's integrity checking has detected the change and hence the exception.
As you have MIGRATION_1_2 you probably just need to change the version number from 1 to 2 as per :-
#Database(entities = {Word.class, User.class, Address.class, Geo.class, Company.class, Album.class, Photo.class, AlbumPhotoCrossRef.class}, version = 2, exportSchema = true
The message in the log basically says the above bar about having a migration available as per :-
java.lang.IllegalStateException: Room cannot verify the data integrity. Looks like you've changed schema but forgot to update the version number. You can simply fix this by increasing the version number.
However, looking at the migration it's altering the user table by adding a column. This doesn't appear to cover the changes you say you have made (added Word entity/table). You may wish to consider the alternative.
The alternative is to uninstall the App and rerun and the new schema will be applied (not any good if the App has been published as any data will be lost).
Room undertakes this checking by the use of a table called room_master_table this table stores an identity hash which is generated according to the schema that room builds/maintains from the code. Change the schema (code) and the hash changes. If the hash mismatches and the version number is not changed then the exception (or similar in the case of down grade)
I've found multiple sites saying using UUID is possible, but not how. I've tried to simply have a "_id" property that is a UUID, but when I use postman to get the object the "_id" field says null.
Here is a screenshot.
I've made sure mongodb knows UUID by specifying it in the settings:
`
import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.client.*;
import static com.mongodb.client.model.Filters.eq;
import com.mongodb.client.model.FindOneAndReplaceOptions;
import com.mongodb.client.model.ReturnDocument;
import de.tudo.ls14.aqua.smarthome.model.Device;
import de.tudo.ls14.aqua.smarthome.model.Household;
import de.tudo.ls14.aqua.smarthome.model.User;
import org.bson.Document;
import org.bson.UuidRepresentation;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.codecs.pojo.PojoCodecProvider;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;
#Repository("Mongodao")
public class MongoDao {
final MongoClient mongoClient;
final MongoDatabase mongoDatabase;
final MongoCollection<User> userCollection;
final MongoCollection<Household> householdCollection;
final MongoCollection<Device> deviceCollection;
public MongoDao() {
String password = System.getProperty("password");//Passwort aus den VM options
Logger.getLogger("org.mongodb.driver").setLevel(Level.ALL);
ConnectionString connectionString = new ConnectionString("someConnectionString");
CodecRegistry pojoCodecRegistry = fromProviders(PojoCodecProvider.builder().automatic(true).build());
CodecRegistry codecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), pojoCodecRegistry);
MongoClientSettings clientSettings = MongoClientSettings.builder()
.uuidRepresentation(UuidRepresentation.STANDARD)
.applyConnectionString(connectionString)
.codecRegistry(codecRegistry)
.build();
mongoClient = MongoClients.create(clientSettings);
mongoDatabase = mongoClient.getDatabase("ProjektDB");
userCollection = mongoDatabase.getCollection("userCollection", User.class);
householdCollection = mongoDatabase.getCollection("householdCollection", Household.class);
deviceCollection = mongoDatabase.getCollection("deviceCollection", Device.class);
}
public User getUserById(UUID id) {
return userCollection.find(eq("id", id)).first();
}
public Household getHouseholdById(UUID id) {
return householdCollection.find(eq("id", id)).first();
}
public Device getDeviceById(UUID id) {
return deviceCollection.find(eq("id", id)).first();
}
public int addHousehold(Household household) {
householdCollection.insertOne(household);
return 1;
}
public int addUser(User user) {
userCollection.insertOne(user);
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> added:"+user.toString());
return 1;
}
public int addDevice(Device device) {
deviceCollection.insertOne(device);
return 1;
}
public User updateUserById(User user) {
Document filterByUserId = new Document("_id", user.get_id());
FindOneAndReplaceOptions returnDocAfterReplace = new FindOneAndReplaceOptions().returnDocument(ReturnDocument.AFTER);
return userCollection.findOneAndReplace(filterByUserId, user, returnDocAfterReplace);
}
//nur zum testen
public List<User> getAllUsers() {
MongoCursor<User> cursor = userCollection.find().iterator();
List<User> userList = new ArrayList<>();
try{
while(cursor.hasNext()){
userList.add(cursor.next());
}
} finally {
cursor.close();
}
return userList;
}
}
`
Funny enough when i check with ATLAS it even says the _id field is an objectid as seen here.
I've printed my object out and it is clear that the _id field is UUID as seen here.
For the sake of it here is also shown that my pojo certainly uses UUID for the _id field. I'm out of ideas.
Do I have to specify things differently?
I had to add a #BsonProperty("_id") annotation to the UUID property in the POJO because it was just private UUID id = IdUtils.newId(); Not _id.
To query using the java driver:
import org.bson.Document;
public User findUserById(final UUID id){
return collection.find(new Document("_id", id)).first();
}
THIS IS MY ENTITY
my probelem is i don't knwo why my http requtte dosn't work
i'm using ARC application to test the requette this is the error
"status": 500,
"error": "Internal Server Error",
"exception":"org.springframework.beans.ConversionNotSupportedException",
"message": "Failed to convert property value of type 'java.lang.Long' to required type 'com.projet.pfe.entities.AF' for property 'fa'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.Long' to required type 'com.projet.pfe.entities.AF' for property 'fa': no matching editors or conversion strategy found",
"path": "/saveactaf/2/2/333"
package com.projet.pfe.entities;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#IdClass(ActiviteAF.class)
#Entity
public class ActiviteAF implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#ManyToOne
#JoinColumn(name="idact")
private Activite activite;
#Id
#ManyToOne
#JoinColumn(name="idaf")
private AF fa;
private double montant;
public Activite getActivite() {
return activite;
}
public void setActivite(Activite activite) {
this.activite = activite;
}
public AF getFa() {
return fa;
}
public void setFa(AF fa) {
this.fa = fa;
}
public double getMontant() {
return montant;
}
public void setMontant(double montant) {
this.montant = montant;
}
public ActiviteAF(Activite activite, AF fa, double montant) {
super();
this.activite = activite;
this.fa = fa;
this.montant = montant;
}
public ActiviteAF() {
super();
}
}
this is my Repository
package com.projet.pfe.DAO;
import java.util.Collection;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.projet.pfe.entities.ActiviteAF;
public interface ActiviteAFRepository extends JpaRepository<ActiviteAF,Long> {
#Query("select af from ActiviteAF af where af.activite.idActivite like :x")
public Collection<ActiviteAF> activitebyid(#Param("x") Long id);
}
this is the Rest Controller
package com.projet.pfe.service;
import com.projet.pfe.DAO.AFRepository;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.projet.pfe.DAO.ActiviteAFRepository;
import com.projet.pfe.DAO.ActiviteRepository;
import com.projet.pfe.entities.AF;
import com.projet.pfe.entities.Activite;
import com.projet.pfe.entities.ActiviteAF;
import org.springframework.web.bind.annotation.PathVariable;
#RestController
public class ActAFRestService {
#Autowired
private ActiviteAFRepository actafmet;
#Autowired
private ActiviteRepository actr;
#Autowired
private AFRepository afr;
#RequestMapping(value="/saveactaf/{idact}/{idaf}/{montant}",method=RequestMethod.POST)
public ActiviteAF save(#PathVariable(name="idact")long idact,#PathVariable(name="idaf")long idaf,#PathVariable(name="montant")double montant){
Activite a = new Activite();
AF af = new AF();
a = actr.findOne(idact);
af = afr.findOne(idaf);
ActiviteAF aaf = new ActiviteAF(a,af,montant);
return actafmet.save(aaf);
}
}
I find a solution , juste make a singel. Id and change the others to a simple annotation(forign keys) , this solution work but need a test( activite,af ) in the case of adding new object .
https://github.com/sanjuthomas/spring-data-mongodb
I have try several examples such as the one above to understand how to unit test mongo applications using fongo. All the examples examples worked - including the one above but when I upgrade the pom to the latest releases supported in spring boot all the examples fail. It seems the application context is no longer getting loaded for the test. Is this unit test functionality broken or do I need to change the code?
Below is the code that fails and used to work in Spring 3 - now the rule fails stating that a mongo instance does not exist in the context:
package com.ourownjava.spring.data.mongo.repository;
import static com.lordofthejars.nosqlunit.mongodb.MongoDbRule.MongoDbRuleBuilder.newMongoDbRule;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.foursquare.fongo.Fongo;
import com.lordofthejars.nosqlunit.annotation.ShouldMatchDataSet;
import com.lordofthejars.nosqlunit.annotation.UsingDataSet;
import com.lordofthejars.nosqlunit.mongodb.MongoDbRule;
import com.mongodb.Mongo;
import com.ourownjava.spring.data.mongo.model.Trade;
/**
* Spring Data MongoDB Repository Unit testcase.
*
* #author ourownjava.com
*
*/
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration
public class TestTradeRepository {
#Autowired
private ApplicationContext applicationContext;
#Rule
public MongoDbRule mongoDbRule = newMongoDbRule().defaultSpringMongoDb(
"trade-db");
#Autowired
private TradeRepository tradeRepository;
#Test
#ShouldMatchDataSet(location = "/testData/trade-t1.json")
public void shouldSaveTrade(){
tradeRepository.save(createTrade());
}
#Test
#UsingDataSet(locations = {"/testData/trade-t1.json"})
public void shouldFindByTraderId(){
final List<Trade> trades = tradeRepository.findByTraderId("papjac");
assertNotNull(trades);
assertTrue(trades.size() > 0);
assertEquals("papjac", trades.get(0).getTraderId());
}
#Test
#UsingDataSet(locations = {"/testData/trade-t1.json"})
public void shouldFindByExchangeCode(){
final List<Trade> trades = tradeRepository.findByExchangeCode("NYSE");
assertNotNull(trades);
assertTrue(trades.size() > 0);
assertEquals("NYSE", trades.get(0).getExchangeCode());
}
private Trade createTrade(){
final Trade trade = new Trade();
trade.setId("t1");
trade.setTraderId("papjac");
trade.setExchangeCode("NYSE");
trade.setValue(90.3);
return trade;
}
#Configuration
#EnableMongoRepositories
#ComponentScan(basePackageClasses = { TradeRepository.class })
static class MongoConfiguration extends AbstractMongoConfiguration {
#Override
protected String getDatabaseName() {
return "trade-db";
}
#Override
public Mongo mongo() {
return new Fongo("trade-test").getMongo();
}
#Override
protected String getMappingBasePackage() {
return "com.ourownjava.spring.data.mongo";
}
}
}
You have to use Annotation #Bean for mongo()
#Bean
#Override
public Mongo mongo() {
return new Fongo("trade-test").getMongo();
}
Can anyone tell me how to create CXF API? For jbilling integration, I want to create CXF API. But I don't know how to create it.
you can create a class in jbilling which call other evn and send headers and body as Json or string.
like this.
package com.cycle30.plugin.payment;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.log4j.Logger;
public class HttpJMSClient {
private PostMethod postMethod;
private String webUrl;
private List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>();
private static final Logger logger = Logger.getLogger(HttpJMSClient.class);
public HttpJMSClient() {
// TODO Auto-generated constructor stub
}
public void getConnection()
{
webUrl="http://localhost:8081";
nameValuePairs.add(new NameValuePair("x-force-user-id","abc1233"));
nameValuePairs.add(new NameValuePair("x-trans-id","123"));
}
public String makeCall( String body)
{
Object output=null;
try{
WebClient client = WebClient.create(webUrl);
for (NameValuePair h : nameValuePairs) {
client.header(h.getName(), h.getValue());
}
Response response = client.type(MediaType.APPLICATION_JSON).post(body,
Response.class);
logger.debug("Output from Server .... \n");
output = response.getEntity();
logger.debug(output);
System.out.println("my res: "+output.toString());
int statusCode = response.getStatus();
System.out.println("status code: "+statusCode);
return output.toString();
}catch(Exception e){
logger.error(e.getMessage());
logger.error(e.getCause());
}
return output.toString();
}
}