I am working on a web dev project right now using netbeans 8.2 + glassfish 4.1
My code seems to be good since it is not showing any type of errors. However, when I try to run it and I paste the code in google postman my response look like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<clubss></clubss>
Just to make sure, my project is on football teams. I currently have a table with 3 team only, just to keep it short. A weird thing that I noticed is the last line - "clubss". I searched through my code and could not find the word "clubss" anywhere - I do have loats of "club" + "clubs" but nowhere a "clubss".
However, most important thing to me at the moment is to get the whole thing running and to display the 3 teams in postman.
If you require any code just let me know. I did not paste them in in the first place because
a) it might turned out it is not needed
b) they are fairly long and it would make the post look bad.
However if you do need it I will update it immediately.
Thanks in advance, any help appreciated. UPDATE
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
#XmlRootElement(name="clubs")
// define the field order
#XmlType(propOrder={"id", "name", "year", "country", "league",
"picture", "description"})
public class Clubs {
private int id;
private String name, year, country, league, picture, description;
// JAXB requires a default ctor
public Clubs(){
}
public Clubs(int id, String name, String year, String country, String league, String picture, String description) {
this.id = id;
this.name = name;
this.country = country;
this.year = year;
this.league = league;
this.picture = picture;
this.description = description;
}
#XmlElement
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#XmlElement
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
#XmlElement
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
#XmlElement
public String getLeague() {
return league;
}
public void setLeague(String league) {
this.league = league;
}
#XmlElement
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
#XmlElement
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "Clubs{" + "id=" + id + ", name=" + name + ", country=" + country + ", league=" + league + ", year=" + year + ", picture=" + picture + ", description=" + description + '}';
}
}
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ClubsDAO {
private Connection con = null;
public static void main(String[] args) {
ClubsDAO dao = new ClubsDAO();
int nextId = dao.getNextClubId();
System.out.println(nextId);
}
public ClubsDAO() {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
con = DriverManager.getConnection(
"jdbc:derby://localhost:1527/CD_WD3_DB",
"sean", "sean");
System.out.println("OK");
} catch (ClassNotFoundException ex) {
//Logger.getLogger(ClubsDAO.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("ClassNotFoundException");
ex.printStackTrace();
} catch (SQLException ex) {
//Logger.getLogger(ClubsDAO.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("SQLException");
ex.printStackTrace();
}
}
public int updateClubs(Clubs clubs){
int rowsUpdated=0;
try{
PreparedStatement ps = con.prepareStatement(
"UPDATE APP.CLUB SET NAME=?, YR=?, COUNTRY=?,"
+ "LEAGUE=?, DESCRIPTION=?, PICTURE=? WHERE "
+ "ID = ?");
ps.setString(1, clubs.getName());
ps.setString(2, clubs.getYear());
ps.setString(4, clubs.getCountry());
ps.setString(5, clubs.getLeague());
ps.setString(6, clubs.getDescription());
ps.setString(7, clubs.getPicture());
ps.setInt(8, clubs.getId());
rowsUpdated = ps.executeUpdate();
}catch (Exception e){
System.err.println("Exception in executeUpdate()");
e.printStackTrace();
return -1;
}
return rowsUpdated;// 1
}
public int addClubs(Clubs clubs){
int numRowsInserted=0;
try{
PreparedStatement ps = con.prepareStatement(
"INSERT INTO APP.CLUB " // CLUBS??
+ "(ID, NAME, YR, COUNTRY, "
+ "LEAGUE, DESCRIPTION, PICTURE) "
+ "VALUES (?,?,?,?,?,?,?)");
ps.setString(1, clubs.getName());
ps.setString(2, clubs.getYear());
ps.setString(4, clubs.getCountry());
ps.setString(5, clubs.getLeague());
ps.setString(6, clubs.getDescription());
ps.setString(7, clubs.getPicture());
ps.setInt(8, clubs.getId());
numRowsInserted = ps.executeUpdate();
}catch (Exception e){
e.printStackTrace();
return -1;
}
return numRowsInserted;
}
public int getNextClubId(){
int nextClubId = -1;
try{
PreparedStatement ps =
con.prepareStatement(
"SELECT MAX(ID) AS MAX_ID FROM APP.CLUB");
ResultSet rs = ps.executeQuery();
if(!rs.next()){ // set the db cursor
return -1;
}
nextClubId = rs.getInt("MAX_ID") + 1;
}catch(Exception e){
e.printStackTrace();
return -1;
}
return nextClubId;
}
public List<Clubs> findAll() {
List<Clubs> list
= new ArrayList<>();
try {
PreparedStatement pstmt
= con.prepareStatement("SELECT * FROM APP.CLUB ORDER BY ID");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
list.add(processRow(rs));
}
} catch (SQLException ex) {
//Logger.getLogger(ClubsDAO.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("SQLException");
ex.printStackTrace();
}
return list;
}
public Clubs processRow(ResultSet rs) throws SQLException {
Clubs clubs = new Clubs();
clubs.setId(rs.getInt("id"));
clubs.setName(rs.getString("name"));
clubs.setCountry(rs.getString("country"));
clubs.setLeague(rs.getString("league"));
clubs.setYear(rs.getString("yr"));
clubs.setPicture(rs.getString("picture"));
clubs.setDescription(rs.getString("description"));
return clubs;
}
public Clubs findById(int clubId) {
Clubs club = null;
try {
PreparedStatement pstmt
= con.prepareStatement("SELECT * FROM APP.CLUB WHERE ID=?");
pstmt.setInt(1, clubId);
ResultSet rs = pstmt.executeQuery();
if (!rs.next()) { // !F => T
return null;
}
// we have a record
club = processRow(rs);
} catch (SQLException ex) {
//Logger.getLogger(ClubDAO.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("SQLException");
ex.printStackTrace();
}
return club;
}
public List<Clubs> findByName(String name) {
List<Clubs> list
= new ArrayList<Clubs>();
try {
PreparedStatement pstmt
= con.prepareStatement(
"SELECT * FROM APP.CLUB "
+ "WHERE UPPER(NAME) "
+ "LIKE ? ORDER BY NAME");
pstmt.setString(1, "%" + name.toUpperCase() + "%");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
list.add(processRow(rs));
}
} catch (SQLException ex) {
ex.printStackTrace();
}
return list;
}
public int deleteById(int clubId){
int numRowsDeleted=0;
try{
PreparedStatement pstmt =
con.prepareStatement("DELETE FROM APP.CLUB WHERE ID=?");
pstmt.setInt(1, clubId);
numRowsDeleted = pstmt.executeUpdate();
}catch (Exception e){
e.printStackTrace();
}
return numRowsDeleted; // 0 == failure; 1 == success
}
public int deleteAllClubs(){
int result=0;
try{
PreparedStatement pstmt =
con.prepareStatement("DELETE FROM APP.CLUB");
result = pstmt.executeUpdate(); // 0 == failure; >=1 == success
}catch (Exception e){
e.printStackTrace();
}
return result; // 0 == failure; >=1 == success
}
}
package rest.clubs;
// link into JAX-RS
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
#ApplicationPath("/rest")
public class RestConfig extends Application{
#Override
public Set<Class<?>> getClasses(){
final Set<Class<?>> classes =
new HashSet<Class<?>>();
classes.add(ClubsResource.class);
return classes;
}
}
package rest.clubs;
import dao.Clubs;
import dao.ClubsDAO;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
import javax.ws.rs.OPTIONS;
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.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
#Path("/clubs")
public class ClubsResource {
// this class responds to ".../rest/clubs"
private static ClubsDAO dao = new ClubsDAO();
#Context
private UriInfo context;
public ClubsResource() {
}
#GET
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response getAllClubs() {
System.out.println("get all");
List<Clubs> clubList
= dao.findAll();
GenericEntity<List<Clubs>> entity;
entity = new GenericEntity<List<Clubs>>(clubList) {
};
return Response
.status(Response.Status.OK)
.header("Access-Control-Allow-Origin", "*")
.entity(entity)
.build();
}
#POST
#Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response addClubs(Clubs newClubs) {
System.out.println("POST - " + newClubs);
// the 'id' field in the request entity body is ignored!
int nextClubId = dao.getNextClubId();
newClubs.setId(nextClubId);
System.out.println("POST: nextClubId == " + nextClubId);
// now, our Clubobject is set up; insert into db
dao.addClubs(newClubs);
// now set up the HTTP response as per the HTTP spec
return Response
.status(Response.Status.CREATED)
.header("Location",
String.format("%s%s",
context.getAbsolutePath().toString(),
newClubs.getId()))
.header("Access-Control-Allow-Origin", "*")
.entity(newClubs)
.build();
}
#OPTIONS
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response optionsForAllClubs() {
System.out.println("OPTIONS for all");
// what is the verb set for this URI?
// what is the API supported?
Set<String> api = new TreeSet<>();
api.add("GET");// get all
api.add("POST");// add
api.add("DELETE");// delete all
api.add("HEAD");// get with no entity body
return Response
.noContent()
.allow(api)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "Content-Type")
.build();
}
#OPTIONS
#Path("{clubId}")
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response optionsForOneClub() {
System.out.println("OPTIONS for one");
// what is the verb set for this URI?
// what is the API supported?
Set<String> api = new TreeSet<>();
api.add("GET");// get one
api.add("PUT");// update (or add)
api.add("DELETE");// delete one
api.add("HEAD");// get with no entity body
return Response
.noContent()
.allow(api)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "DELETE, PUT, GET")
.header("Access-Control-Allow-Headers", "Content-Type")
.build();
}
#PUT
#Path("{clubId}")
#Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response updateOneClub(Clubs updateClub, #PathParam("clubId") int clubId) {
System.out.println("PUT - " + updateClub);
if (clubId == updateClub.getId()) {
// entity body id == id in URI
if (dao.findById(clubId) == null) {
// id not in db, create
dao.addClubs(updateClub);
// now set up the HTTP response as per the HTTP spec
return Response
.status(Response.Status.CREATED)
.header("Location",context.getAbsolutePath().toString())
.header("Access-Control-Allow-Origin", "*")
.entity(updateClub)
.build();
} else {
// id in db, update
dao.updateClubs(updateClub);
return Response
.status(Response.Status.OK)
.entity(updateClub)
.build();
}
} else {
// id in xml <> id in URI
return Response
.status(Response.Status.CONFLICT)
.entity("<conflict idInURI='"+clubId+"' idInEntityBody='"+updateClub.getId()+"' />")
.build();
}
}
#HEAD
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response headerForAllClubs() {
System.out.println("HEAD");
return Response
.noContent()
.build();
}
#HEAD
#Path("{clubId}")
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response headerForOneClub(#PathParam("clubId") String clubId) {
return Response
.noContent()
.build();
}
#DELETE
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response deleteAllClubs() {
System.out.println("delete all");
int rowsDeleted = dao.deleteAllClubs();
if (rowsDeleted > 0) { // success
// now set up the HTTP response message
return Response
.noContent()
.status(Response.Status.NO_CONTENT)
.header("Access-Control-Allow-Origin", "*")
.build();
} else {
// error
return Response
.status(Response.Status.NOT_FOUND)
.entity("<error rowsDeleted='" + rowsDeleted + "' />")
.header("Access-Control-Allow-Origin", "*")
.build();
}
}
#GET
#Path("{clubId}")
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response getOneClub(#PathParam("clubId") String clubId) {
System.out.println("getOneClub::" + clubId);
Clubs club
= dao.findById(Integer.parseInt(clubId));
return Response
.status(Response.Status.OK)
.header("Access-Control-Allow-Origin", "*")
.entity(club)
.build();
}
#GET
#Path("search/{name}") // /clubs/search/Real
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response getByName(#PathParam("name") String name) {
System.out.println("getByName: " + name);
List<Clubs> clubList
= dao.findByName(name);
GenericEntity<List<Clubs>> entity;
entity = new GenericEntity<List<Clubs>>(clubList) {
};
return Response
.status(Response.Status.OK)
.header("Access-Control-Allow-Origin", "*")
.entity(entity)
.build();
}
#DELETE
#Path("{clubId}") // Path Param i.e. /clubs/1
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response deleteOneClub(#PathParam("clubId") String clubId) {
System.out.println("deleteOneClub(): " + clubId);
// delete the row from the db where the id={clubId}
int numRowsDeleted = dao.deleteById(Integer.parseInt(clubId));
if (numRowsDeleted == 1) { // success
return Response
.noContent()
.status(Response.Status.NO_CONTENT)
.header("Access-Control-Allow-Origin", "*")
.build();
} else {// error
return Response
.status(Response.Status.NOT_FOUND)
.entity("<idNotInDB id='" + clubId + "' />")
.header("Access-Control-Allow-Origin", "*")
.build();
}
}
}
I have created MDB to pick the message from MQ and inserting in to DB2.
I have created data sourse to get the DB connection in WAS. Its inserting message. But due to the speed of the MessageListener some messages not inserted because the connection got closed..
Please help me to handle the conction here..
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import javax.naming.NamingException;
#MessageDriven(
activationConfig = { #ActivationConfigProperty(
propertyName = "destinationType", propertyValue = "javax.jms.Queue"), #ActivationConfigProperty(
propertyName = "destination", propertyValue = "jms/MDBQueue")
},
mappedName = "jms/MDBQueue")
public class AsyncMessageConsumerBean implements MessageListener {
// TODO Auto-generated constructor stub
private javax.naming.InitialContext ctx = null;
private javax.sql.DataSource serviceDataSource = null;
private String environment = null;
/**
* #see MessageListener#onMessage(Message)
*/
public void onMessage(Message message) {
// TODO Auto-generated method stub
System.out.println("On Message Started.....");
try{
if (message instanceof javax.jms.BytesMessage)
{
javax.jms.BytesMessage bytesMessage = (javax.jms.BytesMessage) message;
byte[] bytes = new byte[(int) bytesMessage.getBodyLength()];
bytesMessage.readBytes(bytes);
System.out.println("Reply Message");
String replyMessage = new String(bytes, "UTF-8");
System.out.println(" The message received from MQ :-----" + replyMessage);
insertMQMessage(replyMessage);
}else {
javax.jms.TextMessage TextMessage = (javax.jms.TextMessage) message;
System.out.println("----------- The text message received from UM Queue"+TextMessage.getText());
insertMQMessage(TextMessage.getText());
}
}catch (JMSException ex) {
throw new RuntimeException(ex);
}catch(Exception ex){
ex.printStackTrace();
}
}
public void insertMQMessage(String mqMessage) throws Exception
{
Statement stmtsql = null;
Connection connection = null;
try
{
connection = getDBConnection();
System.out.println("Connection Object :"+connection);
String mqMsgTrackerInsertQry = "";
System.out.println("MQ Tracker insert Query:" + mqMsgTrackerInsertQry);
stmtsql = connection.createStatement();
boolean status = stmtsql.execute(mqMsgTrackerInsertQry);
}
catch(Exception e)
{
e.printStackTrace();
throw e;
}
finally
{
if (stmtsql != null)
try {
stmtsql.close();
} catch (SQLException ignore) {
}
if (connection != null)
try {
connection.close();
} catch (SQLException ignore) {
}
}
}
private Connection getDBConnection() throws SQLException {
try {
ctx = new javax.naming.InitialContext();
serviceDataSource = (javax.sql.DataSource) ctx.lookup("jdbc/DB_DS_XA");
System.out.println("Datasource initiallised"+serviceDataSource);
} catch (NamingException e) {
System.out.println("peformanceappraisalstatus: COULDN'T CREATE CONNECTION!");
e.printStackTrace();
}
Connection connection = null;
try {
connection = serviceDataSource.getConnection();
//connection.setAutoCommit(false);
} catch (SQLException e) {
throw e;
}
return connection;
}
}
I have a servlet as follows that is running perfectly on my Eclipse tomcat. When I upload it to the webapps folder and restart my tomcat on my Ubuntu server, the URL for it(/ServerAPP/Login) won't load, though the tomcat root page does fine. If anyone has any idea why this is happening, I would greatly appreciate it. I'm fairly new to Ubuntu and the inner workings of Tomcat so I could have missed anything.
I can give more information on request, I'm just not sure how much is needed, or if there's something simple and stupid I'm not thinking about.
package Actions;
import java.io.*;
import java.sql.*;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import javax.sql.DataSource;
#WebServlet(urlPatterns={"/Login"})
public class Login extends HttpServlet implements DataSource {
private String User = null;
Connection connection = null;
private String password = null;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if(request.getParameter("User") != null){
this.setUser((String) request.getParameter("User").toString());
}
if(request.getParameter("password") != null){
this.setPassword((String) request.getParameter("password").toString());
}
try {
System.out.println("Loading driver...");
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new RuntimeException("Cannot find the driver in the classpath!", e);
}
Login ds = new Login();
try {
connection = ds.getConnection();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PrintWriter out = response.getWriter();
if(connection != null){
//out.println(User + " " + password);
//Check if user exists in database
if(User!= null){
Statement stmt;
ResultSet rs;
try {
stmt = connection.createStatement();
rs = stmt.executeQuery("SELECT * FROM tblUsers WHERE Username = '" + User + "';");
if(!rs.next()){
out.println("Username: " + User + " was not found in Users table.");
}
else{
//User was found now check if password is correct
if(rs.getString(3).equals(password)){
out.println("User: " + User + " login successful!");
}
else if(rs.getString(3).equals(password) == false){
//password was incorrect
out.println("Password incorrect!");
}
/*
while(rs.next()){
out.println("User ID: " + rs.getInt(1) + " Username: " + rs.getString(2));
}
*/
}
rs.close();
stmt.close();
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
Statement stmt;
ResultSet rs;
try {
stmt = connection.createStatement();
rs = stmt.executeQuery("Select * from tblUsers;");
while(rs.next()){
out.println("User ID: " + rs.getInt(1) + " Username: " + rs.getString(2));
}
rs.close();
stmt.close();
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
}
}
#Override
public PrintWriter getLogWriter() throws SQLException {
// TODO Auto-generated method stub
return null;
}
#Override
public void setLogWriter(PrintWriter out) throws SQLException {
// TODO Auto-generated method stub
}
#Override
public void setLoginTimeout(int seconds) throws SQLException {
// TODO Auto-generated method stub
}
#Override
public int getLoginTimeout() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
#Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
// TODO Auto-generated method stub
return null;
}
#Override
public <T> T unwrap(Class<T> iface) throws SQLException {
// TODO Auto-generated method stub
return null;
}
#Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
// TODO Auto-generated method stub
return false;
}
#Override
public Connection getConnection() throws SQLException {
if (connection != null) {
System.out.println("Cant craete a Connection");
} else {
connection = DriverManager.getConnection(
"<redacted>", "AWSCards", "Cards9876");
}
return connection;
}
#Override
public Connection getConnection(String username, String password)
throws SQLException {
// TODO Auto-generated method stub
if (connection != null) {
System.out.println("Cant craete a Connection");
} else {
connection = DriverManager.getConnection(
"<redacted>", username, password);
}
return connection;
}
public String getUser() {
return User;
}
public void setUser(String user) {
User = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
So I ended up figuring it out, and I thought it might help others to know.
Reason:
Apparently, my tomcat on ubuntu was only java 6, while my eclipse was targeting java 7.
Fix:
I went to the project properties and changed the target(which made eclipse mad), but then recompiled it and put it on the tomcat on ubuntu, and it works fine.
Thanks to the people who tried to help me.
I want to fetch a string from setValues() method of ItemPreparedStatementSetter which is my SQL string. I want to use this String into setSql() method of ItemWriter. Can somebody help me to achieve this.
Below is my PreparedStatementSetter class:
public class PreparedStatementSetter implements
ItemPreparedStatementSetter<Object>{
public static final int INT = 4;
public static final int STRING = 12;
public void setValues(Object item, PreparedStatement ps)
throws SQLException{
#SuppressWarnings({ "rawtypes", "unchecked" })
Map<String, Object> map = (LinkedHashMap) item;
int i = 0;
String columnType;
String sql="";
String final_sql;
try {
sql=generateSql();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
int len=map.size();
for(int k=0 ; k<len ; k++)
{
sql=sql+","+"?";
}
sql=sql+")";
// i want to use this final_sql string in setsql() method of itemwriter
final_sql=sql.replaceFirst("," , " ");
for (Map.Entry<String, Object> entry : map.entrySet()) {
i++;
columnType = entry.getKey().substring(0,
(entry.getKey().indexOf("_")));
switch (Integer.parseInt(columnType)) {
case INT: {
ps.setInt(i, (Integer) (entry.getValue()));
break;
}
case STRING: {
ps.setString(i, (String) (entry.getValue()));
break;
}
}
}
}
private String generateSql()
throws ParserConfigurationException, SAXException, IOException
{
String sql="";
Insert insert;
String table="";
try
{
File is = new File("C:/Users/AMDecalog.Trainees/workspace/SpringJobExecuter/config/input1.xml");
JAXBContext context = JAXBContext.newInstance(Insert.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
insert = (Insert) unmarshaller.unmarshal(is);
Insert in = insert;
List<String> into = in.getInto().getTablename();
for(String s : into)
{
table = table+s;
System.out.println(table);
}
sql = "insert into" + " " + table + " " + "values(";
System.out.println(sql);
}
catch (JAXBException e)
{
e.printStackTrace();
}
return sql;
}
OK, you don't implement your PreparedStatementSetter the right way.
All you have to do is to declare your SQL in the ItemWriter config or in the itemWriter Implementation.
I will assume you are using a JdbcBatchItemWriter:
public class MyItemWrtier extends JdbcBatchItemWriter<MyDomainObj> implements InitializingBean{
#Override
public void afterPropertiesSet() throws Exception {
// set the SQL
String SQL= "UPDATE MYTABLE WHERE FIELD1 = ? AND FIELD2 = ?"
super.setSql(SQL);
}
}
Now, your batch config should declare this writer like this.
<bean id="myItemWriter" class="xxx.yyy.MyItemWriter">
<property name="dataSource" ref="dataSourceIemt" />
<property name="itemPreparedStatementSetter" ref="myPreparedStatementSetter" />
</bean>
And Finally,
#Component("myPreparedStatementSetter")
public class MyPreparedStatementSetter implements ItemPreparedStatementSetter<MyDomainObj> {
public void setValues(MyDomainObj obj, PreparedStatement ps) throws SQLException {
ps.setString(1, obj.getsometing());
ps.setString(2, obj.getsometingElse());
}
}
Hope it is clear.
Regards
I have a problem. When I try to use the "Select distinct" in HSQLDB, the stream of results returns me all rows instead of me returning only distinct rows.
I've tried the following syntax:
SELECT DISTINCT FROM ratings UserID order by UserID;
SELECT DISTINCT (UserID) FROM ratings order by UserID;
SELECT DISTINCT UserID FROM ratings;
SELECT DISTINCT (UserID) FROM ratings;
None of them works. What is the problem?
If anyone able to help me I appreciate.
Thank you.
The function code where I perform the action is as follows:
private void readUserFile(String filename) {
try {
//Verify if file users exists
boolean exists = (new File(filename)).exists();
if (!exists) {
//If file users not exists create one, bases on distinct users that exist in ratings table
ResultSet rsUsers = jdbcTemplate.getDataSource().getConnection().createStatement().executeQuery("SELECT DISTINCT UserID FROM ratings order by UserID;");
List<String> users = new ArrayList<String>();
while (rsUsers.next()) {
users.add(String.valueOf(rsUsers.getInt(1)));
}
rsUsers.close();
//Create and write to file
BufferedWriter f = null;
f = new BufferedWriter(new FileWriter(filename));
for (String user : users) {
f.write(user);
f.newLine();
}
f.close();
}
PreparedStatement prstInsert = con.prepareStatement("INSERT INTO users VALUES (?)");
BufferedReader in = new BufferedReader(new FileReader(filename));
int i = 0;
while (true) {
String s = in.readLine();
if (s == null) { // end of file
log.info("Total imported users: " + i);
break;
}
i++;
int userid = Integer.parseInt(s);
prstInsert.setInt(1, userid);
if (i != 0 && Math.round((double) i / 100) == ((double) i / 100)) {
log.info("Imported users: " + i);
}
prstInsert.executeUpdate();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}