Hi i am creating client from my webservice. Client is generated successfully but when I call that from java code It throws following error:
Exception in thread "main" javax.xml.ws.WebServiceException: Failed to access the WSDL at: https://ebs-uat.corp.chartercom.com/csg_cter/2.06/orderdetailservice.asmx?wsdl. It failed with:
Server returned HTTP response code: 401 for URL: https://ebs-uat.corp.chartercom.com/csg_cter/2.06/orderdetailservice.asmx?wsdl.
at com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.tryWithMex(RuntimeWSDLParser.java:151)
at com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.parse(RuntimeWSDLParser.java:133)
at com.sun.xml.internal.ws.client.WSServiceDelegate.parseWSDL(WSServiceDelegate.java:254)
at com.sun.xml.internal.ws.client.WSServiceDelegate.<init>(WSServiceDelegate.java:217)
at com.sun.xml.internal.ws.client.WSServiceDelegate.<init>(WSServiceDelegate.java:165)
at com.sun.xml.internal.ws.spi.ProviderImpl.createServiceDelegate(ProviderImpl.java:93)
at javax.xml.ws.Service.<init>(Service.java:56)
at com.charter.enterprise.billing.csg.orderdetails.OrderDetailServicePort.<init>(OrderDetailServicePort.java:68)
at com.charter.enterprise.billing.csg.orderdetails.OrderDetailServiceClient.main(OrderDetailServiceClient.java:18)
Caused by: java.io.IOException: Server returned HTTP response code: 401 for URL: https://ebs-uat.corp.chartercom.com/csg_cter/2.06/orderdetailservice.asmx?wsdl
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1436)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:234)
at java.net.URL.openStream(URL.java:1010)
at com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.createReader(RuntimeWSDLParser.java:793)
at com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.resolveWSDL(RuntimeWSDLParser.java:251)
at com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.parse(RuntimeWSDLParser.java:118)
... 7 more
It throws exception in first line when creating webservice port
DataServicePort dataServicePort = new DataServicePort();
My complete client class is:
public class OrderDetailServiceClient {
#WebServiceRef
private static OrderDetailServicePort orderDetailServicePort;
private static OrderDetailService orderDetailService;
public static void main(String[] args) {
orderDetailServicePort = new OrderDetailServicePort();
orderDetailService = orderDetailServicePort.getOrderDetailService();
// Add your code to call the desired methods.
System.out.println("Before calling method!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
verifyOrderDetail();
}
private static void verifyOrderDetail() {
BindingProvider prov = (BindingProvider) orderDetailService;
prov.getRequestContext().put(BindingProvider.USERNAME_PROPERTY,
"CHTR\tst_aopebstest");
prov.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY,
"T$t_#0p3B$t#sT");
orderDetailService = (OrderDetailService) prov;
VerifyOrderDetailRequest verifyOrderDetailRequest = new VerifyOrderDetailRequest();
VerifyOrderDetailResponse verifyOrderDetailResponse = orderDetailService
.verifyOrderDetail(verifyOrderDetailRequest, null);
}
}
I can hit in my browser. And it is also working in SoapUI. Where am I going wrong?
Any suggestion will be appreciated.
Thanks in advance.
It looks like you can't access that web service, have you tried accessing that web service through a web browser?
Related
I want to add Authorization header for basic Authorization to my jetty-client request.
I am running two instances on same browser one is server one is client ,Java-8 is being used as a technology, No DB No Spring etc. using org.eclipse.jetty,jetty-websocket,version-8.1.15.v20140411.
I had a websocketEndPointManager class which contains the initialization method for both Server(dedicated class is CSWebsocket) and client(Cpwebsocket).
How can I achieve basic auth in my scenario where server maintains username and password is to matched in current session after its instance is ready, currently my setup able to perform upgrade to websocket but not basic
Snippet of client websocket start method where handshake occur :
private void startCPWebSocket() throws Exception{
String uri ="";
try {
HandlerRegistry.register(this);
WebSocketClientFactory factory = new WebSocketClientFactory();
Configuration configuration = TestSession.getConfiguration();
uri = configuration.getSystemUnderTestEndpoint();
TestSession.getConfiguration().setToolURL("NA");
TestSession.getConfiguration().setSystemUnderTestEndpoint(uri);
factory.start();
WebSocketClient client = factory.newWebSocketClient();
client.setMaxIdleTime(24*60*60*1000);
client.open(new URI(uri.trim()),new CPWebSocket()).get(24*60*60,
TimeUnit.SECONDS);
LogUtils.logInfo("WebSocket URL : "+uri,true);
}
catch (ExecutionException e) {
LogUtils.logError(e.getMessage(), e,false);
LogUtils.logWarn("Could not establish websocket connection.",true);
//System.exit(0);
TestSession.setTerminated(true);
throw e;
I am using jersey filter.
In My code logic in AuthenticationFilter.java, if the authorization header is empty, then return the access denied error message.
First time I am hitting the application through rest client tool using the URL without attaching the header
http://localhost:8080/JerseyDemos2/rest/pocservice
Get the status 401 with error message "you cannot access this resource". This is right.
When i tried to hit second time thorugh rest client tool, and server return the exception message.
I deployed my application in tomcat 7.x both windows and linux
Why it give the error when we hit the second time.
How to resolve this
#Provider
public class AuthenticationFilter implements javax.ws.rs.container.ContainerRequestFilter {
#Context
private ResourceInfo resourceInfo;
private static final String AUTHORIZATION_PROPERTY = "Authorization";
private static final Response ACCESS_DENIED = Response.status(Response.Status.UNAUTHORIZED).entity("You cannot access this resource").build();
#Override
public void filter(ContainerRequestContext requestContext) {
// Get request headers
final MultivaluedMap<String, String> headers = requestContext.getHeaders();
// Fetch authorization header
final List<String> authorization = headers.get(AUTHORIZATION_PROPERTY);
// If no authorization information present; block access
if (authorization == null || authorization.isEmpty()) {
requestContext.abortWith(ACCESS_DENIED);
return;
}
}
} }
Error message:
Dec 19, 2016 6:26:18 PM org.glassfish.jersey.server.ServerRuntime$Responder writeResponse
SEVERE: An I/O error has occurred while writing a response message entity to the container output stream.
java.lang.IllegalStateException: The output stream has already been closed.
at org.glassfish.jersey.message.internal.CommittingOutputStream.setStreamProvider(CommittingOutputStream.java:147)
at org.glassfish.jersey.message.internal.OutboundMessageContext.setStreamProvider(OutboundMessageContext.java:803)
......
Please help me
Thanks in advance.
I Removed static variable
private static final Response ACCESS_DENIED = Response.status(Response.Status.UNAUTHORIZED).entity("You cannot access this resource").build();
and i declared local variable. now its working fine.
#Provider
public class AuthenticationFilter implements javax.ws.rs.container.ContainerRequestFilter {
#Context
private ResourceInfo resourceInfo;
private static final String AUTHORIZATION_PROPERTY = "Authorization";
#Override
public void filter(ContainerRequestContext requestContext) {
Response ACCESS_DENIED = Response.status(Response.Status.UNAUTHORIZED).entity("You cannot access this resource").build();
// Get request headers
final MultivaluedMap<String, String> headers = requestContext.getHeaders();
// Fetch authorization header
final List<String> authorization = headers.get(AUTHORIZATION_PROPERTY);
// If no authorization information present; block access
if (authorization == null || authorization.isEmpty()) {
requestContext.abortWith(ACCESS_DENIED);
return;
}
}
} }
You're trying to write in a response that was written before. The full log shows where is it happening. Upload the log and the code where the httpresponse is used/modified.
What I want to do:
Implement a Camel route from a CXF Endpoint to an JMS queue with schema validation in CXF endpoint.
Validation is enabled in CXF endpoint:
/* Set endpoint properties */
Map<String, Object> propertiesMap = new HashMap<String, Object>();
propertiesMap.put("schema-validation-enabled", "true");
/* Create endpoint */
CxfEndpoint cxfEndpoint = new CxfEndpoint();
cxfEndpoint.setWsdlURL("wsdl/input.wsdl");
cxfEndpoint.setDataFormat(DataFormat.CXF_MESSAGE);
cxfEndpoint.setProperties(propertiesMap);
cxfEndpoint.getInInterceptors().add(new FaultInterceptor());
The Camel route:
from(cxfEndpoint)
.routeId("INPUT_ROUTE")
.to("jms:foo.bar");
The CXF interceptor:
public class FaultInterceptor extends AbstractSoapInterceptor {
private static final Logger LOGGER = Logger.getLogger(FaultInterceptor.class);
public FaultInterceptor() {
super(Phase.UNMARSHAL);
}
public void handleMessage(SoapMessage message) throws Fault {
LOGGER.info("handleMessage=" + message.getExchange().getInMessage());
}
#Override
public void handleFault(SoapMessage message) {
Fault fault = (Fault) message.getContent(Exception.class);
LOGGER.info("handleFault='" + fault + "'");
/* Add some header property that says the message is invalid */
}
}
Problem:
The works ok if I send a valid SOAP message. If I send an invalid SOAP message, the handleFault method kicks in, logs the fault and that's all.
For the invalid SOAP message scenario, is it possible that I can log the fault with handleFault method and still route the invalid message to the JMS queue?
This is the only interceptor I've added to the endpoint.
I'm using:
Apache ServiceMix 5.0.0
Apache Camel 2.12.3
Apache CXF 2.7.10
You can't do a try/catch statement since the error happends in the "from" clause.
However, you can use a Dead Letter Channel.
errorHandler(deadLetterChannel("jms:foo.bar.invalid"));
from(cxfEndpoint)
.routeId("INPUT_ROUTE")
.to("jms:foo.bar");
I need to write a REST client with Jersey implementation of JAX-RS to access my RESTful webservice that works with a secure EJB. I have a #OneToMany relationship from class A to B. I am using Glassfish 3.1.1 application server. But when I run the my rest client it gives me following errors:
Error on the client side:
com.sun.jersey.api.client.UniformInterfaceException: GET http://localhost:8080/myapp/rest/a/all returned a response status of 500 Internal Server Error
Error on the server side:
SEVERE: The response of the WebApplicationException cannot be utilized as the response is already committed. Re-throwing to the HTTP container
javax.ws.rs.WebApplicationException: javax.xml.bind.PropertyException: Unsupported Property
at com.sun.jersey.core.provider.jaxb.AbstractListElementProvider.writeTo(AbstractListElementProvider.java:183)
at com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:306)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1437)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1539)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:330)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:174)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:828)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:725)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1019)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:619)
MyRestClient is my rest client that I am using in a standalone client application to call my RESTful webservice that I have implemented as an EJB session bean.
MyRestClient.java
public class MyRestClient {
public static void main(String[] args) {
Client client = Client.create();
client.addFilter(new HTTPBasicAuthFilter("username", "password"));
WebResource resource = client.resource("http://localhost:8080/myapp/rest/a/all");
List<A> aList = resource.get(new GenericType<List<A>>() {});
for(A nextA: aList){
System.out.println(nextA.getTitle());
}
}
}
AResource is my REST webservice that has been implemented as an EJB webservice.
AResource.java
#Stateless
#Path("/a")
public class AResource {
#EJB
private AService aService;
#GET
#Produces(MediaType.APPLICATION_XML)
#Path("/all")
public List<A> getAllA() {
return aService.getAllA();
}
}
A and B are the domain objects used to hold the data returned from the server at the client side.
A.java
#XmlRootElement
public class A implements Serializable{
private List<B> bList = new ArrayList<B>();
public List<B> getBList() {
return bList;
}
//remaining code
}
B.java
#XmlRootElement
public class B implements Serializable {
private String text;
private A a;
#XmlTransient
public A getA() {
return a;
}
public void afterUnmarshal(Unmarshaller u, Object parent) {
this.a = (A) parent;
}
//remaining code
}
Could someone help me understand why am I getting these errors?
Thanks.
The first exception you were getting on the client side is caused by the fact there was an error on the server and the server returned unexpected response (as instead of the resource response, it returned an error response with html body).
The second problem is caused by a Jersey's 1.8 hard dependency on JAXB RI, which got introduced by mistake. So, when you try using MOXy, it would fail. This is fixed in Jersey 1.9 and 1.9.1. So, if you want to continue using MOXy, just upgrade Jersey in GF from update center to the latest one and it should start working.
I was using org.eclipse.persistence.moxy-2.3.jar to test it over JAXB RI used by Glassfish 3.1.1. I had set javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory in jaxb.properties file in the classpath with my domain objects to test MOXy, which after being removed solved the problem.
So, removing the jaxb.properties file from classpath solved the problem.
The problem was being created by the line:
List<A> aList = resource.get(new GenericType<List<A>>() {});
how can I access a webservice through a basic http authentification? I am using the netbeans built in webservice client features. But when I try to access the webservice, I get an exception with a 401 auth failed error message.
How can I pass the right username and password?
Thank you!
You could use BindingProvider or WSBindingProvider class to access a Web Service through a basic http authentification.
The code is as follows.
XxxService service = new XxxService();
Xxx port = service.getXxxPort();
Map<String, Object> reqContext = ((BindingProvider)port).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "username");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "password");
You can also provide your own Authenticator. That way it will work even if the WDSL itself is protected by basic HTTP authentication.
#WebServiceRef(wsdlLocation = "https://laka/sito?wsdl")
static XxxService service;
public static void main(String[] args) {
Authenticator.setDefault(new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("user", "password".toCharArray());
}
});
service = new XxxService();
Xxx port = service.getXxxPort();
// invoke webservice and print response
XxxResponse resp = port.foo();
System.out.println(resp.toString());
}