FileUtils.copyUrlToFile is not working - java

I have fairly basic question i'm trying to download a PDF from this URL using java:
http://kundservice.svd.se/ui/templates/HttpHandler/PDFTidningen/PDFTidningen.ashx?date=2014-07-27&file=SVD_D_BILAGA_2014-07-27.pdf&mac=92267fcd3c75feff13154ba66870a523&free=True
here is my code "very basic":
public class Main {
private static final String PATH = "C:\\project\\DownloadTest\\src\\main\\resources\\tmp\\";
private static final String FILENAME = "data.pdf";
private static final String SvDPDFURL = "http://kundservice.svd.se/ui/templates/HttpHandler/PDFTidningen/PDFTidningen.ashx?date=2014-07-27&file=SVD_D_BILAGA_2014-07-27.pdf&mac=92267fcd3c75feff13154ba66870a523&free=True";
public static void main(String[] args) throws Exception{
File file = new File(PATH + FILENAME);
URL url = new URL(SvDPDFURL);
FileUtils.copyURLToFile(url, file);
}
}
the problem is that file is empty, what i'm i doing wrong.

Just make it https instead of http.
https://kundservice.svd.se/ui/templates/HttpHandler/PDFTidningen/PDFTidningen.ashx?date=2014-07-27&file=SVD_D_BILAGA_2014-07-27.pdf&mac=92267fcd3c75feff13154ba66870a523&free=True
It is happening because there is a redirect when you hit the url. It redirects to https. Browsers get the response and the response code is 302 then redirects to the given url but the FileUtility can not handle that.
To confirm use firebug or chrome developers tool by hitting F12 and go to Network tab.

Related

POST request failing when using Linux path in Java

I have the following #Service class in my Spring application:
#Service
public class FileService {
//#Autowired
//CustomerDetailsRepository customerDetailsRepository;
//private static final String FILE_DIRECTORY = "D:\\temp\\xmlFromAdmin";
private static final String FILE_DIRECTORY = "//opt//xmlFromAdmin";
static String fileName = "";
#Autowired
CustomerDetailsRepository customerDetailsRepository;
//private static CustomerDetails customerDetails;
//private static final String TRANSFORMED_FILE_DIRECTORY = "D:\\temp\\valuesToFrontend";
private static final String TRANSFORMED_FILE_DIRECTORY = "//opt//valuesToFrontend";
public void storeFile(MultipartFile file) throws Exception {
fileName = file.getOriginalFilename();
Path filePath = Paths.get(FILE_DIRECTORY + "/" + fileName);
File fullFilePath = new File(FILE_DIRECTORY + "/" + fileName);
String transformedFileName = TRANSFORMED_FILE_DIRECTORY+"/"+fileName;
Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
Thread.sleep(1000);
FileDecryption fileDecryption = new FileDecryption();
fileDecryption.transformDocument(fullFilePath,transformedFileName);
From the front-end, I am taking an XML file from the user, transforming it, and feeding values to the front-end. This code is running fine when I run this on my local Windows machine, with the commented out path. However, when I put the code into Linux, file upload is failing. The path in Linux is also specified. I am getting Error 500 when uploading, even though the URL is correct. What is the error here? This is the POST request in the service file in angular:
uploadLicenseFile(fileName: string, file: File): Observable<any> {
let headers = new HttpHeaders({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
//'Access-Control-Allow-Headers': 'X-Requested-With, content-type, Authorization'
'Access-Control-Allow-Headers': 'Content-Type,Accept,X-Access-Token,X-Key,Authorization,X-Requested-With,Origin,Access-Control-Allow-Origin,Access-Control-Allow-Credentials,content-type=multipart/*'
})
let options = {headers:headers, observer: 'response'};
const formData: FormData = new FormData();
formData.append('fileName', fileName);
formData.append('file', file);
//return this.http.post(this.url+'/fileUpload/upload', formData,options)
const req = new HttpRequest('POST', this.url+'/fileUpload/upload', formData, {
reportProgress: true,
responseType: 'json'
});
return this.http.request(req);
}
The problem was permission. The files being uploaded were by tomcat user whereas the directories I created were by root. Bypassed directory creation as of now.

Jersey, using HTML file instead of HTML string

Currently I need to programm a RESTful Webservice in Java and I'm using Grizzly server as my server and I'm using Jersey for the HTML code generation.
This is my Grizzly server:
public static void main(String[] args) throws IOException {
URI baseUri = URI.create("http://localhost:9998");
final ResourceConfig resourceConfig = new ResourceConfig(homepage.class);
final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(baseUri, resourceConfig);
System.out.println("Starting grizzly ...");
JOptionPane.showMessageDialog(null, "Stop Server");
server.shutdownNow();
}
And this is my current homepage code:
#Path("")
public class homepage {
#GET
#Produces("text/html")
public String sayHelloInHtml() {
return "<html><body><h2>Hello World</h2></body></html>";
}
}
Right now I'm using a string for my HTML code but is their a way to use a HTML file instead?
Also how can I create a button that triggers a Java method on click? I know how to create a button but I don't know how to make the event handler to trigger the Java method on click.

Decode WebTarget URI

I have one property in property file
appointments.deleteAppointmentwithReasonApi=api/appointment/{id}?reason={reason}
URL=http://xyz/etc/
in another file
public static final String DELETE_APPOINTMENT_REASON = PropertiesUtil.getPropertyValueFromKey(REST_WEBSERVICE_URLS_PROP_FILE,
"appointments.deleteAppointmentwithReasonApi"); // To get API name
public static final String URL = ServicesUtil.getURL(); // to get endpoint URL
In my java API call, I gave something like this
WebTarget target = client.target(CommonConstants.URL)
.path(CommonConstants.DELETE_APPOINTMENT_REASON)
.resolveTemplate("id", appointmentID).resolveTemplate("reason", reason);
System.out.println(target);
My response is printing like this...
JerseyWebTarget { http://xyz/etc/api/appointment/abc-123-ced-456%3Freason=Test }
which is not hitting the proper Web Services...I want it to be like this
JerseyWebTarget { http://xyz/etc/api/appointment/abc-123-ced-456?reason=Test }
I know i need to encode URL. I am not able to do it somehow. Any suggestion ?

File Upload Issues in Jersey RestFull Service

I'm using jersey as backend in one of my applications. I am having trouble in uplaoding file using jersey. I have used the common file upload code available on google.
#POST
#Path("/setProfileImage")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces(MediaType.TEXT_HTML)
public String setProfileImage(
#FormDataParam("profileimage") InputStream uploadedInputStream,
#QueryParam("myemail") String myemail) throws IOException {
String contextRoot = uri.getBaseUri().getPath();
String uploadedFileLocationOrig = httpRequest.getSession().getServletContext().getRealPath("") + "/images/" + myemail + "_orig.png";
FileUtils.copyInputStreamToFile(uploadedInputStream, new File(uploadedFileLocationOrig));
return "true";
}
The code runs without error, but the image copied at the destination is not valid and an empty file is returned when I hit this file using its url.
Any ideas what I'm doing wrong here?
I finally figured it out, the version of Jersey was pretty old i.e. 1.17 and following code worked like a charm for me
#POST
#Path("/setProfileImage")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces(MediaType.TEXT_HTML)
public String setProfileImage(
final MimeMultipart file,
#QueryParam("myemail") String myemail) throws IOException, javax.mail.MessagingException {
String uploadedFileLocationOrig = httpRequest.getSession().getServletContext().getRealPath("") + "/images/" + myemail + "_orig.png";
FileUtils.copyInputStreamToFile(file.getBodyPart(0).getInputStream(), new File(uploadedFileLocationOrig));
return "true";
}

Why am I getting a 400 response code?

I am trying to get some acquaintance in using facebook API using Java (restfb). I am trying out the following code.
public class FBJava {
private String API_Key = "xxxxxx";
private String API_Secret = "xxxxxxxx";
public String firstReq = "https://graph.facebook.com/oauth/authorize?client_id="+API_Key+"&" +
"redirect_uri=http://www.facebook.com/connect/login_success.html& scope=publish_stream,offline_access,create_event";
public String secondReq = "https://graph.facebook.com/oauth/access_token?client_id="+API_Key+"" +
"&redirect_uri=http://www.facebook.com/connect/login_success.html&client_secret="+API_Secret+"&code=";
public static void main(String[] args) throws IOException {
FBJava fb = new FBJava();
System.out.println(fb.firstReq);
URL request = new URL(fb.firstReq);
HttpURLConnection conn = (HttpURLConnection) request.openConnection();
conn.connect();
int code = conn.getResponseCode();
System.out.println(code);
}
}
When I run the firstReq string in the browser manually, it is redirecting me to the correct page. But when I check the response code I am getting a 400 which means that its a bad request. I want to know why does it respond differently when I try to run it through the program. I know I am doing something wrong, but want to know what is the mistake and why is it occurring? Any kind of insight in this matter would be appreciated.
There is an error in the firstReq url. It contains a whitespace character between "& scope". Try this (I just removed the whitespace):
public String firstReq = "https://graph.facebook.com/oauth/authorize?client_id="+API_Key+"&" +
"redirect_uri=http://www.facebook.com/connect/login_success.html&scope=publish_stream,offline_access,create_event";

Categories

Resources