org.datanucleus.rest.RestServlet Maven / Gradle / Ivy
/**********************************************************************
Copyright (c) 2009 Erik Bengtson and others. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
...
**********************************************************************/
package org.datanucleus.rest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URLDecoder;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import javax.jdo.JDOException;
import javax.jdo.JDOFatalUserException;
import javax.jdo.JDOHelper;
import javax.jdo.JDONullIdentityException;
import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.jdo.spi.Detachable;
import javax.jdo.spi.JDOImplHelper;
import javax.jdo.spi.PersistenceCapable;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.datanucleus.ClassLoaderResolver;
import org.datanucleus.OMFContext;
import org.datanucleus.ObjectManager;
import org.datanucleus.StateManager;
import org.datanucleus.exceptions.ClassNotResolvedException;
import org.datanucleus.jdo.JDOPersistenceManager;
import org.datanucleus.jdo.JDOPersistenceManagerFactory;
import org.datanucleus.metadata.AbstractClassMetaData;
import org.datanucleus.metadata.IdentityType;
import org.datanucleus.state.JDOStateManagerImpl;
import org.datanucleus.store.fieldmanager.FieldManager;
import org.datanucleus.util.ClassUtils;
import org.datanucleus.util.NucleusLogger;
import org.datanucleus.util.TypeConversionHelper;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import flexjson.JSONSerializer;
/**
* This servlet exposes persistent class via RESTful HTTP requests. HTTP GET (retrieve/query), POST (update/insert), PUT
* (update/insert), DELETE
*/
public class RestServlet extends HttpServlet
{
PersistenceManagerFactory pmf;
public static final NucleusLogger LOGGER_REST = NucleusLogger.getLoggerInstance("DataNucleus.REST");
public void init(ServletConfig config) throws ServletException
{
System.setProperty("appengine.orm.disable.duplicate.pmf.exception", "true");
String factory = config.getInitParameter("persistence-context");
try
{
pmf = JDOHelper.getPersistenceManagerFactory(factory);
}
catch(JDOException ex)
{
LOGGER_REST.error(ex.getMessage(),ex);
new ServletException(ex);
}
super.init(config);
}
/**
* Get the class name
* @param req
* @return
*/
private String getClassName(HttpServletRequest req)
{
String path = req.getRequestURI().substring(req.getContextPath().length() + req.getServletPath().length());
StringTokenizer tokenizer = new StringTokenizer(path, "/");
return tokenizer.nextToken();
}
/**
* get the id (second path segment)
* @param req
* @return
*/
private Object getId(HttpServletRequest req)
{
OMFContext ctx = ((JDOPersistenceManagerFactory) pmf).getOMFContext();
ClassLoaderResolver clr = ctx.getClassLoaderResolver(RestServlet.class.getClassLoader());
String path = req.getRequestURI().substring(req.getContextPath().length() + req.getServletPath().length());
StringTokenizer tokenizer = new StringTokenizer(path, "/");
String className = tokenizer.nextToken(); // ignore class name
String id = null;
if (tokenizer.hasMoreTokens())
{
id = tokenizer.nextToken();
if( id==null)
{
return null;
}
AbstractClassMetaData cmd = ctx.getMetaDataManager().getMetaDataForClass(className, clr);
if (cmd!=null && cmd.usesSingleFieldIdentityClass())
{
Object value = TypeConversionHelper.convertTo(id, cmd.getMetaDataForMemberAtRelativePosition(cmd.getPKMemberPositions()[0]).getType());
return getObject(value, clr.classForName(cmd.getObjectidClass()), clr.classForName(cmd.getFullClassName()), cmd);
}
}
try
{
if(id==null && req.getContentLength()>0)
{
char[] buffer = new char[req.getContentLength()];
req.getReader().read(buffer);
id = new String(buffer);
}
}
catch (IOException e)
{
throw new RuntimeException(e);
}
if (id==null)
{
return null;
}
try
{
id = URLDecoder.decode(id,"UTF-8");
//if it's a JSONObject
JSONObject jsonobj = new JSONObject(id);
return getObject(jsonobj,clr.classForName(jsonobj.getString("class")));
}
catch(JSONException ex)
{
//not a JSON sintax
}
catch (UnsupportedEncodingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return id;
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
OMFContext ctx = ((JDOPersistenceManagerFactory) pmf).getOMFContext();
try
{
String className = getClassName(req);
ClassLoaderResolver clr = ctx.getClassLoaderResolver(RestServlet.class.getClassLoader());
AbstractClassMetaData cmd = ctx.getMetaDataManager().getMetaDataForEntityName(className);
Class cls = null;
try
{
if (cmd != null)
{
className = cmd.getFullClassName();
cls = clr.classForName(className, true);
}
else
{
cls = clr.classForName(className, true);
cmd = ctx.getMetaDataManager().getMetaDataForClass(cls, clr);
}
}
catch (ClassNotResolvedException ex)
{
JSONObject error = new JSONObject();
error.put("exception", ex.getMessage());
resp.getWriter().write(error.toString());
resp.setStatus(404);
resp.setHeader("Content-Type","application/json");
return;
}
Object id = getId(req);
if (id == null)
{
// no id provided
try
{
// get the whole extent
String queryString = "SELECT FROM " + cls.getName();
if (req.getQueryString() != null)
{
// query by filter
queryString += " WHERE " + URLDecoder.decode(req.getQueryString(), "UTF-8");
}
PersistenceManager pm = pmf.getPersistenceManager();
try
{
pm.currentTransaction().begin();
Query query = pm.newQuery(queryString);
Object result = query.execute();
JSONSerializer serializer = new JSONSerializer();
resp.getWriter().write(serializer.deepSerialize(result));
resp.setHeader("Content-Type","application/json");
resp.setStatus(200);
pm.currentTransaction().commit();
}
finally
{
if (pm.currentTransaction().isActive())
{
pm.currentTransaction().rollback();
}
pm.close();
}
return;
}
catch (JDOFatalUserException e)
{
JSONObject error = new JSONObject();
error.put("exception", e.getMessage());
resp.getWriter().write(error.toString());
resp.setStatus(400);
resp.setHeader("Content-Type","application/json");
return;
}
catch (JDOException ex)
{
JSONObject error = new JSONObject();
error.put("exception", ex.getMessage());
resp.getWriter().write(error.toString());
resp.setStatus(404);
resp.setHeader("Content-Type","application/json");
return;
}
catch (RuntimeException ex)
{
ex.printStackTrace();
// errors from the google appengine may be raised when running queries
JSONObject error = new JSONObject();
error.put("exception", ex.getMessage());
resp.getWriter().write(error.toString());
resp.setStatus(404);
resp.setHeader("Content-Type","application/json");
return;
}
}
if (cmd.getIdentityType() != IdentityType.APPLICATION)
{
JSONObject error = new JSONObject();
error.put("exception", "Only application identity types are support.");
resp.getWriter().write(error.toString());
resp.setStatus(404);
resp.setHeader("Content-Type","application/json");
return;
}
PersistenceManager pm = pmf.getPersistenceManager();
try
{
pm.currentTransaction().begin();
Object result = pm.getObjectById(id);
JSONSerializer serializer = new JSONSerializer();
resp.getWriter().write(serializer.deepSerialize(result));
resp.setHeader("Content-Type","application/json");
pm.currentTransaction().commit();
return;
}
catch (JDOObjectNotFoundException ex)
{
resp.setContentLength(0);
resp.setStatus(404);
return;
}
catch (JDOException ex)
{
JSONObject error = new JSONObject();
error.put("exception", ex.getMessage());
resp.getWriter().write(error.toString());
resp.setStatus(404);
resp.setHeader("Content-Type","application/json");
return;
}
finally
{
if (pm.currentTransaction().isActive())
{
pm.currentTransaction().rollback();
}
pm.close();
}
}
catch (JSONException e)
{
try
{
JSONObject error = new JSONObject();
error.put("exception", e.getMessage());
resp.getWriter().write(error.toString());
resp.setStatus(404);
resp.setHeader("Content-Type","application/json");
}
catch (JSONException e1)
{
// ignore
}
}
}
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
doPost(req, resp);
}
protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
resp.addHeader("Allow", " GET, HEAD, POST, PUT, TRACE, OPTIONS");
resp.setContentLength(0);
}
protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
OMFContext ctx = ((JDOPersistenceManagerFactory) pmf).getOMFContext();
String className = getClassName(req);
ClassLoaderResolver clr = ctx.getClassLoaderResolver(RestServlet.class.getClassLoader());
AbstractClassMetaData cmd = ctx.getMetaDataManager().getMetaDataForEntityName(className);
Class cls = null;
try
{
if (cmd != null)
{
className = cmd.getFullClassName();
cls = clr.classForName(className, true);
}
else
{
cls = clr.classForName(className, true);
cmd = ctx.getMetaDataManager().getMetaDataForClass(cls, clr);
}
}
catch (ClassNotResolvedException ex)
{
resp.setStatus(404);
return;
}
Object id = getId(req);
if (id == null)
{
// no id provided
try
{
// get the whole extent
String queryString = "SELECT FROM " + cls.getName();
if (req.getQueryString() != null)
{
// query by filter
queryString += " WHERE " + URLDecoder.decode(req.getQueryString(), "UTF-8");
}
PersistenceManager pm = pmf.getPersistenceManager();
try
{
pm.currentTransaction().begin();
Query query = pm.newQuery(queryString);
/*Object result = */query.execute();
resp.setStatus(200);
pm.currentTransaction().commit();
}
finally
{
if (pm.currentTransaction().isActive())
{
pm.currentTransaction().rollback();
}
pm.close();
}
return;
}
catch (JDOFatalUserException e)
{
resp.setStatus(400);
return;
}
catch (JDOException ex)
{
resp.setStatus(404);
return;
}
catch (RuntimeException ex)
{
resp.setStatus(404);
return;
}
}
if (cmd.getIdentityType() != IdentityType.APPLICATION)
{
resp.setStatus(404);
return;
}
PersistenceManager pm = pmf.getPersistenceManager();
try
{
pm.currentTransaction().begin();
/*Object result = */pm.getObjectById(id);
resp.setStatus(200);
pm.currentTransaction().commit();
return;
}
catch (JDOException ex)
{
resp.setStatus(404);
return;
}
finally
{
if (pm.currentTransaction().isActive())
{
pm.currentTransaction().rollback();
}
pm.close();
}
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
if (req.getContentLength() < 1)
{
resp.setContentLength(0);
resp.setStatus(400);// bad request
return;
}
char[] buffer = new char[req.getContentLength()];
req.getReader().read(buffer);
String str = new String(buffer);
JSONObject jsonobj;
PersistenceManager pm = pmf.getPersistenceManager();
try
{
pm.currentTransaction().begin();
jsonobj = new JSONObject(str);
String className = getClassName(req);
Object obj = pm.makePersistent(getObjectFromJSONOject(jsonobj, className, pm));
JSONSerializer serializer = new JSONSerializer();
resp.getWriter().write(serializer.deepSerialize(obj));
resp.setHeader("Content-Type","application/json");
pm.currentTransaction().commit();
}
catch (ClassNotResolvedException e)
{
try
{
JSONObject error = new JSONObject();
error.put("exception", e.getMessage());
resp.getWriter().write(error.toString());
resp.setStatus(500);
resp.setHeader("Content-Type","application/json");
LOGGER_REST.error(e.getMessage(),e);
}
catch (JSONException e1)
{
throw new RuntimeException(e1);
}
}
catch (JDOFatalUserException e)
{
try
{
JSONObject error = new JSONObject();
error.put("exception", e.getMessage());
resp.getWriter().write(error.toString());
resp.setStatus(400);
resp.setHeader("Content-Type","application/json");
LOGGER_REST.error(e.getMessage(),e);
}
catch (JSONException e1)
{
throw new RuntimeException(e1);
}
}
catch (JDOException e)
{
try
{
JSONObject error = new JSONObject();
error.put("exception", e.getMessage());
resp.getWriter().write(error.toString());
resp.setStatus(500);
resp.setHeader("Content-Type","application/json");
LOGGER_REST.error(e.getMessage(),e);
}
catch (JSONException e1)
{
throw new RuntimeException(e1);
}
}
catch (JSONException e)
{
try
{
JSONObject error = new JSONObject();
error.put("exception", e.getMessage());
resp.getWriter().write(error.toString());
resp.setStatus(500);
resp.setHeader("Content-Type","application/json");
LOGGER_REST.error(e.getMessage(),e);
}
catch (JSONException e1)
{
throw new RuntimeException(e1);
}
}
finally
{
if (pm.currentTransaction().isActive())
{
pm.currentTransaction().rollback();
}
pm.close();
}
resp.setStatus(201);// created
}
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
PersistenceManager pm = pmf.getPersistenceManager();
try
{
String className = getClassName(req);
OMFContext ctx = ((JDOPersistenceManager) pm).getObjectManager().getOMFContext();
ClassLoaderResolver clr = ctx.getClassLoaderResolver(RestServlet.class.getClassLoader());
AbstractClassMetaData cmd = ctx.getMetaDataManager().getMetaDataForEntityName(className);
Class cls = null;
try
{
if (cmd != null)
{
className = cmd.getFullClassName();
cls = clr.classForName(className, true);
}
else
{
cls = clr.classForName(className, true);
cmd = ctx.getMetaDataManager().getMetaDataForClass(cls, clr);
}
}
catch (ClassNotResolvedException ex)
{
try
{
JSONObject error = new JSONObject();
error.put("exception", ex.getMessage());
resp.getWriter().write(error.toString());
resp.setStatus(404);
resp.setHeader("Content-Type","application/json");
}
catch (JSONException e)
{
// will not happen
}
return;
}
pm.currentTransaction().begin();
Object id = getId(req);
Object obj = pm.getObjectById(id);
pm.deletePersistent(obj);
pm.currentTransaction().commit();
}
catch (JDONullIdentityException ex)
{
try
{
JSONObject error = new JSONObject();
error.put("exception", ex.getMessage());
resp.getWriter().write(error.toString());
resp.setStatus(400);
resp.setHeader("Content-Type","application/json");
return;
}
catch (JSONException e)
{
// will not happen
}
}
catch (JDOObjectNotFoundException ex)
{
try
{
JSONObject error = new JSONObject();
error.put("exception", ex.getMessage());
resp.getWriter().write(error.toString());
resp.setStatus(400);
resp.setHeader("Content-Type","application/json");
return;
}
catch (JSONException e)
{
// will not happen
}
}
catch (JDOFatalUserException e)
{
try
{
JSONObject error = new JSONObject();
error.put("exception", e.getMessage());
resp.getWriter().write(error.toString());
resp.setStatus(400);
resp.setHeader("Content-Type","application/json");
return;
}
catch (JSONException e1)
{
// ignore
}
}
catch (JDOException e)
{
try
{
JSONObject error = new JSONObject();
error.put("exception", e.getMessage());
resp.getWriter().write(error.toString());
resp.setStatus(500);
resp.setHeader("Content-Type","application/json");
LOGGER_REST.error(e.getMessage(),e);
}
catch (JSONException e1)
{
// ignore
}
}
finally
{
if (pm.currentTransaction().isActive())
{
pm.currentTransaction().rollback();
}
pm.close();
}
resp.setContentLength(0);
resp.setStatus(204);// created
}
/**
* @param jsonobj
* @param className
* @param pm
* @return
* @throws ClassNotResolvedException when the class is not found
* @throws {@link JDOFatalUserException} many situations, such as for google appengine when trying the set primary
* key of a PC_NEW
*/
protected Object getObjectFromJSONOject(final JSONObject jsonobj, String className, PersistenceManager pm)
{
OMFContext ctx = ((JDOPersistenceManager) pm).getObjectManager().getOMFContext();
ClassLoaderResolver clr = ctx.getClassLoaderResolver(RestServlet.class.getClassLoader());
AbstractClassMetaData cmd = ctx.getMetaDataManager().getMetaDataForEntityName(className);
Class cls = null;
if (cmd != null)
{
className = cmd.getFullClassName();
cls = clr.classForName(className, true);
}
else
{
cls = clr.classForName(className, true);
cmd = ctx.getMetaDataManager().getMetaDataForClass(cls, clr);
}
ObjectManager om = ((JDOPersistenceManager) pm).getObjectManager();
if (cmd == null)
{
return getObject(jsonobj, cls);
}
int[] fieldNumbers = cmd.getAllMemberPositions();
LocalSM sm1 = null;
sm1 = new LocalSM(cls);
sm1.replaceFields(fieldNumbers, new LocalFieldManager(jsonobj, null, cmd, pm));
Object obj = sm1.getObject();
try
{
Object id = om.getApiAdapter().getNewApplicationIdentityObjectId(sm1.getObject(), cmd);
obj = pm.getObjectById(id);
StateManager sm = (JDOStateManagerImpl) om.findStateManager(obj);
fieldNumbers = cmd.getNonPKMemberPositions();
sm.replaceFields(fieldNumbers, new LocalFieldManager(jsonobj, sm, cmd, pm));
return obj;
}
catch (JDONullIdentityException ex)
{
// raised when the object has no identity values, so we assume this is a new object
sm1.disconnect();
return obj;
}
catch (JDOObjectNotFoundException ex)
{
// raised when the object cannot be found, so we assume this is a new object
sm1.disconnect();
return obj;
}
}
class LocalFieldManager implements FieldManager
{
JSONObject jsonobj;
AbstractClassMetaData cmd;
StateManager sm;
PersistenceManager pm;
/**
* @param jsonobj
* @param sm may be null
* @param cmd
* @param pm
*/
LocalFieldManager(JSONObject jsonobj, StateManager sm, AbstractClassMetaData cmd, PersistenceManager pm)
{
this.jsonobj = jsonobj;
this.cmd = cmd;
this.sm = sm;
this.pm = pm;
}
public String fetchStringField(int position)
{
String fieldName = cmd.getMetaDataForMemberAtRelativePosition(position).getName();
if (!jsonobj.has(fieldName))
{
return null;
}
try
{
String value = jsonobj.getString(fieldName);
if (sm != null)
{
sm.makeDirty(position);
}
return value;
}
catch (JSONException e)
{
// should not happen
}
return null;
}
public short fetchShortField(int position)
{
String fieldName = cmd.getMetaDataForMemberAtRelativePosition(position).getName();
if (!jsonobj.has(fieldName))
{
return 0;
}
try
{
short value = (short) jsonobj.getInt(fieldName);
if (sm != null)
{
sm.makeDirty(position);
}
return value;
}
catch (JSONException e)
{
// should not happen
}
return 0;
}
public Object fetchObjectField(int position)
{
String fieldName = cmd.getMetaDataForMemberAtRelativePosition(position).getName();
if (!jsonobj.has(fieldName))
{
return null;
}
try
{
if (jsonobj.isNull(fieldName))
{
return null;
}
Object value = jsonobj.get(fieldName);
if( value instanceof JSONObject)
{
value = getObjectFromJSONOject((JSONObject)value, ((JSONObject)value).getString("class"), pm);
if (sm != null)
{
sm.makeDirty(position);
}
return value;
}
if( value instanceof JSONArray)
{
value= fetchJSONArray((JSONArray)value,position);
if (sm != null)
{
sm.makeDirty(position);
}
return value;
}
if (sm != null)
{
sm.makeDirty(position);
}
return TypeConversionHelper.convertTo(value, cmd.getMetaDataForMemberAtRelativePosition(position).getType());
}
catch(JSONException ex)
{
throw new RuntimeException(ex);
}
}
private List fetchJSONArray(JSONArray array, int position) throws JSONException
{
List elements = new ArrayList();
for( int i=0; i 0)
{
value = str.charAt(0);
}
if (sm != null)
{
sm.makeDirty(position);
}
return value;
}
catch (JSONException e)
{
// should not happen
}
return 0;
}
public byte fetchByteField(int position)
{
String fieldName = cmd.getMetaDataForMemberAtRelativePosition(position).getName();
if (!jsonobj.has(fieldName))
{
return 0;
}
try
{
String str = jsonobj.getString(fieldName);
byte value = 0;
if (str != null && str.length() > 0)
{
value = str.getBytes()[0];
}
if (sm != null)
{
sm.makeDirty(position);
}
return value;
}
catch (JSONException e)
{
// should not happen
}
return 0;
}
public boolean fetchBooleanField(int position)
{
String fieldName = cmd.getMetaDataForMemberAtRelativePosition(position).getName();
if (!jsonobj.has(fieldName))
{
return false;
}
try
{
boolean value = jsonobj.getBoolean(fieldName);
if (sm != null)
{
sm.makeDirty(position);
}
return value;
}
catch (JSONException e)
{
e.printStackTrace();
}
return false;
}
public void storeStringField(int arg0, String arg1)
{
}
public void storeShortField(int arg0, short arg1)
{
}
public void storeObjectField(int arg0, Object arg1)
{
}
public void storeLongField(int arg0, long arg1)
{
}
public void storeIntField(int arg0, int arg1)
{
}
public void storeFloatField(int arg0, float arg1)
{
}
public void storeDoubleField(int arg0, double arg1)
{
}
public void storeCharField(int arg0, char arg1)
{
}
public void storeByteField(int arg0, byte arg1)
{
}
public void storeBooleanField(int arg0, boolean arg1)
{
}
}
/**
* This class is used to populate fields of PC objects
*/
private class LocalSM implements javax.jdo.spi.StateManager
{
PersistenceCapable myPC;
FieldManager fm;
public LocalSM(Class cls)
{
myPC = JDOImplHelper.getInstance().newInstance(cls, this);
}
public boolean getBooleanField(PersistenceCapable arg0, int arg1, boolean arg2)
{
return false;
}
public byte getByteField(PersistenceCapable arg0, int arg1, byte arg2)
{
return 0;
}
public char getCharField(PersistenceCapable arg0, int arg1, char arg2)
{
return 0;
}
public double getDoubleField(PersistenceCapable arg0, int arg1, double arg2)
{
return 0;
}
public float getFloatField(PersistenceCapable arg0, int arg1, float arg2)
{
return 0;
}
public int getIntField(PersistenceCapable arg0, int arg1, int arg2)
{
return 0;
}
public long getLongField(PersistenceCapable arg0, int arg1, long arg2)
{
return 0;
}
public Object getObjectField(PersistenceCapable arg0, int arg1, Object arg2)
{
return null;
}
public Object getObjectId(PersistenceCapable arg0)
{
return null;
}
public PersistenceManager getPersistenceManager(PersistenceCapable arg0)
{
return null;
}
public short getShortField(PersistenceCapable arg0, int arg1, short arg2)
{
return 0;
}
public String getStringField(PersistenceCapable arg0, int arg1, String arg2)
{
return null;
}
public Object getTransactionalObjectId(PersistenceCapable arg0)
{
return null;
}
public Object getVersion(PersistenceCapable arg0)
{
return null;
}
public boolean isDeleted(PersistenceCapable arg0)
{
return false;
}
public boolean isDirty(PersistenceCapable arg0)
{
return false;
}
public boolean isLoaded(PersistenceCapable arg0, int arg1)
{
return false;
}
public boolean isNew(PersistenceCapable arg0)
{
return false;
}
public boolean isPersistent(PersistenceCapable arg0)
{
return false;
}
public boolean isTransactional(PersistenceCapable arg0)
{
return false;
}
public void makeDirty(PersistenceCapable arg0, String arg1)
{
}
public void preSerialize(PersistenceCapable arg0)
{
}
public void providedBooleanField(PersistenceCapable arg0, int arg1, boolean arg2)
{
}
public void providedByteField(PersistenceCapable arg0, int arg1, byte arg2)
{
}
public void providedCharField(PersistenceCapable arg0, int arg1, char arg2)
{
}
public void providedDoubleField(PersistenceCapable arg0, int arg1, double arg2)
{
}
public void providedFloatField(PersistenceCapable arg0, int arg1, float arg2)
{
}
public void providedIntField(PersistenceCapable arg0, int arg1, int arg2)
{
}
public void providedLongField(PersistenceCapable arg0, int arg1, long arg2)
{
}
public void providedObjectField(PersistenceCapable arg0, int arg1, Object arg2)
{
}
public void providedShortField(PersistenceCapable arg0, int arg1, short arg2)
{
}
public void providedStringField(PersistenceCapable arg0, int arg1, String arg2)
{
}
public boolean replacingBooleanField(PersistenceCapable arg0, int arg1)
{
return fm.fetchBooleanField(arg1);
}
public byte replacingByteField(PersistenceCapable arg0, int arg1)
{
return fm.fetchByteField(arg1);
}
public char replacingCharField(PersistenceCapable arg0, int arg1)
{
return fm.fetchCharField(arg1);
}
public Object[] replacingDetachedState(Detachable arg0, Object[] arg1)
{
return null;
}
public double replacingDoubleField(PersistenceCapable arg0, int arg1)
{
return fm.fetchDoubleField(arg1);
}
public byte replacingFlags(PersistenceCapable arg0)
{
return 0;
}
public float replacingFloatField(PersistenceCapable arg0, int arg1)
{
return fm.fetchFloatField(arg1);
}
public int replacingIntField(PersistenceCapable arg0, int arg1)
{
return fm.fetchIntField(arg1);
}
public long replacingLongField(PersistenceCapable arg0, int arg1)
{
return fm.fetchLongField(arg1);
}
public Object replacingObjectField(PersistenceCapable arg0, int arg1)
{
return fm.fetchObjectField(arg1);
}
public short replacingShortField(PersistenceCapable arg0, int arg1)
{
return fm.fetchShortField(arg1);
}
public javax.jdo.spi.StateManager replacingStateManager(PersistenceCapable arg0, javax.jdo.spi.StateManager arg1)
{
return null;
}
public String replacingStringField(PersistenceCapable arg0, int arg1)
{
return fm.fetchStringField(arg1);
}
public void setBooleanField(PersistenceCapable arg0, int arg1, boolean arg2, boolean arg3)
{
}
public void setByteField(PersistenceCapable arg0, int arg1, byte arg2, byte arg3)
{
}
public void setCharField(PersistenceCapable arg0, int arg1, char arg2, char arg3)
{
}
public void setDoubleField(PersistenceCapable arg0, int arg1, double arg2, double arg3)
{
}
public void setFloatField(PersistenceCapable arg0, int arg1, float arg2, float arg3)
{
}
public void setIntField(PersistenceCapable arg0, int arg1, int arg2, int arg3)
{
}
public void setLongField(PersistenceCapable arg0, int arg1, long arg2, long arg3)
{
}
public void setObjectField(PersistenceCapable arg0, int arg1, Object arg2, Object arg3)
{
}
public void setShortField(PersistenceCapable arg0, int arg1, short arg2, short arg3)
{
}
public void setStringField(PersistenceCapable arg0, int arg1, String arg2, String arg3)
{
}
void replaceFields(int[] fieldNumbers, FieldManager fm)
{
this.fm = fm;
myPC.jdoReplaceFields(fieldNumbers);
}
public Object getObject()
{
return myPC;
}
public void disconnect()
{
try
{
// Calls to pc.jdoReplaceStateManager must be run privileged
AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
myPC.jdoReplaceStateManager(null);
return null;
}
});
}
catch (SecurityException e)
{
}
}
}
/**
* Deserialise from JSON to an object. (Used for non SingleFieldIdentity classes)
* @param jsonobj
* @param cls
* @return
*/
private Object getObject(final Object field, final Class cls, final Class pcType, final AbstractClassMetaData cmd)
{
OMFContext ctx = ((JDOPersistenceManagerFactory) pmf).getOMFContext();
return ctx.getApiAdapter().getNewSingleFieldIdentity(cls,pcType,field);
}
/**
* Deserialise from JSON to an object. (Used for non PersistenceCapable classes)
* @param jsonobj
* @param cls
* @return
*/
private Object getObject(final JSONObject jsonobj, final Class cls)
{
if (cls.getName().equals("com.google.appengine.api.users.User"))
{
String email = null;
String authDomain = null;
try
{
email = jsonobj.getString("email");
}
catch (JSONException e)
{
// should not happen if the field exists
}
try
{
authDomain = jsonobj.getString("authDomain");
}
catch (JSONException e)
{
// should not happen if the field exists
}
return ClassUtils.newInstance(cls, new Class[]{String.class, String.class}, new String[]{email, authDomain});
}
else if (cls.getName().equals("com.google.appengine.api.datastore.Key"))
{
try
{
Object parent = null;
if (jsonobj.has("parent") && !jsonobj.isNull("parent"))
{
OMFContext ctx = ((JDOPersistenceManagerFactory) pmf).getOMFContext();
ClassLoaderResolver clr = ctx.getClassLoaderResolver(RestServlet.class.getClassLoader());
//if it's a JSONObject
JSONObject parentobj = jsonobj.getJSONObject("parent");
parent = getObject(parentobj,clr.classForName(jsonobj.getString("class")));
}
if (jsonobj.has("appId"))
{
String appId = jsonobj.getString("appId");
String kind = jsonobj.getString("kind");
Class keyFactory = Class.forName("com.google.appengine.api.datastore.KeyFactory",false,cls.getClassLoader());
if( parent != null)
{
return ClassUtils.getMethodForClass(keyFactory, "createKey", new Class[]{cls,String.class,String.class}).invoke(null, new Object[]{parent,kind,appId});
}
else
{
return ClassUtils.getMethodForClass(keyFactory, "createKey", new Class[]{String.class,String.class}).invoke(null, new Object[]{kind,appId});
}
}
else
{
long id = jsonobj.getLong("id");
String kind = jsonobj.getString("kind");
Class keyFactory = Class.forName("com.google.appengine.api.datastore.KeyFactory",false,cls.getClassLoader());
if( parent != null)
{
return ClassUtils.getMethodForClass(keyFactory, "createKey", new Class[]{cls,String.class,long.class}).invoke(null, new Object[]{parent,kind,new Long(id)});
}
else
{
return ClassUtils.getMethodForClass(keyFactory, "createKey", new Class[]{String.class,long.class}).invoke(null, new Object[]{kind,new Long(id)});
}
}
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
else
{
try
{
return AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
try
{
Constructor c = ClassUtils.getConstructorWithArguments(cls, new Class[]{});
c.setAccessible(true);
Object obj = c.newInstance(new Object[]{});
String[] fieldNames = JSONObject.getNames(jsonobj);
for (int i = 0; i < jsonobj.length(); i++)
{
//ignore class field
if(!fieldNames[i].equals("class"))
{
Field field = cls.getField(fieldNames[i]);
field.setAccessible(true);
field.set(obj, jsonobj.get(fieldNames[i]));
}
}
return obj;
}
catch (InstantiationException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalAccessException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalArgumentException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SecurityException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (NoSuchFieldException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (InvocationTargetException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
});
}
catch (SecurityException ex)
{
ex.printStackTrace();
}
}
return null;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy