I'm new to java and I'm trying to compile and run a web service example from a book.
The example uses 3 files.
I can create an Eclipse Project and Run it. It works fine this way.
From the command line I tried
javac TimeServer.java TimeServerImpl.java TimeServerPublisher.java
And got no errors
This program does not run on the command line returns error:
"Could not find the main class"
java TimeServerPublisher
running using the -classpath option returns the same result.
Set classpath does not help either. ie
java -classpath . TimeServerPublisher
fails as well
Most of the online docs specify I need a classpath. I tried everything they suggested.
Please Help. Thanks in advance
Source:
TimeServer.java
package ch01.ts;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
#WebService
#SOAPBinding(style = Style.RPC) // more on this later
public interface TimeServer
{
#WebMethod String getTimeAsString();
#WebMethod long getTimeAsElapsed();
}
TimeServerImpl.java
package ch01.ts;
import java.util.Date;
import javax.jws.WebService;
#WebService(endpointInterface = "ch01.ts.TimeServer")
public class TimeServerImpl implements TimeServer
{
#Override
public String getTimeAsString()
{
return new Date().toString();
}
#Override
public long getTimeAsElapsed()
{
return new Date().getTime();
}
TimeServerPublisher.java
package ch01.ts;
import javax.xml.ws.Endpoint;
public class TimeServerPublisher
{
public static void main(String[ ] args)
{
Endpoint.publish("http://127.0.0.1:9876/ts", new TimeServerImpl());
}
}
Your class is not named TimeServerPublisher; it's named ch01.ts.TimeServerPublisher. Even if you manage to get the JVM to find your class file, it will reject it with a wrong-name error, as you must invoke the class with its full name.
Put all the class files into a directory ch01/ts if they're not there already, and from ch01's parent directory, type
java -cp . ch01.ts.TimeServerPublisher
I guarantee that done correctly this will work.
get rid of the package statements until you know how they work. to have that package, your sources and binaries should be under ./ch01/ts/ and you would compile and invoke as:
javac ch01/ts/*.java
java ch01.ts.TimeServerPublisher
Move all your class files to folder ch01/ts.
and then execute command
java ch01.ts.TimeServerPublisher
There you go. If you say javac -d ch01/ts *.java during compilation, it will be solved.
Related
Purpose
I want to be able to create a package and call it.
Alternatively, I would like to create separate files for my method (to avoid having x classes in one file).
Setup
Here is my LetterGrader.java file:
package grade.util;
import java.util.*;
import java.io.*;
public class LetterGrader {
private void readArgs() {
System.out.println("Hello, read CLA!");
}
}
Here is my TestLetterGrader.java file:
import java.util.*;
import java.io.*;
public class TestLetterGrader {
public static void main(String[] args) {
LetterGrader letterGrader = new LetterGrader(); // instantiate
letterGrader.readArgs(); // call method
}
}
Steps Taken
First, I compile LetterGrader:
This auto creates the bin/grade/util/LetterGrader.class file
javac -d bin -sourcepath src src/grade/util/LetterGrader.java
Here is my working directory at this point
Second, I compile TestLetterGrader:
This fails
javac -d bin -sourcepath src src/grade/util/TestLetterGrader.java
The error message:
src/grade/util/TestLetterGrader.java:6: error: cannot find symbol
LetterGrader letterGrader = new LetterGrader(); // instantiate
^
symbol: class LetterGrader
location: class TestLetterGrader
Question
I believe I am misunderstanding how to call a classes from separate files (in the same location). How can I accomplish this?
You are importing class that is in bin folder. Don’t do that it would not work. You don’t need any import, because the classes are in the same place. Make package under src folder and place the classes there. Remove package grade.util and rename it to the package where you place the classes.
File structure:
src
\
\
yourpackage
\
\
LetterGrader.java TestLetterGrader.java
Then delete everything in your build folder and compile the classes. Java will make it’s magic. You do need to worry about bin folder, it is only for storing compiled classes.
Classes will look like this:
//package name that you created
package yourpackage;
public class LetterGrader {
//need to be public when calling from another class
public void readArgs() {
System.out.println("Hello, read CLA!");
}
}
And
//folder that you placed the .java files
package yourpackage;
//without any import
public class TestLetterGrader {
public static void main(String[] args) {
LetterGrader letterGrader = new LetterGrader(); // instantiate
letterGrader.readArgs(); // call method
}
}
Your second question:
You can use classes from other folders, but you you have to import them and they have to be under src folder.
Tell you have class A.java in folder Second and class B.java in folder Main. You will import the the folder in this case import Second.A;
And then call the class A a = new A();
When you have method in a that you want to call simply do:
a.yourmethod();
You have to change private void ... to public void... because you cannot call private outside of the class.
When you are running compiled classes they have to be in the same folder.
Thanks #maratonec for the guidance.
My initial mistake was that I was misunderstanding/misassigning the classpath assignment variable when running a program via terminal. The below helped me.
Compiling and Running a Java Program (on a PC)
• Set the working directory (say, JavaBook)
C:\> cd JavaBook
• Compile HelloWorld.java
C:\JavaBook> javac -d bin src\HelloWorld.java
•Run the program
C:\JavaBook> java -classpath bin HelloWorld
Also, the approach of having all my class files in the same location simplified things. I didn't have to worry about classpath. But not ideal as I have many files to work with.
As for the package creation, I am going to play around with java a bit more before using it. I think I need to solidify my understanding.
Thanks for helping me!
So, I have a package "com", which consists of two sub-packages "Common" and "Model1". The Model1 contains a class Model which I am trying to import in the Servlet2 class, which resides in the Common package. I compile the Model class first which stays fine, but the Servlet2 class doesn't and comes up with an error saying "package com.Model1 doesn't exist"
Here's the Model class:
package com.Model1;
import java.util.*;
**public** class Model{
public ArrayList<String> getBrands(String color){
ArrayList<String> brands=new ArrayList<String>();
if(color.equals("amber")){
brands.add("Jack Amber");
brands.add("Red Moose");
}
else{
brands.add("Jail Pale Ale");
brands.add("Gout Stout");
}
return brands;
}
}
Here's the Servle2 class:
package com.Common;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import com.Model1.Model;
public class Servlet2 extends HttpServlet{
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("Coffee selection advice<br>");
String c=req.getParameter("color");
Model m=new Model();
ArrayList result=m.getBrands(c);
out.println("<br>Got coffee color "+c);
Iterator it=result.iterator();
while(it.hasNext()){
out.println("<br> Try: "+it.next());
}
}
}
I just can't seem to figure out how to sort this out.
Edit: Realised that default modifier is restrictive, but even making it public doesn't seem to work.
I am using notepad++ and I hope this works as the Minimal, Complete, and Verifiable example:
package com.common;
import com.model.*;
public class TheClassIWantToImportInto {
public static void main(String[] args){
System.out.println("Testing 1");
TheClassIwantToImport obj=new TheClassIWantToImportInto();
obj.testFunction();
}
}
The second class:
package com.model;
public class TheClassIWantToImport{
public void testFunction(){
System.out.println("testing function");
}
}
Both the .java files are in the same folder "C:\Program Files\Java\jdk1.8.0_161\bin"
Using the following commands in this order:
javac -d . TheClassIWantToImport.java (Works fine)
javac -d . TheClassIWantToImportInto.java (Error: package com.model doesn't exist)
Set up your project such that you have some root dir which is your project's main directory. Let's call that /Users/you/projects/MyCoolProject
Within that, make a src/main dir which will contain your sources. A source file goes in a directory that matches its package declaration. com.Model1 is a bad package name for three reasons. Convention states not to start them with caps, convention states that they are supposed to represent either your reverse website or failing that, at least the project name, and finally 'model1' is not descriptive. So let's go with package com.mycompany.coolproject.vehicleModel; instead. In that case, your Model class should be on your disk at /Users/you/projects/MyCoolProject/src/main/com/mycompany/coolproject/vehicleModel/Model.java
Use a build tool such as maven or gradle to build your project. This is going to be a lot simpler than trying to manually make javac do the right thing here. If you MUST use java, make dir build in /users/you/projects/MyCoolProject, make sure you're in that directory, and then try: javac -d build -sourcepath src/main src/main/com/mycompany/coolproject/vehicleModel/*.java and note that you'll have to add a path to that every time you make another package (to avoid having to do that... use maven or gradle).
Once you've done that, this error goes away (the error indicates that javac can't find the other source file because your project isn't properly set up yet. The above instructions lead to a properly set up project, with javac/maven/gradle being capable of finding all your source files as needed, and it's how almost all java programmers work).
I am attempting to build my first Java web service using this tutorial http://www.ibm.com/developerworks/webservices/tutorials/ws-jax/ws-jax.html but it produces errors at a certain point that I cannot resolve. The tutorial includes a download and even when I simply use the relevant file from the download its still gives me the errors. All java classes have complied until this point. The OrderProcessService class has complied fine and I have checked all spelling of files and folder names but still it is as if the java compiler cannot see the OrderProcessService class. What am I doing wrong here? I have copied in the OrderProcessService class and the OrderWebServicePublisher class. The other classes in the bean directory, such as Customer and Address are just POJO's. Here is the error;
The OrderProcessService.java
package com.ibm.jaxws.tutorial.service;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import com.ibm.jaxws.tutorial.service.bean.OrderBean;
// JWS annotation that specifies that the portType name of the
// Web service is "OrderProcessPort" the service name is
// "OrderProcess" and the targetNamespace used in the generated
// WSDL is "http://jaxws.ibm.tutorial/jaxws/orderprocess"
#WebService(serviceName = "OrderProcess",
portName = "OrderProcessPort",
targetNamespace = "http://jaxws.ibm.tutorial/jaxws/orderprocess")
// JWS annotation that specifies the mapping of the service onto the
// SOAP message protocol. In particular, it specifies that the SOAP
// messages
// are document literal
#SOAPBinding(style=SOAPBinding.Style.DOCUMENT, use=SOAPBinding.Use.LITERAL,
parameterStyle=SOAPBinding.ParameterStyle.WRAPPED)
public class OrderProcessService{
#WebMethod
public OrderBean processOrder(OrderBean orderBean){
// Do processing
System.out.println("processOrder called for customer"
+ orderBean.getCustomer().getCustomerId());
// Items ordered are
if(orderBean.getOrderItems() != null) {
System.out.println("Number of items is"
+ orderBean.getOrderItems().length);
}
// Process Order
// Set the order ID
orderBean.setOrderId("A1234");
return orderBean;
}
}
The OrderWebServicePublisher.java
package com.ibm.jaxws.tutorial.service.publish;
import javax.xml.ws.Endpoint;
import com.ibm.jaxws.tutorial.service.OrderProcessService;
public class OrderWebServicePublisher {
public static void main(String[] args) {
Endpoint.publish("http://localhost:8080/OrderProcessWeb/orderprocess",
new OrderProcessService());
System.out.println("The web service is published at
http://localhost:8080/OrderProcessWeb/orderprocess");
System.out.println("To stop running the web service , terminate the
java process");
}
}
Looks like you are running from the command line. You will need to specify the classpath of all required classes.
Instead of doing
javac com\....\OrderWebService.java
do
javac -cp <path to your OrderProcessorService> com\...\OrderWebService.Java
More examples please see Setting multiple jars in java classpath
I am going to guess you haven't setup the classpath correctly? If running from command line utilize the -cp option. If running from IDE, define accordingly.
Did you write this in an IDE or a text editor. An IDE like Eclipse would have caught it. But usually this error is seen in situation like a jar is missing in your classpath. But it seems you have the java file and compiled it again. For your case when I looked at the link in your question : did you run:
wsgen -cp . com.ibm.jaxws.tutorial.service.OrderProcessService -wsdl ?
I want to import and call a java class(which in from an external package ) from a scala object . My code is like this
Java code:
package com.test.services.account;
public class MyMain {
public static void main(String[] args) {
System.out.println("coming into main");
}
}
Scala code:
package com.newtest.newservice.scala
import _root_.com.test.services.account.MyMain
object scalatest {
def main(args: Array[String]) {
println("Hello, world! " + args.toList)
// Deployer.main(args)
val de:MyMain = new MyMain()
println(de.toString())
}
}
when i compile it using scalac scalatest.scala, it gives an error
scalatest.scala:2: error: object test is not a member of package com
import root.com.test.services.account.MyMain
^
one error found
Could anybody guide me how can i import my java class into scala code ?
Thanks
Suresh
If you don't want to use something like sbt, you should first decide where your CLASSPATH is. Since you have two different class files (one generated from Java and one from Scala), you need at least one directory where your class files need to live. Let's say that is d:\myclasses.
In that case, you'd compile the java file using this command:
d:\mycode> javac -d d:\myclasses MyMain.java
This would generate your Java class file in the appropriate package structure at d:\myclasses. Then you would compile the scala file like so
scalac -classpath d:\myclasses -d d:\myclasses scalatest.scala
Instead of passing the classpath as part of the scalac command line, you could also set your CLASSPATH environment variable to d:\myclasses.
I am trying to run the example but eclipse cant seem to resolve the ActionSupport class. Could anyone tell me which package and jar should I import ?
For struts 2.3.1.2
The jar required is :: xwork-core-2.3.1.2.jar. Add that to your classpath. Check which version of xwork you need with the bundle that comes with struts2
Edit::
If you have jar in your classpath . simple Ctrl+O(organize imports). If it gives you option .
select com.opensymphony.xwork2.ActionSupport;
The full path is
com.opensymphony.xwork2.ActionSupport
Make sure you have the correct packages installed.
In case you want to check if everything else is working fine you can try running the project without com.opensymphony.xwork2.ActionSupport
This way, the sample code will be like:
package org.apache.struts.helloworld.action;
import org.apache.struts.helloworld.model.MessageStore;
//import com.opensymphony.xwork2.ActionSupport;
public class HelloWorldAction {
private MessageStore messageStore;
public String execute() {
messageStore = new MessageStore() ;
return "Success";
}
public MessageStore getMessageStore() {
return messageStore;
}
}