How do I resume a file upload? - java

I am using plupload at JavaScript library.
I want to resume file uploads if there is a failure while implementing file uploads.
I've been told to use HTTP chunk transfer.
but I don't know, How can I use it.
please show following server-side code.
private static final int BUFFER_SIZE = 100 * 1024;
try {
Integer chunk = 0, chunks = 0;
if(null != request.getParameter("chunk") && !request.getParameter("chunk").equals("")){
chunk = Integer.valueOf(request.getParameter("chunk"));
}
if(null != request.getParameter("chunks") && !request.getParameter("chunks").equals("")){
chunks = Integer.valueOf(request.getParameter("chunks"));
}
logger.info("chunk:[" + chunk + "] chunks:[" + chunks + "]");
...
appendFile(file.getInputStream(), destFile, response);
if (chunk == chunks - 1) {
logger.info("upload success !");
}else {
logger.info("left ["+(chunks-1-chunk)+"] chunks...");
}
} catch (IOException e) {
logger.error(e.getMessage());
}
}
public void appendFile(InputStream in, File destFile, HttpServletResponse response) {
OutputStream out = null;
try {
if (destFile.exists()) {
out = new BufferedOutputStream(new FileOutputStream(destFile, true), BUFFER_SIZE);
} else {
out = new BufferedOutputStream(new FileOutputStream(destFile),BUFFER_SIZE);
}
in = new BufferedInputStream(in, BUFFER_SIZE);
int len = 0;
byte[] buffer = new byte[BUFFER_SIZE];
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
} catch (Exception e) {
logger.error(e.getMessage());
}
finally {
try {
if (null != in) {
in.close();
}
if(null != out){
out.close();
}
} catch (IOException e) {
e.getMessage();
logger.error(e.getMessage());
}
}
}

Related

How to add image inside a tab as a icon while developing Harmony application?

I want to add an image inside the tab and I have Image Resource Id but tab.setIconElement(Element) takes element.
currently, I am trying like this
tabList = (TabList) findComponentById(ResourceTable.Id_TabList);
TabList.Tab tab = tabList.new Tab(this);
tab.setIconElement(Element); // want the image as an element
tabList.addTab(tab);
How can I add an image inside the tab or create its element with Image Resource Id only?
Or is there any other way to do it?
First you have to decode the Image resource using ImageSource.DecodingOptions, Later create PixelMapElement from PixelMap. Finally using set PixelMapElement to Tab using setIconElement API,
public static void createIcons(AbilitySlice abilitySlice, TabList.Tab tab, int id) {
if (tab == null) {
LogUtil.error(TAG, "createTabIcon failed");
return;
}
try {
PixelMap pixelMap = createByResourceId(abilitySlice, id, "image/png");
PixelMapElement pixelMapElement = new PixelMapElement(pixelMap);
pixelMapElement.setBounds(0, 0, 70, 70);
tab.setIconElement(pixelMapElement);
tab.setPadding(5, 5, 5, 5);
} catch (NotExistException | IOException e) {
LogUtil.error(TAG, "createTabIcon " + e.getLocalizedMessage());
}
}
public static PixelMap createByResourceId(AbilitySlice abilitySlice, int id, String str)
throws IOException, NotExistException {
if (abilitySlice == null) {
LogUtil.error(TAG, "createByResourceId but slice is null");
throw new IOException();
} else {
ResourceManager resourceManager = abilitySlice.getResourceManager();
if (resourceManager != null) {
Resource resource = resourceManager.getResource(id);
if (resource != null) {
ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
sourceOptions.formatHint = str;
ImageSource create = ImageSource.create(readResource(resource), sourceOptions);
resource.close();
if (create != null) {
ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
decodingOptions.desiredSize = new Size(0, 0);
decodingOptions.desiredRegion = new ohos.media.image.common.Rect(0, 0, 0, 0);
decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;
PixelMap pixelMap = create.createPixelmap(decodingOptions);
return pixelMap;
}
LogUtil.error(TAG, "imageSource is null");
throw new FileNotFoundException();
}
LogUtil.error(TAG, "get resource failed");
throw new IOException();
}
LogUtil.error(TAG, "get resource manager failed");
throw new IOException();
}
}
private static byte[] readResource(Resource resource) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] bArr = new byte[1024];
while (true) {
try {
int read = resource.read(bArr, 0, 1024);
if (read == -1) {
break;
}
byteArrayOutputStream.write(bArr, 0, read);
} catch (IOException e) {
LogUtil.error(TAG, "readResource failed " + e.getLocalizedMessage());
}finally {
byteArrayOutputStream.close();
}
}
LogUtil.debug(TAG, "readResource finish");
LogUtil.debug(TAG, "readResource len: " + byteArrayOutputStream.size());
return byteArrayOutputStream.toByteArray();
}

Catch 404 error from BufferedInputStream

I have a function for html page download.
Here is the code:
public class pageDownload {
public static void down(final String filename, final String urlString)
throws MalformedURLException, IOException {
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
in = new BufferedInputStream(new URL(urlString).openStream());
fout = new FileOutputStream(new File(filename));
final byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
}
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
} catch (IndexOutOfBoundsException e) {
System.err.println("IndexOutOfBoundsException: " + e.getMessage());
}
in.close();
fout.close();
}
}
Works ok, problem appears when i try to download a page that not exist. I can't figure out how to handle 404 error in this case.
Has anyone some idea?
Do you mean something like this? I added a finally to save close the Streams
public class pageDownload {
public static void down(final String filename, final String urlString)
throws MalformedURLException, IOException {
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
in = new BufferedInputStream(new URL(urlString).openStream());
fout = new FileOutputStream(new File(filename));
final byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
}
} catch(FileNotFoundException ex)
{
System.err.println("Caught 404: " + e.getMessage());
}
catch(IOException ex)
{
System.err.println("Caught IOException: " + e.getMessage());
}
catch(IndexOutOfBoundsException e)
{
System.err.println("IndexOutOfBoundsException: " + e.getMessage());
}
finally{
if(in != null)
try { in.close(); } catch ( IOException e ) { }
if(fout != null)
try { fout.close(); } catch ( IOException e ) { }
}
}
}
Your problem is you get a NullPointerException when you try to close the streams. You should anyway close them in a finally clause or use try with resources:
public static void down(final String filename, final String urlString)
throws IOException {
try (BufferedInputStream in = new BufferedInputStream(new URL(urlString)
.openStream());
FileOutputStream fout = new FileOutputStream(new File(filename))) {
final byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
}
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
} catch (IndexOutOfBoundsException e) {
System.err.println("IndexOutOfBoundsException: " + e.getMessage());
}
}

Read form ZipDecryptInputStream and write it to OutputStream

public void decrypt(String inputFile, String password) {
ZipDecryptInputStream zipDecrypt = null;
try {
zipDecrypt = new ZipDecryptInputStream(new FileInputStream(
inputFile), password);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
File file = new File("outouttfile.tsv");
OutputStream fop = null;
try {
fop = new FileOutputStream(file);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = zipDecrypt.read(buffer)) != -1) {
fop.write(buffer, 0, bytesRead);
System.out.println("Written");
}
} catch (IOException e) {
e.printStackTrace();
}
}
My while loop becomes an infinite loop and does not stop reading the file even its read once. Any idea why?

Java Voice Chat Error

I am making a voice chat program. I have two servers one for voice and one for messages. When I connect two people I get this error, Thank you in advance. I attached the client code, ClientAudio code and the Client receive code
java.io.StreamCorruptedException: invalid type code: 00
at java.io.ObjectInputStream$BlockDataInputStream.readBlockHeader(ObjectInputStream.java:2508)
at java.io.ObjectInputStream$BlockDataInputStream.refill(ObjectInputStream.java:2543)
at java.io.ObjectInputStream$BlockDataInputStream.read(ObjectInputStream.java:2702)
at java.io.ObjectInputStream.read(ObjectInputStream.java:865)
at client.chat$ClientAudioRec.run(chat.java:388)
at java.lang.Thread.run(Thread.java:745)
its calling the error on
try {
bytesRead = ((ObjectInput) i2).read(inSound, 0, inSound.length);
} catch (Exception e) {
e.printStackTrace();
}
Code
public class Client implements Runnable { // CLIENT
private String msg;
public void run() {
try {
s1 = new Socket(ipAddress, port);
s2 = new Socket(ipAddress, 1210);
o1 = new ObjectOutputStream(s1.getOutputStream());
o1.writeObject(name);
serverListModel.addElement(name);
i1 = new ObjectInputStream(s1.getInputStream());
Thread voice = new Thread(new ClientAudio());
voice.start();
while(true) {
msg = (String) i1.readObject();
String[] namePart = msg.split("-");
if(namePart[0].equals("AddName") && !namePart[1].equals(name) && !serverListModel.contains(namePart[1])) {
serverListModel.addElement(namePart[1]);
}
if(namePart[0].equals("RemoveName") && !namePart[1].equals(name)) {
serverListModel.removeElement(namePart[1]);
}
if(!msg.equals(null) && !namePart[0].equals("AddName") && !namePart[0].equals("RemoveName")) {
chatWindow.append(msg+"\n");
}
}
} catch (IOException | ClassNotFoundException e) {
chatWindow.append("Server Closed");
e.printStackTrace();
try {
s1.close();
} catch (IOException e1) {
e1.printStackTrace();
}
mainWindow(true);
}
}
}
public class ClientAudio implements Runnable { // CLIENT AUDIO
public void run() {
try {
o2 = new ObjectOutputStream(s2.getOutputStream());
System.out.println("AUDIO");
int bytesRead = 0;
byte[] soundData = new byte[1];
Thread car = new Thread(new ClientAudioRec());
car.start();
while(true) {
bytesRead = mic.read(soundData, 0, bytesRead);
if(bytesRead >= 0) {
o2.write(soundData, 0, bytesRead);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class ClientAudioRec implements Runnable { // CLIENT AUDIO REC
public void run() {
i2 = new ObjectInputStream(s2.getInputStream());
System.out.println("REC");
SourceDataLine inSpeaker = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class, af);
try {
inSpeaker = (SourceDataLine)AudioSystem.getLine(info);
inSpeaker.open(af);
} catch (LineUnavailableException e1) {
System.out.println("ERROR 22");
e1.printStackTrace();
}
int bytesRead = 0;
byte[] inSound = new byte[100];
inSpeaker.start();
while(bytesRead != -1)
{
try{
bytesRead = ((ObjectInput) i2).read(inSound, 0, inSound.length);
} catch (Exception e){
e.printStackTrace();
}
if(bytesRead >= 0)
{
inSpeaker.write(inSound, 0, bytesRead);
}
}
}
}

I want to use ZBar Barcode Reader's zbarimg.exe in my java code , when i compile my program , a window pops up and gone in a fraction of seconds

public static void main(String[] args) {
String filePath = "C:/Program Files/ZBar/bin/zbarimg -d C:/Program Files/ZBar/examples/barcode.png";
try {
System.out.println("hello");
Process p = Runtime.getRuntime().exec(filePath);
//BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
System.out.println("World");
final InputStream stdout = p.getInputStream();
final OutputStream stdin = p.getOutputStream();
new Thread(new Runnable() {
#Override
public void run() {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
try {
while ((line = br.readLine()) != null) {
System.out.println("[OUT] " + line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
public void run() {
try {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = System.in.read(buffer)) != -1) {
for(int i = 0; i < buffer.length; i++) {
int intValue = new Byte(buffer[i]).intValue();
if (intValue == 0) {
bytesRead = i;
break;
}
}
// for some reason there are 2 extra bytes on the end
stdin.write(buffer, 0, bytesRead-2);
System.out.println("[IN] " + new String(buffer, 0, bytesRead-2) + " [/IN]");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
You probably shouldn't be invoking an external process to decode like that, I suspect you're receiving a '\r\n' (aka Carraige Return Line Feed) from your external process. I recommend you use a Java library to perform the decode... here is how you might with ZXing "Zebra Crossing".

Categories