java.io.IOException: Stream closed - java

For multiple image retrieval I am calling a PhotoHelperServlet with an anchor tag to get imageNames(multiple images) as follows
PhotoHelperServlet to get names of Images
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Getting userid from session
Image image = new Image();
image.setUserid(userid);
ImageDAO imageDAO = new ImageDAO();
try {
List<Image> imageId = imageDAO.listNames(image);
if (imageId == null) {
// check if imageId is retreived
}
request.setAttribute("imageId", imageId);
//Redirect it to home page
RequestDispatcher rd = request.getRequestDispatcher("/webplugin/jsp/profile/photos.jsp");
rd.forward(request, response);
catch (Exception e) {
e.printStackTrace();
}
In ImageDAO listNames() method :
public List<Image> listNames(Image image) throws IllegalArgumentException, SQLException, ClassNotFoundException {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultset = null;
Database database = new Database();
List<Image> imageId = new ArrayList<Image>();
try {
connection = database.openConnection();
preparedStatement = connection.prepareStatement(SQL_GET_PHOTOID);
preparedStatement.setLong(1, image.getUserid());
resultset = preparedStatement.executeQuery();
while(resultset.next()) {
image.setPhotoid(resultset.getLong(1));
imageId.add(image);
}
} catch (SQLException e) {
throw new SQLException(e);
} finally {
close(connection, preparedStatement, resultset);
}
return imageId;
}
In JSP code:
<c:forEach items="${imageId}" var="imageid">
<img src="Photos/${imageid}">
</c:forEach>
In PhotoServlet doGet() method to get a photo:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String imageid = request.getPathInfo().substring(1);
if(imageid == null) {
// check for null and response.senderror
}
ImageDAO imageDAO = new ImageDAO();
try {
Image image = imageDAO.getPhotos(imageid);
if(image == null) {}
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(image.getPhoto(), 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 {
if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
}
} catch(Exception e) {
e.printStackTrace();
}
In ImageDAO getPhotos() method
public Image getPhotos(String imageid) throws IllegalArgumentException, SQLException, ClassNotFoundException {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultset = null;
Database database = new Database();
Image image = new Image();
try {
connection = database.openConnection();
preparedStatement = connection.prepareStatement(SQL_GET_PHOTO);
preparedStatement.setString(1, imageid);
resultset = preparedStatement.executeQuery();
while(resultset.next()) {
image.setPhoto(resultset.getBinaryStream(1));
}
} catch (SQLException e) {
throw new SQLException(e);
} finally {
close(connection, preparedStatement, resultset);
}
return image;
}
In web.xml
<!-- Getting each photo -->
<servlet>
<servlet-name>Photos Module</servlet-name>
<servlet-class>app.controllers.PhotoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Photos Module</servlet-name>
<url-pattern>/Photos/*</url-pattern>
</servlet-mapping>
<!-- Getting photo names -->
<servlet>
<servlet-name>Photo Module</servlet-name>
<servlet-class>app.controllers.PhotoHelperServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Photo Module</servlet-name>
<url-pattern>/Photo</url-pattern>
</servlet-mapping>
Question:
I am getting following Exception:
java.io.IOException: Stream closed
on this Line:
at app.controllers.PhotoServlet.doGet(PhotoServlet.java:94)
while ((length = input.read(buffer)) > 0) {
The full Exception:
java.io.IOException: Stream closed
at java.io.BufferedInputStream.getInIfOpen(BufferedInputStream.java:134)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:256)
at java.io.BufferedInputStream.read(BufferedInputStream.java:317)
at java.io.FilterInputStream.read(FilterInputStream.java:90)
at app.controllers.PhotoServlet.doGet(PhotoServlet.java:94)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)

I'd imagine that the basic code flow is laid out like follows:
try {
Get connection, statement, resultset
Use connection, statement, resultset
Get inputstream of resultset
} finally {
Close resultset, statement, connection
}
try {
Get outputstream
Use inputstream of resultset, outputstream
} finally {
Close outputstream, inputstream of resultset
}
And that the close of the ResultSet has implicitly closed the InputStream. It look like that your JDBC driver does not store the InputStream of the ResultSet fully in memory or on temp storage when the ResultSet is closed. Perhaps the JDBC driver is a bit simplistic, or not well thought designed, or the image is too large to be stored in memory. Who knows.
I'd first figure out what JDBC driver impl/version you're using and then consult its developer documentation to learn about settings which may be able to change/fix this behaviour. If you still can't figure it out, then you'd have to rearrange the basic code flow as follows:
try {
Get connection, statement, resultset
Use connection, statement, resultset
try {
Get inputstream of resultset, outputstream
Use inputstream of resultset, outputstream
} finally {
Close outputstream, inputstream of resultset
}
} finally {
Close resultset, statement, connection
}
Or
try {
Get connection, statement, resultset
Use connection, statement, resultset
Get inputstream of resultset
Copy inputstream of resultset
} finally {
Close resultset, statement, connection
}
try {
Get outputstream
Use copy of inputstream, outputstream
} finally {
Close outputstream, copy of inputstream
}
The first approach is the most efficient, only the code is clumsy. The second approach is memory inefficient when you're copying to ByteArrayOutputStream, or performance inefficient when you're copying to FileOutputStream. If the images are mostly small and do not exceed a megabyte or something, then I'd just copy it to ByteArrayOutputStream.
InputStream input = null;
OutputStream output = null;
try {
input = new BufferedInputStream(resultSet.getBinaryStream("columnName"), DEFAULT_BUFFER_SIZE);
output = new ByteArrayOutputStream();
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
for (int length; ((length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
} finally {
if (output != null) try { output.close(); } catch (IOException ignore) {}
if (input != null) try { input.close(); } catch (IOException ignore) {}
}
Image image = new Image();
image.setPhoto(new ByteArrayInputStream(output.toByteArray()));
// ...

参考一下:
ImageLoad
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
/**
* 图片加载帮助类(自动异步加载、图片文件缓存、缓存文件管理)
*
* #author n.zhang
*
*/
public class ImageLoad {
private static final String TAG = "imageLoad";// 日志标签
private static final String TAG_REF = TAG + "Ref";
private Executor executor; // 线程池
private int defaultImageID;// 默认图片id
private Context context;// 你懂的
private HashMap<String, PathInfo> cache = new HashMap<String, PathInfo>();// URL
boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); // 路径信息对应表
private LinkedList<PathInfo> use = new LinkedList<PathInfo>();// 已在使用的路径信息队列
private LinkedList<PathInfo> lost = new LinkedList<PathInfo>();// 还未使用的路径信息队列
private LinkedList<PathInfo> original = new LinkedList<PathInfo>();// 初始图片路径信息队列
private int index = 0;// id下标
/**
* 图片加载工具,默认10线程下载,缓存80张图片
*
* #param context
*/
public ImageLoad(Context context) {
this(context, 10, 80, 0);
}
/**
* 图片加载工具
*
* #param context
* 你懂的
* #param threadSize
* 最大线程数
* #param maxCacheSize
* 最大缓存图片数量
* #param defaultImageID
* 默认图片id
*/
public ImageLoad(Context context, int threadSize, int maxCacheSize, int defaultImageID) {
this.context = context;
this.defaultImageID = defaultImageID;
executor = Executors.newFixedThreadPool(threadSize);
loadImagePathInfo();
// 图片信息数量不足不满最大值,以空白图片信息补足。
newImagePathInfo(maxCacheSize);
for (PathInfo pi : original) {
if (null == pi.url) {
lost.offer(pi);
} else {
use.offer(pi);
cache.put(pi.url, pi);
}
}
File dir = null;
if (sdCardExist) {
dir = new File(Environment.getExternalStorageDirectory() + "/t_image/");
} else {
dir = new File(context.getCacheDir() + "/t_image/");
}
// 如果文件存在并且不是目录,则删除
if (dir.exists() && !dir.isDirectory()) {
dir.delete();
}
// 如果目录不存在,则创建
if (!dir.exists()) {
dir.mkdir();
}
}
/**
* 路径信息
*
* #author n.zhang
*
*/
public static class PathInfo {
private int id;// 图片id 此id用于生成存储图片的文件名。
private String url;// 图片url
}
/**
* 获得图片存储路径
*
* #param url
* #return
*/
public PathInfo getPath(String url) {
PathInfo pc = cache.get(url);
if (null == pc) {
pc = lost.poll();
}
if (null == pc) {
pc = use.poll();
refresh(pc);
}
return pc;
}
/**
* #info 微博使用加载数据路径
* #author FFMobile-cuihe
* #date 2012-3-1 下午2:13:10
* #Title: getsPath
* #Description: TODO
* #param#param url
* #param#return 设定文件
* #return PathInfo 返回类型
* #throws
*/
public PathInfo getsPath(String url) {
PathInfo pc = cache.get(url);
if (null == pc) {
pc = lost.peek();
}
// if (null == pc) {
// pc = use.peek();
// refresh(pc);
// }
return pc;
}
public PathInfo getLocalPath(String url) {
PathInfo pc = cache.get(url);
if (null == pc) {
pc = lost.peek();
}
return pc;
}
/**
* 刷新路径信息(从索引中删除对应关系、删除对应的图片文件、获取一个新id)
*
* #param pc
*/
private void refresh(PathInfo pc) {
long start = System.currentTimeMillis();
File logFile = null;
try {
cache.remove(pc.url);
File file = toFile(pc);
file.delete();
logFile = file;
pc.id = index++;
pc.url = null;
} finally {
Log.d(TAG_REF, "ref time {" + (System.currentTimeMillis() - start) + "}; ref {" + logFile + "}");
}
}
/**
* 获得file对象
*
* #param pi
* 路径缓存
* #return
*/
public File toFile(PathInfo pi) {
if (sdCardExist) {
return new File(Environment.getExternalStorageDirectory() + "/t_image/" + pi.id + ".jpg");
} else {
return new File(context.getCacheDir() + "/t_image/" + pi.id + ".jpg");
}
}
/**
* 请求加载图片
*
* #param url
* #param ilCallback
*/
public void request(String url, final ILCallback ilCallback) {
final long start = System.currentTimeMillis();
final PathInfo pc = getPath(url);
File file = toFile(pc);
if (null != pc.url) {
ilCallback.seed(Uri.fromFile(file));
Log.d(TAG, "load time {" + (System.currentTimeMillis() - start) + "}; cache {" + pc.url + "} ");
} else {
pc.url = url;
Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
if (null == msg.obj) {
ilCallback.seed(Uri.EMPTY);
Log.d(TAG, "load lost time {" + (System.currentTimeMillis() - start) + "}; network lost {"
+ pc.url + "}");
} else {
ilCallback.seed((Uri) msg.obj);
Log.d(TAG, "load time {" + (System.currentTimeMillis() - start) + "}; network {" + pc.url + "}");
}
};
};
executor.execute(new DownloadImageTask(pc, file, mHandler));
}
}
private void localRequest(String url, final ILCallback ilCallback) {
final long start = System.currentTimeMillis();
final PathInfo pc = getLocalPath(url);
File file = toFile(pc);
if (null != pc.url) {
ilCallback.seed(Uri.fromFile(file));
Log.d(TAG, "load time {" + (System.currentTimeMillis() - start) + "}; cache {" + pc.url + "} ");
}
}
public void localRequest(String url, ImageView iv) {
localRequest(url, new ImageViewCallback(iv));
}
/**
* 请求加载图片
*
* #param url
* #param iv
*/
public void request(String url, ImageView iv) {
request(url, new ImageViewCallback(iv));
}
/**
* 请求加载图片
*
* #param url
* #param iv
*/
// public void request(String url, ImageButton iv) {
// request(url, new ImageButtonCallbacks(iv));
// }
/**
* 请求加载图片
*
* #param url
* #param iv
*/
// public void request(String url, Button iv) {
// request(url, new ButtonCallbacks(iv));
// }
/**
* 请求加载图片
*
* #param url
* #param iv
*/
public void request(String url, ImageSwitcher iv) {
request(url, new ImageSwitcherCallbacks(iv));
}
/**
* 下载图片任务
*
* #author Administrator
*
*/
private class DownloadImageTask implements Runnable {
private Handler hc;
private PathInfo pi;
private File file;
public DownloadImageTask(PathInfo pi, File file, Handler hc) {
this.pi = pi;
this.file = file;
this.hc = hc;
}
public void run() {
try {
byte[] b = requestHttp(pi.url);
if (null == b) {
throw new IOException("数据为空");
}
writeFile(file, b);
use.offer(pi);
cache.put(pi.url, pi);
Message message = new Message();
message.obj = Uri.fromFile(file);
hc.sendMessage(message);
} catch (IOException e) {
Message message = hc.obtainMessage(0, Uri.EMPTY);
hc.sendMessage(message);
Log.i(TAG, "image download lost.", e);
} catch (RuntimeException e) {
Message message = hc.obtainMessage(0, Uri.EMPTY);
hc.sendMessage(message);
Log.i(TAG, "image download lost.", e);
}
}
}
private void writeFile(File file, byte[] data) throws IOException {
FileOutputStream out = new FileOutputStream(file);
try {
out.write(data);
} finally {
out.close();
}
}
private static byte[] requestHttp(String url) throws IOException {
DefaultHttpClient client = new DefaultHttpClient();
System.gc();
try {
HttpGet get = new HttpGet(url);
HttpResponse res = client.execute(get);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (200 == res.getStatusLine().getStatusCode()) {
res.getEntity().writeTo(baos);
return baos.toByteArray();
} else {
throw new IOException("httpStatusCode:" + res.getStatusLine().getStatusCode());
}
} finally {
client.getConnectionManager().shutdown();
}
}
/**
* 读取图片路径信息
*
* #return
*/
#SuppressWarnings("unchecked")
private void loadImagePathInfo() {
long start = System.currentTimeMillis();
File file = new File(context.getCacheDir() + "/imagePathCache.json");
try {
if (!file.isFile()) {
// 文件不存在。
Log.d(TAG, "path info file does not exist");
imageGc();
return;
}
StringWriter sw = new StringWriter();
char[] buf = new char[1024];
int len;
FileReader fr = new FileReader(file);
while (-1 != (len = fr.read(buf))) {
sw.write(buf, 0, len);
}
fr.close();
JSONObject json = new JSONObject(sw.toString());
Iterator<String> it = json.keys();
while (it.hasNext()) {
String key = it.next();
int id = json.getInt(key);
PathInfo pi = new PathInfo();
pi.url = key;
pi.id = id;
if (index < id) {
index = id;
}
original.add(pi);
}
// 打开文件文件缓存成功
Log.i(TAG, "load path info ok.");
} catch (IOException e) {
Log.i(TAG, "load path info lost - IOException.", e);
imageGc();
} catch (JSONException e) {
Log.i(TAG, "load path info lost - JSONException.", e);
imageGc();
} finally {
if (file.exists()) {
file.delete();
Log.d(TAG, "delete path info file");
}
Log.d(TAG, "load path info time {" + (System.currentTimeMillis() - start) + "}");
}
}
/**
* 如果路径信息加载失败,清理图片目录。
*/
private void imageGc() {
long start = System.currentTimeMillis();
try {
File dir;
if (sdCardExist) {
dir = new File(Environment.getExternalStorageDirectory() + "/t_image/");
} else {
dir = new File(context.getCacheDir() + "/t_image/");
}
if (dir.isDirectory()) {
for (File file : dir.listFiles()) {
file.delete();
// gc
Log.d(TAG_REF, "gc {" + file + "}");
}
}
} finally {
// gc 计时
Log.d(TAG_REF, "gc time {" + (System.currentTimeMillis() - start) + "}");
}
}
private void newImagePathInfo(int max_size) {
for (int i = original.size(); i < max_size; i++) {
PathInfo pc = new PathInfo();
pc.id = index++;
original.add(pc);
}
}
/**
* 保存图片路径信息(如记录,下次程序打开,可读取该记录已存图片继续可用)
*/
public void saveImagePathInfo() {
long start = System.currentTimeMillis();
try {
JSONObject json = new JSONObject();
for (PathInfo pi : use) {
try {
json.put(pi.url, pi.id);
} catch (JSONException e) {
e.printStackTrace();
}
}
File file = new File(context.getCacheDir() + "/imagePathCache.json");
try {
FileWriter fw = new FileWriter(file);
fw.write(json.toString());
fw.close();
Log.i(TAG, "image file info save ok.");
} catch (IOException e) {
e.printStackTrace();
Log.i(TAG, "image file info save lost.");
file.delete();
}
} finally {
Log.d(TAG, "save time {" + (System.currentTimeMillis() - start) + "}");
}
}
/**
* 图片加载回调
*
* #author n.zhang
*
*/
public static interface ILCallback {
public void seed(Uri uri);
}
private class ImageViewCallback implements ILCallback {
public ImageViewCallback(ImageView iv) {
if (defaultImageID > 0) {
iv.setImageResource(defaultImageID);
}
this.iv = iv;
}
private ImageView iv;
public void seed(Uri uri) {
File f = new File(uri.getPath());
iv.setImageURI(Uri.parse(f.toString()));
f = null;
}
}
// private class ImageButtonCallbacks implements ILCallback {
// public ImageButtonCallbacks(ImageButton iv) {
// if (defaultImageID > 0) {
// iv.setBackgroundResource(defaultImageID);
////iv.setImageResource(defaultImageID);
// }
// this.iv = iv;
// }
//
// private ImageButton iv;
//
// public void seed(Uri uri) {
// iv.setImageURI(uri);
// }
// }
// private class ButtonCallbacks implements ILCallback {
// public ButtonCallbacks(Button iv) {
// if (defaultImageID > 0) {
// iv.setBackgroundResource(defaultImageID);
////iv.setImageResource(defaultImageID);
// }
// this.iv = iv;
// }
//
// private Button iv;
//
// public void seed(Uri uri) {
// iv.setImageURI(uri);
// }
// }
private class ImageSwitcherCallbacks implements ILCallback {
public ImageSwitcherCallbacks(ImageSwitcher iv) {
if (defaultImageID > 0) {
iv.setImageResource(defaultImageID);
}
this.iv = iv;
}
private ImageSwitcher iv;
public void seed(Uri uri) {
iv.setImageURI(uri);
}
}
}

It looks as if the problem is actually not in the code you posted. For some reason the stream input is closed. So you are probably closing the stream in image.getPhoto()

Related

Android - Zip Path Traversal in play store

I am uploading my App on play store but get me bellow error:
Zip Path Traversal Your app contains an unsafe unzipping pattern that
may lead to a Path Traversal vulnerability. Please see this Google
Help Center article to learn how to fix the issue.
org.apache.cordova.Zip.unzipSync
I edited my source code like this LINK, but get me error.
Here is my source code changed:
public class Zip extends CordovaPlugin {
private static final String LOG_TAG = "Zip";
// Can't use DataInputStream because it has the wrong endian-ness.
private static int readInt(InputStream is) throws IOException {
int a = is.read();
int b = is.read();
int c = is.read();
int d = is.read();
return a | b << 8 | c << 16 | d << 24;
}
#Override
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException {
if ("unzip".equals(action)) {
unzip(args, callbackContext);
return true;
}
return false;
}
private void unzip(final CordovaArgs args, final CallbackContext callbackContext) {
this.cordova.getThreadPool().execute(new Runnable() {
public void run() {
unzipSync(args, callbackContext);
}
});
}
private void unzipSync(CordovaArgs args, CallbackContext callbackContext) {
InputStream inputStream = null;
try {
String zipFileName = args.getString(0);
String outputDirectory = args.getString(1);
// Since Cordova 3.3.0 and release of File plugins, files are accessed via cdvfile://
// Accept a path or a URI for the source zip.
Uri zipUri = getUriForArg(zipFileName);
Uri outputUri = getUriForArg(outputDirectory);
CordovaResourceApi resourceApi = webView.getResourceApi();
File tempFile = resourceApi.mapUriToFile(zipUri);
if (tempFile == null || !tempFile.exists()) {
String errorMessage = "Zip file does not exist";
callbackContext.error(errorMessage);
Log.e(LOG_TAG, errorMessage);
return;
}
File outputDir = resourceApi.mapUriToFile(outputUri);
outputDirectory = outputDir.getAbsolutePath();
outputDirectory += outputDirectory.endsWith(File.separator) ? "" : File.separator;
if (outputDir == null || (!outputDir.exists() && !outputDir.mkdirs())) {
String errorMessage = "Could not create output directory";
callbackContext.error(errorMessage);
Log.e(LOG_TAG, errorMessage);
return;
}
OpenForReadResult zipFile = resourceApi.openForRead(zipUri);
ProgressEvent progress = new ProgressEvent();
progress.setTotal(zipFile.length);
inputStream = new BufferedInputStream(zipFile.inputStream);
inputStream.mark(10);
int magic = readInt(inputStream);
if (magic != 875721283) { // CRX identifier
inputStream.reset();
} else {
// CRX files contain a header. This header consists of:
// * 4 bytes of magic number
// * 4 bytes of CRX format version,
// * 4 bytes of public key length
// * 4 bytes of signature length
// * the public key
// * the signature
// and then the ordinary zip data follows. We skip over the header before creating the ZipInputStream.
readInt(inputStream); // version == 2.
int pubkeyLength = readInt(inputStream);
int signatureLength = readInt(inputStream);
inputStream.skip(pubkeyLength + signatureLength);
progress.setLoaded(16 + pubkeyLength + signatureLength);
}
// The inputstream is now pointing at the start of the actual zip file content.
ZipInputStream zis = new ZipInputStream(inputStream);
inputStream = zis;
ZipEntry ze;
byte[] buffer = new byte[32 * 1024];
boolean anyEntries = false;
while ((ze = zis.getNextEntry()) != null) {
try {
anyEntries = true;
String compressedName = ze.getName();
if (ze.isDirectory()) {
try {
File dir = new File(outputDirectory + compressedName);
File f = new File(dir, ze.getName());
String canonicalPath = f.getCanonicalPath();
if (!canonicalPath.startsWith(dir.toString())){
dir.mkdirs();
}else {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
}
}
}
} catch (Exception e) {
String errorMessage = "An error occurred while unzipping.";
callbackContext.error(errorMessage);
Log.e(LOG_TAG, errorMessage, e);
}
} else {
File file = new File(outputDirectory + compressedName);
File f = new File(file, ze.getName());
String canonicalPath = f.getCanonicalPath();
if (!canonicalPath.startsWith(file.toString())) {
file.getParentFile().mkdirs();
if (file.exists() || file.createNewFile()) {
try {
Log.w("Zip", "extracting: " + file.getPath());
FileOutputStream fout = new FileOutputStream(file);
int count;
while ((count = zis.read(buffer)) != -1) {
fout.write(buffer, 0, count);
}
fout.close();
} catch (Exception e) {
String errorMessage = "An error occurred while unzipping.";
callbackContext.error(errorMessage);
Log.e(LOG_TAG, errorMessage, e);
}
}
}else {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
}
}
}
}
progress.addLoaded(ze.getCompressedSize());
updateProgress(callbackContext, progress);
zis.closeEntry();
} catch (Exception e) {
String errorMessage = "An error occurred while unzipping.";
callbackContext.error(errorMessage);
Log.e(LOG_TAG, errorMessage, e);
}
}
// final progress = 100%
progress.setLoaded(progress.getTotal());
updateProgress(callbackContext, progress);
if (anyEntries)
callbackContext.success();
else
callbackContext.error("Bad zip file");
} catch (Exception e) {
String errorMessage = "An error occurred while unzipping.";
callbackContext.error(errorMessage);
Log.e(LOG_TAG, errorMessage, e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
}
}
}
}
private void updateProgress(CallbackContext callbackContext, ProgressEvent progress) throws JSONException {
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, progress.toJSONObject());
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);
}
private Uri getUriForArg(String arg) {
CordovaResourceApi resourceApi = webView.getResourceApi();
Uri tmpTarget = Uri.parse(arg);
return resourceApi.remapUri(
tmpTarget.getScheme() != null ? tmpTarget : Uri.fromFile(new File(arg)));
}
private static class ProgressEvent {
private long loaded;
private long total;
public long getLoaded() {
return loaded;
}
public void setLoaded(long loaded) {
this.loaded = loaded;
}
public void addLoaded(long add) {
this.loaded += add;
}
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
public JSONObject toJSONObject() throws JSONException {
return new JSONObject(
"{loaded:" + loaded +
",total:" + total + "}");
}
}
}

Discontinuous FTP download throws "Read timed out" or "Connection reset"

I used FTP and FTPClient in package 'org.apache.commons.net.ftp' to download files from FTP server.
Here is my total example code
public class FtpInput {
private static final Logger LOG = Logger.getLogger(FtpInput.class);
private static final int TIMEOUT = 120000;
private static final String SIZE_COMMAND_REPLY_CODE = "213 ";
/**
* FTPClient
*/
private FTPClient ftpClient;
/**
* FTP size
*/
private long completeFileSize = 0;
protected String ip = "";
protected int port = 21;
protected String user = "";
protected String passwd = "";
protected String path = "";
protected String fileName = "";
/**
* count input bytes
*/
private CountingInputStream is;
/**
* the bytes already processed
*/
private long processedBytesNum;
private byte[] inputBuffer = new byte[1024];
/**
* connect to ftp server and fetch inputStream
*/
public void connect() {
this.ftpClient = new FTPClient();
ftpClient.setRemoteVerificationEnabled(false);
try {
ftpClient.connect(ip, port);
if (!ftpClient.login(user, passwd)) {
throw new IOException("ftp login failed!");
}
if (StringUtils.isNotBlank(path)) {
if (!ftpClient.changeWorkingDirectory(path)) {
ftpClient.mkd(path);
if (!ftpClient.changeWorkingDirectory(path)) {
throw new IOException("ftp change working dir failed! path:" + path);
}
}
}
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setSoTimeout(TIMEOUT);
ftpClient.setConnectTimeout(TIMEOUT);
ftpClient.setDataTimeout(TIMEOUT);
ftpClient.enterLocalPassiveMode();
// keep control channel keep-alive when download large file
ftpClient.setControlKeepAliveTimeout(120);
} catch (Throwable e) {
e.printStackTrace();
throw new RuntimeException("ftp login failed!", e);
}
// get complete ftp size
completeFileSize = getFtpFileSize();
LOG.info(String.format("ftp file size: %d", completeFileSize));
try {
InputStream ftpis = this.ftpClient.retrieveFileStream(this.fileName);
if (ftpis == null) {
LOG.error("cannot fetch source file.");
}
this.is = new CountingInputStream(ftpis);
} catch (Throwable e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
/**
* readBytes
*
* #return
*/
public byte[] readBytes() {
byte[] bytes = readBytesFromStream(is, inputBuffer);
// the bytes processed
processedBytesNum = is.getCount();
return bytes;
}
/**
* readBytesFromStream
*
* #param stream
* #param inputBuffer
* #return
*/
protected byte[] readBytesFromStream(InputStream stream, byte[] inputBuffer) {
Preconditions.checkNotNull(stream != null, "InputStream has not been inited yet.");
Preconditions.checkArgument(inputBuffer != null && inputBuffer.length > 0);
int readBytes;
try {
readBytes = stream.read(inputBuffer);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (readBytes == inputBuffer.length) {
// inputBuffer is filled full.
return inputBuffer;
} else if (readBytes > 0 && readBytes < inputBuffer.length) {
// inputBuffer is not filled full.
byte[] tmpBytes = new byte[readBytes];
System.arraycopy(inputBuffer, 0, tmpBytes, 0, readBytes);
return tmpBytes;
} else if (readBytes == -1) {
// Read end.
return null;
} else {
// may other situation happens?
throw new RuntimeException(String.format("readBytesFromStream: readBytes=%s inputBuffer.length=%s",
readBytes, inputBuffer.length));
}
}
/**
* fetch the byte size of remote file size
*/
private long getFtpFileSize() {
try {
ftpClient.sendCommand("SIZE", this.fileName);
String reply = ftpClient.getReplyString().trim();
LOG.info(String.format("ftp file %s size reply : %s", fileName, reply));
Preconditions.checkArgument(reply.startsWith(SIZE_COMMAND_REPLY_CODE),
"ftp file size reply: %s is not success", reply);
String sizeSubStr = reply.substring(SIZE_COMMAND_REPLY_CODE.length());
long actualFtpSize = Long.parseLong(sizeSubStr);
return actualFtpSize;
} catch (Throwable e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
public void close() {
try {
if (is != null) {
LOG.info(String.format("already read %d bytes from ftp file %s", is.getCount(), fileName));
is.close();
}
if (ftpClient != null) {
// Must call completePendingCommand() to finish command.
boolean isSuccessTransfer = ftpClient.completePendingCommand();
if (!isSuccessTransfer) {
LOG.error("error happened when complete transfer of ftp");
}
ftpClient.logout();
ftpClient.disconnect();
}
} catch (Throwable e) {
e.printStackTrace();
LOG.error(String.format("Close ftp input failed:%s,%s", e.getMessage(), e.getCause()));
} finally {
is = null;
ftpClient = null;
}
}
public void validInputComplete() {
Preconditions.checkArgument(processedBytesNum == completeFileSize, "ftp file transfer is not complete");
}
/**
* main
*
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String ip = "***.***.***.****";
int port = 21;
String user = "***";
String passwd = "***";
String path = "/home/work";
String fileName = "b.txt";
FtpInput input = new FtpInput();
try {
input.fileName = fileName;
input.path = path;
input.ip = ip;
input.port = port;
input.user = user;
input.passwd = passwd;
// connect to FTP server
input.connect();
while (true) {
// read bytes
byte[] bytes = input.readBytes();
if (bytes == null) {
break;
}
LOG.info("read " + bytes.length + " bytes at :" + new Date(System.currentTimeMillis()));
// Attention: this is used for simulating the process of writing data into hive table
// it maybe consume more than 1 minute;
Thread.sleep(3000);
}
input.validInputComplete();
} catch (Exception e) {
e.printStackTrace();
} finally {
input.close();
}
}
}
here is the exception message:
java.net.SocketTimeoutException: Read timed out
or
java.net.SocketException: Connection reset
at stream.readBytes in method readBytesFromStream
At first, i think it probably caused by writing into hive table slowly, and then the FTP Server closed the connection.
But actually, the speed of writing into hive table is fast enough.
Now, i need your help, how can i fix this problem.
From your comments, it looks like it can take hours before you finish downloading the file.
You cannot reasonably expect an FTP server to wait for you for hours to finish the transfer. Particularly if you are not transferring anything most of the time. You waste server resources and most servers will protect themselves against such abuse.
Your design is flawed.
You should redesign your application to first fully download the file; and import the file only after the download finishes.

How to use network I/O with Android [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 6 years ago.
The purpose of the class below is to get text from different articles of different news websites. The version below is designed for Android, but it throws a NetworkOnMainThread Exception when run. When I used an earlier version of this class, made specifically to run on a computer, it worked fine, but I'm not really sure how network I/O works on Android. I've seen some other answers to questions about this topic, but I don't understand why in Android the program throws an exception but on a desktop it works fine. Can anyone explain?
package com.example.user.helloworld;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
public class ArticleReceiver {
private ArrayList<Article> newsArticles = new ArrayList<>();
private ArrayList<String> newsLinks = new ArrayList<>();
public ArticleReceiver(int numArticles, String link) {
if (numArticles != 0) {
receiveNewsArticles(numArticles, link);
}else{
System.out.println("ERROR: numArticles request for " + link + " cannot equal 0.");
}
}
private void receiveNewsArticles(int numArticles, String urlAddress) {
URL rssUrl = null;
// if connected to Internet
if (true){//isInternetAvailable()) {
try {
// gather links
rssUrl = new URL(urlAddress);
BufferedReader in = new BufferedReader(new InputStreamReader(rssUrl.openStream()));
String line;
// fix bbc trash urls
if (urlAddress.equals(Main.BBC_URL)) {
numArticles++;
}
while ((line = in.readLine()) != null && newsLinks.size() <= numArticles) {
if (line.contains("<link>")) {
// find links through tags
int firstPos = line.indexOf("<link>");
String temp = line.substring(firstPos);
temp = temp.replace("<link>", "");
int lastPos = temp.indexOf("</link>");
temp = temp.substring(0, lastPos);
newsLinks.add(temp);
}
}
in.close();
// test if there are links and if there is remove first
// unnecessary
// link
if (!newsLinks.isEmpty()) {
if (urlAddress.equals(Main.BBC_URL)) {
newsLinks.remove(0);
newsLinks.remove(0);
}else if(urlAddress.equals(Main.CNN_URL) || urlAddress.equals(Main.FOX_URL) || urlAddress.equals(Main.ESPN_URL)){
newsLinks.remove(0);
}
} else {
System.out.println("ERROR: No Found Articles. Check If You Have Wifi.");
}
// gather articles from HTML "section" or "p" tag of article using Jsoup
for (String newsLink : newsLinks) {
// get webpage
Document doc = Jsoup.connect(newsLink).get();
// get article from different websites
String article = null;
if (urlAddress.equals(Main.FOX_URL)) {
Elements element = doc.select("p");
article = element.text();
} else if (urlAddress.equals(Main.CNN_URL)) {
Elements element = doc.select("section");
article = element.text();
} else if (urlAddress.equals(Main.BBC_URL)) {
Elements element = doc.select("p");
article = element.text();
}else if(urlAddress.equals(Main.ESPN_URL)){
Elements element = doc.select("p");
article = element.text();
}
newsArticles.add(new Article(article, Main.SUMMARY_SENTENCES));
}
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("ERROR: No internet connection established.");
return;
}
}
public ArrayList<Article> getArticles() {
return newsArticles;
}
public Article getArticle(int i) {
if (newsArticles.size() <= i) {
return null;
} else {
return newsArticles.get(i);
}
}
//The method below does not recognize the "getSystemService" method, and when the method is no longer present there is a NetworkOnMainThreadException
private boolean isInternetAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
You need to execute web service connections asynchronous.
What I use in my projects is have a class ApiConnection and with interface get response. Example:
Apiconnection class
public class APIConnection extends AsyncTask<Object, String, Void> {
private final String TAG = "API-CONNECTION";
private StringBuilder sbuilder;
private JSONObject json;
private APIConnectionInterface mInterface;
protected int httpResponseCode = 0;
private String entity = null, url;
private APIConnectionType mmode;
private boolean DEBUG = BuildConfig.DEBUG;
private String[][] headers;
/**
Constructor For APIConnection
*/
public APIConnection(APIConnectionInterface thisdelegate, APIConnectionType mode, String murl, String entity) {
this.mInterface = thisdelegate;
this.mmode = mode;
this.url = murl;
this.entity = entity;
initHeaders();
}
private void initHeaders(){
headers = new String[][]{
{"token", "MY_TOKEN"},
{"Content-Type", "application/json;charset=utf-8"},
{"user-agent", "android"},
{"Accept-Language", "es"}
};
}
#Override
protected Void doInBackground(Object... params) {
BufferedReader buffer = null;
InputStreamReader in = null;
OutputStream os = null;
int timeoutConnection = 30000, timeoutSocket = 20000;
try{
sbuilder = new StringBuilder();
url = convertURL(url);
if (entity==null)entity="{}";
URL u = new URL(url);
HttpURLConnection conn;
if (url.startsWith("https://"))
conn = (HttpsURLConnection) u.openConnection();
else
conn = (HttpURLConnection) u.openConnection();
conn.setReadTimeout(timeoutConnection);
conn.setConnectTimeout(timeoutSocket);
for (String[] arr : headers){ conn.addRequestProperty(arr[0], arr[1]); }
/*GET*/if (mmode == APIConnectionType.GET) {
conn.setDoInput(true);
conn.setRequestMethod(mmode.toString());
httpResponseCode = conn.getResponseCode();
in = new InputStreamReader(
httpResponseCode == HttpURLConnection.HTTP_OK ? conn.getInputStream() : conn.getErrorStream(),"UTF-8");
/*OTHER*/} else if (mmode == APIConnectionType.POST || mmode == APIConnectionType.PUT ||
mmode == APIConnectionType.PATCH || mmode == APIConnectionType.DELETE) {
conn.setRequestMethod(mmode.toString());
conn.setDoOutput(true);
byte[] outputInBytes = entity.getBytes("UTF-8");
os = conn.getOutputStream();
os.write( outputInBytes );
httpResponseCode = conn.getResponseCode();
in = new InputStreamReader(
httpResponseCode == HttpURLConnection.HTTP_OK ? conn.getInputStream() : conn.getErrorStream(), "UTF-8");
}
if (in!=null){
buffer=new BufferedReader(in);
String line;
while ((line = buffer.readLine()) != null) {
sbuilder.append(line);
}
}else {
sbuilder.append("");
}
}
catch(IOException e) {
if (DEBUG)Log.d(TAG, "onBackground Exception " + e.getMessage());
sbuilder= new StringBuilder();
httpResponseCode = 0;
cancel(true);
return null;
} finally {
if (buffer != null) {
try {
buffer.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
if (os!=null){
try {
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result){
try{
if (DEBUG) timelapse_e = System.currentTimeMillis();
if (sbuilder != null) {
json = new JSONObject(sbuilder.toString());
}
if (sbuilder != null){
sbuilder.setLength(0);
sbuilder.trimToSize();
}
sbuilder = null;
GoRunning();
hideDialog();
}
catch(RuntimeException e) {
if (DEBUG)Log.d(TAG, "PostExecute RuntimeException " + e.getMessage());
cancel(true);
}
catch(Exception e) {
if (DEBUG)Log.d(TAG, "PostExecute Exception " + e.getMessage());
cancel(true);
}
}
#Override protected void onCancelled() {
if (mInterface != null) mInterface.onCancelled(APIConnection.this);
super.onCancelled();
}
#Override protected void onPreExecute() {
super.onPreExecute();
if (DEBUG) timelapse_s = System.currentTimeMillis();
if (mInterface != null) mInterface.onStartLoading(APIConnection.this);
}
public void GoRunning(){
if (mInterface != null) try {
mInterface.onDataArrival(APIConnection.this, json, httpResponseCode);
} catch (JSONException e) {
onCancelled();
e.printStackTrace();
}
}
/**
* Hide Dialog (Progress dialog) if is showing and activity NOT Finishing
*/
private void hideDialog() {
if (mInterface != null) mInterface.onFinishedLoading(APIConnection.this);
}
/** <b>convertURL(String str);</b><br/>
* replaces any special characters to <b>%??</b><br/>
* Replacements actived:<br/>
* "{Space}" ==> "%20"
* #param str URL to encode
* #return url encoded
*/
public static String convertURL(String str) {
return str.trim().replace(" ", "%20");
// .replace("&", "%26")
// .replace(",", "%2c").replace("(", "%28").replace(")", "%29")
// .replace("!", "%21").replace("=", "%3D").replace("<", "%3C")
// .replace(">", "%3E").replace("#", "%23").replace("$", "%24")
// .replace("'", "%27").replace("*", "%2A").replace("-", "%2D")
// .replace(".", "%2E").replace("/", "%2F").replace(":", "%3A")
// .replace(";", "%3B").replace("?", "%3F").replace("#", "%40")
// .replace("[", "%5B").replace("\\", "%5C").replace("]", "%5D")
// .replace("_", "%5F").replace("`", "%60").replace("{", "%7B")
// .replace("|", "%7C").replace("}", "%7D"));
}
public interface APIConnectionInterface {
void onDataArrival(APIConnection apiConnection, JSONObject json, int httpResponseCode) throws JSONException;
void onStartLoading(APIConnection apiConnection);
void onFinishedLoading(APIConnection apiConnection);
void onCancelled(APIConnection apiConnection);
}
public enum APIConnectionType {
GET("GET"),
POST("POST"),
PUT("PUT"),
PATCH("PATCH"),
DELETE("DELETE");
private String methodName;
APIConnectionType(String methodName){this.methodName = methodName;}
#Override public String toString() {return methodName;}
}
}
And then from any Activity or Fragment I can call the web service async
like this:
new APIConnection(new APIConnection.APIConnectionInterface() {
#Override public void onDataArrival(APIConnection apiConnection, JSONObject json, int httpResponseCode) {
try {
if (isHttpResponseOk(httpResponseCode, json)){//200 or 201
JSONObject obj = json.getJSONObject("results");
// do things with json
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override public void onStartLoading(APIConnection apiConnection) {showProgressDialog();}
#Override public void onFinishedLoading(APIConnection apiConnection) {hideProgressDialog();}
#Override public void onCancelled(APIConnection apiConnection) {hideProgressDialog();}
}, APIConnection.APIConnectionType.GET, MyApp.API_URL + "/master_data/", null).execute();
The only thing you need is to adapt the response to other object you need.
I hope that helps

retrieving data from sqlite in blackberry java

i need to retrieve data from sqlite .and retrieved data should be displayed in a gridfieldmanager layout.i have done the below code please help me how to display data from database over the myscreen.
SQLManager screen
public class SQLManager {
static String snapsdata;
private static String DB_NAME = "employee_details.db3";
private Database _db;
public SQLManager() throws Exception {
// Determine if an SDCard is present
boolean sdCardPresent = false;
String root = null;
Enumeration e = FileSystemRegistry.listRoots();
while (e.hasMoreElements()) {
root = (String) e.nextElement();
if (root.equalsIgnoreCase("sdcard/")) {
sdCardPresent = true;
}
}
if (!sdCardPresent) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert("This application requires an SD card to be
present.");
System.exit(0);
}
});
} else {
String dbLocation = "/SDCard/databases/sample/";
// Create URI
URI uri = URI.create(dbLocation + DB_NAME);
// Open or create a plain text database. This will create the
// directory and file defined by the URI (if they do not already
// exist).
Database db = DatabaseFactory.openOrCreate(uri,
new DatabaseSecurityOptions(false));
// Close the database in case it is blank and we need to write to
// the file
db.close();
//Dialog.alert("db");
// Open a connection to the database file
FileConnection fileConnection = (FileConnection) Connector
.open("file://" + dbLocation + DB_NAME);
// If the file is blank, copy the pre-defined database from this
// module to the SDCard.
if (fileConnection.exists() && fileConnection.fileSize() == 0) {
readAndWriteDatabaseFile(fileConnection);
//Dialog.alert("db1");
}
// Open the database
db = DatabaseFactory.open(uri);
_db = db;
}
}
/**
* Copies the pre-defined database from this module to the location
* specified by the fileConnection argument.
*
* #param fileConnection
* File connection to the database location
*/
public void readAndWriteDatabaseFile(FileConnection fileConnection)
throws IOException {
OutputStream outputStream = null;
InputStream inputStream = null;
// Open an input stream to the pre-defined encrypted database bundled
// within this module.
inputStream = getClass().getResourceAsStream("/" + DB_NAME);
//Dialog.alert("db" + inputStream);
// Open an output stream to the newly created file
outputStream = (OutputStream) fileConnection.openOutputStream();
// Read data from the input stream and write the data to the
// output stream.
byte[] data = new byte[1024 * 5];
int length = 0;
while (-1 != (length = inputStream.read(data))) {
outputStream.write(data, 0, length);
}
// Close the connections
if (fileConnection != null) {
fileConnection.close();
}
if (outputStream != null) {
outputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
}
/**
* Constructs a new SQLManager object
*
* #param db
* Database to manage
*/
public SQLManager(Database db) {
_db = db;
}
/**
* Closes the database
*/
void closeDB() {
try {
_db.close();
} catch (DatabaseException dbe) {
}
}
public void SaveEmployeeInformation(int employeeid, String employee_name,
String position, int salary){
//return productinfo;
Statement st;
try {
st = _db.createStatement("INSERT INTO
employee_details(employee_id,employee_name,position,salary) VALUES (?, ?,
?, ?)");
try
{
st.prepare();
Object[] bindParams = {new Integer(employeeid), new
String(employee_name), new String(position), new Integer(salary)};
long rowID = st.executeInsert(bindParams);
// Dialog.alert("ro "+rowID);
}
finally
{
st.close();
closeDB();
}
} catch (DatabaseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Vector getEmployeeInformation(){
Vector productinfo = new Vector();
try {
Statement statement = null;
// Read in all records from the Category table
statement = _db
.createStatement("select MAX(employee_id) as
employeeReportId from employee_details");
// ProjectImagesID Project_id,ImagePath,ImageDescription
statement.prepare();
// statement.setCursorBufferSize(10);
Cursor cursor = statement.getCursor();
Employeelist productdatas;
Row row;
// Iterate through the result set. For each row, create a new
// Category object and add it to the hash table.
while (cursor.next()) {
row = cursor.getRow();
productdatas = new Employeelist(row.getInteger(0));
productinfo.addElement(productdatas);
}
// Dialog.alert(""+productinfo.size());
statement.close();
cursor.close();
} catch (DatabaseException dbe) {
Dialog.alert("SD PRODUCTINFP " + dbe.toString());
} catch (DataTypeException e) {
Dialog.alert("PRODUCTINFP " + e.toString());
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
closeDB();
}
return productinfo;
}
}
myscreen screen
public final class MyScreen extends MainScreen
{
/**
* Creates a new MyScreen object
*/
public MyScreen()
{
// Set the displayed title of the screen
setTitle("MyTitle");
// int reportid = 0;
try {
SQLManager emp = new SQLManager();
emp.SaveEmployeeInformation(7,"farah","developer", 4000);
emp.getEmployeeInformation();
} catch (Exception e)
{// TODO Auto-generated catch block
e.printStackTrace();
}
int row = 5;
GridFieldManager dfm = new GridFieldManager(row,3, 0);
add(dfm);
}
}
First try to acheive the successul set up and retreiving of data from SQlite Db. .Then with retrieved data,try to use it in grid field Manager.
Please write exact problem in code which helps us to solvethe problem.

POST method not called on servlet - GWT project

I have this servlet to handle uploaded file and to store them on server.
public class ImageService extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final long MAX_FILE_SIZE = 1024 * 1024 * 1024; // 1GB
#Override
protected void doPost(final HttpServletRequest request,
final HttpServletResponse response) {
slog("SERVLET STARTED");
List<String> files = new ArrayList<String>();
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
slog("REQUEST IS MULTIPART");
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("text/html");
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
try {
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = iterator.next();
if (!item.isFormField()) {
String fileName = item.getName();
slog("TROVATO FILE " + item.getName());
String root = getServletContext().getRealPath("/");
File path = new File(root + "/fileuploads");
slog("SALVO FILE IN " + path.getAbsolutePath());
if (!path.exists()) {
path.mkdirs();
}
File uploadedFile = creaFileNonAmbiguo(path, fileName);
slog("NOME ASSEGNATO AL FILE " + uploadedFile.getName());
item.write(uploadedFile);
response.getWriter()
.write(uploadedFile.getName() + ";");
files.add(uploadedFile.getName());
}
}
response.getWriter().flush();
slog("RISPOSTA INVIATA");
} catch (Exception e) {
e.printStackTrace();
}
} else {
slog("LA RICHIESTA NON E' MULTIPART");
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}
slog("SERVLET TERMINATA");
}
#Override
protected void doGet(final HttpServletRequest request,
final HttpServletResponse response) {
response.setContentType("image/jpeg");
String root = getServletContext().getRealPath("/").concat(
"fileuploads/");
String path = root.concat(request.getParameter("src"));
File file = new File(path);
response.setContentLength((int) file.length());
FileInputStream in;
try {
in = new FileInputStream(file);
OutputStream out = response.getOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while ((len = in.read(buf)) >= 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private File creaFileNonAmbiguo(File path, String fileName) {
File res = new File(path + "/" + fileName);
if (!res.exists())
return res;
else {
return creaFileNonAmbiguo(path, "c".concat(fileName));
}
}
private void slog(String s) {
System.out.println("UPLOAD SERVLET: " + s);
}
}
As you can see the servlet has doPost and doGet. doGet() is correctly called in this part of my code:
[...]
String path = GWT.getModuleBaseURL() + "imageUpload?src=";
for (String foto : result) {
String url = path.concat(foto);
[...]
But the doPost method is never called, as I can see from the Chrome debugger and from the fact that SERVLET STARTED is never logged.
This is the way I call the doPost() method from client:
inserisciSegnalazioneBtn.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
if (!catLst.isEnabled()
|| catLst.getItemText(catLst.getSelectedIndex())
.equals("")
|| catLst.getItemText(catLst.getSelectedIndex())
.equals("")
|| descrizioneBox.getText().equals("")
|| gsb.getText().equals("")) {
Window.alert("ATTENZIONE: devi riempire tutti i campi");
return;
}
segnalazione.setCategoria(new Categoria(catLst.getItemText(catLst
.getSelectedIndex())));
segnalazione.setDescrizione(descrizioneBox.getText());
segnalazione.setIndirizzo(gsb.getText());
segnalazione.setUtente(LoginPanel.username);
Segnalazioni_Degrado.dataLayerService.inserisciSegnalazione(
segnalazione, new AsyncCallback<Boolean>() {
#Override
public void onFailure(Throwable caught) {
caught.printStackTrace();
}
#Override
public void onSuccess(Boolean result) {
if (result) {
geocode(segnalazione);
uploadFrm.submit();
Window.alert("Inserimento avvenuto con successo");
MenuPanel.refreshBtn.click();
} else
Window.alert("L'inserimento ha avuto esito negativo");
thisPnl.hide();
}
});
}
});
uploadFrm.setAction(GWT.getModuleBaseURL() + "imageUpload");
uploadFrm.setEncoding(FormPanel.ENCODING_MULTIPART);
uploadFrm.setMethod(FormPanel.METHOD_POST);
uploadFrm
.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
#Override
public void onSubmitComplete(SubmitCompleteEvent event) {
Window.alert("SUBMIT COMPLETATO");
String res = event.getResults();
if (res != null && !res.equals("")) {
Window.alert("IL SERVER RISPONDE " + res.toString());
String[] uploadedFiles = res.split(";");
aggiornaFotoDB(uploadedFiles, segnalazione);
}
}
});
The weird thing is that it works properly on DevMode, but it doesn't work when I deploy my webapp to Tomcat.
What's wrong with my code?
It turned out that the problem was
thisPnl.hide();
The solution was to hide the panel INSIDE the SubmitCompleteHandler

Categories

Resources