GWT Upload/Download best practices - gwt

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.

Related

not able to download file with size more than 63kb using UnityWebRequest

i am try to download asset bundle from an url but the request keep on cancelling after downloading 63kb. Can anyone explain to me why this may be happening?
My Code :
public IEnumerator DL()
{
string downloadlink = "https://drive.google.com/file/d/1OGyrB4-MQfo-HVom9ENvV4dn312_wL4Q/view?usp=sharing";
string filepath = Application.persistentDataPath + "/electroplatingNN";
//Download
UnityWebRequest dlreq = new UnityWebRequest(downloadlink);
dlreq.downloadHandler = new DownloadHandlerFile(filepath);
dlreq.timeout = 15;
UnityWebRequestAsyncOperation op = dlreq.SendWebRequest();
while (!op.isDone)
{
//here you can see download progress
Debug.Log(dlreq.downloadedBytes / 1000 + "KB");
yield return null;
}
if (dlreq.isNetworkError || dlreq.isHttpError)
{
Debug.Log(dlreq.error);
}
else
{
Debug.Log("download success");
}
dlreq.Dispose();
yield return null;
}
As already mentioned in the comments the issue is not in the UnityWebrequest but rather Google Drive doesn't simply download your file as you expect.
Instead the data you download is actually only the web page which would allow you to download it. If I simply open your file in a browser I get a page looking like this
where I now could download your file.
There are packages like this or this which implement the necessary stuff for actually download files from Google Drive API in Unity.

How would I receive all fields from a dynamic form with Struts?

I found myself with the following problem:
I have a page generated with logic:iterate that shows the current supervisor and assistant of a service.
That page also acts as a form where people can add their possible substitutes, but you never know how many of those are there.
Due to the environment I am currently working with it had to be without JSTL so a lot of options were gone; couldn't get DynaActionForm working for this either.
Since I couldn't find anything but I already got the answer I decided to create this to answer anyone who might have the same issue.
Code:
public ActionForward post(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
String[] tot;
try {
Enumeration<?> fieldsForm = request.getParameterNames();
while(fieldsForm.hasMoreElements()) {
String current = (String) fieldsForm.nextElement();
tot = request.getParameterValues(current);
System.out.println("Field name is: " + current);
for (i=0; i<tot.length; i++) {
// do whatever you need to do; contents are in tot[i]
System.out.println("Value " + i + " is: " + tot[i]);
}
}
catch (Exception ex) {
ex.printStackTrace();
System.err.println(ex.getMessage());
}
}

openshift, rest apis binary deployment

I was following the link
https://access.redhat.com/documentation/en-US/OpenShift_Enterprise/2/pdf/REST_API_Guide/OpenShift_Enterprise-2-REST_API_Guide-en-US.pdf
to build my rest api java application that will deploy a WAR binary file from a web location into my account.
I am getting
InboundJaxrsResponse{context=ClientResponse{method=POST, uri=https://openshift.redhat.com/broker/rest/application/#{myAppID}/deployments, status=422, reason=Unprocessable Entity}} as a response:
where #{myAppID} is the app uuid that I replace here for security
I am using glassfish rest api and my piece of code is:
String url_of_war = "https://code.google.com/p/web-actions/downloads/detail?name=helloworld.war";
WebTarget webtarget;
Client client
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
#Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
};
client = ClientBuilder.newBuilder().sslContext(trustAllCertificates()).hostnameVerifier(hostnameVerifier ).build();
}
URIBuilder uriBuilder = new URIBuilder();
try {
uriBuilder = uriBuilder.setScheme("https").setHost("openshift.redhat.com/broker/rest/").setPath("application/#{myAppId}/deployments");
if (getPort() > 0) {
uriBuilder = uriBuilder.setPort(getPort());
}
URI uri = uriBuilder.build();
webtarget = client.target(uri);
} catch (Exception e) {
String msg = "Could not build URI!";
throw new RuntimeException(msg, e);
}
Invocation.Builder invocationBuilder = webtarget.request(MediaType.APPLICATION_JSON_TYPE).accept(MediaType.APPLICATION_JSON_TYPE);
invocationBuilder.header("Authorization", "Basic "+Base64.encodeBase64String("#{myuser}:#{mypass}".getBytes()));
Form form = new Form();
form.param("hot_deploy", "false");
form.param("force_clean_build", "false");
form.param("artifact_url", URLEncoder.encode(url_of_war, "UTF-8"));
Response response = invocationBuilder.post(Entity.form(form));
what am I doing wrong here, I am stuck in this since 30 days with no clue online, i also tried to create openshift/jboss compatible deployment folder where i placed the war file and made available for download as a copmressed .tar.gz file but same problem
your help is highly appreciated.
thank you
Binary deployments need to be in a very specific format, they can't just be a war file (or a zipped war file).
You should check out this blog article (https://blog.openshift.com/using-openshift-without-git/) about using binary deployments on OpenShift Online for further reference. I think it will help you get your code working.

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();
}

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

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";
}
}
});
}