I use an MYSQL Blob to store an Image inside a Database. Now I want to show the image in my IONIC application in which I also uploaded it.
How it works and how can I store it inside an Object?
You can find my code here:
Java Class
public JSONObject getItems(String email) throws SQLException, ClassNotFoundException, IOException {
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
Connection conn = new MYSQLAccess().getConnection();
String sql = "SQL String";
PreparedStatement pstm = conn.prepareStatement(sql);
pstm.setString(1, email);
ResultSet rs = pstm.executeQuery();
while (rs.next()) {
jsonObject.put("1", rs.getBlob("1"));
jsonObject.put("2",rs.getInt("2"));
jsonObject.put("3", rs.getString("3"));
jsonObject.put("4", rs.getString("4"));
jsonArray.add(performanceCarsJsonObject);
}
jsonObject = new JSONObject();
jsonObject.put("array", jsonArray);
conn.close();
return jsonObject;
}
TypeScript Ionic/ Angualar
getPerformanceCars() {
let params = {"email": this.user.getEmail()};
this.cars.performanceCars(params).then(data => {
this._List = data;
this._List = this._List.value.icons;
this.itemList = this._List;
});
}
Ionic HTML
<ion-list>
<ion-item-sliding *ngFor="let items of itemList">
<button ion-item (click)="openItem(item)">
<ion-avatar item-start>
<img [src]="items.img" />
</ion-avatar>
<h2>{{ items.email }}</h2>
<p>{{ items.values }}</p>
<ion-note item-end *ngIf="items.note">{{ cars.note }}</ion-note>
</button>
</ion-item-sliding>
</ion-list>
The preview of the photo within the IONIC Input Uploader uses the following HTML code.
<div class="profile-image" style="background-image: url("data:image/jpeg;base64,DATA;);"></div>
I hope you can help me, to fix my problem.
Solution
I fixed the problems by creating two new methods. In the first step, I create the getItemBlob Method to extract the Blob outside the database. In the next step, I create the method getItemImage in the controller class. These methods search the correct blob inside the database by the itemID convert the Blob in an InputStream and in the last step inside a ServletOutputStream.
In the HTML part, I used a normal img Tag and mapped the server hostname, port and the getItemImage method together to display the image.
Java Class (Item Services)
public Blob getItemBlob(String id) throws SQLException{
Blob image = null;
Connection conn = new MYSQLAccess().getConnection();
String sql = "SELECT ITEMDATA FROM OWNITEM WHERE OWNITEMID = ? AND ACTIVE = 1";
PreparedStatement pstm = conn.prepareStatement(sql);
pstm.setString(1, id);
ResultSet rs = pstm.executeQuery();
while (rs.next()) {
image = rs.getBlob("ITEMDATA");
}
conn.close();
return image;
}
Java Class (Item Controller)
#ResponseBody
#CrossOrigin(origins = "http://localhost:8100")
#RequestMapping(value = "/getItemImage")
public void getItemImage(#RequestParam("id") String id, HttpServletResponse response) throws IOException, SQLException {
ServletOutputStream out = response.getOutputStream();
ItemServices myItemServices = new ItemServices();
Blob image = myItemServices.getItemBlob(id);
response.setContentType("image/jpg");
InputStream in = image.getBinaryStream();
int length = (int)image.length();
int bufferSize = 1920;
byte[] buffer = new byte[bufferSize];
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
in.close();
out.flush();
}
Java Class (Subscriber Controller)
#SuppressWarnings("unchecked")
public JSONObject getSubscribersItems(String email) throws SQLException, ClassNotFoundException {
JSONObject subscribersItemsJsonObject = new JSONObject();
JSONArray subscribersItemsJsonArray = new JSONArray();
ArrayList<String> subscribersArrayList = this.getSubscriber(email);
Connection conn = new MYSQLAccess().getConnection();
String sql = "SELECT T1.OWNITEMID,T1.ITEMNAME,T2.USERNAME,T2.COUNTRY FROM OWNITEM T1,CUSTOMER T2 WHERE T1.EMAIL = T2.EMAIL AND T1.EMAIL = ? AND T1.ITEMDATA != 'NULL' AND T2.ACTIVE = 1";
PreparedStatement pstm = conn.prepareStatement(sql);
for (int i = 0; i < subscribersArrayList.size(); i++) {
pstm.setString(1, subscribersArrayList.get(i));
ResultSet rs = pstm.executeQuery();
while (rs.next()) {
subscribersItemsJsonObject = new JSONObject();
subscribersItemsJsonObject.put("itemID", rs.getInt("OWNITEMID"));
subscribersItemsJsonObject.put("itemName", rs.getString("ITEMNAME"));
subscribersItemsJsonObject.put("username", rs.getString("USERNAME"));
subscribersItemsJsonObject.put("country", rs.getString("COUNTRY"));
subscribersItemsJsonArray.add(subscribersItemsJsonObject);
}
}
subscribersItemsJsonObject = new JSONObject();
subscribersItemsJsonObject.put("items", subscribersItemsJsonArray);
conn.close();
return subscribersItemsJsonObject;
}
IONIC HTML
<ion-list>
<ion-item-sliding *ngFor="let items of subscriberItemsItemList">
<button ion-item (click)="openItems(items)">
<ion-avatar item-start>
<img src="{{ itemImageUrl }}/getItemImage?id={{ cars.itemID }}" />
</ion-avatar>
<h2>{{ items.username }}</h2>
<p>{{ items.country }}</p>
<ion-note item-end *ngIf="items.note">{{ items.note }}</ion-note>
</button>
</ion-item-sliding>
</ion-list>
IONIC TypeScript/ Angular
getDesignCars() {
let params = {"email": this.user.getEmail()};
this.cars.homeCars(params).then(data => {
this._subscriberCarsList = data;
this._subscriberCarsList = this._subscriberCarsList.value.cars;
this.subscriberCarsItemList = this._subscriberCarsList;
});
}
Related
Hello I want to populate a table from database but I have some difficult to do since I am newbie in java programming
here is the Users.java where the method getData(select) is implemented:
#Override
public Users getData(Users u) throws Exception {
Connection con = null;
Users user = null;
ResultSet rs = null;
PreparedStatement ps = null;
try{
con = getConnection();
String sql = "SELECT * FROM USERS";
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()){
user = new Users();
user.setFirstName(rs.getString("First_NAME"));
user.setLastName(rs.getString("LAST_NAME"));
user.setAge(rs.getInt("AGE"));
}
}catch(Exception ex){
JOptionPane.showMessageDialog(null,ex.getMessage());
}finally{
rs.close();
ps.close();
closeConnection(con);
}
return user;
}
Well the data is stored in Users object now and I want to display it on a jTable which is located in patientJframe file can you tell me how to do that?
I created a method on patientJframe but I dont know what to do Im stuck onhere.
PatientJframe :
public void PopulatejTable(){
try {
Users u = null;
Users user = UsersDB.getInstance().getData(u);
if(user== null){
DefaultTableModel dtm = (DefaultTableModel)jTable.getModel();
dtm.setRowCount(0);
Vector vector = new Vector();
vector.add(user.getCin());
vector.add(user.getLastName());
vector.add(user.getFirstName());
}else{
JOptionPane.showMessageDialog(null,"Faild");
}
} catch (Exception ex) {
Logger.getLogger(AddNewPatient.class.getName()).log(Level.SEVERE, null, ex);
}
}
The method it is correct ? please can you help me ?
I tried to select some data from a MYSQL database tab and insert them into another MYSQL database table.
This is my servlet code
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
ArrayList al = null;
int size = 0;
size = AcceptDao.getData(name);
if (size>0) {
out.println("<script type=\"text/javascript\">");
out.println("alert('Successfully Employee Added');");
out.println("</script>");
} else {
out.println("<script type=\"text/javascript\">");
out.println("alert('Try Again');");
out.println("</script>");
}
}
and here is my java code to do select and insert data.
public static int getData(String Uname) {
ArrayList al = null;
int status = 0;
String name = null;
String role = null;
String pass = null;
try {
Connection con = ConnectionProvider.getCon();
String query = "SELECT noty_name,noty_user_role,noty_pass FROM notification WHERE noty_name='" + Uname + "'";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
al = new ArrayList();
while (rs.next()) {
name = rs.getString("noty_name");
role = rs.getString("noty_user_role");
pass = rs.getString("noty_pass");
}
PreparedStatement ps = con.prepareStatement("INSERT INTO employee (name,user_role,pass) values(?,?,?)");
ps.setString(1, name);
ps.setString(2, role);
ps.setString(3, pass);
status = ps.executeUpdate();
} catch (Exception e) {
}
return status;
}
this isn't work properly. this code doesn't do select and insert. What is the wrong with this code.
Please note that the code part for "insert" is outside the loop. So only the last data in the loop will be inserted, if available.
Moreover there is no need of while(rs.next) loop. you can use if(rs.next) condition if you are sure that you be passing a unique name in the request.
while (rs.next()) {
name = rs.getString("noty_name");
role = rs.getString("noty_user_role");
pass = rs.getString("noty_pass");
}
/* The Below part is wrong */
PreparedStatement ps = con.prepareStatement("INSERT INTO employee (name,user_role,pass) values(?,?,?)");
ps.setString(1, name);
ps.setString(2, role);
ps.setString(3, pass);
status = ps.executeUpdate();
Instead use this below code
public static int getData(String Uname) {
ArrayList al = null;
int status = 0;
String name = null;
String role = null;
String pass = null;
try {
Connection con = ConnectionProvider.getCon();
String query = "SELECT noty_name,noty_user_role,noty_pass FROM notification WHERE name='" + Uname + "'";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
al = new ArrayList();
PreparedStatement ps = con.prepareStatement("INSERT INTO employee (name,user_role,pass) values(?,?,?)");
while (rs.next()) {
name = rs.getString("noty_name");
role = rs.getString("noty_user_role");
pass = rs.getString("noty_pass");
ps.setString(1, name);
ps.setString(2, role);
ps.setString(3, pass);
status = ps.executeUpdate();
}
} catch (Exception e) {
}
return status;
}
I can return a single object into json format from the returnMachineTable method. But when i try to return all the objects from the Manufacturer table. i cannot return it as json format. Any suggestions?
#Path("/test")
public class testWS {
// private static final String api_version = "00.01.00";
#GET
#Path("/database")
// #Produces(MediaType.TEXT_PLAIN)
#Produces(MediaType.APPLICATION_JSON)
public Machine returnMachineTable() throws Exception {
// public String returnDatabaseStatus() throws Exception{
PreparedStatement query = null;
String myString = "";
String returnString = null;
Connection conn = null;
Machine u = null;
// returnString = "<p>data base context: "+"shit ass"+"</p>";
try {
conn = db.DBConn().getConnection();
query = conn.prepareStatement("SELECT * FROM MACHINE");
ResultSet rs = query.executeQuery();
while (rs.next()) {
myString = myString + rs.getString("LOCATION") + "!!!!!"
+ rs.getInt("MACHINEID") + "!!!!!"
+ rs.getInt("MACHINEID");
Long maintainenceDate = rs.getDate("MAINTDATE").getTime();
Long dateInstalled = rs.getDate("DATEINSTALLED").getTime();
u = new Machine();
u.setMachineId(rs.getInt("MACHINEID"));
u.setLocation(rs.getString("LOCATION"));
u.setMaintainenceDate(maintainenceDate);
u.setDateInstalled(dateInstalled);
u.setInstaller(rs.getString("INSTALLER"));
u.setMachineCode(rs.getString("MACHINECODE"));
u.setModel(rs.getString("MODEL"));
u.setManufacturerID(rs.getString("MANUFACTURERID"));
u.setName(rs.getString("NAME"));
u.setSoftware(rs.getString("SOFTWARE"));
myString = u.toString();
}
returnString = "---" + myString + "---\n";
query.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null)
conn.close();
}
// return returnString;
return u;
}
#GET
#Path("/ManufacturerTable")
#Produces(MediaType.APPLICATION_JSON)
public List<Manufacturer> returnManufacturerTable() throws Exception {
PreparedStatement query = null;
String myString = "";
String returnString = null;
Connection conn = null;
Manufacturer u = null;
List<Manufacturer> ulist = null;
int i = 0;
String uList = "";
try {
conn = db.DBConn().getConnection();
query = conn.prepareStatement("SELECT * FROM MANUFACTURER");
ResultSet rs = query.executeQuery();
JSONArray jsonArray = new JSONArray();
while (rs.next()) {
myString = myString + rs.getString("MANUFACTURERNAME")
+ "!!!!!" + rs.getInt("MANUFACTURERID");
u = new Manufacturer();
u.setManufacturerName(rs.getString("MANUFACTURERNAME"));
u.setManufacturerId(rs.getInt("MANUFACTURERID"));
ulist.add(i, u);
i++;
myString = myString+"\n"+u.toString();
}
returnString = "---" + myString + "---\n";
query.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null)
conn.close();
}
// return returnString;
/* Gson gson = new Gson();
return gson.toJson(ulist);*/
return ulist;
}
}
I think you should clean your code first.
IE: you are declaring this variable and never using it.
JSONArray jsonArray = new JSONArray();
Secondly, why you put all the object properties to a big string? Why not just add all objects to an array and then convert it to json array?
i've created this servlet to connect to database and retrieve data then output them in JSON format.
this is the servlet :
public class ConnectServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("application/json");
PrintWriter out=res.getWriter();
JSONArray relatedWorkordersArray = new JSONArray();
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/users","root","");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from user");
JSONObject jObj=new JSONObject();
st = (Statement) con.createStatement();
rs = (ResultSet) st.executeQuery("select * from user");
while (rs.next()) {
String nom = rs.getString("nom");
String prenom = rs.getString("prenom");
int age = rs.getInt("age");
JSONObject Object = new JSONObject();
Object.put("nom", nom);
Object.put("prenom", prenom);
Object.put("age", age);
relatedWorkordersArray.put(Object);
}
jObj.put("data",relatedWorkordersArray.toString());
jObj.put("Success", true);
rs.close ();
st.close ();
con.close();
//print JSON object
out.print(jObj);
Now, In my sencha touch project i've created a JSON-P STORE and i've putted in his url the name of this servlet : ConnectServlet.java but i have an error: unable to load data using the supplied configuration. open in browser : ConnectServlet.java
how can I do to make this proxy using the servlet to get data from database?
you may find your solution here.click here
I try to create dynamic crosstab. When I try, I have an error java.lang.ClassCastException Jasper Report Crosstab than I solved it. But my report is empty. I don't get it why. I check my result set is empty or not. But it does not empty.
Here is my code:
public class DynamicJasperTemplate{
.....//variables define here
public void buildReport() throws Exception{
....//I create query here and get row column and measure field name
JRDataSource ds = getDataSource(query,a,b,c);//I get data from db as jrdatasource
DynamicReport dr = buildReportLayout(a,b,c,ds); // build report layout and add it crosstab in this method.
params.put("sr",ds);//I set report parameter value
JasperReport jr = DynamicJasperHelper.generateJasperReport(dr, new ClassicLayoutManager(), params);
JasperPrint jp = JasperFillManager.fillReport(jr, params, ds);
JasperExportManager.exportReportToPdfFile(jp,"C:/report-out.pdf");
}
private DynamicReport buildReportLayout(String[] a,String[] b,String[] c, JRDataSource ds) {
FastReportBuilder drb = new FastReportBuilder();
drb.setWhenNoDataAllSectionNoDetail();
initStyles();
CrosstabBuilder cb = new CrosstabBuilder();
cb.setHeight(200)
.setWidth(500)
.setHeaderStyle(mainHeaderStyle)
.setDatasource("sr",DJConstants.DATA_SOURCE_ORIGIN_REPORT_DATASOURCE, DJConstants.DATA_SOURCE_TYPE_JRDATASOURCE)
.setUseFullWidth(true)
.setColorScheme(4)
.setAutomaticTitle(true)
.setCellBorder(Border.PEN_1_POINT());
Object obj="NUMBER";
Object obj1="VARCHAR2";
String type = null;
for(int i=0; i<a.length; i++) {
DJCrosstabRow row = new CrosstabRowBuilder().setProperty(a[i],String.class.getName())
.setHeaderWidth(100).setHeight(0)
.setTitle(a[i])
.setShowTotals(true).setTotalStyle(totalStyle)
.setTotalHeaderStyle(totalHeader).setHeaderStyle(colAndRowHeaderStyle)
.build();
cb.addRow(row);
}
DJCrosstabColumn col =new CrosstabColumnBuilder().setProperty(b.toString(),"java.sql.Timestamp")
.setHeaderHeight(60).setWidth(50)
.setTitle(b.toString()).setShowTotals(true)
.setTotalStyle(totalStyle).setTotalHeaderStyle(totalHeader)
.setHeaderStyle(colAndRowHeaderStyle)
.build();
cb.addColumn(col);
cb.addMeasure(c[0],"java.math.BigDecimal", DJCalculation.NOTHING , c[0],measureStyle);
djcross = cb.build();
drb.addHeaderCrosstab(djcross);
drb.setUseFullPageWidth(true);
drb.addParameter("sr", "java.util.Collection");
DynamicReport dr = drb.build();
return dr;
}
private void initStyles() {
....//here ı define styles
}
private JRDataSource getDataSource(String query,String[] a,String[] b,String[] c) throws SQLException, JRException {
Connection con = new getConnection().conn();
List<Map<String, ?>> arr = new ArrayList<Map<String, ?>>();
String columnValue;
Map data = new HashMap();
JRResultSetDataSource result = null;
ResultSet rs = null;
int i;
try{
if(con!=null){
Statement stmt = con.createStatement();
rs = stmt.executeQuery(query);
JRDataSource ds = new JRResultSetDataSource(rs);
return ds;
}
......
I hope you can tell me the what I make wrong.
I solved my problem here solution :
when ı delete drb.addParameter("sr", "java.util.Collection"); and b.toString() i make error as unknown column change it b[0] than my problem solved.