WebService not being produced./Generated - java

I am trying to deploy a webservice on my localhost, but it doesn't seem to produce the "Endpoint".
I don't know how I messed it up :(
I am using apache cxf 2.7.1 and glassfish 3.1. I even attempted to add ear libraries.
Here is my build path:
and my project explorer looks like this:
I have annotations on both my webservice and webservice interface, as shown below:
Code for webservice interface (I removed the other some parts to make the code shorter)
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import no.solarsoft.venus2.webservice.exception.WebServiceException;
import no.solarsoft.venus2.webservice.queryoptions.ParticipantQuery;
import no.solarsoft.venus2.webservice.queryoptions.ParticipantQueryParameterKey;
import no.solarsoft.venus2.webservice.queryoptions.QueryParameter;
#WebService()
public interface WebServiceVenus2Interface {
/**
* FETCHING DATA FROM DATABASE
*
*/
#WebMethod
public void Foo(ParticipantQueryParameterKey pqpk);
#WebMethod
public String test();
#WebMethod
public String sayHello(String string) throws WebServiceException;
The code for my web service:
import javax.annotation.Resource;
import javax.jws.WebParam;
import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;
import no.solarsoft.venus2.datamanager.CRUDOperation;
import no.solarsoft.venus2.datamanager.DataManager;
import no.solarsoft.venus2.entities.GradeScale;
import no.solarsoft.venus2.enums.ImageType;
import no.solarsoft.venus2.exception.DataAccessException;
import no.solarsoft.venus2.exception.InstanceNotFoundException;
import no.solarsoft.venus2.service.EmailService;
import no.solarsoft.venus2.webservice.exception.ParameterValidationException;
import no.solarsoft.venus2.webservice.exception.WebServiceException;
import no.solarsoft.venus2.webservice.exception.WebServiceFaultBean;
import no.solarsoft.venus2.webservice.queryoptions.ParticipantQuery;
import no.solarsoft.venus2.webservice.queryoptions.ParticipantQueryParameterKey;
import no.solarsoft.venus2.webservice.queryoptions.QueryParameter;
// #Stateless()
#javax.jws.WebService(endpointInterface = "no.solarsoft.venus2.webservice.WebServiceVenus2Interface", serviceName = "WebServiceVenus2Service")
public class WebServiceVenus2 implements WebServiceVenus2Interface {
private DataManager dataManager = DataManager.getInstance();
private static final Logger log = Logger.getAnonymousLogger();
#Resource
WebServiceContext wsContext;
#Override
public void Foo(ParticipantQueryParameterKey pqpk) {}
private void logEntered(String login) {
log.info(MessageFormat.format("{0}: ''{1}'' entered web service method ''{2}()''",
WebServiceVenus2.class.getSimpleName(), login, getMethodName()));
}
private String getClientIp() {
MessageContext mc = wsContext.getMessageContext();
HttpServletRequest req = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST);
return req.getRemoteAddr();
}
/**
* Get the method name for a depth in call stack. <br />
* Utility function
*
* #param depth
* depth in the call stack (0 means current method, 1 means call method, ...)
* #return method name
*/
public static String getMethodName() {
final StackTraceElement[] ste = Thread.currentThread().getStackTrace();
return ste[3].getMethodName(); // Thank you Tom Tresansky
}
/**
* FETCHING DATA FROM DATABASE
*/
#Override
public String test() {
String ip = getClientIp();
logEntered(ip);
return "WebService test succeded! Client IP: " + ip;
}
#Override
public String sayHello(String string) throws WebServiceException {
logEntered(null);
if (string == null || string.isEmpty()) {
log.severe("Throwing excetion...");
throw new WebServiceException("String can not be empty or NULL!", new WebServiceFaultBean());
}
log.exiting(WebServiceVenus2.class.getName(), WebServiceVenus2.getMethodName());
return "Hello " + string + "!";
}
and here is my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
</web-app>
I hope someone can help me. Thanks

I loaded this code nearly verbatim to a dynamic web module in eclipse and deployed to Glassfish4. When deployed (using eclipse "add to server") the WSDL is available at http://localhost:8181/Venus2WebService/WebServiceVenus2Service?wsdl
and the web service endpoint is http://localhost:8181/Venus2WebService/WebServiceVenus2Service
The only jars I included from CXF (not shown in your post) are, from reading WHICH_JARS readme within CXF binary distribution lib dir:
asm-3.3.1.jar
commons-logging-1.1.1.jar
cxf-2.7.17.jar
geronimo-javamail_1.4_spec-1.7.1.jar
geronimo-jaxws_2.2_spec-1.1.jar
jaxb-api-2.2.6.jar
jaxb-impl-2.2.6.jar
neethi-3.0.3.jar
stax2-api-3.1.4.jar
wsdl4j-1.6.3.jar
xmlschema-core-2.1.0.jar
I got the endpoint URL from watching the eclipse console for the server:
2015-09-09T21:45:40.683-0400|Info: Webservice Endpoint deployed WebServiceVenus2
listening at address at http://oc-mbp01.local:8181/Venus2WebService/WebServiceVenus2Service.
Classpath (all in WEB-INF/lib for me):

Related

How to configure jhipster application

I am new to jhipster. I generated a project with the terminal jhipster command. I have a gateway service, upon trying to start the application I am getting these errors, the funny thing is I did not modify anything just out of box this happened. I have java 15, :
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'gatewayResource' defined in file : Unable to resolve Configuration with the provided Issuer of "http://localhost:9080/auth/realms/jhipster"
this is my gateway class:
package com.moniesta.admin.web.rest;
import com.moniesta.admin.web.rest.vm.RouteVM;
import java.util.ArrayList;
import java.util.List;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.route.RouteLocator;
import reactor.core.publisher.Flux;
import org.springframework.http.*;
import org.springframework.security.access.annotation.Secured;
import com.moniesta.admin.security.AuthoritiesConstants;
import org.springframework.web.bind.annotation.*;
/**
* REST controller for managing Gateway configuration.
*/
#RestController
#RequestMapping("/api/gateway")
public class GatewayResource {
private final RouteLocator routeLocator;
private final DiscoveryClient discoveryClient;
#Value("${spring.application.name}")
private String appName;
public GatewayResource(RouteLocator routeLocator, DiscoveryClient discoveryClient) {
this.routeLocator = routeLocator;
this.discoveryClient = discoveryClient;
}
/**
* {#code GET /routes} : get the active routes.
*
* #return the {#link ResponseEntity} with status {#code 200 (OK)} and with body the list of routes.
*/
#GetMapping("/routes")
#Secured(AuthoritiesConstants.ADMIN)
public ResponseEntity<List<RouteVM>> activeRoutes() {
Flux<Route> routes = routeLocator.getRoutes();
List<RouteVM> routeVMs = new ArrayList<>();
routes.subscribe(route -> {
RouteVM routeVM = new RouteVM();
// Manipulate strings to make Gateway routes look like Zuul's
String predicate = route.getPredicate().toString();
String path = predicate.substring(predicate.indexOf("[") + 1, predicate.indexOf("]"));
routeVM.setPath(path);
String serviceId = route.getId().substring(route.getId().indexOf("_") + 1).toLowerCase();
routeVM.setServiceId(serviceId);
// Exclude gateway app from routes
if (!serviceId.equalsIgnoreCase(appName)) {
routeVM.setServiceInstances(discoveryClient.getInstances(serviceId));
routeVMs.add(routeVM);
}
});
return ResponseEntity.ok(routeVMs);
}
}

/ExampleApplication/IntrusionException] INTRUSION - Mixed encoding (2x) detected in URL

I am retrieving URL from database and it contains special characters like % - = / ? etc. so while I try to populate that in my page JSON is not able to parse that URL and it is giving me some exception when I was debugging I got like this
(Log4JLogger.java:log:449) [SECURITY FAILURE Anonymous:null#unknown -> /ExampleApplication/IntrusionException] INTRUSION - Mixed encoding (2x) detected
I tried from these link here this my offending URL here
but it is not working he mentioned that bug is solved. but for which version version here I am using is 2.1.0 below is my code
package com.ghn.repufact.review.extractor;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import javax.ws.rs.core.UriBuilder;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.log4j.Logger;
import org.owasp.esapi.ESAPI;
import org.owasp.esapi.Encoder;
import org.owasp.esapi.Validator;
import org.owasp.esapi.errors.EncodingException;
import org.owasp.esapi.reference.DefaultValidator;
import org.springframework.stereotype.Component;
#Component
public class ValidateURL {
private static final Logger logger=Logger.getLogger(ValidateResponse.class);
public String parseOrgConsumerLink(String myLink) throws URISyntaxException {
if(myLink==null || "".equalsIgnoreCase(myLink))
return myLink;
Encoder enc=ESAPI.encoder();
URI mixURI=new URI(myLink);
UriBuilder uriBuider=UriBuilder.fromUri(enc.canonicalize(mixURI.getAuthority()+mixURI.getPath()));
uriBuider.path(enc.canonicalize(mixURI.getAuthority() + mixURI.getPath()));
logger.info("Uri after URIbuilder:"+uriBuider.build().toString());
List<NameValuePair> params = URLEncodedUtils.parse(mixURI, "UTF-8");
for (NameValuePair nameValuePair : params)
uriBuider.queryParam(enc.canonicalize(nameValuePair.getName()), enc.canonicalize(nameValuePair.getValue()));
String canonicalizedUrl = uriBuider.build().toString();
logger.info("canonicaliz URI:"+canonicalizedUrl);
return canonicalizedUrl;
}
public boolean isCanonicalizedURI(String myLink) throws EncodingException {
Validator validator=DefaultValidator.getInstance();
//boolean flag=validator.isValidInput("test", myLink, "URI", 200, false);
myLink = ESAPI.encoder().encodeForURL(myLink);
boolean flag = validator.isValidInput("APPNAME", myLink, "URLSTRING", 600, true, false);
logger.info("checking for URI:"+myLink+" isCanonical:"+flag);
return flag;
}
}
please let me know if any work around here. By the way I am using spring MVC

JNDI Initial Context & Lookup_problem for EJB 3

This issue is very common. I have read some articles but can't find the problem. I want to create a simple HelloWorld program in EJB 3.0, eclipse luna, jboss 7.1.1 Final.
Here is my bean:
package com.tcs.HelloWorldPack;
import javax.ejb.Stateless;
/**
* Session Bean implementation class HelloWorld
*/
#Stateless(mappedName="HelloWorldBean")
public class HelloWorld implements HelloWorldRemote {
/**
* Default constructor.
*/
public HelloWorld() {
// TODO Auto-generated constructor stub
}
#Override
public void displayMsg() {
// TODO Auto-generated method stub
System.out.println("Hello World!!");
}
}
Here is my remote interface:
package com.tcs.HelloWorldPack;
import javax.ejb.Local;
//import javax.ejb.Remote;
import javax.ejb.Remote;
#Remote
public interface HelloWorldRemote {
void displayMsg();
}
Here is my client which is running in the same machine:
package com.tcs.HelloWorldClient;
import java.util.Hashtable;
import java.util.Properties;
import com.tcs.HelloWorldPack.*;
import javax.ejb.EJB;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class HelloWorldClient {
public static void main(String[] args) throws NamingException {
final Hashtable jndiProperties = new Hashtable();
jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
jndiProperties.put(javax.naming.Context.SECURITY_PRINCIPAL, "myUser");
jndiProperties.put(javax.naming.Context.SECURITY_CREDENTIALS, "myPass");
// jndiProperties.put(javax.naming.Context.PROVIDER_URL, "jnp://localhost:1099");
// jndiProperties.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
jndiProperties.put("jboss.naming.client.ejb.context", true);
final Context context = new InitialContext(jndiProperties);
final String appName= "HeloWorldEJBEAR";
final String moduleName= "";
final String distinctName ="";
final String beanName = "HeloWorld";
final String viewClassName = "com.tcs.HelloWorldPack.HelloWorldRemote";
HelloWorldRemote hello = (HelloWorldRemote) context.lookup("ejb:" + appName + "/" + moduleName + "/" + distinctName + "/" + beanName + "!" + viewClassName);
hello.displayMsg();
}
}
This is my jboss-ejb-client.properties file:
remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED=false
remote.connections=default
remote.connection.default.host=localhost
remote.connection.default.port = 4447
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false
remote.connection.default.username=myUser
remote.connection.default.password=myPass
I have put the properties file in the classpath also.But this is happening when I am trying to run it:
Exception in thread "main" java.lang.IllegalStateException: No EJB receiver available for handling [appName:HeloWorldEJBEAR,modulename:,distinctname:] combination for invocation context org.jboss.ejb.client.EJBClientInvocationContext#413ded77
at org.jboss.ejb.client.EJBClientContext.requireEJBReceiver(EJBClientContext.java:584)
at org.jboss.ejb.client.ReceiverInterceptor.handleInvocation(ReceiverInterceptor.java:119)
at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:181)
at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:136)
at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:121)
at org.jboss.ejb.client.EJBInvocationHandler.invoke(EJBInvocationHandler.java:104)
at com.sun.proxy.$Proxy0.displayMsg(Unknown Source)
at com.tcs.HelloWorldClient.HelloWorldClient.main(HelloWorldClient.java:71)
Jan 08, 2015 3:34:44 PM org.jboss.ejb.client.remoting.ChannelAssociation$ResponseReceiver handleEnd
INFO: Channel Channel ID de8d2aa6 (outbound) of Remoting connection 44477156 to localhost/127.0.0.1:4447 can no longer process messages
I have also uploaded my directory structure. I am new to the EJB concept. Please help me to find where is the problem. Thanks in advance.
Your module name is an empty String, but the module name can't be an empty string in the JNDI name.
Look here
you have to set the name of your ejb module .jar, without the .jar suffix.
final String moduleName = "HeloWorldEJB";
Then it should work.
As you are out to do a simple example lets keeep it simple [KISS],Most of your code is correct the catch is the client, I have simplified the client code, added my comments in client hope its self explanatory.And.... Added on EJB #javax.ejb.Stateless(name = "HelloWorldEJB") //This is portable No Vendor locked in. Alternative is mappedName [removed from your code #Stateless(mappedName="HelloWorldBean") p]which i believe is more weblogic and glassfish centric.
Ensure you have client.jar in your class path. this is the only jar you will have to add aftr you have created the EJB project in intelija or eclipse or any other ide.
I have deployed the EJB's in glassfish container once ear deployed successfully, run the client.
Apart from the below code you wont need any other configurations. This code is portable and should work on most containers however Surprises is fun do run as is and let me know .....
Once the below works for you you can add other jndi properties as per your project requirement and move on.....
==============================
The Remote
package com.au.ejbs;
import javax.ejb.Remote;
#Remote
public interface HelloWorldI {
String displayMessage(String message);
}
=================================
2. The Impl
package com.au.ejbs;
import javax.ejb.Remote;
#javax.ejb.Stateless(name = "HelloWorldEJB")
public class HelloWorld implements HelloWorldI {
#Override
public String displayMessage(String message) {
// TODO Auto-generated method stub
return "Returning from Remote" + message;
}
}
======================================
3. The client
package com.au.clients;
import com.au.ejbs.HelloWorldI;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class HelloWorldT {
public static void main(String[] args) throws NamingException {
Context context = new InitialContext();
HelloWorldI helloWorldI = (HelloWorldI)context.lookup("java:global/ejb3_2_ear_exploded/ejb/HelloWorldEJB");
//portable syntax java:global/[ ear name]/[module name normally the jar name in my case ejb.jar within the ear, ejb3_2_ear_exploded]/name in ....javax.ejb.Stateless(name = "HelloWorldEJB")/
System.out.println( "output " + helloWorldI.displayMessage("From Client with luv...."));
}
}
===================
4. output
output Returning from RemoteFrom Client with luv....

How to access web service using an ordinary java class?

**My Web service class**
import javax.jws.WebMethod;
import javax.jws.WebService;
/**
* #author edward
*
*/
#WebService
public class HelloWeb {
#WebMethod
public String sayGreeting(String name) {
return "Greeting " + name + "....!";
}
}
My Server java class
import javax.xml.ws.Endpoint;
public class Server {
public static void main(String[] args) {
Endpoint.publish("http://localhost:9090/HelloWeb", new HelloWeb());
System.out.println("Hello Web service is ready");
}
}
Server is running properly, and i am able to access the service using url that returns WSDL code.But i want to access the server using unique URL in java.I have the following client java code.
Client to access HelloWeb Service
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.rpc.Service;
import javax.xml.rpc.ServiceFactory;
public class WebClient {
String wsdl = "http://172.21.1.65:9090/HelloWeb?wsdl";
String namespace = "http://helloweb.com";
String serviceName = "HelloWebService";
QName serviceQN = new QName(namespace, serviceName);
{
try{
ServiceFactory serviceFactory = ServiceFactory.newInstance();
Service service = serviceFactory.createService(new URL(wsdl), serviceQN);
}catch (Exception e) {
}
}
}
try this, note that I compiled and ran your server in "test" package, it's important. This is just a basic example to start with JAX-WS.
package test;
import java.net.URL;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
public class WebClient {
#WebService(name = "HelloWeb", targetNamespace = "http://test/")
public interface HelloWeb {
#WebMethod
String sayGreeting(String name);
}
public static void main(String[] args) throws Exception {
Service serv = Service.create(new URL(
"http://localhost:9090/HelloWeb?wsdl"),
new QName("http://test/", "HelloWebService"));
HelloWeb p = serv.getPort(HelloWeb.class);
System.out.println(p.sayGreeting("John"));
}
}

Problem with the Apache DefaultHttpClient class

I am a newbie for servlet applications, trying to learn the subject. On my way, I wrote a servlet class called FormWebServlet that uses the org.apache.http.impl.client.DefaultHttpClient class. However, I get the exception
java.lang.ClassNotFoundException: org.apache.http.impl.client.DefaultHttpClient
... that clearly shows that this class does not exist, although I have added the jar file to the project.
The server returns an "HTTP Status 500" error with the message that the "root cause" is this missing class:
java.lang.NoClassDefFoundError: org/apache/http/impl/client/DefaultHttpClient
testPackage.FormWebServlet.doGet(FormWebServlet.java:45)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
TRIES
1) I searched for the missing jar file and added it to the project (by going on the project in "Eclipse JAVA EE IDE for Web Developers, 20100917-0705"'s project explorer, select "Properties", selected the "Java Build Path" and clicked the [Add External JARs...] button.) The added jar file is from the Apache site and is called httpclient-4.1.1.jar.
2) As I still get the same error, I extracted with 7-ZIP the DefaultHttpClient.class file and put it into the WebContent/WEB-INF/lib directory.
QUESTION
What am I doing wrong? Neither of the other two JAR files do contain the class, nor is there a class with this name in the WEB-INF/lib folder.
DETAILS
Inculded JARs:
common-httpclient-3.0.1.jar
httpclient-4.1.1.jar
httpcore-4.1.jar
FormWebServlet.jar:
/**
*
*/
package testPackage;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import coreServlets.ServletUtilities;
/**
*
*/
#WebServlet(description = "Gets the book's barcode with a form", urlPatterns = { "/FormWebServlet" })
public class FormWebServlet extends HttpServlet {
/** */
private static final long serialVersionUID = 6008315960327824633L;
/**
* #see HttpServlet#doGet(HttpServletRequest request,
* HttpServletResponse response)
*/
protected void doGet(final HttpServletRequest request,
final HttpServletResponse response)
throws IOException, ServletException {
final String BAR_CODE = request.getParameter("barCode");
response.setContentType("text/html");
final PrintWriter out = response.getWriter();
if (BAR_CODE != null) {
HttpClient client = new DefaultHttpClient();
final String ADDRESS = ServletUtilities.getHttpAddress(BAR_CODE);
out.println("ADDRESS = \"" + ADDRESS + '\"');
HttpGet get = new HttpGet(ADDRESS);
HttpResponse httpResponse = null;
// Removed commented code that will use these objects
}
}
}
Just put the JAR files themselves into WEB-INF/lib, not the class file. That way they will be included in your deployment.

Categories