"could you send some details about the version of Restlet you are using"
-->
Restlet 2.0 Milestone 4 (EE JAVA)
"the code of your server resource?"
-->
Iam attaching the main application code and the code of the jdbc client.
"How are you converting the result set as a json array?"
-->
I am attaching part of the corresponding functions of different classes in one
txt file
package restletserverpackage;
import java.io.IOException;
import java.net.URLDecoder;
import java.sql.SQLException;
import restletdatasourcespackage.JdbcClient;
import restletdatasourcespackage.QueryProcess;
import restletutilitiespackage.IOClass;
import restletconfigurationpackage.Configuration;
import restletwebservicespackage.userProfileService;
import restletutilitiespackage.Parameter;
import restletwebservicespackage.findMyLocationService;
import org.json.JSONException;
import org.restlet.Component;
import org.restlet.data.Form;
import org.restlet.Restlet;
import org.restlet.data.MediaType;
import org.restlet.data.Method;
import org.restlet.data.Protocol;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.Status;
import org.restlet.ext.jetty.HttpServerHelper;
import org.restlet.ext.jetty.JettyServerHelper;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.Server;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* <b>RestletMainWebApplication class is the main class RestletMainWebApplication.</b>
* <p>
* RestletMainWebApplication class provides a Restlet object to handle all the requests on the
* server. Parses these GET or POST requests to know which provider, service,
* input and output format are requested by user. After it the Restlet calls the
* right method and draws the result. <br />
* <br />
* WebService step by step:
* <ul>
* <li>1. Parses XML configuration file</li>
* <li>2. Launches a server with the specified port number</li>
* <li>3. Creates the Restlet object</li>
* <li>4. In case of requests on the server, parses this request to know all
* requested information (provider, service, format, data,...)</li>
* <li>5. Starts the requested service with data and configuration specified in
* the request</li>
* <li>6. Draws the result in the specified format</li>
* </p>
*
*
*/
public class RestletMainWebApplication extends org.restlet.Application {
static final String SET_USER_PROFILE = "setUserProfile";
static final String FIND_MY_LOCATION="findMyLocation";
private String result = null;
private JsonRepresentation jResult;
private MediaType resultFormat;
private Configuration configuration;
private JdbcClient jClient;
private IOClass ioClass;
private boolean error;
/**
* Constructor RestletMainWebApplication
*
* @throws Exception
*/
public RestletMainWebApplication() throws Exception
{
Component component = new Component();
configuration = new Configuration();
configuration.parseXML();
//create embedding jetty server
Server embeddingJettyServer=new Server(component.getContext(),Protocol.HTTP,"192.168.10.1",
Integer.parseInt(configuration.getPort()),component);
//construct and start JettyServerHelper
JettyServerHelper jettyServerHelper=new HttpServerHelper(embeddingJettyServer);
jettyServerHelper.start();
ioClass = new IOClass(configuration);
jClient = new JdbcClient(configuration);
Restlet restlet = new Restlet()
{
@Override
synchronized public void handle(Request request, Response response)
{
error = false;
try
{
configuration.parseURL(request.getResourceRef().getRemainingPart().split("\\?")[0]);
}
catch (Exception e1)
{
Logger.getLogger(RestletMainWebApplication.class.getName()).log(Level.SEVERE,"ERROR: Wrong URL",e1);
error = true;
response.setStatus(Status.SERVER_ERROR_INTERNAL);
}
if (!error)
{
Form form = new Form();
// GET Request
if (request.getMethod() == Method.GET)
{
form = new Form(request.getResourceRef().getRemainingPart().split("\\?")[1]);
}
// POST Request
else if (request.getMethod() == Method.POST && request.isEntityAvailable())
{
form = request.getEntityAsForm();
}
else
{
error = true;
response.setStatus(Status.SERVER_ERROR_INTERNAL);
}
if (!error)
{
int paramNum = configuration.getParameters().size();
try
{
for (int i = 0; i < paramNum; i++)
{
Parameter parameter = null;
if (i < configuration.getParameters().size())
parameter = configuration.getParameters().get(i);
if (form.getNames().contains(parameter.getCodeName()))
{
parameter.setValue(URLDecoder.decode(form.getValues(parameter.getCodeName()).replaceAll("\\+", "\\%2B"), "UTF-8"));
//parameter.setValue(URLDecoder.decode(form.getValues(parameter.getCodeName()).replaceAll("\\space", "\\%20"), "UTF-8"));
parameter.setValue(URLDecoder.decode(form.getValues(parameter.getCodeName()).replaceAll("\\,", "\\%2C"), "UTF-8"));
}
else if (parameter.isRequired())
{
error = true;
response.setStatus(Status.SERVER_ERROR_INTERNAL);
Logger.getLogger(RestletMainWebApplication.class.getName()).log(Level.SEVERE,"ERROR: The parameter: \""+ parameter.getName() + "\" is required",0);
}
}
}
catch (IOException e1)
{
Logger.getLogger(RestletMainWebApplication.class.getName()).log(Level.SEVERE,"ERROR: Reading data failed",0);
response.setStatus(Status.SERVER_ERROR_INTERNAL);
error = true;
}
}
if (!error)
{
QueryProcess qProcess = null;
// Choosing an action -->
if (configuration.getService().getName().equals(SET_USER_PROFILE))
qProcess = new userProfileService (configuration, jClient, ioClass);
else if (configuration.getService().getName().equals(FIND_MY_LOCATION)){
qProcess=new findMyLocationService(configuration, jClient, ioClass);
try {
qProcess.startjson();
} catch (SQLException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
jResult=qProcess.getjsonResult();
}
try
{
qProcess.start();
}
catch (NullPointerException e)
{
Logger.getLogger(RestletMainWebApplication.class.getName()).log(Level.SEVERE,"ERROR: Invalid process"+qProcess.getResult(),e);
response.setStatus(Status.SERVER_ERROR_INTERNAL);
error = true;
}
catch (SQLException e)
{
Logger.getLogger(RestletMainWebApplication.class.getName()).log(Level.SEVERE,"ERROR: Exception \"SQLException\" to draw the result",e);
response.setStatus(Status.SERVER_ERROR_INTERNAL);
error = true;
}
catch (JSONException e)
{
Logger.getLogger(RestletMainWebApplication.class.getName()).log(Level.SEVERE,"ERROR: Exception \"JSONException\" to draw the result",e);
response.setStatus(Status.SERVER_ERROR_INTERNAL);
error = true;
}
result = qProcess.getResult();
if(result==null)
{
response.setStatus(Status.CLIENT_ERROR_REQUESTED_RANGE_NOT_SATISFIABLE);
error = true;
}
// OUTPUT FORMAT -->
/*if (configuration.getFormatOut().getName().equals("html"))
{
resultFormat = MediaType.TEXT_HTML;
}*/
if (configuration.getFormatOut().getName().equals("xml"))
{
resultFormat = MediaType.TEXT_XML;
}
else if (configuration.getFormatOut().getName().equals("json"))
{
//resultFormat = MediaType.TEXT_JAVASCRIPT;
resultFormat = MediaType.APPLICATION_JSON;
//resultFormat = MediaType.ALL;
//resultFormat = MediaType.TEXT_PLAIN;
}
else if (configuration.getFormatOut().getName().equals("document"))
{
resultFormat = MediaType.TEXT_PLAIN;
}
if (!error)
response.setEntity(result, resultFormat);
}
}
}
//}
//if (error)
//{
//response.setStatus(Status.SERVER_ERROR_INTERNAL);
//}
};
component.getDefaultHost().attach("/", restlet);
component.start();
}
/**
* Launches the RestletMainWebApplication service
*
* @throws Exception
*/
public static void main(String[] args) throws Exception
{
new RestletMainWebApplication();
}
}
package restletdatasourcespackage;
import org.antlr.stringtemplate.StringTemplate;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.Client;
import org.restlet.Component;
import org.restlet.Context;
import org.restlet.Server;
import org.restlet.data.Preference;
import org.restlet.data.Request;
import org.restlet.data.Response;
import java.io.File;
import java.io.IOException;
import org.restlet.engine.http.HttpResponse;
import org.restlet.engine.http.HttpServerAdapter;
import org.restlet.engine.http.HttpServerCall;
import org.restlet.ext.json.JsonRepresentation;
import java.sql.ResultSet;
import org.restlet.data.MediaType;
import org.restlet.data.Protocol;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.representation.Variant;
import restletconfigurationpackage.Configuration;
import restletutilitiespackage.IOClass;
import restletutilitiespackage.Service;
import org.restlet.ext.jdbc.JdbcClientHelper;
import org.restlet.ext.jdbc.RowSetRepresentation;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sql.rowset.WebRowSet;
/**
* <b>To access to a database</b>
* <p>
* Provides methods to open, request and close a database connection <br />
* DatabaseConnection object is characterized by the following information:
* <ul>
* <li>A Connection object</li>
* <li>A Statement object</li>
* <li>A boolean to know if the connection is started or not</li>
* <li>An JdbcClientConfiguration object to provide information about "how to
* connect"</li>
* </ul>
* </p>
*/
public class JdbcClient {
private JdbcClientConfiguration jdbcConfiguration;
private Configuration configuration;
private IOClass ioClass;
// private Configuration configuration;
/**
* Constructor JdbcClient
* <p>
* Creates a new DatabaseConnection object with the specified Configuration
* object
* </p>
*
*/
public JdbcClient(Configuration configuration) {
this.configuration = configuration;
ioClass = new IOClass(configuration);
}
/**
* Creates and sends the query using pool connection
*
* @param query
* the SQL query
* @return the result of the request
* @throws JSONException
*/
@SuppressWarnings("unchecked")
public ResultSet performRequest(Service service, String query) {
StringTemplate queryTemplate = new StringTemplate(ioClass
.loadFile(new File(configuration.getUrlXMLTemplateQuery())));
jdbcConfiguration = service.getJdbcClientConfiguration();
// Makes the SQL query
queryTemplate.setAttribute("user", jdbcConfiguration.getUser());
queryTemplate.setAttribute("password", jdbcConfiguration.getPassword());
queryTemplate.setAttribute("query", query);
ResultSet result=null;
Client client = new Client(Protocol.JDBC);
JdbcClientHelper helper = new JdbcClientHelper(client);
try {
Class.forName(jdbcConfiguration.getDriver());
} catch (ClassNotFoundException e) {
Logger.getLogger(JdbcClient.class.getName()).log(Level.SEVERE,
"ERROR: Can not find the driver", e);
}
Representation req = new StringRepresentation(queryTemplate.toString()
.replace("&", "&"), MediaType.TEXT_XML);
Request request=JdbcClientHelper.create(jdbcConfiguration.getURL(),
req);
request.getClientInfo().getAcceptedMediaTypes()
.add(new Preference(MediaType.TEXT_PLAIN));
/*List<Variant> variants = new ArrayList<Variant>();
variants.add(new Variant(MediaType.APPLICATION_JSON));
variants.add(new Variant(MediaType.TEXT_PLAIN));*/
//Response response = client.handle(request);
Response response = new Response(request);
helper.handle(request, response);
WebRowSet rowSet= ((RowSetRepresentation) response.getEntity())
.getWebRowSet();
//if(MediaType.MULTIPART_FORM_DATA.equals(request.getEntity().getMediaType()))
/*RowSetRepresentation rset = new RowSetRepresentation(rowSet);
if (rset.getMediaType()==MediaType.TEXT_JAVASCRIPT){
JSONObject json = null;
try {
//json = new JsonRepresentation(response.getEntity()).toJsonObject();
json = new JsonRepresentation(response.getEntity()).getJsonObject();
} catch (JSONException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
JSONObject jsonResultSet = json.getJSONObject("ResultSet");
result=(ResultSet)jsonResultSet;
//result=(ResultSet)json;
}
else {
*/
try {
//client.put(jdbcConfiguration.getURL(), (JsonRepresentation) rowSet);
result = rowSet;
} catch(Exception e) {
Logger
.getLogger(JdbcClient.class.getName())
.log(
Level.SEVERE,
"ERROR: Can not cast the result from WebRowSet to ResultSet",e);
}
//}
return result;
}
}FROM CLASS "IOClass.java"
/**
* Draws the result of find My Location Web service
*
* @param resultSet
* result of the SQL query
* @return result this query's result in json format
* @throws SQLException
* Error to extract data from ResultSet object *
* @throws JSONException
* Error to make json object
*/
public String findMyLocationJSONResult(ResultSet resultSet)
throws SQLException, JSONException {
String result = "";
JSONObject jsonResult = new JSONObject();
JSONArray jsonArray = new JSONArray();
while (resultSet != null && resultSet.next()) {
resultSet.moveToCurrentRow();
jsonResult.put("poi_name",
resultSet.getString("poi_name"));
jsonResult.put("address_street", resultSet
.getString("address_street"));
jsonResult.put("address_num", resultSet.getString(new
Integer(
"address_num")));
jsonResult.put("address_zip", resultSet.getString(new
Integer(
"address_zip")));
jsonResult.put("phone_num",
resultSet.getString("phone_num"));
byte[] imgBytes = resultSet.getBytes("image");
byte[] encodedImg = Base64.encodeBase64(imgBytes);
String img=Arrays.toString(encodedImg);
jsonResult.put("image",img);
jsonResult.put("image_title",
resultSet.getString("image_title"));
jsonResult.put("description",
resultSet.getString("description"));
jsonResult.put("document", resultSet.getString("doc"));
jsonResult.put("link", resultSet.getString("link"));
jsonResult.put("status", resultSet.getString("status"));
jsonArray.put(jsonResult);
result = jsonArray.toString();
}
return result;
}
//FROM CLASS "findMyLocationService.java"
/*
* Starts the user profile service
*
* @throws SQLException error to send the query to the database
*
* @throws JSONException Error to transform the result in json format
*/
@Override
public Representation startjson() throws SQLException, JSONException {
StringTemplate query = this.ioClass.findMyLocationGetQuery();
// Makes the SQL query
query.setAttribute("positional_accuracy",
positionData.getAccuracy());
query.setAttribute("longitude", positionData.getLon());
query.setAttribute("latitude", positionData.getLat());
query.setAttribute("observer_profileid",configuration.getService().getParameter("userID").getValue());
if
(configuration.getService().getParameter("poiType").getValue() == "null"){
query.setAttribute("poi_type",configuration.getService().getParameter("poiType").getValue());
ResultSet res =
this.jdbcClient.performRequest(configuration
.getService(), query.toString());
result = this.ioClass.findMyLocationJSONResult(res);
return new JsonRepresentation(result);
}
else {
query.setAttribute("poi_type",configuration.getService().getParameter("poiType").getValue());
ResultSet res = this.jdbcClient.performRequest(configuration
.getService(), query.toString());
result = this.ioClass.findMyLocationJSONResult(res);
return new JsonRepresentation(result);
}
}