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
Related
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.
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);
}
}
I was making a pretty simple jar to unzip a zip and run the jar that was inside of it. The problem I've run into is that it doesn't do anything at all.
This is the main, and only class file for the jar. The manifest does point correctly to it, and it loads without errors.
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.BufferedOutputStream;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import static java.lang.Integer.parseInt;
import java.net.URLConnection;
import java.net.URL;
import java.util.zip.ZipFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.Enumeration;
import sign.signlink;
import java.nio.file.*;
import java.io.FileReader;
public class ClientUpdater {
private String fileToExtractNew = "/client.zip";
private String getJarDir() throws FileNotFoundException, IOException{
String linebuf="",verStr="";
FileInputStream fis = new FileInputStream("/runLocationURL.txt");
BufferedReader br= new BufferedReader(new InputStreamReader(fis));
while ((linebuf = br.readLine()) != null) {
verStr = linebuf;
}
return verStr;
}
public static void main(String[] args) {
System.out.println("start");
}
private void unZip() {
System.out.println("unzipping");
try {
ZipEntry zipEntry;
//client
BufferedInputStream bufferedInputStreamNew = new BufferedInputStream(new FileInputStream(this.fileToExtractNew));
ZipInputStream zipInputStreamNew = new ZipInputStream(bufferedInputStreamNew);
//client
while ((zipEntry = zipInputStreamNew.getNextEntry()) != null) {
String stringNew = zipEntry.getName();
File fileNew = new File(this.getJarDir() + File.separator + stringNew);
if (zipEntry.isDirectory()) {
new File(this.getJarDir() + zipEntry.getName()).mkdirs();
continue;
}
if (zipEntry.getName().equals(this.fileToExtractNew)) {
this.unzipNew(zipInputStreamNew, this.fileToExtractNew);
break;
}
new File(fileNew.getParent()).mkdirs();
this.unzipNew(zipInputStreamNew, this.getJarDir() + zipEntry.getName());
}
zipInputStreamNew.close();
}
catch (Exception var1_2) {
var1_2.printStackTrace();
}
}
private void unzipNew(ZipInputStream zipInputStreamNew, String stringNew) throws IOException {
System.out.println("unzipping new");
FileOutputStream fileOutputStreamNew = new FileOutputStream(stringNew);
byte[] arrby = new byte[4024];
int n = 0;
while ((n = zipInputStreamNew.read(arrby)) != -1) {
fileOutputStreamNew.write(arrby, 0, n);
}
fileOutputStreamNew.close();
Runtime.getRuntime().exec("java -jar " + getJarDir() + "/Project Pk Client.jar");
System.exit(0);
}
}
It shows the "Start" message, but not the other 2, so it never reaches those methods. Is it because they aren't being called? I'm still learning Java.
You actually have to call your other methods from main. Right now, all you are telling the computer to do is print start and then exit. Functions do not get called simply by existing.
It seems based on a quick glance that you just need to add unzip(); to your main function, right after the System.out.println line.
To do this, you need to say that those other methods are static, so you need to say private static void unZip() instead of private void unZip(). Do this for your other methods too.
import java.io.*;
import static java.lang.Integer.parseInt;
import java.net.URLConnection;
import java.net.URL;
import java.util.zip.ZipFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.Enumeration;
import sign.signlink;
import java.nio.file.*;
public class ClientUpdater {
private String fileToExtractNew = "/client.zip";
private static String getJarDir() throws FileNotFoundException, IOException{
String linebuf="",verStr="";
FileInputStream fis = new FileInputStream("/runLocationURL.txt");
BufferedReader br= new BufferedReader(new InputStreamReader(fis));
while ((linebuf = br.readLine()) != null) {
verStr = linebuf;
}
return verStr;
}
public static void main(String[] args) {
System.out.println("start");
unZip();
}
private static void unZip() {
System.out.println("unzipping");
try {
ZipEntry zipEntry;
//client
BufferedInputStream bufferedInputStreamNew = new BufferedInputStream(new FileInputStream(this.fileToExtractNew));
ZipInputStream zipInputStreamNew = new ZipInputStream(bufferedInputStreamNew);
//client
while ((zipEntry = zipInputStreamNew.getNextEntry()) != null) {
String stringNew = zipEntry.getName();
File fileNew = new File(this.getJarDir() + File.separator + stringNew);
if (zipEntry.isDirectory()) {
new File(this.getJarDir() + zipEntry.getName()).mkdirs();
continue;
}
if (zipEntry.getName().equals(this.fileToExtractNew)) {
this.unzipNew(zipInputStreamNew, this.fileToExtractNew);
break;
}
new File(fileNew.getParent()).mkdirs();
this.unzipNew(zipInputStreamNew, this.getJarDir() + zipEntry.getName());
}
zipInputStreamNew.close();
}
catch (Exception var1_2) {
var1_2.printStackTrace();
}
}
private static void unzipNew(ZipInputStream zipInputStreamNew, String stringNew) throws IOException {
System.out.println("unzipping new");
FileOutputStream fileOutputStreamNew = new FileOutputStream(stringNew);
byte[] arrby = new byte[4024];
int n = 0;
while ((n = zipInputStreamNew.read(arrby)) != -1) {
fileOutputStreamNew.write(arrby, 0, n);
}
fileOutputStreamNew.close();
Runtime.getRuntime().exec("java -jar " + getJarDir() + "/Project Pk Client.jar");
System.exit(0);
}
}
I want to get the get the ContentResult from document which is in alfresco :
using this code
ContentResult contentResult = AlfrescoClientWS.getContentsById(docid,"HTTP://192.168.8.100:9080/alfresco/api",
GedListener.credentialUser, GedListener.credentialPwd);
I work in jboss 7.1 and I use this jar :
alfresco-web-service-client-4.0.d.jar,axis-1.4.jar,axis-saaj-1.2.jar,wsdl4j-1.6.2.jar,wss4j-1.5.4-patched.jar,xmlsec-1.4.1.jar
but when I test I have this error:
17:07:40,546 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/myProject].[FileUploadServlet]] (http-localhost-127.0.0.1-8080-5) "Servlet.service()" pour la servlet FileUploadServlet a généré une exception: java.lang.NoSuchMethodError: org.apache.xml.security.transforms.Transform.init()V
at org.apache.ws.security.WSSConfig.staticInit(WSSConfig.java:244) [wss4j-1.5.4-patched.jar:]
at org.apache.ws.security.WSSConfig.<init>(WSSConfig.java:256) [wss4j-1.5.4-patched.jar:]
at org.apache.ws.security.WSSConfig.getNewInstance(WSSConfig.java:265) [wss4j-1.5.4-patched.jar:]
at org.apache.ws.security.handler.WSHandler.doSenderAction(WSHandler.java:89) [wss4j-1.5.4-patched.jar:]
at org.apache.ws.axis.security.WSDoAllSender.invoke(WSDoAllSender.java:170) [wss4j-1.5.4-patched.jar:]
at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32) [axis-1.4.jar:]
at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118) [axis-1.4.jar:]
at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83) [axis-1.4.jar:]
at org.apache.axis.client.AxisClient.invoke(AxisClient.java:127) [axis-1.4.jar:]
at org.apache.axis.client.Call.invokeEngine(Call.java:2784) [axis-1.4.jar:]
at org.apache.axis.client.Call.invoke(Call.java:2767) [axis-1.4.jar:]
at org.apache.axis.client.Call.invoke(Call.java:2443) [axis-1.4.jar:]
at org.apache.axis.client.Call.invoke(Call.java:2366) [axis-1.4.jar:]
at org.apache.axis.client.Call.invoke(Call.java:1812) [axis-1.4.jar:]
at org.alfresco.webservice.content.ContentServiceSoapBindingStub.read(ContentServiceSoapBindingStub.java:467) [alfresco-web-service-client-4.0.d.jar:]
at com.dq.urbanplanning.web.ged.AlfrescoClientWS.getContentsById(AlfrescoClientWS.java:162) [classes:]
............
.........
I have this class java :AlfrescoClientWS.java
import org.alfresco.webservice.content.Content;
import org.alfresco.webservice.content.ContentFault;
import org.alfresco.webservice.content.ContentServiceSoapBindingStub;
import org.alfresco.webservice.repository.QueryResult;
import org.alfresco.webservice.repository.RepositoryServiceSoapBindingStub;
import org.alfresco.webservice.repository.UpdateResult;
import org.alfresco.webservice.types.CML;
import org.alfresco.webservice.types.CMLAddAspect;
import org.alfresco.webservice.types.CMLCreate;
import org.alfresco.webservice.types.ContentFormat;
import org.alfresco.webservice.types.NamedValue;
import org.alfresco.webservice.types.ParentReference;
import org.alfresco.webservice.types.Predicate;
import org.alfresco.webservice.types.Query;
import org.alfresco.webservice.types.Reference;
import org.alfresco.webservice.types.ResultSet;
import org.alfresco.webservice.types.ResultSetRow;
import org.alfresco.webservice.types.Store;
import org.alfresco.webservice.util.AuthenticationUtils;
import org.alfresco.webservice.util.Constants;
import org.alfresco.webservice.util.ContentUtils;
import org.alfresco.webservice.util.Utils;
import org.alfresco.webservice.util.WebServiceFactory;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import javax.activation.MimetypesFileTypeMap;
public class AlfrescoClientWS {
public static ContentResult getContentsById(String contentId, String cmurl, String userName, String pwd)
throws Exception {
ContentResult contentResult = new ContentResult();
// Start the session
WebServiceFactory.setEndpointAddress(cmurl);
AuthenticationUtils.startSession(userName, pwd);
try {
Store storeRef = new Store(Constants.WORKSPACE_STORE, "SpacesStore");
ContentServiceSoapBindingStub contentService = WebServiceFactory.getContentService();
Reference contentReference = new Reference(storeRef, contentId, null);
Content[] readResult = null;
try {
readResult = contentService.read(new Predicate(new Reference[] { contentReference }, storeRef, null), Constants.PROP_CONTENT);
} catch (ContentFault e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
if ((readResult != null) && (readResult[0] != null)) {
Content content = readResult[0];
ContentFormat cnf = content.getFormat();
Reference ref = content.getNode();
String[] splitedUrl = content.getUrl().split("/");
String name = splitedUrl[splitedUrl.length - 1];
InputStream is = ContentUtils.getContentAsInputStream(content);
byte[] contentByte = IOUtils.toByteArray(is);
contentResult.setName(name);
contentResult.setMimetype(cnf.getMimetype());
contentResult.setId(ref.getUuid());
contentResult.setUrl(content.getUrl());
contentResult.setPath(ref.getPath());
contentResult.setContentByte(contentByte);
System.out.println(" document has been retrieved");
}
} catch (Exception e) {
System.out.println(e.toString());
} finally {
// End the session
AuthenticationUtils.endSession();
// System.exit(0);
}
return contentResult;
}
}
the error is related to this line :
readResult = contentService.read(new Predicate(new Reference[] { contentReference }, storeRef, null), Constants.PROP_CONTENT);
I test my code using Main class with this code :
import org.alfresco.webservice.content.Content;
import org.alfresco.webservice.content.ContentFault;
import org.alfresco.webservice.content.ContentServiceSoapBindingStub;
import org.alfresco.webservice.repository.QueryResult;
import org.alfresco.webservice.repository.RepositoryServiceSoapBindingStub;
import org.alfresco.webservice.repository.UpdateResult;
import org.alfresco.webservice.types.CML;
import org.alfresco.webservice.types.CMLAddAspect;
import org.alfresco.webservice.types.CMLCreate;
import org.alfresco.webservice.types.ContentFormat;
import org.alfresco.webservice.types.NamedValue;
import org.alfresco.webservice.types.ParentReference;
import org.alfresco.webservice.types.Predicate;
import org.alfresco.webservice.types.Query;
import org.alfresco.webservice.types.Reference;
import org.alfresco.webservice.types.ResultSet;
import org.alfresco.webservice.types.ResultSetRow;
import org.alfresco.webservice.types.Store;
import org.alfresco.webservice.util.AuthenticationUtils;
import org.alfresco.webservice.util.Constants;
import org.alfresco.webservice.util.ContentUtils;
import org.alfresco.webservice.util.Utils;
import org.alfresco.webservice.util.WebServiceFactory;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import javax.activation.MimetypesFileTypeMap;
public class AlfrescoClientWS {
public static void main(String[] args) {
try {
ContentResult contentResult =AlfrescoClientWS.getContentsById("85e686c6-aecd-4747-9f2e-56d8c58a3e08",
"HTTP://192.168.0.100:9080/alfresco/api", "admin", "12345");
System.out.println("-- contentResult:" + contentResult.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
public static ContentResult getContentsById(String contentId, String cmurl, String userName, String pwd)
throws Exception {
ContentResult contentResult = new ContentResult();
// Start the session
WebServiceFactory.setEndpointAddress(cmurl);
AuthenticationUtils.startSession(userName, pwd);
try {
Store storeRef = new Store(Constants.WORKSPACE_STORE, "SpacesStore");
ContentServiceSoapBindingStub contentService = WebServiceFactory.getContentService();
Reference contentReference = new Reference(storeRef, contentId, null);
Content[] readResult = null;
try {
readResult = contentService.read(new Predicate(new Reference[] { contentReference }, storeRef, null), Constants.PROP_CONTENT);
} catch (ContentFault e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
if ((readResult != null) && (readResult[0] != null)) {
Content content = readResult[0];
ContentFormat cnf = content.getFormat();
Reference ref = content.getNode();
String[] splitedUrl = content.getUrl().split("/");
String name = splitedUrl[splitedUrl.length - 1];
InputStream is = ContentUtils.getContentAsInputStream(content);
byte[] contentByte = IOUtils.toByteArray(is);
contentResult.setName(name);
contentResult.setMimetype(cnf.getMimetype());
contentResult.setId(ref.getUuid());
contentResult.setUrl(content.getUrl());
contentResult.setPath(ref.getPath());
contentResult.setContentByte(contentByte);
System.out.println(" document has been retrieved");
}
} catch (Exception e) {
System.out.println(e.toString());
} finally {
// End the session
AuthenticationUtils.endSession();
// System.exit(0);
}
return contentResult;
}
}
but when I test my code using jboss I have problem
My Server Program:-
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
public class GetFileServeredit implements Runnable {
public static final int SERVERPORT = 4747;
public String FileName=null;
public void run() {
try {
ServerSocket svr=new ServerSocket(SERVERPORT);
while(true){
System.out.println("S: Waiting...");
Socket sktClient=svr.accept();
System.out.println("S: Receiving...");
try{
PrintService services[] = PrintServiceLookup.lookupPrintServices(null, null);
PrintWriter out2 = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sktClient.getOutputStream())),true);
/*for(int z=0;z<services.length;z++){
out2.println(services[z]);
}*/
out2.println("aaa 12212");
out2.flush();
out2.close();
sktClient.close();
System.out.println("Transfer complete.");
}
catch(Exception e){
e.printStackTrace();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String [] args){
Thread servThread =new Thread(new GetFileServeredit());
servThread.start();
}
}
My Client Program
:-
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
public class ClientPrinters implements Runnable {
static final int PORT = 4747; //Change this to the relevant port
static final String HOST = "192.***.*.***"; //Change this to the relevant HOST,//(where Server.java is running)
public void run() {
try {
System.out.print("Sending data...\n");
Socket skt = new Socket(HOST, PORT);
ArrayList Printers =new ArrayList();
InputStream inStream = skt.getInputStream();
BufferedReader inm = new BufferedReader(new InputStreamReader(inStream));
while ((inm.read()) != -1) {
Printers.add(inm.readLine());
}
inm.close();
inStream.close();
skt.close();
}
catch( Exception e ) {
System.out.print("Error! It didn't work! " + e + "\n");
}
}
public static void main(String [] args){
Thread cThread =new Thread(new ClientPrinters());
cThread.start();
}
}
The out that i am sending form the server i.e
out2.println("aaa 12212");
becomes 12212 only at the client side,why? where is the other text??
while ((inm.read()) != -1) {
Printers.add(inm.readLine());
}
This line first reads a single and if that succeeds, it tries to read a line. This swallows (and ignores) one character per line.
Also: you don't specify any character encodings in your server and client: This will work (with some restrictions) as long as client and server run using the same locale. But it will break once they use different default encodings.
It's probably best to just specify the encoding to use "on the wire". A great candidate for this is UTF-8:
// server
PrintWriter out2 = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sktClient.getOutputStream(), "UTF-8")),true);
// client
BufferedReader inm = new BufferedReader(new InputStreamReader(inStream, "UTF-8"));
I was not running your code,but.
while ((inm.read()) != -1) {
}
I think .read() consumed some byte.
you should use some buffer(byte[]) and call .read(buffer)!=-1
Perhaps what you intended was
List<String> printers =new ArrayList<String>();
String line;
while ((line = inm.readLine()) != null)
printers.add(line);
Note: use camelCase for field/variable names.