I create a jax-ws service for get some data.I user tomcat 8.5.11.. The web service works fine and when I put the URL the WSDL shows and it previews all web methods... But it doesn't preview the output(XML) of each methods. How can I preview the output... I'm the service provider... I want to know how the output will be preview to the clients...
This is my web service class.
/*
* 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.
*/
package lk.slsi.webService;
import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.ws.rs.PathParam;
import lk.slsi.domain.CustomsPermit;
import lk.slsi.services.permitServices;
import org.springframework.beans.factory.annotation.Autowired;
#WebService(serviceName = "customsPermit")
public class webServiceforCustoms {
#Autowired
private permitServices permitServices;
#WebMethod
public List<CustomsPermit> getXmlbyDate(String dtIssue) {
List<CustomsPermit> permitRelease = permitServices.getPermitByDate(dtIssue);
return permitRelease;
}
#WebMethod
public CustomsPermit getXmlbyEntryNo(String SNumber) {
CustomsPermit permitRelease = permitServices.getPermitBySNumber(SNumber);
return permitRelease;
}
#WebMethod
public List<CustomsPermit> getXmlbyVATNo(String importerVAT) {
List<CustomsPermit> permitRelease = permitServices.getPermitByImporterVAT(importerVAT);
return permitRelease;
}
}
Related
I want to read request header from SOAP incoming request in my Java code for some authorization purpose. I found few work-arounds like using SOAPHandlers and . Code as below :
`package com.cerillion.ccs.framework;
import java.util.HashSet;
import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
import org.apache.log4j.Logger;
public class ApiSoapHandler implements SOAPHandler<SOAPMessageContext> {
private static final Logger logger = Logger.getLogger(ApiSoapHandler.class.getName());
#Override
public void close(MessageContext arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean handleFault(SOAPMessageContext context) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean handleMessage(SOAPMessageContext context) {
logger.debug("Inside ApiSoapHandler");
try {
SOAPMessage message = context.getMessage();
SOAPHeader header = message.getSOAPHeader();
message.saveChanges();
} catch (SOAPException e) {
logger.error("Error occurred while adding credentials to SOAP header.",
e);
}
return true;
}
#Override
public Set<QName> getHeaders() {
/* QName securityTokenHeader = new QName("urn:com.intertech.secty", "token");
//new QName(“urn:com.intertech.secty”,“username”);
HashSet<QName> headers = new HashSet<QName>();
headers.add(securityTokenHeader);
return headers;*/
return null;
} }`
I ma really curious about to have some other simple alternative rather than writing entire handler just for fetching custom header tag. Is this the only way to read SOAP request header ? Any leads are really appreciated
I am new to restful webservices and following java restful api tutorials.
all the HTTP requests are working fine except the DELETE request.
i am facing the same issue as described in this link.
REST - HTTP Status 405 - Method Not Allowed
also , in the predefined header values postman is showing
allow →GET,OPTIONS,PUT(image link is below)
i am following the correct syntax and url format as per the specification(pasted in image) but delete is not working.
allowed : GET,OPTIONS,PUT.img
please let me know where i am missing.
Edit : Source code :
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.koushik.javabrains.messenger.model.Message;
import org.koushik.javabrains.messenger.service.MessageService;
#Path("/messages")
public class MessageResource {
MessageService messageService = new MessageService();
#GET
#Produces(MediaType.APPLICATION_JSON)
public List<Message> getMessages(){
System.out.println("Hello There");
List<Message> returnedList = messageService.getAllMessages();
System.out.println(returnedList);
return returnedList;
}
#GET
#Path("/{messageId}")
#Produces(MediaType.APPLICATION_JSON)
public Message getMessage(#PathParam("messageId") long messageId){
System.out.println("Message returned");
return messageService.getMessage(messageId);
}
#POST
#Produces(MediaType.APPLICATION_JSON)
public Message addMessage(Message message){
return messageService.addMessage(message);
}
#PUT
#Path("/{messageId}")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Message updateMessage(#PathParam("messageId") long id , Message message){
message.setId(id);
return messageService.updateMessage(message);
}
#DELETE
#Path("/messageId")
#Produces(MediaType.APPLICATION_JSON)
public void deleteMessage(#PathParam("messageId") long id){
System.out.println("Hello There");
messageService.removeMessage(id);
}
}
package org.koushik.javabrains.messenger.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.koushik.javabrains.messenger.database.DatabaseClass;
import org.koushik.javabrains.messenger.model.Message;
public class MessageService {
private Map<Long , Message> messages = DatabaseClass.getMessages();
public MessageService(){
messages.put(1L, new Message(1, "Hello World" , "koushik"));
messages.put(2L, new Message(2, "Hello Jersey" , "Koushik"));
}
public List<Message> getAllMessages(){
return new ArrayList<Message>(messages.values());
}
public Message getMessage(long id){
Message m = messages.get(id);
System.out.println("Value of message "+m);
return m;
}
public Message addMessage(Message message){
message.setId(messages.size()+1);
messages.put(message.getId(), message);
return message;
}
public Message updateMessage(Message message){
if(message.getId() <=0){
return null;
}
messages.put(message.getId(), message);
return message;
}
public Message removeMessage(long id){
return messages.remove(id);
}
}
package org.koushik.javabrains.messenger.database;
import java.util.HashMap;
import java.util.Map;
import org.koushik.javabrains.messenger.model.Message;
import org.koushik.javabrains.messenger.model.Profile;
public class DatabaseClass {
private static Map<Long , Message> messages = new HashMap();
private static Map<String , Profile> profiles = new HashMap();
public static Map<Long , Message> getMessages() {
return messages;
}
public static Map<String, Profile> getProfiles() {
return profiles;
}
}
except delete other requests are working fine.
on sending DELETE the server is returning HTTP -405 method not allowed.
also on sending delete request then in the header values postman is showing
allow →GET,OPTIONS,PUT
Thanks
Make sure you do not have any URL Parameters entered in Postman, also make sure you do not pass any headers in postman.
The delete request should be plain without and of these.
Also, the string message ID need to be put in curly brackets. That would be the reason for your 405 mostly.
Change path annotation as below and try.
#Path("/{messageId}")
Below is my SOAP request:
Aditya
?
My rest of the classes are:
HelloWorld.java
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
//Service Endpoint Interface
#WebService
#SOAPBinding(style = Style.RPC)
public interface HelloWorld{
#WebMethod String getHelloWorldAsString(String name, String company);
}
HelloWorldImpl.java:
import javax.jws.WebService;
import com.sun.xml.internal.ws.developer.SchemaValidation;
//Service Implementation
//#SchemaValidation
#WebService(endpointInterface = "org.techsavvy.HelloWorld")
public class HelloWorldImpl implements HelloWorld{
#Override
public String getHelloWorldAsString(String name, String company) {
return "Hello!! your name is " + name+ " and you work in " +company+ ".";
}
}
HelloWorldPublisher.java
import javax.xml.ws.Endpoint;
import org.techsavvy.HelloWorldImpl;
//Endpoint publisher
public class HelloWorldPublisher{
public static void main(String[] args) {
Endpoint.publish("http://localhost:9999/ws/hello", new HelloWorldImpl());
}
}
Problem: I am running my webservice in SOAPUI by adding the wsdl path(http://localhost:9999/ws/hello?wsdl). Once the request is generated I am entering the values for and and it runs successfully.
I want that if I am adding any extra tag to my generated request, response should not be generated and system should throw an error.
NOTE: I am not using any framework.
I want to add username and password to soap header in java by using PasswordText Type and axis2.
Code snippet I use
public static void WSSPasswordAuthentication(org.apache.axis2.client.ServiceClient client, String endPointUrl, String username, String password) throws CSException{
OMFactory omFactory = OMAbstractFactory.getOMFactory();
OMElement omSecurityElement = omFactory.createOMElement(new QName( "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Security", "wsse"), null);
OMElement omusertoken = omFactory.createOMElement(new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "UsernameToken","wsse"), null);
OMElement omuserName = omFactory.createOMElement(new QName("", "Username", "wsse"), null);
omuserName.setText(username);
OMElement omPassword = omFactory.createOMElement(new QName("", "Password", "wsse"), null);
omPassword.addAttribute("Type","http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText",null );
omPassword.setText(password);
omusertoken.addChild(omuserName);
omusertoken.addChild(omPassword);
omSecurityElement.addChild(omusertoken);
client.addHeader(omSecurityElement);
}
And resultant header :
<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"><wsu:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"><Username>erapor</Username><Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">erapor</Password></wsu:UsernameToken></wsse:Security>
But
The header I want : <soapenv:Header><wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"><wsse:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"><wsse:Username>erapor</wsse:Username><wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">erapor</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header>
Otherwise I couldn't use the header
How can I modify?
You can use plain JAXWS if you have an option to resolve this instead of using AXIS2 on the client side. This is generic and easy to add these kind of security headers.
In your JDK 6.0 HOME (This example works only from JDK 6.0 and above)
jdk1.6.0_26\bin\wsimport is an utility available
You can create the stub using the wsimport utility
wsimport -keep -verbose http://localhost:8080/<WebserviceName>/services/<WebserviceName>?wsdl
Create a message handler
MessageHandler.java
package com.secure.client;
import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPHeader;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
public class MessageHandler implements SOAPHandler<SOAPMessageContext>{
#Override
public void close(MessageContext arg0) {
// TODO Auto-generated method stub
}
#Override
public Set getHeaders() {
// TODO Auto-generated method stub
return null;
}
#Override
public boolean handleFault(SOAPMessageContext context) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean handleMessage(SOAPMessageContext soapMessageContext) {
try {
boolean outMessageIndicator = (Boolean) soapMessageContext
.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outMessageIndicator) {
SOAPEnvelope envelope = soapMessageContext.getMessage().getSOAPPart().getEnvelope();
SOAPHeader header = envelope.addHeader();
SOAPElement security = header.addChildElement("Security", "wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
SOAPElement usernameToken = security.addChildElement("UsernameToken", "wsse");
usernameToken.addAttribute(new QName("xmlns:wsu"), "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
SOAPElement username = usernameToken.addChildElement("Username", "wsse");
username.addTextNode("wsuser");
SOAPElement password = usernameToken.addChildElement("Password", "wsse");
password.setAttribute("Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText");
password.addTextNode("wspwd");
}
} catch (Exception ex) {
throw new WebServiceException(ex);
}
return true;
}
}
Create HeaderHandlerResolver.java
package com.secure.client;
import java.util.ArrayList;
import java.util.List;
import javax.xml.ws.handler.Handler;
import javax.xml.ws.handler.HandlerResolver;
import javax.xml.ws.handler.PortInfo;
public class HeaderHandlerResolver implements HandlerResolver {
#SuppressWarnings("unchecked")
public List<Handler> getHandlerChain(PortInfo portInfo) {
List<Handler> handlerChain = new ArrayList<Handler>();
MessageHandler hh = new MessageHandler();
handlerChain.add(hh);
return handlerChain;
}
}
You can create the client code using stub
Client.java
import javax.xml.ws.BindingProvider;
import com.secure.HelloService;
import com.secure.HelloServiceException;
import com.secure.HelloServicePortType;
public class Client {
public static void main(String[] args) {
HelloService service = new HelloService();
service.setHandlerResolver(new HeaderHandlerResolver());
HelloServicePortType port = service.getHelloServiceHttpSoap11Endpoint();
// Use the BindingProvider's context to set the endpoint
BindingProvider bp = (BindingProvider)port;
bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://localhost:8080/<WebserviceName>/services/<WebserviceName>");
System.out.println(port.getVersion());
try {
System.out.println(port.getHello("Zack"));
} catch (HelloServiceException e) {
e.printStackTrace();
}
}
}
i did this tutorial http://netbeans.org/kb/docs/websvc/rest.html to create a restful webservice with my mysql db.
the basic things works fine, but now i want to extend the service functionality. how can i add additional parameters to the GET service ?
i tried this
but as a result I have all cities.
when I add the parameter countryCode links the service becomes
http://localhost:8080/Data/resources/converter.city/?
countryCode=TUR×tamp=1323114935089
This is my code
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package service;
import converter.City;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
/**
*
* #author mehdi
*/
#Stateless
#Path("converter.city")
public class CityFacadeREST extends AbstractFacade<City> {
#PersistenceContext(unitName = "DataPU")
private EntityManager em;
public CityFacadeREST() {
super(City.class);
}
#POST
#Override
#Consumes({"application/xml", "application/json"})
public void create(City entity) {
super.create(entity);
}
#PUT
#Override
#Consumes({"application/xml", "application/json"})
public void edit(City entity) {
super.edit(entity);
}
#DELETE
#Path("{id}")
public void remove(#PathParam("id") Integer id) {
super.remove(super.find(id));
}
#GET
#Path("{id}")
#Produces({"application/xml", "application/json"})
public City find(#PathParam("id") Integer id) {
return super.find(id);
}
#GET
#Override
#Produces({"application/xml", "application/json"})
public List<City> findAll() {
return super.findAll();
}
#GET
#Path("{from}/{to}")
#Produces({"application/xml", "application/json"})
public List<City> findRange(#PathParam("from") Integer from, #PathParam("to") Integer to) {
return super.findRange(new int[]{from, to});
}
#GET
#Path("count")
#Produces("text/plain")
public String countREST() {
return String.valueOf(super.count());
}
#java.lang.Override
protected EntityManager getEntityManager() {
return em;
}
}
You will have to update the annotations in your Java resource class to accept the additional parameter(s). Have you looked at the annotation support for query parameters in JAX-RS?