I have created a custom SQLDataset implementation where it takes a SQL query and returns a List of LinkedHashmap back to the requestcontroller to be displayed in JSP or download in Excel format.
Could you please let me know if the approach is thread safe?
SqlDataset.java
package com.sqle.core;
import com.util.QueryProcessor;
import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class SqlDataset implements Serializable {
private String query;
private QueryProcessor qp;
private ResultSet rsSet;
private List<LinkedHashMap<String, Object>> rsList = new ArrayList<>();
private ArrayList<String> dataHeader = new ArrayList<>();
public SqlDataset() {}
public SqlDataset(String uquery) {
this.query = uquery;
}
private ResultSet getQueryResult() throws Exception {
qp = new QueryProcessor(query);
this.rsSet = qp.getQueryResultSet();
return this.rsSet;
}
public List<LinkedHashMap<String, Object>> getResult() throws Exception {
return this.getValues(this.getQueryResult());
}
public List<LinkedHashMap<String, Object>> getResult(String query) throws Exception {
this.query = query;
return this.getValues(this.getQueryResult());
}
public int getRowCount() {
return this.rsList.size();
}
public ArrayList getHeaders() {
for (LinkedHashMap<String, Object> aRsList : this.rsList) {
for (Map.Entry<String, Object> dh : aRsList.entrySet()) {
if (!this.dataHeader.contains(dh.getKey()))
this.dataHeader.add(dh.getKey());
}
}
return this.dataHeader;
}
private List<LinkedHashMap<String, Object>> getValues(ResultSet rs) throws SQLException {
ResultSetMetaData rmd = rs.getMetaData();
int columns = rmd.getColumnCount();
while (rs.next()) {
LinkedHashMap<String, Object> row = new LinkedHashMap<>(columns);
for (int i = 1; i <= columns; ++i) {
row.put(rmd.getColumnName(i), rs.getObject(i));
}
this.rsList.add(row);
}
return this.rsList;
}
}
Below is the code written in request controller:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String act = request.getParameter("act").toLowerCase();
RequestDispatcher rd = request.getRequestDispatcher("sqleditor.jsp");
try {
if (act.equalsIgnoreCase("exec")) {
String uqry = request.getParameter("isql");
if (!uqry.isEmpty()) {
SqlDataset sd = new SqlDataset(uqry);
rslist = sd.getResult();
if (sd.getRowCount() > 0) {
headRow = sd.getHeaders();
request.setAttribute("resHead", headRow);
request.setAttribute("result", rslist);
} else {
throw new NoDataException("No data found to display");
}
} else {
throw new NoDataException("Please enter a query");
}
rd.forward(request, response);
} else if (act.equalsIgnoreCase("excel")) {
String uqry = request.getParameter("isql");
if (!uqry.isEmpty()) {
try {
SqlDataset sd = new SqlDataset();
rslist = sd.getResult(uqry);
if (sd.getRowCount() > 0) {
headRow = sd.getHeaders();
response.reset();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=\"" + FILENAME + "\"");
ExcelWriter ew = new ExcelWriter();
ew.initExcelfile(rslist, headRow, response.getOutputStream());
} else {
throw new NoDataException("No data found to download");
}
} catch (Exception evar1) {
throw new AppException(evar1.getMessage());
}
} else {
throw new NoDataException("Please enter a query");
}
}
} catch (SQLException evar2) {
request.setAttribute("errormsg", evar2.getMessage());
rd.forward(request, response);
} catch (NullPointerException evar3) {
request.setAttribute("errormsg", evar3.getMessage());
rd.forward(request, response);
} catch (Exception evar4) {
request.setAttribute("errormsg", evar4.getMessage());
rd.forward(request, response);
}
}
Will this code work is multiple users use this application and running different queries successively?
Modified SQLdataset class:
package com.sqle.core;
import com.util.QueryProcessor;
import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class SqlDataset implements Serializable {
private List<LinkedHashMap<String, Object>> rsList = new ArrayList<>();
public SqlDataset() {}
private ResultSet getQueryResult(String query) throws Exception {
QueryProcessor qp = new QueryProcessor(query);
ResultSet rsSet = qp.getQueryResultSet();
return rsSet;
}
public List<LinkedHashMap<String, Object>> getResult(String query) throws Exception {
return this.getValues(this.getQueryResult(query));
}
public ArrayList getHeaders() {
ArrayList<String> dataHeader = new ArrayList<>();
for (LinkedHashMap<String, Object> aRsList : this.rsList) {
for (Map.Entry<String, Object> dh : aRsList.entrySet()) {
if (!dataHeader.contains(dh.getKey()))
dataHeader.add(dh.getKey());
}
}
return dataHeader;
}
private List<LinkedHashMap<String, Object>> getValues(ResultSet rs) throws SQLException {
ResultSetMetaData rmd = rs.getMetaData();
int columns = rmd.getColumnCount();
while (rs.next()) {
LinkedHashMap<String, Object> row = new LinkedHashMap<>(columns);
for (int i = 1; i <= columns; ++i) {
row.put(rmd.getColumnName(i), rs.getObject(i));
}
this.rsList.add(row);
}
return this.rsList;
}
public int getRowCount() {
return this.rsList.size();
}
}
It depends on how you use this class.
With your doPost method in controller it is thread safe for multiple users because you create new SqlDataset object every time.
It means it will be used only by thread which processes a single request.
Your Controller code is re-entrant and thread safe.
BTW in case if you plan to use your SqlDataset as singleton (e.g. Spring bean or such) - it is not thread safe. It has instance variables used in process - it means SqlDataset methods are not re-entrant.
just think about them...
do you really need private QueryProcessor qp; while you create new instance every time in the getQueryResult() method?
do you really need private ArrayList<String> dataHeader = new ArrayList<>();
while you just return it from getHeaders() - why do not just create new ArrayList before for loops inside the method.
...and so on...
If you make everything passed to methods as parameters and return everything created inside methods it will be fully thread safe.
Singletons may have only immutable instance variables (logically almost constants) to keep some settings or properties applicable to any threads which use it.
The SqlDataset.java itself is not thread safe as you have instance variables in it.
However if you only use it in some of your request controller's methods then there will be no problems. This is because a Servlet is not thread safe but the Servlets methods are that.
Related
I wrote little app in Java but it don't serv HTML properly.
Problem occurs when method checkCookies return false. Normally an "else" clause should be executed but this doesn't happen. Some intresting thing - the app is going 3 times from start of handle() method to first condition (counter is increasing). I don't know how to repair it. If i got a cookie with name "Login" or i manually modify method to always return true it's working good.
Main file:
Loginpage.java
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
public class Loginpage {
public static void main (String[] args) throws Exception{
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/form", new Form());
server.setExecutor(null);
server.start();
}
}
Form.java
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.*;
import java.net.HttpCookie;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Form implements HttpHandler {
int counter = 0;
#Override
public void handle(HttpExchange httpExchange) throws IOException {
counter++;
System.out.println(counter);
List<String> cookies = httpExchange.getRequestHeaders().get("Cookie");
HttpCookie cookie;
String response = "<html><body>system</body></html>";
String method = httpExchange.getRequestMethod();
if (checkCookies(cookies)) {
response = "<html><body> Hello! </body></html>";
} else {
if (method.equals("GET")) {
response = "<html><body><form method='post'>" +
"<input type='text' name='username'><br>" +
"<input type='password' name='pass'><br>" +
"<input type='submit' value='login'<br>" +
"</form></body></html>";
} else if (method.equals("POST")) {
InputStreamReader isr = new InputStreamReader(httpExchange.getRequestBody(), "utf-8");
BufferedReader br = new BufferedReader(isr);
String formData = br.readLine();
Map data = parseFormData(formData);
if (checkData(data)) {
cookie = new HttpCookie("Login", String.valueOf(counter + (counter * 12)));
httpExchange.getResponseHeaders().add("Set-Cookie", cookie.toString());
}
}
}
httpExchange.sendResponseHeaders(200, response.length());
OutputStream os = httpExchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
private boolean checkCookies(List<String> cookies) {
boolean isValid = false;
for (String s : cookies) {
System.out.println(s);
if (s.matches("Login.*")) {
isValid = true;
}
}
System.out.println(isValid);
return isValid;
}
private boolean checkData(Map<String, String> data) {
DAO dao = new DAO();
String username = data.get("username");
System.out.println(username);
String password = data.get("pass");
System.out.println(password);
if (dao.checkData(username, password)) {
return true;
} else return false;
}
private static Map<String, String> parseFormData(String formData) throws UnsupportedEncodingException {
Map<String, String> map = new HashMap<>();
String[] pairs = formData.split("&");
for (String pair : pairs) {
String[] keyValue = pair.split("=");
String value = new URLDecoder().decode(keyValue[1], "UTF-8");
map.put(keyValue[0], value);
}
return map;
}
}
UPDATE
I found the cause of my problem. If I send a empty List to the checkCookies() method the program "hangs". Adding the condition
if (cookies == null) return false;
in checkCookies() method solved the problem but I do not know why it was not just return false before fix.
Can anyone explain it?
I'm getting the following exception when attempting to save a simple POJO with a map field.
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to com.orientechnologies.orient.core.db.record.OIdentifiable
Here's my code:
package com.example.test;
import com.orientechnologies.orient.client.remote.OServerAdmin;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.object.db.OObjectDatabaseTx;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class Main {
static class Entity {
private Map map;
public Entity() {
}
public Entity(Map map) {
this.map = map;
}
public Map getMap() {
return map;
}
public void setMap(Map map) {
this.map = map;
}
}
private static void doIt() {
String dbUser = "root";
String dbPass = "root";
String dbUrl = "remote:localhost:2424/sandbox";
try {
OServerAdmin serverAdmin = new OServerAdmin(dbUrl);
serverAdmin.connect(dbUser, dbPass);
if (serverAdmin.existsDatabase("plocal")) {
serverAdmin.dropDatabase("plocal");
}
serverAdmin.createDatabase("document", "plocal");
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
ODatabaseDocumentTx databaseDocumentTx = new ODatabaseDocumentTx(dbUrl);
databaseDocumentTx.open(dbUser, dbPass);
OObjectDatabaseTx objectDatabaseTx = new OObjectDatabaseTx(databaseDocumentTx);
objectDatabaseTx.getEntityManager().registerEntityClass(Entity.class);
Map map = new HashMap();
map.put("a", "a");
Entity entity = objectDatabaseTx.save(new Entity(map)); //<-- EXCEPTION THROWN HERE!!!
}
public static void main(String[] args) {
doIt();
}
}
Full stack trace:
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to com.orientechnologies.orient.core.db.record.OIdentifiable
at com.orientechnologies.orient.core.db.record.ORecordLazyMap.put(ORecordLazyMap.java:41)
at com.orientechnologies.orient.object.enhancement.OObjectEntitySerializer.multiValueToStream(OObjectEntitySerializer.java:1398)
at com.orientechnologies.orient.object.enhancement.OObjectEntitySerializer.typeToStream(OObjectEntitySerializer.java:805)
at com.orientechnologies.orient.object.enhancement.OObjectEntitySerializer.toStream(OObjectEntitySerializer.java:1216)
at com.orientechnologies.orient.object.enhancement.OObjectEntitySerializer.serializeObject(OObjectEntitySerializer.java:144)
at com.orientechnologies.orient.object.db.OObjectDatabaseTx.save(OObjectDatabaseTx.java:454)
at com.orientechnologies.orient.object.db.OObjectDatabaseTx.save(OObjectDatabaseTx.java:399)
at com.example.test.Main.doIt(Main.java:56)
at com.example.test.Main.main(Main.java:60)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Any guidance as to what is going on would greatly be appreciated!
I have used this code and it works
import com.orientechnologies.orient.client.remote.OServerAdmin;
import com.orientechnologies.orient.object.db.OObjectDatabaseTx;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class Main {
static class Entity {
private Map<String,Object> map;
public Entity() {
this.map=null;
}
public Entity(Map<String,Object> map) {
this.map = map;
}
public Map<String,Object> getMap() {
return map;
}
public void setMap(Map<String,Object> map) {
this.map = map;
}
}
private static void doIt() {
String dbUser = "root";
String dbPass = "root";
String dbUrl = "remote:localhost:2424/sandbox";
try {
OServerAdmin serverAdmin = new OServerAdmin(dbUrl);
serverAdmin.connect(dbUser, dbPass);
if (serverAdmin.existsDatabase("plocal")) {
serverAdmin.dropDatabase("plocal");
System.out.println("Db cancellalto");
}
//serverAdmin.createDatabase("document", "plocal");
serverAdmin.createDatabase("sandbox", "object", "plocal");
System.out.println("Db creato");
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
OObjectDatabaseTx objectDatabaseTx = new OObjectDatabaseTx(dbUrl);
objectDatabaseTx.open(dbUser,dbPass);
objectDatabaseTx.getEntityManager().registerEntityClass(Entity.class);
Entity e = objectDatabaseTx.newInstance(Entity.class);
Map<String, Object> map = new HashMap<String, Object>();
map.put("a", "a");
e.setMap(map);
// Save the entity
e = objectDatabaseTx.save(e);
}
public static void main(String[] args) {
doIt();
}
}
Hope it helps
After some digging around I'm going to answer my own question. I can make my code work by explicitly declaring the Entity.map field as OType.EMBEDDEDMAP. See below:
...
objectDatabaseTx.getEntityManager().registerEntityClass(Entity.class);
OClass oClass = objectDatabaseTx.getMetadata().getSchema().getClass(Entity.class);
oClass.createProperty("map", OType.EMBEDDEDMAP);
...
However, I ultimately need my map to contain any value (ie: Map<String, Object>). But I can't because there's an open bug for that ...
https://github.com/orientechnologies/orientdb/issues/3063
So that's it folks...
I've recently starting working on a java webapp (JSP / Servlet) that was developed by the internal developer of a company.
This app randomly doesn't return data, and inspecting the log I found some NullPointerExceptions related to the classes' member variable which holds the database connection. Following the stack trace it seems that a second thread closes the connection after it ended its task leaving the first thread without a connection.
By the needs of the company the app uses different databases, one which rules appdata, and others which contain data the app has to retrieve. So every class attached to the main servlet may connect to one or more databases depending on the task it has to accomplish.
I'm not familiar with JavaEE but giving a look at the database connection class, I see nothing which protect threads from conflicting each other.
Which is the correct way to handle such connections?
This is the code of the Database handler:
package it.metmi.mmasgis.utils;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class DBManager
{
private String szDatabase;
private String szUsername;
private String szPassword;
private String szError;
private Connection db;
private boolean bConnected;
private Logger logger;
public DBManager(String szDBName)
{
this(szDBName, "", "");
}
public DBManager(String szDBName, String szName, String szPass)
{
szDatabase = szDBName;
szUsername = szName;
szPassword = szPass;
bConnected = false;
szError = "";
logger = LogManager.getFormatterLogger(DBManager.class.getName());
}
public boolean connect()
{
logger.entry();
try {
Class.forName("com.mysql.jdbc.Driver");
if(!szDatabase.isEmpty())
{
String szCon = "jdbc:mysql://localhost/" + szDatabase;
if(!szUsername.isEmpty())
{
szCon += "?user=" + szUsername;
if(!szPassword.isEmpty())
szCon += "&password=" + szPassword;
}
db = DriverManager.getConnection(szCon);
bConnected = true;
} else {
logger.error("No database name!!");
System.exit(0);
}
} catch(SQLException | ClassNotFoundException e) {
szError = e.getMessage();
e.printStackTrace();
logger.error("Can't connect: %s", e);
}
return logger.exit(bConnected);
}
public void disconnect()
{
logger.entry();
try {
db.close();
bConnected = false;
} catch(SQLException e) {
e.printStackTrace();
logger.error("Can't disconnect: %s", e);
}
logger.exit();
}
public boolean isConnected()
{
return bConnected;
}
public String getError()
{
return szError;
}
public ArrayList<HashMap<String,String>> query(String szQuery)
{
logger.entry(szQuery);
ArrayList<HashMap<String,String>> aResults = new ArrayList<HashMap<String,String>>();
int iCols = 0;
try {
Statement stmt = db.createStatement();
logger.info("Query: %s", szQuery);
ResultSet rs = stmt.executeQuery(szQuery);
ResultSetMetaData rsmd = rs.getMetaData();
iCols = rsmd.getColumnCount();
while(rs.next())
{
HashMap<String,String> pv = new HashMap<String,String>();
for(int i = 0; i < iCols; i++)
{
String szCol = rsmd.getColumnLabel(i + 1);
String szVal = rs.getString(i + 1);
pv.put(szCol, szVal);
}
aResults.add(pv);
}
rs.close();
stmt.close();
} catch(SQLException e) {
e.printStackTrace();
szError = e.getMessage();
logger.error("Error executing query: %s", e);
}
return logger.exit(aResults);
}
public boolean update(String szQuery)
{
logger.entry(szQuery);
boolean bResult = false;
try {
Statement stmt = db.createStatement();
logger.info("Query: %s", szQuery);
stmt.executeUpdate(szQuery);
bResult = true;
stmt.close();
} catch(SQLException e) {
e.printStackTrace();
szError = e.getMessage();
bResult = false;
logger.error("Error executing query: %s", e);
}
return logger.exit(bResult);
}
}
The class Task which all the servlet classes are based on, is a simple abstract class:
package it.metmi.mmasgis.servlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public abstract class Task
{
public abstract void doTask(HttpServletRequest request, HttpServletResponse response);
}
The class which throws NullPointerExceptions it this one, during the invocation of db.disconnect(). This class is called rapidly via AJAX 4 or 5 times from the interface written in JS.
package it.metmi.mmasgis.servlet.params;
import it.metmi.mmasgis.servlet.Task;
import it.metmi.mmasgis.utils.Const;
import it.metmi.mmasgis.utils.DBManager;
import it.metmi.mmasgis.utils.Query;
import it.metmi.mmasgis.utils.Utility;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ClassType extends Task
{
private DBManager db = null;
private Logger logger = LogManager.getFormatterLogger(ClassType.class.getName());
#Override
public void doTask(HttpServletRequest request, HttpServletResponse response)
{
logger.entry(request, response);
String szCensimento = Utility.getParameter(request, "censimento");
String szCategoria = Utility.getParameter(request, "category");
ArrayList<HashMap<String,String>> aClasses = new ArrayList<HashMap<String,String>>();
PrintWriter out = null;
logger.debug("Census: %s", szCensimento);
logger.debug("Category: %s", szCategoria);
db = new DBManager(szCensimento, Const.DB_USER, Const.DB_PASS);
if(db.connect())
{
String szQuery = String.format(Query.classes, szCategoria, szCategoria);
aClasses = db.query(szQuery);
db.disconnect();
}
try {
out = response.getWriter();
jsonEncode(aClasses, out);
} catch(IOException e) {
e.printStackTrace();
logger.error("Failed to encode JSON: %s", e);
}
logger.exit();
}
private void jsonEncode(ArrayList<HashMap<String,String>> aData, PrintWriter out)
{
HashMap<String,Object> result = new HashMap<String,Object>();
result.put("results", aData);
result.put("success", true);
Gson gson = new GsonBuilder().create();
gson.toJson(result, out);
}
}
If the webapp would use only one database, it could be rewritten as a Singleton, but in this way I have no idea on how to handle different connections for different databases.
How can avoid these exceptions?
The problem was that the connection object was declared as member.
Moving the variable inside the methods resolved.
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 :)
this is my nodefinder.java file
package com.acme.web.action.executer;
import java.sql.ResultSet;
import java.util.Map;
import org.alfresco.web.bean.repository.Node;
import org.alfresco.web.bean.repository.Repository;
import org.alfresco.web.ui.common.component.UIActionLink;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import org.alfresco.service.cmr.model.FileFolderService;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.search.SearchParameters;
import org.alfresco.service.cmr.search.SearchService;
public class NodeFinder {
// private static final String = null;
SearchParameters sp = new SearchParameters();
private NodeService nodeService;
private FileFolderService fileFolderService;
//geting the filefolder service
public FileFolderService getFileFolderService() {
return fileFolderService;
}
// setting the file folder service
public void setFileFolderService(FileFolderService fileFolderService) {
this.fileFolderService = fileFolderService;
}
// getting the node servise
public NodeService getNodeService() {
return nodeService;
}
// setting the node server
public void setNodeService(NodeService nodeService) {
this.nodeService = nodeService;
}
public void execute(ActionEvent event) {
ResultSet resultSet_s = null;
UIActionLink comp = (UIActionLink) event.getComponent();
Map<String, String> params = comp.getParameterMap();
String id = params.get("id1");
System.out.println("1");
NodeRef actionedUponNodeRef = new NodeRef(Repository.getStoreRef(), id);
String qry_s = "#cm\\:name:train";
System.out.println("2");
SearchParameters sp_s = new SearchParameters();
System.out.println("3");
sp_s.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
sp_s.setLanguage(SearchService.LANGUAGE_LUCENE);
sp_s.setQuery(qry_s);
System.out.println( "4" );
Node node = new Node(actionedUponNodeRef);
System.out.println("5");
resultSet_s = (ResultSet) Repository.getServiceRegistry(
FacesContext.getCurrentInstance()).getSearchService().query(
sp_s);
System.out.println("5.1");
if (resultSet_s != null) {
System.out.println("6");
System.out.println("Node value is::::" + node.getName());
}
}
}
Because you imported java.sql.ResultSet instead of an alfresco class/interface compatible to org.alfresco.repo.search.impl.lucene.PagingLuceneResultSet
Look at that line ...(ResultSet) Repository.getServiceRegistry(..., then look at your exception and finally at your imports. There you will see that ResultSet is actually java.sql.ResultSet (which is indicated by your ClassCastException's message).
If you then look at the super classes or interfaces of org.alfresco.repo.search.impl.lucene.PagingLuceneResultSet I'd say you won't find any java.sql.ResultSet. That's why you get that exception.