Package com.onpositive.gae.baseviewer

Source Code of com.onpositive.gae.baseviewer.DataStoreTableUI$NamespacesRealm

package com.onpositive.gae.baseviewer;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.DriverPropertyInfo;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.Statement;
import java.sql.Types;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.logging.Logger;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.eclipse.core.internal.resources.XMLWriter;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuCreator;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.MessageDialogWithToggle;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Spinner;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.xml.sax.AttributeList;
import org.xml.sax.HandlerBase;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.images.Composite;
import com.google.apphosting.api.ApiProxy;
import com.onpositive.commons.elements.AbstractUIElement;
import com.onpositive.commons.elements.CTabFolderElement;
import com.onpositive.commons.elements.Container;
import com.onpositive.commons.elements.LinkElement;
import com.onpositive.commons.elements.SWTEventListener;
import com.onpositive.commons.ui.appearance.HorizontalLayouter;
import com.onpositive.commons.ui.appearance.OneElementOnLineLayouter;
import com.onpositive.commons.ui.dialogs.InputElementDialog;
import com.onpositive.commons.ui.dialogs.TitledDialog;
import com.onpositive.commons.ui.tableeditor.Field;
import com.onpositive.commons.ui.tableeditor.Filter;
import com.onpositive.commons.ui.tableeditor.OperationCallback;
import com.onpositive.commons.ui.tableeditor.Query;
import com.onpositive.commons.ui.tableeditor.Sort;
import com.onpositive.gae.baseviewer.BaseDataFacade.CGAEField;
import com.onpositive.gae.baseviewer.BaseDataFacade.Callback;
import com.onpositive.gae.baseviewer.BaseDataFacade.PGAEField;
import com.onpositive.gae.baseviewer.BaseStatistics.KindInfo;
import com.onpositive.gae.baseviewer.EditorUtility.IUpdateList;
import com.onpositive.gae.baseviewer.ImportExportDialogs.ExportData;
import com.onpositive.gae.baseviewer.ImportExportDialogs.ImportData;
import com.onpositive.gae.baseviewer.Request.State;
import com.onpositive.gae.baseviewer.requests.SimpleRequest;
import com.onpositive.gae.tools.UIUtils;
import com.onpositive.gae.tools.license.LicenseChecker;
import com.onpositive.semantic.model.api.property.IStatusChangeListener;
import com.onpositive.semantic.model.api.property.IValueListener;
import com.onpositive.semantic.model.api.property.adapters.ITextLabelProvider;
import com.onpositive.semantic.model.api.property.adapters.TextProviderAdapter;
import com.onpositive.semantic.model.api.property.java.annotations.Caption;
import com.onpositive.semantic.model.binding.Binding;
import com.onpositive.semantic.model.binding.IBinding;
import com.onpositive.semantic.model.realm.CodeAndMessage;
import com.onpositive.semantic.model.realm.OrderedRealm;
import com.onpositive.semantic.model.realm.Realm;
import com.onpositive.semantic.model.realm.ValidatorAdapter;
import com.onpositive.semantic.model.ui.property.IPropertyEditor;
import com.onpositive.semantic.model.ui.property.editors.ButtonSelector;
import com.onpositive.semantic.model.ui.property.editors.CompositeEditor;
import com.onpositive.semantic.model.ui.property.editors.DisposeBindingListener;
import com.onpositive.semantic.model.ui.property.editors.OneLineTextElement;
import com.onpositive.semantic.model.ui.property.editors.structured.ComboEnumeratedValueSelector;
import com.onpositive.semantic.model.ui.property.editors.structured.ListEnumeratedValueSelector;

public class DataStoreTableUI {

  public final static String PREF_REMEMBER_DECISION = "remember_decision_export";
  public final static String PREF_EXPORT = "show_confirm_dialog_export";

  public class DriverWrapper implements Driver {

    private Driver driver;

    public DriverWrapper(Driver dr) {
      driver = dr;
    }

    public boolean acceptsURL(String arg0) throws SQLException {
      return driver.acceptsURL(arg0);
    }

    public Connection connect(String arg0, Properties arg1)
        throws SQLException {
      return driver.connect(arg0, arg1);
    }

    public int getMajorVersion() {
      return driver.getMajorVersion();
    }

    public int getMinorVersion() {
      return driver.getMinorVersion();
    }

    public DriverPropertyInfo[] getPropertyInfo(String arg0, Properties arg1)
        throws SQLException {
      return driver.getPropertyInfo(arg0, arg1);
    }

    public boolean jdbcCompliant() {
      return driver.jdbcCompliant();
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
      return Logger.getGlobal();
    }

  }

  public class JDBCSaver extends DataSaver {

    private JDBCTypeTranslator translator;

    private class JDBCTypeTranslator {
      public HashMap<String, String> translateTypesToSQL(
          HashMap<String, String> old) {
        HashMap<String, String> result = new HashMap<String, String>();
        Set keySet = old.keySet();
        for (Iterator<String> i = keySet.iterator(); i.hasNext();) {
          String key = i.next();
          String oldType = old.get(key);
          String sqlType = getSQLType(oldType);
          result.put(key, sqlType);
        }
        return result;
      }

      public String getValueAsSQLData(Object value) {
        if (value == null) {
          return "NULL";
        }
        Class typeObj = value.getClass();
        if (typeObj == String.class) {
          return "\'" + (String) value + "\'";
        } else if (typeObj == java.util.Date.class) {
          return translator.formatValueToSQLString(new java.sql.Date(
              ((Date) value).getTime()).toString(),
              "java.util.Date");
        } else {
          return formatValueToSQLString(
              StringInputOutput.toString(value), value.getClass()
                  .getCanonicalName());
        }
      }

      public void insertValueToQuery(PreparedStatement stat, int index,
          Object value, String type) {
        try {

          if (value == null) {
            if (type.equals("VARCHAR(" + maxSizeOfColumns + ")")) {
              stat.setNull(index, Types.VARCHAR);
            } else if (type.equals("DATE")) {
              stat.setNull(index, Types.DATE);
            } else if (type.equals("BIT")) {
              stat.setNull(index, Types.BIT);
            } else if (type.equals("TINYINT")) {
              stat.setNull(index, Types.TINYINT);
            } else if (type.equals("BIGINT")) {
              stat.setNull(index, Types.BIGINT);
            } else if (type.equals("SMALLINT")) {
              stat.setNull(index, Types.SMALLINT);
            } else if (type.equals("REAL")) {
              stat.setNull(index, Types.REAL);
            } else if (type.equals("DOUBLE")) {
              stat.setNull(index, Types.DOUBLE);
            }
            return;
          }

          Class typeObj = Class.forName(type);
          if (typeObj == String.class) {
            stat.setString(index, (String) value);
          } else if (typeObj == java.util.Date.class) {
            stat.setDate(index,
                new java.sql.Date(((Date) value).getTime()));
          } else if (typeObj == Boolean.class) {
            stat.setBoolean(index, (Boolean) value);
          } else if (typeObj == Byte.class) {
            stat.setByte(index, (Byte) value);
          } else if (typeObj == Long.class) {
            stat.setLong(index, (Long) value);
          } else if (typeObj == Short.class) {
            stat.setShort(index, (Short) value);
          } else if (typeObj == Float.class) {
            stat.setFloat(index, (Float) value);
          } else if (typeObj == Double.class) {
            stat.setDouble(index, (Double) value);
          } else {
            String val = StringInputOutput.toString(value);
            stat.setString(index, val);
          }

        } catch (ClassNotFoundException e) {
          e.printStackTrace();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }

      public String formatValueToSQLString(String value, String type) {
        Class typeObj;
        try {
          typeObj = Class.forName(type);
          if (typeObj == String.class) {
            return "\'" + value + "\'";
          } else if (typeObj == java.util.Date.class) {
            return "\'" + value + "\'";// value
          } else if (typeObj == Boolean.class) {
            return value;
          } else if (typeObj == Byte.class) {
            return value;
          } else if (typeObj == Long.class) {
            return value;
          } else if (typeObj == Short.class) {
            return value;
          } else if (typeObj == Float.class) {
            return value;
          } else if (typeObj == Double.class) {
            return value;
          } else {
            return "\'" + value + "\'";
          }
        } catch (ClassNotFoundException e) {
          e.printStackTrace();
        }
        return "unknown";
      }

      public boolean isSupported(Class type) {
        if (type == null) {
          return false;
        }
        if (type == String.class) {
          return true;
        } else if (type == java.util.Date.class) {
          return true;
        } else if (type == Boolean.class) {
          return true;
        } else if (type == Byte.class) {
          return true;
        } else if (type == Long.class) {
          return true;
        } else if (type == Short.class) {
          return true;
        } else if (type == Float.class) {
          return true;
        } else if (type == Double.class) {
          return true;
        } else {
          return false;
        }

      }

      private String getSQLType(String javaType) {
        try {
          if (javaType.equals("null")) {
            return "VARCHAR(" + maxSizeOfColumns + ")";
          }

          Class typeObj = Class.forName(javaType);
          if (typeObj == String.class) {
            return "VARCHAR(" + maxSizeOfColumns + ")";
          } else if (typeObj == java.util.Date.class) {
            return "DATE";
          } else if (typeObj == Boolean.class) {
            return "BIT";
          } else if (typeObj == Byte.class) {
            return "TINYINT";
          } else if (typeObj == Long.class) {
            return "BIGINT";
          } else if (typeObj == Short.class) {
            return "SMALLINT";
          } else if (typeObj == Float.class) {
            return "REAL";
          } else if (typeObj == Double.class) {
            return "DOUBLE";
          } else {
            return "VARCHAR(2048)";
          }
        } catch (ClassNotFoundException e) {
          e.printStackTrace();
        }
        return "none";
      }

    }

    public JDBCSaver(BaseDataFacade facade) {
      super(facade);
      translator = new JDBCTypeTranslator();
    }

    public static final int ONLY_VARNAMES = 0;
    public static final int ONLY_TYPES = 1;
    public static final int TYPES_AND_VARNAMES = 2;
    public static final int PREPARED = 3;

    private HashMap<String, String> types;
    private HashMap<String, String> typesForSQLTable;
    private String connectionString;
    private String driverName;

    private String login;
    private String passwd;

    private int maxSizeOfColumns;

    public int getMaxSizeOfColumns() {
      return maxSizeOfColumns;
    }

    public void setMaxSizeOfColumns(int maxSizeOfColumns) {
      this.maxSizeOfColumns = maxSizeOfColumns;
    }

    private String kind;
    private Map libraries;
    private ArrayList<String> path;
    private String resourceName;

    public String getResourceName() {
      return resourceName;
    }

    public void setResourceName(String resourceName) {
      this.resourceName = resourceName;
    }

    public void setPath(ArrayList<String> path) {
      this.path = path;
    }

    public void setKind(String kind) {
      this.kind = kind;
    }

    public void setConnectionProperties(String connectionString,
        String login, String passwd) {
      this.connectionString = connectionString;
      if (login != null) {
        this.login = login;
      } else {
        this.login = "";
      }
      if (passwd != null) {
        this.passwd = passwd;
      } else {
        this.passwd = "";
      }
    }

    public void setDriverName(String driverName) {
      this.driverName = driverName;
    }

    public void setTypes(HashMap<String, String> types) {
      this.types = (HashMap<String, String>) types.clone();
    }

    private void loadDriver() {
      try {
        ClassLoader loader = ClassLoader.getSystemClassLoader();
        URL[] urls = new URL[path.size()];
        int j = 0;
        for (Iterator<String> i = path.iterator(); i.hasNext();) {
          String tmp = i.next();
          // File f = new File(tmp);
          urls[j] = new URL("jar:file:" + File.separator + tmp + "!/");// f.toURL();
          j++;
        }
        URLClassLoader ucl = new URLClassLoader(urls, loader);
        Driver d = (Driver) ucl.loadClass(driverName).newInstance();
        DriverManager.registerDriver(new DriverWrapper(d));

        typesForSQLTable = translator.translateTypesToSQL(types);
      } catch (Exception e) {
        showErrorDialog("The following error occured:"
            + e.getLocalizedMessage());
      }
    }

    public void initSaveProcedure() {
      loadDriver();
      HashMap<String, String> typesForSQLTable = translator
          .translateTypesToSQL(types);
      StringBuilder queryStringForFirstTable = new StringBuilder();
      queryStringForFirstTable.append("CREATE TABLE ");
      queryStringForFirstTable.append(kind);
      queryStringForFirstTable.append(" (");

      queryStringForFirstTable.append(getParametersOfTable(
          typesForSQLTable, TYPES_AND_VARNAMES));
      queryStringForFirstTable.append(", KEY(");
      queryStringForFirstTable.append(Entity.KEY_RESERVED_PROPERTY);
      queryStringForFirstTable.append("))");

      StringBuilder queryStringForSecondTable = new StringBuilder();
      queryStringForSecondTable.append("CREATE TABLE ");
      queryStringForSecondTable.append(kind);
      queryStringForSecondTable.append("_props (");
      queryStringForSecondTable.append(Entity.KEY_RESERVED_PROPERTY);
      queryStringForSecondTable.append(" VARCHAR(" + maxSizeOfColumns
          + "),");
      queryStringForSecondTable.append(" column_name ");
      queryStringForSecondTable.append("VARCHAR(" + maxSizeOfColumns
          + "), type VARCHAR(" + maxSizeOfColumns + "), KEY(");
      queryStringForSecondTable.append(Entity.KEY_RESERVED_PROPERTY);
      queryStringForSecondTable.append(", column_name))");

      try {

        Connection connect = DriverManager.getConnection(
            connectionString, login, passwd);

        DatabaseMetaData dmd = connect.getMetaData();
        String[] tableTypes = new String[] { "TABLE" };
        ResultSet rs = dmd.getTables(connect.getCatalog(), null, null,
            tableTypes);
        ArrayList<String> tables = new ArrayList<String>();
        while (rs.next()) {
          tables.add(rs.getString("TABLE_NAME"));
        }
        if (tables.contains(kind.toLowerCase())
            || tables.contains(kind.toUpperCase())
            || tables.contains(kind)) {
          Statement stat = connect.createStatement();
          stat.executeUpdate("DROP TABLE " + kind);
        }
        if (tables.contains((kind + "_props").toLowerCase())
            || tables.contains((kind + "_props").toUpperCase())
            || tables.contains((kind + "_props"))) {
          Statement stat = connect.createStatement();
          stat.executeUpdate("DROP TABLE " + kind.toLowerCase()
              + "_props");
        }

        Statement stat = connect.createStatement();
        stat.executeUpdate(queryStringForFirstTable.toString());
        stat.executeUpdate(queryStringForSecondTable.toString());
        stat.close();
        connect.close();
      } catch (SQLException e) {
        showErrorDialog("The following error occured:"
            + e.getLocalizedMessage());
      }
    }

    private String getParametersOfTable(
        HashMap<String, String> typesForSQLTable, int style) {
      StringBuilder formatted = new StringBuilder();
      Set<String> keys = typesForSQLTable.keySet();
      int it = 0;
      for (Iterator<String> i = keys.iterator(); i.hasNext();) {

        String key = i.next();
        String value = typesForSQLTable.get(key);
        if (style == TYPES_AND_VARNAMES) {
          formatted.append(key + " " + value);
        } else if (style == ONLY_VARNAMES) {
          formatted.append(key);
        } else if (style == ONLY_TYPES) {
          formatted.append(value);
        } else if (style == PREPARED) {
          formatted.append("?");
        }

        if (it != keys.size() - 1) {
          formatted.append(", ");
        } else {
          formatted.append(" ");
        }
        it++;
      }
      return formatted.toString();
    }

    public void save(Entity[] data) {
      try {
        Connection connection = DriverManager
            .getConnection(connectionString);
        Statement stat = connection.createStatement();

        String formattedParametersString = getParametersOfTable(
            typesForSQLTable, ONLY_VARNAMES);

        StringBuilder insertStrFirst = new StringBuilder();

        insertStrFirst.append("INSERT INTO ");
        insertStrFirst.append(kind);
        insertStrFirst.append("( ");
        insertStrFirst.append(formattedParametersString);
        insertStrFirst.append(") VALUES (");

        formattedParametersString = getParametersOfTable(
            typesForSQLTable, PREPARED);
        insertStrFirst.append(formattedParametersString + ")");

        PreparedStatement insOne = connection
            .prepareStatement(insertStrFirst.toString());

        StringBuilder insertStrSecond = new StringBuilder();
        insertStrSecond.append("INSERT INTO ");
        insertStrSecond.append(kind);
        insertStrSecond.append("_props ( ");
        insertStrSecond.append(Entity.KEY_RESERVED_PROPERTY);
        insertStrSecond.append(", column_name, type ) VALUES (");
        insertStrSecond.append("?,?,? )");

        PreparedStatement insTwo = connection
            .prepareStatement(insertStrSecond.toString());
        StringBuilder valuesFirst = new StringBuilder();

        // foreach entity
        for (Entity elem : data) {
          String[] unsupported = fillUpdateQueryForEntity(elem,
              insOne);

          for (String current : unsupported) {
            String[] values = StringInputOutput.split(current, ':');
            if (values.length != 3) {
              throw new Exception("Parsing error");
            }

            String k = values[0].replaceAll("\\:", ":");
            String c = values[1].replaceAll("\\:", ":");
            String t = values[2].replaceAll("\\:", ":");

            insTwo.setString(1, k);
            insTwo.setString(2, c);
            insTwo.setString(3, t);

            insTwo.executeUpdate();
          }

          insOne.executeUpdate();
        }
        connection.close();
      } catch (SQLException e) {
        showErrorDialog("Error occured:" + e.getLocalizedMessage());
      } catch (Exception e) {
        showErrorDialog("Error occured:" + e.getLocalizedMessage());
      }
    }

    private String[] fillUpdateQueryForEntity(Entity elem,
        PreparedStatement stat) {
      ArrayList<String> unsupported = new ArrayList<String>();

      Key key = elem.getKey();
      String type = key.getClass().getCanonicalName();
      String keyType = type;

      // format unsupported value
      String valueOfKey = StringInputOutput.toString(key);
      unsupported.add(valueOfKey.replaceAll(":", "\\:") + ":"
          + Entity.KEY_RESERVED_PROPERTY + ":"
          + type.replaceAll(":", "\\:"));

      Map<String, Object> p = elem.getProperties();
      Set<String> props = p.keySet();
      int k = 1;
      for (Iterator<String> i = typesForSQLTable.keySet().iterator(); i
          .hasNext();) {

        String currProperty = i.next();
        if (currProperty.equals(Entity.KEY_RESERVED_PROPERTY)) {
          translator.insertValueToQuery(stat, k, key, keyType);
          k++;
          continue;
        }

        Object valueOfProp = p.get(currProperty);
        Class typeOfProp = null;

        if (valueOfProp != null) {
          type = valueOfProp.getClass().getCanonicalName();
          translator.insertValueToQuery(stat, k, valueOfProp, type);
          typeOfProp = valueOfProp.getClass();
        } else {
          translator.insertValueToQuery(stat, k, null,
              typesForSQLTable.get(currProperty));
        }

        if (!translator.isSupported(typeOfProp)) {
          type = StringInputOutput.typeToString(valueOfProp);
          unsupported.add(valueOfKey.replaceAll(":", "\\:") + ":"
              + currProperty.replaceAll(":", "\\:") + ":"
              + type.replaceAll(":", "\\:"));
        }
        k++;
      }
      return unsupported.toArray(new String[unsupported.size()]);
    }

    public void onFinish() {
      String filePath = getResourceName();
      File resource = new File(filePath);
      resource.delete();
    }

  }

  public abstract class DataSaver {
    private BaseDataFacade facade;
    private long size;

    public long getSize() {
      return size;
    }

    public void setSize(long size) {
      this.size = size;
    }

    private IProgressMonitor monitor;

    public void setMonitor(IProgressMonitor monitor) {
      this.monitor = monitor;
    }

    public IProgressMonitor getMonitor() {
      return monitor;
    }

    public void init(BaseDataFacade facade) {
      this.facade = facade;
    }

    public BaseDataFacade getFacade() {
      return facade;
    }

    public DataSaver(BaseDataFacade facade) {
      this.facade = facade;
    }

    public abstract void save(Entity[] data);

    public abstract void onFinish();
  }

  public final static String LINE_SEPARATOR = (String) System
      .getProperty("line.separator");

  private static final String PROPS_SUFFIX = "_props";

  public interface IWriter {
    void beginWriting(String outputResource, long entitiesCount);

    void writeData(Entity[] entities, String outputResource);

    void stopWriting(String output);

    String getFileExtension();
  }

  public interface IReader {
    void readData(String input, DataSaver saver, int numberOfReaded);
  }

  private class CallBackForImportDataImpl implements Callback {

    private ArrayList<Entity> values = new ArrayList<Entity>();

    private boolean hasError = false;

    public boolean objectFetched(Object object) {
      if (object instanceof Entity) {
        if (!values.contains((Entity) object)) {
          values.add((Entity) object);
        }
      } else if (object instanceof State) {
        State state = (State) object;
        if (state.message != null && state.trace != null) {
          hasError = true;
        }
      }
      return true;
    }

    public boolean hasErrors() {
      return hasError;
    }

    public ArrayList<Entity> getEntities() {
      if (!hasError) {
        return values;
      }
      return null;
    }

    public void clear() {
      hasError = false;
      values = new ArrayList<Entity>();
    }

  }

  private class ExportJob extends Job {

    private final static int SIZE_OF_READED = 100;

    private IReader reader;
    private ExportData data;
    private DataSaver saver;

    public void init(IReader reader, ExportData data, DataSaver saver) {
      this.reader = reader;
      this.data = data;
      this.saver = saver;
    }

    public ExportJob(String name) {
      super(name);
    }

    protected IStatus run(IProgressMonitor monitor) {
      // setUser(false);
      ApiProxy.setEnvironmentForCurrentThread(new FakeEnvironment(
          getAppId()));
      if (reader == null || data == null || saver == null) {
        return Status.CANCEL_STATUS;
      }
      monitor.beginTask("Export in process...", 100);
      saver.setMonitor(monitor);
      reader.readData(data.outPut, saver, SIZE_OF_READED);

      return Status.OK_STATUS;
    }

  }

  private class ImportJob extends Job {

    private static final int EXCEPTION = 2;
    private static final int NO_ERRORS = 0;
    private static final int CALLBACK_ERRORS = 1;
    private static final int NUMBER_OF_CALLBACK_ERRORS = 10;
    private static final String PRIMARY_KEY = "ONPOSITIVE_FILTER_FOR_PRIMARY_KEY";

    private BaseDataFacade currFacade;

    private ImportData parameters;
    private IWriter writer;

    private int callBackErrorsCount = 0;

    private int numberOfEntities = 0;
    private int currentSize = 0;
    private int numberOfRequests = 0;

    private long allEntities;
    private double progressSize;

    private Key offset = null;

    public void setWriter(IWriter writer) {
      this.writer = writer;
    }

    public void setParameters(ImportData parameters) {
      this.parameters = parameters;
    }

    public void setFacade(BaseDataFacade facade) {
      this.currFacade = facade;
    }

    public ImportJob(String name) {
      super(name);
    }

    protected IStatus run(IProgressMonitor monitor) {
      try {
        if (parameters == null || writer == null || currFacade == null) {
          return Status.CANCEL_STATUS;
        }
        SimpleRequest req = null;
        if (parameters.filterColumns && parameters.selectedEntitiesOf) {
          Query query = currFacade.getCurrentQuery();
          int limit = currFacade.getLimit();
          String kind = currFacade.getKind();
          req = new SimpleRequest(kind, query, limit);
        }

        // Initialization of progress bar:
        BaseStatistics stats = null;
        if (!facade.isDebug()) {
          stats = BaseStatistics.query(currFacade.getProject(),
              new NullProgressMonitor(), false,
              currFacade.getNamespace());
        }
        if (stats != null) {
          if (stats.map != null) {
            KindInfo info = (KindInfo) stats.map.get(currFacade
                .getKind());
            if (info != null) {
              allEntities = info.entityCount;
              progressSize = 0;
            }
          }
        } else {
          allEntities = 0;
          progressSize = 1;
        }
        writer.beginWriting(parameters.outPut, allEntities);
        Sort sort = new Sort(Entity.KEY_RESERVED_PROPERTY, true);

        CallBackForImportDataImpl cb = new CallBackForImportDataImpl();
        int returningCode = -1;
        currentSize = currFacade.getLimit();
        while (callBackErrorsCount < NUMBER_OF_CALLBACK_ERRORS) {
          try {
            returningCode = pageReading(sort, cb, monitor,
                currFacade, req);
            if (returningCode == NO_ERRORS) {
              break;
            } else if (returningCode == CALLBACK_ERRORS) {
              currentSize = (currentSize) / 2 + 1;
              // progressSize -= 1;
              callBackErrorsCount++;
            } else if (returningCode == EXCEPTION) {
              break;
            }
          } catch (Exception e) {
            Activator.log(e);
            callBackErrorsCount++;

            currentSize = (currentSize) / 2 + 1;
            // progressSize -= 1;

            if (callBackErrorsCount == NUMBER_OF_CALLBACK_ERRORS) {
              showErrorDialog("Unable to read data from data storage:\n The following exception was thrown:\n"
                  + e.getMessage());
              Display.getCurrent().asyncExec(new Runnable() {

                public void run() {
                  if (MessageDialog
                      .openConfirm(Display.getCurrent()
                          .getActiveShell(),
                          "Problem",
                          "Do you want continue retrieving data from data storage?")) {
                    callBackErrorsCount = 0;
                  }
                }
              });
            }
          }
        }
        if (callBackErrorsCount == NUMBER_OF_CALLBACK_ERRORS
            && returningCode == CALLBACK_ERRORS) {
          showErrorDialog("Unable to read data from data storage: Status incorrect");
        }

        int endW = 100 - (int) progressSize;
        if (endW > 0) {
          monitor.worked(endW);
        }
        writer.stopWriting(parameters.outPut);
        return Status.OK_STATUS;
      } catch (CloneNotSupportedException e) {
        showErrorDialog("Unable to read data from data storage:\n The following exception was thrown:\n"
            + e.getMessage());
      } catch (Exception e) {
        showErrorDialog("Unable to read data from data storage:\n The following exception was thrown:\n"
            + e.getMessage());
      }
      writer.stopWriting(parameters.outPut);
      return Status.OK_STATUS;
    }

    private int pageReading(Sort sort, CallBackForImportDataImpl cb,
        IProgressMonitor monitor, BaseDataFacade cFacade,
        SimpleRequest req) throws Exception {

      ArrayList<Entity> recieved = null;
      int count = 0;
      do {
        monitor.internalWorked(progressSize);
        cFacade.setLimit(currentSize - 1);
        monitor.setTaskName("Status: Requests sended - "
            + numberOfRequests + "; Entities imported - "
            + numberOfEntities + "; Current buffer size - "
            + (currentSize) + "");
        Query newQuery = null;
        if (offset != null) {
          Filter filt = new Filter(PRIMARY_KEY, Filter.GREATER,
              offset);
          newQuery = new Query(new Filter[] { filt }, sort, 1000, 0);
        } else {
          newQuery = new Query(new Filter[0], sort, 1000, 0);
        }
        monitor.subTask("\nExtracting data from data storage...");
        cFacade.query(newQuery, cb, new NullProgressMonitor(), true);
        numberOfRequests++;
        if (cb.hasError) {
          cb.clear();
          // result.clear();
          return CALLBACK_ERRORS;
        } else {
          recieved = cb.getEntities();
          if (recieved != null && recieved.size() != 0) {
            // if req != null we should filter data before it
            // will be written
            // Key nextOffset = recieved.get(recieved.size() - 1)
            // .getKey();
            // if (offset != null) {
            // if (nextOffset.compareTo(offset) >= 0) {
            // break;
            // } else {
            // offset = nextOffset;
            // }
            // } else {
            offset = recieved.get(recieved.size() - 1).getKey();
            // }
            // offset = recieved.get(recieved.size() - 1).getKey();
            cFacade.objects.add(recieved.get(recieved.size() - 1));
            int allSize = recieved.size();
            cb.clear();
            accept(recieved, req);
            numberOfEntities += recieved.size();
            monitor.subTask("\nWriting data to resource"
                + parameters.outPut + "...");
            writer.writeData(
                recieved.toArray(new Entity[recieved.size()]),
                parameters.outPut);
            callBackErrorsCount = 0;
            if (allEntities != 0) {
              progressSize = ((((double) allSize) / ((double) allEntities)) * 100);
            }
            count++;
            if (count == 5) {
              currentSize *= 2;
              count = 0;
            }
          }
        }

      } while (recieved != null && recieved.size() != 0);

      return NO_ERRORS;
    }

    private void accept(ArrayList<Entity> readed, SimpleRequest req) {
      if (req != null) {
        ArrayList<Entity> filtered = new ArrayList();
        for (Entity tmp : readed) {
          if (req.accept(tmp)) {
            filtered.add(tmp);
          }
        }
        if (filtered.size() == 0) {
          readed.clear();
        } else {
          readed.retainAll(filtered);
        }
      }
    }
  }

  private class CsvWriterImpl implements IWriter {

    private ImportData data;

    public CsvWriterImpl(ImportData data) {
      this.data = data;
    }

    public void writeData(Entity[] entities, String outputResource) {
      try {
        // DataOutputStream dOs_out = new DataOutputStream(
        // new FileOutputStream(outputResource, true));
        BufferedWriter dOs_out = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(
                outputResource, true), "UTF-8"));

        // DataOutputStream dOs_prop = new DataOutputStream(
        // new FileOutputStream(data.outPut + PROPS_SUFFIX, true));
        BufferedWriter dOs_prop = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(
                outputResource + PROPS_SUFFIX, true), "UTF-8"));

        for (Entity tmp : entities) {
          StringBuilder outputStr = new StringBuilder();
          StringBuilder propsStr = new StringBuilder();
          Set<String> titleSet = tmp.getProperties().keySet();
          // writing a key
          Key key = tmp.getKey();
          String keyVal = StringInputOutput.toString(key);
          keyVal = encodeCSV(keyVal);
          outputStr.append(keyVal);
          propsStr.append(Entity.KEY_RESERVED_PROPERTY + ":"
              + key.getClass().getCanonicalName());
          if (titleSet.size() != 0) {
            outputStr.append(",");
            propsStr.append(",");
          }
          for (Iterator<String> i = titleSet.iterator(); i.hasNext();) {
            String next = i.next();
            Object valueToString = tmp.getProperty(next);
            if (valueToString == null) {
              outputStr.append("null");
              propsStr.append(next + ":" + "null");
            } else {
              String output = StringInputOutput
                  .toString(valueToString);
              output = encodeCSV(output);
              outputStr.append(output);
              if (valueToString instanceof Collection) {
                propsStr.append(next + ":");
                propsStr.append(valueToString.getClass()
                    .getCanonicalName() + "|");
                Collection col = (Collection) valueToString;
                for (Iterator it = col.iterator(); it.hasNext();) {
                  Object nxt = it.next();
                  if (nxt != null) {
                    String clName = nxt.getClass()
                        .getCanonicalName();
                    propsStr.append(clName);
                  } else {
                    propsStr.append("null");
                  }
                  propsStr.append("|");
                }
              } else {
                propsStr.append(next
                    + ":"
                    + valueToString.getClass()
                        .getCanonicalName());
              }
            }

            if (i.hasNext()) {
              outputStr.append(",");
              propsStr.append(",");
            }

          }

          dOs_out.write(outputStr.toString());
          dOs_out.write(LINE_SEPARATOR);

          dOs_prop.write(propsStr.toString());
          dOs_prop.write(LINE_SEPARATOR);
        }
        dOs_out.close();
        dOs_prop.close();
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    public void beginWriting(String outputResource, long entitiesCount) {
      FileOutputStream fOs1;
      try {
        fOs1 = new FileOutputStream(outputResource);
        // DataOutputStream dOs2 = new DataOutputStream(
        // new FileOutputStream(outputResource + PROPS_SUFFIX));
        BufferedWriter dOs2 = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(
                outputResource + PROPS_SUFFIX), "UTF-8"));
        dOs2.write("expected:" + entitiesCount + LINE_SEPARATOR);
        fOs1.close();
        dOs2.close();
      } catch (FileNotFoundException e) {
        showErrorDialog("Unable to write data to resource.\n The following exception was thrown:\n message: \n"
            + e.getLocalizedMessage());
      } catch (IOException e) {
        showErrorDialog("Unable to write data to resource.\n The following exception was thrown:\n"
            + e.getLocalizedMessage());
      }
    }

    public void stopWriting(String output) {
      // do nothing
    }

    private String encodeCSV(String old) {
      String lineSeparator = LINE_SEPARATOR;
      String tmp = old;
      tmp = tmp.replaceAll(",", "&ltcomma&gt");
      tmp = tmp.replaceAll("\\n", "\\\\n");
      tmp = tmp.replaceAll("\\r", "\\\\r");
      return tmp;
    }

    public String getFileExtension() {
      return ".csv";
    }
  }

  private class XmlWriterImpl implements IWriter {
    private static final String MAJOR_TAG = "entities";
    private static final String ENTITY_TAG = "entity";
    private static final String PROPERTY_TAG = "property";
    private static final String LIST_ELEMENT_TAG = "listElement";
    private static final String KIND_TAG = "kind";
    private static final String NAME_TAG = "name";
    private static final String VALUE_TAG = "value";
    private static final String CLASS_TAG = "type";
    private static final String ALL = "expected";
    private XMLWriter writer;
    private FileOutputStream fOs;

    public void writeData(Entity[] entities, String outputResource) {

      for (Entity tmp : entities) {
        String kind = tmp.getKind();
        HashMap entityMap = new HashMap();
        entityMap.put(KIND_TAG, kind);

        // Printing entitity opening tag
        writer.printTag(ENTITY_TAG, entityMap, true, true);
        Key key = tmp.getKey();
        String idKey = Entity.KEY_RESERVED_PROPERTY;
        String typeKey = key.getClass().getCanonicalName();
        String valueKey = StringInputOutput.toString(key);

        HashMap forKeyProp = new HashMap<String, String>();
        forKeyProp.put(NAME_TAG, idKey);
        forKeyProp.put(CLASS_TAG, typeKey);
        forKeyProp.put(VALUE_TAG, valueKey);

        writer.printTag(PROPERTY_TAG, forKeyProp, true, false);
        writer.endTag(PROPERTY_TAG);

        Map<String, Object> properties = tmp.getProperties();
        for (Iterator<String> i = properties.keySet().iterator(); i
            .hasNext();) {
          String next = i.next();
          Object value = properties.get(next);

          HashMap propsMap = new HashMap();
          if (value == null) {
            String id = next;
            String clazz = "null";
            String valStr = "null";
            propsMap.put(NAME_TAG, id);
            propsMap.put(CLASS_TAG, clazz);
            propsMap.put(VALUE_TAG, valStr);

            // Printing properties opening tag
            writer.printTag(PROPERTY_TAG, propsMap, true, false);
            writer.endTag(PROPERTY_TAG);
          } else if (value instanceof Collection) {

            String id = next;
            String clazz = value.getClass().getCanonicalName();
            propsMap.put(NAME_TAG, id);
            propsMap.put(CLASS_TAG, clazz);

            // Printing collection opening tag
            writer.printTag(PROPERTY_TAG, propsMap, true, true);

            Collection col = (Collection) value;
            propsMap.clear();
            for (Iterator it = col.iterator(); it.hasNext();) {
              Object nxt = it.next();
              if (nxt != null) {
                clazz = nxt.getClass().getCanonicalName();
                String val = StringInputOutput.toString(nxt);
                val = val.replaceAll(LINE_SEPARATOR, "\\\\n");
                propsMap.put(CLASS_TAG, clazz);
                propsMap.put(VALUE_TAG, val);
              } else {
                propsMap.put(CLASS_TAG, "null");
                propsMap.put(VALUE_TAG, "null");
              }

              // Printing collections elements
              // opening tag
              writer.printTag(LIST_ELEMENT_TAG, propsMap, true,
                  false);

              // closing tag
              writer.endTag(LIST_ELEMENT_TAG);
              propsMap.clear();
            }

            // closing tag
            writer.endTag(PROPERTY_TAG);
          } else {
            String id = next;
            String clazz = value.getClass().getCanonicalName();
            String valStr = StringInputOutput.toString(value);
            valStr = valStr.replaceAll(LINE_SEPARATOR, "\\\\n");
            propsMap.put(NAME_TAG, id);
            propsMap.put(CLASS_TAG, clazz);
            propsMap.put(VALUE_TAG, valStr);

            // Printing properties elements opening
            // tag
            writer.printTag(PROPERTY_TAG, propsMap, true, false);
            // closing tag
            writer.endTag(PROPERTY_TAG);
          }
        }
        writer.endTag(ENTITY_TAG);
      }

    }

    public void beginWriting(String outputResource, long entitiesCount) {
      try {

        fOs = new FileOutputStream(outputResource);
        writer = new XMLWriter(fOs);

        // Printing entities opening tag
        HashMap args = new HashMap<String, String>();
        args.put(ALL, entitiesCount + "");
        writer.printTag(MAJOR_TAG, args);
      } catch (FileNotFoundException e) {
        showErrorDialog("Unable to  write data to" + outputResource);
      } catch (UnsupportedEncodingException e) {
        showErrorDialog("Unable to  write data to" + outputResource);
      }
    }

    public void stopWriting(String output) {
      writer.endTag(MAJOR_TAG);
      writer.flush();
      writer.close();
      try {
        fOs.close();
      } catch (IOException e) {
        showErrorDialog("Unable to  write data to" + output);
      }

    }

    public String getFileExtension() {
      return ".xml";
    }
  }

  private class XmlReaderImpl implements IReader {
    private final class SpecialBase extends HandlerBase {
      private final String input;
      private final int numberOfReaded;
      private final DataSaver saver;
      private String currentKind;
      private Map<String, Object> currentProperties;
      private Collection currentCol = null;
      private String collParsing = null;

      private SpecialBase(String input, int numberOfReaded,
          DataSaver saver) {
        this.input = input;
        this.numberOfReaded = numberOfReaded;
        this.saver = saver;
      }

      public void startElement(String name, AttributeList attributes)
          throws SAXException {
        if (name.equals(MAJOR_TAG)) {
          // It's begun!!!!
          try {
            String fullSize = attributes.getValue(ALL);
            long size = Long.parseLong(fullSize);
            saver.setSize(size);
          } catch (NumberFormatException e) {
            saver.setSize(0);
          }
        } else if (name.equals(ENTITY_TAG)) {
          currentKind = attributes.getValue(KIND);
          currentProperties = new HashMap<String, Object>();
        } else if (name.equals(PROPERTY_TAG)) {
          String type = attributes.getValue(CLASS);
          if (type.equals("null")) {
            String id = attributes.getValue(NAME);
            currentProperties.put(id, null);
          } else {
            try {
              Class cl = Class.forName(type);
              if (Collection.class.isAssignableFrom(cl)) {
                currentCol = (Collection) cl.newInstance();
                collParsing = attributes.getValue(NAME);
              } else {
                String id = attributes.getValue(NAME);
                String val = attributes.getValue(VALUE);
                val = xmlEncode(val);
                val = val.replaceAll("\\\\n", LINE_SEPARATOR);
                Object value = StringInputOutput.createObject(
                    type, val, tFacade.getNamespace());
                currentProperties.put(id, value);
              }
            } catch (ClassNotFoundException e) {
              showErrorDialog("Unable to read data from " + input);
            } catch (InstantiationException e) {
              showErrorDialog("Unable to read data from " + input);
            } catch (IllegalAccessException e) {
              showErrorDialog("Unable to read data from " + input);
            }

          }
        } else if (name.equals(LIST_ELEMENT_TAG)) {
          String type = attributes.getValue(CLASS);
          String val = attributes.getValue(VALUE);
          val = xmlEncode(val);
          val = val.replaceAll("\\\\n", LINE_SEPARATOR);
          Object value = StringInputOutput.createObject(type, val,
              tFacade.getAppId());
          currentCol.add(value);
        }
      }

      public void endElement(String name) throws SAXException {
        if (name.equals(MAJOR_TAG)) {
          if (resList.size() != 0) {
            saver.save(resList.toArray(new Entity[resList.size()]));
            resList.clear();
          }
        } else if (name.equals(PROPERTY_TAG)) {
          if (collParsing != null && currentCol != null) {
            currentProperties.put(collParsing, currentCol);

            currentCol = null;
            collParsing = null;
          }
        } else if (name.equals(ENTITY_TAG)) {
          Entity newEnt = new Entity(
              (Key) currentProperties
                  .get(Entity.KEY_RESERVED_PROPERTY));
          for (Iterator<String> i = currentProperties.keySet()
              .iterator(); i.hasNext();) {
            String next = i.next();
            if (!next.equals(Entity.KEY_RESERVED_PROPERTY)) {
              newEnt.setProperty(next,
                  currentProperties.get(next));
            }
          }

          resList.add(newEnt);
          currentKind = null;
          currentProperties = null;

          if (resList.size() == numberOfReaded) {
            saver.save(resList.toArray(new Entity[resList.size()]));
            resList.clear();
          }
        }
      }
    }

    private final BaseDataFacade tFacade;
    private static final String MAJOR_TAG = "entities";
    private static final String ENTITY_TAG = "entity";
    private static final String PROPERTY_TAG = "property";
    private static final String LIST_ELEMENT_TAG = "listElement";
    private static final String KIND = "kind";
    private static final String NAME = "name";
    private static final String VALUE = "value";
    private static final String CLASS = "type";
    private static final String ALL = "expected";
    private final ArrayList<Entity> resList = new ArrayList<Entity>();
    private String input;

    private XmlReaderImpl(BaseDataFacade tFacade) {
      this.tFacade = tFacade;
    }

    private String xmlEncode(String str) {
      String result;
      result = str.replaceAll("&lt;", "<");
      result = result.replaceAll("&lt;", "<");
      result = result.replaceAll("&gt;", ">");
      result = result.replaceAll("&quot;", "\"");
      result = result.replaceAll("&apos;", "\'");
      result = result.replaceAll("&amp;", "&");
      return result;
    }

    public void readData(final String input, final DataSaver saver,
        final int numberOfReaded) {
      HandlerBase handler = new SpecialBase(input, numberOfReaded, saver);

      try {
        FileInputStream fIs = new FileInputStream(input);

        SAXParser parser = SAXParserFactory.newInstance()
            .newSAXParser();
        InputSource is = new InputSource(fIs);

        parser.parse(is, handler);
        fIs.close();
        saver.onFinish();
      } catch (ParserConfigurationException e) {
        showErrorDialog("Unable to read data from " + input);
      } catch (SAXException e) {
        showErrorDialog("Unable to read data from " + input);
      } catch (FileNotFoundException e) {
        showErrorDialog("Unable to read data from " + input);
      } catch (IOException e) {
        showErrorDialog("Unable to read data from " + input);
      }

      return;
    }
  }

  private class JDBCReaderImpl implements IReader {

    private ExportData expDat;
    private BaseDataFacade tFacade;

    /*
     * private class fromJDBCTranslator{ public HashMap<String, V> }
     */

    public void settFacade(BaseDataFacade tFacade) {
      this.tFacade = tFacade;
    }

    public void setExpDat(ExportData expDat) {
      this.expDat = expDat;
    }

    public void readData(String input, DataSaver saver, int numberOfReaded) {
      loadDriver();

      Connection connect;
      try {
        connect = DriverManager.getConnection(expDat.jdbcConnection,
            expDat.databaseLogin, expDat.databasePasswd);

        DatabaseMetaData dmd = connect.getMetaData();
        String[] tableTypes = new String[] { "TABLE" };
        ResultSet rs = dmd.getTables(connect.getCatalog(), null, null,
            tableTypes);
        ArrayList<String> tables = new ArrayList<String>();
        while (rs.next()) {
          tables.add(rs.getString("TABLE_NAME"));
        }

        String[] kinds = getAvailableKinds(tables);

        // foreach kind
        for (String kind : kinds) {
          ArrayList<Entity> entities = new ArrayList<Entity>();

          String mainQuery = "SELECT * from " + kind;
          String supportString = "SELECT column_name, type FROM "
              + kind + "_props WHERE "
              + Entity.KEY_RESERVED_PROPERTY + "=?";
          PreparedStatement support = connect
              .prepareStatement(supportString);
          Statement stat = connect.createStatement();

          ResultSet entitiesSet = stat.executeQuery(mainQuery);
          ResultSetMetaData resMetaSet = entitiesSet.getMetaData();

          HashMap<String, String> dataBaseEntitiesHeader = new HashMap<String, String>();
          for (int i = 1; i <= resMetaSet.getColumnCount(); i++) {
            String colName = resMetaSet.getColumnName(i);
            String colType = resMetaSet.getColumnTypeName(i);
            dataBaseEntitiesHeader.put(colName, colType);
          }

          while (entitiesSet.next()) {
            HashMap<String, Object> preTranslatedValues = new HashMap<String, Object>();
            for (Iterator<String> i = dataBaseEntitiesHeader
                .keySet().iterator(); i.hasNext();) {
              String keyStr = i.next();
              Object tmpObj = entitiesSet.getObject(keyStr);
              preTranslatedValues.put(keyStr, tmpObj);
            }

            String keyS = (String) preTranslatedValues
                .get(Entity.KEY_RESERVED_PROPERTY);
            support.setString(1, keyS);
            ResultSet forTranslateRS = support.executeQuery();
            HashMap<String, String> typesForTranslate = new HashMap<String, String>();
            while (forTranslateRS.next()) {
              String key = forTranslateRS.getString(1);
              String type = forTranslateRS.getString(2);
              typesForTranslate.put(key, type);
            }

            HashMap<String, Object> propsForEntity = tranlateFromSQL(
                preTranslatedValues, typesForTranslate);

            // Creating of entity Object!!!

            Key k = (Key) propsForEntity
                .get(Entity.KEY_RESERVED_PROPERTY);
            Entity e = new Entity(k);

            for (Iterator<String> i = propsForEntity.keySet()
                .iterator(); i.hasNext();) {
              String key = i.next();
              if (!key.equals(Entity.KEY_RESERVED_PROPERTY)) {
                e.setProperty(key, propsForEntity.get(key));
              }
            }
            entities.add(e);
            if (entities.size() == 100) {
              saver.save(entities.toArray(new Entity[entities
                  .size()]));
              entities.clear();
            }
          }

          if (entities.size() != 0) {
            saver.save(entities.toArray(new Entity[entities.size()]));
            entities.clear();
          }
        }

        connect.close();
      } catch (SQLException e) {
        showErrorDialog("The following error occured:"
            + e.getLocalizedMessage());
        // e.printStackTrace();
      }
    }

    private HashMap<String, Object> tranlateFromSQL(
        HashMap<String, Object> preTr, HashMap<String, String> props) {
      HashMap<String, Object> res = new HashMap<String, Object>();
      for (Iterator<String> i = preTr.keySet().iterator(); i.hasNext();) {
        String key = i.next();

        if (!props.containsKey(key)) {
          Object value = preTr.get(key);
          if (value != null && value instanceof java.sql.Date) {
            try {
              Date util = DateFormat.getDateTimeInstance(
                  DateFormat.FULL, DateFormat.FULL).parse(
                  DateFormat.getDateTimeInstance(
                      DateFormat.FULL, DateFormat.FULL)
                      .format(value));
              res.put(key, util);
            } catch (ParseException e) {
              e.printStackTrace();
            }
          } else {
            res.put(key, value);
          }
        } else {
          Object value = preTr.get(key);
          String type = props.get(key);
          Object val = StringInputOutput.createObject(type,
              (String) value, tFacade.getNamespace());
          res.put(key, val);
        }

      }

      return res;
    }

    private String[] getAvailableKinds(ArrayList<String> allKinds) {
      ArrayList<String> res = new ArrayList<String>();
      for (Iterator<String> i = allKinds.iterator(); i.hasNext();) {
        String current = i.next();
        if (current.endsWith("_props")) {
          String kind = current.replaceAll("_props", "");
          if (allKinds.contains(kind)) {
            res.add(kind);
          }
        }
      }

      return res.toArray(new String[res.size()]);
    }

    private void loadDriver() {
      try {
        ClassLoader loader = ClassLoader.getSystemClassLoader();
        URL[] urls = new URL[expDat.jdbcDriverClassPath.size()];
        int j = 0;
        for (Iterator<String> i = expDat.jdbcDriverClassPath.iterator(); i
            .hasNext();) {
          String tmp = i.next();
          // File f = new File(tmp);
          urls[j] = new URL("jar:file:" + File.separator + tmp + "!/");// f.toURL();
          j++;
        }
        URLClassLoader ucl = new URLClassLoader(urls, loader);
        Driver d = (Driver) ucl.loadClass(expDat.jdbcDriverClassName)
            .newInstance();
        DriverManager.registerDriver(new DriverWrapper(d));

      } catch (Exception e) {
        showErrorDialog(e.getLocalizedMessage());
      }
    }
  }

  protected BaseDataFacade facade;

  public BaseDataFacade getFacade() {
    return facade;
  }

  public void setFacade(BaseDataFacade facade) {
    this.facade = facade;
  }

  IStructuredSelection currentSelection;

  private final class ShowNSListDialog extends TitledDialog {

    private CompositeEditor editor;

    private ShowNSListDialog(CompositeEditor editor) {
      super(editor);
      this.editor = editor;
    }

    protected void okPressed() {
      Binding b = (Binding) editor.getBinding();
      b.commit();
      NamespacesRealm nsr = (NamespacesRealm) b.getValue();
      String currentNS = nsr.current;
      if (currentNS == null) {
        if (facade.namespace == null) {
          currentNS = facade.namespace = "";
        } else {
          currentNS = facade.namespace;
        }
      } else {
        facade.namespace = currentNS;
      }
      facade.handleChangingNamespace();
      ArrayList<String> realmNS = nsr.namespaces;
      try {
        AnnotationsStorage.setKnownNameSpaces(facade.getProject()
            .getProject(), realmNS.toArray(new String[realmNS
            .size()]));
      } catch (CoreException e) {
        e.printStackTrace();
      }
      facade.refresh();
      super.okPressed();
    }
  }

  private final class EditDialog extends TitledDialog {
    private final CompositeEditor editor;
    private boolean showParentLink;
    private IUpdateList callback;

    public void setUpdatingCallback(IUpdateList callback) {
      this.callback = callback;
    }

    private EditDialog(CompositeEditor editor, boolean showParent) {
      super(editor);
      this.editor = editor;
      this.showParentLink = showParent;
    }

    protected void okPressed() {
      ((Binding) bnd).commit();
      if (callback != null) {
        Entity e = (Entity) ((Binding) bnd).getObject();
        callback.update(e);
      }
      // check if
      if (((Binding) bnd).isParsingEnabled()) {
        ((Binding) bnd).switchParsingMode(false);
      }

      super.okPressed();
    }

    protected void createButtonsForButtonBar(
        org.eclipse.swt.widgets.Composite parent) {
      org.eclipse.swt.widgets.Composite cm = new org.eclipse.swt.widgets.Composite(
          parent, SWT.NONE);

      Entity e = (Entity) this.editor.getBinding().getObject();

      if (e.getParent() != null) {
        cm.setLayout(new GridLayout(4, false));
      } else {
        cm.setLayout(new GridLayout(4, false));
      }
      if (showParentLink) {
        Link l0 = new Link(cm, SWT.NONE);
        l0.setText("<a>Customize Key</a>");
        l0.addSelectionListener(new SelectionAdapter() {

          public void widgetSelected(SelectionEvent e) {
            Binding b = new Binding("");
            b.setName("Customize Key");
            b.setDescription("Please type long or string key in 'Id or Name' field");
            final Binding id = new Binding(b.getBinding("id"));
            id.setRequired(true);
            id.setName("Id or Name:");
            id.setValue("", null);
            id.setReadOnly(false);
            OneLineTextElement<String> idel = new OneLineTextElement<String>(
                id);

            // OneLineTextElement<String>nl=new
            // OneLineTextElement<String>(name);
            CompositeEditor ed = new CompositeEditor(b);
            ed.setLayoutManager(new OneElementOnLineLayouter());
            ed.add(idel);
            // ed.add(nl);
            Container buttons = new Container();
            buttons.setLayoutManager(new HorizontalLayouter());
            ButtonSelector ba = new ButtonSelector();
            ba.setText("Ok");
            final InputElementDialog dlg = new InputElementDialog(
                ed);
            ba.setValue(new Runnable() {

              public void run() {
                String value = (String) id.getValue();
                Key k = null;
                Entity value2 = (Entity) editor.getBinding()
                    .getValue();
                Key c = (Key) value2.getKey();
                if (c != null && c.isComplete()) {
                  if (!value2.hasProperty("$$OLD_KEY_SET")) {
                    value2.setProperty("$$OLD_KEY_SET",
                        Boolean.TRUE);
                    value2.setProperty("$$OLD_KEY"
                        + Entity.KEY_RESERVED_PROPERTY,
                        c);
                  }
                }
                if (value != null && value.trim().length() != 0) {
                  String vl = value.trim();
                  try {
                    long l = Long.parseLong(vl);

                    k = KeyFactory.createKey(
                        value2.getKind(), l);
                  } catch (Exception e) {
                    k = KeyFactory.createKey(
                        ((Entity) editor.getBinding()
                            .getValue()).getKind(),
                        vl);
                  }
                } else {
                  return;
                }
                // value2.setProperty(Entity.KEY_RESERVED_PROPERTY,
                // k);
                try {
                  java.lang.reflect.Field f = value2
                      .getClass().getDeclaredField("key");
                  f.setAccessible(true);
                  f.set(value2, k);
                } catch (Exception e) {
                  Activator.log(e);
                }
                if (k != null) {
                  String string = "" + k.toString();
                  ((Binding) editor.getBinding())
                      .setName(string);
                  EditDialog.this.setTitle(string);
                  ;
                  dlg.close();
                }
              }
            });
            ButtonSelector ba1 = new ButtonSelector();
            ba1.setValue(new Runnable() {

              public void run() {
                dlg.close();
              }
            });
            ba1.setText("Cancel");
            buttons.add(ba);
            buttons.add(ba1);
            ed.add(buttons);
            DisposeBindingListener.linkBindingLifeCycle(b, ed);
            dlg.open();
            super.widgetSelected(e);
          }
        });
      }
      Link l1 = new Link(cm, SWT.NONE);
      l1.setText("<a>Add new property</a>");
      l1.addSelectionListener(new SelectionListener() {

        public void widgetSelected(SelectionEvent e) {
          Binding b = new Binding("");
          b.setName("Configure new Property");
          final Binding binding = b.getBinding("name");
          binding.setName("Name");
          binding.setReadOnly(false);

          binding.addValidator(new ValidatorAdapter<String>() {

            public CodeAndMessage isValid(IBinding context,
                String object) {
              if (object == null || object.length() == 0) {
                return CodeAndMessage
                    .errorMessage("please define property name");
              }
              Binding b = (Binding) editor.getBinding();
              if (b.getKnownChilds().contains(object)) {
                return CodeAndMessage
                    .errorMessage("property with this name already exits");
              }
              return super.isValid(context, object);
            }
          });
          final Binding type = b.getBinding("type");
          final Binding kc = b.getBinding("keyKind");
          kc.setName("Kind:");
          kc.setValue(
              ((Entity) editor.getBinding().getValue()).getKind(),
              null);
          kc.setReadOnly(false);
          kc.setRequired(false);
          type.setName("Type");
          type.setReadOnly(false);
          type.setRequired(true);
          final OneLineTextElement<String> keyKind = new OneLineTextElement<String>(
              kc);
          type.setAdapter(ITextLabelProvider.class,
              new TextProviderAdapter() {

                public String getText(Object object) {
                  Class<?> c = (Class<?>) object;
                  return c.getSimpleName();
                }
              });
          type.setValue(String.class, null);
          type.setRealm(new Realm<Class<?>>(
              EditorUtility.SUPPORTED_TYPES));
          final Binding multi = b.getBinding("multi");
          multi.setReadOnly(false);
          multi.setName("Multivalue");
          type.setName("Type");
          multi.setValue(false, null);
          CompositeEditor z = new CompositeEditor(b);
          final Container m = new Container();
          m.setLayoutManager(new OneElementOnLineLayouter());
          OneLineTextElement<String> t = new OneLineTextElement<String>(
              binding);
          // t.setCaption("Name:");
          m.add(t);
          ComboEnumeratedValueSelector<Class<?>> element2 = new ComboEnumeratedValueSelector<Class<?>>(
              type);
          type.addValueListener(new IValueListener<Class<?>>() {

            public void valueChanged(Class<?> oldValue,
                Class<?> newValue) {
              if (newValue == Key.class) {
                m.add(2, keyKind);
                m.getControl().getShell().pack(true);
              } else if (oldValue == Key.class) {
                m.remove(keyKind);
                m.getControl().getShell().pack(true);
              }

            }

          });
          ButtonSelector sl = new ButtonSelector(SWT.CHECK);
          sl.setBinding(multi);
          m.add(element2);
          m.add(sl);
          z.setLayoutManager(new OneElementOnLineLayouter());
          z.add(m);
          Container m1 = new Container();
          m1.setLayoutManager(new HorizontalLayouter());
          final InputElementDialog dl = new InputElementDialog(z);
          final ButtonSelector ok = new ButtonSelector();
          ok.setText("Ok");
          ok.setValue(new Runnable() {

            public void run() {
              String value = (String) binding.getValue();
              BaseDataFacade.GAEField gaeField = facade
                  .createField(value,
                      (Class<?>) type.getValue(),
                      (Boolean) (multi.getValue()),
                      (String) kc.getValue());
              EditingBinding binding2 = (EditingBinding) editor
                  .getBinding();
              binding2.removedElements.remove(value);
              binding2.fieldsChanged = true;
              binding2.getBinding(value).setValue(null, null);
              EditorUtility.createBindingsWithButton(
                  (Entity) binding2.getValue(), editor,
                  (Binding) binding2,
                  new Field[] { gaeField }, facade, true);
              dl.close();
              editor.getControl().getShell().layout(true, true);
              editor.getControl().getShell().pack(true);
            }
          });
          ok.setEnabled(false);
          b.addStatusChangeListener(new IStatusChangeListener() {

            public void statusChanged(IBinding bnd,
                CodeAndMessage cm) {
              ok.setEnabled(cm.getCode() == 0);

            }
          });
          ButtonSelector cancel = new ButtonSelector();
          cancel.setText("Cancel");
          m1.add(ok);
          m1.add(cancel);
          cancel.setValue(new Runnable() {

            public void run() {
              dl.close();
            }
          });
          m1.getLayoutHints().setGrabHorizontal(true);
          m1.getLayoutHints().setAlignmentHorizontal(SWT.RIGHT);
          z.add(m1);
          DisposeBindingListener.linkBindingLifeCycle(b, z);
          dl.open();
        }

        public void widgetDefaultSelected(SelectionEvent e) {

        }
      });
      Link l2 = new Link(cm, SWT.NONE);
      l2.setText("<a>Remove property</a>");
      l2.addSelectionListener(new SelectionListener() {

        public void widgetSelected(SelectionEvent e) {
          Binding bnd2 = new Binding("");
          bnd2.setName("Select property to remove");
          CompositeEditor ed = new CompositeEditor(bnd2);
          ed.setLayoutManager(new OneElementOnLineLayouter());
          final ListEnumeratedValueSelector<String> element2 = new ListEnumeratedValueSelector<String>();
          ed.add(element2);
          final Binding bnd = (Binding) editor.getBinding();
          Collection<String> str = bnd.getKnownChilds();
          element2.setRealm(new Realm<String>(str));
          element2.setValue(str);
          element2.getLayoutHints().setHint(new Point(200, 300));
          final InputElementDialog em = new InputElementDialog(ed);

          DisposeBindingListener.linkBindingLifeCycle(bnd2, ed);
          Container b = new Container();
          b.setLayoutManager(new HorizontalLayouter());
          final ButtonSelector ok = new ButtonSelector();
          ok.setText("Ok");
          ok.setEnabled(false);
          element2.addSelectionChangedListener(new ISelectionChangedListener() {

            public void selectionChanged(SelectionChangedEvent event) {
              ok.setEnabled(!event.getSelection().isEmpty());
            }
          });
          b.add(ok);
          ok.setValue(new Runnable() {

            public void run() {
              for (Object o : element2.getSelection().toArray()) {
                AbstractUIElement<?> findEditor = findEditor(
                    editor, o.toString());
                if (findEditor != null) {
                  Container parent2 = findEditor.getParent();
                  if (parent2.getParent() instanceof CTabFolderElement) {
                    Container parent3 = parent2.getParent();
                    parent3.remove(parent2);
                    Container p4 = parent3.getParent();

                    if (p4 instanceof CompositeEditor) {
                      CompositeEditor ce = (CompositeEditor) p4;
                      String id = ce.getId();
                      if (id != null
                          && id.equals(o.toString())) {
                        ce.getParent().remove(ce);
                      }
                    }
                  } else {
                    parent2.remove(findEditor);

                    if (parent2 instanceof CompositeEditor) {
                      CompositeEditor ce = (CompositeEditor) parent2;
                      if (ce.getId().equals(o.toString())) {
                        ce.getParent().remove(ce);
                      }
                    }
                  }

                  Binding binding = bnd.getBinding(o
                      .toString());
                  binding.dispose();
                  EditingBinding b = (EditingBinding) editor
                      .getBinding();
                  b.removedElements.add(o.toString());
                }

              }
              editor.getControl().getShell().layout(true, true);

              em.close();
            }
          });

          ButtonSelector cancel = new ButtonSelector();
          cancel.setText("Cancel");
          cancel.setValue(new Runnable() {

            public void run() {
              em.close();
            }
          });
          b.add(cancel);
          ed.add(b);
          em.open();
        }

        public void widgetDefaultSelected(SelectionEvent e) {

        }
      });
      /*
       * Link l3=new Link(cm,SWT.NONE);
       * l3.setText("<a>Change property type</a>");
       */
      if (e.getParent() != null) {
        Link l3 = new Link(cm, SWT.NONE);
        l3.setText("<a>Edit parent entity</a>");
        l3.addSelectionListener(new SelectionListener() {

          public void widgetSelected(SelectionEvent e) {
            Entity curr = (Entity) editor.getBinding().getObject();
            if (curr.getParent() != null
                && facade.getParents().containsKey(
                    curr.getParent())) {
              Entity p = (Entity) facade.getParents().get(
                  curr.getParent());
              // DataStoreTableUI.this.open(p);
              openSubDialog(p);
            }

          }

          public void widgetDefaultSelected(SelectionEvent e) {
            // TODO Auto-generated method stub

          }
        });
      }
      org.eclipse.swt.widgets.Composite cm1 = new org.eclipse.swt.widgets.Composite(
          parent, SWT.NONE);
      GridLayout layout = new GridLayout(3, false);
      layout.marginWidth = 0;
      cm1.setLayout(layout);
      super.createButtonsForButtonBar(cm1);
      GridLayout ll = (GridLayout) parent.getLayout();
      ll.numColumns = 2;
      ll.makeColumnsEqualWidth = false;
      ll.marginWidth = 0;
    }
  }

  public class EditingBinding extends Binding {
    private final Entity e;

    public Entity getE() {
      return e;
    }

    private HashSet<String> removedElements = new HashSet<String>();
    private boolean edit;
    private boolean fieldsChanged;

    private boolean resetToNull = false;
    private boolean notIndexable = false;

    public boolean isNotIndexable() {
      return notIndexable;
    }

    public void setNotIndexable(boolean notIndexable) {
      this.notIndexable = notIndexable;
    }

    protected EditingBinding(Object object, Entity e, boolean edit) {
      super(object);
      this.e = e;
      this.edit = edit;
      resetToNull = false;
      notIndexable = false;
    }

    public boolean isResetToNull() {
      return resetToNull;
    }

    public void setResetToNull(boolean resetToNull) {
      this.resetToNull = resetToNull;
    }

    protected Binding createBinding(String path) {
      Object val = this.getId().length() > 0 ? this.value : this
          .getObject();
      EditingBinding ed = new EditingBinding(val, e, true);
      ed.setParent(this);
      ed.id = path;

      return ed;// /Binding(this, path, val);
    }

    public void commit() {
      for (String b : getKnownChilds()) {
        // if(facade.getKindsOfChildren().containsKey(b)){
        // continue;
        // }
        Binding binding = getBinding(b);
        Object value = binding.getValue();

        if (binding instanceof EditingBinding) {
          if (((EditingBinding) binding).isResetToNull()) {
            ((EditingBinding) binding).setResetToNull(false);
            setPropValue(b, binding, null);
            continue;
          }

        }

        // int count = 0;
        // if (value instanceof Collection<?>) {
        // Collection c = (Collection) value;
        // for (Iterator iterator = c.iterator(); iterator.hasNext();) {
        // Object object = (Object) iterator.next();
        // if (object instanceof NullValue) {
        // iterator.remove();
        // count++;
        // }
        // }
        // for (int a = 0; a < count; a++) {
        // c.add(null);
        // }
        // }
        try {
          // if (value instanceof Collection) {
          // Collection c = (Collection) value;
          // if (c.size() != 0) {
          // Object obj = c.toArray(new Object[c.size()])[c
          // .size() - 1];
          // if (isSupported(obj)) {
          // setPropValue(b, binding, value);
          // }
          // } else {
          // setPropValue(b, binding, value);
          // }
          // } else {
          // if (isSupported(value)) {
          // setPropValue(b, binding, value);
          // }
          // }
          setPropValue(b, binding, value);
        } catch (Exception e) {
          MessageDialog.openError(Display.getDefault()
              .getActiveShell(), "Error", e.getMessage());
          throw new RuntimeException(e);
        }
      }
      for (String a : removedElements) {
        e.removeProperty(a);
      }
      OperationCallback callback = new OperationCallback() {

        public void passed(Object object) {
          if (edit && !fieldsChanged) {
            facade.refresh(object);
            facade.updateChildren(object);
            facade.updateParent(object);
          } else {
            doRefresh();
          }
        }

        public void failed(Exception exception) {
          MessageDialog.openError(Display.getDefault()
              .getActiveShell(), "Error", exception.getMessage());
          openSubDialog(e);
        }
      };
      if (edit) {
        facade.store(e, callback);
      } else {
        facade.add(e, callback);
      }

    }

    protected void setPropValue(String b, Binding binding, Object value) {
      Field f = facade.getField(b);
      Object val = null;
      if (f != null) {
        if (f.getType() != null) {
          Class<?> type = f.getType();
          if (value instanceof Collection) {
            val = new ArrayList<Object>();
            Collection<?> coll = (Collection<?>) value;
            for (Iterator<?> i = coll.iterator(); i.hasNext();) {
              Object nxt = i.next();
              if (nxt instanceof NullValue) {
                ((List<Object>) val).add(null);
              } else {
                if (!isSupported(nxt)) {
                  return;
                }
                nxt = parseSingleValue(nxt, type);
                ((List<Object>) val).add(nxt);
              }
            }
          } else {
            if (!isSupported(value)) {
              return;
            }
            val = parseSingleValue(value, type);

          }

        }
        if (binding instanceof EditingBinding) {
          if (((EditingBinding) binding).isNotIndexable()) {
            e.setUnindexedProperty(b, val);
          } else {
            e.setProperty(b, val);
          }
        } else {
          e.setProperty(b, val);
        }
      }
    }

    private Object parseSingleValue(Object value, Class type) {
      if (type == Double.class) {
        if (value instanceof String) {
          value = Double.parseDouble((String) value);
        }
      } else if (type == Long.class) {
        if (value instanceof String) {
          value = Long.parseLong((String) value);
        }
      } else if (type == Float.class) {
        if (value instanceof String) {
          value = Float.parseFloat((String) value);
        }
      } else if (type == Integer.class) {
        if (value instanceof String) {
          value = Integer.parseInt((String) value);
        }
      }
      return value;
    }
  }

  private boolean isSupported(Object val) {
    if (val == null) {
      return true;
    }
    Class clz = val.getClass();
    boolean flag = false;
    for (Class z : EditorUtility.SUPPORTED_TYPES) {
      if (z.isAssignableFrom(clz)) {
        flag = true;
      }
    }
    return flag;
  }

  private final class DetailsFilterDialog extends TitledDialog {
    private final ListEnumeratedValueSelector<Field> vl;

    IStructuredSelection selection;

    private DetailsFilterDialog(IPropertyEditor<?> editor,
        ListEnumeratedValueSelector<Field> vl) {
      super(editor);
      this.vl = vl;
      vl.setValueAsSelection(true);
    }

    protected void okPressed() {
      Collection<Object> currentValue = vl.getCurrentValue();
      selection = new StructuredSelection(currentValue.toArray());
      super.okPressed();
    }
  }

  final class DeleteAction extends Action {
    {
      setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(
          Activator.PLUGIN_ID, "/icons/delete.gif"));
    }

    protected DeleteAction(String text) {
      super(text);
    }

    public void run() {
      facade.delete(currentSelection.toArray(), new OperationCallback() {
        public void passed(Object object) {
          doRefresh();

        }

        public void failed(Exception exception) {
          doRefresh();
        }
      });
    }
  }

  final class RefreshAction extends Action {
    {
      setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(
          Activator.PLUGIN_ID, "/icons/refresh_tab.gif"));
    }

    protected RefreshAction(String text) {
      super(text);
    }

    public void run() {
      doRefresh();
    }
  }

  final class BulkExportAction extends Action {
    {
      setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(
          Activator.PLUGIN_ID, "/icons/exportpref_obj.gif"));
    }

    @Override
    public void run() {
      final boolean debug = facade.isDebug();
      if (!LicenseChecker.checkLicense(debug)) {
        return;
      }

      final IJavaProject javaGaeProject = UIUtils.getJavaGaeProject();

      if (javaGaeProject != null) {
        Check check = new Check() {
          @Override
          protected void internalRun(IJavaProject project) {
            facade.setProject(project);

            final ExportData result = ImportExportDialogs
                .showBulkExportDialog(facade);
            if (result != null) {
              boolean exportIsRequired = checkPossibilityOfExport();
              if (!exportIsRequired) {
                return;
              }

              if (debug) {
                LocalServerLauncher.launchLocalServer(facade
                    .getProject());
              }

              Job bulkJob = new Job("Bulk Export In Progress...") {

                @Override
                protected IStatus run(IProgressMonitor monitor) {
                  // Display.getDefault().syncExec(
                  // new Runnable() {
                  // public void run() {

                  String outputFolder = result.outPut;
                  File rootDir = new File(outputFolder);
                  if (rootDir.exists()) {
                    File[] list = rootDir.listFiles();
                    if (list == null) {
                      return Status.OK_STATUS;
                    }
                    for (File f : list) {
                      String kind = f.getName();
                      if (f.isDirectory()) {
                        File[] nflist = f.listFiles();
                        if (nflist == null) {
                          continue;
                        }
                        for (File nf : nflist) {
                          String ckind = nf.getName();
                          exportSingleKind(kind,
                              result, ckind);
                        }
                      } else {
                        exportSingleKind("", result,
                            kind);
                      }
                    }
                  }
                  // }
                  // });
                  return Status.OK_STATUS;
                }
              };
              bulkJob.schedule();
            }
          }
        };
        check.doCheck(javaGaeProject);
      }

      return;
    }

    private void exportSingleKind(String namespace, ExportData root,
        String fileName) {

      String kind = fileName.split("\\.")[0];

      ExportData dat = new ExportData();
      if (root.asCsv) {
        dat.asCsv = true;
        dat.asXML = false;
        dat.asBinary = false;
        if (!fileName.endsWith(".csv")) {
          return;
        }

      } else if (root.asXML) {
        dat.asCsv = false;
        dat.asXML = true;
        dat.asBinary = false;
        if (!fileName.endsWith(".xml")) {
          return;
        }
      }

      if (namespace.equals("")) {
        dat.outPut = root.outPut + File.separator + fileName;
      } else {
        dat.outPut = root.outPut + File.separator + namespace
            + File.separator + fileName;
      }

      BaseDataFacade tFacade = new BaseDataFacade(kind,
          facade.getProject(), facade.isDebug());
      tFacade.setNamespace(namespace);
      executeExports(dat, tFacade);
    }

    private BulkExportAction() {
      super("Bulk Export");
    }
  }

  final class BulkImportAction extends Action {
    {
      setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(
          Activator.PLUGIN_ID, "/icons/importpref_obj.gif"));
    }

    @Override
    public void run() {
      final boolean debug = facade.isDebug();
      if (!LicenseChecker.checkLicense(debug)) {
        return;
      }

      final IJavaProject javaGaeProject = UIUtils.getJavaGaeProject();

      if (javaGaeProject != null) {
        Check check = new Check() {
          @Override
          protected void internalRun(IJavaProject project) {

            facade.setProject(project);

            final ImportData result = ImportExportDialogs
                .showBulkImportDialog(facade);
            if (result != null) {
              if (debug) {
                LocalServerLauncher.launchLocalServer(facade
                    .getProject());
              }

              Job bulkExport = new Job(
                  "Bulk Import In Progress...") {

                @Override
                protected IStatus run(
                    final IProgressMonitor monitor) {
                  // Display.getDefault().syncExec(
                  // new Runnable() {
                  // public void run() {

                  try {
                    List<String> namespaces = getNamespacesList();
                    if (namespaces == null) {
                      namespaces = new LinkedList<String>();
                    }
                    if (!namespaces.contains("")) {
                      namespaces.add("");
                    }
                    for (String n : namespaces) {
                      if (n == null) {
                        continue;
                      }
                      List<String> kinds = getKindsList(
                          n, debug, javaGaeProject);
                      if (!n.equals("")) {
                        File f = new File(result.outPut
                            + File.separator + n);
                        f.mkdirs();

                      }
                      if (kinds != null) {
                        for (String k : kinds) {
                          importSingleKind(k, result,
                              n);
                        }
                      }
                    }

                  } catch (Exception e) {
                    e.printStackTrace();
                  }
                  // }
                  // });
                  return Status.OK_STATUS;
                }
              };
              bulkExport.schedule();
            }
          }
        };
        check.doCheck(javaGaeProject);
      }

    }

    private void importSingleKind(String kind, ImportData data,
        String namespace) {
      BaseDataFacade tmpFacade = new BaseDataFacade(kind,
          facade.getProject(), facade.isDebug());
      ImportData tmpData = new ImportData();
      tmpFacade.setNamespace(facade.getNamespace());

      if (data.asCsv) {
        tmpData.asCsv = true;
        tmpData.asXML = false;
        tmpData.asBinary = false;
        if (!namespace.equals("")) {
          tmpData.outPut = data.outPut + File.separator + namespace
              + File.separator + tmpFacade.getKind() + ".csv";
        } else {
          tmpData.outPut = data.outPut + File.separator
              + tmpFacade.getKind() + ".csv";
        }
      } else if (data.asXML) {
        tmpData.asCsv = false;
        tmpData.asXML = true;
        tmpData.asBinary = false;
        if (!namespace.equals("")) {
          tmpData.outPut = data.outPut + File.separator + namespace
              + File.separator + tmpFacade.getKind() + ".xml";
        } else {
          tmpData.outPut = data.outPut + File.separator
              + tmpFacade.getKind() + ".xml";
        }

      }

      executeImports(tmpData, tmpFacade);
    }

    private BulkImportAction() {
      super("Bulk Import");
    }
  }

  final class ExportAction extends Action {

    {
      setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(
          Activator.PLUGIN_ID, "/icons/exportpref_obj.gif"));
    }

    public void run() {
      final ExportData data = ImportExportDialogs
          .showExportDialog(facade);

      if (data != null) {

        boolean result = checkPossibilityOfExport();

        if (!result) {
          return;
        }

        executeExport(data, facade);
      }
    }

    private ExportAction() {
      super("Export data to data store");
    }
  }

  final class ImportAction extends Action {

    {
      setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(
          Activator.PLUGIN_ID, "/icons/importpref_obj.gif"));
    }

    public void run() {
      final ImportData data = ImportExportDialogs
          .showImportDialog(facade);

      if (data == null) {
        return;
      }

      executeImport(data, facade);

    }

    private ImportAction() {
      super("Import data from data store");
    }
  }

  final class ChangeNameSpaceAction extends Action {
    {
      setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(
          Activator.PLUGIN_ID, "/icons/module_rep.gif"));

    }

    public void run() {
      changeNamespace();
    }

    private ChangeNameSpaceAction() {
      super("Choosing namespace");
    }
  }

  final class ShowQueueFunctionsAction extends Action implements IMenuCreator {

    private final class VCHListener implements IValueListener<Field> {
      private final Binding value;
      private final CompositeEditor editor;
      private final Entity res;
      private final CompositeEditor[] inner;

      private VCHListener(Binding value, CompositeEditor editor,
          Entity res, CompositeEditor[] inner) {
        this.value = value;
        this.editor = editor;
        this.res = res;
        this.inner = inner;
      }

      public void valueChanged(Field oldValue, Field newValue) {
        changeEditor(editor, inner, newValue, oldValue, res, value);
      }
    }

    private MenuManager mm;

    {
      setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(
          Activator.PLUGIN_ID, "/icons/cog.png"));

    }

    public void run() {
      // Menu m = getMenu(Display.getDefault().getActiveShell());
      // m.setVisible(true);

      super.run();
    }

    private ShowQueueFunctionsAction() {
      super("Show queue menu", AS_DROP_DOWN_MENU);
      setMenuCreator(this);

    }

    public void dispose() {
      mm.dispose();
    }

    public Menu getMenu(Control parent) {
      mm = new MenuManager();

      mm.add(new Action("Remove all entities") {

        public void run() {
          OperationCallback callback = new OperationCallback() {

            public void passed(Object object) {
              doRefresh();
            }

            public void failed(Exception exception) {
              MessageDialog.openError(Display.getDefault()
                  .getActiveShell(), "Error", exception
                  .getMessage());
            }
          };

          DataStoreTableUI.this.facade.removeAll(callback);
        }
      });
      mm.add(new Action("Rename property") {

        public void run() {
          final OperationCallback callback = new OperationCallback() {

            public void passed(Object object) {
              doRefresh();
            }

            public void failed(Exception exception) {
              MessageDialog.openError(Display.getDefault()
                  .getActiveShell(), "Error", exception
                  .getMessage());
            }
          };

          TitleAreaDialog tid = new TitleAreaDialog(Display
              .getDefault().getActiveShell()) {

            private Combo combo;
            private org.eclipse.swt.widgets.Label l1;
            private org.eclipse.swt.widgets.Text txt;
            private org.eclipse.swt.widgets.Label l2;
            private String[] realm;

            protected Control createDialogArea(
                org.eclipse.swt.widgets.Composite parent) {
              org.eclipse.swt.widgets.Composite p = new org.eclipse.swt.widgets.Composite(
                  (org.eclipse.swt.widgets.Composite) super
                      .createDialogArea(parent), SWT.NONE);
              Collection<String> fs = getFullRealm();
              if (fs.size() == 0) {
                MessageDialog.openError(Display.getDefault()
                    .getActiveShell(), "Error",
                    "Properties list should not be empty.");
                return p;
              }

              p.setLayout(new GridLayout(2, false));
              p.setLayoutData(new GridData(SWT.FILL, SWT.FILL,
                  true, true));

              realm = fs.toArray(new String[fs.size()]);

              l1 = new Label(p, SWT.NONE);
              l1.setText("Available properties:");
              l1.setLayoutData(new GridData(SWT.FILL, SWT.FILL,
                  false, true));

              combo = new Combo(p, SWT.DROP_DOWN | SWT.READ_ONLY);
              combo.setItems(realm);
              combo.setLayoutData(new GridData(SWT.FILL,
                  SWT.FILL, true, true));
              combo.select(0);

              l2 = new Label(p, SWT.NONE);
              l2.setText("New name:");
              l2.setLayoutData(new GridData(SWT.FILL, SWT.FILL,
                  false, true));

              txt = new org.eclipse.swt.widgets.Text(p,
                  SWT.BORDER);
              txt.setLayoutData(new GridData(SWT.FILL, SWT.FILL,
                  true, true));

              return p;// p;
            }

            protected void okPressed() {
              int oldS = combo.getSelectionIndex();
              if (oldS >= 0) {
                String oldSelected = realm[oldS];
                String newProp = txt.getText();
                if (newProp != null && newProp.length() != 0) {
                  facade.renameProperty(oldSelected, newProp,
                      callback);
                }
              }
              super.okPressed();
            }
          };

          tid.create();
          // tid.getShell().setSize(350, 200);
          tid.setTitle("Parameters dialod");
          tid.setMessage("Please choose property and enter new name for it.");
          tid.getShell().pack(true);
          tid.open();
        }
      });
      mm.add(new Action("Remove property") {

        public void run() {
          final OperationCallback callback = new OperationCallback() {

            public void passed(Object object) {
              facade.updateFields();
              doRefresh();
            }

            public void failed(Exception exception) {
              MessageDialog.openError(Display.getDefault()
                  .getActiveShell(), "Error", exception
                  .getMessage());
            }
          };
          TitleAreaDialog tid = new TitleAreaDialog(Display
              .getDefault().getActiveShell()) {

            private Combo combo;
            private org.eclipse.swt.widgets.Label l1;
            private String[] realm;

            protected Control createDialogArea(
                org.eclipse.swt.widgets.Composite parent) {
              org.eclipse.swt.widgets.Composite p = new org.eclipse.swt.widgets.Composite(
                  (org.eclipse.swt.widgets.Composite) super
                      .createDialogArea(parent), SWT.NONE);

              Collection<String> fs = getFullRealm();
              if (fs.size() == 0) {
                MessageDialog.openError(Display.getDefault()
                    .getActiveShell(), "Error",
                    "Properties list should not be empty.");
                return p;
              }

              p.setLayout(new GridLayout(2, false));
              p.setLayoutData(new GridData(SWT.FILL, SWT.FILL,
                  true, true));

              realm = fs.toArray(new String[fs.size()]);

              l1 = new Label(p, SWT.NONE);
              l1.setText("Available properties:");
              l1.setLayoutData(new GridData(SWT.FILL, SWT.FILL,
                  false, true));

              combo = new Combo(p, SWT.DROP_DOWN | SWT.READ_ONLY);
              combo.setLayoutData(new GridData(SWT.FILL,
                  SWT.FILL, true, true));
              combo.setItems(realm);
              combo.select(0);

              return p;// p;
            }

            protected void okPressed() {
              int oldS = combo.getSelectionIndex();
              if (oldS >= 0) {
                String oldSelected = realm[oldS];
                facade.removeProperty(oldSelected, callback);
              }
              super.okPressed();
            }
          };

          tid.create();
          // tid.getShell().setSize(350, 190);
          tid.setTitle("Parameters dialog");
          tid.setMessage("Please choose property for removing.");
          tid.getShell().pack(true);
          tid.open();
        }
      });
      mm.add(new Action("Make property indexed") {

        public void run() {

          final Binding binding = new Binding("");

          final OperationCallback callback = new OperationCallback() {

            public void passed(Object object) {
              facade.updateFields();
              doRefresh();
            }

            public void failed(Exception exception) {
              MessageDialog.openError(Display.getDefault()
                  .getActiveShell(), "Error", exception
                  .getMessage());
            }
          };

          TitleAreaDialog tid = new TitleAreaDialog(Display
              .getDefault().getActiveShell()) {

            private Combo combo;

            private org.eclipse.swt.widgets.Label l1;
            private String[] realm;

            protected Control createDialogArea(
                org.eclipse.swt.widgets.Composite parent) {
              org.eclipse.swt.widgets.Composite p = new org.eclipse.swt.widgets.Composite(
                  (org.eclipse.swt.widgets.Composite) super
                      .createDialogArea(parent), SWT.NONE);
              Field[] f = facade.getFields();
              ArrayList<String> fs = new ArrayList();
              for (Field tmp : f) {
                if (!(tmp instanceof PGAEField)
                    && !(tmp instanceof CGAEField)) {
                  if (!tmp.name
                      .equals(Entity.KEY_RESERVED_PROPERTY)) {
                    if (tmp.getType() != null
                        && (tmp.getType() == Blob.class || tmp
                            .getType() == Text.class)) {
                      continue;
                    }
                    fs.add(tmp.name);
                  }
                }
              }
              if (fs.size() == 0) {
                MessageDialog.openError(Display.getDefault()
                    .getActiveShell(), "Error",
                    "Properties list should not be empty.");
                return p;
              }

              p.setLayout(new GridLayout(2, false));
              p.setLayoutData(new GridData(SWT.FILL, SWT.FILL,
                  true, true));

              realm = fs.toArray(new String[fs.size()]);

              l1 = new Label(p, SWT.NONE);
              l1.setText("Available properties:");
              l1.setLayoutData(new GridData(SWT.FILL, SWT.FILL,
                  false, true));

              combo = new Combo(p, SWT.DROP_DOWN | SWT.READ_ONLY);
              combo.setLayoutData(new GridData(SWT.FILL,
                  SWT.FILL, true, true));
              combo.setItems(realm);
              combo.select(0);
              return p;// p;
            }

            protected void okPressed() {
              int oldS = combo.getSelectionIndex();
              if (oldS >= 0) {
                String selected = realm[oldS];
                facade.changeIndexation(selected, false,
                    callback);
              }
              super.okPressed();
            }
          };

          tid.create();
          // tid.getShell().setSize(350, 170);
          tid.setTitle("Parameters dialog");
          tid.setMessage("Please choose property which will be marked as 'indexed'");
          tid.getShell().pack(true);
          tid.open();
        }
      });
      mm.add(new Action("Make property unindexed") {

        public void run() {

          final Binding binding = new Binding("");

          final OperationCallback callback = new OperationCallback() {

            public void passed(Object object) {
              facade.updateFields();
              doRefresh();
            }

            public void failed(Exception exception) {
              MessageDialog.openError(Display.getDefault()
                  .getActiveShell(), "Error", exception
                  .getMessage());
            }
          };

          TitleAreaDialog tid = new TitleAreaDialog(Display
              .getDefault().getActiveShell()) {

            private Combo combo;

            private org.eclipse.swt.widgets.Label l1;
            private String[] realm;

            protected Control createDialogArea(
                org.eclipse.swt.widgets.Composite parent) {
              org.eclipse.swt.widgets.Composite p = new org.eclipse.swt.widgets.Composite(
                  (org.eclipse.swt.widgets.Composite) super
                      .createDialogArea(parent), SWT.NONE);
              Field[] f = facade.getFields();
              ArrayList<String> fs = new ArrayList();
              for (Field tmp : f) {
                if (!(tmp instanceof PGAEField)) {
                  if (!tmp.name
                      .equals(Entity.KEY_RESERVED_PROPERTY)) {
                    if (tmp.getType() != null
                        && (tmp.getType() == Blob.class || tmp
                            .getType() == Text.class)) {
                      continue;
                    }

                    fs.add(tmp.name);
                  }
                }
              }
              if (fs.size() == 0) {
                MessageDialog.openError(Display.getDefault()
                    .getActiveShell(), "Error",
                    "Properties list should not be empty.");
                return p;
              }
              p.setLayout(new GridLayout(2, false));
              p.setLayoutData(new GridData(SWT.FILL, SWT.FILL,
                  true, true));

              realm = fs.toArray(new String[fs.size()]);

              l1 = new Label(p, SWT.NONE);
              l1.setText("Available properties:");
              l1.setLayoutData(new GridData(SWT.FILL, SWT.FILL,
                  false, true));

              combo = new Combo(p, SWT.DROP_DOWN | SWT.READ_ONLY);
              combo.setLayoutData(new GridData(SWT.FILL,
                  SWT.FILL, true, true));
              combo.setItems(realm);
              combo.select(0);
              return p;// p;
            }

            protected void okPressed() {
              int oldS = combo.getSelectionIndex();
              if (oldS >= 0) {
                String selected = realm[oldS];
                facade.changeIndexation(selected, true,
                    callback);
              }
              super.okPressed();
            }
          };

          tid.create();
          // tid.getShell().setSize(350, 170);
          tid.setTitle("Parameters dialog");
          tid.setMessage("Please choose property which will be marked as 'unindexed'");
          tid.getShell().pack(true);
          tid.open();
        }
      });
      mm.add(new Action("Set value for property") {

        public void run() {
          openDialog(false);
        }
      });
      mm.add(new Action("Set default value for property") {

        public void run() {
          openDialog(true);
        }
      });

      mm.add(createDuplicateEntityAction());

      Menu m = mm.createContextMenu(parent);
      m.setEnabled(true);
      m.setVisible(true);
      return m;
    }

    private void openDialog(final boolean fillDefault) {
      final OperationCallback callback = new OperationCallback() {

        public void passed(Object object) {
          facade.updateFields();
          doRefresh();
        }

        public void failed(Exception exception) {
          MessageDialog.openError(Display.getDefault()
              .getActiveShell(), "Error", exception.getMessage());
        }
      };

      Collection<Field> rStr = getFullFieldRealm();
      if (rStr.size() == 0) {
        MessageDialog.openError(Display.getDefault().getActiveShell(),
            "Error", "Properties list should not be empty.");
        return;
      }
      ApiProxy.setEnvironmentForCurrentThread(new FakeEnvironment(
          getAppId(), facade.namespace));
      final CompositeEditor[] inner = new CompositeEditor[1];
      // inner[0] = new CompositeEditor();

      final Entity res = new Entity(facade.getKind());

      Realm<Field> realm = new Realm<Field>(rStr);

      Binding bnd = new Binding("");
      bnd.setName("Choose property for initializing.");
      final CompositeEditor editor = new CompositeEditor(bnd);
      editor.setLayout(new GridLayout(1, true));

      final Binding value = new EditingBinding(res, res, false) {
        public void commit() {
          for (String b : getKnownChilds()) {
            // if(facade.getKindsOfChildren().containsKey(b)){
            // continue;
            // }
            Binding binding = getBinding(b);
            Object value = binding.getValue();

            if (binding instanceof EditingBinding) {
              if (((EditingBinding) binding).isResetToNull()) {
                ((EditingBinding) binding)
                    .setResetToNull(false);
                setPropValue(b, binding, null);
                continue;
              }

            }

            // int count = 0;
            // if (value instanceof Collection<?>) {
            // Collection c = (Collection) value;
            // for (Iterator iterator = c.iterator(); iterator
            // .hasNext();) {
            // Object object = (Object) iterator.next();
            // if (object instanceof NullValue) {
            // iterator.remove();
            // count++;
            // }
            // }
            // for (int a = 0; a < count; a++) {
            // c.add(null);
            // }
            // }
            try {
              // if (value instanceof Collection) {
              // Collection c = (Collection) value;
              // if (c.size() != 0) {
              // Object obj = c
              // .toArray(new Object[c.size()])[c
              // .size() - 1];
              // if (isSupported(obj)) {
              // setPropValue(b, binding, value);
              // }
              // } else {
              // setPropValue(b, binding, value);
              // }
              // } else {
              // if (isSupported(value)) {
              // setPropValue(b, binding, value);
              // }
              // }
              setPropValue(b, binding, value);
            } catch (Exception e) {
              MessageDialog.openError(Display.getDefault()
                  .getActiveShell(), "Error", e.getMessage());
              throw new RuntimeException(e);
            }
          }
        }
      };
      value.setName("New Value");
      value.setReadOnly(false);

      Binding combo = bnd.getBinding("combo");
      combo.setName("All Available Properties");
      combo.setReadOnly(false);
      combo.setAutoCommit(true);
      combo.setRealm(realm);
      combo.setRequired(true);

      combo.setAdapter(ITextLabelProvider.class,
          new TextProviderAdapter() {

            public String getText(Object object) {
              return ((Field) object).name;
            }
          });

      ComboEnumeratedValueSelector<Field> fields = new ComboEnumeratedValueSelector<Field>(
          combo);
      fields.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false));

      IValueListener l = new VCHListener(value, editor, res, inner);
      combo.addValueListener(l);

      editor.add(fields);

      if (rStr.size() != 0) {
        combo.setValue(rStr.toArray()[0], null);
      }

      TitledDialog tid = new TitledDialog(editor) {

        protected void okPressed() {
          ((Binding) value).commit();
          Map<String, Object> map = res.getProperties();
          for (String s : map.keySet()) {
            if (fillDefault) {
              facade.setPropertyValue(s, res, true, callback);
            } else {
              facade.setPropertyValue(s, res, false, callback);
            }
            break;

          }
          super.okPressed();
        }
      };
      // tid.getShell().pack(true);
      tid.open();
    }

    private Collection<String> getFullRealm() {
      Field[] f = facade.getFields();
      ArrayList<String> fs = new ArrayList();
      for (Field tmp : f) {
        if (!(tmp instanceof PGAEField) && !(tmp instanceof CGAEField)) {
          if (!tmp.name.equals(Entity.KEY_RESERVED_PROPERTY)) {
            fs.add(tmp.name);
          }
        }

      }
      return fs;
    }

    private void changeEditor(final CompositeEditor parent,
        CompositeEditor[] arr, Field fN, Field fO, Entity e,
        Binding value) {
      if (arr[0] != null) {
        parent.remove(arr[0]);
        arr[0].dispose();
      }

      String oldPr = "";
      if (fO != null) {
        oldPr = fO.name;
      }
      String newPr = fN.name;

      if (e.hasProperty(oldPr)) {
        e.removeProperty(oldPr);
        Collection<String> coll = value.getKnownChilds();
        for (String id : coll) {
          value.getBinding(id).dispose();
        }
      }
      e.setProperty(newPr, null);
      arr[0] = new CompositeEditor(value, Container.GROUP);
      arr[0].setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, true));

      EditorUtility.createBindingsWithButton(e, arr[0], value,
          new Field[] { fN }, facade, false);
      parent.add(arr[0]);
      Display.getCurrent().asyncExec(new Runnable() {

        public void run() {
          parent.getControl().getShell().pack(true);
          parent.getControl().getShell().layout(true, true);
        }
      });

    }

    private Collection<Field> getFullFieldRealm() {
      Field[] f = facade.getFields();
      ArrayList<Field> fs = new ArrayList();
      for (Field tmp : f) {
        if (!(tmp instanceof PGAEField) && !(tmp instanceof CGAEField)) {
          if (!tmp.name.equals(Entity.KEY_RESERVED_PROPERTY)) {
            fs.add(tmp);
          }
        }
      }
      return fs;
    }

    public Menu getMenu(Menu parent) {
      throw new UnsupportedOperationException();
    }

  }

  private void jdbcExportAction(final ImportData data, BaseDataFacade tFacade) {
    IWriter temporaryWriter = new XmlWriterImpl();
    try {
      // Import data inside temporary storage
      File tmpFile = File.createTempFile("temp_jdbcImport", ".xml");
      String dataOut = tmpFile.getCanonicalPath();
      data.outPut = dataOut;
      importDataFromGoogleDataBaseToResource(data, temporaryWriter,
          tFacade, true);

      final HashMap<String, String> types = new HashMap<String, String>();
      final String[] kinds = new String[1];
      kinds[0] = null;
      final int[] maxSize = new int[1];
      maxSize[0] = 300;

      HandlerBase handler = new HandlerBase() {

        private static final String PROPERTY_TAG = "property";

        private static final String NAME = "name";
        private static final String VALUE = "value";
        private static final String CLASS = "type";
        private static final String KIND_TAG = "kind";
        private static final String ENTITY_TAG = "entity";

        public void startElement(String name, AttributeList attributes)
            throws SAXException {
          if (name.equals(PROPERTY_TAG)) {
            String type = attributes.getValue(CLASS);
            String id = attributes.getValue(NAME);
            String value = attributes.getValue(VALUE);
            if (value != null && value.length() > maxSize[0]) {
              maxSize[0] = value.length();
            }

            if (types.containsKey(id)) {
              if (type.equals("null")) {
                types.put(id, type);
              } else if (!type.equals(types.get(id))) {
                types.put(id, "java.lang.String");
              }
            } else {
              if (type == null) {
                types.put(id, "null");
              } else {
                types.put(id, type);
              }
            }
          } else if (name.equals(ENTITY_TAG)) {
            if (kinds[0] == null) {
              String kind = attributes.getValue(KIND_TAG);
              kinds[0] = kind;
            }
          }
        }
      };

      FileInputStream fIs = new FileInputStream(tmpFile);
      SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
      JDBCSaver saverJDBC = new JDBCSaver(tFacade);
      XmlReaderImpl reader = new XmlReaderImpl(tFacade);

      parser.parse(fIs, handler);
      fIs.close();
      saverJDBC.setConnectionProperties(data.jdbcConnection,
          data.databaseLogin, data.databasePasswd);
      saverJDBC.setDriverName(data.jdbcDriverClassName);
      saverJDBC.setKind(kinds[0]);
      saverJDBC.setTypes(types);
      saverJDBC.setPath((ArrayList<String>) data.jdbcDriverClassPath
          .clone());
      saverJDBC.setResourceName(dataOut);
      saverJDBC
          .setMaxSizeOfColumns(maxSize[0] > 8000 ? 8000 : maxSize[0]);
      ExportData expData = new ExportData();
      expData.outPut = dataOut;

      saverJDBC.initSaveProcedure();
      ExportJob job = new ExportJob("Import data inside data Storage");
      job.init(reader, expData, saverJDBC);
      job.schedule();

      // tmpFile.delete();

    } catch (IOException e) {
      e.printStackTrace();
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (SAXException e) {
      e.printStackTrace();
    }
  }

  private final class DuplicateEntityAction extends Action {
    private DuplicateEntityAction(String text) {
      super(text);
    }

    public void run() {
      final OperationCallback callback = new OperationCallback() {

        public void passed(Object object) {
          facade.updateFields();
          doRefresh();
        }

        public void failed(Exception exception) {
          MessageDialog.openError(Display.getDefault()
              .getActiveShell(), "Error", exception.getMessage());
        }
      };
      TitleAreaDialog tid = new TitleAreaDialog(Display.getDefault()
          .getActiveShell()) {

        private Spinner sp;
        private Label l1;

        protected Control createDialogArea(
            org.eclipse.swt.widgets.Composite parent) {
          org.eclipse.swt.widgets.Composite p = new org.eclipse.swt.widgets.Composite(
              (org.eclipse.swt.widgets.Composite) super
                  .createDialogArea(parent),
              SWT.NONE);
          p.setLayout(new GridLayout(2, false));
          p.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

          Field[] f = facade.getFields();
          ArrayList<String> fs = new ArrayList();
          for (Field tmp : f) {
            if (!(tmp instanceof PGAEField)) {
              if (!tmp.name.equals(Entity.KEY_RESERVED_PROPERTY)) {
                fs.add(tmp.name);
              }
            }
          }

          l1 = new Label(p, SWT.NONE);
          l1.setText("Select number of copies:");
          l1.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false,
              false));

          sp = new Spinner(p, SWT.READ_ONLY | SWT.BORDER | SWT.WRAP);
          sp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
              false));
          sp.setIncrement(10);
          sp.setSelection(10);
          sp.setMaximum(10000);
          sp.setMinimum(1);

          sp.setDigits(0);
          return p;

        }

        protected void okPressed() {
          int selection = sp.getSelection();
          if (!currentSelection.isEmpty()) {
            Object selected = currentSelection.getFirstElement();
            if (selected instanceof Entity) {
              facade.duplicateEntity((Entity) selected,
                  selection, callback);
            }
          }
          super.okPressed();
        }

      };

      if (currentSelection.isEmpty()) {
        MessageDialog.openError(Display.getDefault().getActiveShell(),
            "Error", "Selected entity should not be empty");
        return;
      }

      tid.create();
      tid.getShell().setSize(350, 170);
      tid.setTitle("Parameters dialog");
      tid.setMessage("Please enter number of copies");
      tid.open();
      return;
    }
  }

  public final class CreateAction extends Action {
    {
      setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(
          Activator.PLUGIN_ID, "/icons/add_exc.gif"));
    }

    private CreateAction(String text) {
      super(text);
    }

    public void run() {
      com.google.apphosting.api.ApiProxy
          .setEnvironmentForCurrentThread(new FakeEnvironment(
              getAppId()));
      final Entity entity = new Entity(facade.getKind());

      CompositeEditor editor = new CompositeEditor();
      final EditingBinding bnd = new EditingBinding(entity, entity, false);
      bnd.setName("New " + facade.getKind());
      bnd.switchParsingMode(true);
      editor.setBinding(bnd);
      // Field[] full = getAllFields();
      EditorUtility.createBindingsWithButton(entity, editor, bnd,
          facade.getFields(), facade, true);

      final TitledDialog dlg = new EditDialog(editor, true);
      dlg.setResizable(true);
      DisposeBindingListener.linkBindingLifeCycle(bnd, editor);
      dlg.open();
    }
  }

  public String[] openDetailDialog(String kind) {
    ApiProxy.setEnvironmentForCurrentThread(new FakeEnvironment(getAppId()));
    CompositeEditor editor = new CompositeEditor();
    final Binding bnd = new Binding(String.class);
    bnd.setName("Key details");

    editor.setBinding(bnd);

    final ListEnumeratedValueSelector<Field> vl = new ListEnumeratedValueSelector<Field>();
    final DetailsFilterDialog dlg = new DetailsFilterDialog(editor, vl);
    vl.setAsCheckBox(true);
    dlg.setResizable(true);
    editor.add(vl);
    final OrderedRealm<Field> realm = new OrderedRealm<Field>();
    bnd.setDescription("Capturing properties...");
    vl.setRealm(realm);

    DisposeBindingListener.linkBindingLifeCycle(bnd, editor);
    final BaseDataFacade baseDataFacade = new BaseDataFacade(kind,
        facade.getProject(), facade.isDebug());
    baseDataFacade.setNamespace(facade.getNamespace());
    baseDataFacade.setLimit(100);
    Thread thread = new Thread() {
      public void run() {
        try {
          Entity[] query = baseDataFacade.query(
              baseDataFacade.getDefaultQuery(),
              new NullProgressMonitor());
          Field[] determineFields = baseDataFacade
              .determineFields(Arrays.asList(query));
          for (Field f : determineFields) {
            if (f.getType() != null
                && Comparable.class.isAssignableFrom(f
                    .getType())) {
              realm.add(f);
            } else if (f.getType() == Text.class) {
              realm.add(f);
            } else if (f.getType() == Key.class) {
              realm.add(f);
            }
          }
          Display.getDefault().syncExec(new Runnable() {

            public void run() {
              dlg.setMessage("Please check properties which should be displayed in details");
            }
          });

        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    };
    thread.setDaemon(true);
    thread.start();
    dlg.open();
    if (dlg.selection != null) {
      IStructuredSelection s = dlg.selection;
      Object[] ar = s.toArray();
      String[] result = new String[ar.length];
      for (int a = 0; a < ar.length; a++) {
        result[a] = ((Field) ar[a]).name;
      }
      return result;
    }
    return null;
  }

  public AbstractUIElement<?> findEditor(Container root, String id) {
    List<AbstractUIElement<?>> children = root.getChildren();
    for (AbstractUIElement<?> c : children) {
      if (c instanceof IPropertyEditor<?>) {
        IPropertyEditor<?> m = (IPropertyEditor<?>) c;
        if (m instanceof CompositeEditor) {
          CompositeEditor ce = (CompositeEditor) m;
          String idd = ((CompositeEditor) m).getId();
          if (idd != null && idd.equals(id)) {
            AbstractUIElement<?> findEditor = findEditor(ce, id);
            if (findEditor != null) {
              return findEditor;
            }
          }
        }
        IBinding mBind = m.getBinding();
        String idd = null;
        if (mBind != null && (idd = mBind.getId()) != null
            && idd.equals(id)) {
          return c;
        }
      }
      if (c instanceof Container) {
        AbstractUIElement<?> findEditor = findEditor((Container) c, id);
        if (findEditor != null) {
          return findEditor;
        }
      }
      if (c instanceof LinkElement) {
        LinkElement le = (LinkElement) c;
        String idd = le.getId();
        if (idd != null && idd.equals(id)) {
          return c;
        }
      }
    }
    return null;
  }

  private void openSubDialog(Object selection) {
    ApiProxy.setEnvironmentForCurrentThread(new FakeEnvironment(getAppId()));
    Object property = ((Entity) selection)
        .getProperty(BaseDataFacade.ONPOSITIVE_MAGIC_SHORTENED_PROPERTIES);
    if (property != null) {
      try {
        selection = facade.queryFull((Entity) selection);
      } catch (IOException e1) {
        MessageDialog.openError(Display.getCurrent().getActiveShell(),
            "Error", e1.getMessage());
        return;
      }
    }
    final com.google.appengine.api.datastore.Entity e = (Entity) selection;
    final CompositeEditor editor = new CompositeEditor();
    final EditingBinding bnd = new EditingBinding(selection, e, true);

    bnd.setAutoCommit(true);
    bnd.setName(e.getKey().toString());
    editor.setBinding(bnd);

    final TitledDialog dlg = new EditDialog(editor, true);
    dlg.setResizable(true);
    ArrayList<Entity> al = new ArrayList();
    al.add((Entity) selection);
    Field[] fields = facade.determineFields(al);

    bnd.switchParsingMode(true);
    EditorUtility.createBindingsWithButton(e, editor, bnd, fields, facade,
        true);
    DisposeBindingListener.linkBindingLifeCycle(bnd, editor);
    dlg.open();
  }

  public boolean open(Object selection, boolean drawParentLink) {
    // ApiProxy.setEnvironmentForCurrentThread(new
    // FakeEnvironment(getAppId()));
    ApiProxy.setEnvironmentForCurrentThread(new FakeEnvironment(getAppId(),
        facade.namespace));
    Object property = ((Entity) selection)
        .getProperty(BaseDataFacade.ONPOSITIVE_MAGIC_SHORTENED_PROPERTIES);
    if (property != null) {
      try {
        selection = facade.queryFull((Entity) selection);
      } catch (IOException e1) {
        MessageDialog.openError(Display.getCurrent().getActiveShell(),
            "Error", e1.getMessage());
        return false;
      }
    }
    final com.google.appengine.api.datastore.Entity e = (Entity) selection;
    final CompositeEditor editor = new CompositeEditor();
    editor.setLayout(new GridLayout());
    final EditingBinding bnd = new EditingBinding(selection, e, true);

    bnd.setAutoCommit(true);
    bnd.setName(e.getKey().toString());
    editor.setBinding(bnd);

    final TitledDialog dlg = new EditDialog(editor, drawParentLink);//
    dlg.setResizable(true);

    // Field[] p = facade.getpFields();
    Field[] full = getAllFields();
    bnd.switchParsingMode(true);
    EditorUtility.createBindingsWithButton(e, editor, bnd, full, facade,
        true);
    DisposeBindingListener.linkBindingLifeCycle(bnd, editor);
    dlg.create();
    int ch = dlg.open();

    if (ch == Window.OK) {
      return true;
    }

    return false;
    // refreshBindings(bnd, e);
  }

  private Field[] getAllFields() {
    Field[] c = facade.getChFields();
    Field[] f = facade.getFields();
    Field[] full = null;

    if (c == null && f == null) {
      full = new Field[0];
    } else {

      int cLen = 0;
      if (c != null) {
        cLen = c.length;
      }

      full = new Field[f.length + cLen/* + p.length */];

      if (f.length != 0) {
        System.arraycopy(f, 0, full, 0, f.length);
      }
      // if(p.length != 0){
      // System.arraycopy(p,0,full,f.length, p.length);
      // }
      if (c != null && c.length != 0) {
        System.arraycopy(c, 0, full, f.length/* + p.length */, c.length);
      }
    }
    return full;
  }

  private void refreshBindings(EditingBinding b, Entity e) {
    String id = Entity.KEY_RESERVED_PROPERTY;
    b.getBinding(id).setReadOnly(b.getBinding(id).isReadOnly());
    for (String ch : b.getKnownChilds()) {
      b.getBinding(ch).setReadOnly(b.getBinding(ch).isReadOnly());
    }
  }

  public void open(Object selection, boolean drawParentLink, boolean edit,
      IUpdateList callBList) {
    ApiProxy.setEnvironmentForCurrentThread(new FakeEnvironment(getAppId()/*
                                       * ,
                                       * facade
                                       * .
                                       * namespace
                                       */));
    Object property = ((Entity) selection)
        .getProperty(BaseDataFacade.ONPOSITIVE_MAGIC_SHORTENED_PROPERTIES);
    if (property != null) {
      try {
        selection = facade.queryFull((Entity) selection);
      } catch (IOException e1) {
        MessageDialog.openError(Display.getCurrent().getActiveShell(),
            "Error", e1.getMessage());
        return;
      }
    }

    final com.google.appengine.api.datastore.Entity e = (Entity) selection;
    final CompositeEditor editor = new CompositeEditor();
    final EditingBinding bnd = new EditingBinding(selection, e, edit);

    bnd.setAutoCommit(true);
    bnd.setName(e.getKey().toString());
    editor.setBinding(bnd);

    final TitledDialog dlg = new EditDialog(editor, drawParentLink);//
    if (callBList != null)
      ;
    ((EditDialog) dlg).setUpdatingCallback(callBList);
    dlg.setResizable(true);

    Field[] full = getAllFields();
    EditorUtility.createBindingsWithButton(e, editor, bnd, full, facade,
        true);
    DisposeBindingListener.linkBindingLifeCycle(bnd, editor);

    dlg.open();
  }

  public void open(Object selection, boolean drawParentLink,
      IUpdateList callBList) {
    ApiProxy.setEnvironmentForCurrentThread(new FakeEnvironment(getAppId()));
    Object property = ((Entity) selection)
        .getProperty(BaseDataFacade.ONPOSITIVE_MAGIC_SHORTENED_PROPERTIES);
    if (property != null) {
      try {
        selection = facade.queryFull((Entity) selection);
      } catch (IOException e1) {
        MessageDialog.openError(Display.getCurrent().getActiveShell(),
            "Error", e1.getMessage());
        return;
      }
    }

    final com.google.appengine.api.datastore.Entity e = (Entity) selection;
    final CompositeEditor editor = new CompositeEditor();
    final EditingBinding bnd = new EditingBinding(selection, e, true);

    bnd.setAutoCommit(true);
    bnd.setName(e.getKey().toString());
    editor.setBinding(bnd);

    final TitledDialog dlg = new EditDialog(editor, drawParentLink);//
    if (callBList != null)
      ;
    ((EditDialog) dlg).setUpdatingCallback(callBList);
    dlg.setResizable(true);

    Field[] full = getAllFields();
    EditorUtility.createBindingsWithButton(e, editor, bnd, full, facade,
        true);
    DisposeBindingListener.linkBindingLifeCycle(bnd, editor);
    dlg.open();
  }

  public String getAppId() {
    return facade.getAppId();
  }

  public void createPartControl(Composite parent) {

  }

  public void doRefresh() {
    facade.refresh();
  }

  public Action createActions(ToolBarManager toolBarManager, boolean full) {
    toolBarManager.add(new CreateAction("Create new entity"));
    DeleteAction action = new DeleteAction("Delete selected");
    toolBarManager.add(action);
    toolBarManager.add(new RefreshAction("Refresh view"));
    if (full) {
      toolBarManager.add(new Separator());
      toolBarManager.add(new ImportAction());
      toolBarManager.add(new ExportAction());
      toolBarManager.add(new ChangeNameSpaceAction());
      toolBarManager.add(new ShowQueueFunctionsAction());
    }
    return action;
  }

  public IAction createCreateAction() {
    return new CreateAction("Create new entity");
  }

  public IAction createImportAction() {
    return new ImportAction();
  }

  public IAction createExportAction() {
    return new ExportAction();
  }

  public IAction createBulkExportAction() {
    return new BulkExportAction();
  }

  public IAction createBulkImportAction() {
    return new BulkImportAction();
  }

  public IAction createEditAction() {
    Action action = new Action("Edit selected") {

      {
        setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(
            Activator.PLUGIN_ID, "/icons/text_edit.gif"));

      }

      public void run() {
        boolean needRefresh = open(currentSelection.getFirstElement(),
            true);
        if (needRefresh) {
          facade.updateFields();
          doRefresh();
        }
      }

    };
    return action;
  }

  public IAction createDeleteAction() {
    DeleteAction action = new DeleteAction("Delete selected");
    return action;
  }

  public IAction createRefreshAction() {
    return new RefreshAction("Refresh view");
  }

  private void importDataFromGoogleDataBaseToResource(ImportData data,
      IWriter writer, BaseDataFacade tFacade, boolean needJoin) {

    ImportJob importJob = new ImportJob("Import for " + tFacade.getKind()
        + "  skind in process...");
    importJob.setFacade(tFacade);
    importJob.setParameters(data);
    importJob.setWriter(writer);
    importJob.schedule();
    if (needJoin) {
      try {
        importJob.join();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }

  }

  public static void showErrorDialog(final String message) {
    Display.getDefault().asyncExec(new Runnable() {

      public void run() {
        MessageDialog.openError(Display.getCurrent().getActiveShell(),
            "Error", message);
      }
    });
  }

  private boolean resultsComparison(Entity[] arr1, Entity[] arr2,
      boolean printM) {
    int m = 0;
    int u = 0;
    int a = 0;
    if (arr1.length != arr2.length) {
      System.out
          .println("UNLIKE! " + " Reason: Arrays size is different");
      return false;
    }

    System.out.println("== Arrays Size is: " + arr1.length + "==");

    boolean flag = true;
    for (int i = 0; i < arr1.length; i++) {
      Entity tmp1 = arr1[i];
      Entity tmp2 = arr2[i];

      Map<String, Object> props1 = tmp1.getProperties();
      Map<String, Object> props2 = tmp2.getProperties();

      Set<String> s1 = props1.keySet();
      Set<String> s2 = props2.keySet();

      if (s1.size() != s2.size()) {
        System.out
            .println("UNLIKE! "
                + " Reason:  Size of maps of the properties is different");
        return false;
      }

      if (!(s1.containsAll(s2) && s2.containsAll(s1))) {
        System.out.println("UNLIKE! " + "Entity: " + i
            + " Reason: Keys for sets of entities is different");
        return false;
      }

      for (Iterator<String> it = s1.iterator(); it.hasNext();) {
        a++;
        String key = it.next();
        if (true) {// !key.equals(Entity.KEY_RESERVED_PROPERTY)) {

          Object val1 = props1.get(key);
          Object val2 = props2.get(key);

          if (val1 == null && val2 == null) {
            m++;
            if (printM) {
              System.out.println("Match " + "Index: " + i
                  + " PropKey: " + key + " Reason: Ok!");
            }
          } else if ((val1 == null && val2 != null)
              || (val2 == null && val1 != null)) {
            u++;
            System.out
                .println("UNLIKE! "
                    + "Index: "
                    + i
                    + " PropKey: "
                    + key
                    + " Reason: The values for the entities is different THE ONE IS NULL");
            flag = false;
          } else if (!val1.equals(val2)) {
            if (val1 instanceof Date) {
              String sd1 = StringInputOutput.toString(val1);
              String sd2 = StringInputOutput.toString(val1);
              if (sd1.equals(sd2)) {
                m++;
                if (printM) {
                  System.out.println("Match " + "Index: " + i
                      + " PropKey: " + key
                      + " Reason: Ok!");
                }
                continue;
              }
            }
            u++;
            System.out
                .println("UNLIKE! "
                    + "Index: "
                    + i
                    + " PropKey: "
                    + key
                    + " Reason: The values for the entities is different NOT EQUAL");
            flag = false;
          } else {
            m++;
            if (printM) {
              System.out.println("Match " + "Index: " + i
                  + " PropKey: " + key + " Reason: Ok!");
            }
          }
        }
      }
    }
    System.out.println("Checked: " + a + " Differences: " + u + " Maches: "
        + m);
    if (!flag) {
      return false;
    }

    return true;
  }

  public static class NamespacesRealm {
    @Caption("AllNamespaces")
    ArrayList<String> namespaces = new ArrayList();

    @Caption("CurrentNamespace")
    String current;
  }

  @SuppressWarnings("unchecked")
  private void changeNamespace() {
    final NamespacesRealm r = new NamespacesRealm();
    try {
      List<String> nr = getNamespacesList();

      r.namespaces.addAll(nr);
    } catch (CoreException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }

    Binding bnd = new Binding(r);
    bnd.setAutoCommit(true);

    bnd.setName("Namespace list");
    bnd.setDescription("Please choose namespace");

    CompositeEditor editor = new CompositeEditor(bnd);
    Container c1 = new Container();
    c1.setLayoutManager(new OneElementOnLineLayouter());
    Container c2 = new Container();
    Container all = new Container();

    GridData c1gd = new GridData(SWT.FILL, SWT.FILL, true, true);
    c1gd.horizontalIndent = 0;
    c1gd.verticalIndent = 0;
    c1.setLayoutData(c1gd);
    // c1.setBordered(true);

    c2.setLayout(new GridLayout(1, false));
    c2.setLayoutData(new GridData(SWT.RIGHT, SWT.BOTTOM, false, false));
    // c2.setBordered(true);

    GridLayout alll = new GridLayout(2, false);
    alll.marginWidth = 1;
    alll.marginHeight = 1;
    all.setLayout(alll);

    GridData allgd = new GridData(SWT.FILL, SWT.FILL, true, true);
    allgd.horizontalAlignment = 0;
    allgd.verticalAlignment = 0;
    all.setLayoutData(allgd);
    // all.setBordered(true);

    final Binding currNSBinding = bnd.getBinding("current");

    final OneLineTextElement<String> current = new OneLineTextElement(
        currNSBinding);
    current.setReadOnly(true);

    final Binding nsListBinding = bnd.getBinding("namespaces");
    nsListBinding.setMaxCardinality(1);
    final ListEnumeratedValueSelector<String> l = new ListEnumeratedValueSelector<String>(
        nsListBinding) {

      protected void updateSize(TableViewer newCheckList) {
        TableColumn tableColumn = (TableColumn) columnWidget;
        tableColumn.pack();
      }
    };

    l.addSelectionChangedListener(new ISelectionChangedListener() {

      public void selectionChanged(SelectionChangedEvent event) {
        ISelection s = event.getSelection();
        if (s instanceof StructuredSelection) {
          StructuredSelection ss = (StructuredSelection) s;
          String selected = (String) ss.getFirstElement();
          if (selected != null) {
            currNSBinding.setValue(selected, null);
          }

        }
        return;
      }
    });

    c1.add(current);
    c1.add(l);

    ButtonSelector add = new ButtonSelector();
    add.addListener(SWT.Selection, new SWTEventListener() {

      public void handleEvent(AbstractUIElement element, Event event) {
        currNSBinding.setName("Current Namespace");
        currNSBinding.setDescription("Add New Namespace");
        currNSBinding.setValue("", null);
        CompositeEditor ce = new CompositeEditor(currNSBinding) {

          protected void update(AbstractUIElement<?> container) {
            super.update(container);
            getControl().pack(true);
          }
        };

        OneLineTextElement<String> f = new OneLineTextElement(
            currNSBinding);
        ce.setLayout(new FillLayout());
        ce.add(f);

        TitledDialog td = new TitledDialog(ce) {

          protected void okPressed() {
            currNSBinding.commit();
            super.okPressed();
          }

          public int open() {
            int ch = super.open();
            return ch;
          }
        };
        td.create();
        td.getShell().setSize(300, 190);
        td.open();

        String curr = (String) currNSBinding.getValue();

        if (!l.getRealm().contains(curr)) {// curr.length() != 0) {
          l.addValue(curr);
        }
        return;
      }

    });
    add.setText("add");
    add.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, false, false));

    ButtonSelector remove = new ButtonSelector();
    remove.addListener(SWT.Selection, new SWTEventListener() {

      public void handleEvent(AbstractUIElement element, Event event) {
        IStructuredSelection s = l.getSelection();
        StructuredSelection ss = (StructuredSelection) s;
        String selected = (String) ss.getFirstElement();
        if (selected.length() != 0) {
          l.removeValue(selected);
        }
        return;
      }

    });
    remove.setText("remove");
    remove.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, true));

    c2.add(add);
    c2.add(remove);

    all.add(c1);
    all.add(c2);
    editor.add(all);

    ShowNSListDialog dlg = new ShowNSListDialog(editor);
    dlg.open();
  }

  private List<String> getNamespacesList() throws CoreException, Exception {
    String[] realm = AnnotationsStorage.getKnownNameSpaces(facade
        .getProject().getProject());
    List<String> nr = Arrays.asList(realm);
    List<String> nnr = new LinkedList<String>();
    nnr.addAll(nr);

    List<String> q = BaseStatistics.queryGoogleStatistic("__namespace__",
        facade.getProject(), new NullProgressMonitor(), "",
        facade.isDebug());

    if (q != null) {
      for (String qq : q) {
        if (qq == null) {
          continue;
        }
        if (!nnr.contains(qq)) {
          nnr.add(qq);
        }
      }
    }
    return nnr;
  }

  private List<String> getKindsList(String namespace, boolean debug,
      IJavaProject javaGaeProject) throws Exception {
    List<String> kinds = BaseStatistics.queryGoogleStatistic("__kind__",
        javaGaeProject, new NullProgressMonitor(), namespace, debug);

    String[] lk = AnnotationsStorage.getKnownKinds(javaGaeProject
        .getProject());
    for (String lkk : lk) {
      if (!kinds.contains(lkk)) {
        kinds.add(lkk);
      }
    }
    return kinds;
  }

  public Action createDuplicateEntityAction() {
    return new DuplicateEntityAction("Duplicate selected entity");
  }

  private boolean checkPossibilityOfExport() {
    final boolean[] flag = new boolean[1];
    Display.getDefault().syncExec(new Runnable() {

      public void run() {
        final IPreferenceStore store = Activator.getDefault()
            .getPreferenceStore();
        boolean remember = store.getBoolean(PREF_REMEMBER_DECISION);
        boolean showDialog = store.getBoolean(PREF_EXPORT);
        int open = IDialogConstants.NO_ID;
        if (!remember) {
          String projectName = facade.getProject().getProject()
              .getName();
          String appId = facade.getAppId();
          boolean isLocal = facade.isDebug();
          String server = "local";
          if( !isLocal){
            server = "remote";
          }
          String question = "Do you really want to import data to <"
              + projectName + "> project with id <" + appId
              + "> to the " + server + " server?";
          MessageDialogWithToggle dialog = MessageDialogWithToggle
              .openYesNoQuestion(Display.getCurrent()
                  .getActiveShell(), "Export Confirmation",
                  question, "Remember Decision", false,
                  store, PREF_EXPORT);
          boolean toggleState = dialog.getToggleState();
          store.setValue(PREF_REMEMBER_DECISION, toggleState);
          open = dialog.getReturnCode();
        } else {
          if (showDialog) {
            open = IDialogConstants.YES_ID;
          } else {
            open = IDialogConstants.NO_ID;
          }
        }

        if (open == IDialogConstants.YES_ID) {
          flag[0] = true;
          store.setValue(PREF_EXPORT, true);
        } else {
          store.setValue(PREF_EXPORT, false);
        }
      }
    });
    boolean result = flag[0];
    return result;
  }

  private void executeExport(final ExportData data, BaseDataFacade facade) {
    if (data.multiExport) {

      String[] parts = data.outPut.split(",");
      String path = parts[0].replaceAll("&#044;", ",");
      for (int i = 1; i < parts.length; i++) {
        String fileName = parts[i].replaceAll("&#044;", ",");
        String kind = fileName.split("\\.")[0];

        ExportData dat = new ExportData();
        if (data.asCsv) {
          dat.asCsv = true;
          dat.asXML = false;
          dat.asBinary = false;
        } else if (data.asXML) {
          dat.asCsv = false;
          dat.asXML = true;
          dat.asBinary = false;
        } else if (data.asBinary) {
          dat.asCsv = false;
          dat.asXML = false;
          dat.asBinary = true;
          dat.jdbcDriverClassName = new String(
              data.jdbcDriverClassName);
          data.jdbcConnection = new String(data.jdbcConnection);
          data.jdbcDriverClassPath = (ArrayList<String>) data.jdbcDriverClassPath
              .clone();
        }

        dat.outPut = path + File.separator + parts[i];
        BaseDataFacade tFacade = new BaseDataFacade(kind,
            facade.getProject(), facade.isDebug());
        tFacade.setNamespace(facade.getNamespace());
        executeExports(dat, tFacade);
      }
    } else {
      // data.jdbcConnection =
      // "jdbc:mysql://localhost:3306/data";//
      // data.jdbcDriverClassName = "com.mysql.jdbc.Driver";
      executeExports(data, facade);
    }
  }

  private void executeExports(final ExportData data,
      final BaseDataFacade tFacade) {
    final DataSaver saver = new DataSaver(tFacade) {

      private int count = 0;
      double performed = 0;

      public void save(Entity[] readed) {

        this.getMonitor().internalWorked(performed);
        this.getMonitor().subTask("\nSaving data from: " + data.outPut);
        tFacade.store(readed, new OperationCallback() {

          public void passed(Object object) {
            tFacade.refresh();
          }

          public void failed(Exception exception) {
            showErrorDialog("Error in exporting data to data storage: \n"
                + exception.getLocalizedMessage());

          }
        });
        count += readed.length;
        this.getMonitor().setTaskName(
            "Export in process... \nEntities saved - " + count);
        performed = (((double) readed.length) / this.getSize()) * 100;
      }

      public void onFinish() {
        // Do nothing

      }

    };

    if (data.asCsv) {

      IReader csvReader = new IReader() {

        private String decodeCSV(String old) {
          String tmp = old;
          tmp = tmp.replaceAll("&ltcomma&gt", ",");
          tmp = tmp.replaceAll("\\\\n", "\n");
          tmp = tmp.replaceAll("\\\\r", "\r");
          return tmp;
        }

        public void readData(String input, DataSaver saver,
            int numberOfReaded) {
          String inputStr;
          String paramsStr;
          try {
            // DataInputStream dIs_input = new DataInputStream(
            // new BufferedInputStream(
            // new FileInputStream(input)));
            BufferedReader dIs_input = new BufferedReader(
                new InputStreamReader(
                    new FileInputStream(input), "UTF-8"));
            // new FileReader(input));
            BufferedReader dIs_props = new BufferedReader(
                new InputStreamReader(new FileInputStream(input
                    + PROPS_SUFFIX), "UTF-8"));
            // DataInputStream dIs_props = new DataInputStream(
            // new BufferedInputStream(
            // new FileInputStream(input
            // + PROPS_SUFFIX)));
            // new FileReader(input + PROPS_SUFFIX));

            // int count = 0;
            try {
              String fullSize = dIs_props.readLine();
              String[] splitted = fullSize.split(":");
              if (splitted[0].equals("expected")) {
                long size = Long.parseLong(splitted[1]);
                saver.setSize(size);
              }
            } catch (NumberFormatException e) {
              saver.setSize(0);
            }
            ArrayList<Entity> resultList = new ArrayList<Entity>();
            while ((inputStr = dIs_input.readLine()) != null
                && (paramsStr = dIs_props.readLine()) != null) {
              String[] entitiesVal = StringInputOutput.split(
                  inputStr, ',');
              String[] propsVal = paramsStr.split(",");

              if ((entitiesVal.length/* + 1 */) == propsVal.length) {
                Map<String, Object> props = new HashMap<String, Object>();
                for (int i = 0; i < entitiesVal.length; i++) {
                  String tmpPropVal = propsVal[i];
                  String[] fromProps = tmpPropVal.split(":");
                  if (fromProps.length == 2) {
                    String tmpEntVal = entitiesVal[i];
                    String args = decodeCSV(tmpEntVal);
                    // String args = entitiesVal[i]
                    // .replaceAll("\\,", ","); //
                    // \\\\,
                    // args =
                    // args.replaceAll("\\\\n",
                    // LINE_SEPARATOR);
                    Object data = StringInputOutput
                        .createObject(fromProps[1],
                            args,
                            tFacade.getNamespace());
                    props.put(fromProps[0], data);
                  } else {
                  }
                }
                Key keyOfEntity = (Key) props
                    .get(Entity.KEY_RESERVED_PROPERTY);
                Entity tmp = new Entity(keyOfEntity);
                for (String propName : props.keySet()) {
                  if (!propName
                      .equals(Entity.KEY_RESERVED_PROPERTY)) {
                    tmp.setProperty(propName,
                        props.get(propName));
                  }
                }
                resultList.add(tmp);
                if (resultList.size() == numberOfReaded) {
                  saver.save(resultList
                      .toArray(new Entity[resultList
                          .size()]));
                  resultList.clear();
                }
              } else {
              }
            }

            dIs_input.close();
            dIs_props.close();

            if (resultList.size() != 0) {
              saver.save(resultList.toArray(new Entity[resultList
                  .size()]));
              resultList.clear();
            }

            return;
          } catch (FileNotFoundException e) {
            showErrorDialog("Unable to read data from " + input);
          } catch (IOException e) {
            showErrorDialog("Unable to read data from " + input);
          }
          return;
        }

      };

      ExportJob job = new ExportJob("Export data");
      job.init(csvReader, data, saver);
      job.schedule();

    } else if (data.asXML) {

      final IReader xmlReader = new XmlReaderImpl(tFacade);

      ExportJob job = new ExportJob("Export data");
      job.init(xmlReader, data, saver);
      job.schedule();

    } else if (data.asBinary) {
      JDBCReaderImpl jdbcReader = new JDBCReaderImpl();
      jdbcReader.setExpDat(data);
      jdbcReader.settFacade(tFacade);
      ExportJob job = new ExportJob("Export data");
      job.init(jdbcReader, data, saver);
      job.schedule();
    }
  }

  private void executeImports(final ImportData data, BaseDataFacade tFacade) {
    if (data.asCsv) {
      CsvWriterImpl csvWriter = new CsvWriterImpl(data);
      importDataFromGoogleDataBaseToResource(data, csvWriter, tFacade,
          false);

    } else if (data.asXML) {

      IWriter xmlWriter = new XmlWriterImpl();

      importDataFromGoogleDataBaseToResource(data, xmlWriter, tFacade,
          false);

      return;

    } else if (data.asBinary) {
      jdbcExportAction(data, tFacade);
    }
  }

  private void executeImport(final ImportData data, BaseDataFacade facade) {
    if (data.entitiesOfSelectedKinds) {
      for (String kind : data.kinds) {
        if (kind != null) {
          BaseDataFacade tmpFacade = new BaseDataFacade(kind,
              facade.getProject(), facade.isDebug());
          ImportData tmpData = new ImportData();
          tmpFacade.setNamespace(facade.getNamespace());

          if (data.asCsv) {
            tmpData.asCsv = true;
            tmpData.asXML = false;
            tmpData.asBinary = false;
            tmpData.outPut = data.outPut + File.separator
                + tmpFacade.getKind() + ".csv";
          } else if (data.asBinary) {
            tmpData.asCsv = false;
            tmpData.asXML = false;
            tmpData.asBinary = true;
            tmpData.jdbcConnection = new String(data.jdbcConnection);
            tmpData.jdbcDriverClassName = new String(
                data.jdbcDriverClassName);
            tmpData.jdbcDriverClassPath = (ArrayList<String>) data.jdbcDriverClassPath
                .clone();
          } else if (data.asXML) {
            tmpData.asCsv = false;
            tmpData.asXML = true;
            tmpData.asBinary = false;
            tmpData.outPut = data.outPut + File.separator
                + tmpFacade.getKind() + ".xml";

          }

          tmpData.filterColumns = false;
          tmpData.selectedEntitiesOf = false;
          tmpFacade.setNamespace(facade.getNamespace());
          executeImports(tmpData, tmpFacade);
        }
      }
    } else {

      BaseDataFacade tmpFacade;
      try {
        tmpFacade = (BaseDataFacade) facade.clone();
        tmpFacade.objects = new ArrayList<Entity>();
        // data.jdbcConnection =
        // "jdbc:mysql://localhost:3306/data";//
        // data.jdbcDriverClassName = "com.mysql.jdbc.Driver";

        executeImports(data, tmpFacade);
      } catch (CloneNotSupportedException e) {
      }
    }
  }

}
TOP

Related Classes of com.onpositive.gae.baseviewer.DataStoreTableUI$NamespacesRealm

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.