@Override
 public void dispose() {
   super.dispose();
   ImageUtil.disposeImage("Images.AliasIcon");
   ImageUtil.disposeImage("Images.ConnectedAliasIcon");
   ImageUtil.disposeImage("Images.ConnectionIcon");
   ImageUtil.disposeImage("Images.DriverIcon");
   ImageUtil.disposeImage("Images.QueryIcon");
   ImageUtil.disposeImage("Images.QueryParamIcon");
   ImageUtil.disposeImage("Images.DBResourcesIcon");
 }
 public NewConnectionDropDownAction() {
   setText(Messages.getString("ConnectionsView.Actions.NewConnection"));
   setToolTipText(Messages.getString("ConnectionsView.Actions.NewConnectionToolTip"));
   setImageDescriptor(ImageUtil.getDescriptor("Images.NewConnectionIcon"));
   setMenuCreator(this);
 }
/**
 * Create table script for the selected node.
 *
 * @modified Davy Vanherbergen
 */
public class CreateTableScriptAction extends AbstractDBTreeContextAction {

  private static final ImageDescriptor _image = ImageUtil.getDescriptor("Images.TableIcon");

  /**
   * Custom image for refresh action
   *
   * @see org.eclipse.jface.action.IAction#getImageDescriptor()
   */
  @Override
  public ImageDescriptor getImageDescriptor() {
    return _image;
  }

  /**
   * Set the text for the menu entry.
   *
   * @see org.eclipse.jface.action.IAction#getText()
   */
  @Override
  public String getText() {
    return Messages.getString("DatabaseStructureView.Actions.CreateTableScript");
  }

  /**
   * Create table script for selected node.
   *
   * @see org.eclipse.jface.action.IAction#run()
   */
  @Override
  public void run() {

    TableNode tableNode = (TableNode) _selectedNodes[0];
    ITableInfo info = tableNode.getTableInfo();

    StringBuffer buf = new StringBuffer(4 * 1024);
    String sep = System.getProperty("line.separator");

    try {
      SQLDatabaseMetaData metaData = tableNode.getSession().getMetaData();

      ArrayList<String> pks = new ArrayList<String>();
      PrimaryKeyInfo[] pksInfo = metaData.getPrimaryKey(info);
      for (PrimaryKeyInfo pkInfo : pksInfo) pks.add(pkInfo.getColumnName());

      TableColumnInfo[] columnsInfo = metaData.getColumnInfo(info);
      String tableName = _selectedNodes[0].getQualifiedName();
      buf.append("CREATE TABLE ");
      buf.append(tableName);
      buf.append("(");

      for (TableColumnInfo col : columnsInfo) {
        // String columnName = resultSet.getString(4);
        // String typeName = resultSet.getString(6);
        // String columnSize = resultSet.getString(7);
        // String decimalDigits = resultSet.getString(9);
        // String defaultValue = resultSet.getString(13);
        boolean notNull = "NO".equalsIgnoreCase(col.isNullable());
        String sLower = col.getColumnName().toLowerCase();
        buf.append(sep);
        buf.append(col.getColumnName() + " ");

        buf.append(col.getTypeName());

        boolean bNumeric = false;
        if (sLower.equals("numeric") || sLower.equals("number") || sLower.equals("decimal"))
          bNumeric = true;

        if (sLower.indexOf("char") != -1 || sLower.indexOf("int") != -1) {
          buf.append("(");
          buf.append(col.getColumnSize());
          buf.append(")");

        } else if (bNumeric) {
          buf.append("(");
          buf.append(col.getColumnSize());
          if (col.getDecimalDigits() > 0) buf.append(col.getDecimalDigits());
          buf.append(")");
        }

        if (pks.size() == 1 && pks.get(0).equals(col.getColumnName())) {
          buf.append(" PRIMARY KEY");
        }

        String defaultValue = col.getDefaultValue();
        if (defaultValue != null && !defaultValue.equals("")) {
          buf.append(" default ");
          boolean isSystemValue = bNumeric;

          if (defaultValue.equalsIgnoreCase("CURRENT_TIMESTAMP")) {
            isSystemValue = true;
          }

          if (!isSystemValue) buf.append("'");
          buf.append(defaultValue);
          if (!isSystemValue) buf.append("'");
        }

        if (notNull) {
          buf.append(" not null");
        }
        buf.append(",");
      }
      buf.deleteCharAt(buf.length() - 1);
      buf.append(")" + sep);

      SQLEditorInput input =
          new SQLEditorInput(
              "SQL Editor (" + SQLExplorerPlugin.getDefault().getEditorSerialNo() + ").sql");
      input.setUser(_selectedNodes[0].getSession().getUser());
      IWorkbenchPage page =
          SQLExplorerPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage();

      SQLEditor editorPart =
          (SQLEditor)
              page.openEditor(input, "com.safi.workshop.sqlexplorer.plugin.editors.SQLEditor");
      editorPart.setText(buf.toString());
    } catch (SQLException e) {
      SQLExplorerPlugin.error("Error creating export script", e);
    } catch (PartInitException e) {
      SQLExplorerPlugin.error("Error creating export script", e);
    }
  }

  /**
   * Action is availble when a node is selected
   *
   * @see
   *     com.safi.workshop.sqlexplorer.dbstructure.actions.AbstractDBTreeContextAction#isAvailable()
   */
  @Override
  public boolean isAvailable() {

    if (_selectedNodes.length != 0) {
      return true;
    }
    return false;
  }
}
/** @author Davy Vanherbergen */
public class RollbackAction extends AbstractEditorAction {

  private ImageDescriptor _image = ImageUtil.getDescriptor("Images.EditorRollbackIcon");

  public RollbackAction(SQLEditor editor) {
    super(editor);
  }

  @Override
  public ImageDescriptor getImageDescriptor() {
    return _image;
  }

  @Override
  public String getText() {

    return Messages.getString("SQLEditor.Actions.RollBack");
  }

  @Override
  public String getToolTipText() {

    return Messages.getString("SQLEditor.Actions.RollBack.ToolTip");
  }

  /** Action is available when session doesn't have autocommit */
  @Override
  public boolean isDisabled() {

    if (_editor.getSession() == null) {
      return true;
    }

    return _editor.getSession().isAutoCommit();
  }

  @Override
  public void run() {

    try {

      _editor.getSession().rollback();
      _editor.setMessage(Messages.getString("SQLEditor.Actions.RollBack.Success"));

    } catch (final Exception e) {

      _editor
          .getSite()
          .getShell()
          .getDisplay()
          .asyncExec(
              new Runnable() {

                public void run() {

                  MessageDialog.openError(
                      _editor.getSite().getShell(),
                      Messages.getString("SQLEditor.Actions.RollBack.Error.Title"),
                      e.getMessage());
                }
              });
    }
  }
}
/**
 * Label provider for database structure outline.
 *
 * @author Davy Vanherbergen
 */
public class ConnectionTreeLabelProvider extends LabelProvider {

  private Image _driverImage = ImageUtil.getImage("Images.DriverIcon");

  private Image _inactiveAliasImage = ImageUtil.getImage("Images.AliasIcon");

  private Image _activeAliasImage = ImageUtil.getImage("Images.ConnectedAliasIcon");

  private Image _sessionImage = ImageUtil.getImage("Images.ConnectionIcon");

  private Image _queryImage = ImageUtil.getImage("Images.QueryIcon");

  private Image _queryParamImage = ImageUtil.getImage("Images.QueryParamIcon");

  private Image _dbResImage = ImageUtil.getImage("Images.DBResourcesIcon");

  @Override
  public void dispose() {
    super.dispose();
    ImageUtil.disposeImage("Images.AliasIcon");
    ImageUtil.disposeImage("Images.ConnectedAliasIcon");
    ImageUtil.disposeImage("Images.ConnectionIcon");
    ImageUtil.disposeImage("Images.DriverIcon");
    ImageUtil.disposeImage("Images.QueryIcon");
    ImageUtil.disposeImage("Images.QueryParamIcon");
    ImageUtil.disposeImage("Images.DBResourcesIcon");
  }

  /**
   * Return the image used for the given node.
   *
   * @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object)
   */
  @Override
  public Image getImage(Object element) {
    if (element instanceof Alias) {
      Alias alias = (Alias) element;

      for (User user : alias.getUsers())
        if (!user.getSessions().isEmpty()) return _activeAliasImage;
      return _inactiveAliasImage;
    } else if (element instanceof ManagedDriver) {
      return _driverImage;
    } else if (element instanceof Query) return _queryImage;
    else if (element instanceof QueryParameter) return _queryParamImage;
    else if (element instanceof DriverManager) return _dbResImage;
    return _sessionImage;
  }

  /**
   * Return the text to display
   *
   * @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object)
   */
  @Override
  public String getText(Object element) {
    if (element instanceof Alias) {
      Alias alias = (Alias) element;

      String label = alias.getName();
      int numSessions = 0;

      for (User user : alias.getUsers()) numSessions += user.getConnections().size();

      if (numSessions == 1)
        return label
            + " ("
            + numSessions
            + " "
            + Messages.getString("ConnectionsView.ConnectedAlias.single.Postfix")
            + ")";

      if (numSessions > 1)
        return label
            + " ("
            + numSessions
            + " "
            + Messages.getString("ConnectionsView.ConnectedAlias.multiple.Postfix")
            + ")";

      return label;

    } else if (element instanceof User) {
      User user = (User) element;
      return user.getUserName();

    } else if (element instanceof SQLConnection) {
      SQLConnection connection = (SQLConnection) element;
      String label;

      if (connection.getDescription() == null) {
        SimpleDateFormat fmt = new SimpleDateFormat("HH:mm:ss");
        label =
            Messages.getString("ConnectionsView.ConnectedAlias.ConnectedSince")
                + ' '
                + fmt.format(new Date(connection.getCreatedTime()));
      } else
        label =
            Messages.getString("ConnectionsView.ConnectedAlias.Connection")
                + ' '
                + connection.getDescription();

      if (connection.isPooled())
        label += ' ' + Messages.getString("ConnectionsView.ConnectedAlias.Pooled");
      return label;
    } else if (element instanceof ManagedDriver) {
      return ((ManagedDriver) element).getId()
          + " driver: "
          + ((ManagedDriver) element).getDriverClassName();
    } else if (element instanceof Query) {
      return ((Query) element).getName();
    } else if (element instanceof QueryParameter) {
      return ((QueryParameter) element).getName();
    } else if (element instanceof DriverManager) {
      return "DB Resources";
    }

    return null;
  }
}
  private void addExtensionNodes() {

    String databaseProductName =
        getSession().getRoot().getDatabaseProductName().toLowerCase().trim();

    IExtensionRegistry registry = Platform.getExtensionRegistry();
    IExtensionPoint point = registry.getExtensionPoint("AsteriskSafletDesigner.diagram", "node");
    IExtension[] extensions = point.getExtensions();

    for (IExtension e : extensions) {

      IConfigurationElement[] ces = e.getConfigurationElements();

      for (IConfigurationElement ce : ces) {
        try {

          // include only nodes that are attachted to the schema
          // node..
          String parent = ce.getAttribute("parent-node");
          if (parent.indexOf("catalog") == -1) {
            continue;
          }

          boolean isValidProduct = false;
          String[] validProducts = ce.getAttribute("database-product-name").split(",");

          // include only nodes valid for this database
          for (String validProduct : validProducts) {

            String product = validProduct.toLowerCase().trim();

            if (product.length() == 0) {
              continue;
            }

            if (product.equals("*")) {
              isValidProduct = true;
              break;
            }

            String regex = TextUtil.replaceChar(product, '*', ".*");
            if (databaseProductName.matches(regex)) {
              isValidProduct = true;
              break;
            }
          }

          if (!isValidProduct) {
            continue;
          }

          String imagePath = ce.getAttribute("icon");
          String id = ce.getAttribute("id");
          String type = ce.getAttribute("table-type").trim();

          AbstractNode childNode = (AbstractNode) ce.createExecutableExtension("class");
          childNode.setParent(this);
          childNode.setSession(_session);
          childNode.setType(type);

          String fragmentId = id.substring(0, id.indexOf('.', 28));
          if (imagePath != null && imagePath.trim().length() != 0) {
            childNode.setImage(ImageUtil.getFragmentImage(fragmentId, imagePath));
          }

          _childNames.add(childNode.getLabelText());
          if (!isExcludedByFilter(childNode.getLabelText())) {
            addChildNode(childNode);
          }

        } catch (Throwable ex) {
          SQLExplorerPlugin.error("Could not create child node", ex);
        }
      }
    }
  }