download file from database through browser in java desktop (non web) - java

is it possible to download file from database through browser (ex: mozilla,chrome) in java desktop application (non web app) ? can you explain me with an example code ?
thanks in advance,

Use Desktop#browse() wherein you just specify the URI of that file (exactly the one as you would enter in the address bar of a normal webbrowser).
Desktop.getDesktop().browse(new URI("http://example.com/download/file.ext"));
The other side has just to set Content-Disposition: attachment on this response to force a Save As dialogue (and of course fill the response body with the necessary data from the DB).

Anything that is available through a browser should be available to a Java desktop app. At least unless the server (e.g. Google) goes to measures to block 'programmatic access'.
can you explain me with an example code?
Sure, adapted from the Java Sound info. page.
import java.net.URL;
import javax.swing.*;
import javax.sound.sampled.*;
public class LoopSound {
public static void main(String[] args) throws Exception {
// imagine a DB is preparing/serving this - same difference.
URL url = new URL(
"http://pscode.org/media/leftright.wav");
Clip clip = AudioSystem.getClip();
AudioInputStream ais = AudioSystem.
getAudioInputStream( url );
clip.open(ais);
clip.loop(-1);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(null, "Close to exit!");
}
});
}
}

Related

Calling a webpage without opening it from processing

I'm totally desperate trying to do this. I Started a new job where I was given an app made in Processing and now I need it to call a simple index.html(https://west-4f2bc.firebaseapp.com) but not opening it on the browser.
Is there anyway to do it?
later I'm going to pass data adding parameters in URL but now I just need to call it as it is without a window opening.
Please Help me.....
I tried a lot of variants of this code
import processing.net.*;
Client myClient;
void setup() {
// Connect to the local machine at port 10002.
// This example will not run if you haven't
// previously started a server on this port.
myClient = new Client(this, "west-4f2bc.firebaseapp.com", 80);
// Say hello
myClient.write("GET /\r\n");
}
void draw() {
}
Thanks.
With this I only get true, so it connects but I only get 0.
import processing.net.*;
Client myClient;
int dataIn;
void setup() {
size(200, 200);
// Connect to the local machine at port 5204.
// This example will not run if you haven't
// previously started a server on this port.
myClient = new Client(this, "west-4f2bc.firebaseapp.com", 80);
println(myClient.active());
println(dataIn);
}
void draw() {
}
with this I get connected but after Client SocketException: Socket closed
import processing.net.*;
Client myClient;
int dataIn;
void setup() {
Client client;
client = new Client(this, "west-4f2bc.firebaseapp.com", 80);
if (client.active()==true) {
println("connected");
// Make a HTTP request:
client.write("GET /call.html?id=ola&nome=artur\r\n");
client.write("\r\n");
client.stop();
} else {
// if you didn't get a connection to the server:
println("connection failed");
}
}
I've never really used Processing's Networking library, but from what I can tell it's not usually used to read data from a website- it's used for lower-level communication between a client and server. It might be possible to use it to read a website, but what you have already looks more complicated than it has to be.
Remember that Processing is built on top of Java, so anything you can do in Java, you can do in Processing. If I were you, I would do a google search for "java read website" for a ton of results, including:
Reading Directly from a URL
How to read a text file directly from Internet using Java?
Reading website's contents into string
How to read a text from a web page with Java?
Using Java to pull data from a webpage?
I used another library.
import http.requests.*;
void setup()
{
size (100, 100);
}
void draw()
{
PostRequest post = new PostRequest("https://"+"www.example.com");
post.send();
System.out.println("Reponse Content: " + post.getContent());
System.out.println("Reponse Content-Length Header: " + post.getHeader("Content-Length"));
noLoop();
}
Still doesnt does my final objective but at least it can communicate with the page.

Get the path of a file via file explorer

First of all I'm sorry if this question has been asked before or if there is documentation about the topic but i didn't found anything.
I want to make a windows app that open windows file explorer and you can browse for and then select a mp3 file, so you can play it (and replay it) in this program. I know how to open file explorer, this is my code :
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
public class Main
{
public static void main(String[] args) throws IOException {
Desktop desktop = Desktop.getDesktop();
File dirToOpen = null;
try {
dirToOpen = new File("c:\\");
desktop.open(dirToOpen);
} catch (IllegalArgumentException iae) {
System.out.println("File Not Found");
}
}
}
But i don't know how to select an mp3 file and then get the path of the file, so i can play it later.
I don't think you are approaching this right. You should use something like a FileDialog to choose a file:
FileDialog fd = new FileDialog(new JFrame());
fd.setVisible(true);
File[] f = fd.getFiles();
if(f.length > 0){
System.out.println(fd.getFiles()[0].getAbsolutePath());
}
Since you are only getting 1 MP3 file, you only need the first index of the File array returned from the getFiles() method. Since it is a modal dialog, the rest of your application will wait until after you choose a file. If you want to get multiple files at once, just loop through this aforementioned Files array.
See the documentation here: https://docs.oracle.com/javase/7/docs/api/java/awt/FileDialog.html

Error Accessing Embedded Resource

I'm making a program, and I want it to start playing sounds when it opens. I figured the easiest way for me to do this is to embed the .wav file in the src folder in my jar. I have placed the file in a packaged called files and all the other files i am using such as pictures are in that package and they all work fine. my method for playing sounds is here:
public static void playSound(String dir, int loopTimes) throws Exception {
URL url = new File(dir).toURI().toURL();
Clip clip = AudioSystem.getClip();
// getAudioInputStream() also accepts a File or InputStream
AudioInputStream ais = AudioSystem.getAudioInputStream(url);
clip.open(ais);
if (loopTimes == -1)
loopTimes = Clip.LOOP_CONTINUOUSLY;
clip.loop(loopTimes);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
}
});
}
and it works for playing the sounds when they are on my desktop, my documents, anywhere else. the path that i am inputting for playing the sound is "files/FBP.wav" were FBP is the name of the file. i havent been able to find any solutions on google, and i have the feeling that it is because it is in the JAR. I have also just simply tried this:
if(new File("files/FBP.wav").exists()){
System.out.println("EXISTS!");
}
System.exit(0);
and it never printed out that it exists. i have made sure that it is in the bin folder as well. i am using eclipse. the error i get is filenotfoundexception. any help is appreciated! Thanks in advance!
Replace:
URL url = new File(dir).toURI().toURL();
With:
URL url = MySoundClassName.class.getClassLoader().getResource(dir);
Or for non-static methods:
URL url = getClass().getClassLoader().getResource(dir);

playing .mp3 file in java using notepad

I know this is a repeat question.
check original one here or here.
So my code is just the copy paste :
import javafx.scene.media.*;
class Gui {
public static void main(String[] args) {
try{
Media hit = new Media("skin.mp3");
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();
}catch(Exception e){
e.printStackTrace();
}
}
}
The exception which i'm getting is :
java.lang.IllegalArgumentException: uri.getScheme() == null!
at com.sun.media.jfxmedia.locator.Locator.<init>(Locator.java:217)
at javafx.scene.media.Media.<init>(Media.java:364)
at Gui.main(gui.java:6)
I'm compiling & running it correctly i.e. by including the jfxrt.jar file in classpath
Note: I'm just using notepad instead of any IDE.
So can anyone tell me the reason of IllegalArgumentException
Thankx
UPDATE : By using file://e:/skin.mp3 it worked fine but left me with another exception :
MediaException: MEDIA_INACCESSIBLE : e
at javafx.scene.media.Media.<init>(Unknown Source)
at Gui.main(gui.java:6)
So if you can put some light on this exception.
By the way i've checked the song, its not corrupt because it is playing nicely in vlc.
From the JavaFX API docs
The supplied URI must conform to RFC-2396 as required by java.net.URI.
Only HTTP, FILE, and JAR URIs are supported.
So, I suspect from reading the docs, you need to supply a URI path.
Something like file://path/to/file/skin.mp3 will probably work.
There are a few problems with the code in this question.
The class needs to be public.
JavaFX 2 applications need to extend the Application class.
JavaFX 2 applications should define a start method.
The locator for the media being created should be a full URI as noted by MadProgrammer.
Even though the question has a javafx-2 tag, I wonder if it is written for JavaFX 1.x JavaFX Script (which is now an unsupported programming language and incompatible with JavaFX 2). If so, I'd recommend coding in Java and using JavaFX 2.x for this rather than JavaFX Script.
On Windows a file representation of an absolute locator of a URI has three slashes after the file protocol. For example, the following is valid:
file:///C:/Users/Public/Music/skin.mp3
For some reason, a single slash will also work (I guess internally Java will interpolate the extra // for the protocol specifier on files or perhaps there is something I don't understand in the URL specification which means that you don't need a // after the protocol).
file:/C:/Users/Public/Music/skin.mp3
One way to check the file uri for something is valid to ask if the file uri exists
System.out.println("File " + filename + " exists? " + new File(filename).exists());
After you know your file uri is valid, you can convert it to a string using.
file.toURI().toURL().toExternalForm()
Here is a short sample program for playing some audio in JavaFX using a MediaPlayer with a little bit of error handling, so that it is easier to understand if something goes wrong.
import java.io.File;
import java.net.MalformedURLException;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.media.*;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
/** plays an audio in JavaFX 2.x */
public class SimpleAudioPlayer extends Application {
public static void main(String[] args) { launch(args); }
#Override public void start(Stage stage) throws MalformedURLException {
final Label status = new Label("Init");
MediaPlayer mediaPlayer = createMediaPlayer(
"C:/Users/Public/Music/Sample Music/Future Islands - Before the Bridge.mp3",
status
);
StackPane layout = new StackPane();
layout.getChildren().addAll(status);
stage.setScene(new Scene(layout, 600, 100, Color.CORNSILK));
stage.show();
if (mediaPlayer != null) {
mediaPlayer.play();
}
}
/**
* creates a media player using a file from the given filename path
* and tracks the status of playing the file via the status label
*/
private MediaPlayer createMediaPlayer(final String filename, final Label status) throws MalformedURLException {
File file = new File(filename);
if (!file.exists()) {
status.setText("File does not exist: " + filename);
}
final String mediaLocation = file.toURI().toURL().toExternalForm();
Media media = new Media(mediaLocation);
MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.setOnError(new Runnable() {
#Override public void run() {
status.setText("Error");
}
});
mediaPlayer.setOnPlaying(new Runnable() {
#Override public void run() {
status.setText("Playing: " + mediaLocation);
}
});
mediaPlayer.setOnEndOfMedia(new Runnable() {
#Override public void run() {
status.setText("Done");
}
});
return mediaPlayer;
}
}
Here is a link to an additional example of a JavaFX 2.x media player which plays all of the mp3 files in a given directory sequentially.

Serializing objects in an applet

Ok, simply put I am making a quiz game in a java applet, and I want to serialize an object which stores the high scores. When I do this it works perfectly in eclipse but not in a browser.
Here is the code of my applet where it reads the file:
and yes I have all of the appropriate imports
package histApplet;
public class QuizApplet extends Applet
{
private static final String TRACKERLOC = "histApplet/track.ser";
private StatsTracker tracker;
private int difflevel = 1;
//other instance variables
public void init()
{
//other code
if(new File(TRACKERLOC).exists())
{
tracker = null;
FileInputStream fis = null;
ObjectInputStream in = null;
try
{
fis = new FileInputStream(TRACKERLOC);
in = new ObjectInputStream(fis);
tracker = (StatsTracker)in.readObject();
in.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
}
}
else
{
tracker = new StatsTracker(difflevel);
}
//other code
}
And here is my html code
<html>
<head><title>QuizApplet</title></head>
<body>
<center><applet code="histApplet/QuizApplet.class" height=550 width=700>
</applet></center>
</body>
</html>
If I comment out this code it works in a browser but otherwise doesn't. I'm not sure why this doesn't work, and any help would be greatly appreciated.
See my answer on how to write into a text file in Java.
Java Applets execute in a sandbox within the browser, so have limited access to resources in the client machine running the applet (into the browser). File system can't be accessed by an Applet, as explained in several sites SecuringJava, Oracle.
You need to sign your Applet (trusted code) in order to get access to the file system, Oracle.
As written by David, applets can't access the local file system.
They can send data to the host they came from (and receive answers from there), so you could store the highscores on the server, if you have some server-side program which accepts these highscores there.
An alternative would be using a JNLP-deployed applet, then your applet could access an applet-specific local storage with a PersistenceService.

Categories