Trying to print JSON results from a webservice using hibernate and Spring - java

I have two projects defined 1) GeneralOrm which is used for general purpose web services and 2)CompanyWS which includes company specific webservices.
I am using Spring and Hibernate 4 version
I am writing a GET request to pull information based on two parameters namely, employeeID and informationID. There can only be one employeeID and multiple
informationID. Based on a employeeID and Information ID, I want to display the employeeID, INFORMATION_ID, VALUE_DISPLAY_NAME and value_emp_ID in my JSON result.
My table EMP_METADATA in the database looks like the following:
column_Name Data_Type
EMPLOYEE_ID NUMBER
INFORMATION_ID NUMBER
VALUE_DISPLAY_NAME VARCHAR2(30 BYTE)
VALUE_EMP_ID NUMBER
Inside CompanyWS project, I have the GET request defined inside a controller in the following manner:
Inside package CompanyWS : edu.abc.company.controller
#RequestMapping(value="/get_em_metadata", method=RequestMethod.GET)
public String getEmpMetaData
(
#RequestParam(value="employee_id", defaultValue="0") Integer employeeID_,
#RequestParam(value="information_id", defaultValue="0") Integer informationID_
)
{
List<EmployeeMetaData> cvmetadata = null;
GetEmployeeResult result = new GetEmployeeResult();
try{
EmployeeMetaDataDao rmDao = (EmployeeMetaDataDao)context.getBean("EmployeeMetaDataDao");
List<EmployeeMetaData> rm = rmDao.findByEmpAndInfoId(employeeID_, informationID_);
if(rm != null) && (!rm.isEmpty()){
System.out.println("Checking Aug 31:"+rm); // This works and print outs on the console
}
} catch(Throwable th) {
th.printStackTrace();
result.setWebServiceStatus(th.getMessage(), false);
}
//return result.toJSON();
}
I am assuming that since my System.out.print statement is printing the following on the console after running the webservice,
Checking Aug 31:[edu.abc.company.orm.EmployeeMetaData#5963b830]
I am half way through and I just need to print the result in the JSON format. In order to print the result, I have defined GetEmployeeResult which is as follows and extending the WebServiceResult class. I am wondering do I need to use GetEmployeeResult and extend WebserviceResult class or I can directly use WebServiceResult class inside my controller to
print the results in JSON format? Any idea how should I proceed with the code for printing JSON inside controller. I have't used Hibernate before. Thanks in advance.
package edu.abc.company.json;
import java.util.List;
import edu.abc.company.domain.CvMetaDataList;
import edu.abc.company.domain.companyMetaDataList;
import edu.abc.company.util.WebServiceResult;
public class GetEmployeeResult extends WebServiceResult {
}
And here is the WebServiceResult class which is defined as follows:
package edu.abc.company.util;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import edu.abc.company.domain.StatusMessage;
import edu.abc.company.json.Views;
// A generic object that can be used to return data and a standardized status message from a web service.
public class WebServiceResult {
protected StatusMessage webservice_status;
// C-tor
public WebServiceResult() {}
// C-tor
public WebServiceResult(StatusMessage webserviceStatus_) {
webservice_status = webserviceStatus_;
}
// Web service status
public StatusMessage getWebServiceStatus() {
return webservice_status;
}
public void setWebServiceStatus(String message_, boolean success_) {
webservice_status = new StatusMessage();
if (success_) {
webservice_status.setStatus(Constants.SUCCESS); // Constants is another class which has messages defined, not including here
webservice_status.setMessage(message_);
} else {
webservice_status.setStatus(Constants.ERROR);
webservice_status.setMessage(message_);
}
}
// Export the object's contents as JSON.
public String toJSON(boolean pretty_) {
String json = "";
try {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, pretty_);
// Convert the object to JSON.
json = objectMapper.writerWithView(Views.Normal.class).writeValueAsString(this);
}
catch(Exception e) {
e.printStackTrace();
}
return json;
}
public String toJSON() {
return toJSON(true);
}
}
The following are just for reference purpose in case someone is interested in looking at it:
I have defined the EmployeeMetaData inside the GeneralOrm project as follows:
Inside package GeneralOrm : edu.abc.company.orm
package edu.abc.company.orm;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="EMP_METADATA")
public class EmployeeMetaData
{
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public int getInformationId() {
return informationId;
}
public void setInformationId(int informationId) {
this.informationId = informationId;
}
public String getValueDisplayName() {
return valueDisplayName;
}
public void setValueDisplayName(String valueDisplayName) {
this.valueDisplayName = valueDisplayName;
}
public int getValueempId() {
return valueempId;
}
public void setValueEmpId(int valueempId) {
this.valueempId = valueempId;
}
#Id
#Column(name="EMPLOYEE_ID")
private int employeeId;
#Column(name="INFORMATION_ID")
private int informationId;
#Column(name="VALUE_DISPLAY_NAME")
private String valueDisplayName;
#Column(name="VALUE_EMP_ID")
private int valueempId;
}
I have defined the EmployeeMetaDataDao inside the GeneralOrm project as follows:
Inside project GeneralOrm : edu.abc.company.orm.dao
package edu.abc.company.orm.dao.impl;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import edu.abc.company.orm.EmployeeMetaData;
import edu.abc.company.orm.dao.EmployeeMetaDataDao;
import edu.abc.company.util.Util;
public class EmployeeMetaDataDaoImpl implements EmployeeMetaDataDao {
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#SuppressWarnings("unchecked")
public List<EmployeeMetaData> list() {
logger.debug("Starting EmployeeMetaDataDaoImpl.list() .....");
Session session = null;
List<EmployeeMetaData> EmployeeMetaData = null;
try {
session = this.sessionFactory.openSession();
EmployeeMetaData = session.createQuery("FROM EmployeeMetaData").list();
} catch(Exception ex) {
ex.printStackTrace();
} finally {
session.close();
}
logger.debug("Completed EmployeeMetaDataDaoImpl.list() .....");
return EmployeeMetaData;
}
public List<EmployeeMetaData> findByEmpAndInfoId(int employee_id, int information_id) {
List<EmployeeMetaData> EmployeeMetaData = null;
Session session = null;
try {
session = this.sessionFactory.openSession();
EmployeeMetaData = session.createQuery("FROM EmployeeMetaData WHERE information_id = '" + information_id + "'" + " AND company_id = '" + employee_id + "'").list();
} catch(Exception ex) {
ex.printStackTrace();
} finally {
session.close();
}
return EmployeeMetaData;
}
// Main method goes here
public static void main(String[] args)
{
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
try{
EmployeeMetaDataDao rpcDao = (EmployeeMetaDataDao)context.getBean("EmployeeMetaDataDao");
List<EmployeeMetaData> EmployeeMetaData = rpcDao.list();
if ((EmployeeMetaData != null) && EmployeeMetaData.size() > 0) {
for (int i=0;i<EmployeeMetaData.size();i++) {
EmployeeMetaData re = EmployeeMetaData.get(i);
}
}
context.close();
} catch(Throwable th) {
th.printStackTrace();
} finally {
context.close();
}
}
private SessionFactory sessionFactory;
private static final Logger logger = LoggerFactory.getLogger(EmployeeMetaDataDaoImpl.class);
}

Related

How can I get data from DAO through the model and append them in the view [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed last year.
I am new to Java and I am trying to implement a login system and a user profile conform to MVC - DAO. I would like to enable the controller trough the method addUserDatatoView() to retrieve the user credentials from DAO, in order to add them as strings in a new JPanel (view). Anyway, I am not sure that my way to proceed is correct. First of all, I am getting all the time the NullPointerException, event though the DAO-level is getting correctly the data from the database:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: Cannot invoke "model.User.getUserName()" because "this.user" is null
at controller.LoginController.addUserDatatoView(LoginController.java:75)
at controller.LoginController.showHome(LoginController.java:65)
at controller.LoginController$LoginListener.actionPerformed(LoginController.java:44)
How can I actually retrieve the data from DAO passing through the Model (User class)? What would be the best way to deploy to data as strings from the controller to the view?
I am quite confused about the communication between the different classes and what is the correct procedure, in order not to contravene MVC-DAO.
I am not asking you to solve the problem, but to get an hint in order to get the right direction.
DAO-Implementation:
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import controller.HomeController;
import ds.OracleDsSingleton;
import model.Event;
import model.User;
import view.HomeView;
import view.LoginView;
import view.ProfileView;
public class DaoImpl implements DAO {
LoginView view;
ProfileView profView;
ResultSet rs;
public DaoImpl(LoginView view, ProfileView profView) {
this.view = view;
this.profView = profView;
}
#Override
public ArrayList<User> getUserLogIn (String userName, String userPass) throws SQLException {
OracleDsSingleton ora = OracleDsSingleton.getInstance();
boolean controlRecords = false;
try {
//ArrayList type User
ArrayList<User> user = new ArrayList<User>();
Connection con = ora.getConnection();
Statement stmt = con.createStatement();
String addQuery = "SELECT * FROM UserList";
ResultSet rs = stmt.executeQuery(addQuery);
while (rs.next()) {
userName = rs.getString("userName");
userPass = rs.getString("userPass");
if (userName.equals(view.getUserNameTextField().getText().toString())
&& (userPass.equals(view.getUserPassTextField().getText().toString()))) {
{
controlRecords = true;
User u = new User(userName, userPass);
user.add(u);
for(User us : user) {
System.out.println("Directly from DAOImp: " + us);
}
return user;
}
}
else {
continue;
}
}
if (!controlRecords) {
JOptionPane.showMessageDialog(null, "Not successfully logged in!");
};
if (con != null)
con.close();
if (stmt != null)
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
Class User:
public class User {
String userName;
String userPass;
public User(String userName, String userPass) {
this.userName = userName;
this.userPass = userPass;
}
public User() throws SQLException {
}
public String getUserName() {
return userName;
}
public String getUserPass() {
return userPass;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String toString() {
return userName + userPass;
}
}
Controller
package controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JComponent;
import controller.LoginController.LoginBACKListener;
import dao.DAO;
import dao.DaoImpl;
import model.User;
import view.HomeView;
import view.LoginView;
import view.ProfileView;
import view.StartView;
public class LoginController{
private User user;
private LoginView view;
private ProfileView profView;
public LoginController(User user, LoginView view) {
this.user = user;
this.view = view;
addListener();
}
private void addListener() {
this.view.setLoginListener(new LoginListener());
}
class LoginListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String name = view.getUserNameTextField().getText();
String pass = view.getUserPassTextField().getText();
DAO myDAO = new DaoImpl(view, profView);
try {
//when method from DAOImpl get filled, proceed to Home
if(myDAO.getUserLogIn(name, pass) != null) {
showHome();
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
public void showHome() {
HomeView home = new HomeView();
home.setVisible(true);
HomeController h = new HomeController(home);
try {
addUserDatatoView();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public ArrayList<User> addUserDatatoView() throws SQLException {
DAO myDAO = new DaoImpl(view, profView);
ArrayList<User> userCredentials = myDAO.getUserLogIn(user.getUserName(), user.getUserPass());
for(User us : userCredentials) {
System.out.println("Directly from Controller: " + us);
}
return userCredentials;
}
}
It is hard to tell from the partial code in the question, but from what I see, a User object can be constructed only after a successful login. so the constructor should change to:
public LoginController(LoginView view) {
this.view = view;
addListener();
}
And
class LoginListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String name = view.getUserNameTextField().getText();
String pass = view.getUserPassTextField().getText();
DAO myDAO = new DaoImpl(view, profView);
try {
user = myDAO.getUserLogIn(name, pass);//change getUserLogIn to return a single User, or null
//when method from DAOImpl get filled, proceed to Home
if(user != null) {
showHome();
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}

ProducerTemplate. Camel. How to add attachment

Can someone tell me how to add an attachment using ProducerTemplate?
I have been searching but I can not find an answer to my case.
I am using Camen 2.1 and I have these three clases:
MailSender2.java
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import org.apache.camel.Exchange;
import org.apache.camel.ExchangePattern;
import org.apache.camel.ProducerTemplate;
public class MailSender2 extends TypeMail{
private static final ResourceBundle RES = ResourceBundle.getBundle("mail");
protected static final String MAIL_NOTIFICATION_ENDPOINT=RES.getString("mail.host.location").trim()+":"+RES.getString("mail.port").trim();
private Map<String, Object> header;
public MailSender2() {
this.header=new HashMap<>();
}
public void send(ProducerTemplate template) {
this.header.put("From", this.getT_from());
this.header.put("To", this.getT_to());
this.header.put("Subject", this.getT_subject());
this.header.put(Exchange.CONTENT_TYPE, "text/html; charset=UTF-8");
//this.getF_ficher() <-- I have here the file to attach
//this.getT_ficnon() <-- I have here the name ot the file
//this.getT_ficext() <-- I have here the extension ot the file
template.sendBodyAndHeaders(MAIL_NOTIFICATION_ENDPOINT, this.getT_mensaje(), header);
}
}
TypeMail.java:
public class TypeMail {
private String t_id;
private String t_from;
private String t_to;
private String t_subject;
private String t_mensaje;
private byte[] f_ficher;
private String t_ficnon;
private String t_ficext;
public String getT_id() {
return t_id;
}
public void setT_id(String t_id) {
this.t_id = t_id;
}
public String getT_from() {
return t_from;
}
public void setT_from(String t_from) {
this.t_from = t_from;
}
public String getT_to() {
return t_to;
}
public void setT_to(String t_to) {
this.t_to = t_to;
}
public String getT_subject() {
return t_subject;
}
public void setT_subject(String t_subject) {
this.t_subject = t_subject;
}
public String getT_mensaje() {
return t_mensaje;
}
public void setT_mensaje(String t_mensaje) {
this.t_mensaje = t_mensaje;
}
public byte[] getF_ficher() {
return f_ficher;
}
public void setF_ficher(byte[] f_ficher) {
this.f_ficher = f_ficher;
}
public String getT_ficnon() {
return t_ficnon;
}
public void setT_ficnon(String t_ficnon) {
this.t_ficnon = t_ficnon;
}
public String getT_ficext() {
return t_ficext;
}
public void setT_ficext(String t_ficext) {
this.t_ficext = t_ficext;
}
}
MailCommunicationTransformer.java:
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ws.soap.client.SoapFaultClientException;
public class MailCommunicationTransformer {
MailSender2 mailSender = null;
static Logger logger = LoggerFactory.getLogger(MailCommunicationTransformer.class);
public MailCommunicationTransformer()
{
}
public MailLog transform(Object actualMessage, Exchange exchange, CamelContext context)
{
mailSender = exchange.getIn().getBody(MailSender2.class);
try {
MailSenderDAO mailSenderDAO = (MailSenderDAO)context.getRegistry().lookup("MailSenderDAO");
mailSenderDAO.validarInput(mailSender);
if (mailSender!=null) {
ProducerTemplate template=exchange.getContext().createProducerTemplate();
try {
mailSender.send(template);
}
catch (Throwable ex) {
ex.printStackTrace();
exchange.setProperty(Exchange.EXCEPTION_CAUGHT,ex);
}
}
}catch (MailException me) {
me.printStackTrace();
exchange.setProperty(Exchange.EXCEPTION_CAUGHT,me);
}
Throwable e = exchange.getProperty(Exchange.EXCEPTION_CAUGHT,
Throwable.class);
String response = "OK";
if (e != null) {
StringBuffer mensaje = new StringBuffer();
if (e instanceof SoapFaultClientException) {
mensaje.append("MAIL fault exception: CLIENT. ");
} else {
mensaje.append("MAIL fault exception: MAIL. ");
}
logger.info("MailCommunicationTransformer",e);
while (e != null) {
e.printStackTrace();
mensaje.append(e.getMessage());
e = e.getCause();
}
response = mensaje.toString();
}
MailLog log = new MailLog(mailSender, response); //, protocolo
return log;
}
}
In TypeMail I have the file in f_ficher, and the fileName (t_ficnon) and extension (t_ficext), but I can not find how to attach this file in MailSender2 before template.sendBodyAndHeaders(.....)
Any help would be very appreciated.
Regards.
Perhaps I don't fully understand your question, but the ProducerTemplate don't know about the message type.
You just send a body and perhaps also headers to an endpoint.
Therefore the body just needs to be a fully constructed MimeMessage object as documented in the Camel Mail docs.
You can simply construct the mail message with Java and then use the object with the ProducerTemplate (what you already do).
template.sendBodyAndHeaders("your-smtp-endpoint", yourMimeMessageInstance, yourHeaderMap);
Thanks for the answer!
But, finally, I could do it this way:
new class EmailProcessor.java
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.util.Objects;
import java.util.ResourceBundle;
import javax.activation.DataHandler;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.apache.commons.codec.binary.Base64;
public class EmailProcessor implements Processor {
// Atributos de la clase
private TypeMail typeMail;
public EmailProcessor(TypeMail typeMail) {
this.typeMail = typeMail;
}
#Override
public void process(Exchange exchange) throws Exception {
Message ms = exchange.getIn();
ms.setHeader("From", this.typeMail.getT_from());
ms.setHeader("To", this.typeMail.getT_to());
ms.setHeader("Subject", this.typeMail.getT_subject());
ms.setHeader(Exchange.CONTENT_TYPE, "text/html; charset=UTF-8");
ms.setBody("<p style='font-family: Calibri;'>" + this.typeMail.getT_mensaje() + "</p>");
if (this.typeMail.getF_ficher() != null) {
String mimeType = "application/pdf";
if ("zip".equals(typeMail.getT_ficext())) {
mimeType = "application/zip";
}
ms.addAttachment(typeMail.getT_ficnom() + "." + typeMail.getT_ficext(), new DataHandler(typeMail.getF_ficher(), mimeType));
}
}
}
MailSender.java:
import java.util.ResourceBundle;
import org.apache.camel.ExchangePattern;
import org.apache.camel.ProducerTemplate;
public class MailSender extends TypeMail{
private static final ResourceBundle RES = ResourceBundle.getBundle("mail");
protected static final String MAIL_NOTIFICATION_ENDPOINT=RES.getString("mail.host.location").trim()+":"+RES.getString("mail.port").trim();
public MailSender() {
}
public void send(ProducerTemplate template) {
template.send(MAIL_NOTIFICATION_ENDPOINT, ExchangePattern.InOnly, new EmailProcessor(this));
}
}

Orientdb: Import database in memory and use it as graph

This is my Java DB class in which I open database and import database export file in memory graph database, where I define all database schema information for testing cases.
Operation going well but how can I access the imported database as graph instance and not document instance of database?
I try so many things but I have failed...
Error :
The Person class exist in my schema so something else is going wrong.
Caused by:
> com.orientechnologies.orient.core.exception.OCommandExecutionException:
> Class 'PERSON' was not found in current database
Code:
import com.orientechnologies.orient.core.db.tool.ODatabaseExportException;
import com.orientechnologies.orient.core.db.tool.ODatabaseImport;
import com.orientechnologies.orient.core.sql.OCommandSQL;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory;
import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx;
import lombok.Getter;
import java.io.IOException;
public class Db {
#Getter private static OrientGraphFactory factory;
#Getter private static OrientGraphNoTx graph;
static public void main(String[] args){
open("memory","database");
importDB("/schemas/diary-11202016.gz");
try {
seed();
} catch (InterruptedException e) {
e.printStackTrace();
}
closeDB();
}
public static void open(String dbType, String dbUrl) {
String dbInfo = dbType + ":" + dbUrl;
System.out.println(dbInfo);
factory = new OrientGraphFactory(dbInfo, "root", "root").setupPool(1, 10);
graph = factory.getNoTx();
}
public static void importDB(String path) {
try {
ODatabaseImport importDb = new ODatabaseImport(graph.getRawGraph(), Db.class.getResourceAsStream(path), (iText) -> {
System.out.print(iText);
});
importDb.setMerge(true);
importDb.importDatabase();
importDb.close();
System.out.println("\nImporting database: OK");
} catch (ODatabaseExportException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void seed() throws InterruptedException {
System.out.println("Starting to seed...");
for (Vertex v : (Iterable<Vertex>) graph.command( new OCommandSQL("select from Person")).execute()) {
System.out.println("- Bought: " + v.getProperty("name"));
}
System.out.println("Finish to seed...");
}
public static void closeDB() {
factory.close();
}
}
Replace the following piece of code
ODatabaseImport importDb = new ODatabaseImport(graph.getRawGraph(), Db.class.getResourceAsStream(path), (iText) -> {
System.out.print(iText);
});
importDb.setMerge(true);
with
ODatabaseImport importDb = new ODatabaseImport(graph.getRawGraph(), path, (iText) -> {
System.out.print(iText);
});
// importDb.setMerge(true);

#autowire annotation not working

I have a controller GGSNAcceptController.java:
package com.viettel.pcrf.controller;
import com.viettel.fw.Exception.LogicException;
import com.viettel.fw.dto.BaseMessage;
import com.viettel.fw.web.controller.BaseController;
import com.viettel.pcrf.common.Const;
import com.viettel.pcrf.dto.GgsnAcceptDTO;
import com.viettel.pcrf.webconfig.service.GgsnAcceptService;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
#Component
#ManagedBean(name = "ggsnAcceptController")
#Scope("view")
public class GGSNAcceptController extends BaseController implements Serializable, BaseTableCTRL {
/**
* VARIABLES & GETTER/SETTER
*/
private GgsnAcceptDTO ggsnAccept;
private GgsnAcceptDTO selectedGgsnAccept;
private List<GgsnAcceptDTO> listGgsnAccept;
public GgsnAcceptDTO getGgsnAccept() {
return ggsnAccept;
}
public void setGgsnAccept(GgsnAcceptDTO ggsnAccept) {
this.ggsnAccept = ggsnAccept;
}
public GgsnAcceptDTO getSelectedGgsnAccept() {
return selectedGgsnAccept;
}
public void setSelectedGgsnAccept(GgsnAcceptDTO selectedGgsnAccept) {
this.selectedGgsnAccept = selectedGgsnAccept;
}
public List<GgsnAcceptDTO> getListGgsnAccept() {
return listGgsnAccept;
}
public void setListGgsnAccept(List<GgsnAcceptDTO> listGgsnAccept) {
this.listGgsnAccept = listGgsnAccept;
}
/**
* SERVICE
*
*/
#Autowired
private GgsnAcceptService ggsnAcceptServ;
/**
* INIT
*
*/
#PostConstruct
#Override
public void init() {
updateCtrl();
}
#Override
public void updateCtrl() {
clear();
System.out.println(ggsnAcceptServ == null);
listGgsnAccept = ggsnAcceptServ.findAll();
}
private String ggsnAcceptSelected;
#Override
public void updateDB() {
try {
if (ggsnAccept == null) {
throw new LogicException("nullSelected", "GGSN Config is not yet selected!");
}
if (formStatus == Const.BTN_ADD && ggsnAcceptServ.isExisted(ggsnAccept)) {
throw new LogicException("insertExisted", "GGSN Config existed!");
}
// if (systemCfgSelected != null && systemCfgSelected.equals(systemCfg.getSystemCfgName()) && langServ.isExisted(systemCfg)) {
// throw new LogicException("updateExisted", "GGSN Config is existed!");
// }
BaseMessage msg = ggsnAcceptServ.updateGgsn(ggsnAccept);
if (msg.isSuccess()) {
reportSuccess("msgInfo", "Success");
}
updateCtrl();
selectedGgsnAccept = (GgsnAcceptDTO) msg.getOutputObject();
} catch (LogicException ex) {
reportError("msgInfo", ex.getDescription());
} catch (Exception ex) {
logger.error(ex, ex);
}
}
#Override
public void deleteDB() {
try {
if (ggsnAccept == null) {
throw new LogicException("nullSelected", "GGSN Config is not selected yet!");
}
BaseMessage msg = ggsnAcceptServ.deleteGgsn(ggsnAccept);
if (msg.isSuccess()) {
reportSuccess("msgInfo", "msg.delete.success");
}
updateCtrl();
} catch (LogicException ex) {
reportError("msgInfo", ex.getDescription());
} catch (Exception ex) {
logger.error(ex, ex);
}
}
#Override
public void prepareAdd() {
ggsnAccept = new GgsnAcceptDTO();
selectedGgsnAccept = null;
}
#Override
public void prepareEdit() {
if (selectedGgsnAccept != null) {
ggsnAccept = selectedGgsnAccept;
}
}
#Override
public void prepareDelete() {
if (selectedGgsnAccept != null) {
ggsnAccept = selectedGgsnAccept;
}
}
#Override
public void clear() {
selectedGgsnAccept = null;
ggsnAccept = null;
}
#Override
public void onRowChangeListener() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
An interface GgsnAcceptService.java:
package com.viettel.pcrf.webconfig.service;
import com.viettel.fw.dto.BaseMessage;
import com.viettel.pcrf.dto.GgsnAcceptDTO;
import java.util.List;
public interface GgsnAcceptService {
public List<GgsnAcceptDTO> findAll();
public List<GgsnAcceptDTO> findAll(List filters);
public BaseMessage updateGgsn(GgsnAcceptDTO ggsn) throws Exception;
public BaseMessage deleteGgsn(GgsnAcceptDTO ggsn) throws Exception;
public boolean isExisted(GgsnAcceptDTO ggsn) throws Exception;
}
And a class implement above interface:
package com.viettel.pcrf.webconfig.service;
import com.viettel.fw.common.util.extjs.FilterRequest;
import com.viettel.fw.dto.BaseMessage;
import com.viettel.pcrf.webconfig.repo.GgsnAcceptRepository;
import com.viettel.pcrf.common.util.mapper.GgsnAcceptMapper;
import com.viettel.pcrf.dto.GgsnAcceptDTO;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.viettel.service.BaseServiceImpl;
import java.util.ArrayList;
#Service
public class GgsnAcceptServiceImpl extends BaseServiceImpl implements GgsnAcceptService {
private GgsnAcceptMapper mapper = new GgsnAcceptMapper();
#Autowired
private GgsnAcceptRepository repository;
public Logger logger = Logger.getLogger(GgsnAcceptService.class);
#Override
public List<GgsnAcceptDTO> findAll(List filters) {
return mapper.toDtoBean(repository.findAll(repository.toPredicate(filters)));
}
#Override
public List<GgsnAcceptDTO> findAll() {
return mapper.toDtoBean(repository.findAll());
}
#Override
public BaseMessage updateGgsn(GgsnAcceptDTO ggsn) throws Exception {
BaseMessage msg = new BaseMessage();
GgsnAcceptDTO newGgsn = mapper.toDtoBean(repository.saveAndFlush(mapper.toPersistenceBean(ggsn)));
msg.setOutputObject(newGgsn);
msg.setSuccess(true);
return msg;
}
#Override
public boolean isExisted(GgsnAcceptDTO ggsn) throws Exception {
List<FilterRequest> listReq = new ArrayList<>();
listReq.add(new FilterRequest("IP", ggsn.getIp()));
return repository.findOne(repository.toPredicate(listReq)) != null;
}
#Override
public BaseMessage deleteGgsn(GgsnAcceptDTO ggsn) throws Exception {
BaseMessage msg = new BaseMessage();
repository.delete(mapper.toPersistenceBean(ggsn));
msg.setSuccess(true);
return msg;
}
}
I got an null error when trying to access a page call controller. Is there anything wrong with my code ?
My property ggsnAcceptServ always null although i have already set autowired for it. I'm new in Spring, please help to explain why this property null. Any help would be great.
You have a problem mixing jsf and spring:
#Component
#ManagedBean(name = "ggsnAcceptController")
#Scope("view")
Your controller will be executed in jsf context not in spring context. Thats why autowiering not working.

How to access and ArrayList inside another class inside multiple try's?

I have a homework to retrieve a myqsl query and save it to a ArrayList , and then to link it to another class and then serialize it and send it through http,
In a scheme it would be
class Server{static class a {try{try{ try{arraylist1} }}}}
class b {var1,var2,link_to(arraylist1)}
then serialize class b and send it
i managed to take the sql query and save the objects in the ArrayList (objects created from class "Personat") through
if (rs != null) {
List<Personat> perList = new ArrayList<Personat>();
while (rs.next()) {
Personat per = new Personat();
per.setID(rs.getInt("var1"));
per.setName(rs.getString("var2"));
per.setAmount(rs.getInt("var3"));
perList.add(per);
}
}
Where rs=ResultSet object
but i cant access the ArrayList from class b so i can serialize it. I have tried to make it static (nothing ,it cant be linked).I have tried to make a getter (yet nothing eclipse wont let me as i automatically generate them).
So i don't know what i should do ! Can someone help me ? Or does anyone have any idea?
i have tried to search google for this but as you can see is a little too specific so no results until now ....
here is my Server.java
package server2;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.InetSocketAddress;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class Server {
private static List<Personat> perList = new ArrayList<Personat>();
//need to access this in the SendRes class
public List<Personat> getPerList() {
return perList;
}
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(3333), 0);
server.createContext("/", new MyHandler());
server.setExecutor(null);
server.start();
}
static public class MyHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
ObjectInputStream ios = new ObjectInputStream(t.getRequestBody());
//
final String url = "jdbc:mysql://localhost/httpServer";
final String user = "root";
final String password = "";
try {
Send oin = (Send) ios.readObject();
int id = oin.getId();
String emri = oin.getName();
int amount = oin.getAmount();
int paid = oin.getPaid();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user,
password);
try {
PreparedStatement s = con
.prepareStatement("INSERT INTO person(ID,Name,Amount,Paid) VALUES (?,?,?,?)");
s.setInt(1, id);
s.setString(2, emri);
s.setInt(3, amount);
s.setInt(4, paid);
s.executeUpdate();
ResultSet rs = s.executeQuery("SELECT * "
+ "from personat ORDER BY EmpId");
if (rs != null) {
while (rs.next()) {
Personat per = new Personat();
per.setID(rs.getInt("ID"));
per.setName(rs.getString("Name"));
per.setAmount(rs.getInt("Amount"));
perList.add(per);
}
}
//here i need to send an SendRes object with the ArrayList inside it
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null) {
con.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
class SendResponse implements Serializable {
String gabim;
String gabimNr;
//link the arraylist from class server here
}
class Personat {
int ID;
public int getID() {
return ID;
}
public void setID(int iD) {
ID = iD;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getAmount() {
return Amount;
}
public void setAmount(int amount) {
Amount = amount;
}
String Name;
int Amount;
}
Objects of type B can only access the public members of type A. To get access to your list you need to make it a public member of A. The typical way to do this is to use a private field and a public getter.
class A
{
private List<Personat> personList;
public List<Personat> getPersonList() { return personList; }
public void handle(HttpExchange t) throws IOException
{
// ...
personList = ...;
// ...
}
}
Note that by giving public access to your list you are also allowing clients to modify the contents of the list. You may prefer to give them a copy of the list if this is not desirable.
On a slightly unrelated note, if you three nested try blocks in a single method then that method is probably too complex and should be refactored into smaller methods.

Categories