Restricting file upload if image isn't attached - jsf

I have a jsf form that takes an email address, brief description, and image from the user. The else statement below is completely ignored when file==null. If a picture isn't uploaded I want an error telling the user they have to upload a image. How do I accomplish this?
import org.primefaces.model.UploadedFile;
private UploadedFile file;
public UploadedFile getFile() {
return file;
}
public void setFile(UploadedFile file) {
this.file = file;
}
public String upload() {
if (file!=null ) {
try {
System.out.println(file.getFileName());
InputStream fin2 = file.getInputstream();
Connection con = DataConnect.getConnection();
PreparedStatement pre = con.prepareStatement("insert into PICTURE_TABLE (EMAIL_ADDRESS,PRICE,ITEM_DESC,PICTURES,DATE) values(?,?,?,?,?)");
pre.setString(1, email);
pre.setString(2, price);
pre.setString(3,itemDesc);
pre.setBinaryStream(4, fin2, file.getSize());
pre.setString(5,time);
pre.executeUpdate();
System.out.println("Inserting Successfully!");
}
catch (Exception e) {
System.out.println("Exception-File Upload." + e.getMessage());
return "imageFail";
}
}
else{
FacesMessage msg = new FacesMessage("Please select image!!");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
this is the jsf tag I'm using.
<h:form enctype="multipart/form-data"

Related

Bitmap compress quality ok in emulator, but not in real device

In my app, images are saving successfully to gallery after editing. but quality is not up to the mark on physical device. I got 0.5mp to 0.7mp highest. but same app I open in emulator and after saving image I got pretty good quality of images (about 1.5mp to 3mp). didn't find the exact reason of this. will be glad if you help to find out. attaching my image saving code below.
public void saveAsFile(#NonNull final String str, #NonNull final SaveSettings saveSettings, #NonNull final OnSaveListener onSaveListener) {
Log.d(TAG, "Image Path: " + str);
this.parentView.saveFilter((OnSaveBitmap) new OnSaveBitmap() {
#Override
public void onBitmapReady(Bitmap bitmap) {
new AsyncTask<String, String, Exception>() {
#Override
public void onPreExecute() {
super.onPreExecute();
PhotoEditor.this.clearHelperBox();
PhotoEditor.this.parentView.setDrawingCacheEnabled(false);
}
#SuppressLint({"MissingPermission"})
public Exception doInBackground(String... strArr) {
Bitmap bitmap;
try {
FileOutputStream fileOutputStream = new FileOutputStream(new File(str), false);
if (PhotoEditor.this.parentView != null) {
PhotoEditor.this.parentView.setDrawingCacheEnabled(true);
if (saveSettings.isTransparencyEnabled()) {
bitmap = BitmapUtil.removeTransparency(PhotoEditor.this.parentView.getDrawingCache());
} else {
bitmap = PhotoEditor.this.parentView.getDrawingCache();
}
bitmap.compress(Bitmap.CompressFormat.PNG, 100 , fileOutputStream);
}
Log.d(PhotoEditor.TAG, "Filed Saved Successfully");
return null;
} catch (Exception e) {
e.printStackTrace();
Log.d(PhotoEditor.TAG, "Failed to save File");
return e;
}
}
#Override
public void onPostExecute(Exception exc) {
super.onPostExecute(exc);
if (exc == null) {
if (saveSettings.isClearViewsEnabled()) {
PhotoEditor.this.clearAllViews();
}
onSaveListener.onSuccess(str);
return;
}
onSaveListener.onFailure(exc);
}
}.execute();
}
public void onFailure(Exception exc) {
onSaveListener.onFailure(exc);
}
});
}
I tried in many ways but couldn't find the solution.

Download File using download manager and save file based on click

I have my download manager, and it work perfect if I try to download a file. But I have a problem.
I have 4 CardView in my activity and I set it onClickListener, so when I click one CardView it will download the file.
Here is the code to call the download function
cardviewR1 = findViewById(R.id.card_viewR1);
cardviewR1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pDialogDL = new ProgressDialog(this);
pDialogDL.setMessage("A message");
pDialogDL.setIndeterminate(true);
pDialogDL.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialogDL.setCancelable(true);
final DownloadTask downloadTask = new DownloadTask(this);
downloadTask.execute(R1Holder);
pDialogDL.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
downloadTask.cancel(true);
}
});
}
});
and here is the download function
private class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private PowerManager.WakeLock mWakeLock;
public DownloadTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/"+getString(R.string.r1)+"_"+NameHolder+".zip");
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
pDialogDL.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
pDialogDL.setIndeterminate(false);
pDialogDL.setMax(100);
pDialogDL.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
mWakeLock.release();
pDialogDL.dismiss();
if (result != null)
Toast.makeText(context, "Download error: " + result, Toast.LENGTH_LONG).show();
else
Toast.makeText(context, "File downloaded", Toast.LENGTH_SHORT).show();
}
}
The code work in my app, but the problem is, when I try to add second CardView which is like this
cardviewR2 = findViewById(R.id.card_viewR2);
cardviewR2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pDialogDL = new ProgressDialog(this);
pDialogDL.setMessage("A message");
pDialogDL.setIndeterminate(true);
pDialogDL.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialogDL.setCancelable(true);
final DownloadTask downloadTask = new DownloadTask(this);
downloadTask.execute(R2Holder);
pDialogDL.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
downloadTask.cancel(true);
}
});
}
});
Yes it will download the second file, but it will overwrite the first file. I think the problem is right here
output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/"+getString(R.string.r1)+"_"+NameHolder+".zip");
Anyone can help me with this code?
I need your help, Thanks
Fixed it by create a new Download Class separately in different file with activity, so the AsyncTask will be call again and again
thanks

Xpages: 'RichText' field on web and saving with java bean

I have a requirement to allow users to enter 'RichText' in a field in an Xpages form on the web. It is just rich text (bold, size, color) no attachments/links/pictures. And no need to edit it on the client.
I have googled this and put together something that kind of is close, but doesn't work. I am only trying to get a minimal working example right now.
Used some info in this link and in another one I cannot find right now.
Any help would be greatly appreciated.
Xpage:
<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core"
xmlns:xe="http://www.ibm.com/xsp/coreex">
<xp:messages id="messages1"></xp:messages>
<xp:panel id="pnlAll">
<xp:this.data>
<xe:objectData saveObject="#{javascript:docModel.save()}"
var="docModel">
<xe:this.createObject><![CDATA[#{javascript:var docModel = new com.scoular.model.Doc();
var unid = sessionScope.get("key");
if (unid != null) {
docModel.loadByUnid(unid);
sessionScope.put("key","");
viewScope.put("readOnly","Yes");
} else {
docModel.create();
viewScope.put("readOnly","No");
}
return docModel;}]]></xe:this.createObject>
</xe:objectData>
</xp:this.data>
<xp:inputRichText id="inputRichText1"
value="#{docModel.body}">
</xp:inputRichText>
<xp:button value="Save"
id="button1"
type="button"
styleClass="btn-primary">
<xp:eventHandler event="onclick" submit="true"
refreshMode="complete" save="true">
<xp:this.action><![CDATA[#{javascript:if (docModel.save() == true) {
}}]]></xp:this.action>
</xp:eventHandler>
</xp:button>
</xp:panel>
</xp:view>
Java:
package com.scoular.model;
import java.io.Serializable;
import java.util.Date;
import org.openntf.domino.Database;
import lotus.domino.MIMEEntity;
import lotus.domino.Stream;
import org.openntf.domino.DateTime;
import org.openntf.domino.Document;
import org.openntf.domino.Session;
import org.openntf.domino.utils.Factory;
import org.openntf.domino.xsp.XspOpenLogUtil;
public class Doc implements Serializable {
private static final long serialVersionUID = -5867831497684227875L;
private com.ibm.xsp.http.MimeMultipart body;
// Common Fields
private String unid;
private Boolean newNote;
private DateTime crtDte;
private String crtUsr;
public Doc() {
}
public void create() {
try {
newNote = true;
Session session = Factory.getSession();
Date date = new Date();
crtDte = session.createDateTime(date);
crtUsr = session.getEffectiveUserName();
} catch (Exception e) {
XspOpenLogUtil.logError(e);
}
}
public void loadByUnid(String unid) {
try {
Session session = Factory.getSession();
String DataDBpath = session.getCurrentDatabase().getServer() + "!!" + "scoApps\\Spectrum\\cashmarkData.nsf";
Database DataDB = session.getDatabase(DataDBpath);
Document doc = DataDB.getDocumentByUNID(unid);
if (null == doc) {
System.out.println("Document not found");
} else {
loadValues(doc);
}
} catch (Exception e) {
XspOpenLogUtil.logError(e);
}
}
public void loadValues(Document doc) {
try {
// common fields
newNote = false;
unid = doc.getUniversalID();
crtDte = doc.getItemValue("checkInDate", DateTime.class);
crtUsr = doc.getItemValueString("crtUsr");
// custom fields
} catch (Exception e) {
XspOpenLogUtil.logError(e);
}
}
public boolean save() {
boolean tmpSave = true;
try {
Document doc = null;
Session session = Factory.getSession();
String DataDBpath = session.getCurrentDatabase().getServer() + "!!" + "scoApps\\Spectrum\\cashmarkData.nsf";
Database DataDB = session.getDatabase(DataDBpath);
if (newNote) {
doc = DataDB.createDocument();
doc.put("form", "doc");
} else {
doc = DataDB.getDocumentByUNID(unid);
}
//Create the body as a MIME entity
session.setConvertMIME(false); // Do not convert MIME to RT MIMEEntity body = doc.createMIMEEntity("body");
Stream stream = session.createStream();
stream.writeText("<ul><li>hello</li><li>world</li></ul>Google");
//body.setContentFromText(stream, "text/html;charset=UTF-8", MIMEEntity.ENC_IDENTITY_7BIT);
stream.close();
doc.save();
} catch (Exception e) {
XspOpenLogUtil.logError(e);
}
return tmpSave;
}
// Getters and Setters for common fields
public String getUnid() {
return unid;
}
public void setUnid(String unid) {
this.unid = unid;
}
public Boolean getNewNote() {
return newNote;
}
public void setNewNote(Boolean newNote) {
this.newNote = newNote;
}
public DateTime getCrtDte() {
return crtDte;
}
public void setCrtDte(DateTime crtDte) {
this.crtDte = crtDte;
}
public String getCrtUsr() {
return crtUsr;
}
public void setCrtUsr(String crtUsr) {
this.crtUsr = crtUsr;
}
public com.ibm.xsp.http.MimeMultipart getBody() {
return body;
}
public void setbody(com.ibm.xsp.http.MimeMultipart body) {
this.body = body;
}
}
To save your MimeMultipart to a MimeEntity field give this a try:
String fieldName = "yourFieldName";
if (doc.hasItem(fieldName))
doc.removeItem(fieldName);
Stream stream = session.createStream();
stream.writeText(body.getHTML());
MIMEEntity mimeEnt = doc.createMIMEEntity(fieldName);
mimeEnt.setContentFromText(stream,
"text/html;charset=UTF-8", MIMEntity.ENC_NONE);
stream.close();
stream.recycle();
Also you may want to remove some CKEditor plugins by adding a dojoAttribute called 'removePlugins'
<xp:inputRichText id="inputRichText1">
<xp:this.dojoAttributes>
<xp:dojoAttribute name="removePlugins"
value="ibmxspimage,smiley,ibmsametimeemoticons"></xp:dojoAttribute>
</xp:this.dojoAttributes>
</xp:inputRichText>
This will remove the toolbar buttons that allow the user to choose emoticons / upload images (which will cause an error)
Note however this will not prevent users from trying to paste Images into the CKEditor, to prevent that you need to make/obtain a custom CKEditor plugin that prevents pasting images both via a 'Data URL' (clipboard paste) or via 'Href' e.g. web address based images.

Stream closed Exception

I'm getting Stream is closed Exception when I'm going to save the uploaded image.
I'm tring to preview graphicImage of uploaded image the before save. This operation is working. But I can't save the image. Here is my code:
private InputStream in;
private StreamedContent filePreview;
// getters and setters
public void upload(FileUploadEvent event)throws IOException {
// Folder Creation for upload and Download
File folderForUpload = new File(destination);//for Windows
folderForUpload.mkdir();
file = new File(event.getFile().getFileName());
in = event.getFile().getInputstream();
filePreview = new DefaultStreamedContent(in,"image/jpeg");
FacesMessage msg = new FacesMessage("Success! ", event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void setFilePreview(StreamedContent fileDownload) {
this.filePreview = fileDownload;
}
public StreamedContent getFilePreview() {
return filePreview;
}
public void saveCompanyController()throws IOException{
OutputStream out = new FileOutputStream(getFile());
byte buf[] = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
out.write(buf, 0, len);
FileMasterDO fileMasterDO=new FileMasterDO();
fileMasterDO.setFileName(getFile().getName());
fileMasterDO.setFilePath(destination +file.getName());
fileMasterDO.setUserMasterDO(userMasterService.findUserId(UserBean.getUserId()));
fileMasterDO.setUpdateTimeStamp(new Date());
in.close();
out.flush();
out.close();
fileMasterService.save(filemaster);
}
The bean is in the session scope.
You're trying to read an InputStream twice (the first time is in DefaultStreamedContent constructor of upload method and the second time is in the copy loop of the save method). This is not possible. It can be read only once. You need to read it into a byte[] first and then assign it as a bean property so that you can reuse it for both the StreamedContent and the save.
Make sure that you never hold external resources such as InputStream or OutputStream as a bean property. Remove them all from the current and other beans where applicable and use byte[] to hold the image's content as property.
In your particular case, you need to fix it as follows:
private byte[] bytes; // No getter+setter!
private StreamedContent filePreview; // Getter only.
public void upload(FileUploadEvent event) throws IOException {
InputStream input = event.getFile().getInputStream();
try {
IOUtils.read(input, bytes);
} finally {
IOUtils.closeQuietly(input);
}
filePreview = new DefaultStreamedContent(new ByteArrayInputStream(bytes), "image/jpeg");
// ...
}
public void saveCompanyController() throws IOException {
OutputStream output = new FileOutputStream(getFile());
try {
IOUtils.write(bytes, output);
} finally {
IOUtils.closeQuietly(output);
}
// ...
}
Note: IOUtils is from Apache Commons IO, which you should already have in the classpath as it's a dependency of <p:fileUpload>.

How to work with LWUIT TABs click events

UPDATE:
My Requirement is to display two Rss files as Tabs on my LWUIT Form
Initially by default first Rss file titles and images should be displayed on first tab
if an end user click on second tab,we should be able to load the second rss file titles and images
I am able to load first Rss File titles,but i am not able to load the second tab if i click on it
How to capture the click event for LWUIT Tab?
Here my code which is not working:
String topNewsurl="TopNews.rss";
String topStoryurl="TopStory.rss";
public class XMLMidlet extends MIDlet{
public void startApp() {
Display.init(this);
Process p;
try {
p = new Process(this);
p.process();
} catch (IOException ex) {
ex.printStackTrace();
}
}
public class Process extends Form {
Process(XMLMidlet midlet) throws IOException {
this.midlet=midlet;
topnews = new Vector();
topstory = new Vector();
tabs = new Tabs();
form1 = new Form();
form2=new Form();
form1.setLayout(new BorderLayout());
form1.setScrollable(false);
image = Image.createImage("/res/Tone.jpg");
Label icon = new Label(image);
form1.setTitleComponent(icon);
form2.setTitleComponent(icon);
form1.setTransitionInAnimator(Transition3D.createRotation(250, true));
try {
newsList = new List(topnews);
newsList.setScrollVisible(false);
newsList.setRenderer(new NewsListCellRenderer());
myNewsList = new List(topstory);
myNewsList.setScrollVisible(false);
myNewsList.setRenderer(new NewsListCellRenderer());
tabs.addTab("Topstory", newsList);
tabs.addTab("TopNews", myNewsList);
tabs.setChangeTabOnFocus(true);
form1.addComponent(BorderLayout.CENTER, tabs);
}
try{
String url = "http:topnews-20.rss";
form1.show();
ParseThread myThread = new ParseThread(this);
myThread.getXMLFeed(url);
} catch (Exception e) {
e.printStackTrace();
}
}
public void addNews(News newsItem) {
//log.debug("addnews");
//System.out.println("addNews");
topnews.addElement(newsItem);
newsList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
List source = (List) ae.getSource();
News selectedNewsItem = (News) source.getSelectedItem();
if (selectedNewsItem != null) {
displayCompleteNewsScreen(selectedNewsItem);
}
}
});
form1.show();
}
public void keyReleased(int keyCode) {
System.out.println("str");
Component p=this.getFocused();
String str= p.getClass().getName();
if(str.toLowerCase().indexOf("radiobutton")!=-1){
process();
}
From the very vague question it seems you want to capture key presses on a LWUIT Form.
jobsForm.addGameKeyListener(Display.GAME_FIRE,
new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//do something here
}
});
jobsForm.addPointerPressedListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
pointer_click = true;
}
});
jobsForm.addPointerReleasedListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (pointer_click) {
//
}
pointer_click = false;
}
});
jobsForm.addPointerDraggedListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//System.out.println("POINTER DRAGGED");
pointer_click = false;
}
});

Resources