Java :Not able to download spreadsheet using google drive API - java

I am trying to download a file from the drive using google drive api
Steps to reproduce :
Step 1:
Click on :https://developers.google.com/drive/v3/reference/files/export#try-it
Step 2:
I have provided fileid and mimetype
I gave fileid and mime type as "application/vnd.google-apps.spreadsheet" and click on execute.i got this error:
"code":403,
"message":"Export requires alt=media to download the exported content."
public static void downloadFile(Drive service,String fileId) throws IOException{
OutputStream outputStream = new ByteArrayOutputStream();
//OutputStream outputStream = new FileOutputStream("/Users/xxxxx/Downloads/driveFile.xls");
//service.get
service.files().export(fileId,"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
.executeMediaAndDownloadTo(outputStream);
}

Based on the error you are getting...
https://developers.google.com/drive/v3/web/manage-downloads
Try adding "?alt=media" to your GET request. My guess is you are missing something in the input parameters or possibly do not have access to the media (not logged in maybe?). I can't help more without seeing the actual code you are attempting to call, or the request you are making.

Related

how to specify a path for a file in repository ( java ) , so that my automation test won't fail

I'm testing an API with rest assured, programming language is JAVA, I'm having little issue, the issue is , I have to send an image using rest assured, and it's being sent successfully locally, but when i push it to git , having problem with specifying the path, and all my tests are run on TeamCity , and I get my cucumber report, report as follows
java.io.FileNotFoundException: C:\Users\nameOfUser\Downloads\38250987.jpeg (The system cannot find the path specified)
I hope I have delivered the issue descriptive enough, in case if u have any questions,doubts please do ask your questions, hoping for your help and cooperation, thanks in advance!
the code as follows
public static Response SendAnImage(String prodID,Cookies cookies) {
File file = new File("C:\\Users\\userName\\Downloads\\38250987.jpeg");
System.out.println("is file found ----> "+file.exists());
Response response = given()
.multiPart("file", file, "image/jpeg")
.when()
.cookies(cookies)
.post("/api/product/"+prodID+"/file/false");
return response;
}
You can put your file in src/test/resources folder, then create a new File like this:
File file = new File("src/test/resources/38250987.jpeg");
You cannot refer to local files in your tests. You need to include the picture file to your Git repository, load them as a resource in the test and then use the method in REST-assured that accepts a byte array instead of a file:
multiPart(String controlName, String fileName, byte[] bytes)

Read and Append data to the File from a Blob URL path before download

This is my first hands on using Java Spring boot in a project, as I have mostly used C# and I have a requirement of reading a file from a blob URL path and appending some string data(like a key) to the same file in the stream before my API downloads the file.
Here are the ways that I have tried to do it:
FileOutputStream/InputStream: This throws a FileNotfoundException as it is not able to resolve the blob path.
URLConnection: This got me somewhere and I was able to download the file successfully but when I tried to write/append some value to the file before I download, I failed.
the code I have been doing.
//EXTERNAL_FILE_PATH is the azure storage path ending with for e.g. *.txt
URL urlPath = new URL(EXTERNAL_FILE_PATH);
URLConnection connection = urlPath.openConnection();
connection.setDoOutput(true); //I am doing this as I need to append some data and the docs mention to set this flag to true.
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write("I have added this");
out.close();
//this is where the issues exists as the error throws saying it cannot read data as the output is set to true and it can only write and no read operation is allowed. So, I get a 405, Method not allowed...
inputStream = connection.getInputStream();
I am not sure if the framework allows me to modify some file in the URL path and read it simultaneously and download the same.
Please help me in understanding if they is a better way possible here.
From logical point of view you are not appending data to the file from URL. You need to create new file, write some data and after that append content from file from URL. Algorithm could look like below:
Create new File on the disk, maybe in TMP folder.
Write some data to the file.
Download file from the URL and append it to file on the disk.
Some good articles from which you can start:
Download a File From an URL in Java
How to download and save a file from Internet using Java?
How to append text to an existing file in Java
How to write data with FileOutputStream without losing old data?

Send image as API response

I need to send images as API response.I created a response but i still cant not send the image.I am using play framework with java.
Http.Response response = new Http.Response();
response.setContentType("image/jpeg");
Thanks.
Do not really know what version of play are you using but this should work for 2.X
public static Result returnImage(){
return ok(new File("public/img/1.jpg")).as("image/jpg");
}
Here you can see that ok() can receive a File as a parameter. To check all the options you can go to Play Framework JavaDocs.
Hope it helps!
Previous answer is correct, however if image is large, I would suggest using chunks and streams:
public Result send() throws FileNotFoundException {
FileInputStream fis = new FileInputStream(new File("some_path/test.jpeg"));
response().setContentType("image/jpeg");
return ok(fis);
}

Generating a dynamic file and download it in GWT

I am developing a GWT application. This application is running in a server. Well, I implement a button which calls a method that generates a local file in server side. However I would like to download/generate this file in client side. How could I do this in GWT?
Thanks
In our project we created a file on server on demand. When the file has been successful created we send notification to browser and created a link.
See servlet code:
public class DownloadServlet extends HttpServlet {
private FileManager fileManager;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String encodedFileName = req.getRequestURI().substring(
req.getContextPath().length() + req.getServletPath().length() + 1);
String decodedFileName = URLDecoder.decode(encodedFileName, "utf-8");
File downloadableFile = fileManager.toFile(decodedFileName);
ServletOutputStream os = resp.getOutputStream();
try {
InputStream is = FileUtils.openInputStream(downloadableFile);
try {
IOUtils.copy(is, os);
} finally {
is.close();
}
} finally {
os.close();
}
}
}
private native void Download(String filename, String text)/*-{
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
pom.setAttribute('download', filename);
document.body.appendChild(pom);
pom.click();
document.body.removeChild(pom); }-*/;
Use JSNI method inside GWT code , provide the file name you want to download in addition to JSON string as text (String) , this method will download a file with specified content in text variable to client browser.
Current situation is, that not all browsers are able to work with local file system, so there is no universal solution in GWT. Also as far as I know FilesSstem API is not finished.
As alternative you can keep using serverside generated files, or use Flash plugin to generate and store files (you will have to create a Flash app, and create some API to control it from GWT).
You should definitely have a look at Aki Miyazaki’s HTML5 file download code for GWT.
It works on the client side as you requested.
AFAIK, as of now, it only works in Chrome, but this is supposed to change as other browsers implement the download attribute.
You can do that using Data URIs:
Make your GWT RPC method return the file content or the data to generate the file.
On the client side, format a Data URI with the file content received or generate the data content.
Use Window.open to open a file save dialog passing the formatted DataURI.
Take a look at this reference, to understand the Data URI usage:
Export to csv in jQuery

Java URL problem

A webpage contains a link to an executable (i.e. If we click on the link, the browser will download the file on your local machine).
Is there any way to achieve the same functionality with Java?
Thank you
Yes there is.
Here a simple example:
You can have a JSF(Java Server Faces) page, with a supporting backing bean that contains a method annotated with #PostConstruct This means that any action(for example downloading), will occur when the page is created.
There is already a question very similar already, have a look at: Invoke JSF managed bean action on page load
You can use Java's, URL class to download a file, but it requires a little work. You will need to do the following:
Create the URL object point at the file
Call openStream() to get an InputStream
Open the file you want to write to (a FileOutputStream)
Read from the InputStream and write to the file, until there is no more data left to read
Close the input and output streams
It doesn't really matter what type of file you are downloading (the fact that it's an executable file is irrelevant) since the process is the same for any type of file.
Update: It sounds like what you actually want is to plug the URL of a webpage into the Java app, and have the Java app find the link in the page and then download that link. If that is the case, the wording of your question is very unclear, but here are the basic steps I would use:
First, use steps 1 and 2 above to get an InputStream for the page
Use something like TagSoup or jsoup to parse the HTML
Find the <a> element that you want and extract its href attribute to get the URL of the file you need to download (if it's a relative URL instead of absolute, you will need to resolve that URL against the URL of the original page)
Use the steps above to download that URL
Here's a slight shortcut, based on jsoup (which I've never used before, I'm just writing this from snippets stolen from their webpage). I've left out a lot of error checking, but hey, I usually charge for this:
Document doc = Jsoup.connect(pageUrl).get();
Element aElement = doc.getElementsByTag("a").first() // Obviously you may need to refine this
String newUrl = aElement.attr("abs:href"); // This is a piece of jsoup magic that ensures that the destination URL is absolute
// assert newUrl != null
URL fileUrl = new URL(newUrl);
String destPath = fileUrl.getPath();
int lastSlash = destPath.lastIndexOf('/');
if (lastSlash != -1) {
destPath = destPath.substring(lastSlash);
}
// Assert that this is really a valid filename
// Now just download fileUrl and save it to destPath
The proper way to determine what the destination filename should be (unless you hardcode it) is actually to look for the Content-Disposition header, and look for the bit after filename=. In that case, you can't use openStream() on the URL, you will need to use openConnection() instead, to get a URLConnection. Then you can use getInputStream() to get your InputStream and getRequestProperty("Content-Disposition") to get the header to figure out your filename. In case that header is missing or malformed, you should then fall-back to using the method above to determine the destination filename.
You can do this using apache commons IO FileUtils
http://commons.apache.org/io/apidocs/org/apache/commons/io/FileUtils.html#copyURLToFile(java.net.URL, java.io.File)
Edit:
I was able to successfully download a zip file from source forge site (it is not empty), It did some thing like this
import java.io.File;
import java.net.URL;
import org.apache.commons.io.FileUtils;
public class Test
{
public static void main(String args[])
{
try {
URL url = new URL("http://sourceforge.net/projects/gallery/files/gallery3/3.0.2/gallery-3.0.2.zip/download");
FileUtils.copyURLToFile(url, new File("test.zip"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I was able successfully download tomcat.exe too
URL url = new URL("http://archive.apache.org/dist/tomcat/tomcat-6/v6.0.16/bin/apache-tomcat-6.0.16.exe");

Categories