Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Copyright (c) 2008 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.store.json;
 
 import java.util.Date;
 import java.util.List;
 import java.util.Map;
 
 
 {
    
Localiser for messages.
 
     protected static final Localiser LOCALISER = Localiser.getInstance(
         "org.datanucleus.store.json.Localisation"JsonStoreManager.class.getClassLoader());
 
     protected AbstractStoreManager storeMgr;
 
     {
         this. = (AbstractStoreManager)storeMgr;
     }
 
     public void close()
     {
         // nothing to do
     }
 
     public void insertObject(ObjectProvider op)
     {
         // Check if read-only so update not permitted
 
         Map<String,Stringoptions = new HashMap<String,String>();
         options.put(.getURLPath(op));
         options.put("Content-Type""application/json");
         ManagedConnection mconn = .getConnection(op.getExecutionContext(), options);
         URLConnection conn = (URLConnectionmconn.getConnection();
         try
         {
             long startTime = System.currentTimeMillis();
             if (..isDebugEnabled())
             {
                 ..debug(.msg("JSON.Insert.Start"
                     op.toPrintableID(), op.getInternalObjectId()));
            }
            JSONObject jsonobj = new JSONObject();
            AbstractClassMetaData cmd = op.getClassMetaData();
            if (cmd.getIdentityType() == .)
            {
                String memberName = JSONUtils.getMemberNameForDatastoreIdentity(cmd);
                Object idKey = ((OID)op.getInternalObjectId()).getKeyValue();
                try
                {
                    jsonobj.put(memberNameidKey);
                }
                catch (JSONException e)
                {
                    throw new NucleusException("Exception setting datastore identity in JSON object"e);
                }
            }
            if (cmd.isVersioned())
            {
                VersionMetaData vermd = cmd.getVersionMetaDataForClass();
                String memberName = JSONUtils.getMemberNameForVersion(vermd);
                if (vermd.getVersionStrategy() == .)
                {
                    long versionNumber = 1;
                    op.setTransactionalVersion(new Long(versionNumber));
                    if (..isDebugEnabled())
                    {
                        ..debug(.msg("JSON.Insert.ObjectPersistedWithVersion",
                            StringUtils.toJVMIDString(op.getObject()), op.getInternalObjectId(), "" + versionNumber));
                    }
                    try
                    {
                        jsonobj.put(memberNameversionNumber);
                    }
                    catch (JSONException e)
                    {
                        throw new NucleusException("Exception setting version in JSON object"e);
                    }
                    if (vermd.getFieldName() != null)
                    {
                        // Version is stored in a field, so set it there too
                        AbstractMemberMetaData verfmd = cmd.getMetaDataForMember(vermd.getFieldName());
                        if (verfmd.getType() == Integer.class)
                        {
                            op.replaceField(verfmd.getAbsoluteFieldNumber(), new Integer((int)versionNumber));
                        }
                        else
                        {
                            op.replaceField(verfmd.getAbsoluteFieldNumber(), new Long(versionNumber));
                        }
                    }
                }
                else if (vermd.getVersionStrategy() == .)
                {
                    Date date = new Date();
                    Timestamp ts = new Timestamp(date.getTime());
                    op.setTransactionalVersion(ts);
                    if (..isDebugEnabled())
                    {
                        ..debug(.msg("JSON.Insert.ObjectPersistedWithVersion",
                            StringUtils.toJVMIDString(op.getObject()), op.getInternalObjectId(), "" + ts));
                    }
                    try
                    {
                        jsonobj.put(memberNamets.getTime());
                    }
                    catch (JSONException e)
                    {
                        throw new NucleusException("Exception setting version in JSON object"e);
                    }
                }
            }
            int[] fieldNumbers = cmd.getAllMemberPositions();
            op.provideFields(fieldNumbersnew StoreFieldManager(opjsonobjtrue));
            ..debug("POST " + jsonobj.toString());
            write("POST",conn.getURL().toExternalForm(), connjsonobjgetHeaders("POST",options));
            if (..isDebugEnabled())
            {
                ..debug(.msg("JSON.ExecutionTime"
                    (System.currentTimeMillis() - startTime)));
            }
            if (.getRuntimeManager() != null)
            {
                .getRuntimeManager().incrementInsertCount();
            }
        }
        finally
        {
            mconn.release();
        }
    }
    public void updateObject(ObjectProvider opint[] fieldNumbers)
    {
        // Check if read-only so update not permitted
        Map<String,Stringoptions = new HashMap<String,String>();
        options.put(.getURLPath(op));
        options.put("Content-Type""application/json");        
        ManagedConnection mconn = .getConnection(op.getExecutionContext(), options);
        URLConnection conn = (URLConnectionmconn.getConnection();
        try
        {
            AbstractClassMetaData cmd = op.getClassMetaData();
            Object currentVersion = op.getTransactionalVersion();
            Object nextVersion = null;
            if (cmd.isVersioned())
            {
                // Version object so calculate version to store with
                VersionMetaData vermd = cmd.getVersionMetaDataForClass();
                if (vermd.getFieldName() != null)
                {
                    // Version field
                    AbstractMemberMetaData verfmd = cmd.getMetaDataForMember(vermd.getFieldName());
                    if (currentVersion instanceof Integer)
                    {
                        // Cater for Integer-based versions TODO Generalise this
                        currentVersion = new Long(((Integer)currentVersion).longValue());
                    }
                    nextVersion = VersionHelper.getNextVersion(vermd.getVersionStrategy(), currentVersion);
                    if (verfmd.getType() == Integer.class || verfmd.getType() == int.class)
                    {
                        // Cater for Integer-based versions TODO Generalise this
                        nextVersion = new Integer(((Long)nextVersion).intValue());
                    }
                    op.replaceField(verfmd.getAbsoluteFieldNumber(), nextVersion);
                }
                else
                {
                    // Surrogate version column
                    nextVersion = VersionHelper.getNextVersion(vermd.getVersionStrategy(), currentVersion);
                }
                op.setTransactionalVersion(nextVersion);
            }
            long startTime = System.currentTimeMillis();
            if (..isDebugEnabled())
            {
                StringBuffer fieldStr = new StringBuffer();
                for (int i=0;i<fieldNumbers.length;i++)
                {
                    if (i > 0)
                    {
                        fieldStr.append(",");
                    }
                    fieldStr.append(cmd.getMetaDataForManagedMemberAtAbsolutePosition(fieldNumbers[i]).getName());
                }
                ..debug(.msg("JSON.Update.Start"
                    op.toPrintableID(), op.getInternalObjectId(), fieldStr.toString()));
            }
            JSONObject jsonobj = new JSONObject();
            if (cmd.isVersioned())
            {
                VersionMetaData vermd = cmd.getVersionMetaDataForClass();
                String memberName = JSONUtils.getMemberNameForVersion(vermd);
                if (vermd.getVersionStrategy() == .)
                {
                    if (..isDebugEnabled())
                    {
                        ..debug(.msg("JSON.Insert.ObjectPersistedWithVersion",
                            StringUtils.toJVMIDString(op.getObject()), op.getInternalObjectId(), 
                            "" + nextVersion));
                    }
                    try
                    {
                        jsonobj.put(memberNamenextVersion);
                    }
                    catch (JSONException e)
                    {
                        throw new NucleusException(e.getMessage(), e);
                    }
                }
                else if (vermd.getVersionStrategy() == .)
                {
                    op.setTransactionalVersion(nextVersion);
                    if (..isDebugEnabled())
                    {
                        ..debug(.msg("JSON.Insert.ObjectPersistedWithVersion",
                            StringUtils.toJVMIDString(op.getObject()), op.getInternalObjectId(), "" + nextVersion));
                    }
                    Timestamp ts = (Timestamp)nextVersion;
                    Date date = new Date();
                    date.setTime(ts.getTime());
                    try
                    {
                        jsonobj.put(memberNamets.getTime());
                    }
                    catch (JSONException e)
                    {
                        throw new NucleusException(e.getMessage(), e);
                    }
                }
            }
            // TODO Why not put ALL fields here not just those that are updated?
            op.provideFields(fieldNumbersnew StoreFieldManager(opjsonobjfalse));
            op.provideFields(op.getClassMetaData().getPKMemberPositions(), new StoreFieldManager(opjsonobjfalse));
            ..debug("PUT " + jsonobj.toString());
            write("PUT"conn.getURL().toExternalForm(), connjsonobjgetHeaders("PUT",options));
            if (..isDebugEnabled())
            {
                ..debug(.msg("JSON.ExecutionTime"
                    (System.currentTimeMillis() - startTime)));
            }
            if (.getRuntimeManager() != null)
            {
                .getRuntimeManager().incrementUpdateCount();
            }
        }
        finally
        {
            mconn.release();
        }
    }
    public void deleteObject(ObjectProvider op)
    {
        // Check if read-only so update not permitted
        Map<String,Stringoptions = new HashMap<String,String>();
        options.put(.getURLPath(op));
        ManagedConnection mconn = .getConnection(op.getExecutionContext(), options);
        URLConnection conn = (URLConnectionmconn.getConnection();
        try
        {
            long startTime = System.currentTimeMillis();
            if (..isDebugEnabled())
            {
                ..debug(.msg("JSON.Delete.Start"
                    op.toPrintableID(), op.getInternalObjectId()));
            }
            HttpURLConnection http = (HttpURLConnection)conn;
            Map<String,Stringheaders = getHeaders("DELETE",options);
            Iterator iterator = headers.keySet().iterator();
            while(iterator.hasNext())
            {
                String key = (Stringiterator.next();
                String value = (Stringheaders.get(key);
                http.setRequestProperty(keyvalue);
            }
            http.setRequestMethod("DELETE");
            http.setReadTimeout(10000);
            http.setConnectTimeout(10000);
            http.connect();
            int code = http.getResponseCode();
            if (code == 404)
            {
                throw new NucleusObjectNotFoundException();
            }
            handleHTTPErrorCode(http);
            if (..isDebugEnabled())
            {
                ..debug(.msg("JSON.ExecutionTime"
                    (System.currentTimeMillis() - startTime)));
            }
            if (.getRuntimeManager() != null)
            {
                .getRuntimeManager().incrementDeleteCount();
            }
        }
        catch (IOException e)
        {
            throw new NucleusDataStoreException(e.getMessage(),e);
        }
        finally
        {
            mconn.release();
        }
    }
    public void fetchObject(ObjectProvider opint[] fieldNumbers)
    {
        Map<String,Stringoptions = new HashMap<String,String>();
        options.put(.getURLPath(op));
        ManagedConnection mconn = .getConnection(op.getExecutionContext(), options);
        URLConnection conn = (URLConnectionmconn.getConnection();
        try
        {
            AbstractClassMetaData cmd = op.getClassMetaData();
            if (..isDebugEnabled())
            {
                // Debug information about what we are retrieving
                StringBuffer str = new StringBuffer("Fetching object \"");
                str.append(op.toPrintableID()).append("\" (id=");
                str.append(op.getExecutionContext().getApiAdapter().getObjectId(op)).append(")").append(" fields [");
                for (int i=0;i<fieldNumbers.length;i++)
                {
                    if (i > 0)
                    {
                        str.append(",");
                    }
                    str.append(cmd.getMetaDataForManagedMemberAtAbsolutePosition(fieldNumbers[i]).getName());
                }
                str.append("]");
                ..debug(str);
            }
            long startTime = System.currentTimeMillis();
            if (..isDebugEnabled())
            {
                ..debug(.msg("HBase.Fetch.Start"
                    op.toPrintableID(), op.getInternalObjectId()));
            }
            // Create JSON object with PK fields set and get the object
            JSONObject jsonobj = new JSONObject();
            if (cmd.getIdentityType() == .)
            {
                String memberName = JSONUtils.getMemberNameForDatastoreIdentity(cmd);
                Object idKey = ((OID)op.getInternalObjectId()).getKeyValue();
                try
                {
                    jsonobj.put(memberNameidKey);
                }
                catch (JSONException e)
                {
                    throw new NucleusException("Exception setting datastore identity in JSON object"e);
                }
            }
            else if (cmd.getIdentityType() == .)
            {
                op.provideFields(op.getClassMetaData().getPKMemberPositions(), new StoreFieldManager(opjsonobjtrue));
            }
            JSONObject result = read("GET"conn.getURL().toExternalForm(), conngetHeaders("GET",options));
            ..debug("GET " + result.toString());
            op.replaceFields(fieldNumbersnew FetchFieldManager(opresult));
            if (..isDebugEnabled())
            {
                ..debug(.msg("HBase.ExecutionTime",
                    (System.currentTimeMillis() - startTime)));
            }
            if (.getRuntimeManager() != null)
            {
                .getRuntimeManager().incrementFetchCount();
            }
        }
        finally
        {
            mconn.release();
        }
    }
    public Object findObject(ExecutionContext ecObject id)
    {
        return null;
    }
    public void locateObject(ObjectProvider op)
    {
        Map<String,Stringoptions = new HashMap<String,String>();
        options.put(.getURLPath(op));
        ManagedConnection mconn = .getConnection(op.getExecutionContext(), options);
        URLConnection conn = (URLConnectionmconn.getConnection();
        try
        {
            HttpURLConnection http = (HttpURLConnection)conn;
            Map<String,Stringheaders = getHeaders("HEAD",options);
            Iterator iterator = headers.keySet().iterator();
            while (iterator.hasNext())
            {
                String key = (Stringiterator.next();
                String value = (Stringheaders.get(key);
                http.setRequestProperty(keyvalue);
            }
            http.setDoOutput(true);
            http.setRequestMethod("HEAD");
            http.setReadTimeout(10000);
            http.setConnectTimeout(10000);
            http.connect();
            int code = http.getResponseCode();
            if (code == 404)
            {
                throw new NucleusObjectNotFoundException();
            }
            handleHTTPErrorCode(http);
        }
        catch (IOException e)
        {
            throw new NucleusObjectNotFoundException(e.getMessage(),e);
        }
    }
    protected void write(String methodString requestUriURLConnection connJSONObject jsonobj,
            Map<StringStringheaders)
    {
        try
        {
            if (..isDebugEnabled())
            {
                ..debug("Writing to URL "+requestUri+" content "+jsonobj.toString());
            }
            int length = jsonobj.toString().length();
            HttpURLConnection http = (HttpURLConnection)conn;
            Iterator<Stringiterator = headers.keySet().iterator();
            while (iterator.hasNext())
            {
                String key = iterator.next();
                String value = headers.get(key);
                http.setRequestProperty(keyvalue);
            }
            http.setRequestProperty("Content-Length"""+length);
            http.setDoOutput(true);
            http.setRequestMethod(method);
            http.setReadTimeout(10000);
            http.setConnectTimeout(10000);
            http.connect();
            OutputStream os = conn.getOutputStream();
            os.write(jsonobj.toString().getBytes());
            os.flush();
            os.close();
            handleHTTPErrorCode(http);
       }
        catch (IOException e)
        {
            throw new NucleusDataStoreException(e.getMessage(),e);
        }
    }
    protected JSONObject read(String methodString requestUriURLConnection connMap headers)
    {
        try
        {
            HttpURLConnection http = (HttpURLConnection)conn;
            Iterator iterator = headers.keySet().iterator();
            while(iterator.hasNext())
            {
                String key = (Stringiterator.next();
                String value = (Stringheaders.get(key);
                http.setRequestProperty(keyvalue);
            }
            //http.setDoOutput(true);
            http.setDoInput(true);
            http.setRequestMethod(method);
            http.setReadTimeout(10000);
            http.setConnectTimeout(10000);
            http.connect();
            int code = http.getResponseCode();
            if (code == 404)
            {
                throw new NucleusObjectNotFoundException();
            }
            /*String msg =*/ http.getResponseMessage();
            StringBuffer sb = new StringBuffer();
            if (http.getContentLength()>0)
            {
                for (int i=0; i<http.getContentLength(); i++)
                {
                    sb.append((char)http.getInputStream().read());
                }
            }
            else
            {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int r;
                while ((r = http.getInputStream().read(buffer)) != -1)
                {
                    baos.write(buffer, 0, r);
                }
                sb.append(new String(baos.toByteArray()));
            }
            http.getInputStream().close();
            return new JSONObject(sb.toString());
        }
        catch (SocketTimeoutException e)
        {
            throw new NucleusDataStoreException(e.getMessage(),e);
        }
        catch (IOException e)
        {
            throw new NucleusDataStoreException(e.getMessage(),e);
        }
        catch (JSONException e)
        {
            throw new NucleusDataStoreException(e.getMessage(),e);
        }
    }
    
    protected Map<String,StringgetHeaders(String httpVerbMap<String,Stringoptions)
    {
        Map<StringStringheaders = new HashMap<StringString>();
        headers.put("Date", CloudStorageUtils.getHTTPDate());
        String contentType = "";
        if (options.containsKey("Content-Type"))
        {
            contentType = options.get("Content-Type");
            headers.put("Content-Type"contentType);
        }
        return headers;
    }

    
Convenience method to get all objects of the candidate type from the specified connection.

Parameters:
mconn Managed Connection
candidateClass Candidate
subclasses Whether to include subclasses
ignoreCache Whether to ignore the cache
om ObjectManager
Returns:
List of objects of the candidate type
            Class candidateClassboolean subclassesboolean ignoreCacheMap options)
    {
        List results = new ArrayList();
        // TODO Support subclasses
        try
        {
            URLConnection conn = (URLConnectionmconn.getConnection();
            ClassLoaderResolver clr = ec.getClassLoaderResolver();
            final AbstractClassMetaData cmd = ec.getMetaDataManager().getMetaDataForClass(candidateClassclr);
            JSONArray jsonarray;
            try
            {
                HttpURLConnection http = (HttpURLConnectionconn;
                Map headers = getHeaders("GET"options);
                Iterator iterator = headers.keySet().iterator();
                while (iterator.hasNext())
                {
                    String key = (Stringiterator.next();
                    String value = (Stringheaders.get(key);
                    http.setRequestProperty(keyvalue);
                }
                http.setDoInput(true);
                http.setRequestMethod("GET");
                http.setReadTimeout(10000);
                http.setConnectTimeout(10000);
                http.connect();
                int code = http.getResponseCode();
                if (code == 404)
                {
                    return .;
                }
                /* String msg = */http.getResponseMessage();
                StringBuffer sb = new StringBuffer();
                if (http.getContentLength() > 0)
                {
                    for (int i = 0; i < http.getContentLength(); i++)
                    {
                        sb.append((charhttp.getInputStream().read());
                    }
                }
                else
                {
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int r;
                    while ((r = http.getInputStream().read(buffer)) != -1)
                    {
                        baos.write(buffer, 0, r);
                    }
                    sb.append(new String(baos.toByteArray()));
                }
                http.getInputStream().close();
                jsonarray = new JSONArray(sb.toString());
            }
            catch (IOException e)
            {
                throw new NucleusDataStoreException(e.getMessage(), e);
            }
            catch (JSONException e)
            {
                throw new NucleusDataStoreException(e.getMessage(), e);
            }
            for (int i = 0; i < jsonarray.length(); i++)
            {
                final JSONObject json = jsonarray.getJSONObject(i);
                Object id = null;
                if (cmd.getIdentityType() == .)
                {
                    String memberName = JSONUtils.getMemberNameForDatastoreIdentity(cmd);
                    Object key = json.get(memberName);
                    if (key instanceof String)
                    {
                        id = OIDFactory.getInstance(ec.getNucleusContext(), (String)key);
                    }
                    else
                    {
                        id = OIDFactory.getInstance(ec.getNucleusContext(), (Long)key);
                    }
                }
                else if (cmd.getIdentityType() == .)
                {
                    id = IdentityUtils.getApplicationIdentityForResultSetRow(eccmdnull
                        truenew FetchFieldManager(eccmdjson));
                }
                Object version = null;
                if (cmd.isVersioned())
                {
                    // Extract the version for applying to the object
                    VersionMetaData vermd = cmd.getVersionMetaDataForClass();
                    String memberName = JSONUtils.getMemberNameForVersion(vermd);
                    long versionLong = -1;
                    try
                    {
                        versionLong = json.getLong(memberName);
                        if (vermd.getVersionStrategy() == .)
                        {
                            version = versionLong;
                        }
                        else if (vermd.getVersionStrategy() == .)
                        {
                            version = new Timestamp(versionLong);
                        }
                    }
                    catch (JSONException e)
                    {
                        //ignore
                    }
                }
                Object obj = ec.findObject(idnew FieldValues()
                {
                    public FetchPlan getFetchPlanForLoading()
                    {
                        return null;
                    }
                    public void fetchNonLoadedFields(ObjectProvider op)
                    {
                        op.replaceNonLoadedFields(cmd.getAllMemberPositions(), new FetchFieldManager(eccmdjson));
                    }
                    public void fetchFields(ObjectProvider op)
                    {
                        op.replaceFields(cmd.getAllMemberPositions(), new FetchFieldManager(eccmdjson));
                    }
                }, nullignoreCache);
                if (cmd.isVersioned() && version != null)
                {
                    ObjectProvider op = ec.findObjectProvider(obj);
                    op.setVersion(version);
                }
                results.add(obj);
            }
        }
        catch (JSONException je)
        {
            throw new NucleusException(je.getMessage(), je);
        }
        return results;
    }
    public String getURLPath(ObjectProvider op)
    {
        AbstractClassMetaData cmd = op.getClassMetaData();
        String url = getURLPath(cmd);
        if (cmd.getIdentityType() == .)
        {
            url += ((OID)op.getInternalObjectId()).getKeyValue();
        }
        else if (cmd.getIdentityType() == .)
        {
            // Create JSON object with PK fields set and get the object
            JSONObject jsonobj = new JSONObject();
            op.provideFields(cmd.getPKMemberPositions(), new StoreFieldManager(opjsonobjtrue));
            try
            {
                // Append the PK to the URL
                AbstractMemberMetaData mmd = 
                    cmd.getMetaDataForManagedMemberAtAbsolutePosition(cmd.getPKMemberPositions()[0]);
                String name = JSONUtils.getMemberNameForMember(mmd);
                url += jsonobj.get(name).toString();
                // TODO Cater for multiple PK fields
            }
            catch (JSONException e)
            {
                throw new NucleusException(e.getMessage(), e);
            }
        }
        return url;
    }
    {
        String url = acmd.getValueForExtension("url");
        if (url == null)
        {
            url = acmd.getFullClassName();
        }
        if (!url.endsWith("/"))
        {
            url += "/";
        }
        return url;
    }
    
    {
        String url = acmd.getValueForExtension("url");
        if (url == null)
        {
            url = acmd.getFullClassName();
        }
        if (!url.endsWith("/"))
        {
            url += "/";
        }
        return url;
    }
    protected void handleHTTPErrorCode(HttpURLConnection httpthrows IOException
    {
        if (http.getResponseCode() >= 400)
        {
            StringBuffer sb = new StringBuffer();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int r;
            if (http.getErrorStream() != null)
            {
                while ((r = http.getErrorStream().read(buffer)) != -1) 
                {
                    baos.write(buffer, 0, r);
                }
                sb.append(new String(baos.toByteArray()));        
                http.getErrorStream().close();
            }
            throw new NucleusDataStoreException("Error on URL: '"+http.getURL().toExternalForm()+
                "' Request Method: "+http.getRequestMethod()+
                " HTTP Error code: "+http.getResponseCode()+" "+http.getResponseMessage()+" error: "+sb.toString());
        }
        else if (http.getResponseCode() >= 300)
        {
            throw new NucleusDataStoreException("Redirect not supported. HTTP Error code: "+http.getResponseCode()+
                " "+http.getResponseMessage());
        }
    }
New to GrepCode? Check out our FAQ X