Java Application conversion into Java applet and passing Parameters from HTML - java

I'm new to Java and tried to create an application which runs a system command when executed.
I accomplished just that with the following code:
package printtest;
import java.io.*;
import java.util.*;
public class PrintTest {
public static void main(String args[])
throws InterruptedException,IOException
{
List<String> command = new ArrayList<String>();
command.add(System.getenv("programfiles") +"\\Internet Explorer\\"+"iexplore.exe");
command.add("http://www.google.com");
ProcessBuilder builder = new ProcessBuilder(command);
Map<String, String> environ = builder.environment();
builder.directory(new File(System.getenv("programfiles")+"\\Internet Explorer\\"));
System.out.println("Directory : " + System.getenv("programfiles")+"Internet Explorer\\");
final Process process = builder.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
System.out.println("Program terminated!");
}
}
If I run the application, it runs a system command in the following syntax "iexplore.exe http://www.google.com". This is great.
The problem I'm having, and I would like to ask for help in it, is this:
I would like to pass variables to this application from a HTML page so the arguments after the executable can be passed in the java application by changing PARAMS in HTML. For this I understood that this app needs to be an applet.
I don't know how to modify this to compile for inclusion in HTML.
Can you help me with this issue?! I've been searching for 2 days now for an answer.
UPDATE:
I'm sorry, I think I'm not explaining as I should. Here's what needs to be done: 1. An order management interface written in PHP needs a way to run a system command with extra parameters to print transport recepts. To do this somehow a webpage should trigger the printing via an applet or any other solution. If you have a an idea about solving this please do tell me. Thanks

I would like to pass variables to this application from a HTML page so the arguments after the executable can be passed in the java application by changing PARAMS in HTML. For this I understood that this app needs to be an applet.
No. As long as you have something on the server side that will generate documents dynamically (e.g. for parameters in HTML or a JNLP launch file), you can use that functionality to create an unique (includes parameters for that use) launch file for a Java Web Start launch.
Of course, whether it is an applet or JWS app., it will require a GUI.
BTW - in case you do not realize:
The code being used will open IE on Windows.
I use Windows but my default browser is FireFox.
It will fail completely on Mac, Linux, Unix..
Java has 3 built-in ways to open a web page.
An Applet has access to the 'AppletContext' class, which offers AppletContext.showDocument(URL).
Java Web Start apps. have access to the JNLP API, which offers BasicService.showDocument(URL).
Java 6+ apps. can use Desktop.browse(URI).
Either of the last two is superior to the Applet method, since they either return a boolean to indicate success, or throw a range of helpful exceptions. For use in an applet or an app. launched using JWS, either of the Desktop class or using a Process would require digitally signed and trusted code.

Related

Start a lightweight web-server using Swift to receive OAuth1.0 callback in iOS App

I'm a newbie in Swift (and iPhone dev). I'm working on a project where I need to build an iOS (using swift) mobile client to demonstrate OAuth1.0 (3-legged flow).
I'm not finding any concrete solution to start a server using swift. I need to pass a call-back endpoint to the request_token url so that my program can receive the oauth_verifierId.
I found the following close solutions (libs) from net, but either lack of examples/docs or due to my less exp on swift, things are not in place yet.
https://github.com/swisspol/GCDWebServer - No/less concrete example (not sure how to import this in swift project)
https://github.com/robbiehanson/CocoaHTTPServer - Looks good but not
getting any e2e solution. I want to avoid Obj-C lib in my Swift project.
https://github.com/glock45/swifter
Actually, I don't need a wrapper like above. It would be best if I could write a Java equivalent like following.
ServerSocket s = new ServerSocket(7000);
Socket remote = s.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(
remote.getInputStream()));
PrintWriter out = new PrintWriter(remote.getOutputStream());
String str = null;
while (!str.equals("")){
str = in.readLine();
if(str.startsWith("GET")){
String[] splitStr = str.split("&");
for(String s1 : splitStr){
if(s1.startsWith("oauth_verifier")){
String verifierId = s1.split("=")[1];
System.out.println("VerifierId - " + verifierId);
}
}
break;
}
}
I think my answer would a little bit late, just put a sign here for later comers.
If you are about to use GCDWebServer:
pod "GCDWebServer", "~> 3.0" in your Podfile, then pod install, pod update.
Put a file named APP_NAME-Bridging-Header.h in SOME_PATH, put these lines below the #define statement:
#import "GCDWebServer.h"
#import "GCDWebServerDataResponse.h"
Go Project Name -> Build Settings -> Search for bridging -> update Objective-C Bridging Header to $(SRCROOT)/SOME_PATH/APP_NAME-Bridging-Header.h.
Now the Objective-C library is globally imported, you could use it everywhere.
Use this line of code to instantiate a GCDWebServer instance:
let webServer = GCDWebServer()
Now play it with yourself :)

Executing an external rails project command from Java application

I'm working on a big system that interconnects different platforms in different languages. Two of these platforms are a RoR website and a Java application whose task is to insert data (no matter where from) to the RoR PostgreSQL database. Currently, I was using simple SQL queries to insert, for example, a product. This is working right, however, I can't take advantage of framework's included tools like timestamps and model callbacks.
The question is, is there a way to, instead of executing those SQL queries, execute rails console commands, considering my Java application runs completely apart the RoR application? If you need to know, I'm using rails 4.
Please excuse my english and thank you in advance.
I don't think that is a good idea at all. But you can achieve this if the java application connects to the same machine RoR is running. You can then use rails runner or you can execute some rake task. The use of rails runner is really simple, check out this example from the official documentation from http://guides.rubyonrails.org/command_line.html#rails-runner
$ bin/rails runner -e staging "Model.long_running_method"
I did as #IvanT suggested, however despite the diverse approaches I can't make it work, here's one of the codes I tried:
String railsCmd = "Product.where(:category_id => 9).each { |p| p.update_attribute(:brand, 'NO BRAND') }";
String wholeCommand = "rails runner -e development \"" + railsCmd + "\"";
StringBuilder output = new StringBuilder();
Process p = Runtime.getRuntime().exec(wholeCommand, null, new File("/path/to/rails/project/bin"));
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = reader.readLine())!= null) {
output.append(line).append("\n");
}
System.out.println(output.toString());
It takes a couple seconds to process, as it's doing something, but there is no change in products themselves. I tried the command directly in the terminal and works good.
I would also like to know why you think it's not a good idea.
Thank you for your time.

how to find the names of currently opened applications (on taskbar) in windows, using java?

I'm making an application which is like windows task manager. For that, I need the list of all opened applications (not processes), which are shown in taskbar.
Here are some sources to look into:
http://www.daniweb.com/web-development/jsp/threads/93197
http://java.ittoolbox.com/groups/technical-functional/java-l/java-code-required-to-access-task-manager-569041
http://www.sqaforums.com/showflat.php?Cat=0&Number=658713&an=0&page=6
Looks like you'll be using the Runtime class.
None of your links CFL_Jeff says anything of how to get active application windows (which I assume is what you want?
Don't think this can be accomplished with java or a simple windows commandline.
Here might be a way to do it in C#:
Get the list of opened windows C#
Or you might have to take a look here:
http://msdn.microsoft.com/en-us/library/windows/desktop/ff468919%28v=vs.85%29.aspx
An emergency solution might be to use the "tasklist /v" command and get all processes that have a "windowtitle" that differ from "I/T"(might be locale dependent), but that will give you tray icons aswell I'm afraid.
Edit:
To get the tasklist, you can use the following:
try
{
Process p = Runtime.getRuntime().exec("cmd /c tasklist /v");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
String input;
while ((input = stdInput.readLine()) != null)
{
output += input;
}
stdInput.close();
}
catch(Exception k){JOptionPane.showMessageDialog(null, k.getMessage());}

Get a specific argument with a firefox add-on

I'm trying to start firefox form a Java program, so far i know how to do that with option as well. But i'm interested in send a specific argument so a javascript add-on could obtain it.
For example, i use the command Runtime.getRuntime().exec("/usr/bin/firefox") to start firefox, my goal is to use something like Runtime.getRuntime().exec("/usr/bin/firefox 12345"), where 12345 is my argument and obtain it via a simple add-on.
Is this possible at all? is there another method/way to pass an argument to an add-on on firefox start?
Thanks in advance.
Start firefox with a url that contains your argument.
Use it as Runtime.getRuntime().exec(new String[] {"/usr/bin/firefox", "12345"})
Can't tell you how to get that argument in your Firefox add-on. Maybe modifying your question if that's what you're mainly asking?
I think your functionality would break the security model of firefox. but there are commands that you can use, http://www.binaryturf.com/lesser-firefox-command-line-options/
In first thank you all for your answers, all of you help me to get this work done. After some more research and thinking of some security issues, i end up using the Java process builder adding an environment variable with the value i want:
//Initiates the process i'm about to start.
ProcessBuilder pb = new ProcessBuilder(args);
//Gets the system environment.
Map<String, String> env = pb.environment();
//Register VAR with value Value as an evironment variable in this process context
env.put("VAR", "Value");
//Stats the process initiated in the 1st line.
pb.start();
So with this i can run an application and have environment variables on it's context, now i just want to access them in my JavaScript add-on, simply with this:
var env = Components.classes["#mozilla.org/process/environment;1"].getService(Components.interfaces.nsiEnvironment);
var X = env.get('VAR');
where X will have the value in the environment variable VAR (previous defined in the Java code);

is it possible to create a java applet, during execution of another java application

I have been developing a Java application which executes a long series of queries and calculations, and presents its results as a series of HTML pages. For visualizing graphs I have been playing around with JUNG library for a while, and it appears as the real strength of the library is the support for user interaction, which is of course unavailable when the graph is saved as a static image (PNG in my case).
I was wondering if it would be:
a) possible
b) feasible
c) sensible
... to create an applet, during execution of the main application, which then can be insert to the HTML reports and can be used interactively after the application has finished execution and the user goes through the report pages.
If this is not possible due to technical reasons; do you have any alternative recommendations/ suggestions as to how I can achieve something like this?
Thanks,
EDIT: Just to clarify the concept, the "main" application is a link in a chain of events, and thus has so separate GUI. The idea with the applet is NOT to mimic or transport all the stuff from the main app to a HTML page, but to make it possible to use interactive tools that come with JUNG library, when the user is reviewing the graphical results AFTER the execution of the main software has finished.
Let me know if the concept is still rather unclear and I'll give a second attempt to explain things in further detail.
UPDATE: Following the advices I got, thnx to #boffinBrain & #AndrewThompson, I wrote my applet, and placed in a package in my project along with other visualization related classes. The hierarchy is as follows:
my.domain.project
my.domain.project.tests
my.domain.project.visualization
Now the HTML reports are created at an arbitrary location on the local drive, this is a feature as the user gives an output folder prior to running the "main" application. In my ReportGenerator class (which generates these HTML files) I have the following bit of code:
File bin = new File(getClass().getProtectionDomain().getCodeSource().getLocation().toString());
String codebase = bin.getParent();
System.out.println(codebase);
String archive = "lib/collections-generic-4.01/collections-generic-4.01.jar";
String applet_name = "bin/my.domain.project.visualization.HierarchyGraphApplet.class";
codebase printout shows: file:/home/username/workspace/project which is correct what I'd expected. Under the project folder there's bin/ and lib/, and inside bin there is the right hierarchy of folders all the way down to my applet class which also exists.
Now why did I write all this down; well because when I try to run my applet on the reports I get:
java.lang.NoClassDefFoundError: bin/my/domain/project/visualization/HierarchyGraphApplet (wrong name: my/domain/project/visualization/HierarchyGraphApplet)
I have read similar questions like: this or this but it seems like the problem is somewhere else. I double checked the spelling etc...
Is there something simple I am missing, or is there a more complicated problem at hand?
Maybe this example will give you some ideas to pursue. It creates data files used as 'reports' for consumption by the applet(s).
Because the applet gains the data via an input file whose title is specified in an applet param. The content of the data file is only limited by the requirements of the report, your skill to create it & parse it, ..and available disk space. ;)
Compile & run the main(String[]) to (hopefully) see 2 web pages open in tabs of your browser.
import java.awt.Desktop;
import javax.swing.*;
import java.net.*;
import java.io.*;
/** Simplistic example, not intended to show good I/O practices
or Exception handling for the sake of brevity. */
public class Reporter extends JApplet {
public void init() {
String input = getParameter("input");
JEditorPane report = new JEditorPane();
report.setText("Problem loading input file");
add(report);
URL url;
try {
url = new URL(getDocumentBase(), input);
report.setPage(url);
} catch(Exception e) {
e.printStackTrace();
}
}
/** The main represents our report generator. It is part
of the applet class only in order to create an SSCCE. Good
design would imply that it might be in a class ReportGenerator,
while the applet is in class ReportViewer. */
public static void main(String[] args) throws Exception {
File f;
String title = "1";
String data = "apples";
createInput(title, data);
f = createHTML(title);
Desktop.getDesktop().browse(f.toURI());
title = "2";
data = "oranges";
createInput(title, data);
f = createHTML(title);
Desktop.getDesktop().browse(f.toURI());
System.out.println( "End of report generation.." );
}
public static void createInput(String title, String data) throws Exception {
File f = new File("data" + title + ".txt");
PrintWriter pw = new PrintWriter(f);
pw.println(data);
pw.flush();
pw.close();
}
public static File createHTML(String title) throws Exception {
File f = new File("Data" + title + ".html");
PrintWriter pw = new PrintWriter(f);
pw.println("<html>");
pw.println("<title>");
pw.println("Data " + title);
pw.println("<title>");
pw.println("<body>");
pw.println("<h1>");
pw.println("Data " + title);
pw.println("</h1>");
pw.println("<applet ");
pw.println("code='Reporter'");
pw.println("width='400'");
pw.println("height='400'");
pw.println(">");
pw.println("<param name='input' value='data" + title + ".txt'>");
pw.println("</applet>");
pw.println("</body>");
pw.println("</html>");
pw.flush();
pw.close();
return f;
}
}
In relation to further questions:
..does the given code assume that the html reports and the applet are located in the same folder?
Not necessarily. The input parameter might specify ../other/data3.txt for the other directory at the same level as the one contained by the HTML, or /reports/data3.txt for a reports directory at the root of the site.
..As you have also noted, in a real-life example the code for the applet would most likely be in its own class, would that pose any complications as to how it would be incorporated into the html files (which are generated in a separate class, named ReportGenerator)?
It would require only slight changes to point to the applet.jar as opposed to the application.jar. Use a codebase to separate the HTML from the directory of the applet.jar (though archives can also be accessed via relative or absolute URLs).
It's definitely feasible to create an applet to display the data, but you don't want to dynamically generate a new one each time. You want to create a separate, stand-alone applet which can generate your graphs/reports from a set of input data in text format, and then when you create the HTML page, supply the report data using an applet parameter (using the PARAM tag).

Categories

Resources