How do I stream each line to the Parser instance?
package net.bounceme.dur.files;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;
public class StreamFile {
private final static Logger log = Logger.getLogger(StreamFile.class.getName());
private Parser p = new Parser();
public StreamFile() {
}
public void read(String filePath) {
Stream<String> stream = null;
try {
stream = Files.lines(Paths.get(filePath));
} catch (IOException ex) {
Logger.getLogger(StreamFile.class.getName()).log(Level.SEVERE, null, ex);
}
stream.forEach(System.out::println);
}
}
Related
I am trying to convert a .prn file to html. But due to file format, I am not able to parse in a way I want.
I tried many approaches. some of are:
package main;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class PrnToHtml {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader(".\\Workbook2.prn"));
FileWriter writer = new FileWriter("output_prn.html")) {
writer.write("<html><body><h3>PRN to HTML</h3><table border>\n");
String currentLine;
while ((currentLine = reader.readLine()) != null) {
writer.write("<tr>");
for(String field: currentLine.split("\\s{2,}")) // "\\s{2,}"
writer.write("<td>" + field + "</td>");
writer.write("</tr>\n");
}
writer.write("</table></body></html>\n");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output of this will be html page looks like this:
prn file\data looks like this:
Other this I tried to read this is:
package main;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class PRNToHtml {
private static final String DILIM_PRN = " ";
private static final Pattern PRN_SPLITTER = Pattern.compile(DILIM_PRN);
public static void main(String[] args) throws URISyntaxException, IOException {
try (#SuppressWarnings("resource")
Stream<String> lines = new BufferedReader(new FileReader(".\\Workbook2.prn")).lines()) {
List<String[]> inputValuesInLines = lines.map(l -> PRN_SPLITTER.split(l)).collect(Collectors.toList());
for (String[] strings : inputValuesInLines) {
for (String s : strings) {
System.out.print(s.replaceAll("\\s+", "") + " ");
}
System.out.println();
}
}
}
}
output of this is the exactly same looking in prn data file. But when I am trying to embed in html, it is looking weird like this:
Help will be appreciated.
Thank you :)
I have a program which does the following:
Stores a file name in Main method
Passes that file to the below method(StreamParser)from Main
Method StreamParser reads that file as Stream
StreamParser should return Stream
In main method when I call forEach on purchaseEventStream it gives an error in line
purchaseEventStream.forEach(purchaseEvent -> {
Exception in thread "main" java.lang.IllegalStateException: source already consumed or
closed
at java.base/java.util.stream.AbstractPipeline.sourceSpliterator(AbstractPipeline.java:409)
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
at com.cognitree.internship.streamprocessing.Main.main(Main.java:22)
StreamParser Class
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class StreamParser {
public Stream<PurchaseEvent> parser(String fileName) throws IOException {
Stream<PurchaseEvent> purchaseEventStream;
try (Stream<String> lines = Files.lines(Paths.get(fileName))) {
purchaseEventStream= lines.map(line -> {
String[] fields = line.split(",");
PurchaseEvent finalPurchaseEvent = new PurchaseEvent();
finalPurchaseEvent.setSessionId(fields[0]);
finalPurchaseEvent.setTimeStamp(fields[1]);
finalPurchaseEvent.setItemId(fields[2]);
finalPurchaseEvent.setPrice(fields[3]);
finalPurchaseEvent.setQuantity(fields[4]);
return finalPurchaseEvent;
});
return purchaseEventStream;
}
}
}
Main Class
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) throws IOException {
OutputStreamWriter outputStream = new OutputStreamWriter(new
FileOutputStream("output1.txt"));
String file = "/Users/mohit/intern-mohit/yoochoose-buys.dat";
StreamParser streamParser = new StreamParser();
List<ReportGenerator> reports = new ArrayList<>();
PurchaseEventCount purchaseEventCount = new PurchaseEventCount();
QuantityPerSession quantityPerSession = new QuantityPerSession();
SessionCount sessionCount = new SessionCount();
reports.add(purchaseEventCount);
reports.add(sessionCount);
reports.add(quantityPerSession);
Stream<PurchaseEvent> purchaseEventStream = streamParser.parser(file);
purchaseEventStream.forEach(purchaseEvent -> {
for (ReportGenerator report : reports) {
report.generateReports(purchaseEvent);
}
});
reports.forEach(report -> {
try {
report.printReports(outputStream);
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
Why am i getting the error?
A stream in java is not a collection. It does not store data. You should create and return a collection from method parser() in class StreamParser and then create a stream from the returned collection.
I rewrote your StreamParser class to return a List.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
public class StreamParser {
public List<PurchaseEvent> parser(String fileName) throws IOException {
List<PurchaseEvent> purchaseEventStream = Files.lines(Paths.get(fileName))
.map(line -> {
String[] fields = line.split(",");
PurchaseEvent finalPurchaseEvent = new PurchaseEvent();
finalPurchaseEvent.setSessionId(fields[0]);
finalPurchaseEvent.setTimeStamp(fields[1]);
finalPurchaseEvent.setItemId(fields[2]);
finalPurchaseEvent.setPrice(fields[3]);
finalPurchaseEvent.setQuantity(fields[4]);
return finalPurchaseEvent;
})
.collect(Collectors.toList());
return purchaseEventStream;
}
}
And I changed your Main class accordingly.
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
OutputStreamWriter outputStream = new OutputStreamWriter(new FileOutputStream("output1.txt"));
String file = "/Users/mohit/intern-mohit/yoochoose-buys.dat";
StreamParser streamParser = new StreamParser();
List<ReportGenerator> reports = new ArrayList<>();
PurchaseEventCount purchaseEventCount = new PurchaseEventCount();
QuantityPerSession quantityPerSession = new QuantityPerSession();
SessionCount sessionCount = new SessionCount();
reports.add(purchaseEventCount);
reports.add(sessionCount);
reports.add(quantityPerSession);
List<PurchaseEvent> purchaseEventStream = streamParser.parser(file);
purchaseEventStream.forEach(purchaseEvent -> {
for (ReportGenerator report : reports) {
report.generateReports(purchaseEvent);
}
});
reports.forEach(report -> {
try {
report.printReports(outputStream);
}
catch (IOException e) {
e.printStackTrace();
}
});
}
}
I'm trying to write UTs for a file called DocumentStoreAccessor.java. Here is the class below:
package com.company.main.accessor;
import com.company.main.dagger.component.AccessorComponent;
import com.company.main.dagger.component.DaggerAccessorComponent;
import com.company.main.util.aws.s3.AWSS3Util;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
#Slf4j
#RequiredArgsConstructor
public class DocumentStoreAccessor {
private final DocumentStore documentStoreClient; //Comes from Dagger
public DocumentStoreAccessor() {
AccessorComponent accessorComponent = DaggerAccessorComponent.create();
this.documentStoreClient = accessorComponent.provideDocumentStoreClient();
}
private int putContentsIntoS3(CreateUploadS3UrlResult createUploadS3UrlResponse,
#NonNull File file) {
int uploadStatusCode = 0;
try {
URL url = new URL(createUploadS3UrlResponse.getS3Url());
uploadStatusCode = new AWSS3Util().upload(url, file); //Instance comes from a util class
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return uploadStatusCode;
}
public String uploadFile(File file, DocumentFileExtension fileExtension) throws Exception {
String documentId = null;
CreateUploadS3UrlResult createUploadS3Urlresult = documentStoreClient.createUploadS3Url(new CreateUploadS3UrlRequest());
int putContentsStatusCode = putContentsIntoS3(createUploadS3Urlresult, file);
if (putContentsStatusCode == 200) {
CreateDocumentRequest createDocumentRequest = new CreateDocumentRequest()
CreateDocumentResult document = documentStoreClient.createDocument(createDocumentRequest);
documentId = document.getDocumentId();
} else {
throw new Exception("Status code is: " + putContentsStatusCode);
}
return documentId;
}
}
Inside this file I do new AWSS3Util().upload(url, file).
And here is the AWSS3Util.java
package com.company.main.util.aws.s3;
import com.company.main.exception.DataAccessException;
import com.company.main.exception.RetriableDataAccessException;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
#Slf4j
#AllArgsConstructor
#Builder
public class AWSS3Util {
private static final String PUT_REQUEST_METHOD = "PUT";
public int upload(#NonNull final URL url, #NonNull final File file) throws IOException {
final InputStream inputStream = new FileInputStream(file);
final Reader fileReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
final BufferedReader br = new BufferedReader(fileReader);
HttpURLConnection connection = null;
int responseCode = 0;
try {
// Create the connection and use it to upload the new object using the pre-signed URL.
connection = create(url);
connection.setDoOutput(true);
connection.setRequestMethod(PUT_REQUEST_METHOD);
final OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8);
String st;
while ((st = br.readLine()) != null) {
out.write(st);
}
out.close();
responseCode = connection.getResponseCode();
} catch (IOException e) {
throw new RetriableDataAccessException(String.format("S3 upload request failed with request: %s", url.toString()), e);
} finally {
inputStream.close();
fileReader.close();
br.close();
}
return responseCode;
}
private HttpURLConnection create(URL url) throws IOException {
return (HttpURLConnection) url.openConnection();
}
}
I want to make new AWSS3Util().upload(url, file) return a 200..
I'm unable to do so.. I keep getting a NullPointerException. Here is what I have for the past day:
package com.company.main.accessor;
import com.company.main.util.aws.s3.AWSS3Util;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
#ExtendWith(MockitoExtension.class)
public class DocumentStoreAccessorTest {
#Mock
private DocumentStore mockDocumentStoreClient;
#Mock
private HttpURLConnection httpURLConnection;
#Mock
private OutputStream outputStream;
#InjectMocks
private DocumentStoreAccessor classUnderTest;
private URL url;
private AWSS3Util awss3Util;
private CreateUploadS3UrlRequest dummyCreateUploadS3UrlRequest;
private CreateUploadS3UrlResult dummyCreateUploadS3UrlResult;
private CreateDocumentRequest dummyCreateDocumentRequest;
private CreateDocumentResult dummyCreateDocumentResult;
#BeforeEach
void setUp() throws IOException {
awss3Util = new AWSS3Util();
url = getMockUrl(httpURLConnection);
dummyCreateUploadS3UrlRequest = new CreateUploadS3UrlRequest();
dummyCreateUploadS3UrlResult = new CreateUploadS3UrlResult().withS3Url("http://foo.io://:99");
dummyCreateDocumentRequest = new CreateDocumentRequest();
dummyCreateDocumentResult = new CreateDocumentResult().withDocumentId("foo");
}
#Test
void uploadSuccess() throws IOException {
when(mockDocumentStoreClient.createUploadS3Url(dummyCreateUploadS3UrlRequest)).thenReturn(dummyCreateUploadS3UrlResult);
AWSS3Util aSpy = Mockito.spy(awss3Util);
Mockito.when(aSpy.upload(url, getDataToUpload())).thenReturn(200);
when(mockDocumentStoreClient.createDocument(dummyCreateDocumentRequest)).thenReturn(dummyCreateDocumentResult);
String id = classUnderTest.uploadFile(getDataToUpload(), DocumentFileExtension.XLSX);
assertEquals(id, "foo");
verify(mockDocumentStoreClient, times(1)).createUploadS3Url(dummyCreateUploadS3UrlRequest);
}
private File getDataToUpload() {
return new File("TestFileName.xlsx");
}
/**
* We cannot directly use Mockito to mock URL. This helper method, helps us to create the mock url.
* <p>
* https://stackoverflow.com/questions/565535/mocking-a-url-in-java
*/
private URL getMockUrl(HttpURLConnection httpURLConnection) throws IOException {
final URLStreamHandler handler = new URLStreamHandler() {
#Override
protected URLConnection openConnection(final URL arg0)
throws IOException {
return httpURLConnection;
}
};
final URL url = new URL("http://foo.io", "foo.io", 80, "", handler);
return url;
}
}
I'm unable to mock the URL class, so I followed a another Stackoverflow post..
The AWSS3Util cannot come through Dagger, it is a util class that we're all using so this must not change.
I'm not sure if I'm going in the right direction.. I've tried "spying" on that AWSS3Util class. I want this method to return a 200 or any status code of my choice to cover them in UTs by asserting a String return as seen in the example below
I can change the the upload method inside AWSS3Util to static if it helps UTs
Cannot use PowerMockito (this is a last resort)
Try incorporating Yan's comments:
#Test
void verifyCreateUploadS3UrlInvocation() throws Exception {
when(mockDocumentStoreClient.createUploadS3Url(dummyCreateUploadS3UrlRequest)).thenReturn(dummyCreateUploadS3UrlResult);
when(httpURLConnection.getOutputStream()).thenReturn(outputStream);
when(httpURLConnection.getResponseCode()).thenReturn(200);
when(awss3Util.upload(url, getDataToUpload())).thenReturn(200);
when(mockDocumentStoreClient.createDocument(dummyCreateDocumentRequest)).thenReturn(dummyCreateDocumentResult);
String id = classUnderTest.uploadFile(getDataToUpload(), DocumentFileExtension.XLSX);
assertEquals(id, "foo");
verify(mockDocumentStoreClient, times(1)).createUploadS3Url(dummyCreateUploadS3UrlRequest);
}
I get a 405 thrown when I specifically want it to send a 200, and therefore java.lang.Exception: Status code is: 405 thrown from my function.
Firstly I would change a little bit AWSS3Util, because reading binary files as string can lead to very interesting results.
import lombok.NonNull;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class AWSS3Util {
private static final String PUT_REQUEST_METHOD = "PUT";
public int upload(#NonNull final URL url, #NonNull final File file) throws IOException {
HttpURLConnection connection = create(url);
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
connection.setDoOutput(true);
connection.setRequestMethod(PUT_REQUEST_METHOD);
try (BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream())) {
byte[] buffer = new byte[1024];
int len;
while ((len = bis.read(buffer)) > 0) {
bos.write(buffer, 0, len);
}
}
return connection.getResponseCode();
}
}
private HttpURLConnection create(URL url) throws IOException {
return (HttpURLConnection) url.openConnection();
}
}
Test for upload method could be like this:
import org.junit.jupiter.api.Test;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.nio.file.Files;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class MyTest {
#Test
public void test() throws IOException {
final HttpURLConnection mockUrlCon = mock(HttpURLConnection .class);
URLStreamHandler stubUrlHandler = new URLStreamHandler() {
#Override
protected URLConnection openConnection(URL u) throws IOException {
return mockUrlCon;
}
};
URL url = new URL("http://foo.io", "foo.io", 80, "", stubUrlHandler);
when(mockUrlCon.getResponseCode()).thenReturn(200);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
when(mockUrlCon.getOutputStream()).thenReturn(outputStream);
File file = new File("c:\\anyFile.png");
int responseCode = new AWSS3Util().upload(url, file);
assertEquals(200, responseCode);
byte[] expectedBytes = Files.readAllBytes(file.toPath());
byte[] actualBytes = outputStream.toByteArray();
assertArrayEquals(expectedBytes, actualBytes);
}
}
I had to violate the second rule - I had to DependencyInject it via Dagger
package com.company.main.dagger.module;
import com.company.main.util.aws.s3.AWSS3Util;
import dagger.Module;
import dagger.Provides;
import javax.inject.Singleton;
#Module
public class AWSS3UtilModule {
#Provides
#Singleton
public static AWSS3Util provideAwss3Util() {
return new AWSS3Util();
}
}
and then in my component
import javax.inject.Singleton;
#Singleton
#Component(modules = {
ShipDocsDMSAccessorModule.class,
AWSS3UtilModule.class
})
public interface AccessorComponent {
ShipDocsDMS provideShipDocsDMSClient();
AWSS3Util provideAwss3Util();
}
and then in my main class
#Slf4j
#RequiredArgsConstructor
public class ShipDocsDMSAccessor {
private final ShipDocsDMS shipDocsDMSClient;
private final AWSS3Util awss3Util;
public ShipDocsDMSAccessor() {
AccessorComponent accessorComponent = DaggerAccessorComponent.create();
this.shipDocsDMSClient = accessorComponent.provideShipDocsDMSClient();
this.awss3Util = accessorComponent.provideAwss3Util();
}
.
.
.
.
and then in my test, I can freely mock AWSS3Util dependency and carry ahead and force out the required response.
I am using PDFBOX and reading and saving the contents from PDF file . Requirement is text should be splitted to Header and Item in seperate array list .
PDF looks below.
Expected :
Following details PO,DeliveryDate,Vendor no should shown in arraylist 1 and other details like barcode,item number,description,quantity should shown in arraylist 2 .
Exisiting code for extracting data as txt from PDF.
PDFBoxReadFromFile.java
package pdfboxreadfromfile;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.PDFTextStripperByArea;
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.io.RandomAccessFile;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.io.*;
public class PDFBoxReadFromFile {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
PDFManager pdfManager = new PDFManager();
pdfManager.setFilePath("C:\\Users\\34\\Documents\\test.pdf");
try {
String text = pdfManager.toText();
System.out.println(text);
File file = new File("C:/Users/34/eclipse-workspace/pdfboxreadfromfile/file.txt");
FileWriter fw = new FileWriter(file);
PrintWriter pw = new PrintWriter(fw);
pw.println(text);
pw.close();
} catch (IOException ex) {
//System.err.println(ex.getMessage());
Logger.getLogger(PDFBoxReadFromFile.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
PDFManager.Java
package pdfboxreadfromfile;
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.io.RandomAccessFile;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
public class PDFManager {
private PDFParser parser;
private PDFTextStripper pdfStripper;
private PDDocument pdDoc;
private COSDocument cosDoc;
private String Text;
private String filePath;
private File file;
public PDFManager() {
}
public String toText() throws IOException {
this.pdfStripper = null;
this.pdDoc = null;
this.cosDoc = null;
file = new File(filePath);
parser = new PDFParser(new RandomAccessFile(file, "r")); // update for PDFBox V 2.0
parser.parse();
cosDoc = parser.getDocument();
pdfStripper = new PDFTextStripper();
pdDoc = new PDDocument(cosDoc);
pdDoc.getNumberOfPages();
pdfStripper.setStartPage(0);
pdfStripper.setEndPage(pdDoc.getNumberOfPages());
Text = pdfStripper.getText(pdDoc);
return Text;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public PDDocument getPdDoc() {
return pdDoc;
}
}
java
I want to create a Java application ( and then make it and applet to work on the web) that allows to upload a file to a remote server. The file has already been downloaded previously from the server. I have already have the code for the download part, but for the uploading I have the following code shown below..
The import libraries are fine but the issue is on the Uploader class that does throw me an error.. I think my BufferReader class is missing something but I need your help to debugging it...
UploadApplet.java
import com.leo.upload.BufferReader;
import com.leo.upload.Uploader;
import java.awt.Color;
import java.awt.FileDialog;
import java.awt.Frame;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.AccessControlException;
import java.security.AccessController;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Properties;
import java.util.Random;
import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.logging.LoggingPermission;
import java.util.logging.SimpleFormatter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JApplet;
import javax.swing.JPanel;
import netscape.javascript.JSObject;
public class UploadApplet extends JApplet {
public void start()
{
super.start();
uploadFile("/Users/XXXXX/Desktop/Tesing123.indd","http://xx.xx.xxx.xxx/");
}
public String uploadFile(String paramString1, String paramString2)
{
String str = "0";
try {
// I call the Uploader class to make the upload to the server
str = (String)AccessController.doPrivileged(new Uploader(paramString1, paramString2));
System.out.println(str);
}
catch (Exception e) {
e.printStackTrace();
}
return str;
}
Uploader.java
import com.leo.upload.BufferReader;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.PrivilegedAction;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class Uploader
implements PrivilegedAction<String>
{
private static final String a = Uploader.class.getName();
private Logger b = Logger.getLogger(a);
private String c;
private String d;
public Uploader(String paramString1, String paramString2)
{
this.c = paramString1;
this.d = paramString2;
}
public String run()
{
FileInputStream localFileInputStream = null;
BufferedInputStream localBufferedInputStream = null;
Writer localWriter = null;
InputStream localInputStream = null;
LineNumberReader localLineNumberReader = null;
Object localObject1 = "0";
try
{
File localFile = new File(this.c);
localFileInputStream = new FileInputStream(localFile);
localBufferedInputStream = new BufferedInputStream(localFileInputStream);
Object localObject2 = new URL(this.d);
URLConnection localURLConnection = ((URL)localObject2).openConnection();
localURLConnection.addRequestProperty("Filename", localFile.getName());
localURLConnection.setRequestProperty("Content-type", "application/binary");
long l = localFile.length();
Object localObject3;
if (l <= 2147483647L) {
if ((localURLConnection instanceof HttpURLConnection)) {
localObject3 = (HttpURLConnection)localURLConnection;
((HttpURLConnection)localObject3).setFixedLengthStreamingMode((int)localFile.length());
}
localURLConnection.setDoOutput(true);
**// I call the BufferReader class, and the a method to perform the writing**
BufferReader.a(localBufferedInputStream, localURLConnection.getOutputStream());
localInputStream = localURLConnection.getInputStream();
localLineNumberReader = new LineNumberReader(new InputStreamReader(localInputStream, "UTF8"));
localObject1 = localLineNumberReader.readLine();
}
else {
localObject3 = "An error occurred during file upload: Cannot upload a file larger than 2GB.";
JOptionPane.showMessageDialog(null, localObject3, "Error during file upload", 0);
this.b.severe((String)localObject3);
localObject1 = localObject3;
}
}
catch (Throwable localIOException4) {
localIOException4.printStackTrace();
Object localObject2 = "An error occurred during file upload: " + localIOException4.toString();
localObject1 = localObject2;
} finally {
BufferReader.a(localFileInputStream, localBufferedInputStream, localWriter);
if (localLineNumberReader != null) {
try {
localLineNumberReader.close();
} catch (IOException localIOException5) {
localIOException5.printStackTrace();
}
}
if (localInputStream != null) {
try {
localInputStream.close();
} catch (IOException localIOException6) {
localIOException6.printStackTrace();
}
}
}
return (String)(String)(String)localObject1;
}
}
BufferReader.java
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Writer;
import java.util.logging.Logger;
public final class BufferReader
{
private static Logger logthis = Logger.getLogger(BufferReader.class.getName());
public static void a(InputStream paramInputStream, OutputStream paramOutputStream)
throws IOException
{
byte[] arrayOfByte = new byte[4096];
int i = 0;
int j;
while ((j = paramInputStream.read(arrayOfByte)) != -1) {
paramOutputStream.write(arrayOfByte, 0, j);
i += j;
}
logthis.fine("CopyBytes : " + i);
}
public static void a(InputStream paramInputStream, FileOutputStream paramFileOutputStream, BufferedOutputStream paramBufferedOutputStream)
{
if (paramInputStream != null) {
try {
paramInputStream.close();
} catch (IOException localIOException1) {
localIOException1.printStackTrace();
}
}
if (paramFileOutputStream != null) {
try {
paramFileOutputStream.flush();
} catch (IOException localIOException2) {
localIOException2.printStackTrace();
}
}
if (paramBufferedOutputStream != null) {
try {
paramBufferedOutputStream.flush();
} catch (IOException localIOException3) {
localIOException3.printStackTrace();
}
}
if (paramFileOutputStream != null) {
try {
paramFileOutputStream.close();
} catch (IOException localIOException4) {
localIOException4.printStackTrace();
}
}
if (paramBufferedOutputStream != null)
try {
paramBufferedOutputStream.close();
} catch (IOException localIOException5) {
localIOException5.printStackTrace();
}
}
public static void a(InputStream paramInputStream, BufferedInputStream paramBufferedInputStream, Writer paramWriter)
{
if (paramBufferedInputStream != null)
try {
paramBufferedInputStream.close();
}
catch (IOException localIOException1)
{
}
if (paramInputStream != null)
try {
paramInputStream.close();
}
catch (IOException localIOException2)
{
}
if (paramWriter != null)
try {
paramWriter.close();
}
catch (IOException localIOException3)
{
}
}
public static String a(InputStream paramInputStream)
throws IOException
{
BufferedReader localBufferedReader = new BufferedReader(new InputStreamReader(paramInputStream, "UTF-8"));
StringBuilder localStringBuilder = new StringBuilder();
String str = null;
while ((str = localBufferedReader.readLine()) != null) {
localStringBuilder.append(str);
}
localBufferedReader.close();
return localStringBuilder.toString();
}
}
Bear in mind that unsigned applets aren't usually allowed to open connections to addresses that aren't their originating web server...unless you specify that applets can do whatever they want in the client's java control panel