I am new in apache camel. And I wanna do some simple task using apache camel. I have json data available on this url http://localhost:8080/users/. There are json data from my rest service. But I wanna get this json data and unmarshal it to POJO using apache camel and write some data to txt file. But my app starts and then doesnt't stop.
Here is my JSON data available on http://localhost:8080/users/
[{"id":1,"login":"admin","password":"admin","passwordAgain":null,"email":"admin#admin.com","firstName":"Admin","lastName":"Adminovich","birthday":"2010-10-10","role":{"id":1,"name":"admin"}},
{"id":5,"login":"Snow123","password":"1111","passwordAgain":null,"email":"john#snow.com","firstName":"John","lastName":"Snow","birthday":"2010-10-10","role":{"id":2,"name":"user"}}]
spring.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:camel="http://camel.apache.org/schema/spring"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<bean id="MyRouteBuilder" class="MyRouteBuilder" init-method="restart">
</bean>
<camelContext xmlns="http://camel.apache.org/schema/spring">
<routeBuilder ref="MyRouteBuilder"/>
</camelContext>
</beans>
MyRouteBuilder
import Mapping.User;
import Mapping.Users;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;
import org.apache.camel.component.restlet.RestletConstants;
import org.apache.camel.model.dataformat.JsonLibrary;
import org.restlet.Response;
import org.restlet.data.MediaType;
import org.restlet.data.Status;
public class MyRouteBuilder extends RouteBuilder {
private String routePort = null;
private String routeAnswer = null;
public void restart() {
String start = "Route Property Placeholder Example started on port" + " 8080" + "!";
System.out.println(start);
}
public void configure() throws Exception {
from("timer:foo?repeatCount=1").to("http://10.10.34.145:8080/users/").unmarshal().json(JsonLibrary.Jackson, Users.class ).log("STARTED!")
.process(new Processor() {
public void process (Exchange exchange) throws Exception {
Users usersList = exchange.getIn().getBody(Users.class);
exchange.getIn().setBody(usersList.usersList);
System.out.println(usersList.usersList.size());
}
}).to("file:///home/name/username/Desktop/camel.txt").stop();
}
}
User
package Mapping;
import com.google.gson.FieldNamingStrategy;
import java.lang.reflect.Field;
public class User {
public User() {
}
private int id;
private String login;
private String password;
private String passwordAgain;
private String email;
private String firstName;
private String lastName;
private String birthday;
public void setId(int id) {
this.id = id;
}
public void setLogin(String login) {
this.login = login;
}
public void setPassword(String password) {
this.password = password;
}
public void setPasswordAgain(String passwordAgain) {
this.passwordAgain = passwordAgain;
}
public void setEmail(String email) {
this.email = email;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public void setRole(String role) {
this.role = role;
}
public int getId() {
return id;
}
public String getLogin() {
return login;
}
public String getPassword() {
return password;
}
public String getPasswordAgain() {
return passwordAgain;
}
public String getEmail() {
return email;
}
public String getFirsteName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getBirthday() {
return birthday;
}
public String getRole() {
return role;
}
private String role;
}
Users
package Mapping;
import java.util.ArrayList;
import java.util.List;
public class Users {
public List<User> usersList = new ArrayList<User>();
}
Main
import org.apache.camel.main.Main;
public class MainClass {
public static void main(String[] args) {
Main main = new Main();
main.enableHangupSupport();
MyRouteBuilder rb = new MyRouteBuilder();
main.addRouteBuilder(rb);
try {
main.run(args);
} catch (Exception e) {
e.printStackTrace();
}
}
}
In my case I converted JsonData to Java object and created a custom CSV file using following dependencies.
jackson-mapper-asl
jackson-core-asl
You can create simple text file or CSV whatever it is.
This is my route:
from("couchdb:http://localhost:5984/order")
.startupOrder(1)
.process(new JsonToCsvProcessor())
.to("file:/home/r2/Desktop/ofBizFile?fileExist=append&fileName=orders-${date:now:dd-MM-yyyy}.csv");
This is my Processor where I am passing JsonString to ObjectMapper for Pojo:
{
public void process(Exchange exchange)throws Exception{
String jsonString = exchange.getIn().getBody(String.class);
exchange.getOut().setBody(convertJsonToCSV(jsonString).toString());
}
public StringBuilder convertJsonToCSV(String jsonStringArgs){
StringBuilder csvFile = new StringBuilder();
//Here customize data format using append()
.
.
return csvFile;
}
}
If you don't know how to use ObjectMapper this link will help you out.
https://www.youtube.com/watch?v=02X6U81MdJ0&t=1s
Use one of the amounts in json's case: Jackson or Gson
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-jackson</artifactId>
<version>${camel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-gson</artifactId>
<version>${camel.version}</version>
</dependency>
I recommend checking the documentation
you can do the unmarshal direct on the route:
unmarshal().json(JsonLibrary.Jackson, MyModel.class)
or you can create a processor:
#Component
public class MyModelUnMarshalProccessor implements Processor {
#Override
public void process(Exchange exchange) throws Exception {
MyModel model = exchange.getIn().getBody(MyModel.class);
exchange.getOut().setBody(model);
exchange.getOut().setHeader("id", body.getId());
}
}
#Autowired
MyModelUnMarshalProccessor myModelUnMarshalProccessor;
from("{{fromServices}}")
.log("${body}")
.process(myModelMarshalProccessor)
good luck
Related
I want retrieve user email from MySql database table using spring boot.i used findByEmailAndPassword in controller but it retrieve null value for email.
Here is my Code
controller
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.example.demo.JPARepository;
import com.example.demo.pojo.regisbean;
#Controller
public class registerController {
regisbean pp;
#RequestMapping(value = "/")
public String mm() {
System.out.println("I am in m1 method");
return "index";
}
#RequestMapping(value = { "/register", "home" })
public String m1() {
System.out.println("I am in mm method");
return "register";
}
#Autowired
JPARepository jpaRepository;
#PostMapping("/register")
public String regis(#ModelAttribute regisbean rb)
{
System.out.println("I m in regis method");
regisbean b=jpaRepository.save(rb);
if(b!=null)
return "index";
else
return "fail";
}
#RequestMapping(value= {"/login1","login2"})
public String m2() {
System.out.println("i m in m2()");
return "login";
}
#PostMapping("/login")
public String login(#ModelAttribute regisbean rx,Model m) {
System.out.println("I am in Login");
regisbean re=jpaRepository.findByEmailAndPassword(rx.getEmail(), rx.getPassword());
if(re!=null)
{
m.addAttribute("email",rx.getEmail());
m.addAttribute("password",rx.getPassword());
System.out.println("yes");
return "loginsuccess";
}
else
{
System.out.println(rx.getEmail());
System.out.println("failed");
return "register";
}
}
}
pojo class
package com.example.demo.pojo;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "pro")
public class regisbean {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column
private String name;
#Column
private String email;
#Column
private String phonenumber;
#Column
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhonenumber() {
return phonenumber;
}
public void setPhonenumber(String phonenumber) {
this.phonenumber = phonenumber;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Repository
package com.example.demo;
import org.springframework.data.repository.CrudRepository;
import com.example.demo.pojo.regisbean;
public interface JPARepository extends CrudRepository<regisbean, Integer> {
public regisbean findByEmailAndPassword(String email,String password);
}
I was able to get your code to work by inserting a row in the table:
INSERT INTO pro (
id
,email
,name
,password
,phonenumber
)
VALUES (
0
,'user#domain.com'
,'Jim'
,'secret'
,'123-123-1234'
)
Then changing:
public String login(#ModelAttribute regisbean rx,Model m) {
to:
public String login(#RequestBody RegisBean rx,Model m) {
and POSTing the following request body to the /login resource:
{
"email": "user#domain.com",
"password": "secret"
}
I didn't have to make any changes to your Repo. I suspect your attempt was failing because RegisBean was never being initialized with any values and so the repo was asked to find a record with a null email and a null password.
I am new to spring boot, and I'm trying spring boot security on my sample application and i'm using MongoDB.
I'm facing some issue. I'm using POSTMAN to test the web services that I developed.
I am not able to hit login method using POSTMAN.
Here is my main application
import org.joda.time.DateTime;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
#SpringBootApplication
public class WebApplication {
public static void main(String[] args) {
SpringApplication.run(WebApplication.class, args);
}
#Bean
CommandLineRunner init(final UserRepository userRepository, final UserRoleRepository userRoleRepository) {
return new CommandLineRunner() {
#Override
public void run(String... arg0) throws Exception {
UserRole usRole = new UserRole();
usRole.setUroName("Admin");
usRole.setUroCode("admin");
usRole.setUroType("admin");
usRole.setUroCreatedDttm(new DateTime().toString());
userRoleRepository.save(usRole);
UserTbl userTbl = new UserTbl();
userTbl.setEmail("ganeshsagar58#gmail.com");
userTbl.setUsrPassword("c0b137fe2d792459f26ff763cce44574a5b5ab03");
userTbl.setFirstName("Ganesh");
userTbl.setLastName("Bhagavath");
UserRole userRole = userRoleRepository.findByUroName("Admin");
userTbl.setUro(userRole);
userRepository.save(userTbl);
}
};
}
}
Here is the UserTbl POJO
import java.math.BigInteger;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.joda.time.DateTime;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
#Document
public class UserTbl
{
#Id
private BigInteger id;
#DBRef
private UserRole uro;
#NotNull
#Size(min=2, max =30)
private String firstName;
#NotNull
#Size(min=2, max =30)
private String lastName;
#NotNull
#Email
private String email;
#NotNull
private String usrPassword;
private DateTime usrCreatedDttm;
private DateTime usrModifiedDttm;
public BigInteger getId() {
return id;
}
public void setId(BigInteger id) {
this.id = id;
}
public UserRole getUro() {
return uro;
}
public void setUro(UserRole uro) {
this.uro = uro;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUsrPassword() {
return usrPassword;
}
public void setUsrPassword(String usrPassword) {
this.usrPassword = usrPassword;
}
public DateTime getUsrCreatedDttm() {
return usrCreatedDttm;
}
public void setUsrCreatedDttm(DateTime usrCreatedDttm) {
this.usrCreatedDttm = usrCreatedDttm;
}
public DateTime getUsrModifiedDttm() {
return usrModifiedDttm;
}
public void setUsrModifiedDttm(DateTime usrModifiedDttm) {
this.usrModifiedDttm = usrModifiedDttm;
}
}
Here is the UserRole POJO
import java.math.BigInteger;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document
public class UserRole
{
#Id
private BigInteger id;
private String uroName;
private String uroCode;
private String uroType;
private String uroCreatedDttm;
private String uroModifiedDttm;
public BigInteger getId() {
return id;
}
public void setId(BigInteger id) {
this.id = id;
}
public String getUroName() {
return uroName;
}
public void setUroName(String uroName) {
this.uroName = uroName;
}
public String getUroCode() {
return uroCode;
}
public void setUroCode(String uroCode) {
this.uroCode = uroCode;
}
public String getUroType() {
return uroType;
}
public void setUroType(String uroType) {
this.uroType = uroType;
}
public String getUroCreatedDttm() {
return uroCreatedDttm;
}
public void setUroCreatedDttm(String uroCreatedDttm) {
this.uroCreatedDttm = uroCreatedDttm;
}
public String getUroModifiedDttm() {
return uroModifiedDttm;
}
public void setUroModifiedDttm(String uroModifiedDttm) {
this.uroModifiedDttm = uroModifiedDttm;
}
}
Here is my Websecurity class
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{
private UserRepository userRepository;
private BCryptPasswordEncoder bCryptPasswordEncoder;
private UserRoleRepository userRoleRepository;
#Autowired
public void setUserRoleRepository(UserRoleRepository userRoleRepository)
{
this.userRoleRepository = userRoleRepository;
}
#Autowired
public void setUserRepository(UserRepository userRepository)
{
this.userRepository = userRepository;
}
#Autowired
public void setbCryptPasswordEncoder(BCryptPasswordEncoder bCryptPasswordEncoder)
{
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}
#Bean
public BCryptPasswordEncoder passwordEncoder(){
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
return bCryptPasswordEncoder;
}
#Bean
protected
UserDetailsService userDetailsService() {
return new UserDetailsService() {
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserTbl user = userRepository.findUserByEmail(username);
if (user != null) {
return new User(user.getEmail(), user.getUsrPassword(), true, true, true, true,
AuthorityUtils.createAuthorityList(userRoleRepository.findByUroName("Admin").getUroName()));
} else {
throw new UsernameNotFoundException("could not find the user '"
+ username + "'");
}
}
};
}
public void init(AuthenticationManagerBuilder auth) throws Exception
{
auth.userDetailsService(userDetailsService()).passwordEncoder(bCryptPasswordEncoder);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**", "/posts/**", "/users/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
}
When i hit localhost:8080/login in POSTMAN with POST method (username and password as mentioned in UserTbl), it says
{
"timestamp": "2018-03-31T16:18:40.791+0000",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/login"
}
My application.properties file
spring.data.mongodb.database=web_application
Please check once if you have defined different context explicitly in your application.properties file.
Spring Boot 1.X
server.contextPath=/yourAppContext
server.port=8080
Spring Boot 2.0
server.servlet.contextPath=/yourAppContext
If so, you would need to add context path to your request URL,
like ,
localhost:8080/yourAppContext/login
i am trying to implement basic authentication to somehow secure my rest api.To test, i tried below code to filter the url parameter that contains users however it is not aborting the request without authorization. and the most important is i need to implement it in the way that only update and delete needs to be authorized with the respective username and password. other things i just don't want to filter. i have an user class having username and password (encrypted) properties. so if the url contains PUT or delete method on users/{userID} i want it to verify with the username and password of that specific users. i have listed code of model , resources and filter class below.. i really need your help. thanks in advance.
filter class.
package Authentication;
import java.io.IOException;
import java.util.List;
import java.util.StringTokenizer;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
import org.glassfish.jersey.internal.util.Base64;
#Provider
public class SecureFilter implements ContainerRequestFilter {
private static final String Auth_Header = "Authorization";
private static final String Auth_Header_Prefix = "Basic ";
#Override
public void filter(ContainerRequestContext requestContext) throws IOException {
if (requestContext.getUriInfo().getPath().contains("users")) {
List<String> authHeader = requestContext.getHeaders().get(Auth_Header);
if (authHeader != null && authHeader.size() > 0) {
String authToken = authHeader.get(0);
authToken = authToken.replaceFirst(Auth_Header_Prefix, "");
String decodedString = Base64.decodeAsString(authToken);
StringTokenizer tokenizer = new StringTokenizer(decodedString, ":");
String userName = tokenizer.nextToken();
String password = tokenizer.nextToken();
if ("user".equals(userName) && "password".equals(password)) {
return;
}
Response unauthorizedstatus = Response
.status(Response.Status.UNAUTHORIZED)
.entity("these resources needs authorization. ")
.build();
requestContext.abortWith(unauthorizedstatus);
}
}
}
}
resource class:
import com.mycompany.samplehospital.model.Alert;
import com.mycompany.samplehospital.model.Message;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import com.mycompany.samplehospital.model.User;
import com.mycompany.samplehospital.Services.UserServices;
import com.mycompany.samplehospital.exception.objectNotFound;
import com.mycompany.samplehospital.Services.AlertServices;
import com.mycompany.samplehospital.Services.MessageServices;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
/**
*
* #author sandesh poudel
*/
#Produces(MediaType.APPLICATION_XML)
#Path("/users")
public class userResources {
UserServices service ;
public userResources() throws Exception{
service = new UserServices();
}
#GET
#Produces(MediaType.APPLICATION_XML)
public List<User> getAllUser(){
return UserServices.getUsers();
}
#Path("/{userId}")
#GET
#Produces(MediaType.APPLICATION_XML)
public User getUser(#PathParam("userId") int ID ) throws Exception{
User myUserList = service.getUser(ID);
if (myUserList == null){
throw new objectNotFound("User not Found");
}else {
return myUserList;
}
}
#POST
#Produces(MediaType.APPLICATION_XML)
#Consumes(MediaType.APPLICATION_XML)
public User addUser(User user ) throws Exception{
return service.AddUser(user);
}
}
#PUT
#Path("/{userId}")
#Produces(MediaType.APPLICATION_XML)
#Consumes(MediaType.APPLICATION_XML)
public User updtaeUser(User user) throws Exception{
return service.updateUser(user);
}
#DELETE
#Path("/{userId}")
#Produces(MediaType.APPLICATION_XML)
public User delUser(#PathParam("userId") int ID) throws Exception{
return service.removeUser(ID);
}
#Path("/{userId}/messages")
#GET
#Produces(MediaType.APPLICATION_XML)
public List<Message> getAllMessageByUser(#PathParam("userId") int ID) throws Exception{
MessageServices mservice = new MessageServices();
List<Message> messageUserList = mservice.getAllMessageByUser(ID);
if (messageUserList == null ){
throw new objectNotFound("messages not Found");
} return messageUserList;
}
#GET
#Produces(MediaType.APPLICATION_XML)
#Path("/{userId}/alerts")
public List<Alert> AlertsResources(#PathParam("userId") int userId){
AlertServices myAlert = new AlertServices();
List<Alert> newAlertUserList = myAlert.getAllAlertByUser(userId) ;
if (newAlertUserList == null){
throw new objectNotFound("messages not Found");
} return newAlertUserList;
}
Model class User
package com.mycompany.samplehospital.model;
import java.io.Serializable;
import java.util.Map;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import Authentication.HashPassword;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author sandeshpoudel
*/
#XmlRootElement
public class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String title;
private int age;
private String Sex;
private String Address;
private int phoneNo;
private String fullName;
private int id;
private Map<Integer, Message> allMessage;
private Map<Integer,Alert> allAlerts;
private String userName;
private String passWord;
private HashPassword hs ;
public User() {
}
public User(int id,String fullName, String Sex, Integer age, Integer phoneNumber, String Address, String title,String userName,String password) throws Exception {
hs = new HashPassword();
this.id= id;
this.fullName = fullName;
this.title = title;
this.age = age;
this.Sex = Sex;
this.Address = Address;
this.phoneNo = phoneNumber;
setPassWord(password);
// setPassWord(passWord) uncomment this and remove next line to execute on encryption mode;
this.userName= userName;
}
public void setId(int id){
this.id= id;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public void setTitle(String title) {
this.title = title;
}
public void setAge(int age) {
this.age = age;
}
public void setSex(String Sex) {
this.Sex = Sex;
}
public void setAddress(String Address) {
this.Address = Address;
}
public void setPhoneNo(int phoneNo) {
this.phoneNo = phoneNo;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
#XmlElement
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) throws Exception {
hs = new HashPassword();
this.passWord = hs.encrypt(passWord);
// this.passWord = passWord;
}
#XmlElement
public String getFullName() {
return fullName;
}
/*
*/
#XmlElement
public int getId(){
return id;
}
#XmlElement
public String getTitle() {
return title;
}
#XmlElement
public int getAge() {
return age;
}
#XmlElement
public String getSex() {
return Sex;
}
#XmlElement
public String getAddress() {
return Address;
}
#XmlElement
public int getPhoneNo() {
return phoneNo;
}
#XmlTransient
public Map<Integer, Message> getAllMessage() {
return allMessage;
}
public void setAllMessage(Map<Integer, Message> allMessage) {
this.allMessage = allMessage;
} #XmlTransient
public Map<Integer, Alert> getAllAlerts() {
return allAlerts;
}
public void setAllAlerts(Map<Integer, Alert> allAlerts) {
this.allAlerts = allAlerts;
}
#Override
public String toString(){
return (getSex() +" "+ getAddress()+" "+ getPhoneNo() +" "+ getFullName());
}
}
Basic authentication is part of the servlet specification. So if you run in a servlet container, which is the case, you can just enable basic authentication in the web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<security-constraint>
<web-resource-collection>
<web-resource-name>all-content</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>user</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>foo-realm</realm-name>
</login-config>
<security-role>
<role-name>user</role-name>
</security-role>
</web-app>
You must also configure the realm, and the roles, this depend on your servlet container implementation.
If you are running you app in a Java EE Container you can use standard web security defined in web.xml
https://docs.oracle.com/javaee/7/tutorial/security-webtier002.htm#GKBAA
Or if you use Spring
https://spring.io/guides/gs/securing-web/
In a sample jax rs api, I implemented basic authentication by getting the HttpServletRequest in my rest resource.
I created a doAuthorize() method which extract the Authentication header, decode and validate authentication as you have done.
Then I call doAuthorize() in the resource path methods which need it.
I read the link below but I couldn't send mail with OAuth2 authentication mechanism. Can anyone give me an example about this ?
Without this authentication user have to enable less secure apps option from the gmail's security settings. But I don't want to push user to do that. That's why I need this authentication mechanism.
link: https://java.net/projects/javamail/pages/OAuth2
Given below is the working code how to send emails using OAuth2 in a web project using Spring.
Important :
First create project at Google console, after that when creating credentials at Google console remember to set
application type to other.
Use oauth2.py get access token and other required values needed for the
code. File itself has instructions on how to use it, to get required values.
spring-email.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- email configuration -->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.gmail.com"/>
<property name="port" value="587"/>
<property name="username" value="xxxxxxxxxxxxx#gmail.com"/>
<property name="password" value=""/>
<property name="javaMailProperties">
<props>
<!-- Use SMTP transport protocol -->
<prop key="mail.transport.protocol">smtp</prop>
<!-- Use SMTP-AUTH to authenticate to SMTP server -->
<prop key="mail.smtp.auth">true</prop>
<!-- GMail requires OAuth to not be considered "low-security" -->
<prop key="mail.smtp.auth.mechanisms">XOAUTH2</prop>
<!-- Use TLS to encrypt communication with SMTP server -->
<prop key="mail.smtp.starttls.enable">true</prop>
<prop key="mail.debug">false</prop>
</props>
</property>
</bean>
<bean id="message" class="com.upriverbank.model.Message">
<property name="mailSender" ref="mailSender" />
</bean>
</beans>
OAuthMail.java
package com.abc.security;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.mail.javamail.JavaMailSender;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
public class OAuthMail {
// For using Oauth2
private static String TOKEN_URL = "https://www.googleapis.com/oauth2/v4/token";
private JavaMailSender sender;
// Not a best practice to store client id, secret and token in source
// must be stored in a file.
private String oauthClientId = "xxxxxxxxxxxxxxxx.apps.googleusercontent.com";
private String oauthSecret = "xxxxxxxxxxxxxxxxxxxx";
private String refreshToken = "xxxxxxxxxxxxxxxxxxxxxxx";
private static String accessToken = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" +
"xxxxxxxxxxxxxxxxxxxx";
private long tokenExpires = 1458168133864L;
// getters and setters
public static String getAccessToken() {
return accessToken;
}
public static void setAccessToken(String accessToken) {
accessToken = accessToken;
}
/*
Renew access token if expired
*/
public void renewToken(){
if(System.currentTimeMillis() > tokenExpires) {
try
{
String request = "client_id="+ URLEncoder.encode(oauthClientId, "UTF-8")
+"&client_secret="+URLEncoder.encode(oauthSecret, "UTF-8")
+"&refresh_token="+URLEncoder.encode(refreshToken, "UTF-8")
+"&grant_type=refresh_token";
HttpURLConnection conn = (HttpURLConnection) new URL(TOKEN_URL).openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
PrintWriter out = new PrintWriter(conn.getOutputStream());
out.print(request);
out.flush();
out.close();
conn.connect();
try
{
HashMap<String,Object> result;
result = new ObjectMapper().readValue(conn.getInputStream(), new TypeReference<HashMap<String,Object>>() {});
accessToken = (String) result.get("access_token");
tokenExpires = System.currentTimeMillis()+(((Number)result.get("expires_in")).intValue()*1000);
}
catch (IOException e)
{
String line;
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
while((line = in.readLine()) != null) {
System.out.println(line);
}
System.out.flush();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
Message.java
package com.abc.model;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.upriverbank.security.OAuthMail;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Properties;
public class Message {
public static final String PORT = "465";
private static final String HOST = "smtp.gmail.com";
private final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
private String name;
private String customerID;
private String email;
private int queryType;
private int id;
private String title;
private String rStatus;
private String query;
private Byte isRead;
private int customerId;
private String password;
private static final String BANK_SUPPORT_EMAIL = "xxxxxxx#gmail.com";
public static String getBankSupportEmail() {
return BANK_SUPPORT_EMAIL;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getrStatus() {
return rStatus;
}
public void setrStatus(String rStatus) {
this.rStatus = rStatus;
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
public Byte getIsRead() {
return isRead;
}
public void setIsRead(Byte isRead) {
this.isRead = isRead;
}
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCustomerID() {
return customerID;
}
public void setCustomerID(String customerID) {
this.customerID = customerID;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getQueryType() {
return queryType;
}
public void setQueryType(int queryType) {
this.queryType = queryType;
}
public void viewMessage() {
}
public void setPassword(String password) {
this.password = password;
}
private MailSender mailSender;
public void setMailSender(MailSender mailSender) {
this.mailSender = mailSender;
}
/*
Sending an email according to provided parameters
(sender, receiver, subject, content)
*/
public void sendMessage(String from, String to, String subject, String msg) {
((JavaMailSenderImpl)this.mailSender).setPassword(OAuthMail.getAccessToken());
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(msg);
// sending email
mailSender.send(message);
}
}
MessageTest.java
package com.abc.model;
import com.abc.support.spring.SpringUtil;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
class MessageTest {
#Test
void sendMessage() {
Message mm = (Message) SpringUtil.customBeanFactory("message");
mm.sendMessage("xxxxxxx#gmail.com",
"xxxxxxxxx#gmail.com",
"Testing email",
"This is a testing email");
}
}
I'm developing a project using GAE. I'm writing an integration test with Junit which don't save the entity. I have included the JARs in classpath and I copy here the entity class, the test class and the persistence.xml file.
Persistence.xml
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
<persistence-unit name="transactions-optional">
<provider>org.datanucleus.api.jpa.PersistenceProviderImpl</provider>
<properties>
<property name="datanucleus.NontransactionalRead" value="true"/>
<property name="datanucleus.NontransactionalWrite" value="true"/>
<property name="datanucleus.ConnectionURL" value="appengine"/>
</properties>
</persistence-unit>
</persistence>
Utente.java
package it.bfm.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import com.google.appengine.api.datastore.Key;
#Entity
public class Utente {
#Id
#GeneratedValue (strategy = GenerationType.IDENTITY)
private Key key;
private String nome;
private String cognome;
private String username;
private String password;
private String email;
public Utente(String nome, String cognome, String user, String password,
String email){
this.nome = nome;
this.cognome = cognome;
this.username = user;
this.password = password;
this.email = email;
}
public Key getKey(){
return this.key;
}
public void setNome(String nome){
this.nome = nome;
}
public String getNome(){
return this.nome;
}
public void setCognome(String cognome){
this.cognome = cognome;
}
public String getCognome(){
return this.cognome;
}
public void setUser(String username){
this.username = username;
}
public String getUsername(){
return this.username;
}
public void setPassword(String password){
this.password = password;
}
public String getPasswrd(){
return this.password;
}
public void setEmail(String email){
this.email = email;
}
public String getEmail(){
return this.email;
}
}
UtenteTest.java
package it.bfm.test;
import it.bfm.business.UtenteImpl;
import it.bfm.business.UtenteInterface;
import it.bfm.entity.Utente;
import java.util.List;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import junit.framework.TestCase;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
public class UtenteTest extends TestCase{
private final static LocalServiceTestHelper helper =
new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
private static UtenteInterface utImpl = new UtenteImpl();
#BeforeClass
public static void setUpUtenti() {
utImpl.creaUtente("Utente1", "Test1", "test1", "test1", "test1#test.it");
utImpl.creaUtente("Utente2", "Test2", "test2", "test2", "test2#test.it");
utImpl.creaUtente("Utente3", "Test3", "test3", "test3", "test3#test.it");
}
#Before
public void setUp(){
helper.setUp();
}
#After
public void tearDown() {
helper.tearDown();
}
#Test
public void testCreaUtente() {
utImpl.creaUtente("Utente4", "Test4", "test4", "test4", "test4#test.it");
}
#Test
public void testListaUtenti() {
List<Utente> utenti = null;
utenti = utImpl.listaUtenti();
Assert.assertEquals(4, utenti.size());
}
#Test
public void testCercaUtenteByEmail() {
Utente utente;
String emailTest = "test1#test.it";
String nomeTest = "Utente1";
String cognomeTest = "Test1";
utente = utImpl.cercaUtenteByEmail(emailTest);
Assert.assertEquals(utente.getNome(), nomeTest);
Assert.assertEquals(utente.getCognome(), cognomeTest);
}
#Test
public void testLogin() {
Utente utente;
String usernameTest = "test1";
String passTest = "test1";
String nomeTest = "Utente1";
String cognomeTest = "Test1";
utente = utImpl.login(usernameTest, passTest);
Assert.assertEquals(utente.getNome(), nomeTest);
Assert.assertEquals(utente.getCognome(), cognomeTest);
}
}
The problem is that the methods setUpUtenti ad testCreaUtente don't persist the entities.
The test testListaUtenti fails because the Utenti numbers was expected 4 but is 0.
Every #Test annotated method is invoked on a freshly created instance of class. So basically you can not persist between methods. You should put this code into one method.