how to convert blob data into byte array and get image from DB and send it to UI through rest api - spring

#Override
public byte[] findByusernameAndtenantId(String username,int tenantId) throws SQLException {
Connection con=null;
Blob img ;
byte[] imgData = null ;
try {
Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
con=DriverManager.getConnection("jdbc:cassandra://169.46.155.77:9042/demo");
String query = "SELECT PHOTO FROM demo.IGNITE_USERS where USER_NAME=? and TENANT_ID=?";
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery(query);
while (result.next ())
{
img = result.getBlob(1);
imgData = img.getBytes(1,(int)img.length());
}
result.close();
stmt.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (con != null)
try{
con.close();
}
catch (SQLException e) {
e.printStackTrace();
}
con = null;
}
return imgData ;
}
this is my implementation code .
#RequestMapping(value ="/Image",method = RequestMethod.POST, produces="image/jpg")
public ResponseEntity<byte[]> getImage(#RequestParam String username,#RequestParam int tenantId) throws SQLException
{
byte[] img=null;
img=authService.findByusernameAndtenantId(username,tenantId);
System.out.println("testing functionality");
return new ResponseEntity<byte[]>(img, HttpStatus.OK);
}
this is my controller code
when I run the spring boot program , and do a POST call in Postman client to get the image I am getting Class not found exception : org.apache.cassandra.cql.jdbc.Cassandra Driver.
Can you please help me how to return that image from cassandra DB stored as Blob ?

Related

call an oracle function with array as parameter via hibernate

So i hava an oracle functiion like: function unbind (ids in id_table). It takes an array of ids to perform some updates on my database.
The question is how can I run my function in order to perform update operations?
What I've alreade tried:
1. Query query = getSession().createSQLQuery("call UNBIND(:ids)");
query.setParameter("ids", myIds);
query.executeUpdate();
but I got ora-06576 not a valid function or procedure name
Query query = getSession().createSQLQuery("execute UNBIND(:ids)");
query.setParameter("ids", myIds);
query.executeUpdate();
finish with ora-00900 invalid sql statement
Long [] myArray = movedIds.toArray(new Long[movedIds.size()]);
Boolean result = getSession().doReturningWork(new ReturningWork<Boolean>() {
#Override
public Boolean execute(Connection connection) throws SQLException {
CallableStatement callableStatement = connection.prepareCall("{ ? = call UNBIND(:ids)");
callableStatement.registerOutParameter(1, Types.INTEGER);
callableStatement.setArray(2, connection.createArrayOf("id_table", myArray));
callableStatement.execute();
return !(callableStatement.getInt(1) == 0);
}
});
finishes with java.sql.sqlfeaturenotsupportedexception unsupported feature
The app conects to the database via jboss, so I suppose that could be the problem in p. 3?
SELECT
UNBIND( id_table (6271789) ) FROM DUAL
does not work because my function performs updates...
Anyway is there any other method to run a function that takes an array as a parameter directly from java code?
here is a simple example, does this help?
import java.sql.*;
public class Class1 {
public static void main(String[] args) throws SQLException {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Connection conn = null;
try {
conn = DriverManager.getConnection(
"jdbc:oracle:thin:#//localhost/orcl","scott","tiger");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String query = "{ ? = call test_func(?) }";
CallableStatement cs = null;
try {
cs = conn.prepareCall(query);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int inVal = 0;
cs.setInt(2, inVal);
cs.registerOutParameter(1, oracle.jdbc.OracleTypes.NUMBER);
cs.executeUpdate();
int res = cs.getInt(1);
System.out.println("result is " + res);
}
}

download csv using spring boot and apache commons

I have this below code for downloading CSV as an ajax button click, But the file is not downloading. Only showing the black new tab on the browser.
#RequestMapping(value = "/batch/download", method = RequestMethod.POST, produces = "text/csv")
#ResponseBody
public void downloadNGIBatchSelected(HttpServletResponse response) throws IOException {
List<String> ids = Arrays.asList("1312321","312313");
generateNewCustomerCSV(response.getWriter(),ids);
}
private void generateNewCustomerCSV(PrintWriter writer, List<String> ids){
String NEW_LINE_SEPARATOR = "\n";
//CSV file header
Object[] FILE_HEADER = {"Token Number",
"Token Expiry Date",
};
CSVPrinter csvPrinter = null;
try {
csvPrinter = new CSVPrinter(new BufferedWriter(writer), CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR));
//Create CSV file header
csvPrinter.printRecord(FILE_HEADER);
for (PolicyMap PolicyMap : policyMaps) {
List customerCSV = new ArrayList();
customerCSV.add(PolicyMap.getInsurancePolicy().getTokenNo());
try {
csvPrinter.printRecord(customerCSV);
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
writer.flush();
writer.close();
csvPrinter.close();
} catch (IOException e) {
System.out.println("Error while flushing/closing fileWriter/csvPrinter !!!");
e.printStackTrace();
}
}
}
You have set the content type in #RequestMapping annotation. But it is not going to work in the case when response is being written using HttpServletResponse. In this case, instead of spring, HttpServletResponse is writing the response that's why you have to set the response type in the response before getting the writer.
response.setContentType ("application/csv");
response.setHeader ("Content-Disposition", "attachment; filename=\"nishith.csv\"");

I get a nullpointerexception when connecting to oracle DataBase

Here is the stack trace:
java.sql.SQLException
at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:290)
at org.apache.tomcat.jdbc.pool.PooledConnection.connect(PooledConnection.java:182)
at org.apache.tomcat.jdbc.pool.ConnectionPool.createConnection(ConnectionPool.java:702)
at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:634)
at org.apache.tomcat.jdbc.pool.ConnectionPool.init(ConnectionPool.java:488)
at org.apache.tomcat.jdbc.pool.ConnectionPool.<init>(ConnectionPool.java:144)
at org.apache.tomcat.jdbc.pool.DataSourceProxy.pCreatePool(DataSourceProxy.java:116)
at org.apache.tomcat.jdbc.pool.DataSourceProxy.createPool(DataSourceProxy.java:103)
at org.apache.tomcat.jdbc.pool.DataSourceProxy.getConnection(DataSourceProxy.java:127)
at com.boeing.DBReader.Server.makeConnection(Server.java:85)
at com.boeing.DBReader.Server.<init>(Server.java:26)
at com.boeing.DBReader.Reader.main(Reader.java:13)
Caused by: java.lang.NullPointerException
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:395)
at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:278)
... 11 more
Connection closed
And here is the code:
public class Server
{
private DataSource datasource;
public Server()
{
try
{
createConnectionToDatabase();
} catch (Exception e)
{
// TODO Auto-generated catch block
System.out.println("Exception:" + e.toString());
}
makeConnection();
}
private void createConnectionToDatabase() throws Exception
{
String connectionString = null;
String login = null;
String password = null;
System.out.println("In createConnectionToDatabase");
PoolProperties p = new PoolProperties();
p.setUrl("jdbc:oracle:thin:#***");
p.setUrl(connectionString);
p.setDriverClassName("oracle.jdbc.OracleDriver");
p.setUsername("**");
p.setPassword("**");
p.setJmxEnabled(true);
p.setTestWhileIdle(false);
p.setTestOnBorrow(true);
p.setValidationQuery("SELECT 1 from dual");
p.setTestOnReturn(false);
p.setValidationInterval(30000);
p.setTimeBetweenEvictionRunsMillis(30000);
p.setMaxActive(100);
p.setInitialSize(10);
p.setMaxWait(10000);
p.setRemoveAbandonedTimeout(600);
p.setMinEvictableIdleTimeMillis(30000);
p.setMinIdle(10);
p.setLogAbandoned(true);
p.setRemoveAbandoned(true);
p.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"
+ "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
datasource = new DataSource();
datasource.setPoolProperties(p);
}
private void closeConnection(Connection con) {
if (con != null) {
try {
con.close();
} catch (Exception ignore) {
System.out.println("Could not close connection, WTF?");
}
}
}
private void makeConnection()
{
Connection con = null;
String queryString = "SQL QUERY GOES HERE ";
try {
System.out.println("Connection attempt");
con = datasource.getConnection();
System.out.println("Connection made no issues");
} catch (Exception e) {
System.out.println("Exception:" + e.toString());
e.printStackTrace();
} finally {
closeConnection(con);
System.out.println("Connection closed");
}
}
I have the driver attached to the build path.. What am I doing wrong? This is set up without maven, and just a normal java project.
Thanks!
Not entirely sure from the stack trace, but this looks wrong:
String connectionString = null;
String login = null;
String password = null;
System.out.println("In createConnectionToDatabase");
PoolProperties p = new PoolProperties();
p.setUrl("jdbc:oracle:thin:#***");
p.setUrl(connectionString);
You're setting the URL to connectionString, which is null.

JDBC Update on Oracle failed to commit

I have JDBC Dao Object, and used PreparedStatements to do UPDATE a row at a table in my DB.
I have other methods such as SELECT and INSERT which are successful (insert-commit works).
But the update, just does not commit the changes (does not work at all). While the same UPDATE statement works from Oracle SQLServer directly.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class StaffDAO {
private Connection conn;
public StaffDAO() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("Oracle Driver not found");
System.exit(0);
}
try {
conn = DriverManager.getConnection(
"jdbc:oracle:thin:#db01.xxxdev.com:1521:training",
"training", "training");
} catch (SQLException e) {
System.out.println("Driver manager failed");
}
}
public ResultSet getAllResultSet() {
String sql = "select * from ben_staff";
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery(sql);
} catch (SQLException ex) {
ex.printStackTrace();
}
return rs;
}
public Staff viewEmployee(String id) throws Exception {
Staff st = new Staff();
String sql = "SELECT * from BEN_STAFF where BEN_STAFF.id =\'" + id
+ "\'";
// String psql = "SELECT * FROM BEN_STAFF WHERE ID = ?";
Statement statement = null;
// PreparedStatement pstatement = null;
try {
statement = conn.createStatement();
// pstatement = conn.prepareStatement(psql);
// pstatement.setString(1, id);
} catch (SQLException e) {
System.out.println("Create Statement failed");
System.exit(1);
}
ResultSet rs = null;
try {
rs = statement.executeQuery(sql);
// rs = pstatement.executeQuery();
while (rs.next()) {
st.setId(rs.getString("ID"));
st.setLastName(rs.getString("LASTNAME"));
st.setFirstName(rs.getString("FIRSTNAME"));
st.setMi(rs.getString("MI"));
st.setAddress(rs.getString("ADDRESS"));
st.setCity(rs.getString("CITY"));
st.setState(rs.getString("STATE"));
st.setTelephone(rs.getString("TELEPHONE"));
st.setEmail(rs.getString("EMAIL"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
statement.close();
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return st;
}
public boolean insert(String id, String last, String first, String mi,
String address, String city, String state, String telephone,
String email) {
PreparedStatement pstmt = null;
String psql = "insert into ben_staff (id, lastname, firstname, mi, address, city, state, telephone, email)"
+ "values (?,?,?,?,?,?,?,?,?)";
try {
pstmt = conn.prepareStatement(psql);
// pstmt.setString(1,st.getId());
// pstmt.setString(2, st.getLastName());
// pstmt.setString(3, st.getFirstName());
pstmt.setString(1, id);
pstmt.setString(2, last);
pstmt.setString(3, first);
pstmt.setString(4, mi);
pstmt.setString(5, address);
pstmt.setString(6, city);
pstmt.setString(7, state);
pstmt.setString(8, telephone);
pstmt.setString(9, email);
pstmt.executeUpdate();
conn.commit();
} catch (SQLException ex) {
ex.printStackTrace();
return false;
} finally {
try {
pstmt.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
return true;
}
public boolean update(String id, String last, String first, String mi,
String address, String city, String state, String telephone,
String email) {
PreparedStatement pstmt = null;
String psql = "update ben_staff set lastname=?, firstname=?, mi=?, address=?, city=?, state=?,"
+ " telephone=?, email=? where id=?";
try {
pstmt = conn.prepareStatement(psql);
pstmt.setString(1, last);
pstmt.setString(2, first);
pstmt.setString(3, mi);
pstmt.setString(4, address);
pstmt.setString(5, city);
pstmt.setString(6, state);
pstmt.setString(7, telephone);
pstmt.setString(8, email);
pstmt.setString(9, id);
pstmt.executeUpdate();
conn.commit();
} catch (SQLException ex) {
ex.printStackTrace();
try{
conn.rollback();
} catch (SQLException exx){
System.out.println("Update Rollback Failed");
}
return false;
} finally {
try {
pstmt.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
return true;
}
public void close() {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
What does pstmt.executeUpdate(); return? That would tell you how many rows are being updated. Something like
int numRows = pstmt.executeUpdate();
System.out.println( "Update modified " + numRows + " rows." );
My guess is that your update isn't actually modifying any rows. That would imply that the id being passed in was incorrect. Remember that string comparisons in SQL Server are case insensitive by default while they are case sensitive by default in Oracle.

How do I display arrayList contents from resultset in Java JDBC?

So I am making a simple java project to play around with JDBC in glassfish and see how it works. The program just shows you a list of surveys and a list of questions for the survey you select. However i cant seem to display the list of questions for the survey I selected. I keep getting empty values. These are the methods I have created:
convert the resultset to object model data values
public JHAKSurvey findSurvey(long id) {
System.out.println("JDBC: FIND SURVEY");
Connection connection = null;
PreparedStatement ps = null;
ResultSet rs = null;
JHAKSurvey survey = null;
try {
connection = openConnection();
String query = "SELECT * FROM APP.SURVEY WHERE ID=?";
ps = connection.prepareStatement(query);
ps.setLong(1, id);
rs = ps.executeQuery();
while (rs.next()) {
survey = createSurveyFromResultSet(rs);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(connection);
}
return survey;
}
private method to query the list of questions from the QUESTION table for a survey id
private void findQuestionsBySurvey(JHAKSurvey survey){
System.out.println("JDBC: FIND QUESTIONS BY SURVEY");
Connection connection = null;
PreparedStatement ps = null;
try {
connection = openConnection();
String query = "SELECT * FROM APP.QUESTION WHERE SURVEYID=?";
ps = connection.prepareStatement(query);
ps.setLong(1, survey.getId());
ps.executeQuery(query);
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(connection);
}
}
private method to convert the find the resultset list to an question object and add it to the survey object
private void createQuestionFromResultSet(ResultSet rs, JHAKSurvey survey){
ArrayList<JHAKQuestion> qList = new ArrayList<JHAKQuestion>();
JHAKQuestion question = new JHAKQuestion();
JHAKSurvey ss = new JHAKSurvey();
//qList.add(survey.getQuestions());
try {
while (rs.next()) {
//question.setDescription(qList.toString());
question.setId(rs.getLong("ID"));
question.setDescription(rs.getString("DESCRIPTION"));
qList.add(question);
survey.setQuestions(qList);
}
System.out.println("createQuestionFromResultSet : JDBC : successful");
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("createQuestionFromResultSet : JDBC : fail");
e.printStackTrace();
}
}
private method to convert a resultset to an survey object.
private JHAKSurvey createSurveyFromResultSet(ResultSet rs){
JHAKSurvey survey = new JHAKSurvey();
Boolean active = false;
String yes;
try {
yes = rs.getString("ACTIVE");
survey.setId(rs.getLong("ID"));
survey.setTitle(rs.getString("TITLE"));
if (yes.equals(Character.toString('Y'))) {
survey.setActive(true);
} else {
survey.setActive(false);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return survey;
}
What am I missing? I also seem to get error:
cannot convert from void to JHAKQuestion
When I try the method: createQuestionFromResultSet();
Thank You
Look at your method:
private void findQuestionsBySurvey(JHAKSurvey survey){
You want to get the questions of a survey, but the method returns void. Make it return a List<Question>. And in the body of the method, iterate through the resultset, transform each row into a question, add the question to a List<Question>, and return this list.
Or, if the goal of the method is to add questions to the survey passed as argument, then rename the method to
private void addQuestionsToSurvey(JHAKSurvey survey) {
and, inside the method body, call the method createQuestionFromResultSet (which should be named createQuestionsFromResultSetAndAddThemToSurvey), with the resultset and the survey as argument:
private void findQuestionsBySurvey(JHAKSurvey survey){
System.out.println("JDBC: FIND QUESTIONS BY SURVEY");
Connection connection = null;
PreparedStatement ps = null;
try {
connection = openConnection();
String query = "SELECT * FROM APP.QUESTION WHERE SURVEYID=?";
ps = connection.prepareStatement(query);
ps.setLong(1, survey.getId());
ResultSet rs = ps.executeQuery(query);
createQuestionFromResultSet(survey);
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(connection);
}
}

Resources