Simple Web Service adding two numbers - java

I have created a simple Webservice function as shown below;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ws;
import javax.jws.WebService;
/**
*
* #author Joe
*/
#WebService()
public class Add2Int {
public int add(int a, int b) {
return (a+b);
}
}
and I have created a very simple gui that allows the user to enter 2 numbers and which should output the result however this does not work? I tried it without the gui and it works but when i build the gui it does not work? here is my code for that side of things
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package myjavawsclient;
//import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
*
* #author Joe
*/
public class Calculator extends JFrame implements FocusListener {
JTextField value1 = new JTextField("", 5);
JLabel plus = new JLabel("+");
JTextField value2 = new JTextField("",5);
JLabel equals = new JLabel("=");
JTextField sum = new JTextField("", 5);
public Calculator() {
super("The Calculator");
setSize(350,90);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FlowLayout flow = new FlowLayout(FlowLayout.CENTER);
setLayout(flow);
// add the listners
value1.addFocusListener(this);
value2.addFocusListener(this);
// set up sum field
sum.setEditable(true);
//add componets
add(value1);
add(plus);
add(value2);
add(equals);
add(sum);
setVisible(true);
}
public void focusGained(FocusEvent event){
try { // Call Web Service Operation
ws.Add2IntService service = new ws.Add2IntService();
ws.Add2Int port = service.getAdd2IntPort();
// TODO initialize WS operation arguments here
int result = 0;
int result2 = 0;
result = Integer.parseInt(value1.getText());
result2 = Integer.parseInt(value2.getText());
int total = port.add(result, result2);
sum.setText("" +total);
//float plusTotal = Float.parseFloat(value1.getText()) +
Float.parseFloat(value2.getText());
} catch (Exception ex) {
// TODO handle custom exceptions here
//value1.setText("0");
//value2.setText("0");
//sum.setText("0");
}
}
public void focusLost(FocusEvent event){
focusGained(event);
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Calculator frame = new Calculator();
}
}
I am not getting any errors I am just not getting any result from the 2 numbers, for example 1+1=2 but with my application it allows the user to enter 1 + 1 = ? but where the question mark is nothing gets shown.
I was wondering if anyone could solve this problem for me. Oh and I am using NetBeans and GlassFish App server with WSDL
Joe

You should declare add as a webmethod.
try following:
#WebMethod public int add(int a, int b){
return (a+b);
}

My Fault! I forgot to start the App Server

Related

Having problem while executing the main file

I am just a beginner trying to use a git java project, I have downloaded a java project from git and when I try to run the splash.java file it says:-
Class "Electricity.splash" does not have a main method
Here's the screenshot of the screen:-
Screenshot of my error
conn.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author Hp pc
*/
class conn {
}
screenshot of conn.java file in Electricity folder
screenshot
Here's my splash.java which has the main method:
package Electricity;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class splash {
public static void main(String[] args){
fframe f1 = new fframe();
f1.setVisible(true);
int i;
int x=1;
for(i=2; i<=600; i+=4, x+=1){
f1.setLocation(800 - ((i+x)/2), 500 - (i/2));
f1.setSize(i+x,i);
try{
Thread.sleep(10);
}catch(Exception e){}
}
}
}
class fframe extends JFrame implements Runnable{
Thread t1;
fframe(){
super("Electricity Billing System");
setLayout(new FlowLayout());
ImageIcon c1 = new ImageIcon(ClassLoader.getSystemResource("icon/elect.jpg"));
Image i1 = c1.getImage().getScaledInstance(730, 550,Image.SCALE_DEFAULT);
ImageIcon i2 = new ImageIcon(i1);
JLabel l1 = new JLabel(i2);
add(l1);
t1 = new Thread(this);
t1.start();
}
public void run(){
try{
Thread.sleep(7000);
this.setVisible(false);
Login l = new Login();
l.setVisible(true);
}catch(Exception e){
e.printStackTrace();
}
}
}
Please Guide me, is it because I haven't downloaded jdbc or something else?
First create your main method in the main class then, to specify the class with the main method: left click on the name of your project, properties, Run, and there specify the main class with the main method. In your capture: try, Import java.sql.Connection;

Web scraping console output in Swing GUI [duplicate]

I have posted two pieces of code below. Both codes work fine individually. Now, when I run the file Easy, and click on the "Start" button, I want the class AddNumber to be implemented. I mean to say that, instead of the AddNumber running on the console, is there any way I could make AddNumber run in the JTextArea i have created in the first class upon clicking the "Start" button? I thought maybe by action listener?(the way we do in case of buttons) But I'm not sure. Is there any other way to make my JTextArea act as a console for the other .java files?
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Easy extends JFrame{
JTextArea text=new JTextArea();
JPanel panel=new JPanel(new GridLayout(2,2));
JButton button1 =new JButton("Start");
public Easy(){
panel.add(text);
panel.add(button1);
add(panel,BorderLayout.CENTER);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
//add code to call the other class and make the JTextArea act as a console
}
});
}
public static void main(String arg[]){
Easy frame=new Easy();
frame.setSize(300,100);
frame.setVisible(true);
}
}
The second class:
import java.util.Scanner;
class AddNumber
{
public static void main(String args[])
{
int x, y, z;
System.out.println("Enter two numbers to be added ");
Scanner in = new Scanner(System.in);
x = in.nextInt();
y = in.nextInt();
z = x + y;
System.out.println("Sum of entered numbers = "+z);
}
}
I have seen a few posts talking about PrintStream..but i don't think that applies here.
Please help me out. Thanks :)
UPDATE: well i found this link: http://www.codeproject.com/Articles/328417/Java-Console-apps-made-easy#HowtousethisJavaConsole1 and it works in the sense that it shows "Enter two numbers to be added "...but where can the user provide his input?
EDIT: I just had to make a reference of the console in the main method of my class...and it works... well, not exactly as i would've wished to..but partly..the input still has to go from the terminal of the IDE..
If you do a Google search for: "stdout JTextArea", you will a couple of links to solve your problem.
http://www.coderanch.com/t/458147/GUI/java/Redirect-output-stderr-stdout-JTextArea
Redirecting System.out to JTextPane
http://www.jcreator.com/forums/index.php?showtopic=773
In the last link, buddybob extends java.io.OutputStream to print standard output to his JTextArea. I included his solution below.
TextAreaOutputStream.java
/*
*
* #(#) TextAreaOutputStream.java
*
*/
import java.io.IOException;
import java.io.OutputStream;
import javax.swing.JTextArea;
/**
* An output stream that writes its output to a javax.swing.JTextArea
* control.
*
* #author Ranganath Kini
* #see javax.swing.JTextArea
*/
public class TextAreaOutputStream extends OutputStream {
private JTextArea textControl;
/**
* Creates a new instance of TextAreaOutputStream which writes
* to the specified instance of javax.swing.JTextArea control.
*
* #param control A reference to the javax.swing.JTextArea
* control to which the output must be redirected
* to.
*/
public TextAreaOutputStream( JTextArea control ) {
textControl = control;
}
/**
* Writes the specified byte as a character to the
* javax.swing.JTextArea.
*
* #param b The byte to be written as character to the
* JTextArea.
*/
public void write( int b ) throws IOException {
// append the data as characters to the JTextArea control
textControl.append( String.valueOf( ( char )b ) );
}
}
The TextAreaOutputStream extends the java.io.OutputStream class
and overrides its write(int) method overload, this class uses a
reference to a javax.swing.JTextArea control instance and then
appends output to it whenever its write( int b ) method is called.
To use the TextAreaOutputStream class, [yo]u should use:
Usage
// Create an instance of javax.swing.JTextArea control
JTextArea txtConsole = new JTextArea();
// Now create a new TextAreaOutputStream to write to our JTextArea control and wrap a
// PrintStream around it to support the println/printf methods.
PrintStream out = new PrintStream( new TextAreaOutputStream( txtConsole ) );
// redirect standard output stream to the TextAreaOutputStream
System.setOut( out );
// redirect standard error stream to the TextAreaOutputStream
System.setErr( out );
// now test the mechanism
System.out.println( "Hello World" );

running a simple task example

Hi I've been trying all night to run this example and have had no luck what so ever, I cannot find a solution. I have two file.
First is Worker.java and here is its contents
import javafx.application.Application;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author brett
*/
public class Worker {
/**
* #param args the command line arguments
* #throws java.lang.Exception
*/
/**
*
* #param args
* #throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO code application logic here
doit();
}
private static void doit(){
try {
IteratingTask mytask = new IteratingTask(800000);
mytask.call();
System.out.println(mytask.getValue());
int pro = (int) mytask.getProgress();
System.out.println(pro);
} catch (Exception ex) {
Logger.getLogger(Worker.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Next is the IteratingTask.java file and its contents
//import javafx.concurrent.Task;
import javafx.application.Application;
import javafx.concurrent.Task;
/**
*
* #author brett
*/
public class IteratingTask extends Task<Integer> {
private final int totalIterations;
public IteratingTask(int totalIterations) {
this.totalIterations = totalIterations;
}
#Override protected Integer call() throws Exception {
int iterations;
// iterations = 0;
for (iterations = 0; iterations < totalIterations; iterations++) {
if (isCancelled()) {
updateMessage("Cancelled");
break;
}
updateMessage("Iteration " + iterations);
updateProgress(iterations, totalIterations);
}
return iterations;
}
}
I know I'm doing something very wrong but... I just cant see it.
Here is the error it get
run:
Jan 31, 2015 11:56:38 PM Worker doit
SEVERE: null
java.lang.IllegalStateException: Toolkit not initialized
at com.sun.javafx.application.PlatformImpl.runLater(PlatformImpl.java:270)
at com.sun.javafx.application.PlatformImpl.runLater(PlatformImpl.java:265)
at javafx.application.Platform.runLater(Platform.java:81)
at javafx.concurrent.Task.runLater(Task.java:1211)
at javafx.concurrent.Task.updateMessage(Task.java:1129)
at IteratingTask.call(IteratingTask.java:24)
at Worker.doit(Worker.java:38)
at Worker.main(Worker.java:31)
BUILD SUCCESSFUL (total time: 0 seconds)
It builds ok.... any advice would be awesome.
The problem is that the FX Toolkit, and in particular the FX Application Thread have not been started. The update...(...) methods in Task update various state on the FX Application Thread, so your calls to those methods cause an IllegalStateException as there is no such thread running.
If you embed this code in an actual FX Application, it will run fine. Calling launch() causes the FX toolkit to be started.
Also, note that while this will run, Tasks are generally intended to be run in a background thread, as below:
import javafx.application.Application;
import javafx.scene.Scene ;
import javafx.scene.layout.StackPane ;
import javafx.scene.control.Label ;
import javafx.stage.Stage ;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Worker extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
StackPane root = new StackPane(new Label("Hello World"));
Scene scene = new Scene(root, 350, 75);
primaryStage.setScene(scene);
primaryStage.show();
doit();
}
public static void main(String[] args) throws Exception {
launch(args);
}
private void doit(){
try {
IteratingTask mytask = new IteratingTask(800000);
// mytask.call();
Thread backgroundThread = new Thread(mytask);
backgroundThread.start(); // will return immediately, task runs in background
System.out.println(mytask.getValue());
int pro = (int) mytask.getProgress();
System.out.println(pro);
} catch (Exception ex) {
Logger.getLogger(Worker.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

Find the location in code of a system.out.println

Lets say I'm working in a very large project, and have noticed an empty print line, so I'm assuming there is a System.out.println(""); located somewhere in the code. How would I go about trying to figure out where it is, short of just searching the entire project for all occurrences of System.out.println?
If you're using Java 8+, Durian has a StackDumper class which makes it easy to find where a given line is being printed:
StackDumper.dumpWhenSysOutContains("SomeTrigger")
When "SomeTrigger" is printed, this will get dumped to System.err:
+----------\
| Triggered by SomeTrigger
| at package.MyClass.myMethod(MyClass.java:62)
| (the rest of the stacktrace)
+----------/
For your case (looking for an empty string), it's a little more complicated:
PrintStream sysOutClean = System.out;
StringPrinter sysOutReplacement = new StringPrinter(StringPrinter.stringsToLines(line -> {
if (line.isEmpty()) {
StackDumper.dump("Found empty line");
}
sysOutClean.println(line);
}));
System.setOut(sysOutReplacement.toPrintStream());
Now if there's something like this:
System.out.println("ABC");
System.out.println("123");
System.out.println("");
System.out.println("DEF");
Then your console will look like this:
ABC
123
+----------\
| Found empty line
| at package.MyClass.myMethod(MyClass.java:62)
| (the rest of the stacktrace)
+----------/
DEF
You could implement your own PrintStream and use System.setOut to replace the default stdout. Then either put a debugging marker inside the class (if an empty string is printed), or print out the method name through the call stack (throw and catch an exception and get the stack information).
Example:
/** Control sysout prints */
public static void main(String[] arg) throws Exception {
System.out.println("Default"); //print normally
SysOutController.setSysOutLocationAddressor();
System.out.println("With Address"); //prints with calling location, and on click location cursor directly focus when System.out.**() called
SysOutController.ignoreSysout();
System.out.println("Ignored"); //this line will never prints
SysOutController.resetSysOut();
System.out.println("Default"); //print normally as it is (reset)
}
Just call methods of following class, which helps developers to controll sysout
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
/**
* Class which controls System.out prints in console <br/>
* this class will helps developers to control prints in console
* #implSpec
* <pre><code>
* System.out.println("Default"); //print normally
*
* SysOutController.setSysOutLocationAddressor();
* System.out.println("With Address"); //prints with calling location
*
* SysOutController.ignoreSysout();
* System.out.println("Ignored"); //this line will never prints
*
* SysOutController.resetSysOut();
* System.out.println("Default"); //print normally as it is (reset)
* </code></pre>
* #author Dharmendrasinh Chudasama
*/
public class SysOutController {
private static void setOut(OutputStream out){
System.setOut(new PrintStream(out));
}
private static final OutputStream CONSOLE = new FileOutputStream(FileDescriptor.out);
/**
* Reset System.out.print* method
* #author Dharmendrasinh Chudasama
*/
public static void resetSysOut() { setOut(CONSOLE); }
/**
* System.out.print* will not print anything in console
* #author Dharmendrasinh Chudasama
*/
public static void ignoreSysout() {
setOut(new OutputStream() {
#Override public void write(int b) throws IOException {}
});
}
/**
* Address/location of calling System.out.* method will append in console
* #author Dharmendrasinh Chudasama
*/
public static void setSysOutLocationAddressor() {
setOut(new OutputStream() {
#Override
public void write(int b) throws IOException {
if(b=='\n'){ //if newLine
final StackTraceElement callerStEl = new Throwable().getStackTrace()[9];
String pathData =
"\u001B[37m" //low-visibality
+ "\t :: ("+callerStEl.getFileName()+":"+callerStEl.getLineNumber()+") ["+callerStEl+"]" //code path
+ "\u001B[0m "; //reset
CONSOLE.write(pathData.getBytes());
}
CONSOLE.write(b);
}
});
}
}
This can be due to some of the library also,if you feel that it is because of only System.out.println then,
Solution 1 :
Below code snippet should help you to find out the place where it is getting executed.
import java.io.FileNotFoundException;
import java.io.PrintStream;
public class CustomPrintStream extends PrintStream {
public CustomPrintStream(String fileName) throws FileNotFoundException {
super(fileName);
}
#Override
public void print(String s) {
try{
if(s == null || s.equals("")){
throw new Exception("Invalid print message");
}
super.print(s);
}catch(Exception e){
//TODO Change to your logger framework and leave it as same
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
//TODO : Change to your favorite path and make sure mentioned
//file is available
CustomPrintStream customPrintStream = new CustomPrintStream
("/home/prem/Desktop/test.log");
System.setOut(customPrintStream);
System.out.println("");
} catch (FileNotFoundException e) {
//TODO Change to your logger framework and leave it as same
e.printStackTrace();
}
}
}
Solution 2 :
Since IDE's are available,please get the help from them.If you are using eclipse
Menu -> Search - > File Search-> Place System.out.println(""); in containing search and search for it.
I would rather say not to use the System.out.println in any of the code,for which you can make use of checkstyle and be confident that hence forth no developers use them.
Define a class NewPrintStream extends PrintStream
import java.io.FileNotFoundException;
import java.io.PrintStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NewPrintStream extends PrintStream {
private static final Logger LOGGER = LoggerFactory.getLogger(NewPrintStream.class);
public NewPrintStream(String fileName) throws FileNotFoundException {
super(fileName);
}
#Override
public void println(String x) {
LOGGER.info("xxxxxxx", new Exception("xxxx"));
}
}
Then in main class set stdout/stderr print stream
System.setOut(new NewPrintStream("aaa"));
System.setErr(new NewPrintStream("aaa"));
Put a conditional breakpoint in PrintStream.println(String x) with the condition set to x.equals("") or whatever your string may be.

Error importing classes for RDF crawler

I'm using a rdf crawler, in that I had a class named as:
import edu.unika.aifb.rdf.crawler.*;
import com.hp.hpl.jena.rdf.model.*;
import com.hp.hpl.jena.util.FileManager;
These are class file termed as error, and I try with jena packages but I had attached, it does not make any changes.
Update:
Full SampleCrawl.java class content:
import java.util.*;
import edu.unika.aifb.rdf.crawler.*;
/**
* Call this class with 3 arguments - URL to crawl to,
* depth and time in seconds
*/
public class SampleCrawl {
/**
* #param uRI
* #param depth
* #param time
*/
#SuppressWarnings("rawtypes")
public SampleCrawl(Vector uRI, Vector hf, int depth, int time){
// Initialize Crawling parameters
CrawlConsole c = new CrawlConsole(uRI,hf,depth,time);
// get an ontology file from its local location
// (OPTIONAL)
c.setLocalNamespace("http://www.daml.org/2000/10/daml-ont","c:\\temp\\rdf\\schemas\\daml-ont.rdf");
// set all the paths to get all the results
c.setLogPath("c:\\temp\\crawllog.xml");
c.setCachePath("c:\\temp\\crawlcache.txt");
c.setModelPath("c:\\temp\\crawlmodel.rdf");
try{
// crawl and get RDF model
c.start();
// This writes all three result files out
c.writeResults();
}catch(Exception e){
}
}
/**
* #param args
* #throws Exception
*/
#SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) throws Exception {
if (args.length != 3) {
System.err.println("Usage: java -cp [JARs] SampleCrawl [URL] [depth:int] [time:int]");
System.exit(0);
}
Vector uris = new Vector();
uris.add(args[0]);
// no host filtering - crawl to all hosts
Vector hostfilter = null;
/* You may want to do something else to enable host filtering:
* Vector hostfilter = new Vector();
* hostfilter.add("http://www.w3.org");
*/
int depth = 2;
int time = 60;
try {
depth = Integer.parseInt(args[1]);
time = Integer.parseInt(args[2]);
}
catch (Exception e) {
System.err.println("Illegal argument types:");
System.err.println("Argument list: URI:String depth:int time(s):int");
System.exit(0);
}
new SampleCrawl(uris,hostfilter,depth,time);
}
}
Question:
How to add import edu.unika.aifb.rdf.crawler.; error occurs here
I googled the package that you're trying to import, and it appears that you're using Kaon. Assuming that's so, you have made an error in your import declaration. You have:
import edu.unika.aifb.rdf.crawler.*;
whereas the download available on SourceForge would require:
import edu.unika.aifb.rdf.rdfcrawler.*;
As an aside, it would be helpful if you would include information, such as "I'm trying to use Kaon's rdfcrawler from ..." in your question. Otherwise, we have to try to guess important details in your setup.

Categories

Resources