Runtime.getRuntime().exec(), how to execute file from website link? - java

So far I've got this line to work perfectly and it executes calc.exe on my computer:
Runtime.getRuntime().exec("calc.exe");
But how can I download and execute a file from a website link? For example http://website.com/calc.exe
I found this code on the web but it doesn't work:
Runtime.getRuntime().exec("bitsadmin /transfer myjob /download /priority high http://website.com/calc.exe c:\\calc.exe &start calc.exe");

You use URL and/or URLConnection, download the file, save it somewhere (current working directory, or a temp directory, for example), then execute it using the Runtime.getRuntime().exec().

Using this answer as a starting point you could do this: (this uses HttpClient)
public static void main(String... args) throws IOException {
System.out.println("Connecting...");
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://website.com/calc.exe");
HttpResponse response = client.execute(get);
InputStream input = null;
OutputStream output = null;
byte[] buffer = new byte[1024];
try {
System.out.println("Downloading file...");
input = response.getEntity().getContent();
output = new FileOutputStream("c:\\calc.exe");
for (int length; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
System.out.println("File successfully downloaded!");
Runtime.getRuntime().exec("c:\\calc.exe");
} finally {
if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
}
}

Related

Download File from Direct Download URL

I'm trying to download the following the following file, with this link that redirects you to a direct download: http://www.lavozdegalicia.es/sitemap_sections.xml.gz
I've done my own research, but all the results I see are related to HTTP URL redirections
[3xx] and not to direct download redirections (maybe I'm using the wrong terms to do the research).
I've tried the following pieces of code (cite: https://programmerclick.com/article/7719159084/ ):
// Using Java IO
private static void downloadFileFromUrlWithJavaIO(String fileName, String fileUrl) {
BufferedInputStream inputStream = null;
FileOutputStream outputStream = null;
try {
URL url = new URL(fileUrl);
inputStream = new BufferedInputStream(url.openStream());
outputStream = new FileOutputStream(fileName);
byte data[] = new byte[1024];
int count;
while ((count = inputStream.read(data, 0, 1024)) != -1) {
outputStream.write(data, 0, count);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Using Apache common IO
private static void downloadFileFromUrlWithCommonsIO(String fileName, String fileUrl) {
try {
FileUtils.copyURLToFile(new URL(fileUrl), new File(fileName));
} catch (IOException e) {
e.printStackTrace();
}
}
// Using NIO
private static void downloadFileFromURLUsingNIO(String fileName, String fileUrl) {
try {
URL url = new URL(fileUrl);
ReadableByteChannel readableByteChannel = Channels.newChannel(url.openStream());
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
fileOutputStream.getChannel().transferFrom(readableByteChannel, 0, Long.MAX_VALUE);
fileOutputStream.close();
readableByteChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
But the result I get with any of the three options is an empty file, my thoughts are that the problem is related to the file being a .xml.gz because when I debug it the inputStream doesn't seem to have any content.
I ran out of options, anyone has an idea of how to handle this case, or what would be the correct terms I should use to research about this specific case?
I found a solution, there's probably a more polite way of achieving the same result but this worked fine for me:
//Download the file and decompress it
filecount=0;
URL compressedSitemap = new URL(urlString);
HttpURLConnection con = (HttpURLConnection) compressedSitemap.openConnection();
con.setRequestMethod("GET");
if (con.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP || con.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM) {
String location = con.getHeaderField("Location");
URL newUrl = new URL(location);
con = (HttpURLConnection) newUrl.openConnection();
}
String file = "/home/user/Documentos/Decompression/decompressed" + filecount + ".xml";
GZIPInputStream gzipInputStream = new GZIPInputStream(con.getInputStream());
FileOutputStream fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = gzipInputStream.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
filecount++;
Two things to note:
When I was trying to do HTTPGet the url that was a redirect, the response code was 301 or 302 (depending on the example I used), I overcame this problem with the if check, that follows the redirect and aims to the downloaded file.
Once aiming the file, to get the content of the compressed file I found the GZIPInputStream package, that allowed me to get an inputStream directly from the compressed file and dump it on an xml file, that saved me the time of doing it on three steps (decompress, read, copy).

How can I stream .mp3 files in Java?

I want to stream mp3 files and accessing them using spring, but i dont know how :( have already searched the internet but havent found anything yet. I already tried it using Streams and it worked kinda, but every song starts at the beginning and other people also start at the beginning of the song. My code:
Backend:
new Thread(() -> {
stream = new ByteArrayOutputStream();
while(true){
try {
currentSong = files[rd.nextInt(files.length-1)];
InputStream is = new FileInputStream(new File(currentSong));
int read = 0;
byte[] bytes = new byte[1024];
while((read = is.read(bytes)) !=-1){
stream.write(bytes, 0, read);
}
stream.flush();
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();;
Frontend:
public class DnBController {
#GetMapping("/dnb")
public String play(HttpServletResponse httpServletResponse) throws IOException {
OutputStream os = httpServletResponse.getOutputStream();
httpServletResponse.setContentType("audio/mpeg");
DnbradioApplication.stream.writeTo(httpServletResponse.getOutputStream());
return "site.html";
}

Uploading a user file on discord bot

I'm trying to have users submit files on discord that are then uploaded to a site for processing. However, there seem to be something wrong wiht my code.
When i upload a file i get respone code 400 (bad request) but the site should accept files of w3g format.
private static void onFileUpload(Message.Attachment attachment, TextChannel channel) {
// api.wc3stats.com/upload
String fileName = attachment.getFileName();
if (fileName.substring(fileName.length() - 3).equals("w3g")) {
File file = new File(attachment.getFileName());
attachment.downloadToFile(file);
try {
HttpHelper.postFile(file, "https://api.wc3stats.com/upload");
channel.sendMessage("Uploading: " + file.toString()).queue();
} catch (IOException e) {
e.printStackTrace();
channel.sendMessage(e.getMessage()).queue();
}
System.out.println("Deleted");
file.delete();
} else {
channel.sendMessage("Invalid file type.").queue();
}
}
public static void postFile(File file, String url) throws IOException {
HttpURLConnection connection = null;
FileInputStream fis = null;
BufferedInputStream bis = null;
BufferedOutputStream out = null;
try {
URL urlForPostRequest = new URL(url);
connection = (HttpURLConnection) urlForPostRequest.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
//if (responseCode == HttpURLConnection.HTTP_OK) {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
out = new BufferedOutputStream(connection.getOutputStream());
byte[] buffer = new byte[8192];
int i;
while ((i = bis.read(buffer)) > 0) {
out.write(buffer, 0, i);
}
//}
int responseCode = connection.getResponseCode();
System.out.println("Response: " + connection.getResponseMessage());
System.out.println(responseCode);
} finally {
if (fis != null) fis.close();
if (bis != null) bis.close();
if (out != null) out.close();
System.out.println("closed");
}
}
The current exception it's throwing me is that the file cannot be found. But I can clearly see it in the program directory after it's been attached to discord and downloaded. This also only happens the first time I upload the file. The second time i upload the same file it just gives me the bad request response.
First upload attempt LastReplay.w3g output:
java.io.FileNotFoundException: lol.w3g
C:\SomePath\lol.w3g
cannot be read
closed
Deleted
I can also note that the file now exists in the program directory. Though it should've been removed after everything is complete.
Second upload attempt of LastReplay.w3g output
C:\SomePath\lol.w3g
Can be read
Response: Bad Request
closed
Deleted
I managed to do it using Javascript with help using request-promise, as for java i did not...
if (msg.attachments.size > 0) {
let attached = msg.attachments.array()[0];
const request = require('request-promise');
let formData = {
file: request (attached.url)
};
request.post('https://api.wc3stats.com/upload', {formData, json: true})
.then(function (json) {
// on success handle response json
})
.catch(function (err) {
console.log(err);
});
}

PlayFramework. How to upload a photo using an external endpoint?

How do I upload a photo using a URL in the playframework?
I was thinking like this:
URL url = new URL("http://www.google.ru/intl/en_com/images/logo_plain.png");
BufferedImage img = ImageIO.read(url);
File newFile = new File("google.png");
ImageIO.write(img, "png", newFile);
But maybe there's another way. In the end I have to get the File and file name.
Example controller:
public static Result uploadPhoto(String urlPhoto){
Url url = new Url(urlPhoto); //doSomething
//get a picture and write to a temporary file
File tempPhoto = myUploadPhoto;
uploadFile(tempPhoto); // Here we make a copy of the file and save it to the file system.
return ok('something');
}
To get that photo you can use The play WS API, the code behind is an example extracted from the play docs in the section Processing large responses, I recommend you to read the full docs here
final Promise<File> filePromise = WS.url(url).get().map(
new Function<WSResponse, File>() {
public File apply(WSResponse response) throws Throwable {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = response.getBodyAsStream();
// write the inputStream to a File
final File file = new File("/tmp/response.txt");
outputStream = new FileOutputStream(file);
int read = 0;
byte[] buffer = new byte[1024];
while ((read = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, read);
}
return file;
} catch (IOException e) {
throw e;
} finally {
if (inputStream != null) {inputStream.close();}
if (outputStream != null) {outputStream.close();}
}
}
}
);
Where url is :
String url = "http://www.google.ru/intl/en_com/images/logo_plain.png"
This is as suggested in play documentation for large files:
*
When you are downloading a large file or document, WS allows you to
get the response body as an InputStream so you can process the data
without loading the entire content into memory at once.
*
Pretty much the same as the above answer then some...
Route: POST /testFile 'location of your controller goes here'
Request body content: {"url":"http://www.google.ru/intl/en_com/images/logo_plain.png"}
Controller(using code from JavaWS Processing large responses):
public static Promise<Result> saveFile() {
//you send the url in the request body in order to avoid complications with encoding
final JsonNode body = request().body().asJson();
// use new URL() to validate... not including it for brevity
final String url = body.get("url").asText();
//this one's copy/paste from Play Framework's docs
final Promise<File> filePromise = WS.url(url).get().map(response -> {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = response.getBodyAsStream();
final File file = new File("/temp/image");
outputStream = new FileOutputStream(file);
int read = 0;
byte[] buffer = new byte[1024];
while ((read = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, read);
}
return file;
} catch (IOException e) {
throw e;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}); // copy/paste ended
return filePromise.map(file -> (Result) ok(file.getName() + " saved!")).recover(
t -> (Result) internalServerError("error -> " + t.getMessage()));
}
And that's it...
In order to serve the file after the upload phase you can use this answer(I swear I'm not promoting myself...): static asset serving from absolute path in play framework 2.3.x

File download in httpclient using java?

My code is,
import java.io.*;
import java.net.*;
public class DownloadHttp
{
public static void main(String a[])
{
DownloadHttp d = new DownloadHttp();
String addr = "http://www.gmail.com";
String file = "D:/venkatesh/Software/download1.html";
d.download(addr,file);
}
public void download(String address, String localFileName) {
OutputStream out = null;
URLConnection conn = null;
InputStream in = null;
try {
// Get the URL
URL url = new URL(address);
// Open an output stream to the destination file on our local filesystem
out = new BufferedOutputStream(new FileOutputStream(localFileName));
conn = url.openConnection();
in = conn.getInputStream();
// Get the data
byte[] buffer = new byte[1024];
int numRead;
while ((numRead = in.read(buffer)) != -1) {
out.write(buffer, 0, numRead);
}
// Done! Just clean up and get out
} catch (Exception exception) {
exception.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (IOException ioe) {
// Shouldn't happen, maybe add some logging here if you are not
// fooling around ;)
}
}
}
}
Here I wants download specific file using httpClient using java.
It produces:
"java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)" as error.
How to resolve it, help me, thanks in advance.
I believe it is a network problem. Have you tried to access the url directly or are you behind a firewall?
Recompiled your code on my machine, it works perfectly well. I'm able to fetch files from the web.
Check if your web-browser can download the file for you (make sure it's not a network problem)
One thing to notice though, in your finally block you might want to close the streams separately. So if anything goes wrong with the input stream, the output stream will still be closed.
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception ignored) {}
try {
if (out != null) {
out.close();
}
} catch (Exception ignored) {}
}
I think you are using a proxy when connecting to internet.
Set these in the code and then retry.
System.setProperty("http.proxyHost", *Proxy-IP*);
System.setProperty("http.proxyPort", *Proxy-Port*);

Categories

Resources