Saving and Displaying Image from database using MySQL workbench - java

Good day, I was trying to test on uploading an image to my database but when i'm trying to retrieve the image, nothing shows..
Here's my code for uploading the image
String m_dataForImage;
public String getDataForImage() { return m_dataForImage; }
public void setDataForImage(String value) { this.m_dataForImage = value; }
String m_ShowPhoto;
public String getShowPhoto() { return m_ShowPhoto; }
public void setShowPhoto(String value) { this.m_ShowPhoto = value; }
String m_fileName;
public String getFileName() { return m_fileName; }
public void setFileName(String value) { this.m_fileName = value; }
public void onUploadFile(javax.faces.event.ActionEvent event) {
if (event instanceof BaseActionEventUpload){
try{
ConnectionPool.getInstance();
Base.open(ConnectionPool.dataSourcePooled);
BaseActionEventUpload bae =(BaseActionEventUpload)event;
setFileName(bae.getClientFileName());
m_ShowPhoto = bae.getHexByteString();
byte[] imageByte = bae.getHexBytes();
setShowPhoto("/hex("+ValueManager.encodeHexString(imageByte)+")");//trying to convert byte to hex
photo_storage photo = new photo_storage();
photo.set("timestamp","ss");
photo.set("Primary_Key", "123");
photo.set("File_Name",getFileName());
photo.set("Image_Data",getShowPhoto());
photo.saveIt();
}catch(Throwable t){
t.printStackTrace();
Statusbar.outputAlert(t.toString());
}finally {
Base.close();
}
}
}
and for showing the image:
public void onShowImage(javax.faces.event.ActionEvent event) {
try{
ConnectionPool.getInstance();
Base.open(ConnectionPool.dataSourcePooled);
List<photo_storage> photo = photo_storage.where("Primary_Key = ?",123);
for (photo_storage so:photo){ setShowPhoto("/hex("+ValueManager.encodeHexString(so.getBytes("Image_Data"))+")");
setFileName(so.getString("File_Name"));
setDataForImage(so.getString("Image_Data"));
}catch(Throwable t){
t.printStackTrace();
Statusbar.outputAlert(t.toString());
}finally {
Base.close();
}
}
Im currently using Intellij and CaptainCasa..
Can anyone help?
Thanks in advance.

It seems that it should be
photo.set("Image_Data",imageByte);
instead of
photo.set("Image_Data",getShowPhoto());
because imageByte is where the uploaded image stored.

Related

GraphQL Error: Expected a user-defined GraphQL scalar type with name 'FileUpload' but found none

for several days I have been trying to implement the upload file in Java-GraphQL. I found this topic: How to upload files with graphql-java? I implemented second solutions.
public class FileUpload {
private String contentType;
private byte[] content;
public FileUpload(String contentType, byte[] content) {
this.contentType = contentType;
this.content = content;
}
public String getContentType() {
return contentType;
}
public byte[] getContent() {
return content;
}
}
public class MyScalars {
public static final GraphQLScalarType FileUpload = new GraphQLScalarType(
"FileUpload",
"A file part in a multipart request",
new Coercing<FileUpload, Void>() {
#Override
public Void serialize(Object dataFetcherResult) {
throw new CoercingSerializeException("Upload is an input-only type");
}
#Override
public FileUpload parseValue(Object input) {
if (input instanceof Part) {
Part part = (Part) input;
try {
String contentType = part.getContentType();
byte[] content = new byte[part.getInputStream().available()];
part.delete();
return new FileUpload(contentType, content);
} catch (IOException e) {
throw new CoercingParseValueException("Couldn't read content of the uploaded file");
}
} else if (null == input) {
return null;
} else {
throw new CoercingParseValueException(
"Expected type " + Part.class.getName() + " but was " + input.getClass().getName());
}
}
#Override
public FileUpload parseLiteral(Object input) {
throw new CoercingParseLiteralException(
"Must use variables to specify Upload values");
}
});
}
public class FileUploadResolver implements GraphQLMutationResolver {
public Boolean uploadFile(FileUpload fileUpload) {
String fileContentType = fileUpload.getContentType();
byte[] fileContent = fileUpload.getContent();
// Do something in order to persist the file :)
return true;
}
}
scalar FileUpload
type Mutation {
uploadFile(fileUpload: FileUpload): Boolean
}
I get this error during compilation:
Caused by: com.coxautodev.graphql.tools.SchemaClassScannerError: Expected a user-defined GraphQL scalar type with name 'FileUpload' but found none!
Have you registered it via RuntimeWiring?
Take a look here: Custom Scalar in Graphql-java
You have to extend GraphQLScalarType in your MyScalars class

Change locale in data base android development

How can I localize the database for the project in other languages ​​(for example en, ru, fr and others)
I have an already ready database in English, but I want to make the application multilingual and able to work with other databases depending on the device locale.
I've already seen a lot of forums on this issue, but in each of them it says that you need to get the current locale. But I can not understand where these codes should be attributed. My code is completely listed below.
public class DatabaseHelper extends OrmLiteSqliteOpenHelper
{
private static final String DATABASE_NAME = MuseumConfig.DATABASE_NAME;
private static final String DATABASE_PATH = "/data/data/" + CookbookApplication.getContext().getPackageName() + "/databases/";
private static final int DATABASE_VERSION = CookbookConfig.DATABASE_VERSION;
private static final String PREFS_KEY_DATABASE_VERSION = "database_version";
private Dao<CategoryModel, Long> mCategoryDao = null;
private Dao<AboutModel, Long> mRecipeDao = null;
private Dao<InformationModel, Long> mIngredientDao = null;
// singleton
private static DatabaseHelper instance;
public static synchronized DatabaseHelper getInstance()
{
if(instance==null) instance = new DatabaseHelper();
return instance;
}
private DatabaseHelper()
{
super(CookbookApplication.getContext(), DATABASE_PATH + DATABASE_NAME, null, DATABASE_VERSION);
if(!databaseExists() || DATABASE_VERSION>getVersion())
{
synchronized(this)
{
boolean success = copyPrepopulatedDatabase();
if(success)
{
setVersion(DATABASE_VERSION);
}
}
}
}
#Override
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource)
{
try
{
Logcat.d("DatabaseHelper.onCreate()");
//TableUtils.createTable(connectionSource, CategoryModel.class);
//TableUtils.createTable(connectionSource, RecipeModel.class);
//TableUtils.createTable(connectionSource, IngredientModel.class);
}
catch(android.database.SQLException e)
{
Logcat.e("DatabaseHelper.onCreate(): can't create database", e);
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion)
{
try
{
Logcat.d("DatabaseHelper.onUpgrade()");
}
catch(android.database.SQLException e)
{
Logcat.e("DatabaseHelper.onUpgrade(): can't upgrade database", e);
e.printStackTrace();
}
}
#Override
public void close()
{
super.close();
mCategoryDao = null;
mRecipeDao = null;
mIngredientDao = null;
}
public synchronized void clearDatabase()
{
try
{
Logcat.d("DatabaseHelper.clearDatabase()");
TableUtils.dropTable(getConnectionSource(), CategoryModel.class, true);
TableUtils.dropTable(getConnectionSource(), RecipeModel.class, true);
TableUtils.dropTable(getConnectionSource(), IngredientModel.class, true);
TableUtils.createTable(getConnectionSource(), CategoryModel.class);
TableUtils.createTable(getConnectionSource(), RecipeModel.class);
TableUtils.createTable(getConnectionSource(), IngredientModel.class);
}
catch(android.database.SQLException e)
{
Logcat.e("DatabaseHelper.clearDatabase(): can't clear database", e);
e.printStackTrace();
}
catch(java.sql.SQLException e)
{
Logcat.e("DatabaseHelper.clearDatabase(): can't clear database", e);
e.printStackTrace();
}
}
public synchronized Dao<CategoryModel, Long> getCategoryDao() throws java.sql.SQLException
{
if(mCategoryDao==null)
{
mCategoryDao = getDao(CategoryModel.class);
}
return mCategoryDao;
}
public synchronized Dao<RecipeModel, Long> getRecipeDao() throws java.sql.SQLException
{
if(mRecipeDao==null)
{
mRecipeDao = getDao(RecipeModel.class);
}
return mRecipeDao;
}
public synchronized Dao<IngredientModel, Long> getIngredientDao() throws java.sql.SQLException
{
if(mIngredientDao==null)
{
mIngredientDao = getDao(IngredientModel.class);
}
return mIngredientDao;
}
private boolean databaseExists()
{
File file = new File(DATABASE_PATH + DATABASE_NAME);
boolean exists = file.exists();
Logcat.d("DatabaseHelper.databaseExists(): " + exists);
return exists;
}
private boolean copyPrepopulatedDatabase()
{
String locale = java.util.Locale.getDefault().getDisplayName();
// copy database from assets
try
{
// create directories
File dir = new File(DATABASE_PATH);
dir.mkdirs();
// output file name
String outputFileName = DATABASE_PATH + DATABASE_NAME;
Logcat.d("DatabaseHelper.copyDatabase(): " + outputFileName);
// create streams
InputStream inputStream = CookbookApplication.getContext().getAssets().open(DATABASE_NAME);
OutputStream outputStream = new FileOutputStream(outputFileName);
// write input to output
byte[] buffer = new byte[1024];
int length;
while((length = inputStream.read(buffer))>0)
{
outputStream.write(buffer, 0, length);
}
// close streams
outputStream.flush();
outputStream.close();
inputStream.close();
return true;
}
catch(IOException e)
{
e.printStackTrace();
return false;
}
}
private int getVersion()
{
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(CookbookApplication.getContext());
return sharedPreferences.getInt(PREFS_KEY_DATABASE_VERSION, 0);
}
private void setVersion(int version)
{
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(CookbookApplication.getContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(PREFS_KEY_DATABASE_VERSION, version);
editor.commit();
}
}

How do I save a custom class object data model to a different file each time it is made in java?

I have a custom ListView that uses an object class for its data. The users can add new items to the listview, the arraylist is then saved in SharedPreferences. However, I also want to save each individual item so that I can use it in another Expandable ListView, how could I create a file for each individual item the user creates, or perhaps there is a better why to do it? Thanks in advance. Here is the object class:
public class Item implements Serializable{
String homework, date, classes;
public Item(String homework, String date, String classes){
this.homework = homework;
this.date = date;
this.classes = classes;
}
public String getHomework(){
return homework;
}
public String getDate(){
return date;
}
public String getClasses(){
return classes;
}
}
Why not use a database?There is a bit of setting up, but after the initial set up writing/reading data is very easy.
https://developer.android.com/training/basics/data-storage/databases.html
An example of serialize-deserialize class
public final class Serialize
{
private static final String className = Serialize.class.getName();
public static void save(Object saveThis, String serializeFileName, Context context)
{
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try
{
if(saveThis != null)
{
fos = context.openFileOutput(serializeFileName, Context.MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
oos.writeObject(saveThis);
}
}
catch(Throwable t)
{
//log it
}
finally
{
if(oos != null)
{
try{oos.close();}catch(Throwable t){}
}
if(fos != null)
{
try{fos.close();}catch(Throwable t){}
}
}
}
public static Object read(String serializeFileName, Context context)
{
FileInputStream fis = null;
ObjectInputStream ois = null;
Object readThis = null;
try
{
File file = context.getFileStreamPath(serializeFileName);
if(file != null && file.exists())
{
fis = context.openFileInput(serializeFileName);
ois = new ObjectInputStream(fis);
readThis = ois.readObject();
}
}
catch(Throwable t)
{
//log it
}
finally
{
if(ois != null)
{
try{ois.close();}catch(Throwable t){}
}
if(fis != null)
{
try{fis.close();}catch(Throwable t){}
}
}
return readThis;
}
public static boolean delete(String serializeFileName, Context context)
{
boolean deleted = false;
try
{
File file = context.getFileStreamPath(serializeFileName);
if(file != null && (file.exists()))
{
deleted = file.delete();
}
}
catch(Throwable t)
{
//log it
}
return deleted;
}
public static boolean exist(String serializeFileName, Context context)
{
boolean exist = false;
try
{
File file = context.getFileStreamPath(serializeFileName);
if(file != null && (file.exists()))
{
exist = true;
}
}
catch(Throwable t)
{
//log it
}
return exist;
}
}
Use the save method to save the serializable object in a file and the read method to read it.

read serializable custom object into file android

i am trying to record and reab back my list into file. It's working great until I restart my application. I am working with simulator (I don't have a real phone under Android)
Here is my function to record my class into a file :
public boolean writeRecordsToFile(String path, DummyContent object){
FileOutputStream fos;
ObjectOutputStream oos = null;
try {
fos = fileContext.openFileOutput(path, Context.MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
oos.writeObject(object);
oos.close();
Log.d("fileManager", "Records write successfully");
return true;
} catch (Exception e) {
Log.e("fileManager", "Cant save records : " + e.getMessage());
return false;
}
finally {
if (oos != null)
try {
oos.close();
} catch (Exception e) {
Log.e("fileManager", "Error while closing stream "+e.getMessage());
}
}
}
Here is my reading Function :
public boolean readRecordsFromFile(String path){
FileInputStream fin;
ObjectInputStream ois=null;
try {
fin = fileContext.openFileInput(path);
ois = new ObjectInputStream(fin);
DummyContent records = (DummyContent) ois.readObject();
records.addItem("test", "test", "test");
ois.close();
Log.d("fileManager", "Records read successfully :\n" + records.toString());
Log.d("fileManager", "nbArticle found : " + String.valueOf(records.ITEMS.size()));
Log.d("fileManager", "article 0 title :\n" + records.ITEMS.get(0).content);
Log.d("fileManager", "article 10 title :\n" + records.ITEMS.get(10).content);
return true;
} catch (Exception e) {
Log.e("fileManager", "Cant read saved records : "+e.getMessage());
return false;
}
finally {
if (ois != null)
try {
ois.close();
} catch (Exception e) {
Log.e("fileManager", "Error in closing stream while reading records : "+e.getMessage());
}
}
}
and here is my class :
public class DummyContent implements Serializable {
/**
* An array of sample (dummy) items.
*/
public static List<DummyItem> ITEMS = new ArrayList<DummyItem>();
/**
* A map of sample (dummy) items, by ID.
*/
public static Map<String, DummyItem> ITEM_MAP = new HashMap<String, DummyItem>();
public void addItem(String first, String second, String third) {
DummyItem dummyItem = new DummyItem(first, second, third, android.R.drawable.ic_input_add);
ITEMS.add(dummyItem);
ITEM_MAP.put(dummyItem.id, dummyItem);
}
public void deleteAll() {
ITEMS = new ArrayList<DummyItem>();
ITEM_MAP = new HashMap<String, DummyItem>();
}
public void changeURL(Long index, String newURL) {
ITEMS.get(index.intValue()).url = newURL;
}
public void changeContent(Long index, String newContent) {
ITEMS.get(index.intValue()).contenu = newContent;
}
/**
* A dummy item representing a piece of content.
*/
public static class DummyItem {
public final String id;
public final String content;
public final String details;
public final int imageResource;
public String url;
public String contenu;
public DummyItem(String id, String content, String details, int imageResource) {
this.id = id;
this.content = content;
this.details = details;
this.imageResource = imageResource;
this.url = "";
this.contenu = "";
}
#Override
public String toString() {
return content;
}
}
}
Finally I read my file at the onCreate of my MainActivity (first activity at the lunching app) :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fileManager = new FileManager(this.getApplicationContext());
Log.d("Main", String.valueOf(fileManager.fileExist("Article.art")));
fileManager.readRecordsFromFile("Article.art"); /* Bug here : size of my array is empty but file's size is the same */
}
Here is my console return :
D/fileManager: size = 102
D/fileManager: Records read successfully :
D/fileManager: nbArticle found : 1 (because i add an item at the read
function) E/fileManager: Cant read saved records : Index: 10, Size: 1
I know it is working because when I write and read directly after the writting, I got all my items and I can read several times and I still got all items (this bug semms to be only present when I restart my application)
Maybe can I got help ?
Thanks !
The reason is very easy: You have declared some field as static, which are not covered by standard serialization: So, the contents of these fields were never written nor read from the file. That's why they "dissapeared" after a JVM restart.
Any field you want to be serialized/deserialized, you must declare it as instance member (not static).
See documentation on Serializable.

LWUIT: How to open XHTML file from resource?

I want to open XHTML file which resides in resources. I tried with HTMLComponent of LWUIT. But it is opening only HTML files only. What would be correct way to open XHTML file using any LWUIT component.?
I tried with below code. Its working for HTML files with simple tags. Not working for all tags and attributes.
String htmlFileName = "index.html";
HTMLComponent htmlC = new HTMLComponent(new FileRequestHandler(HtmlScreen.this));
htmlC.setHTMLCallback(new SimpleHTMLCallback(this));
htmlC.setPage("jar://"+"/res/"+htmlFileName.trim());
FileRequestHandler.java:
class FileRequestHandler implements com.divaa.app.DocumentRequestHandler {
HtmlScreen htmlDemo;
static final String DEFAULT_RES = "images";
public FileRequestHandler(HtmlScreen htmlDemo) {
this.htmlDemo=htmlDemo;
}
public InputStream resourceRequested(DocumentInfo docInfo) {
String url=docInfo.getUrl();
// If a from was submitted on a local file, just display the parameters
if ((docInfo.getParams()!=null) && (!docInfo.getParams().equals(""))) {
String method="GET";
if (docInfo.isPostRequest()) {
method="POST";
}
String params=docInfo.getParams();
String newParams="";
if (params!=null) {
for(int i=0;i<params.length();i++) {
char c=params.charAt(i);
if (c=='&') {
newParams+=", ";
} else {
newParams+=c;
}
}
}
return getStream("<h2>Form submitted locally.</h2><b>Method:</b> "+method+"<br><br><b>Parameters:</b><br>"+newParams+"<hr>Continue to local URL","Form Results");
}
url=url.substring(6); // Cut the jar://
byte[] buf;
try {
buf = getBuffer(Display.getInstance().getResourceAsStream(getClass(), url));
if (url.endsWith(".html")) { //only set source to HTML files (not images)
htmlDemo.setSource(new String(getBuffer(new ByteArrayInputStream(buf))));
}
return new ByteArrayInputStream(buf);
} catch (Exception ex) {
System.out.println("ex.toString exception........ "+ex.toString());
ex.printStackTrace();
}
return null;
}
SimpleHTMLCallBack.java:
class SimpleHTMLCallback extends DefaultHTMLCallback {
HtmlScreen htmlDemo;
public SimpleHTMLCallback(HtmlScreen htmlDemo) {
this.htmlDemo=htmlDemo;
}
public boolean linkClicked(HTMLComponent htmlC, String url) {
return true; // Signals the HTMLComponent to prcoess this link as usual (i.e. call DocumentRequestHandler.resourceRequested)
}
public void titleUpdated(HTMLComponent htmlC, String title) {
htmlDemo.setTitle(title);
}
}
Thanks...

Categories