I am creating my first SOAP Service and I am getting the error Not a valid Service. Could someone please help me out? I am creating a project for a imaginary belt store. SO my service is supposed to get all the products that are not shipped yet. For now i am just sending it in an array. Once the service starts working i will modify it in a better way.
Below is my error
Exception in thread "main" javax.xml.ws.WebServiceException: {http://service.itmd.iit/}OrdersImplService is not a valid service. Valid services are: {http://util.itmd.iit/}OrdersImplService
at com.sun.xml.internal.ws.client.WSServiceDelegate.<init>(WSServiceDelegate.java:200)
at com.sun.xml.internal.ws.client.WSServiceDelegate.<init>(WSServiceDelegate.java:145)
at com.sun.xml.internal.ws.spi.ProviderImpl.createServiceDelegate(ProviderImpl.java:93)
at javax.xml.ws.Service.<init>(Service.java:56)
at javax.xml.ws.Service.create(Service.java:680)
at iit.itmd.client.Client.main(Client.java:19)
Below is my Interface
package iit.itmd.service;
import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
import javax.xml.bind.annotation.XmlRootElement;
#WebService
#SOAPBinding(style=Style.RPC)
#XmlRootElement
public interface Orders {
#WebMethod String[] getNotFulfilled();
}
My Order Implementation class which implements the above interface is given below
package iit.itmd.util;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import iit.itmd.service.Orders;
#XmlType
#WebService(endpointInterface="iit.itmd.service.Orders")
public class OrdersImpl implements Orders{
#Override
#XmlElement
public String[] getNotFulfilled() {
// TODO Auto-generated method stub
Connection conn=null;
Statement statement=null;
int i=0;
String selecttableSql="select id,customer_id from orders where status<>'SHIPPED'";
String[] result=null;
try{
DBConn con=new DBConn();
conn=con.getConnection();
statement = conn.createStatement();
ResultSet rs = statement.executeQuery(selecttableSql);
System.out.println(rs.getFetchSize());
while (rs.next()) {
String orderId = rs.getString("ID");
String customerId = rs.getString("CUSTOMER_ID");
result[i]=orderId;
result[i]= customerId;
System.out.println("userid : " + orderId);
System.out.println("username : " + orderId);
}}
catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return result;
}
}
I created a client to call the SOAP Service. The code for the client is below
package iit.itmd.client;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import iit.itmd.domain.*;
import iit.itmd.service.Orders;
public class Client {
public static void main(String[] args) throws MalformedURLException {
URL url = new URL("http://localhost:9999/BeltStore/getnotshipped");
//1st argument service URI, refer to wsdl document above
//2nd argument is service name, refer to wsdl document above
QName qname = new QName("http://service.itmd.iit/", "OrdersImplService");
Service service = Service.create(url, qname);
Orders order = service.getPort(Orders.class);
System.out.println(order.getNotFulfilled());
}
}
Could someone please let me know what i am doing wrong? Thanks.
In your client code you specify a namespace for the service, which is good practice, but I don't see that namespace back in your service code. Your service has to define a namespace and this should correspond with the namespace your client uses for specifying the webservice method. E.g.
#WebService(targetNamespace = "http://service.itmd.iit/")
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am unable to get the values from the remote method 'new DatabaseSelection2().siti.getDatabasesName()' to fill the array databasesNames in 'DatabaseSelection2' class. I make bold the issue line which create the exception. I am unable to solve it someone help me I am posting SchoolInterface, SchoolInterfaceImpl, SchoolServer, and its DatabaseSelection2. I have tried every mean of resource but do not find any answer
class DatabaseSelection2:
package schoolclient;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import schoolserver.SchoolInterface;
public class DatabaseSelection2 {
SchoolInterface siti = null;
public static void main (String[] args){
try {
new DatabaseSelection2().siti =
(SchoolInterface) Naming.lookup("SchoolServer");
}
catch (Exception e) {
e.printStackTrace();
}
**for(Object o : getDatabaseTable())**//line 23
System.out.println(o);
}
private static Object[] getDatabaseTable() {
Object[] databasesNames = new Object[10];
int i = 0;
try {
**for(Object o : new DatabaseSelection2().siti.getDatabasesName())** //line 32
databasesNames[i++] = o;
}
catch (SQLException e) {
JOptionPane.showMessageDialog(null, "SQLException in read"
+ "Databases\n" + e, "Error", JOptionPane.ERROR_MESSAGE);
}
catch (RemoteException e) {
JOptionPane.showMessageDialog(null, "RemoteException in read Databases\n" + e,
"Error", JOptionPane.ERROR_MESSAGE);
}
return databasesNames;
}
}
Exception in thread "main" java.lang.NullPointerException
at schoolclient.DatabaseSelection2.getDatabaseTable(DatabaseSelection2.java:32)
at schoolclient.DatabaseSelection2.main(DatabaseSelection2.java:23)
interface SchoolInterface
package schoolserver;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public interface SchoolInterface extends Remote {
public ArrayList getDatabasesName() throws RemoteException, SQLException;
}
class SchoolServer
package schoolserver;
import java.rmi.Naming;
public class SchoolServer {
public static void main (String[] args) {
try {
SchoolInterfaceImpl sii = new SchoolInterfaceImpl();
Naming.rebind("SchoolServer", sii);
}
catch (Exception e) {
}
}
}
Class SchoolInterfaceImpl :
package schoolserver;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.sql.Connection;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
public class SchoolInterfaceImpl
extends UnicastRemoteObject implements SchoolInterface {
protected SchoolInterfaceImpl() throws RemoteException {
super();
// TODO Auto-generated constructor stub
}
public ArrayList getDatabasesName()
throws RemoteException, SQLException {
ArrayList databasesName = null;
Connection connection = null;
ResultSet resultSet = null;
try {
connection = DriverManager.getConnection(
"jdbc:sqlserver://localhost\\FAISAL:1433;"
+ "username=fas;password=24071982");
resultSet = connection.getMetaData().getCatalogs();
while(resultSet.next()){
databasesName.add(resultSet.getObject(1));
}
}
catch (SQLException e) {
throw new SQLException();
}
finally{
try {
if(connection != null)
connection.close();
}
catch(SQLException e) {
throw new SQLException();
}
try {
if(resultSet != null)
resultSet.close();
}
catch(SQLException e) {
throw new SQLException();
}
}
return databasesName;
}
}
private static Object[] getDatabaseTable() {
Object[] databasesNames = null;
int i = 0;
try {
for(Object o : new DatabaseSelection2().siti.getDatabasesName())
databasesNames[i] = o;
}
here databasesNames is null and you are doing operation on null , that is why you are getting null pointer exception
This question already has answers here:
Java URL encoding of query string parameters
(11 answers)
Closed 5 years ago.
I wrote the netbeans ta web service project. But when I write "50% discount" to the value of a parameter I use with http post, it looks like "P discount" to me. How can I fix this problem?
192.168.0.222:7001/Project/KonuEkle?uye=test&&baslik=%50 discount&&mesaj=test&&kategori=123&&link=null
import com.mrkcn.servlet.Classlar.ConnectInfo;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONException;
import org.json.JSONObject;
public class KonuEkleServlet extends HttpServlet {
public String kullaniciadi;
public String baslik;
public String mesaj;
public String kategori;
public String altKategori;
public String link;
public Connection con;
boolean action = false;
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
ConnectInfo conServlet= new ConnectInfo();
con=null;
con=conServlet.baglanti();
PreparedStatement pstmt=null;
ResultSet rs=null;
Boolean konuEkleKontrol = false;
PrintWriter out = resp.getWriter();
JSONObject j = new JSONObject();
ArrayList<String> konuEkleList = new ArrayList<String>(100);
kullaniciadi = req.getParameter("uye");
baslik = req.getParameter("baslik");
mesaj = req.getParameter("mesaj");
kategori = req.getParameter("kategori");
link = req.getParameter("link");
j.put("mesaj1",baslik);
//altKategori = req.getParameter("altkategori");
//kategoriBilgiGetir(kategori , altKategori);
String konuEkle="insert into konular(uye,baslik,mesaj,kategori,tarih,edittarih,aktif,indirimpuani,altkategori,link) values (?,?,?,?,GETDATE(),NULL,1,0,0,?)";
pstmt=con.prepareStatement(konuEkle);
pstmt.setString(1, kullaniciadi);
pstmt.setString(2, baslik);
pstmt.setString(3, mesaj);
pstmt.setString(4, kategori);
pstmt.setString(5, link);
int count = pstmt.executeUpdate();
action = (count > 0);
if (action)
{
j.put("mesaj","basarili");
konuEkleList.add(j.toString());
out.write(konuEkleList.toString());
out.close();
}
else
{
j.put("mesaj","basarisiz");
konuEkleList.add(j.toString());
out.write(konuEkleList.toString());
out.close();
}
} catch (SQLException ex) {
Logger.getLogger(KonuEkleServlet.class.getName()).log(Level.SEVERE, null, ex);
} catch (JSONException ex) {
Logger.getLogger(KonuEkleServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
URLs are treated as encoded when received by the servlet. The % symbol followed by a 2 hex digits is the ASCII code of the character so %50 represents the letter P. To represent the % symbol you have to send %25 to represent the % symbol.
Your URL should be:
192.168.0.222:7001/Project/KonuEkle?uye=test&&baslik=%2550 discount&&mesaj=test&&kategori=123&&link=null
Here you can find a list of the character codes:
https://www.w3schools.com/tags/ref_urlencode.asp
I have created a RESTFUL webservice, witch returns a json, but at this time i only consult and show a simple select * , i need to create a complete CRUD solution, if anyone have some samples to share, i'll appreciate.
Best Regards to all
My code until now are:
DAO - Access.java
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import dto.Usuarios;
public class Access
{
public ArrayList<Usuarios> getUsuarios(Connection con) throws SQLException
{
ArrayList<Usuarios> usuariosList = new ArrayList<Usuarios>();
PreparedStatement stmt = con.prepareStatement("SELECT * FROM usuarios");
ResultSet rs = stmt.executeQuery();
try
{
while(rs.next())
{
Usuarios usuariosObj = new Usuarios();
usuariosObj.setUsr_id(rs.getInt("usr_id"));
usuariosObj.setUsr_login(rs.getString("usr_login"));
usuariosObj.setUsr_pwd(rs.getString("usr_pwd"));
usuariosList.add(usuariosObj);
}
} catch (SQLException e)
{
e.printStackTrace();
}
return usuariosList;
}
}
DTO - Usuarios.java
package dto;
public class Usuarios
{
private int usr_id;
private String usr_login;
private String usr_pwd;
public Usuarios()
{
}
public Usuarios(int usr_id, String usr_login, String usr_pwd)
{
super();
this.usr_id = usr_id;
this.usr_login = usr_login;
this.usr_pwd = usr_pwd;
}
public int getUsr_id()
{
return usr_id;
}
public void setUsr_id(int usr_id)
{
this.usr_id = usr_id;
}
public String getUsr_login()
{
return usr_login;
}
public void setUsr_login(String usr_login)
{
this.usr_login = usr_login;
}
public String getUsr_pwd()
{
return usr_pwd;
}
public void setUsr_pwd(String usr_pwd)
{
this.usr_pwd = usr_pwd;
}
#Override
public String toString()
{
return "[ {usr_id=" + usr_id + ", usr_login=" + usr_login + ", usr_pwd=" + usr_pwd + "} ]";
}
}
Model - AccessManager.java
package model;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import dao.Access;
import dao.Database;
import dto.Usuarios;
public class AccessManager
{
public ArrayList<Usuarios> getUsuarios() throws Exception
{
ArrayList<Usuarios> usuariosList = new ArrayList<Usuarios>();
Database db = new Database();
Connection con = db.getConnection();
Access access = new Access();
usuariosList = access.getUsuarios(con);
return usuariosList;
}
}
WebService - UsuariosService.java
package webService;
import java.util.ArrayList;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import com.google.gson.Gson;
import model.AccessManager;
import dto.Usuarios;
#Path("/UsuariosService")
public class UsuariosService
{
#GET
#Path("/usuarios")
#Produces("application/json")
public String usuarios()
{
String usuarios = null;
ArrayList<Usuarios> usuariosList = new ArrayList<Usuarios>();
try
{
usuariosList = new AccessManager().getUsuarios();
Gson gson = new Gson();
//usuarios = gson.toJson(usuariosList);
usuarios = "{\"usuarios\" :" + gson.toJson(usuariosList) + "}";
} catch (Exception e)
{
e.printStackTrace();
}
return usuarios;
}
}
Usually you should ask a specific trouble you have instead of ask for samples. It looks like you have a structured code and all you need is implement all operations exposing as a service.
In case you need a sample, there quite a lot of resources on the web. Something like this: https://code.google.com/p/javaee6-crud-example/
I'll try give you some quick tips below:
WebService - UsuariosService.java
#POST
#Path("/usuarios")
public Response save(Usuario user) {
try {
manager= new AccessManager();
manager.save(user);
return Response.ok("User has been created.").build();
} catch (Exception e) {
e.printStackTrace();
}
return usuarios;
}
#DELETE
#Path("/usuarios/{id}")
public Response delete(#PathParam("id") String id) {
try {
manager= new AccessManager();
manager.delete(id);
return Response.ok("User has been deleted.").build();
} catch (Exception e) {
e.printStackTrace();
}
return usuarios;
}
#PUT
#Path("/usuarios/{id}")
public Response delete(#PathParam("id") String id, Usuario user) {
try {
manager= new AccessManager();
manager.update(id, user);
return Response.ok("User has been updated.").build();
} catch (Exception e) {
e.printStackTrace();
}
return usuarios;
}
If you donĀ“t understand the usage of PUT, DELETE, POST and so on, I recommend you to read HTTP Method Tutorial. There is several discussion regarding this but you might skip it for a while.
I think you might get an idea from here. Your DAO needs to implement methods to perform CRUD interface as well. The link I've added has a very simple sample that might help as well. You might also check this JPA link.
Not sure whether info above helped but I think it is a start since you have to code it in order to understand more about it :)
I'm trying to use the #PathParam using Jersey, but it always sees it as null.
Here's the method:
The url is http://localhost:8080/GiftRegistryAPI/api/v2/inventory/david with /v2/inventory being at the class level
package com.omar.rest.inventory;
import javax.websocket.server.PathParam;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import org.codehaus.jettison.json.JSONArray;
import com.omar.rest.util.*;
#Path("/v2/inventory")
public class V2_Inventory {
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response returnHostRegistries(#QueryParam("hostId") int hostId) throws Exception {
String returnString = null;
JSONArray jsonArray = new JSONArray();
try {
// A host ID of 0 indicates a null parameter, there will never be a host with an ID of 0
if (hostId == 0) {
return Response.status(400).entity("Error: please provide a valid host ID for this search").build();
}
Schema dao = new Schema();
jsonArray = dao.qryReturnHostRegistries(hostId);
returnString = jsonArray.toString();
}
catch (Exception e) {
e.printStackTrace();
return Response.status(500).entity("Server was not able to process your request").build();
}
System.out.println(returnString);
return Response.ok(returnString).build();
}
#Path("/{firstName}")
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response returnSearchedRegistries(#PathParam("firstName") String name) throws Exception{
String returnString = null;
JSONArray jsonArray = new JSONArray();
System.out.println("Name: " +name);
try {
Schema dao = new Schema();
jsonArray = dao.qryReturnHostRegistries(name);
returnString = jsonArray.toString();
}
catch (Exception e) {
e.printStackTrace();
return Response.status(500).entity("Server was not able to process your request").build();
}
System.out.println(returnString);
return Response.ok(returnString).build();
}
}
The name parameter when debugged is always null, and I can't find any way at all of getting it to recognise I've entered anything in.
Any ideas what might be going wrong?
It was my import statement
import javax.websocket.server.PathParam;
should have been
import javax.ws.rs.PathParam;
In this error, most of the time the issue is wrong import. Just make sure you have import javax.ws.rs.PathParam;
I am using the below code but it is not able to search the journal article/web content in liferay 6.1
package com.abp.portlets;
import java.io.IOException;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import com.liferay.portal.kernel.search.BooleanClauseOccur;
import com.liferay.portal.kernel.search.BooleanQuery;
import com.liferay.portal.kernel.search.BooleanQueryFactoryUtil;
import com.liferay.portal.kernel.search.Field;
import com.liferay.portal.kernel.search.Hits;
import com.liferay.portal.kernel.search.ParseException;
import com.liferay.portal.kernel.search.SearchContext;
import com.liferay.portal.kernel.search.SearchEngineUtil;
import com.liferay.portal.kernel.search.SearchException;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.util.bridges.mvc.MVCPortlet;
/**
* Portlet implementation class Search
*/
public class Search extends MVCPortlet {
public void doView(RenderRequest renderRequest, RenderResponse renderResponse)throws IOException, PortletException
{
ThemeDisplay themeDisplay = (ThemeDisplay)
renderRequest.getAttribute(WebKeys.THEME_DISPLAY);
SearchContext searchContext = new SearchContext();
searchContext.setSearchEngineId(SearchEngineUtil.SYSTEM_ENGINE_ID);
BooleanQuery contextQuery = BooleanQueryFactoryUtil.create(searchContext);
contextQuery.addRequiredTerm(Field.COMPANY_ID, themeDisplay.getCompanyId());
contextQuery.addRequiredTerm(Field.GROUP_ID, themeDisplay.getScopeGroupId());
BooleanQuery fullQuery = BooleanQueryFactoryUtil.create(searchContext);
String keywords = "mridul test";
BooleanQuery searchQuery = BooleanQueryFactoryUtil.create(searchContext);
if (Validator.isNotNull(keywords)) {
keywords = keywords.trim();
try {
searchQuery.addTerm(Field.TITLE, keywords,true);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// BooleanQuery fullQuery = BooleanQueryFactoryUtil.create(searchContext);
//fullQuery.add(contextQuery, BooleanClauseOccur.MUST);
// if (searchQuery.clauses().size() > 0) {
// fullQuery.add(searchQuery, BooleanClauseOccur.MUST);
// }
System.out.println("fullQuery===============>>"+fullQuery);
try {
fullQuery.add(searchQuery, BooleanClauseOccur.MUST);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Hits hits = SearchEngineUtil.search(searchContext, fullQuery);
for(int i=0;i<hits.getLength();i++)
{
System.out.println(hits.snippet(i).toString());
}
} catch (SearchException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The output I am getting is...
fullQuery===============>>+(+((title:mridul title:test)))
Please help..
Lucene uses fields to index data.
searchQuery.addTerm(**Field.CONTENT**, keywords,true);
Or
searchQuery.addTerms(new String[]{Field.TITLE,Field.DESCRIPTION,Field.CONTENT}, keywords, true)
It looks like you are searching for the exact phrase "mridul test". I think you probably want to search for "mridul" and "test". If so, give this a spin:
String[] terms = keywords.split(" ");
for(String term : terms){
searchQuery.addTerm(Field.TITLE, term,true);
}