how to make push notification in spring mvc and hibernate - java

i have small web application in spring mvc and hibernate.
in this web service via push notification to database into data is automatically push into android device.
how to do push notification?
restful controller
#Controller
#RequestMapping("/json")
public class JsonData
{
#Autowired
private AdminService adminService;
#GET
#RequestMapping(value="/jsonEnglishWord")
#Produces(MediaType.APPLICATION_JSON)
public #ResponseBody List<English_Word> getAllWord() {
return new ArrayList<English_Word>(adminService.getAllWord());
}
#GET
#RequestMapping(value="/jsonGujaratiWord")
#Produces(MediaType.APPLICATION_JSON)
public #ResponseBody List<Gujarati_Word> getallGujarati_Words(){
return new ArrayList<Gujarati_Word>(adminService.getAllGujaratiword());
}
database model
#Entity
#Table(name="English_Word")
public class English_Word {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int word_id;
private String word_name;
#Lob
private String word_explain;
#Temporal(TemporalType.DATE)
private Date word_date;
public int getWord_id() {
return word_id;
}
public void setWord_id(int word_id) {
this.word_id = word_id;
}
public String getWord_name() {
return word_name;
}
public void setWord_name(String word_name) {
this.word_name = word_name;
}
public String getWord_explain() {
return word_explain;
}
public void setWord_explain(String word_explain) {
this.word_explain = word_explain;
}
public Date getWord_date() {
return word_date;
}
public void setWord_date(Date word_date) {
this.word_date = word_date;
}
}

Please refer following link. It helps me. check for java code. first create app on google
http://javapapers.com/android/google-cloud-messaging-gcm-for-android-and-push-notifications/

Related

MVC Post and Put mapping methods, response body values "null" but status 200 OK using Post Man

I'm trying to do an application using Spring Boot MVC and I've run into a problem. For the Post and Put methods I receive status 200 ok but the values are "null". The new registration on database is created but just the Id (autoincrement) column is populated and received in Postman response. Could someone help me please?
` #RequestMapping("/api")
#RestController
public class ExtractedNumbersController {
private final ExtractedNumbersService extractedNumbersService;
#Autowired
public ExtractedNumbersController(ExtractedNumbersService extractedNumbersService) {
this.extractedNumbersService = extractedNumbersService;
}
#PostMapping("/addExtractedNumbers")
public ExtractedNumbers addExtractedNumbers(#RequestBody ExtractedNumbers extractedNumbers) {
return extractedNumbersService.addExtractedNumbers(extractedNumbers);
}
#GetMapping("/findAllExtractedNumbers")
public List<ExtractedNumbers> findAllActivities() {
return extractedNumbersService.findAllExtractedNumbers();
}
#GetMapping("findExtractedNumbersById/{id}")
public Optional<ExtractedNumbers> findExtractedNumbersById(#PathVariable("id") Integer id) {
return extractedNumbersService.findByIdExtractedNumbers(id);
}
#PutMapping("/updateExtractedNumbers/{id}")
public ExtractedNumbers updateProduct(#PathVariable("id") Integer id, #RequestBody ExtractedNumbers extractedNumbers) {
Optional<ExtractedNumbers> extractedNumbersFromDatabase = extractedNumbersService.findByIdExtractedNumbers(id);
if (extractedNumbersFromDatabase.isPresent()) {
extractedNumbersFromDatabase.get().setExtractedNumbers(extractedNumbers.getExtractedNumbers());
extractedNumbersFromDatabase.get().setExtractionDate(extractedNumbers.getExtractionDate());
final ExtractedNumbers updatedExtractedNumbers = extractedNumbersService.addExtractedNumbers(extractedNumbersFromDatabase.get());
return updatedExtractedNumbers;
}
return extractedNumbersService.addExtractedNumbers(extractedNumbers);
}
#DeleteMapping("/deleteExtractedNumbersById/{id}")
public void deleteExtractedNumbersById(#PathVariable("id") Integer id) {
extractedNumbersService.deleteExtractedNumbers(id);
}
}
#Data
#Table
#Entity
#AllArgsConstructor
#NoArgsConstructor
public class ExtractedNumbers {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer extractedNumbersId;
#Column
private String extractedNumbers;
#Column
private String extractionDate;
public ExtractedNumbers(String extractedNumbers, String extractionDate) {
this.extractedNumbers = extractedNumbers;
this.extractionDate = extractionDate;
}
public String getExtractedNumbers() {
return extractedNumbers;
}
public void setExtractedNumbers(String extractedNumbers) {
this.extractedNumbers = extractedNumbers;
}
public String getExtractionDate() {
return extractionDate;
}
public void setExtractionDate(String extractionDate) {
this.extractionDate = extractionDate;
}
}
public interface ExtractedNumbersService {
List<ExtractedNumbers> findAllExtractedNumbers();
ExtractedNumbers addExtractedNumbers(ExtractedNumbers extractedNumbers);
Optional<ExtractedNumbers> findByIdExtractedNumbers(Integer extractedNumbersId);
ExtractedNumbers update(ExtractedNumbers extractedNumbers);
void deleteExtractedNumbers(Integer extractedNumbersId);
}
#Service
public class ExtractedNumbersServiceImpl implements ExtractedNumbersService {
private final ExtractedNumbersRepository extractedNumbersRepository;
public ExtractedNumbersServiceImpl(ExtractedNumbersRepository extractedNumbersRepository) {
this.extractedNumbersRepository = extractedNumbersRepository;
}
#Override
public List<ExtractedNumbers> findAllExtractedNumbers() { return extractedNumbersRepository.findAll() ; }
#Override
public ExtractedNumbers addExtractedNumbers(ExtractedNumbers extractedNumbers) {
return extractedNumbersRepository.save(extractedNumbers);
}
#Override
public Optional<ExtractedNumbers> findByIdExtractedNumbers(Integer extractedNumbersId) {
return extractedNumbersRepository.findById(extractedNumbersId);
}
#Override
public ExtractedNumbers update(ExtractedNumbers extractedNumbers) {
return extractedNumbersRepository.save(extractedNumbers);
}
#Override
public void deleteExtractedNumbers(Integer extractedNumbersId) {
extractedNumbersRepository.deleteById(extractedNumbersId);
}
}`
[Database][1]
Postman
Extracted Numbers Class
Are your attributes in ExtractedNumbers consistent with the database table column?
if your table column is like extracted_numbers you need to do the underline to camel

Why am I getting null values on the server side after sending a post request by Postman

I have created a RESTful webservice using Spring boot to add a record to H2 database but when I send data from postman to my handler method I get null values on the server side and on the response sent to the client side as well, could anybody help me?
Eclipse Snapshot
Postman Snapshot
My Controller Code:
#RestController
public class AlienController {
#Autowired
AlienRepo repo;
#RequestMapping("/")
public String home() {
return"home.jsp";
}
#PostMapping(path="/alien")
public Alien addAlien(Alien alien) {
System.out.println(alien);
repo.save(alien);
return alien;
}
My DAO Class:
#Entity
public class Alien {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int aid;
private String aname;
private String lang;
public int getAid() {
return aid;
}
public void setAid(int aid) {
this.aid=aid;
}
public String getAname() {
return aname;
}
public void setAname(String aname) {
this.aname=aname;
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang=lang;
}
#Override
public String toString() {
return "Alien Info: Aid=" + aid + ", Aname=" + aname + ", Lang=" +lang;
}
}
My AlienRepository code:
public interface AlienRepo extends JpaRepository<Alien, Integer>{
}
You should use the annotation #RequestBody
public Alien addAlien(#RequestBody Alien alien)
You should inform Spring that you are waiting for a HttpRequest that contains a Body , Spring will automatically deserialize the inbound HttpRequest body onto Java object

Randomize result from Elasticsearch using NativeSearchQueryBuilder

Hi I am new ElasticSearch, I am using spring data. I have 2 API which saves data in article and discourse model using elastic search, now when a client app makes a API call for both article and discourse search it gives all article first and then discourse data. but i want to randomize the response how can i do that?
my article model class as follows
#AllArgsConstructor
#Data
#Document(indexName="articles", createIndex=true)
public class Article implements ITResult {
private String id;
private String hostContentId;
private String title;
private List<String> categories;
private String searchResultId;
#Override
public String getSummary() {
return excerpt;
}
#Override
public ContentType getContentType() {
return ContentType.ARTICLE;
}
#Override
public String getHostContentId() {
return hostContentId;
}
#Override
public String getUrl() {
return link;
}
#Override
public String getSearchResultId() {
return searchResultId;
}
public void setSearchResultId(String searchResultId) {
this.searchResultId = searchResultId;
}
}
I have done the following
SearchQuery query = new NativeSearchQueryBuilder().withIndices("articles","course")
.withPageable(new PageRequest(offset,limit))
.withFilter(multiMatchQuery(string, new String[] { "title", "excerpt", "author_name", "link"}))
.build();

Get data from a repository using Spring

Ok so I am new to spring and don't really know how this works. I have been trying a few things and think its close to doing it but not getting any data from the server and giving me this error
Unsatisfied dependency expressed through constructor argument with index 4 of type [jp.co.fusionsystems.dimare.crm.service.impl.MyDataDefaultService]: : Error creating bean with name 'MyDataDefaultService' defined in file
My end point
//mobile data endpoint
#RequestMapping(
value = API_PREFIX + ENDPOINT_MyData + "/getMyData",
method = RequestMethod.GET)
public MyData getMyData() {
return MyDataDefaultService.getData();
}
My Object
public class MyData {
public MyData(final Builder builder) {
videoLink = builder.videoLink;
}
private String videoLink;
public String getVideoLink()
{
return videoLink;
}
public static class Builder
{
private String videoLink = "";
public Builder setVideo(String videoLink)
{
this.videoLink = videoLink;
return this;
}
public MyData build()
{
return new MyData(this);
}
}
#Override
public boolean equals(final Object other) {
return ObjectUtils.equals(this, other);
}
#Override
public int hashCode() {
return ObjectUtils.hashCode(this);
}
#Override
public String toString() {
return ObjectUtils.toString(this);
}
}
The Repository
public classMyServerMyDataRepository implements MyDataRepository{
private finalMyServerMyDataJpaRepository jpaRepository;
private final MyDataConverter MyDataConverter = new MyDataConverter();
#Autowired
publicMyServerMyDataRepository(finalMyServerMyDataJpaRepository jpaRepository) {
this.jpaRepository = Validate.notNull(jpaRepository);
}
#Override
public MyData getData() {
MyDataEntity entity = jpaRepository.findOne((long) 0);
MyData.Builder builder = new MyData.Builder()
.setVideo(entity.getVideoLink());
return builder.build();
}
The DefaultService that gets called by the endpoint
public class MyDataDefaultService {
private static final Logger logger = LoggerFactory.getLogger(NotificationDefaultService.class);
private finalMyServerMyDataRepository repository;
#Autowired
public MyDataDefaultService(MyServerMyDataRepository repository) {
this.repository = Validate.notNull(repository);
}
//Get the data from the server
public MobileData getData()
{
logger.info("Get Mobile Data from the server");
//Get the data from the repository
MobileData mobileData = repository.getData();
return mobileData;
}
}
The Converter
public class MyDataConverter extends AbstractConverter<MyDataEntity, MyData>
{
#Override
public MyData convert(MyDataEntity entity) {
MyData.Builder builder = new MyData.Builder()
.setVideo(entity.getVideoLink());
return builder.build();
}
}
My Entity
#Entity
#Table(name = “myServer”)
public class MyDataEntity extends AbstractEntity{
#Column(name = "video_link", nullable = true)
private String videoLink;
public String getVideoLink() {
return videoLink;
}
public void setVideoLink(final String videoLink) {
this.videoLink = videoLink;
}
}
Thank you for any help with this
Hibernate entity should have default constructor defined and implement Serializable interface as well, assume AbstractEntity matches the requirement. Hibernate won't accept an entity without a primary key so you have to define the one too:
#Entity
#Table(name = “myServer”)
public class MyDataEntity implements Serializable {
#Id
#GeneratedValue
private Long id;
#Column(name = "video_link", nullable = true)
private String videoLink;
public MyDataEntity() {
}
...setters&getters
}
MyData object represents the JSON server response, you can use Jackson annotations to control the result JSON properties:
public class MyDataResponse {
#JsonProperty("video_link")
private String videoLink;
public MyDataResponse() {
}
public MyDataResponse(String videoLink) {
this.videoLink = videoLink;
}
...setters&getters
}
Spring has an awesome project so called Spring Data that provides the JPA repositories, so there's no even the #Repository annotation ever needed:
public class MyDataRepository extends CrudRepository<MyDataEntity, Long> {
}
The Builder class represents the Service layer:
#Service
public class MyDataService {
#Autowired
private MyDataRepository myDataRepository;
public MyDataResponse getMyData(Long id) {
MyDataEntity entity = myDataRepository.findOne(id);
...rest logic, copy necessary data to MyDataResponse
}
}
Then a controller is:
#RestController // #ResponseBody not needed when using like this
public MyDataController {
#Autowired
private MyDataService myDataService;
#RequestMapping("/getMyData") // no need to specify method for GET
public MyDataResponse getMyData(#RequestParam("ID") Long myDataId) {
... validation logic
return myDataService.getMyData(myDataId); // return response
}
}
Now it should work, don't forget to add required dependencies to your classpath.

Spring MVC passing data between controllers

I'm writing web application using SpringMVC. I would like to keep some data in session until user logout. Earlier I did it by #SessionAttributes("someData"), but then I had to put #ModelAttribute("someData") someDataType someData as argument for every request mapping method. So this is what I did :
My AccessData class :
#Component
#Scope(value = "session")
public class AccessData {
private long userID;
private String userKey;
public AccessData(long ID, String key) {
this.userID = ID;
this.userKey = key;
}
public long getUserID() {
return userID;
}
public void setUserID(long userID) {
this.userID = userID;
}
public String getUserKey() {
return userKey;
}
public void setUserKey(String userKey) {
this.userKey = userKey;
}
}
First controller(here I'm getting and validating user input from form) :
#Controller
#Scope(value = "session")
public class LoginController {
#ModelAttribute("accessData")
public AccessData getAccessData() {
return this.accessData;
}
private Utils utilsService;
private LoginService loginService;
#Autowired
private AccessData accessData;
#Autowired
public LoginController(LoginService loginService, Utils utils) {
this.loginService = loginService;
this.utilsService = utils;
}
#RequestMapping(value = ControllerPaths.LOGIN, method = RequestMethod.POST)
public ModelAndView showLoginStatus(
#ModelAttribute(LOGINDATA) LoginData loginData) {
try {
accessData = loginService.validateLoginData(loginData);
} catch (IncorrectLoginDataException e) {
logger.trace("Showing fail login screen...");
return utilsService.getShowView(ViewPaths.LOGIN_FAIL);
} catch (HTTPException e) {
return utilsService.getShowViewWithStringAttribute(
ViewPaths.INFO_VIEW, MESSAGE, CONNECTION_ERROR);
}
return utilsService.getShowView(ViewPaths.LOGIN_SUCCESS);
}
}
Second controller :
#Controller
#Scope(value = "session")
public class SecondController {
#ModelAttribute("accessData")
public AccessData getAccessData() {
return this.accessData;
}
private Utils utilsService;
private LoginService loginService;
#Autowired
private AccessData accessData;
#Autowired
public SecondController(LoginService loginService, Utils utils) {
this.loginService = loginService;
this.utilsService = utils;
}
#RequestMapping(value = ControllerPaths.SHOW_ACCESS_DATA, method = RequestMethod.GET)
public ModelAndView showAccessData(
System.out.println(accessData.getUserKey());
return utilsService.getShowView(ViewPaths.INDEX);
}
}
The problem is that when I'm printing userKey value in second controller, the value is null. I checked if I'm getting correct data from server in LoginController and it's ok. So what am I doing wrong? Thanks in advance for help
The problem is that you are assigning a new object to the accessData variable. Instead you should update the field of the object that it is already referring to.
accessData = loginService.validateLoginData(loginData);
// Replace above line with something like this. Implement the copyProperties
// method to copy the attributes you need
AccessData newAccessData = loginService.validateLoginData(loginData);
copyPropteries(accessData,newAccessData);
Also it is not required to make the Controllers session scoped, add proxyMode=TARGET_CLASS to the scope annotation of the AccessData class.

Categories

Resources