Create Wallet Rest-Api

On Work
This commit is contained in:
GME 2019-03-31 20:50:59 +02:00
parent 4ea0fdd202
commit 892afd8efb
12 changed files with 248 additions and 30 deletions

10
pom.xml
View file

@ -82,6 +82,16 @@
<version>42.2.5</version> <version>42.2.5</version>
</dependency> </dependency>
<!-- ***** --> <!-- ***** -->
<!-- APACHE -->
<!-- https://mvnrepository.com/artifact/commons-lang/commons-lang -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<!-- ***** -->
</dependencies> </dependencies>

View file

@ -2,7 +2,7 @@
-- DROP SEQUENCE public."T_WALLET_wallet_id_seq"; -- DROP SEQUENCE public."T_WALLET_wallet_id_seq";
CREATE SEQUENCE public."T_WALLET_wallet_id_seq"; CREATE SEQUENCE public."t_wallet_id_seq";
ALTER SEQUENCE public."T_WALLET_wallet_id_seq" ALTER SEQUENCE public."t__wallet_id_seq"
OWNER TO monnethicadmin; OWNER TO monnethicadmin;

View file

@ -4,7 +4,7 @@
CREATE TABLE public."T_WALLET" CREATE TABLE public."T_WALLET"
( (
wallet_id integer NOT NULL DEFAULT nextval('"T_WALLET_wallet_id_seq"'::regclass), wallet_id integer NOT NULL DEFAULT nextval('"t_wallet_id_seq"'::regclass),
wallet_hash character varying(255) COLLATE pg_catalog."default" NOT NULL, wallet_hash character varying(255) COLLATE pg_catalog."default" NOT NULL,
user_hash character varying(255) COLLATE pg_catalog."default" NOT NULL, user_hash character varying(255) COLLATE pg_catalog."default" NOT NULL,
type character varying(255) COLLATE pg_catalog."default" NOT NULL, type character varying(255) COLLATE pg_catalog."default" NOT NULL,

View file

@ -17,12 +17,12 @@ import java.util.Collection;
public class QueryWrapper { public class QueryWrapper {
private static Logger logger = Logger.getLogger(QueryWrapper.class); private static Logger logger = Logger.getLogger(QueryWrapper.class);
public String sendQuery(String functionName,String[] args) { public String sendQuery(String functionName,String[] args) throws Exception {
BasicConfigurator.configure(); BasicConfigurator.configure();
UserContext user = Util.readUserContext(Config.ORG1, "admin"); UserContext user = Util.readUserContext(Config.ORG1, "admin");
String response = null; String response = null;
try { //try {
FabricClientWrapper fabricClientWrapper = new FabricClientWrapper(user); FabricClientWrapper fabricClientWrapper = new FabricClientWrapper(user);
ChannelClientWrapper channelClientWrapper = ChannelClientWrapper.setupChannel(fabricClientWrapper); ChannelClientWrapper channelClientWrapper = ChannelClientWrapper.setupChannel(fabricClientWrapper);
@ -49,10 +49,12 @@ public class QueryWrapper {
logger.info("Query payload : " + response + " from peer : " + proposalResponse.getPeer().getName()); logger.info("Query payload : " + response + " from peer : " + proposalResponse.getPeer().getName());
} }
} }
/*
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
*/
return response; return response;
} }
} }

View file

@ -28,6 +28,11 @@ public class Wallet {
public Wallet() { public Wallet() {
} }
public Wallet(String type,String user_hash){
this.type=type;
this.user_hash=user_hash;
}
public Wallet(String wallet_hash, String user_hash, String type, boolean isActive) { public Wallet(String wallet_hash, String user_hash, String type, boolean isActive) {
this.wallet_hash = wallet_hash; this.wallet_hash = wallet_hash;
this.user_hash = user_hash; this.user_hash = user_hash;
@ -79,7 +84,7 @@ public class Wallet {
this.sold = sold; this.sold = sold;
} }
public boolean isIs_active() { public boolean is_active() {
return is_active; return is_active;
} }
@ -105,11 +110,6 @@ public class Wallet {
@Override @Override
public String toString() { public String toString() {
return "Wallet{" + return "{wallet_hash:"+wallet_hash+",user_hash:"+user_hash+",type:"+type+",sold:"+sold+"}";
"wallet_hash='" + wallet_hash + '\'' +
", user_hash='" + user_hash + '\'' +
", type='" + type + '\'' +
", sold=" + sold +
'}';
} }
} }

View file

@ -85,7 +85,7 @@ public class UserDao {
} }
public boolean checkUserPassword(String email, String password) throws Exception { public boolean checkUserPassword(String email, String password) throws Exception {
User user = getUser(email); User user = getUserWithEmail(email);
if(password.equals(user.getPassword())){ if(password.equals(user.getPassword())){
return true; return true;
}else{ }else{
@ -93,7 +93,7 @@ public class UserDao {
} }
} }
public User getUser(String email) throws Exception { public User getUserWithEmail(String email) throws Exception {
if(!verifyUserExist(email)){ if(!verifyUserExist(email)){
return null; return null;
}else{ }else{
@ -105,6 +105,14 @@ public class UserDao {
} }
} }
public User getUserWithHash(String userHash) throws Exception {
userDao = createUserDaoConnection();
QueryBuilder<User,String> queryBuilder = userDao.queryBuilder();
queryBuilder.where().eq("user_hash",userHash);
PreparedQuery<User> preparedQuery = queryBuilder.prepare();
return userDao.queryForFirst(preparedQuery);
}
public void approveUser (String email) throws Exception { public void approveUser (String email) throws Exception {
userDao = createUserDaoConnection(); userDao = createUserDaoConnection();

View file

@ -3,9 +3,7 @@ package restImplementation;
import blockchain.query.TransactionWrapper; import blockchain.query.TransactionWrapper;
import database.user.User; import database.user.User;
import database.user.UserDao; import database.user.UserDao;
import org.hyperledger.fabric.sdk.BlockEvent;
import org.springframework.security.crypto.bcrypt.BCrypt; import org.springframework.security.crypto.bcrypt.BCrypt;
import java.time.Instant; import java.time.Instant;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -30,7 +28,7 @@ public class UserImplementation {
//REGISTER IN REPLICA DB FOR BI //REGISTER IN REPLICA DB FOR BI
Map<String,String> response = new HashMap<>(); Map<String,String> response = new HashMap<>();
User dbUser = userDao.getUser(user.getEmail()); // check if user exist User dbUser = userDao.getUserWithEmail(user.getEmail()); // check if user exist
if(dbUser != null){ if(dbUser != null){
response.put("response","false"); response.put("response","false");
@ -69,7 +67,7 @@ public class UserImplementation {
public User getUser(String email, String password) throws Exception{ public User getUser(String email, String password) throws Exception{
UserDao userDao = new UserDao(); UserDao userDao = new UserDao();
User user1 = userDao.getUser(email); User user1 = userDao.getUserWithEmail(email);
if(user1 != null){ if(user1 != null){
String hash = user1.getPassword(); String hash = user1.getPassword();
if(BCrypt.checkpw(password, hash)){ if(BCrypt.checkpw(password, hash)){
@ -87,7 +85,7 @@ public class UserImplementation {
UserDao userDao = new UserDao(); UserDao userDao = new UserDao();
Map<String,String> response = new HashMap<>(); Map<String,String> response = new HashMap<>();
User userResponse = userDao.getUser(user.getEmail()); User userResponse = userDao.getUserWithEmail(user.getEmail());
if(userResponse != null){ if(userResponse != null){
String hash = userResponse.getPassword(); String hash = userResponse.getPassword();

View file

@ -0,0 +1,95 @@
package restImplementation;
import blockchain.query.QueryWrapper;
import blockchain.query.TransactionWrapper;
import database.Wallet.Wallet;
import database.Wallet.WalletDao;
import database.user.User;
import database.user.UserDao;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.security.crypto.bcrypt.BCrypt;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonReader;
import java.io.StringReader;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class WalletImplementation {
public Map<String,String> createWallet(Wallet wallet) throws Exception {
Map<String,String> response = new HashMap<>();
TransactionWrapper transactionWrapper = new TransactionWrapper();
WalletDao walletDao = new WalletDao();
UserDao userDao = new UserDao();
User user = userDao.getUserWithHash(wallet.getUser_hash());
wallet.setWallet_hash(generateWalletHash(user.getName()+wallet.getType()+user.getFirstname()+ RandomStringUtils.randomAlphabetic(10)));
transactionWrapper.sendTransaction("initWallet",new String[]{wallet.getWallet_hash(),wallet.getType(),wallet.getUser_hash()}); //Create Wallet in Blockchain
wallet.setSold(0.0);
wallet.setIs_active(true);
long now = Instant.now().toEpochMilli();
wallet.setCreation_date(now);
wallet.setModification_date(now);
walletDao.addWallet(wallet); // add wallet to replica DB
response.put("walletHash",wallet.getWallet_hash());
response.put("walletType",wallet.getType());
response.put("walletSold",wallet.getSold().toString());
response.put("response","true");
return response;
}
//getAllUserWallets
public JsonArray getAllUserWallets(String userHash) throws Exception {
QueryWrapper queryWrapper = new QueryWrapper();
JsonArray walletList = null;
String response = queryWrapper.sendQuery("queryWalletsByOwner",new String[]{userHash});
if(response != null) {
JsonReader reader = Json.createReader(new StringReader(response));
walletList = reader.readArray();
}
return walletList;
}
//getWallet
public Wallet getWallet(String walletHash) throws Exception {
QueryWrapper queryWrapper = new QueryWrapper();
String response = queryWrapper.sendQuery("readWallet",new String[]{walletHash});
Wallet wallet = new Wallet();
if(response != null) {
JsonReader reader = Json.createReader(new StringReader(response));
JsonObject walletJson = reader.readObject();
wallet.setWallet_hash(walletJson.getString("id"));
wallet.setUser_hash(walletJson.getString("owner"));
wallet.setType(walletJson.getString("walletType"));
wallet.setSold(walletJson.getJsonNumber("sold").doubleValue());
}
return wallet;
}
//setSold
//transfer
//delete
private String generateWalletHash(String walletBuilderString){
return BCrypt.hashpw(walletBuilderString,BCrypt.gensalt());
}
}

View file

@ -1,9 +1,75 @@
package restService; package restService;
import org.springframework.web.bind.annotation.RequestMapping; import database.Wallet.Wallet;
import org.springframework.web.bind.annotation.RestController; import database.transaction.Transaction;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import restImplementation.WalletImplementation;
import javax.json.JsonArray;
import javax.validation.Valid;
import java.util.Map;
@RestController @RestController
@RequestMapping(value = "/api/rest/wallet") @RequestMapping(value = "/api/rest/wallet")
public class WalletResource { public class WalletResource {
@RequestMapping(value = "/create", method = RequestMethod.POST,produces = "application/json")
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity createWallet(@Valid @RequestBody Wallet wallet){
try{
WalletImplementation walletImplementation = new WalletImplementation();
Map<String,String> walletResponse = walletImplementation.createWallet(wallet);
Wallet returnWallet = new Wallet();
returnWallet.setWallet_hash(walletResponse.get("walletHash"));
returnWallet.setSold(Double.parseDouble(walletResponse.get("walletSold")));
returnWallet.setType(walletResponse.get("walletType"));
if(Boolean.parseBoolean(walletResponse.get("response"))){
return ResponseEntity.status(HttpStatus.OK).body(returnWallet);
}else {
StringResponse responseS = new StringResponse("Wallet already exist");
return ResponseEntity.status(HttpStatus.FOUND).body(responseS);
}
}catch (Exception e){
StringResponse responseS = new StringResponse(e.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(responseS);
}
}
@RequestMapping(value = "/getUserWallets", method = RequestMethod.GET, params = {"userHash"}, produces = "application/json")
@ResponseStatus(HttpStatus.OK)
public ResponseEntity getWallets(@RequestParam(value = "userHash") String userHash){
WalletImplementation walletImplementation = new WalletImplementation();
try{
JsonArray wallets = walletImplementation.getAllUserWallets(userHash);
return ResponseEntity.status(HttpStatus.OK).body(wallets);
} catch (Exception e){
StringResponse responseS = new StringResponse(e.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(responseS);
}
}
@RequestMapping(value = "/getWallet", method = RequestMethod.GET, params = {"walletHash"}, produces = "application/json")
@ResponseStatus(HttpStatus.OK)
public ResponseEntity getWallet(@RequestParam(value = "walletHash") String walletHash){
WalletImplementation walletImplementation = new WalletImplementation();
try{
Wallet walletResponse = walletImplementation.getWallet(walletHash);
if(walletResponse!=null){
return ResponseEntity.status(HttpStatus.OK).body(walletResponse);
}else{
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("{\"response\":null}");
}
}catch (Exception e){
StringResponse responseS = new StringResponse(e.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(responseS);
}
}
} }

View file

@ -22,7 +22,7 @@ public class ReadUserTest {
try{ try{
QueryWrapper queryWrapper = new QueryWrapper(); QueryWrapper queryWrapper = new QueryWrapper();
String functionName = "readUser"; String functionName = "readUser";
String[] args = new String[]{"$2a$10$N1C1lPeVMZ6oY4hSyX2cbuKBoGtJ0yWSXIgBaZ1RsI8QfaoTHCYi2"}; String[] args = new String[]{"$2a$10$tpC8fILKiQqyApJ8/jTPE.YX0grzZsEtmWUyJAidmHOuWGQ4FBdfy"};
String response = queryWrapper.sendQuery(functionName,args); String response = queryWrapper.sendQuery(functionName,args);
if(response != null){ if(response != null){
JsonReader reader = Json.createReader(new StringReader(response)); JsonReader reader = Json.createReader(new StringReader(response));

View file

@ -12,6 +12,7 @@ import java.util.Map;
public class UserImplementationTest { public class UserImplementationTest {
private static Logger logger = Logger.getLogger(UserImplementationTest.class); private static Logger logger = Logger.getLogger(UserImplementationTest.class);
/* /*
@Test @Test
public void RegisterUserWithoutPhone() { public void RegisterUserWithoutPhone() {
@ -30,8 +31,9 @@ public class UserImplementationTest {
logger.warn("Error: "+e); logger.warn("Error: "+e);
} }
} }
*/
/*
@Test @Test
public void RegisterUserWithPhone() { public void RegisterUserWithPhone() {
BasicConfigurator.configure(); BasicConfigurator.configure();
@ -66,14 +68,14 @@ public class UserImplementationTest {
logger.warn("Error: "+e); logger.warn("Error: "+e);
} }
} }
*/ */
/*
@Test @Test
public void approveUserTest() { public void approveUserTest() {
BasicConfigurator.configure(); BasicConfigurator.configure();
User userTest = new User("TotoEmail@gmail.com","$2a$10$Hx5w0c6WM0gJkd0/ZKXZsOyes7UdxYm95TVdG2cBwNjtTk007WKuS"); User userTest = new User("TotoEmail@gmail.com","$2a$10$tpC8fILKiQqyApJ8/jTPE.YX0grzZsEtmWUyJAidmHOuWGQ4FBdfy");
UserImplementation userImplementation = new UserImplementation(); UserImplementation userImplementation = new UserImplementation();
try { try {
userImplementation.approveUser(userTest); userImplementation.approveUser(userTest);
@ -81,7 +83,9 @@ public class UserImplementationTest {
logger.warn("Error: "+e); logger.warn("Error: "+e);
} }
} }
*/
/*
@Test @Test
public void deleteUserTest(){ public void deleteUserTest(){
@ -93,11 +97,8 @@ public class UserImplementationTest {
} catch (Exception e){ } catch (Exception e){
logger.warn("Error: "+e); logger.warn("Error: "+e);
} }
} }
*/
} }

View file

@ -0,0 +1,38 @@
package restImplementation;
import database.Wallet.Wallet;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.junit.Ignore;
import org.junit.Test;
import java.util.Map;
@Ignore
public class WalletImplementationTest {
private static Logger logger = Logger.getLogger(UserImplementationTest.class);
@Test
public void CreateWallet() {
BasicConfigurator.configure();
Wallet wallet = new Wallet("client","$2a$10$tpC8fILKiQqyApJ8/jTPE.YX0grzZsEtmWUyJAidmHOuWGQ4FBdfy");
WalletImplementation walletImplementation = new WalletImplementation();
try{
Map<String,String> walletResponse = walletImplementation.createWallet(wallet);
Wallet returnWallet = new Wallet();
returnWallet.setWallet_hash(walletResponse.get("walletHash"));
returnWallet.setSold(Double.parseDouble(walletResponse.get("walletSold")));
returnWallet.setType(walletResponse.get("walletType"));
logger.info("wallet hash: "+returnWallet.getWallet_hash());
logger.info("wallet sold: "+returnWallet.getSold());
logger.info("wallet type: "+returnWallet.getType());
} catch (Exception e){
logger.warn("Error: "+e.getMessage());
}
}
}