com.android.volley.noconnectionerror:javax.net.SSLHandshakeException: - android-volley

who knows how can solves this problem?
com.android.volley.noconnectionerror:javax.net.SSLHandshakeException:java.security.cert.CertPathVaildatorException: Trust anchor for certification path not found.
implementation 'com.android.volley:volley:1.1.0'
private static String URL_REGIST = "https://192.168.1.126/functions.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_REGIST,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("successs");
//Log.d("123: " , response);
if (success.equals("1")){
Toast.makeText(RegistActivity.this,"Register Success!", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
//Log.e("456: ", response);
Toast.makeText(RegistActivity.this,"Register Error! " + e.toString(), Toast.LENGTH_SHORT).show();
accountloading.setVisibility(View.GONE);
btn_regist.setVisibility(View.VISIBLE);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(RegistActivity.this,"Register Error! " + error.toString(), Toast.LENGTH_SHORT).show();
accountloading.setVisibility(View.GONE);
btn_regist.setVisibility(View.VISIBLE);
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("lastname", lastname);
params.put("firstname", firstname);
params.put("nickname", nickname);
params.put("password", password);
//params.put("birthday", birthday);
params.put("email", email);
//params.put("phone", phone);
return params;
}
};
I don't know what's happening.
below is my php code and it's can link to DB. But I dont know what get errors.
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$lastname = $_POST['lastname'];
$firstname = $_POST['firstname'];
$nickname = $_POST['nickname'];
$password1 = $_POST['password'];
//$birthday = $_POST['birthday'];
$email = $_POST['email'];
//$phone = $_POST['phone'];
$password1 = password_hash($password1, PASSWORD_DEFAULT);
require_once 'connect.php';
$sql = "INSERT INTO user (lastname, firstname, nickname, password1, email)
VALUES
('$lastname','$firstname', '$nickname', '$password1', '$email')";
//$sql = "INSERT INTO user (lastname, firstname, nickname, password1, birthday, email, phone)
//VALUES
//('$lastname','$firstname', '$nickname', '$password1', '$birthday', '$email', '$phone')";
if (mysqli_query($conn, $sql)){
$result["success"] = "1";
$result["message"] = "Success";
echo json_encode($result);
mysqli_close($conn);
} else {
$result["success"] = "0";
$result["message"] = "Error";
echo json_encode($result);
mysqli_close($conn);
}
}

Problem is you are using private static String URL_REGIST = "https://192.168.1.126/functions.php"; as URL.
But your local IP address 192.168.1.126 does not have a valid SSL certificate.
To fix this you can use http instead of https for your local URL.
Please note, you should still use https when deploying to a real server if you have a valid SSL certificate for your real URL.

Related

Trust Anchor for Certification path not found - https POST Request with Volley not working

this question is asked very often, but all the answers 2 or 3 years old. I have a login for my Android app and the date is saved in a MySQL database on my cloud server which has a SSL certificate.
When I test my app on my local machine everything is fine, but when I try to connect with my cloud server I get the message "Trust Anchor for Certification path not found". My credentials are ok.
I know that I have to set a sslSocketFactory. I tried so many, but one worked. I´m sitting now for days. May someone had a idea how to solve
here my code without sslSocketFactory
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.logintest, container, false);
btn_login = view.findViewById(R.id.btn_logintest);
email = view.findViewById(R.id.etEmail);
password = view.findViewById(R.id.etPassword);
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
login();
}
public void login() {
str_email = email.getText().toString();
str_password = password.getText().toString();
if(!str_email.equals("") && !str_password.equals("")) {
StringRequest request = new StringRequest(Request.Method.POST, URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction= fragmentManager.beginTransaction();
DummyFragment dummyFragment = new DummyFragment();
fragmentTransaction.replace(R.id.container,dummyFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
Log.e("Text: ", response);
Toast.makeText(getActivity(), "erfolgreicher Text: " +response, Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Text: " +error.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("str_email", email.getText().toString());
params.put("str_password", password.getText().toString());
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
try {
HashMap<String, String> headers = new HashMap<>();
String credentials = "xxxxxxxxx:xxxxxxxxxx";
String auth = "Basic "
+ Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
headers.put("Content-Type", "application/json");
headers.put("Authorization", auth);
return headers;
} catch (Exception e) {
Log.e(TAG, "Authentication failure");
Toast.makeText(getActivity(), "" +e, Toast.LENGTH_LONG).show();
}
return super.getHeaders();
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue.add(request);
}
else {
if (email.getText().toString().equals("")) {
Toast.makeText(getActivity(), "Bitte Email Adresse eingeben", Toast.LENGTH_SHORT).show();
} else if (password.getText().toString().equals("")) {
Toast.makeText(getActivity(), "Bitte Passwort eingeben", Toast.LENGTH_SHORT).show();
}
}
}
});
return view;
}
}
I tried the code from android developer page, but some error. I tried to set network_security.xml but it didn't worked for me. When I test my credentials with postman I get response 200.

Unable to crate a Firestore Bean, BeanCreationException. java.lang.NoClassDefFoundError: com/google/api/gax/rpc/TransportChannelProvider

I am working with Spring Boot and Spring Security, but is my first time using Google cloud firebase Firestore, I am connecting to my database via Firebase Admin SDK. I have a configuration class that looks like this.
#Configuration
public class FirestoreUserConfig {
#Bean
public Firestore getDB() {
return FirestoreClient.getFirestore();
}
}
I have BeanCreationException, my stack trace, in summary, looks like this.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getDB' defined in class path resource [com/d1gaming/user/firebaseconfig/FirestoreUserConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.google.cloud.firestore.Firestore]: Factory method 'getDB' threw exception; nested exception is java.lang.NoClassDefFoundError: com/google/api/gax/rpc/TransportChannelProvider
Caused by: java.lang.ClassNotFoundException: com.google.api.gax.rpc.TransportChannelProvider
at java.net.URLClassLoader.findClass(URLClassLoader.java:382) ~[na:1.8.0_271]
at java.lang.ClassLoader.loadClass(ClassLoader.java:418) ~[na:1.8.0_271]
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:355) ~[na:1.8.0_271]
at java.lang.ClassLoader.loadClass(ClassLoader.java:351) ~[na:1.8.0_271]
... 105 common frames omitted
The weird thing is I followed Google's documentation on Initializing firebase Admin SDK, I added the corresponding dependencies to my pom.xml file but it does not seem to work anyway. This is my Admin SDK dependency.
<dependency>
<groupId>com.google.firebase</groupId>
<artifactId>firebase-admin</artifactId>
<version>7.0.1</version>
</dependency>
I imagine Maven is not able to find this TransportChannelProvider class, Im not sure. I also tried adding all of gcp core dependencies in case provided Admin SDK dependency didn't have the class but I had the same result. I am also making use of a Service and a RESTController for my back end application, I don't know if it is relevant to include it here but I am going to include it just in case.
#Service
public class UserService {
public final String USERS_COLLECTION = "users";
#Autowired
private PasswordEncoder passwordEncoder;
private Firestore firestore;
//get users collcetion from Firestore.
private CollectionReference getUsersCollection() {
return firestore.collection(this.USERS_COLLECTION);
}
//Post a user onto the user collection. documentID is auto-generated by firestore.
public String saveUser(User user) throws InterruptedException, ExecutionException {
Query query = getUsersCollection().whereEqualTo("userName", user.getUserName());
QuerySnapshot querySnapshot = query.get().get();
//Query to validate if userName is already in use.
if(querySnapshot.isEmpty()) {
ApiFuture<DocumentReference> document = getUsersCollection().add(user);
DocumentReference reference = document.get();
String userId = document.get().getId();
//Assign auto-generated Id to userId field for ease of querying.
WriteBatch batch = FirestoreClient.getFirestore().batch();
batch.update(reference, "userId",userId);
//ENCODE USER PASSWORD!
batch.update(reference, "userPassword",passwordEncoder.encode(reference.get().get().toObject(User.class).getUserPassword()));
List<WriteResult> results = batch.commit().get();
results.forEach(result -> {
System.out.println("Update Time: " + result.getUpdateTime());
});
return "Created user with ID: " + "'" + userId + "'";
}
return "Username is already in use";
}
//Get User by given its email.
public Optional<User> getUserByEmail(String userEmail) throws InterruptedException, ExecutionException{
Query query = getUsersCollection().whereEqualTo("userEmail", userEmail);
QuerySnapshot snapshot = query.get().get();
//if user with provided Email exists in collection.
if(!snapshot.isEmpty()) {
List<User> userLs = snapshot.toObjects(User.class);
//Since there is a unique email for each document,
//There will only be on User object on list, we will retrieve the first one.
for(User currUser: userLs) {
return Optional.of(currUser);
}
}
return null;
}
//Query for user by given userName.
public Optional<User> getUserByUserName(String userName) throws InterruptedException, ExecutionException{
//Perform a query based on a user's Name.
Query query = getUsersCollection().whereEqualTo("userName", userName);
QuerySnapshot snapshot = query.get().get();
if(!snapshot.isEmpty()) {
List<User> userList = snapshot.toObjects(User.class);
//Since there is a unique userName for each document,
//there will only be one User object on the list, we will retrieve the first one.
for(User currUser: userList) {
return Optional.of(currUser);
}
}
return null;
}
//Query for user by given userName.
public User getUserByName(String userName) throws InterruptedException, ExecutionException {
//Perform a query based on a user's Name.
Query query = getUsersCollection().whereEqualTo("userName", userName);
QuerySnapshot snapshot = query.get().get();
if(!snapshot.isEmpty()) {
List<User> userList = snapshot.toObjects(User.class);
//Since there is a unique userName for each document,
//there will only be one User object on the list, we will retrieve the first one.
for(User currUser : userList) {
return currUser;
}
}
return null;
}
//Get User by its auto-generated ID.
public User getUserById(String userId) throws InterruptedException, ExecutionException {
DocumentReference reference = getUsersCollection().document(userId);
if(reference.get().get().exists()) {
DocumentSnapshot snapshot = reference.get().get();
User user = snapshot.toObject(User.class);
return user;
}
return null;
}
//Get DocumentReference on a User.
public DocumentReference getUserReference(String userId) throws InterruptedException, ExecutionException {
DocumentReference reference = getUsersCollection().document(userId);
//Evaluate if documentExists in users collection.
if(reference.get().get().exists()) {
return reference;
}
return null;
}
//return a list of objects located in the users collection.
public List<User> getAllUsers() throws InterruptedException, ExecutionException {
//asynchronously retrieve all documents
ApiFuture<QuerySnapshot> future = getUsersCollection().get();
List<QueryDocumentSnapshot> objects = future.get().getDocuments();
//If there is no documents, return null.
if(!objects.isEmpty()) {
List<User> ls = new ArrayList<>();
objects.forEach((obj) -> {
User currUser = obj.toObject(User.class);
ls.add(currUser);
});
return ls;
}
return null;
}
//delete a User from users collection by a given id.
//In reality delete method just changes UserStatus from active to inactive or banned.
public String deleteUserById(String userId) throws InterruptedException, ExecutionException {
Firestore db = FirestoreClient.getFirestore();
DocumentReference reference = db.collection(USERS_COLLECTION).document(userId);
User user = reference.get().get().toObject(User.class);
if(user == null) {
return "User not found.";
}
WriteBatch batch = db.batch();
batch.update(reference, "userStatusCode",UserStatus.INACTIVE);
ApiFuture<List<WriteResult>> result = batch.commit();
List<WriteResult> results = result.get();
results.forEach(response -> {
System.out.println("Update Time:" + response.getUpdateTime());
});
//Check if user did actually change status.
if(reference.get().get().toObject(User.class).getStatusCode().equals(UserStatus.ACTIVE)) {
return "User with ID: " + "'" + userId + "'" + " was deleted.";
}
return "User could not be deleted";
}
//Delete a User's certain field value.
public String deleteUserField(String userId, String userField) throws InterruptedException, ExecutionException {
Firestore firestore = FirestoreClient.getFirestore();
DocumentReference reference = getUsersCollection().document(userId);
if(!reference.get().get().exists()) {
return "User not found.";
}
Map<String,Object> map = new HashMap<>();
map.put(userField, FieldValue.delete());
WriteBatch batch = firestore.batch();
batch.update(reference, map);
List<WriteResult> results = batch.commit().get();
results.forEach(response -> System.out.println("Update Time: " + response.getUpdateTime()));
return "Field deleted Successfully";
}
//Change UserStatus to BANNED
public String banUserById(String userId) throws InterruptedException, ExecutionException {
Firestore db = FirestoreClient.getFirestore();
final DocumentReference reference = db.collection(this.USERS_COLLECTION).document(userId);
WriteBatch batch = db.batch().update(reference,"userStatusCode",UserStatus.BANNED);
List<WriteResult> results = batch.commit().get();
results.forEach(response -> System.out.println("Update Time: " + response.getUpdateTime()));
if(reference.get().get().toObject(User.class).getStatusCode().equals(UserStatus.BANNED)) {
return "User with ID: " + "'" + userId + "'" + " was BANNED.";
}
return "User could not be BANNED.";
}
//Set a user with all new fields.
public String updateUser(User user) throws InterruptedException, ExecutionException {
Firestore firestore = FirestoreClient.getFirestore();
final DocumentReference reference = getUsersCollection().document(user.getUserId());
DocumentSnapshot snapshot = reference.get().get();
if(snapshot.exists()) {
WriteBatch batch = firestore.batch();
batch.set(reference, user);
List<WriteResult> results = batch.commit().get();
results.forEach(response -> System.out.println("Update time: " + response.getUpdateTime()));
return "User updated successfully";
}
return "User not found.";
}
// Update a specific field on a given document by another given value. In case userId is field to be changed, one integer will be subtracted from userTokens field.
public String updateUserField(String userId,String objectField, String replaceValue) throws InterruptedException, ExecutionException {
Firestore db = FirestoreClient.getFirestore();
final DocumentReference reference = getUsersCollection().document(userId);
if(!reference.get().get().exists()) {
return "User not found.";
}
WriteBatch batch = db.batch();
List<WriteResult> results = new ArrayList<>();
//These fields cannot be updated.
if(!objectField.equals("userName") && !objectField.equals("userCash") && !objectField.equals("userTokens") && !objectField.equals("userId")) {
batch.update(reference, objectField, replaceValue);
results = batch.commit().get();
results.forEach(response ->{
System.out.println("Update time: " + response.getUpdateTime());
});
}
else if(objectField.equals("userName")) {
String response = updateUserName(userId, replaceValue);
return response;
}
else {
return "This field canntot be updated.";
}
return "User field could not be updated.";
}
//Update a user's userName depending of availability and token adquisition capacity. i.e. if user has enough tokens to pay fee.
public String updateUserName(String userId, String newUserName) throws InterruptedException, ExecutionException {
Firestore db = FirestoreClient.getFirestore();
final DocumentReference reference = getUsersCollection().document(userId);
DocumentSnapshot snapshot = reference.get().get();
if(!snapshot.exists()) {
return "User not found.";
}
Query query = getUsersCollection().whereEqualTo("userName", newUserName);
QuerySnapshot querySnapshot = query.get().get();
//Evaluate if userName is already in use.
String response = "Username is already taken";
if(querySnapshot.isEmpty()) {
//Transaction to get() tokens and update() tokens.
ApiFuture<String> futureTransact = db.runTransaction(transaction -> {
DocumentSnapshot doc = transaction.get(reference).get();
double tokens = doc.getDouble("userTokens");
//evaluate if user holds more than one token
if(tokens >= 1) {
transaction.update(reference, "userTokens", tokens - 1);
transaction.update(reference, "userName", newUserName);
return "Username updated to: '"+ newUserName +"'";
}
else {
throw new Exception("Not enough Tokens");
}
});
response = futureTransact.get();
}
return response;
}
//update user Currency field.
public String updateUserCash(String userId, double cashQuantity) throws InterruptedException, ExecutionException {
Firestore firestore = FirestoreClient.getFirestore();
final DocumentReference reference = getUsersCollection().document(userId);
DocumentSnapshot snapshot = reference.get().get();
String response = "User not found.";
//evaluate if document exists
if(snapshot.exists()) {
ApiFuture<String> futureTransaction = firestore.runTransaction(transaction -> {
Map<String,Object> map = new HashMap<>();
map.put("userCash", FieldValue.increment(cashQuantity));
transaction.update(reference, map);
return "Updated userCash";
});
response = futureTransaction.get();
return response;
}
return response;
}
//Update user Token field.
public String updateUserTokens(String userId, double tokenQuantity) throws InterruptedException, ExecutionException {
Firestore firestore = FirestoreClient.getFirestore();
final DocumentReference reference = getUsersCollection().document(userId);
String response = "User not found.";
//evaluate if user exists on collection.
if(reference.get().get().exists()) {
ApiFuture<String> futureTransaction = firestore.runTransaction(transaction -> {
Map<String,Object> map = new HashMap<>();
map.put("userTokens",tokenQuantity);
transaction.update(reference, map);
return "Updated userTokens";
});
response = futureTransaction.get();
return response;
}
return response;
}
//evaluate if given documentId exists on given collection.
public static boolean isPresent(String userId,String collectionName) throws InterruptedException, ExecutionException {
Firestore db = FirestoreClient.getFirestore();
DocumentReference reference = db.collection(collectionName).document(userId);
ApiFuture<DocumentSnapshot> snapshot = reference.get();
DocumentSnapshot document = snapshot.get();
if(!document.exists()) {
return false;
}
return true;
}
//Evaluate if given document's status corresponds to active.
public static boolean isActive(String userId, String collectionName) throws InterruptedException, ExecutionException {
Firestore db = FirestoreClient.getFirestore();
DocumentReference reference = db.collection(collectionName).document(userId);
ApiFuture<DocumentSnapshot> snapshot = reference.get();
DocumentSnapshot result = snapshot.get();
User user = result.toObject(User.class);
if(user.getStatusCode().equals(UserStatus.ACTIVE)) {
return true;
}
return false;
}
}
My Controller class:
#RestController
#RequestMapping("/userapi")
#CrossOrigin(origins = "http://localhost:4200")
public class UserController {
#Autowired
UserService userServ;
#GetMapping(value = "/users/search",params="userName")
#PreAuthorize("hasRole('PLAYER')")
public ResponseEntity<Object> getUserByName(#RequestParam(value = "userName", required = true)final String userName) throws InterruptedException, ExecutionException{
if(userName == null) {
return new ResponseEntity<>("Invalid Input",HttpStatus.BAD_REQUEST);
}
User user = userServ.getUserByName(userName);
if(user == null) {
return new ResponseEntity<>("User Not Found", HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(user,HttpStatus.OK);
}
#GetMapping("/users")
#PreAuthorize("hasRole('PLAYER')")
public ResponseEntity<List<User>> getAllUsers() throws InterruptedException, ExecutionException{
List<User> ls = userServ.getAllUsers();
if(ls.isEmpty()) {
return new ResponseEntity<List<User>>(ls, HttpStatus.NO_CONTENT);
}
return new ResponseEntity<List<User>>(ls, HttpStatus.OK);
}
#DeleteMapping(value = "/users/delete",params="userId")
#PreAuthorize("hasRole('ADMINISTRATOR')")
public ResponseEntity<Object> deleteUserById(#RequestParam(value="userId", required = true)String userId, #RequestParam(required = false, value="userField") String userField) throws InterruptedException, ExecutionException{
if(userField != null) {
String response = userServ.deleteUserField(userId, userField);
if(response.equals("User not found.")) {
return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(response, HttpStatus.OK);
}
String response = userServ.deleteUserById(userId);
if(response.equals("User not found.")) {
return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(response, HttpStatus.OK);
}
#PutMapping(value = "/users/update")
#PreAuthorize("hasRole('ADMINISTRATOR') or hasRole('PLAYER')")
public ResponseEntity<Object> updateUser(#RequestBody User user) throws InterruptedException, ExecutionException{
String response = userServ.updateUser(user);
if(response.equals("User not found.")) {
return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(response, HttpStatus.OK);
}
#PutMapping(value = "/users/update",params="userId")
#PreAuthorize("hasRole('ADMINISTRATOR') or hasRole('PLAYER')")
public ResponseEntity<Object> updateUserField(#RequestParam(required = true, value="userId")String userId, #RequestParam(required = true)String userField, #RequestParam(required = true)String replaceValue) throws InterruptedException, ExecutionException{
String response = userServ.updateUserField(userId, userField, replaceValue);
if(response.equals("User not found.")) {
return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
}
else if(response.equals("This field cannot be updated.")) {
return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(response, HttpStatus.OK);
}
}
I didn't find ANY documentation on this particular problem and that is why I am here, I would be glad if anyone could help me solving this problem. Am I missing something? Anyways thank you for your time, happy coding.
as you said, you are missing the TransportChannelProvider interface and it's implementations. it's not provided in the dependency you added.
try to add this dependency to your POM:
<dependency>
<groupId>com.google.api</groupId>
<artifactId>gax</artifactId>
<version>1.57.0</version>
</dependency>
the interface included there.
After checking my pom.xml and my dependency hierarchies(On Eclipse, found on the toolbar above the console when the pom.xml file is being viewed.), I found I had another dependency on another Spring Boot project that was overriding the one I had on my project, make sure to check all dependencies on different projects as well. The dependency version I had on my other project did not include the classes Spring needed to create a a bean.

How to Redirect request as post using ResponseEntity

I trying to include response from other url from ResponseEntity for oauth authorization but it is failing as I am unable to specify request method.
Below is the code
#RequestMapping(value = "/login/otp", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
#ResponseBody
public ResponseEntity<?> getOTP(#Valid #RequestBody String loginDtls,UriComponentsBuilder ucBuilder) {
LoginDAO login = null;
ResponseEntity<?> resp = null;
try {
ObjectMapper mapper = new ObjectMapper();
String userId = "";
try {
JsonNode root = mapper.readTree(loginDtls);
userId = root.get("userId").textValue();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("UserController : getting otp for contact "+ userId);
login = loginService.findByUserId(userId);
if (login==null) {
System.out.println("A UserDAO with name " + userId + " does not exist");
resp = new ResponseEntity<String>(HttpStatus.NOT_FOUND);
}
String otp = GenUtil.generateOTP();
LoginDAO loginUpd = new LoginDAO(login);
loginUpd.setOtp(otp);
loginUpd.setOtpTimestamp(new Timestamp(System.currentTimeMillis()));
loginService.updateLogin(loginUpd);
System.out.println(loginUpd);
resp = getAuthenticated(ucBuilder);
System.out.println(resp.getStatusCodeValue());
System.out.println(resp.getBody());
}catch(Exception e) {
e.printStackTrace();
}
resp = new ResponseEntity<String>(login.toString(), HttpStatus.OK);
return resp;
}
private ResponseEntity<?> getAuthenticated(UriComponentsBuilder ucBuilder){
HttpHeaders headers = new HttpHeaders();
URI uri= ucBuilder.path("/oauth/token"+PASSWORD_GRANT).build().toUri();
List<MediaType> accept = new ArrayList<MediaType>();
accept.add(MediaType.APPLICATION_JSON_UTF8);
headers.setAccept(accept);
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
headers.setBasicAuth("my-trusted-client", "secret");
System.out.println(headers);
ResponseEntity<?> resp = ResponseEntity.created(uri).headers(headers).build();
return resp;
}

Unable to mock value in Junit/Mockito

I have this auth method for login and i am doing a junit test on it.
I am using Mockito, spring4, hibernate5.
What i am facing is this.
The junit test result is correct for testIsAuthorizedUser_normalLogin().
However for testIsAuthorizedUser_blackListUser(), it is not.
I am expecting it to throw an exception.
The problem lies in this line of code.
when(blacklistDeviceService.getBlacklistDeviceForSearch(
eq(PropertiesUtil.BlacklistType.IP_ADDRESS.ordinal()), eq(request.getRemoteAddr()), eq(true), eq(null), eq(null), eq(null)))
.thenReturn(deviceListForIp);
When i debug the code blacklistDeviceService.getBlacklistDeviceForSearch does not return me the object that i force it to return. instead it return me a empty list.
How do i return the value?
Main implementation
public Map<String,String> isAuthorizedUser(String username, String password, Integer loginType, String imei, HttpServletRequest req) throws ErrorException
{
HashMap<String,String> result = new HashMap<>();
UUID uuid = UUID.randomUUID();
UserInfo user = null;
user = isAuthorizedUser(username, password, loginType, imei, req, uuid.toString());
if (isPolicyEnforce)
{
validate(user);
//trigger when user pwd is expired or when password is reset
if (user.getExpire() || user.getIsPasswordReset())
{
result.put(PropertiesUtil.MAPPING_TOKEN, generateToken(user, uuid.toString()));
result.put(PropertiesUtil.MAPPING_CHANGE_PASSWORD, "true");
return result;
}
}
result.put(PropertiesUtil.MAPPING_TOKEN, generateToken(user, uuid.toString()));
result.put(PropertiesUtil.MAPPING_CHANGE_PASSWORD, "false");
return result;
}
private UserInfo isAuthorizedUser(String username, String password, Integer loginType, String imei, HttpServletRequest req, String uuid) throws ErrorException
{
UserInfo user = userInfoDAO.findById(username);
if (GlobUtil.isNotEmpty(user))
{
try
{
if (isPolicyEnforce && (maxFailAttempt < 0))
{
throw new ErrorException(msgProperty.getProperty(MessageUtil.ERR_AUTH_INVALID_POLICY));
}
Set<Role> roles = new HashSet<>(userRoleDAO.getRoleBy(user));
if(roles.isEmpty())
{
throw new ErrorException(msgProperty.getProperty(MessageUtil.ERR_AUTH_UNAUTHORIZED_USER));
}
if (PasswordEncoder.verifyPassword(password, user.getPassword()))
{
if(isBlacklist(req.getRemoteAddr(), imei))
{
throw new ErrorException(msgProperty.getProperty(MessageUtil.ERR_AUTH_UNAUTHORIZED_DEVICE));
}
if(GlobUtil.isNotEmpty(user.getErrorCount()) && user.getErrorCount() > 0)
{
user.setErrorCount(0);
accessControlTransNewService.transNewUpdateUser(user);
}
accessControlTransNewService.transNewAddLoginLog(username, PropertiesUtil.ACTION_LOGIN, PropertiesUtil.getEnum(PropertiesUtil.LoginType.values(), loginType).name(), "Login - Success.", req);
}
else
{
if (user.getIsActive() && !user.getIsLock())
{
accessControlTransNewService.transNewAddLoginLog(username, PropertiesUtil.ACTION_LOGIN, PropertiesUtil.getEnum(PropertiesUtil.LoginType.values(), loginType).name(), "Login - Fail. Invalid password.", req);
unauthorizedAccess(user, maxFailAttempt);
throw new ErrorException(msgProperty.getProperty(MessageUtil.ERR_AUTH_INVALID_USERPWD));
}
else
{
throw new ErrorException(msgProperty.getProperty(MessageUtil.ERR_AUTH_INACTIVE_USER));
}
}
}
catch (CannotPerformOperationException | InvalidHashException e)
{
throw new ErrorException(e);
}
catch (NumberFormatException nfe)
{
throw new ErrorException(msgProperty.getProperty(MessageUtil.ERR_AUTH_INVALID_POLICY));
}
}
else
{
accessControlTransNewService.transNewAddLoginLog(username, PropertiesUtil.ACTION_LOGIN, PropertiesUtil.getEnum(PropertiesUtil.LoginType.values(), loginType).name(), "Login - Fail. User do not exist.", req);
throw new ErrorException(msgProperty.getProperty(MessageUtil.ERR_AUTH_INVALID_USERPWD));
}
addUserToSession(user, req, uuid);
return user;
}
private boolean isBlacklist(String ipAddress, String imei)
{
List<BlacklistDevice> deviceListForImei = new ArrayList<>();
List<BlacklistDevice> deviceListForIp = new ArrayList<>();
if(GlobUtil.isNotEmpty(imei))
{
deviceListForImei = blacklistDeviceService.getBlacklistDeviceForSearch(PropertiesUtil.BlacklistType.IMEI.ordinal(), imei, true, null, null, null);
}
if(GlobUtil.isNotEmpty(ipAddress))
{
deviceListForIp = blacklistDeviceService.getBlacklistDeviceForSearch(PropertiesUtil.BlacklistType.IP_ADDRESS.ordinal(), ipAddress, true, null, null, null);
}
return (!deviceListForImei.isEmpty()) || (!deviceListForIp.isEmpty());
}
Mock
#Before
public void setUp() throws Exception
{
MockitoAnnotations.initMocks(this);
user = new UserInfo("user1", "sha1:64000:18:VFNOK/vZ3W8Zd9/xDQKUBNlccvpmydbu:rlemV/kvTi/FNZpEA/9jf+Wh", "User 1", "User 1",
"User 1",0, true,false, new Date(), false, null, false, false);
roles = new ArrayList<>();
roles.add(new Role("ADMIN","ADMIN"));
deviceListForImei = new ArrayList<>();
deviceListForIp = new ArrayList<>();
BlacklistDevice blacklistDevice = new BlacklistDevice(1, "Blacklist", PropertiesUtil.BlacklistType.IP_ADDRESS.ordinal(), "192.168.1.100", "admin", new Date(), true);
deviceListForIp.add(blacklistDevice);
}
/**
* Test method for
* {#link com.stengg.stee.auth.service.impl.AccessControlServiceImpl#isAuthorizedUser(java.lang.String, java.lang.String, java.lang.Integer, java.lang.String, javax.servlet.http.HttpServletRequest)}.
*/
#Test
public void testIsAuthorizedUser_normalLogin()
{
MockHttpServletRequest request = new MockHttpServletRequest();
String username = "user1";
String password = "password";
Integer loginType = PropertiesUtil.LoginType.IPAC2.ordinal();
String imei = "";
when(userInfoDAO.findById(anyString())).thenReturn(user);
when(userRoleDAO.getRoleBy(any(UserInfo.class))).thenReturn(roles);
when(blacklistDeviceService.getBlacklistDeviceForSearch(anyInt(), anyString(), anyBoolean(), anyInt(), anyInt(), anyString())).thenReturn(Collections.EMPTY_LIST);
doNothing().when(accessControlTransNewService).transNewAddLoginLog(anyString(), anyString(), anyString(), anyString(), any(HttpServletRequest.class));
when(onlineUsers.getOnlineUser(anyString())).thenReturn(null);
when(blueForceTrackerStore.removeViewer(anyString())).thenReturn(false);
Map<String, String> result1 = accessControlService.isAuthorizedUser(username, password, loginType, imei, request);
//login success
assertNotNull(result1);
assertNotNull(result1.get("token"));
assertNotNull(result1.get("token").contains("Bearer "));
}
#Test(expected = ErrorException.class)
public void testIsAuthorizedUser_blackListUser()
{
MockHttpServletRequest request = new MockHttpServletRequest();
String username = "user1";
String password = "password";
Integer loginType = PropertiesUtil.LoginType.IPAC2.ordinal();
String imei = "";
when(userInfoDAO.findById(anyString())).thenReturn(user);
when(userRoleDAO.getRoleBy(any(UserInfo.class))).thenReturn(roles);
when(blacklistDeviceService.getBlacklistDeviceForSearch(
eq(PropertiesUtil.BlacklistType.IP_ADDRESS.ordinal()), eq(request.getRemoteAddr()), eq(true), eq(null), eq(null), eq(null)))
.thenReturn(deviceListForIp);
doNothing().when(accessControlTransNewService).transNewAddLoginLog(anyString(), anyString(), anyString(), anyString(), any(HttpServletRequest.class));
when(onlineUsers.getOnlineUser(anyString())).thenReturn(null);
when(blueForceTrackerStore.removeViewer(anyString())).thenReturn(false);
Map<String, String> result2 = accessControlService.isAuthorizedUser(username, password, loginType, imei, request);
assertNull(result2);
}
You may want to use another construct:
doReturn(deviceListForIp)
.when(blacklistDeviceService)
.getBlacklistDeviceForSearch(eq(PropertiesUtil.BlacklistType.IP_ADDRESS.ordinal()), eq(request.getRemoteAddr()), eq(true), eq(null), eq(null), eq(null))
An empty list is a sign of not properly mocked behaviour, its default.

Why do I get an IOException in sending an email with Gmail service?

In my android test application, after that i got the JSON file from the Google Developer Console, where i had set on the Gmail API, and that i have put it in the emulator, i get an IOException which says:
"com.google.api.client.googleapis.json.GoogleJsonResponseException:
403 Forbidden { "code" : 403, "errors" : [ {
"domain" : "usageLimits",
"message" : "Access Not Configured. Please use Google Developers Console to activate the API for your project.",
"reason" : "accessNotConfigured" } ], "message" : "Access Not Configured. Please use Google Developers Console to activate the API
for your project." }"
I think that I must use a GoogleClientSecrets object, but i haven't found its use.
Here the code:
public class MainActivity extends Activity
{
final String SCOPE = "oauth2:https://www.googleapis.com/auth/gmail.compose";
final String FILE_NAME = "TestEmail5.json";
private static final int REQUEST_RESOLVE_ERROR = 1001;
Button button;
OnClickListener sendListener = new OnClickListener()
{
#Override
public void onClick(View v)
{
new sendEmailTask().execute();
}
};
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button1);
button.setOnClickListener(sendListener);
}
public static MimeMessage createEmail(String to, String from, String subject, String bodyText) throws MessagingException
{
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
MimeMessage email = new MimeMessage(session);
InternetAddress tAddress = new InternetAddress(to);
InternetAddress fAddress = new InternetAddress(from);
email.setFrom(new InternetAddress(from));
email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
email.setSubject(subject);
email.setText(bodyText);
return email;
}
public static void sendMessage(Gmail service, String userId, MimeMessage email) throws MessagingException, IOException
{
Message message = createMessageWithEmail(email);
message = service.users().messages().send(userId, message).execute();
System.out.println("Message id: " + message.getId());
System.out.println(message.toPrettyString());
}
public static Message createMessageWithEmail(MimeMessage email) throws MessagingException, IOException
{
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
email.writeTo(bytes);
String encodedEmail = Base64.encodeBase64URLSafeString(bytes.toByteArray());
Message message = new Message();
message.setRaw(encodedEmail);
return message;
}
public class sendEmailTask extends AsyncTask
{
#Override
protected Object doInBackground(Object... params)
{
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
String token = "";
AccountManager accountManager = AccountManager.get(MainActivity.this);
Account account[] = accountManager.getAccountsByType("com.google");
String accountName = account[0].name;
try
{
//GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(jsonFactory, new java.io.FileReader(Environment.getExternalStorageDirectory().getAbsolutePath() + "//" + "JSON/" + FILE_NAME));
token = GoogleAuthUtil.getToken(MainActivity.this, accountName, SCOPE);
GoogleCredential credential = new GoogleCredential().setAccessToken(token);
Gmail service = new Gmail.Builder(httpTransport, jsonFactory, credential).setApplicationName("TestEmail5").build();
MimeMessage mm = createEmail("myemail", "myemail", "soggetto", "oggetto");
sendMessage(service, "myemail", mm);
}
catch (UserRecoverableAuthException e)
{
startActivityForResult(e.getIntent(), REQUEST_RESOLVE_ERROR);
}
catch (IOException e)
{
e.printStackTrace();
}
catch (GoogleAuthException e)
{
e.printStackTrace();
}
catch (MessagingException e)
{
e.printStackTrace();
}
return null;
}
};
}
You need to login to http://console.developers.google.com/ and create a project and activate the "Gmail" API for it.
Documented more at:
https://developers.google.com/gmail/api/quickstart/quickstart-java#step_1_enable_the_gmail_api

Resources