com.android.datacloud.Entity.java Source code

Java tutorial

Introduction

Here is the source code for com.android.datacloud.Entity.java

Source

/*
 * Copyright (C) 2008  Javier Perez Pacheco y Javier Ros Moreno
 *
 * Android Data Framework: Trabajo con BD SQLite en Android
 *
 * 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.
 *
 * Javier Perez Pacheco
 * Cadiz (Spain)
 * javi.pacheco@gmail.com
 * 
 * Javier Ros Moreno
 * jros@jros.org
 * 
 *
 */

package com.android.datacloud;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

import com.android.datacloud.core.Field;
import com.android.datacloud.core.Table;

public class Entity {

    private String mTable;
    private long mId = -1;
    private long mForceId = -1;
    protected HashMap<String, Object> mAttributes = new HashMap<String, Object>();
    protected HashMap<String, Object> mMultilanguagesAttributes = new HashMap<String, Object>();

    private boolean errorLoad = false;

    /**
     * Devuelve el _id del registro
     * 
     * @return id del registro
     */
    public long getId() {
        return mId;
    }

    /**
     * Devuelve la tabla de la entidad
     * 
     * @return tabla de la entidad
     */
    public String getTable() {
        return mTable;
    }

    /**
     * Devuelve si es una actualizacin del registro
     * 
     * @return true si es una actualizacin
     */
    public boolean isUpdate() {
        return (mId < 0) ? false : true;
    }

    /**
      * Devuelve si es un nuevo de registro
      * 
      * @return true si es una nuevo registro
      */
    public boolean isInsert() {
        return (mId < 0) ? true : false;
    }

    /**
      * Devuelve el valor a un atributo en tipo entero
      * 
      * @param name nombre del campo
      * @return valor del campo (Tipo int)
      */
    public int getInt(String name) {
        Object obj = getValue(name);
        if (obj == null)
            return 0;
        else
            return Integer.parseInt(obj.toString());
    }

    /**
      * Devuelve el valor a un atributo en tipo String
      * 
      * @param name nombre del campo
      * @return valor del campo (Tipo String)
      */
    public String getString(String name) {
        Field f = getTableObject().getField(name);
        if (f.getType().equals("string-identifier")) {
            return DataCloud.getInstance().getStringFromIdentifier(getValue(name).toString());
        } else {
            Object obj = getValue(name);
            if (obj == null)
                return "";
            else
                return obj.toString();
        }
    }

    /**
      * Devuelve el idenfificador del recurso en la aplicacin
      * 
      * @param name nombre del campo
      * @return valor (Tipo int)
      */
    public int getDrawableIdentifier(String name) {
        int id = DataCloud.getInstance().getContext().getResources().getIdentifier(
                DataCloud.getInstance().getPackage() + ":drawable/" + getValue(name).toString(), null, null);
        return id;
    }

    /**
      * Devuelve un bitmap del recurso en la aplicacin
      * 
      * @param name nombre del campo
      * @return valor (Tipo bitmap)
      */
    public Bitmap getBitmap(String name) {
        int id = DataCloud.getInstance().getContext().getResources().getIdentifier(
                DataCloud.getInstance().getPackage() + ":drawable/" + getValue(name).toString(), null, null);
        java.io.InputStream is = DataCloud.getInstance().getContext().getResources().openRawResource(id);
        BitmapDrawable bmd = new BitmapDrawable(BitmapFactory.decodeStream(is));
        return bmd.getBitmap();
    }

    /**
      * Devuelve un BitmapDrawable del recurso en la aplicacin
      * 
      * @param name nombre del campo
      * @return valor (Tipo BitmapDrawable)
      */
    public BitmapDrawable getBitmapDrawable(String name) {
        int id = DataCloud.getInstance().getContext().getResources().getIdentifier(
                DataCloud.getInstance().getPackage() + ":drawable/" + getValue(name).toString(), null, null);
        java.io.InputStream is = DataCloud.getInstance().getContext().getResources().openRawResource(id);
        BitmapDrawable bmd = new BitmapDrawable(BitmapFactory.decodeStream(is));
        return bmd;
    }

    /**
      * Devuelve un objeto Drawable del recurso en la aplicacin
      * 
      * @param name nombre del campo
      * @return valor (Tipo Drawable)
      */
    public Drawable getDrawable(String name) {
        int id = DataCloud.getInstance().getContext().getResources().getIdentifier(
                DataCloud.getInstance().getPackage() + ":drawable/" + getValue(name).toString(), null, null);
        return DataCloud.getInstance().getContext().getResources().getDrawable(id);
    }

    /**
     * Devuelve un string de la entidad. Formato obtenido del archivo XML
     * 
     * @return string
     */
    @Override
    public String toString() {
        String[] arString = DataCloud.getInstance().getTable(mTable).getToString().split("%");
        String out = "";
        for (int i = 0; i < arString.length; i++) {
            if (isAttribute(arString[i])) {
                Field f = getTableObject().getField(arString[i]);
                if (f.getType().equals("foreign-key"))
                    out += getEntity(arString[i]).toString();
                else
                    out += getString(arString[i]);
            } else if (arString[i].equals(DataCloud.KEY_ID)) {
                out += getId();
            } else {
                out += arString[i];
            }
        }
        return out;
    }

    /**
     * Devuelve el _id que queremos forzar al guardar la entidad
     * 
     * @return id a forzar
     */

    public long getForceId() {
        return mForceId;
    }

    /**
     * Establece el _id que queremos forzar al guardar la entidad
     * 
     * @param forceId identificador
     */

    public void setForceId(long forceId) {
        this.mForceId = forceId;
    }

    public Table getTableObject() {
        return DataCloud.getInstance().getTable(mTable);
    }

    /**
      * Devuelve el valor a un atributo en tipo entero largo
      * 
      * @param name nombre del campo
      * @return valor del campo (Tipo int)
      */
    public long getLong(String name) {
        Object obj = getValue(name);
        if (obj == null)
            return 0;
        else
            return Long.parseLong(obj.toString());
    }

    public double getDouble(String name) {
        Object obj = getValue(name);
        return obj == null ? 0.0 : Double.parseDouble(obj.toString());
    }

    public float getFloat(String name) {
        Object obj = getValue(name);
        return obj == null ? 0.0f : Float.parseFloat(obj.toString());
    }

    /**
     * Aade los atributos desde el objeto table.
     * Se llama desde el constructor. 
     */
    private void addAllAttributesFromTable() {
        Table t = getTableObject();
        for (int i = 0; i < t.getFields().size(); i++) {
            Field f = t.getFields().get(i);
            mAttributes.put(f.getName(), null);
        }
    }

    /**
     * Carga los valores creando un cursor.l  
     */
    protected void loadData() {
        HttpGet request = new HttpGet(DataCloud.getInstance().getURLLoadData(mTable, mId));
        HttpClient client = new DefaultHttpClient();
        HttpResponse httpResponse;
        try {
            httpResponse = client.execute(request);
            String ent = EntityUtils.toString(httpResponse.getEntity());
            JSONObject jsonObject = new JSONObject(ent);

            HashMap<String, Object> attribs = mAttributes;
            Object[] attributeNames = attribs.keySet().toArray();
            int attributeCount = attributeNames.length;

            for (int i = 0; i < attributeCount; i++) {
                String attributeName = attributeNames[i].toString();
                Field f = getTableObject().getField(attributeName);

                if (f.getType().equals("text") || f.getType().equals("string-identifier")
                        || f.getType().equals("drawable-identifier"))
                    attribs.put(attributeName, jsonObject.getJSONObject("user").getString(attributeName));
                else if (f.getType().equals("int"))
                    attribs.put(attributeName, jsonObject.getJSONObject("user").getInt(attributeName));
                else if (f.getType().equals("foreign-key"))
                    attribs.put(attributeName, jsonObject.getJSONObject("user").getInt(attributeName));
                else if (f.getType().equals("real"))
                    attribs.put(attributeName, jsonObject.getJSONObject("user").getDouble(attributeName));
                else
                    attribs.put(attributeName, jsonObject.getJSONObject("user").getString(attributeName));

            }
            errorLoad = false;
        } catch (Exception e) {
            e.printStackTrace();
            errorLoad = true;
        }
    }

    /**
    * Constructor - toma como valor el nombre de tabla de la entidad. Solo para nuevos registros 
    * 
    * @param table la tabla de la entidad
    */
    public Entity(String table) {
        this.mTable = table;
        mForceId = -1;
        addAllAttributesFromTable();
    }

    /**
    * Constructor - toma como valor el nombre de tabla de la entidad y un identificador. 
    * Solo para actualizaciones de registros
    * 
    * @param table la tabla de la entidad
    * @param id el identificador de la entidad
    */
    public Entity(String table, Long id) {
        this.mTable = table;
        mForceId = -1;
        if (id > 0)
            this.mId = id;
        addAllAttributesFromTable();
        loadData();
    }

    /**
      * Estable el valor a un atributo
      * 
      * @param name nombre del campo
      * @param value valor del campo
      */
    public void setValue(String name, Object value) {
        if (Entity.class.isInstance(value))
            mAttributes.put(name, ((Entity) value).getId());
        else
            mAttributes.put(name, value);
    }

    /**
      * Estable el valor a un atributo multilenguaje
      * 
      * @param name nombre del campo
      * @param value valor del campo
      */
    public void setMultilanguageValue(String name, String lang, Object value) {
        mMultilanguagesAttributes.put(name + "_" + lang, value);
    }

    /**
      * Devuelve el valor a un atributo
      * 
      * @param name nombre del campo
      * @return valor del campo (Tipo Object)
      */
    public Object getValue(String name) {
        return mAttributes.get(name);
    }

    /**
      * Devuelve el valor a un atributo en tipo Entity. Para claves foraneas.
      * Creamos el objeto a partir del ID almacenado en el campo.
      * 
      * @param name nombre del campo
      * @return valor del campo (Tipo Entity)
      */
    public Entity getEntity(String name) {
        Field f = getTableObject().getField(name);
        if (f != null && f.getType().equals("foreign-key"))
            return new Entity(f.getForeignTable(), getLong(name));
        else
            return null;
    }

    /**
      * Comprueba si el campo pasado por parmetro es un atributo de la entidad
      * 
      * @param name nombre del campo
      * @return true si es un campo
      */
    public boolean isAttribute(String name) {
        return getTableObject().getField(name) != null;
    }

    /**
     * Indica si un atributo es nulo 
     * @param name
     * @return si o no.
     */
    public boolean isNull(String name) {
        return mAttributes.get(name) == null;
    }

    /**
     * Indica si ha existido un error al cargar los datos
     * @return si o no.
     */
    public boolean isErrorLoad() {
        return errorLoad;
    }

    /**
     * Guarda una fila en la base de datos. Si _id es -1 es un nuevo registro, otra cosa una actualizacin
     * 
     * @return id or -1 if failed
     */
    public boolean save() {
        try {

            if (isInsert()) {
                return true;
            } else {
                //SimpleClient client = new SimpleClient(null, null, DataCloud.getInstance().getServer());
                //client.put(DataCloud.getInstance().getPathLoadData(mTable, mId), payload);

                //System.out.println(DataCloud.getInstance().getURLLoadData(mTable, mId));
                URL url = new URL(DataCloud.getInstance().getURLLoadData(mTable, mId));
                HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
                /*for (Field field : getTableObject().getFields())   {
                   String value = getString(field.getName());
                   //System.out.println(field.getName() + " = " + value);
                   if (value != null) {
                      httpCon.addRequestProperty(field.getName(), value);
                   }
                }*/
                String data = "{\"user\":{\"name\":\"alfonsolo\",\"id\":1,\"email\":\"yo@alfonsojimenez.com\"}}";
                httpCon.setDoInput(true);
                httpCon.setDoOutput(true);
                httpCon.setRequestMethod("PUT");
                httpCon.connect();

                OutputStream out = httpCon.getOutputStream();
                out.write(data.getBytes("UTF-8"));
                out.flush();
                /*
                final BufferedReader in = new BufferedReader(new InputStreamReader(httpCon.getInputStream(), "UTF-8"));
                final StringBuilder result = new StringBuilder();
                String line = in.readLine();
                while (line != null) {
                   result.append(line).append("\n");
                   line = in.readLine();
                }
                in.close();*/

                httpCon.disconnect();

                //System.out.println("result: "+result.toString());
                return true;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * Borra una fila
     * 
     * @return "true" si es borrada, "false" otra cosa
     */
    public boolean delete() {
        try {
            URL url = new URL(DataCloud.getInstance().getURLLoadData(mTable, mId));
            HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
            httpCon.setDoOutput(true);
            httpCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpCon.setRequestMethod("DELETE");
            httpCon.connect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }

}