signed applet, downloading file from server and place it in the file system - applet

I have signed applet, I want to download any kind of file from the server and place it in the file system using the applet.
Please give some pointer.
Thanks in advance.

You'll have to write servlet for this. Because servlets can access to server local file system and get files you want for your applet :)
Make bound like a
applet <-servlet<-server
Good luck

The applet need to be signed to access the file system.
public String downloadFile(final String filename) {
return (String)AccessController.doPrivileged(new PrivilegedAction(){
public Object run() {
try {
// downloadURL is the server URL say http://localhost/downloads
// filename is a file want to download from the server
// localpath is the path you want to download in the file system
URL finalURL = new URL(downloadURL + filename);
ReadableByteChannel rbc = Channels.newChannel(finalURL.openStream());
FileOutputStream fos = new FileOutputStream("/"+localpath.replace("\\","/") + filename);
fos.getChannel().transferFrom(rbc, 0, 1 << 24);
fos.close();
return "true";
}catch (ConnectException ce) {
e.printStackTrace();
return "false";
}
catch (Exception e) {
e.printStackTrace();
return "false";
}
}
});
}

Related

What permission do I need to read zip files - android 11?

I'm working on zip files (android-studio-java)
and I tried below solutions:
android.permission.READ_EXTERNAL_STORAGE ---> failed (no read access for zip file)
Access documents and other files ---> failed (no read access for zip file)
android.permission.MANAGE_EXTERNAL_STORAGE ---> passed
My question is: Is there any lower level of permission for zip files or I have to use MANAGE_EXTERNAL_STORAGE?
Thank you,
Actually you can use ACTION_OPEN_DOCUMENT, no need for MANAGE_EXTERNAL_STORAGE
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
// you can set here the type you need setType(application/zip)
intent.setType("*/*");
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivityForResult(intent, ZIP_READ_CODE);
OnActivityResult
if (resultCode == RESULT_OK) {
case ZIP_READ_CODE: {
Uri uri = data.getData();
File file = null;
try {
file = read_uri_to_file(uri);
} catch (IOException e) {
//handle error
}
}
}
Read the File:
private File read_uri_to_file(Uri uri) throws IOException {
String displayName = "";
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if(cursor != null && cursor.moveToFirst()){
try {
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}finally {
cursor.close();
}
}
//create temp file to copy and handle selected file
File file = File.createTempFile(
FilenameUtils.getBaseName(displayName),
"."+FilenameUtils.getExtension(displayName)
);
//copy selected file, to a temp file
InputStream inputStream = getContentResolver().openInputStream(uri);
FileUtils.copyInputStreamToFile(inputStream, file);
return file;
}

How to get path of resource file and return it from jar file in eclipse plugin

Here I am trying to add Help .html files on Cntl+space. Its working on my laptop because I have source code but not on server. No error but not returning path on server.
Here is my code:
Bundle bundle=Platform.getBundle("my plugin ID");
URL url = FileLocator.find(bundle, new Path("/doc/myfile/file/"), null);
//Here in file folder my html files.
String fPath = "";
try {
URL fileURL = FileLocator.toFileURL(url);
fPath=fileURL.getPath();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String fullPath = filePath + name+"."+ myfileextension;
return fullPath;//returning myfile path
You must give FileLocator.toFileURL the full name of the file you want, you can't use just the folder name.
This is because FileLocator.find may have to extract the file from the plug-in jar to a temporary location to make it available.
So:
URL url = FileLocator.find(bundle, new Path("/doc/myfile/file/" + name + "." + myfileextension), null);
Also check your build.properties file. You must include all the folders you want to use in the plugin in this.

java api to get a file content for enterprise github

I tried so hard for a simple line of code that read a file content from enterprise github with oauth token, but could not find a example of such.
I tried https://github.com/jcabi/jcabi-github, but it does not support enterprise github?(maybe I am wrong)
Now i am trying egit:
GitHubClient client = new GitHubClient("enterprise url");
GitHubRequest request = new GitHubRequest();
request.setUri("/readme");
GitHubResponse response = client.get(request);
Then what? I only saw a getBody, maybe I need to parse it with some kinda json library? It has to be simpler..I am expecting something like: repo.get(url).getContent()
Finally figure out by reading source code..
GitHubClient client = new GitHubClient(YOURENTERPRICEURL);
client.setOAuth2Token(token);
// first use token service
RepositoryService repoService = new RepositoryService(client);
try {
Repository repo = repoService.getRepository(USER, REPONAME);
// now contents service
ContentsService contentService = new ContentsService(client);
List<RepositoryContents> test = contentService.getContents(repo, YOURFILENAME);
List<RepositoryContents> contentList = contentService.getContents(repo);
for(RepositoryContents content : test){
String fileConent = content.getContent();
String valueDecoded= new String(Base64.decodeBase64(fileConent.getBytes() ));
System.out.println(valueDecoded);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

GWT Upload/Download best practices

So I am new to GWT and am not sure what the best programming practices are for what I am trying to do. In my web application the user will be able to upload a data file, my application needs to be able to access this file, do some stuff to it, and then let the user download the manipulated file.
So far I have been able to successfully upload a file with an upload servlet with this doPost method:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(fileItemFactory);
fileUpload.setSizeMax(FILE_SIZE_LIMIT);
List<FileItem> items = fileUpload.parseRequest(req);
for (FileItem item : items) {
if (item.isFormField()) {
logger.log(Level.INFO, "Received form field:");
logger.log(Level.INFO, "Name: " + item.getFieldName());
logger.log(Level.INFO, "Value: " + item.getString());
} else {
logger.log(Level.INFO, "Received file:");
logger.log(Level.INFO, "Name: " + item.getName());
logger.log(Level.INFO, "Size: " + item.getSize());
}
if (!item.isFormField()) {
if (item.getSize() > FILE_SIZE_LIMIT) {
resp.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, "File size exceeds limit");
return;
}
String fileName = item.getName();
if (fileName != null) {
fileName = FilenameUtils.getName(fileName);
}
fileName = getServletContext().getRealPath("/uploadedFiles/" + fileName);
byte[] data = item.get();
FileOutputStream fileOutSt = new FileOutputStream(fileName);
fileOutSt.write(data);
fileOutSt.close();
if (!item.isInMemory())
item.delete();
}
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Throwing servlet exception for unhandled exception", e);
throw new ServletException(e);
}
}
When I look in my war folder, the uploadedFiles folder is created successfully and files are put there.
At this point I am a bit stuck, I have been researching but cannot seem to find a clear concise answer on what is the best way for me to access the uploaded files on the client side in order to manipulate them and then allow the user to download them. Maybe I am approaching this wrong, I am not sure. If someone could point me in the right direction or show me some good examples of the right way to do things that would be great, thanks.
To access the file in client side you need a new servlet or the same you are using with a doGet method.
The client should ask for the file via an Anchor or an Image depending on the file type but adding a parameter so as the server is able to identify the file. Normally you can use the name of the FileInput you used for uploading or maybe you could return a tag from the server.
I would recommend to you to take a try to gwt-upload, it would save a lot of time to you.
I solved my problem. When the file was successfully uploaded, I stored the file name. Later I used a RPC to access the file on the server. I passed the file name to the RPC so that it knows what file I am working on, then it looks for that file in the upload folder. So I can create the java file like this,
File file = new File((this.getServletContext().getRealPath("uploadedFiles") + File.separator + fileName));
and manipulate it how I see fit.

How to test if a URL from an Eclipse bundle is a directory?

I'm trying to populate a directory from the contents of a bundle built into my plug-in. The following code works when the bundle is a file-system, but fails when the bundle is a JAR.
What is the best way to test if a URL is a directory? Or is there a completely different, better approach for creating a file structure from a resource bundle?
static private void bundleCopy(String dir, String destination) throws IOException {
Bundle bundle = com.mds.apg.Activator.getDefault().getBundle();
for (#SuppressWarnings("unchecked")
Enumeration<URL> en = (Enumeration<URL>) bundle.findEntries(dir, "*", true);
en.hasMoreElements();) {
URL url = en.nextElement();
String toFileName = destination + url.getPath().substring(dir.length());
File toFile = new File(toFileName);
InputStream in;
try {
in = url.openStream();
} catch (FileNotFoundException e) {
// this exception get thrown for file system directories but not for jar file ones
if (!toFile.mkdir()) {
throw new IOException("bundleCopy: " + "directory Creation Failed: "
+ toFileName);
}
continue;
}
FileCopy.coreStreamCopy(in, toFile);
}
}
I found an answer:
The key point is that the Enumeration entries for directories end in a '/'.
The following correctly distinguishes between directories and files for both JARs and file systems:
static private void bundleCopy(String dir, String destination)
throws IOException, URISyntaxException {
Bundle bundle = com.mds.apg.Activator.getDefault().getBundle();
Enumeration<URL> en = bundle.findEntries(dir, "*", true);
while (en.hasMoreElements()) {
URL url = en.nextElement();
String pathFromBase = url.getPath().substring(dir.length()+1);
String toFileName = destination + pathFromBase;
File toFile = new File(toFileName);
if (pathFromBase.lastIndexOf('/') == pathFromBase.length() - 1) {
// This is a directory - create it and recurse
if (!toFile.mkdir()) {
throw new IOException("bundleCopy: " + "directory Creation Failed: " + toFileName);
}
} else {
// This is a file - copy it
FileCopy.coreStreamCopy(url.openStream(), toFile);
}
}
}
You could try something like new File(FileLocator.resolve(url).toUri()) to convert from the Eclipse-specific URL to one using a native Java protocol.