Vaadin upload image and store it to database - mysql

I am using a Vaadin upload component and so far I have managed to upload an image to a directory, and display it in a panel component after it is successfull uploaded. What I want to do after this, is to insert it in the database aswell. What I have is a table called Show which has a name, date and an image. In the Show class I have tried to have my image as a byte array or as a Blob.
Column(name="image")
private byte[] image;
#Lob
#Column(name="image")
private Blob image;
In the upload succeded method I want to convert the file to a byte array, and so far I have tried this:
File file = new File("C:\\Users\\Cristina_PC\\Desktop\\" + event.getFilename());
byte[] bFile = new byte[(int) file.length()];
try {
FileInputStream fileInputStream = new FileInputStream(file);
fileInputStream.read(bFile);
uIP.uploadImage(bFile);
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
I tried also this:
byte[] data = Files.readAllBytes(new File("C:\\Users\\Cristina_PC\\Desktop\\" + event.getFilename()).toPath());
uIP.uploadImage(data);
uIP it is actually my uploadImagePresenter, where I tried to transform the byte array to Blob, or simply pass it to the repository as byte array
public void uploadImage(byte[] data) throws SerialException, SQLException{
//Blob blob = new javax.sql.rowset.serial.SerialBlob(data);
showRepo.updateAfterImage(show, data); // or (show, blob)
}
In my repository, in my updateAfterImage method I have:
public void updateAfterImage(Show show, byte[] data) //or Blob data
{
em.getTransaction().begin(); //em - EntityManager
show.setImage(data);
em.getTransaction().commit();
}
Either with Blob or a byte array, I can't manage to update the existing show by setting its image and update it in the database (the cell remains NULL). Also I get no error to help me figure out what is going wrong. Any help/advice would be useful. Thanks!

I have found the solution. What made it work was:
em.getTransaction().begin();
em.find(Show.class, show.getId());
show.setImage(data);
em.merge(spectacol);
em.getTransaction().commit();
in my updateAfterImage method in the show repository.

Related

Problem Saving and Loading Json file in Unity

I'm currently trying to use gestures recognizers in Unity3D. For this I need a library of gestures to be compared with the gesture I'm making.
I'm using a script to save and load from another Unity user since I have no idea how to do it myself.
The problem I'm facing is:
If I save the gestures as json file during gameplay, I can compare them in the same run. But if I restart the run, it stops being able to read the json file and returns NULL or no match as if there were nothing in the json file.
[Serializable]
public class GestureTemplates
{
public List<DrawnGesture> templates;
public GestureTemplates()
{
templates = new List<DrawnGesture>();
}
}
private string gestureFileName = "gestures.json";
void Start () {
LoadTemplates();
}
private void SaveTemplates()
{
string filePath = Application.dataPath + "/streamingAssets/" + gestureFileName;
string saveData = JsonUtility.ToJson(templates);
File.WriteAllText(filePath, saveData);
Debug.Log("Template Saved");
}
private void LoadTemplates()
{
templates = new GestureTemplates();
string filePath = Path.Combine(Application.streamingAssetsPath, gestureFileName);
if (File.Exists(filePath))
{
string data = File.ReadAllText(filePath);
templates = JsonUtility.FromJson<GestureTemplates>(data);
}
}
What I've noticed is it takes a while to save, but it does in fact save since it calls the debug.Log line and the save file can be used in the same run.
Any help would be highly appreciated.
Edit: Nevermind. It's not saving either. It's saving as a Json file with an empty list. The variable is working on the run, but it's not saving nor loading.

Input Stream from MongoDB in JSP

I'm trying to write a method that takes a JSON object that is stored in a mongoDB and serves a ical/ics file to the user.
This is my code so far:
#RequestMapping(value = "/ical", method = RequestMethod.GET)
public void getIcalFile(
String json,
HttpServletResponse response) {
try {
// get your file as InputStream
InputStream is = //Input stream from JSON. HOW?
// copy it to response's OutputStream
IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
} catch (IOException ex) {
//log.info("Error writing file to output stream. Filename was '" + fileName + "'");
throw new RuntimeException("IOError writinethod that takes a JSON object and serves a ical/ics file to the user. This is my code so far:g file to output stream");
}
}
I have no idea how to take an JSON object and use it as an input stream. If there is a better way to do what I am trying to achieve, I would love a suggestion.

How to retrieve blob image from mysql database in jsp

while (rsimg.next())
{
Blob photo = rsimg.getBlob("thumbnails");
}
after that what I have to do to show the image in browser.
Try this code in your servlet file , because it will easier to use and identify errors rather than jsp
import java.sql.*;
import java.io.*;
public class RetrieveImage {
public static void main(String[] args) {
try{
Class.forName("YOUR DRIVER NAME");
Connection con=DriverManager.getConnection(
"URL","USERNAME","PASSWORD");
PreparedStatement ps=con.prepareStatement("select * from TBL_NAME");
ResultSet rs=ps.executeQuery();
if(rs.next()){//now on 1st row
Blob b=rs.getBlob(2); //2 means 2nd column data
byte barr[]=b.getBytes(1,(int)b.length()); //1 means first image
FileOutputStream fout=new FileOutputStream("d:\\IMG_NAME.jpg");
fout.write(barr);
fout.close();
}//end of if
System.out.println("ok");
con.close();
}catch (Exception e) {e.printStackTrace(); }
}
}
Now you can load the image from path given in the above .
Hope this helps !!
In order to show image on web, you will have to use 'img' tag and populate it's 'src' attribute with relative path of your image.
Now the problem is, 'img' tag cannot take binary data as 'src' i.e your client cannot access files from database directly. So what you can do is, create a Servlet that loads the file from database and then streams the file via HttpServletResponse.
Your Servlet will looks something like this:
public class DispalyImage extends HttpServlet {
private static final int DEFAULT_BUFFER_SIZE = 10240; // 10KB.
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Code to access database and get blob image.
// String id = HttpServletRequest.getParameter("id");
// select from table where id='id'
Blob photo = rsimg.getBlob("thumbnails");
response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType("image/jpeg");
response.setHeader("Content-Length", String.valueOf(photo.length()));
// Prepare streams.
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
// Open streams.
input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
// Write file contents to response.
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally {
output.close();
input.close();
}
}
}
Now the problem is, how would your Servlet know which image to stream? Just provide your key as parameter to Servlet. The key would be used to load your image
Assuming you will provide key as 'id', you will display image as
<img src="DisplayImage?id=imageId"></img>
You can retrieve id using HttpServletRequest.getParameter("id") method in your DisplayImage Servlet and load image from database using the id.
Refer FileServlet by BalusC, which has nice example and explanation on how files can ve served from database.

I want to store json values in my android device

I want to store json values in my device. Because everytime application takes time to load json values. Instead of doing number of times to load, just want to load entire json values once. and without internet I can work with that. Once internet get connected, the application automatically load json values. How can I do this ?
You Can use Database for that.
This way also you can store it.
Arraylist<ClassName> jsondata=new ArrayList<ClassName>
Here's an example:
public Class ClassName
{
string fname;
string lname;
public void setfname(String fname)
{
this.fname=fname;
}
public void setlname(String lname)
{
this.lname=lname;
}
public String getlname(String lname)
{
return lname;
}
public String getfname(String fname)
{
return fname;
}
You can use SharedPreferences to save the json in application's storage space.
code
/* save */
SharedPreferences pref = context.getSharedPreferences("mydata", MODE_PRIVATE);
Editor editor = pref.edit();
editor.put("myjson", json.toString());
editor.commit();
/* restore */
JSONObject ret = null;
SharedPreferences pref = context.getSharedPreferences("mydata", MODE_PRIVATE);
String jsonStr = pref.getString("myjson", null);
if (!TextUtil.isEmpty(jsonStr)) {
ret = new JSONObject(jsonStr); // need try-catch
}
======
Do the restore every time the app is launching.
For the second part "Once internet get connected, the application automatically load json values."
You need to listen the network state change broadcast. When you get broadcast said the network (or wifi) is connected, grab the newest json from server, replace the json in the memory and save it to SharedPreferences

Uploading a picture in filesystem with JSP/servlet to MYSQL

I've been having some trouble performing this task and I could use a little help:
Im trying to upload a picture from my filesystem to a MYSQL DB using a JSP/Java Servlet
I have a file in an images folder.
I know I'm supposed to read the file, convert it into a byte, get the outputStream, but I have had little luck doing so (and I've posted no code because my attempts have been train wrecks). After the file is in the outputStream, I know how to form a sql statement as an insert with a blob referenced as a ? parameter, but I cannot get this far.
Any help would be much appreciated.
steps you need to follow
1. use input type="file" tag in your main view.
2.using DiskFileItemFactory read all the bytes of uploaded file
3.keep the file in server's folder
4.identify the file with the file name from this folder location and store it into MySql DB
for this use blob
5.dont directly pick the file from your local system and storing in the DB,first of all you have to upload it into your server and then perform DAO operation
public class UploadFilesServlet extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
try
{
//step1
DiskFileItemFactory df=new DiskFileItemFactory();
//step2
df.setSizeThreshold(10000); //setting buffersize
String temp=getServletContext().getRealPath("/WEB-INF/temp");
df.setRepository(new File(temp)); //if buffer crossed comes into the temp
//step3
ServletFileUpload sf=new ServletFileUpload(df);
//step4
List<FileItem> items=(List<FileItem>)sf.parseRequest(req);
//step5
for(FileItem item: items)
{
if(item.isFormField())
{
//this item is a simple text field
String name=item.getFieldName();
String value=item.getString();
pw.println(name+"="+value+"<br/>");
}
else
{
//this is a file
String name=item.getFieldName();
String fileName=item.getName();
if(fileName.lastIndexOf('\\')!=-1)
fileName=fileName.substring(fileName.lastIndexOf('\\')+1);
fileName=getServletContext().getRealPath("/WEB-INF/upload/"+fileName);
item.write(new File(fileName));
pw.println("file:"+fileName+"saved</br>");
BlobDemo.saveFile(fileName);
}//else
}//for
}catch(Exception e){e.printStackTrace(); }
}
}
this code places the client's file into WEB_INF/upload folder ,after the file uploading
locate the file using the same path and use the streams and blob data types to store the file with its file name.
public class BlobDemo {
private static String url = "jdbc:oracle:thin:#localhost:1521:xe";
private static String username = "kodejava";
private static String password = "welcome";
public static void saveFile(String fileName)throws Exception {
Connection conn = null;
FileInputStream fis = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, username, password);
conn.setAutoCommit(false);
String sql = "INSERT INTO Files_Table(name, file) VALUES (?, ?)";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, fileName);
File file = new File("WEB-INF\\upload\\"+fileName);
fis = new FileInputStream(file);
stmt.setBinaryStream(2, fis, (int) file.length());
stmt.execute();
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
}
if (conn != null && !conn.isClosed()) {
conn.close();
}
}
}
}