1

I am trying to download a PDF file available at one of the rest URL using JAX RS and Jersey with authorization .

import org.apache.commons.io.IOUtils;
import javax.net.ssl.*;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.File;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

public class ReportView {
    public void process(String authStringEnc) {

        System.setProperty("javax.net.ssl.trustStore","C:\\Users\\alim\\Desktop\\my-app\\stage\\npkeystore.jks");
        System.setProperty("javax.net.ssl.trustStorePassword","changeit");
        System.setProperty("javax.net.ssl.trustAnchors","C:\\Users\\alim\\Desktop\\my-app\\stage\\npkeystore.jks");

        Client client = ClientBuilder.newClient();
       // WebTarget target = client.target("https://x.x.x.x/api/profiler/1.0/reporting/reports/751252/").path("view");
        WebTarget target = client.target("https://x.x.x.x/api/profiler/1.0/reporting/reports/751252/view");

        Response resp = target.request("application/pdf,image/jpeg,application/xml,application/vnd.ms-excel").header("Authorization", authStringEnc).get(Response.class);


        System.out.println("Code : " + resp.getStatus());

        if(resp.getStatus() == Response.Status.OK.getStatusCode()) {
            InputStream is = resp.readEntity(InputStream.class);

            File downloadfile = new File("C://Users/alim/Downloads/view.pdf");
            try {

                byte[] byteArray = IOUtils.toByteArray(is);
                FileOutputStream fos = new FileOutputStream(downloadfile);
                fos.write(byteArray);
                fos.flush();
                fos.close();
            }catch(Exception e){
                e.getMessage();
            }

            IOUtils.closeQuietly(is);
            System.out.println("the file details after call:"+ downloadfile.getAbsolutePath()+", size is "+downloadfile.length());
        }
        else{
            throw new WebApplicationException("Http Call failed. response code is"+resp.getStatus()+". Error reported is"+resp.getStatusInfo());
        }
    }

But the above code snippet returns a 400 Bad Request . Not sure if I have specified the URL incorrectly . Using the same URL in Postman returns a PDF file .

Exception in thread "main" javax.ws.rs.WebApplicationException: Http Call failed. response code is 400. Error reported is Bad Request

Also removing the certificate block returns me PKIX Certification Exception while I have already defined it in main class and using it in one of the subclass .

Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

JAX-RS and Jersey concepts are pretty new to me. Not Sure where I am going wrong in terms of specifying URL with authentication,certificate and request.

Any help/guidance over same would really help.

Alim Azad
  • 471
  • 2
  • 9
  • 23
  • Is the endpoint developed by yourself too? Can you share the code of the endpoint? – Bentaye Nov 23 '18 at 08:36
  • @Bentaye : No. The endpoint is a riverbed netprofiler reporting tool that extracts reports . Reference : **https://support.riverbed.com/apis/profiler/1.0/service.html)** wherein the rest api call to get reports is mentioned **https://{device}/api/profiler/1.0/reporting/reports/{report_id}** . To get GUI view of reports in browser , URL **https://{device}/api/profiler/1.0/reporting/reports/{report_id}/view** needs to be hit . I need to download the viewed report in PDF format . Please guide . – Alim Azad Nov 24 '18 at 09:51
  • I have referred below query for the same **https://stackoverflow.com/questions/24716357/jersey-client-to-download-and-save-file** – Alim Azad Nov 24 '18 at 09:54
  • Would you mind trying this url `http://enos.itcollege.ee/~jpoial/java/naited/pildid/corejava.pdf` just to check that you can download PDFs (no Authorization header needed) – Bentaye Nov 26 '18 at 16:02

2 Answers2

0

Might be a comment but can't format that in a comment.

Reading the doc I can see that

  1. Retrieve the report data.

Once the report completes, the client can retrieve its data or the rendered version of the report in a number of formats.

The following resources can be used to retrieve a rendered version of the report:

/profiler/1.0/reporting/reports/{id}/view.pdf
/profiler/1.0/reporting/reports/{id}/view.csv

These are for PDF and CSV versions respectively.

Could you try

WebTarget target = client
    .target("https://x.x.x.x/api/profiler/1.0/reporting/reports/751252/view.pdf");
Response resp = target
    .request("application/pdf,image/jpeg,application/xml,application/vnd.ms-excel")
    .header("Authorization", authStringEnc)
    .get(Response.class);
Bentaye
  • 9,403
  • 5
  • 32
  • 45
  • No its the same issue still . Is there an other way round to download file using HttpsURLConnection with authentication? – Alim Azad Nov 26 '18 at 12:37
0

I tried an other way round and was able to download the PDF files . Below is the code snippet for the same .

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


        String download_url = "https://x.x.x.x/api/profiler/1.0/reporting/reports/" + reportID +"/view";
        String name = "report";
        String password = "report";
        String authString = name + ":" + password;
        String authStringEnc = Base64.getEncoder().encodeToString(authString.getBytes());

        System.out.println(" Downloading " + name + " report");

        Client restClient = Client.create();
        WebResource webResource = restClient.resource(download_url);
        ClientResponse resp = webResource.header("Authorization", "Basic " + authStringEnc)
                .get(ClientResponse.class);


        if(resp.getStatus() != 200){
            System.err.println(" Failed : HTTP error code : " + resp.getStatus());
        }
        else
        {
            System.out.println(" Response : " + resp.getStatus() + " OK. Successfully Connected");
        }

        InputStream is = resp.getEntityInputStream();
        OutputStream os = new FileOutputStream(curDir + "\\" + country.toLowerCase() + "\\ReportsExtracted\\" + name + ".pdf");

        byte[] buffer = new byte[1024];
        int bytesRead;

        while((bytesRead = is.read(buffer)) != -1){
            os.write(buffer, 0, bytesRead);
        }
        is.close();

        //flush OutputStream to write any buffered data to file
        os.flush();
        os.close();

        System.out.println(" Downloaded " + name + " report");

Hope this helps.

user229044
  • 232,980
  • 40
  • 330
  • 338
Alim Azad
  • 471
  • 2
  • 9
  • 23