<commit_before>/*
 * IceWM
 *
 * Copyright (C) 1997-2001 Marko Macek
 */
#include "config.h"

#include "ylib.h"
#include "wmbutton.h"

#include "wmaction.h"
#include "wmframe.h"
#include "wmtitle.h"
#include "yxapp.h"
#include "yicon.h"
#include "yprefs.h"
#include "prefs.h"
#include "wpixmaps.h"

static YColor *titleButtonBg = 0;
static YColor *titleButtonFg = 0;

//!!! get rid of this
extern YColor *activeTitleBarBg;
extern YColor *inactiveTitleBarBg;

YFrameButton::YFrameButton(YWindow *parent,
                           YFrameWindow *frame,
                           YAction action,
                           YAction action2):
    YButton(desktop, actionNull),
    fFrame(frame),
    fAction(action),
    fAction2(action2)
{
    reparent(parent, 0, 0);
    if (titleButtonBg == 0)
        titleButtonBg = new YColor(clrNormalTitleButton);
    if (titleButtonFg == 0)
        titleButtonFg = new YColor(clrNormalTitleButtonText);

    if (fAction == actionNull)
        setPopup(frame->windowMenu());

    setSize(0,0);
}

YFrameButton::~YFrameButton() {
}

void YFrameButton::handleButton(const XButtonEvent &button) {
    if (button.type == ButtonPress &&
        (buttonRaiseMask & (1 << (button.button - 1))))
    {
        if (!(button.state & ControlMask) && raiseOnClickButton) {
            getFrame()->activate();
            if (raiseOnClickButton && fAction != actionDepth)
                getFrame()->wmRaise();
        }
    }
    YButton::handleButton(button);
}

void YFrameButton::handleClick(const XButtonEvent &up, int count) {
    if (fAction == actionNull && up.button == 1) {
        if ((count % 2) == 0) {
            setArmed(false, false);
            getFrame()->wmClose();
        }
    } else if (up.button == 3 && (KEY_MODMASK(up.state) & (xapp->AltMask)) == 0) {
        if (!isPopupActive())
            getFrame()->popupSystemMenu(this, up.x_root, up.y_root,
                                        YPopupWindow::pfCanFlipVertical |
                                        YPopupWindow::pfCanFlipHorizontal);
    }
}

void YFrameButton::handleBeginDrag(const XButtonEvent &down, const XMotionEvent &/*motion*/) {
    if (down.button == 3 && getFrame()->canMove()) {
        if (!isPopupActive()) {
            YFrameTitleBar* tbar = getFrame()->titlebar();
            getFrame()->startMoveSize(true, true,
                                      0, 0,
                                      down.x + x() + (tbar ? tbar->x() : 0),
                                      down.y + y() + (tbar ? tbar->y() : 0));
        }
    }
}

void YFrameButton::setActions(YAction action, YAction action2) {
    fAction2 = action2;
    if (action != fAction) {
        fAction = action;
        repaint();
    }
}

void YFrameButton::updatePopup() {
    getFrame()->updateMenu();
}

void YFrameButton::actionPerformed(YAction /*action*/, unsigned int modifiers) {
    if ((modifiers & ShiftMask) && fAction2 != actionNull)
        getFrame()->actionPerformed(fAction2, modifiers);
    else
        getFrame()->actionPerformed(fAction, modifiers);
}

ref<YPixmap> YFrameButton::getPixmap(int pn) const {
    if (fAction == actionMaximize)
        return maximizePixmap[pn];
    else if (fAction == actionMinimize)
        return minimizePixmap[pn];
    else if (fAction == actionRestore)
        return restorePixmap[pn];
    else if (fAction == actionClose)
        return closePixmap[pn];
    else if (fAction == actionHide)
        return hidePixmap[pn];
    else if (fAction == actionRollup)
        return getFrame()->isRollup() ? rolldownPixmap[pn] : rollupPixmap[pn];
    else if (fAction == actionDepth)
        return depthPixmap[pn];
    else if (fAction == actionNull &&
             LOOK(lookPixmap | lookMetal | lookGtk | lookFlat | lookMotif))
        return menuButton[pn];
    else
        return null;
}

void YFrameButton::paint(Graphics &g, const YRect &/*r*/) {
    int xPos = 1, yPos = 1;
    int pn = LOOK(lookPixmap | lookMetal | lookGtk | lookFlat)
        && getFrame()->focused() ? 1 : 0;
    const bool armed(isArmed());

    g.setColor(titleButtonBg);

    if (fOver && rolloverTitleButtons) {
        if (pn == 1) {
            pn = 2;
        } else {
            pn = 0;
        }
    }

    int iconSize =
    YIcon::smallSize();
    ref<YIcon> icon =
        (fAction == actionNull) ? getFrame()->clientIcon() : null;

    ref<YPixmap> pixmap = getPixmap(pn);
    if (pixmap == null && pn) {
        pixmap = getPixmap(0);
    }

    if (pixmap->depth() != g.rdepth()) {
        tlog("YFrameButton::%s: attempt to use pixmap 0x%lx of depth %d with gc of depth %d\n",
                __func__, pixmap->pixmap(), pixmap->depth(), g.rdepth());
    }

    if (wmLook == lookWarp4) {
        if (fAction == actionNull) {
            g.fillRect(0, 0, width(), height());

            if (armed)
                g.setColor(activeTitleBarBg);

            g.fillRect(1, 1, width() - 2, height() - 2);

            if (icon != null && showFrameIcon) {
                icon->draw(g,
                           (width() - iconSize) / 2,
                           (height() - iconSize) / 2,
                           iconSize);
            }
        } else {
            g.fillRect(0, 0, width(), height());

            if (pixmap != null)
                g.copyPixmap(pixmap, 0, armed ? 20 : 0,
                             pixmap->width(), pixmap->height() / 2,
                             (width() - pixmap->width()) / 2,
                             (height() - pixmap->height() / 2));
        }
    }
    else if (LOOK(lookMotif | lookWarp3 | lookNice)) {
        g.draw3DRect(0, 0, width() - 1, height() - 1, !armed);

        if (wmLook != lookMotif) {
            if (armed) {
                xPos = 3;
                yPos = 3;
                g.drawLine(1, 1, width() - 2, 1);
                g.drawLine(1, 1, 1, height() - 2);
                g.drawLine(2, 2, width() - 3, 2);
                g.drawLine(2, 2, 2, height() - 3);
            } else {
                xPos = 2;
                yPos = 2;
                g.drawRect(1, 1, width() - 3, width() - 3);
            }
        }

        unsigned const w(LOOK(lookMotif) ? width() - 2 : width() - 4);
        unsigned const h(LOOK(lookMotif) ? height() - 2 : height() - 4);

        if (fAction == actionNull) {
            g.fillRect(xPos, yPos, w, h);

            if (icon != null && showFrameIcon) {
                icon->draw(g,
                           xPos + (w - iconSize) / 2,
                           yPos + (h - iconSize) / 2,
                           iconSize);
            }
            else if (pixmap != null) {
                g.drawCenteredPixmap(xPos, yPos, w, h, pixmap);
            }
        } else {
            if (pixmap != null)
                g.drawCenteredPixmap(xPos, yPos, w, h, pixmap);
        }
    }
    else if (wmLook == lookWin95) {
        if (fAction == actionNull) {
            if (!armed) {
                YColor * bg(getFrame()->focused() ? activeTitleBarBg
                            : inactiveTitleBarBg);
                g.setColor(bg);
            }

            g.fillRect(0, 0, width(), height());

            if (icon != null && showFrameIcon) {
                icon->draw(g,
                           (width() - iconSize) / 2,
                           (height() - iconSize) / 2,
                           iconSize);
            }
        } else {
            g.drawBorderW(0, 0, width() - 1, height() - 1, !armed);

            if (armed)
                xPos = yPos = 2;

            if (pixmap != null)
                g.drawCenteredPixmap(xPos, yPos, width() - 3, height() - 3,
                                     pixmap);
        }
    }
    else if (LOOK(lookPixmap | lookMetal | lookFlat | lookGtk)) {
        if (pixmap != null) {
            if ( getPixmap(1) != null ) {
                int const h(pixmap->height() / 2);
                g.copyPixmap(pixmap, 0, armed ? h : 0, pixmap->width(), h, 0, 0);
            } else {
                // If we have only an image we change
                // the over or armed color and paint it.
               g.fillRect(0, 0, width(), height());
               if (armed)
                   g.setColor(activeTitleBarBg->darker());
               else if (rolloverTitleButtons && fOver)
                   g.setColor(activeTitleBarBg->brighter());
               g.fillRect(1, 1, width()-2, height()-3);
               int x(((int)width()  - (int)pixmap->width())  / 2);
               int y(((int)height() - (int)pixmap->height()) / 2);
               g.drawPixmap(pixmap, x, y);
            }
        }
        else {
            g.fillRect(0, 0, width(), height());
        }

        if (fAction == actionNull && icon != null && showFrameIcon) {
            icon->draw(g,
                       ((int)width() - (int)iconSize) / 2,
                       ((int)height() - (int)iconSize) / 2,
                       iconSize);
        }
    }
}

void YFrameButton::paintFocus(Graphics &/*g*/, const YRect &/*r*/) {
}

// vim: set sw=4 ts=4 et:
<commit_msg>Fix SEGV.<commit_after>/*
 * IceWM
 *
 * Copyright (C) 1997-2001 Marko Macek
 */
#include "config.h"

#include "ylib.h"
#include "wmbutton.h"

#include "wmaction.h"
#include "wmframe.h"
#include "wmtitle.h"
#include "yxapp.h"
#include "yicon.h"
#include "yprefs.h"
#include "prefs.h"
#include "wpixmaps.h"

static YColor *titleButtonBg = 0;
static YColor *titleButtonFg = 0;

//!!! get rid of this
extern YColor *activeTitleBarBg;
extern YColor *inactiveTitleBarBg;

YFrameButton::YFrameButton(YWindow *parent,
                           YFrameWindow *frame,
                           YAction action,
                           YAction action2):
    YButton(desktop, actionNull),
    fFrame(frame),
    fAction(action),
    fAction2(action2)
{
    reparent(parent, 0, 0);
    if (titleButtonBg == 0)
        titleButtonBg = new YColor(clrNormalTitleButton);
    if (titleButtonFg == 0)
        titleButtonFg = new YColor(clrNormalTitleButtonText);

    if (fAction == actionNull)
        setPopup(frame->windowMenu());

    setSize(0,0);
}

YFrameButton::~YFrameButton() {
}

void YFrameButton::handleButton(const XButtonEvent &button) {
    if (button.type == ButtonPress &&
        (buttonRaiseMask & (1 << (button.button - 1))))
    {
        if (!(button.state & ControlMask) && raiseOnClickButton) {
            getFrame()->activate();
            if (raiseOnClickButton && fAction != actionDepth)
                getFrame()->wmRaise();
        }
    }
    YButton::handleButton(button);
}

void YFrameButton::handleClick(const XButtonEvent &up, int count) {
    if (fAction == actionNull && up.button == 1) {
        if ((count % 2) == 0) {
            setArmed(false, false);
            getFrame()->wmClose();
        }
    } else if (up.button == 3 && (KEY_MODMASK(up.state) & (xapp->AltMask)) == 0) {
        if (!isPopupActive())
            getFrame()->popupSystemMenu(this, up.x_root, up.y_root,
                                        YPopupWindow::pfCanFlipVertical |
                                        YPopupWindow::pfCanFlipHorizontal);
    }
}

void YFrameButton::handleBeginDrag(const XButtonEvent &down, const XMotionEvent &/*motion*/) {
    if (down.button == 3 && getFrame()->canMove()) {
        if (!isPopupActive()) {
            YFrameTitleBar* tbar = getFrame()->titlebar();
            getFrame()->startMoveSize(true, true,
                                      0, 0,
                                      down.x + x() + (tbar ? tbar->x() : 0),
                                      down.y + y() + (tbar ? tbar->y() : 0));
        }
    }
}

void YFrameButton::setActions(YAction action, YAction action2) {
    fAction2 = action2;
    if (action != fAction) {
        fAction = action;
        repaint();
    }
}

void YFrameButton::updatePopup() {
    getFrame()->updateMenu();
}

void YFrameButton::actionPerformed(YAction /*action*/, unsigned int modifiers) {
    if ((modifiers & ShiftMask) && fAction2 != actionNull)
        getFrame()->actionPerformed(fAction2, modifiers);
    else
        getFrame()->actionPerformed(fAction, modifiers);
}

ref<YPixmap> YFrameButton::getPixmap(int pn) const {
    if (fAction == actionMaximize)
        return maximizePixmap[pn];
    else if (fAction == actionMinimize)
        return minimizePixmap[pn];
    else if (fAction == actionRestore)
        return restorePixmap[pn];
    else if (fAction == actionClose)
        return closePixmap[pn];
    else if (fAction == actionHide)
        return hidePixmap[pn];
    else if (fAction == actionRollup)
        return getFrame()->isRollup() ? rolldownPixmap[pn] : rollupPixmap[pn];
    else if (fAction == actionDepth)
        return depthPixmap[pn];
    else if (fAction == actionNull &&
             LOOK(lookPixmap | lookMetal | lookGtk | lookFlat | lookMotif))
        return menuButton[pn];
    else
        return null;
}

void YFrameButton::paint(Graphics &g, const YRect &/*r*/) {
    int xPos = 1, yPos = 1;
    int pn = LOOK(lookPixmap | lookMetal | lookGtk | lookFlat)
        && getFrame()->focused() ? 1 : 0;
    const bool armed(isArmed());

    g.setColor(titleButtonBg);

    if (fOver && rolloverTitleButtons) {
        if (pn == 1) {
            pn = 2;
        } else {
            pn = 0;
        }
    }

    int iconSize =
    YIcon::smallSize();
    ref<YIcon> icon =
        (fAction == actionNull) ? getFrame()->clientIcon() : null;

    ref<YPixmap> pixmap = getPixmap(pn);
    if (pixmap == null && pn) {
        pixmap = getPixmap(0);
    }

    if (pixmap != null && pixmap->depth() != g.rdepth()) {
        tlog("YFrameButton::%s: attempt to use pixmap 0x%lx of depth %d with gc of depth %d\n",
                __func__, pixmap->pixmap(), pixmap->depth(), g.rdepth());
    }

    if (wmLook == lookWarp4) {
        if (fAction == actionNull) {
            g.fillRect(0, 0, width(), height());

            if (armed)
                g.setColor(activeTitleBarBg);

            g.fillRect(1, 1, width() - 2, height() - 2);

            if (icon != null && showFrameIcon) {
                icon->draw(g,
                           (width() - iconSize) / 2,
                           (height() - iconSize) / 2,
                           iconSize);
            }
        } else {
            g.fillRect(0, 0, width(), height());

            if (pixmap != null)
                g.copyPixmap(pixmap, 0, armed ? 20 : 0,
                             pixmap->width(), pixmap->height() / 2,
                             (width() - pixmap->width()) / 2,
                             (height() - pixmap->height() / 2));
        }
    }
    else if (LOOK(lookMotif | lookWarp3 | lookNice)) {
        g.draw3DRect(0, 0, width() - 1, height() - 1, !armed);

        if (wmLook != lookMotif) {
            if (armed) {
                xPos = 3;
                yPos = 3;
                g.drawLine(1, 1, width() - 2, 1);
                g.drawLine(1, 1, 1, height() - 2);
                g.drawLine(2, 2, width() - 3, 2);
                g.drawLine(2, 2, 2, height() - 3);
            } else {
                xPos = 2;
                yPos = 2;
                g.drawRect(1, 1, width() - 3, width() - 3);
            }
        }

        unsigned const w(LOOK(lookMotif) ? width() - 2 : width() - 4);
        unsigned const h(LOOK(lookMotif) ? height() - 2 : height() - 4);

        if (fAction == actionNull) {
            g.fillRect(xPos, yPos, w, h);

            if (icon != null && showFrameIcon) {
                icon->draw(g,
                           xPos + (w - iconSize) / 2,
                           yPos + (h - iconSize) / 2,
                           iconSize);
            }
            else if (pixmap != null) {
                g.drawCenteredPixmap(xPos, yPos, w, h, pixmap);
            }
        } else {
            if (pixmap != null)
                g.drawCenteredPixmap(xPos, yPos, w, h, pixmap);
        }
    }
    else if (wmLook == lookWin95) {
        if (fAction == actionNull) {
            if (!armed) {
                YColor * bg(getFrame()->focused() ? activeTitleBarBg
                            : inactiveTitleBarBg);
                g.setColor(bg);
            }

            g.fillRect(0, 0, width(), height());

            if (icon != null && showFrameIcon) {
                icon->draw(g,
                           (width() - iconSize) / 2,
                           (height() - iconSize) / 2,
                           iconSize);
            }
        } else {
            g.drawBorderW(0, 0, width() - 1, height() - 1, !armed);

            if (armed)
                xPos = yPos = 2;

            if (pixmap != null)
                g.drawCenteredPixmap(xPos, yPos, width() - 3, height() - 3,
                                     pixmap);
        }
    }
    else if (LOOK(lookPixmap | lookMetal | lookFlat | lookGtk)) {
        if (pixmap != null) {
            if ( getPixmap(1) != null ) {
                int const h(pixmap->height() / 2);
                g.copyPixmap(pixmap, 0, armed ? h : 0, pixmap->width(), h, 0, 0);
            } else {
                // If we have only an image we change
                // the over or armed color and paint it.
               g.fillRect(0, 0, width(), height());
               if (armed)
                   g.setColor(activeTitleBarBg->darker());
               else if (rolloverTitleButtons && fOver)
                   g.setColor(activeTitleBarBg->brighter());
               g.fillRect(1, 1, width()-2, height()-3);
               int x(((int)width()  - (int)pixmap->width())  / 2);
               int y(((int)height() - (int)pixmap->height()) / 2);
               g.drawPixmap(pixmap, x, y);
            }
        }
        else {
            g.fillRect(0, 0, width(), height());
        }

        if (fAction == actionNull && icon != null && showFrameIcon) {
            icon->draw(g,
                       ((int)width() - (int)iconSize) / 2,
                       ((int)height() - (int)iconSize) / 2,
                       iconSize);
        }
    }
}

void YFrameButton::paintFocus(Graphics &/*g*/, const YRect &/*r*/) {
}

// vim: set sw=4 ts=4 et:
<|endoftext|>


<commit_before>// Copyright (c) 2014, Alexander Aprelev.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>

#include <occi.h>

#include "include/dart_api.h"
#include "include/dart_native_api.h"

Dart_NativeFunction ResolveName(Dart_Handle name,
                                int argc,
                                bool* auto_setup_scope);

DART_EXPORT Dart_Handle oracledart_extension_Init(Dart_Handle parent_library) {
  if (Dart_IsError(parent_library)) { return parent_library; }

  Dart_Handle result_code = Dart_SetNativeResolver(parent_library, ResolveName);
  if (Dart_IsError(result_code)) return result_code;

  return Dart_Null();
}

Dart_Handle HandleError(Dart_Handle handle) {
  if (Dart_IsError(handle)) Dart_PropagateError(handle);
  return handle;
}

struct OracleConnection {
  oracle::occi::Environment *env;
  oracle::occi::Connection *conn;

  OracleConnection(std::string user, std::string password, std::string db) {
    env = oracle::occi::Environment::createEnvironment(oracle::occi::Environment::DEFAULT);
    conn = env->createConnection(user, password, db);
  }

  void Terminate() {
    env->terminateConnection(conn);
    oracle::occi::Environment::terminateEnvironment(env);
    conn = NULL;
    env = NULL;
  }
};

struct OracleStatement {
  OracleConnection *connection;
  oracle::occi::Statement *statement;

  OracleStatement(OracleConnection *connection,
                  oracle::occi::Statement *statement):
      connection(connection),
      statement(statement) {}

  void Close() {
    if (connection != NULL && connection->conn != NULL) {
      connection->conn->terminateStatement(statement);
      connection = NULL;
      statement = NULL;
    }
  }
};

struct OracleResultset {
  OracleStatement *statement;
  oracle::occi::ResultSet *resultset;

  OracleResultset(OracleStatement *statement,
                  oracle::occi::ResultSet *resultset):
      statement(statement),
      resultset(resultset) {}

  void Close() {
    if (statement != NULL
      && resultset != NULL
      && statement->statement != NULL
      && statement->connection->conn != NULL) {
      statement->statement->closeResultSet(resultset);
      statement = NULL;
      resultset = NULL;
	  }
  }
};

static void OracleConnectionFinalizer(void* isolate_callback_data,
                                      Dart_WeakPersistentHandle handle,
                                      void* pvoid_oracle_connection) {
  OracleConnection* oracle_connection =
      static_cast<OracleConnection*>(pvoid_oracle_connection);
  oracle_connection->Terminate();
}

static void OracleStatementFinalizer(void* isolate_callback_data,
                                     Dart_WeakPersistentHandle handle,
                                     void* pvoid_oracle_statement) {
  OracleStatement* oracle_statement =
     static_cast<OracleStatement*>(pvoid_oracle_statement);
  oracle_statement->Close();
}

static void OracleResultsetFinalizer(void* isolate_callback_data,
                                     Dart_WeakPersistentHandle handle,
                                     void* pvoid_oracle_resultset) {
  OracleResultset* oracle_resultset =
      static_cast<OracleResultset*>(pvoid_oracle_resultset);
  oracle_resultset->Close();
}

void OracleConnection_Connect(Dart_NativeArguments arguments) {
  Dart_EnterScope();

  Dart_Handle connection_obj = Dart_GetNativeArgument(arguments, 0);

  Dart_Handle username_object = HandleError(Dart_GetNativeArgument(arguments, 1));
  const char* username;
  HandleError(Dart_StringToCString(username_object, &username));
  Dart_Handle password_object = HandleError(Dart_GetNativeArgument(arguments, 2));
  const char* password;
  HandleError(Dart_StringToCString(password_object, &password));
  Dart_Handle db_object = HandleError(Dart_GetNativeArgument(arguments, 3));
  const char* db;
  HandleError(Dart_StringToCString(db_object, &db));

  OracleConnection* connection = NULL;
  try {
   connection = new OracleConnection(username, password, db);
  } catch(oracle::occi::SQLException exception) {
    Dart_PropagateError(Dart_NewUnhandledExceptionError(Dart_NewStringFromCString(exception.getMessage().c_str())));
  }

  HandleError(Dart_SetNativeInstanceField(
      connection_obj,
      0,
      reinterpret_cast<intptr_t>(connection)));

  Dart_NewWeakPersistentHandle(
      connection_obj,
      connection,
      0,
      OracleConnectionFinalizer);

  Dart_ExitScope();
}

void OracleConnection_CreateStatement(Dart_NativeArguments arguments) {
  Dart_EnterScope();

  Dart_Handle connection_obj = HandleError(Dart_GetNativeArgument(arguments, 0));
  OracleConnection* connection;
  HandleError(Dart_GetNativeInstanceField(
      connection_obj,
      0,
      reinterpret_cast<intptr_t*>(&connection)));

  Dart_Handle statement_obj = HandleError(Dart_GetNativeArgument(arguments, 1));

  Dart_Handle query_obj = HandleError(Dart_GetNativeArgument(arguments, 2));
  const char* query;
  HandleError(Dart_StringToCString(query_obj, &query));

  OracleStatement* oracleStatement = NULL;
  try {
    oracle::occi::Statement* stmt = connection->conn->createStatement(query);
    oracleStatement = new OracleStatement(connection, stmt);
  } catch(oracle::occi::SQLException exception) {
    Dart_PropagateError(Dart_NewUnhandledExceptionError(Dart_NewStringFromCString(exception.getMessage().c_str())));
  }

  HandleError(Dart_SetNativeInstanceField(
      statement_obj,
      0,
      reinterpret_cast<intptr_t>(oracleStatement)));

  Dart_NewWeakPersistentHandle(
      statement_obj,
      oracleStatement,
      0,
      OracleStatementFinalizer);

  Dart_ExitScope();
}

void OracleStatement_Execute(Dart_NativeArguments arguments) {
  Dart_EnterScope();

  Dart_Handle statement_obj = HandleError(Dart_GetNativeArgument(arguments, 0));
  OracleStatement* oracleStatement;
  HandleError(Dart_GetNativeInstanceField(
      statement_obj,
      0,
      reinterpret_cast<intptr_t*>(&oracleStatement)));

  Dart_Handle resultset_obj = HandleError(Dart_GetNativeArgument(arguments, 1));
  oracle::occi::ResultSet *rset = NULL;
  try {
    rset = oracleStatement->statement->executeQuery();
  } catch(oracle::occi::SQLException exception) {
    Dart_PropagateError(Dart_NewUnhandledExceptionError(Dart_NewStringFromCString(exception.getMessage().c_str())));
  }

  OracleResultset* resultset = new OracleResultset(oracleStatement, rset);
  HandleError(Dart_SetNativeInstanceField(
      resultset_obj,
      0,
      reinterpret_cast<intptr_t>(resultset)));

  Dart_NewWeakPersistentHandle(
      resultset_obj,
      resultset,
      0,
      OracleResultsetFinalizer);

  Dart_ExitScope();
}

void OracleStatement_SetInt(Dart_NativeArguments arguments) {
  Dart_EnterScope();

  Dart_Handle statement_obj = HandleError(Dart_GetNativeArgument(arguments, 0));
  OracleStatement* oracleStatement;
  HandleError(Dart_GetNativeInstanceField(
      statement_obj,
      0,
      reinterpret_cast<intptr_t*>(&oracleStatement)));

  Dart_Handle index_obj = HandleError(Dart_GetNativeArgument(arguments, 1));
  int64_t index;
  HandleError(Dart_IntegerToInt64(index_obj, &index));

  Dart_Handle value_obj = HandleError(Dart_GetNativeArgument(arguments, 2));
  int64_t value;
  HandleError(Dart_IntegerToInt64(value_obj, &value));

  try {
    oracleStatement->statement->setInt(index, value);
  } catch(oracle::occi::SQLException exception) {
    Dart_PropagateError(Dart_NewUnhandledExceptionError(Dart_NewStringFromCString(exception.getMessage().c_str())));
  }

  Dart_ExitScope();
}

void OracleStatement_SetString(Dart_NativeArguments arguments) {
  Dart_EnterScope();

  Dart_Handle statement_obj = HandleError(Dart_GetNativeArgument(arguments, 0));
  OracleStatement* oracleStatement;
  HandleError(Dart_GetNativeInstanceField(
      statement_obj,
      0,
      reinterpret_cast<intptr_t*>(&oracleStatement)));

  Dart_Handle index_obj = HandleError(Dart_GetNativeArgument(arguments, 1));
  int64_t index;
  HandleError(Dart_IntegerToInt64(index_obj, &index));

  Dart_Handle value_obj = HandleError(Dart_GetNativeArgument(arguments, 2));
  const char* value;
  HandleError(Dart_StringToCString(value_obj, &value));

  try {
    oracleStatement->statement->setString(index, value);
  } catch(oracle::occi::SQLException exception) {
    Dart_PropagateError(Dart_NewUnhandledExceptionError(Dart_NewStringFromCString(exception.getMessage().c_str())));
  }

  Dart_ExitScope();
}

void OracleResultset_Next(Dart_NativeArguments arguments) {
  Dart_EnterScope();

  Dart_Handle resultset_obj = HandleError(Dart_GetNativeArgument(arguments, 0));
  OracleResultset* resultset;
  HandleError(Dart_GetNativeInstanceField(
    resultset_obj,
    0,
    reinterpret_cast<intptr_t*>(&resultset)));

  try {
    Dart_Handle result = HandleError(Dart_NewBoolean(resultset->resultset->next()));
    Dart_SetReturnValue(arguments, result);
  } catch(oracle::occi::SQLException exception) {
    Dart_PropagateError(Dart_NewUnhandledExceptionError(Dart_NewStringFromCString(exception.getMessage().c_str())));
  }

  Dart_ExitScope();
}

void OracleResultset_Get(Dart_NativeArguments arguments, oracle::occi::Type type) {
  Dart_EnterScope();

  Dart_Handle resultset_obj = HandleError(Dart_GetNativeArgument(arguments, 0));
  OracleResultset* resultset;
  HandleError(Dart_GetNativeInstanceField(
    resultset_obj,
    0,
    reinterpret_cast<intptr_t*>(&resultset)));

  Dart_Handle index_obj = HandleError(Dart_GetNativeArgument(arguments, 1));
  int64_t index;
  HandleError(Dart_IntegerToInt64(index_obj, &index));

  Dart_Handle result = NULL;
  try {
    switch(type) {
      case oracle::occi::OCCIINT:
        result = HandleError(Dart_NewInteger(resultset->resultset->getInt(index)));
        break;
      case oracle::occi::OCCISTRING:
      {
        std::string s = resultset->resultset->getString(index);
        result = Dart_NewStringFromCString(s.c_str());
        break;
      }
      case oracle::occi::OCCIDOUBLE:
        result = Dart_NewDouble(resultset->resultset->getDouble(index));
        break;
      case oracle::occi::OCCIFLOAT:
        result = Dart_NewDouble(resultset->resultset->getFloat(index));
        break;
      default:
        Dart_PropagateError(Dart_NewApiError("Requested type is not supported by OracleDart."));
        break;
    }
  } catch(oracle::occi::SQLException exception) {
    Dart_PropagateError(
      Dart_NewUnhandledExceptionError(
        Dart_NewStringFromCString(
          exception.getMessage().c_str())));
  }
  Dart_SetReturnValue(arguments, result);
  Dart_ExitScope();
}

void OracleResultset_GetInt(Dart_NativeArguments arguments) {
  return OracleResultset_Get(arguments, oracle::occi::OCCIINT);
}

void OracleResultset_GetString(Dart_NativeArguments arguments) {
  return OracleResultset_Get(arguments, oracle::occi::OCCISTRING);
}

void OracleResultset_GetDouble(Dart_NativeArguments arguments) {
  return OracleResultset_Get(arguments, oracle::occi::OCCIDOUBLE);
}

void OracleResultset_GetFloat(Dart_NativeArguments arguments) {
  return OracleResultset_Get(arguments, oracle::occi::OCCIFLOAT);
}

struct FunctionLookup {
  const char* name;
  Dart_NativeFunction function;
};

FunctionLookup function_list[] = {
    {"OracleConnection_Connect", OracleConnection_Connect},
    {"OracleConnection_CreateStatement", OracleConnection_CreateStatement},
    {"OracleStatement_Execute", OracleStatement_Execute},
    {"OracleStatement_SetInt", OracleStatement_SetInt},
    {"OracleStatement_SetString", OracleStatement_SetString},
    {"OracleResultset_GetString", OracleResultset_GetString},
    {"OracleResultset_GetInt", OracleResultset_GetInt},
    {"OracleResultset_GetDouble", OracleResultset_GetDouble},
    {"OracleResultset_GetFloat", OracleResultset_GetFloat},
    {"OracleResultset_Next", OracleResultset_Next},

    {NULL, NULL}};

Dart_NativeFunction ResolveName(Dart_Handle name,
                                int argc,
                                bool* auto_setup_scope) {
  if (!Dart_IsString(name)) return NULL;
  Dart_NativeFunction result = NULL;
  if (auto_setup_scope == NULL) return NULL;
  *auto_setup_scope = true;
  Dart_EnterScope();
  const char* cname;
  HandleError(Dart_StringToCString(name, &cname));

  for (int i=0; function_list[i].name != NULL; ++i) {
    if (strcmp(function_list[i].name, cname) == 0) {
      result = function_list[i].function;
      break;
    }
  }
  Dart_ExitScope();
  return result;
}
<commit_msg>Fix the build due to changes to the api.<commit_after>// Copyright (c) 2014, Alexander Aprelev.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>

#include <occi.h>

#include "include/dart_api.h"
#include "include/dart_native_api.h"

Dart_NativeFunction ResolveName(Dart_Handle name,
                                int argc,
                                bool* auto_setup_scope);

DART_EXPORT Dart_Handle oracledart_extension_Init(Dart_Handle parent_library) {
  if (Dart_IsError(parent_library)) { return parent_library; }

  Dart_Handle result_code = Dart_SetNativeResolver(parent_library, ResolveName, NULL);
  if (Dart_IsError(result_code)) return result_code;

  return Dart_Null();
}

Dart_Handle HandleError(Dart_Handle handle) {
  if (Dart_IsError(handle)) Dart_PropagateError(handle);
  return handle;
}

struct OracleConnection {
  oracle::occi::Environment *env;
  oracle::occi::Connection *conn;

  OracleConnection(std::string user, std::string password, std::string db) {
    env = oracle::occi::Environment::createEnvironment(oracle::occi::Environment::DEFAULT);
    conn = env->createConnection(user, password, db);
  }

  void Terminate() {
    env->terminateConnection(conn);
    oracle::occi::Environment::terminateEnvironment(env);
    conn = NULL;
    env = NULL;
  }
};

struct OracleStatement {
  OracleConnection *connection;
  oracle::occi::Statement *statement;

  OracleStatement(OracleConnection *connection,
                  oracle::occi::Statement *statement):
      connection(connection),
      statement(statement) {}

  void Close() {
    if (connection != NULL && connection->conn != NULL) {
      connection->conn->terminateStatement(statement);
      connection = NULL;
      statement = NULL;
    }
  }
};

struct OracleResultset {
  OracleStatement *statement;
  oracle::occi::ResultSet *resultset;

  OracleResultset(OracleStatement *statement,
                  oracle::occi::ResultSet *resultset):
      statement(statement),
      resultset(resultset) {}

  void Close() {
    if (statement != NULL
      && resultset != NULL
      && statement->statement != NULL
      && statement->connection->conn != NULL) {
      statement->statement->closeResultSet(resultset);
      statement = NULL;
      resultset = NULL;
	  }
  }
};

static void OracleConnectionFinalizer(void* isolate_callback_data,
                                      Dart_WeakPersistentHandle handle,
                                      void* pvoid_oracle_connection) {
  OracleConnection* oracle_connection =
      static_cast<OracleConnection*>(pvoid_oracle_connection);
  oracle_connection->Terminate();
}

static void OracleStatementFinalizer(void* isolate_callback_data,
                                     Dart_WeakPersistentHandle handle,
                                     void* pvoid_oracle_statement) {
  OracleStatement* oracle_statement =
     static_cast<OracleStatement*>(pvoid_oracle_statement);
  oracle_statement->Close();
}

static void OracleResultsetFinalizer(void* isolate_callback_data,
                                     Dart_WeakPersistentHandle handle,
                                     void* pvoid_oracle_resultset) {
  OracleResultset* oracle_resultset =
      static_cast<OracleResultset*>(pvoid_oracle_resultset);
  oracle_resultset->Close();
}

void OracleConnection_Connect(Dart_NativeArguments arguments) {
  Dart_EnterScope();

  Dart_Handle connection_obj = Dart_GetNativeArgument(arguments, 0);

  Dart_Handle username_object = HandleError(Dart_GetNativeArgument(arguments, 1));
  const char* username;
  HandleError(Dart_StringToCString(username_object, &username));
  Dart_Handle password_object = HandleError(Dart_GetNativeArgument(arguments, 2));
  const char* password;
  HandleError(Dart_StringToCString(password_object, &password));
  Dart_Handle db_object = HandleError(Dart_GetNativeArgument(arguments, 3));
  const char* db;
  HandleError(Dart_StringToCString(db_object, &db));

  OracleConnection* connection = NULL;
  try {
   connection = new OracleConnection(username, password, db);
  } catch(oracle::occi::SQLException exception) {
    Dart_PropagateError(Dart_NewUnhandledExceptionError(Dart_NewStringFromCString(exception.getMessage().c_str())));
  }

  HandleError(Dart_SetNativeInstanceField(
      connection_obj,
      0,
      reinterpret_cast<intptr_t>(connection)));

  Dart_NewWeakPersistentHandle(
      connection_obj,
      connection,
      0,
      OracleConnectionFinalizer);

  Dart_ExitScope();
}

void OracleConnection_CreateStatement(Dart_NativeArguments arguments) {
  Dart_EnterScope();

  Dart_Handle connection_obj = HandleError(Dart_GetNativeArgument(arguments, 0));
  OracleConnection* connection;
  HandleError(Dart_GetNativeInstanceField(
      connection_obj,
      0,
      reinterpret_cast<intptr_t*>(&connection)));

  Dart_Handle statement_obj = HandleError(Dart_GetNativeArgument(arguments, 1));

  Dart_Handle query_obj = HandleError(Dart_GetNativeArgument(arguments, 2));
  const char* query;
  HandleError(Dart_StringToCString(query_obj, &query));

  OracleStatement* oracleStatement = NULL;
  try {
    oracle::occi::Statement* stmt = connection->conn->createStatement(query);
    oracleStatement = new OracleStatement(connection, stmt);
  } catch(oracle::occi::SQLException exception) {
    Dart_PropagateError(Dart_NewUnhandledExceptionError(Dart_NewStringFromCString(exception.getMessage().c_str())));
  }

  HandleError(Dart_SetNativeInstanceField(
      statement_obj,
      0,
      reinterpret_cast<intptr_t>(oracleStatement)));

  Dart_NewWeakPersistentHandle(
      statement_obj,
      oracleStatement,
      0,
      OracleStatementFinalizer);

  Dart_ExitScope();
}

void OracleStatement_Execute(Dart_NativeArguments arguments) {
  Dart_EnterScope();

  Dart_Handle statement_obj = HandleError(Dart_GetNativeArgument(arguments, 0));
  OracleStatement* oracleStatement;
  HandleError(Dart_GetNativeInstanceField(
      statement_obj,
      0,
      reinterpret_cast<intptr_t*>(&oracleStatement)));

  Dart_Handle resultset_obj = HandleError(Dart_GetNativeArgument(arguments, 1));
  oracle::occi::ResultSet *rset = NULL;
  try {
    rset = oracleStatement->statement->executeQuery();
  } catch(oracle::occi::SQLException exception) {
    Dart_PropagateError(Dart_NewUnhandledExceptionError(Dart_NewStringFromCString(exception.getMessage().c_str())));
  }

  OracleResultset* resultset = new OracleResultset(oracleStatement, rset);
  HandleError(Dart_SetNativeInstanceField(
      resultset_obj,
      0,
      reinterpret_cast<intptr_t>(resultset)));

  Dart_NewWeakPersistentHandle(
      resultset_obj,
      resultset,
      0,
      OracleResultsetFinalizer);

  Dart_ExitScope();
}

void OracleStatement_SetInt(Dart_NativeArguments arguments) {
  Dart_EnterScope();

  Dart_Handle statement_obj = HandleError(Dart_GetNativeArgument(arguments, 0));
  OracleStatement* oracleStatement;
  HandleError(Dart_GetNativeInstanceField(
      statement_obj,
      0,
      reinterpret_cast<intptr_t*>(&oracleStatement)));

  Dart_Handle index_obj = HandleError(Dart_GetNativeArgument(arguments, 1));
  int64_t index;
  HandleError(Dart_IntegerToInt64(index_obj, &index));

  Dart_Handle value_obj = HandleError(Dart_GetNativeArgument(arguments, 2));
  int64_t value;
  HandleError(Dart_IntegerToInt64(value_obj, &value));

  try {
    oracleStatement->statement->setInt(index, value);
  } catch(oracle::occi::SQLException exception) {
    Dart_PropagateError(Dart_NewUnhandledExceptionError(Dart_NewStringFromCString(exception.getMessage().c_str())));
  }

  Dart_ExitScope();
}

void OracleStatement_SetString(Dart_NativeArguments arguments) {
  Dart_EnterScope();

  Dart_Handle statement_obj = HandleError(Dart_GetNativeArgument(arguments, 0));
  OracleStatement* oracleStatement;
  HandleError(Dart_GetNativeInstanceField(
      statement_obj,
      0,
      reinterpret_cast<intptr_t*>(&oracleStatement)));

  Dart_Handle index_obj = HandleError(Dart_GetNativeArgument(arguments, 1));
  int64_t index;
  HandleError(Dart_IntegerToInt64(index_obj, &index));

  Dart_Handle value_obj = HandleError(Dart_GetNativeArgument(arguments, 2));
  const char* value;
  HandleError(Dart_StringToCString(value_obj, &value));

  try {
    oracleStatement->statement->setString(index, value);
  } catch(oracle::occi::SQLException exception) {
    Dart_PropagateError(Dart_NewUnhandledExceptionError(Dart_NewStringFromCString(exception.getMessage().c_str())));
  }

  Dart_ExitScope();
}

void OracleResultset_Next(Dart_NativeArguments arguments) {
  Dart_EnterScope();

  Dart_Handle resultset_obj = HandleError(Dart_GetNativeArgument(arguments, 0));
  OracleResultset* resultset;
  HandleError(Dart_GetNativeInstanceField(
    resultset_obj,
    0,
    reinterpret_cast<intptr_t*>(&resultset)));

  try {
    Dart_Handle result = HandleError(Dart_NewBoolean(resultset->resultset->next()));
    Dart_SetReturnValue(arguments, result);
  } catch(oracle::occi::SQLException exception) {
    Dart_PropagateError(Dart_NewUnhandledExceptionError(Dart_NewStringFromCString(exception.getMessage().c_str())));
  }

  Dart_ExitScope();
}

void OracleResultset_Get(Dart_NativeArguments arguments, oracle::occi::Type type) {
  Dart_EnterScope();

  Dart_Handle resultset_obj = HandleError(Dart_GetNativeArgument(arguments, 0));
  OracleResultset* resultset;
  HandleError(Dart_GetNativeInstanceField(
    resultset_obj,
    0,
    reinterpret_cast<intptr_t*>(&resultset)));

  Dart_Handle index_obj = HandleError(Dart_GetNativeArgument(arguments, 1));
  int64_t index;
  HandleError(Dart_IntegerToInt64(index_obj, &index));

  Dart_Handle result = NULL;
  try {
    switch(type) {
      case oracle::occi::OCCIINT:
        result = HandleError(Dart_NewInteger(resultset->resultset->getInt(index)));
        break;
      case oracle::occi::OCCISTRING:
      {
        std::string s = resultset->resultset->getString(index);
        result = Dart_NewStringFromCString(s.c_str());
        break;
      }
      case oracle::occi::OCCIDOUBLE:
        result = Dart_NewDouble(resultset->resultset->getDouble(index));
        break;
      case oracle::occi::OCCIFLOAT:
        result = Dart_NewDouble(resultset->resultset->getFloat(index));
        break;
      default:
        Dart_PropagateError(Dart_NewApiError("Requested type is not supported by OracleDart."));
        break;
    }
  } catch(oracle::occi::SQLException exception) {
    Dart_PropagateError(
      Dart_NewUnhandledExceptionError(
        Dart_NewStringFromCString(
          exception.getMessage().c_str())));
  }
  Dart_SetReturnValue(arguments, result);
  Dart_ExitScope();
}

void OracleResultset_GetInt(Dart_NativeArguments arguments) {
  return OracleResultset_Get(arguments, oracle::occi::OCCIINT);
}

void OracleResultset_GetString(Dart_NativeArguments arguments) {
  return OracleResultset_Get(arguments, oracle::occi::OCCISTRING);
}

void OracleResultset_GetDouble(Dart_NativeArguments arguments) {
  return OracleResultset_Get(arguments, oracle::occi::OCCIDOUBLE);
}

void OracleResultset_GetFloat(Dart_NativeArguments arguments) {
  return OracleResultset_Get(arguments, oracle::occi::OCCIFLOAT);
}

struct FunctionLookup {
  const char* name;
  Dart_NativeFunction function;
};

FunctionLookup function_list[] = {
    {"OracleConnection_Connect", OracleConnection_Connect},
    {"OracleConnection_CreateStatement", OracleConnection_CreateStatement},
    {"OracleStatement_Execute", OracleStatement_Execute},
    {"OracleStatement_SetInt", OracleStatement_SetInt},
    {"OracleStatement_SetString", OracleStatement_SetString},
    {"OracleResultset_GetString", OracleResultset_GetString},
    {"OracleResultset_GetInt", OracleResultset_GetInt},
    {"OracleResultset_GetDouble", OracleResultset_GetDouble},
    {"OracleResultset_GetFloat", OracleResultset_GetFloat},
    {"OracleResultset_Next", OracleResultset_Next},

    {NULL, NULL}};

Dart_NativeFunction ResolveName(Dart_Handle name,
                                int argc,
                                bool* auto_setup_scope) {
  if (!Dart_IsString(name)) return NULL;
  Dart_NativeFunction result = NULL;
  if (auto_setup_scope == NULL) return NULL;
  *auto_setup_scope = true;
  Dart_EnterScope();
  const char* cname;
  HandleError(Dart_StringToCString(name, &cname));

  for (int i=0; function_list[i].name != NULL; ++i) {
    if (strcmp(function_list[i].name, cname) == 0) {
      result = function_list[i].function;
      break;
    }
  }
  Dart_ExitScope();
  return result;
}
<|endoftext|>


<commit_before>// Copyright (c) 2014, Alexander Aprelev.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>

#include <occi.h>

#include "include/dart_api.h"
#include "include/dart_native_api.h"

Dart_NativeFunction ResolveName(Dart_Handle name,
                                int argc,
                                bool* auto_setup_scope);

DART_EXPORT Dart_Handle oracledart_extension_Init(Dart_Handle parent_library) {
  if (Dart_IsError(parent_library)) { return parent_library; }

  Dart_Handle result_code = Dart_SetNativeResolver(parent_library, ResolveName, NULL);
  if (Dart_IsError(result_code)) return result_code;

  return Dart_Null();
}

Dart_Handle HandleError(Dart_Handle handle) {
  if (Dart_IsError(handle)) Dart_PropagateError(handle);
  return handle;
}

struct OracleConnection {
  oracle::occi::Environment *env;
  oracle::occi::Connection *conn;

  OracleConnection(std::string user, std::string password, std::string db) {
    env = oracle::occi::Environment::createEnvironment(oracle::occi::Environment::DEFAULT);
    conn = env->createConnection(user, password, db);
  }

  void Terminate() {
    env->terminateConnection(conn);
    oracle::occi::Environment::terminateEnvironment(env);
    conn = NULL;
    env = NULL;
  }
};

struct OracleStatement {
  OracleConnection *connection;
  oracle::occi::Statement *statement;

  OracleStatement(OracleConnection *connection,
                  oracle::occi::Statement *statement):
      connection(connection),
      statement(statement) {}

  void Close() {
    if (connection != NULL && connection->conn != NULL) {
      connection->conn->terminateStatement(statement);
      connection = NULL;
      statement = NULL;
    }
  }
};

struct OracleResultset {
  OracleStatement *statement;
  oracle::occi::ResultSet *resultset;

  OracleResultset(OracleStatement *statement,
                  oracle::occi::ResultSet *resultset):
      statement(statement),
      resultset(resultset) {}

  void Close() {
    if (statement != NULL
      && resultset != NULL
      && statement->statement != NULL
      && statement->connection->conn != NULL) {
      statement->statement->closeResultSet(resultset);
      statement = NULL;
      resultset = NULL;
	  }
  }
};

struct OracleMetadataVector {
  std::vector<oracle::occi::MetaData> v_metadata;

  OracleMetadataVector(std::vector<oracle::occi::MetaData> &_v_metadata) {
      v_metadata = _v_metadata;
  }
};

static void OracleConnectionFinalizer(void* isolate_callback_data,
                                      Dart_WeakPersistentHandle handle,
                                      void* pvoid_oracle_connection) {
  OracleConnection* oracle_connection =
      static_cast<OracleConnection*>(pvoid_oracle_connection);
  oracle_connection->Terminate();
}

static void OracleStatementFinalizer(void* isolate_callback_data,
                                     Dart_WeakPersistentHandle handle,
                                     void* pvoid_oracle_statement) {
  OracleStatement* oracle_statement =
     static_cast<OracleStatement*>(pvoid_oracle_statement);
  oracle_statement->Close();
}

static void OracleResultsetFinalizer(void* isolate_callback_data,
                                     Dart_WeakPersistentHandle handle,
                                     void* pvoid_oracle_resultset) {
  OracleResultset* oracle_resultset =
      static_cast<OracleResultset*>(pvoid_oracle_resultset);
  oracle_resultset->Close();
}

void OracleConnection_Connect(Dart_NativeArguments arguments) {
  Dart_EnterScope();

  Dart_Handle connection_obj = Dart_GetNativeArgument(arguments, 0);

  Dart_Handle username_object = HandleError(Dart_GetNativeArgument(arguments, 1));
  const char* username;
  HandleError(Dart_StringToCString(username_object, &username));
  Dart_Handle password_object = HandleError(Dart_GetNativeArgument(arguments, 2));
  const char* password;
  HandleError(Dart_StringToCString(password_object, &password));
  Dart_Handle db_object = HandleError(Dart_GetNativeArgument(arguments, 3));
  const char* db;
  HandleError(Dart_StringToCString(db_object, &db));

  OracleConnection* connection = NULL;
  try {
   connection = new OracleConnection(username, password, db);
  } catch(oracle::occi::SQLException exception) {
    Dart_PropagateError(Dart_NewUnhandledExceptionError(Dart_NewStringFromCString(exception.getMessage().c_str())));
  }

  HandleError(Dart_SetNativeInstanceField(
      connection_obj,
      0,
      reinterpret_cast<intptr_t>(connection)));

  Dart_NewWeakPersistentHandle(
      connection_obj,
      connection,
      0,
      OracleConnectionFinalizer);

  Dart_ExitScope();
}

void OracleConnection_CreateStatement(Dart_NativeArguments arguments) {
  Dart_EnterScope();

  Dart_Handle connection_obj = HandleError(Dart_GetNativeArgument(arguments, 0));
  OracleConnection* connection;
  HandleError(Dart_GetNativeInstanceField(
      connection_obj,
      0,
      reinterpret_cast<intptr_t*>(&connection)));

  Dart_Handle statement_obj = HandleError(Dart_GetNativeArgument(arguments, 1));

  Dart_Handle query_obj = HandleError(Dart_GetNativeArgument(arguments, 2));
  const char* query;
  HandleError(Dart_StringToCString(query_obj, &query));

  OracleStatement* oracleStatement = NULL;
  try {
    oracle::occi::Statement* stmt = connection->conn->createStatement(query);
    oracleStatement = new OracleStatement(connection, stmt);
  } catch(oracle::occi::SQLException exception) {
    Dart_PropagateError(Dart_NewUnhandledExceptionError(Dart_NewStringFromCString(exception.getMessage().c_str())));
  }

  HandleError(Dart_SetNativeInstanceField(
      statement_obj,
      0,
      reinterpret_cast<intptr_t>(oracleStatement)));

  Dart_NewWeakPersistentHandle(
      statement_obj,
      oracleStatement,
      0,
      OracleStatementFinalizer);

  Dart_ExitScope();
}

void OracleStatement_Execute(Dart_NativeArguments arguments) {
  Dart_EnterScope();

  Dart_Handle statement_obj = HandleError(Dart_GetNativeArgument(arguments, 0));
  OracleStatement* oracleStatement;
  HandleError(Dart_GetNativeInstanceField(
      statement_obj,
      0,
      reinterpret_cast<intptr_t*>(&oracleStatement)));

  Dart_Handle resultset_obj = HandleError(Dart_GetNativeArgument(arguments, 1));
  oracle::occi::ResultSet *rset = NULL;
  try {
    rset = oracleStatement->statement->executeQuery();
  } catch(oracle::occi::SQLException exception) {
    Dart_PropagateError(Dart_NewUnhandledExceptionError(Dart_NewStringFromCString(exception.getMessage().c_str())));
  }

  OracleResultset* resultset = new OracleResultset(oracleStatement, rset);
  HandleError(Dart_SetNativeInstanceField(
      resultset_obj,
      0,
      reinterpret_cast<intptr_t>(resultset)));

  Dart_NewWeakPersistentHandle(
      resultset_obj,
      resultset,
      0,
      OracleResultsetFinalizer);

  Dart_ExitScope();
}

void OracleStatement_SetInt(Dart_NativeArguments arguments) {
  Dart_EnterScope();

  Dart_Handle statement_obj = HandleError(Dart_GetNativeArgument(arguments, 0));
  OracleStatement* oracleStatement;
  HandleError(Dart_GetNativeInstanceField(
      statement_obj,
      0,
      reinterpret_cast<intptr_t*>(&oracleStatement)));

  Dart_Handle index_obj = HandleError(Dart_GetNativeArgument(arguments, 1));
  int64_t index;
  HandleError(Dart_IntegerToInt64(index_obj, &index));

  Dart_Handle value_obj = HandleError(Dart_GetNativeArgument(arguments, 2));
  int64_t value;
  HandleError(Dart_IntegerToInt64(value_obj, &value));

  try {
    oracleStatement->statement->setInt(index, value);
  } catch(oracle::occi::SQLException exception) {
    Dart_PropagateError(Dart_NewUnhandledExceptionError(Dart_NewStringFromCString(exception.getMessage().c_str())));
  }

  Dart_ExitScope();
}

void OracleStatement_SetString(Dart_NativeArguments arguments) {
  Dart_EnterScope();

  Dart_Handle statement_obj = HandleError(Dart_GetNativeArgument(arguments, 0));
  OracleStatement* oracleStatement;
  HandleError(Dart_GetNativeInstanceField(
      statement_obj,
      0,
      reinterpret_cast<intptr_t*>(&oracleStatement)));

  Dart_Handle index_obj = HandleError(Dart_GetNativeArgument(arguments, 1));
  int64_t index;
  HandleError(Dart_IntegerToInt64(index_obj, &index));

  Dart_Handle value_obj = HandleError(Dart_GetNativeArgument(arguments, 2));
  const char* value;
  HandleError(Dart_StringToCString(value_obj, &value));

  try {
    oracleStatement->statement->setString(index, value);
  } catch(oracle::occi::SQLException exception) {
    Dart_PropagateError(Dart_NewUnhandledExceptionError(Dart_NewStringFromCString(exception.getMessage().c_str())));
  }

  Dart_ExitScope();
}

void OracleResultset_Next(Dart_NativeArguments arguments) {
  Dart_EnterScope();

  Dart_Handle resultset_obj = HandleError(Dart_GetNativeArgument(arguments, 0));
  OracleResultset* resultset;
  HandleError(Dart_GetNativeInstanceField(
    resultset_obj,
    0,
    reinterpret_cast<intptr_t*>(&resultset)));

  try {
    Dart_Handle result = HandleError(Dart_NewBoolean(resultset->resultset->next()));
    Dart_SetReturnValue(arguments, result);
  } catch(oracle::occi::SQLException exception) {
    Dart_PropagateError(Dart_NewUnhandledExceptionError(Dart_NewStringFromCString(exception.getMessage().c_str())));
  }

  Dart_ExitScope();
}

void OracleResultset_Get(Dart_NativeArguments arguments, oracle::occi::Type type) {
  Dart_EnterScope();

  Dart_Handle resultset_obj = HandleError(Dart_GetNativeArgument(arguments, 0));
  OracleResultset* resultset;
  HandleError(Dart_GetNativeInstanceField(
    resultset_obj,
    0,
    reinterpret_cast<intptr_t*>(&resultset)));

  Dart_Handle index_obj = HandleError(Dart_GetNativeArgument(arguments, 1));
  int64_t index;
  HandleError(Dart_IntegerToInt64(index_obj, &index));

  Dart_Handle result = NULL;
  try {
    switch(type) {
      case oracle::occi::OCCIINT:
        result = HandleError(Dart_NewInteger(resultset->resultset->getInt(index)));
        break;
      case oracle::occi::OCCISTRING:
      {
        std::string s = resultset->resultset->getString(index);
        result = Dart_NewStringFromCString(s.c_str());
        break;
      }
      case oracle::occi::OCCIDOUBLE:
        result = Dart_NewDouble(resultset->resultset->getDouble(index));
        break;
      case oracle::occi::OCCIFLOAT:
        result = Dart_NewDouble(resultset->resultset->getFloat(index));
        break;
      default:
        Dart_PropagateError(Dart_NewApiError("Requested type is not supported by OracleDart."));
        break;
    }
  } catch(oracle::occi::SQLException exception) {
    Dart_PropagateError(
      Dart_NewUnhandledExceptionError(
        Dart_NewStringFromCString(
          exception.getMessage().c_str())));
  }
  Dart_SetReturnValue(arguments, result);
  Dart_ExitScope();
}

void OracleResultset_GetInt(Dart_NativeArguments arguments) {
  return OracleResultset_Get(arguments, oracle::occi::OCCIINT);
}

void OracleResultset_GetString(Dart_NativeArguments arguments) {
  return OracleResultset_Get(arguments, oracle::occi::OCCISTRING);
}

void OracleResultset_GetDouble(Dart_NativeArguments arguments) {
  return OracleResultset_Get(arguments, oracle::occi::OCCIDOUBLE);
}

void OracleResultset_GetFloat(Dart_NativeArguments arguments) {
  return OracleResultset_Get(arguments, oracle::occi::OCCIFLOAT);
}

void OracleResultset_GetMetadataVector(Dart_NativeArguments arguments) {
  Dart_EnterScope();

  Dart_Handle resultset_obj = HandleError(Dart_GetNativeArgument(arguments, 0));
  OracleResultset* resultset;
  HandleError(Dart_GetNativeInstanceField(
    resultset_obj,
    0,
    reinterpret_cast<intptr_t*>(&resultset)));

  Dart_Handle metadata_vector_obj = HandleError(Dart_GetNativeArgument(arguments, 1));

  OracleMetadataVector* metadata_vector = NULL;
  try {
    metadata_vector = new OracleMetadataVector(
        resultset->resultset->getColumnListMetaData());
  } catch(oracle::occi::SQLException exception) {
    Dart_PropagateError(Dart_NewUnhandledExceptionError(Dart_NewStringFromCString(exception.getMessage().c_str())));
  }

  HandleError(Dart_SetNativeInstanceField(
      metadata_vector_obj,
      0,
      reinterpret_cast<intptr_t>(metadata_vector)));

  Dart_ExitScope();
}

void OracleMetadataVector_GetSize(Dart_NativeArguments arguments) {
  Dart_EnterScope();

  Dart_Handle metadata_vector_obj = HandleError(Dart_GetNativeArgument(arguments, 0));
  OracleMetadataVector* metadata_vector;
  HandleError(Dart_GetNativeInstanceField(
    metadata_vector_obj,
    0,
    reinterpret_cast<intptr_t*>(&metadata_vector)));

  Dart_Handle result = NULL;
  result = HandleError(Dart_NewInteger(metadata_vector->v_metadata.size()));

  Dart_SetReturnValue(arguments, result);
  Dart_ExitScope();
}

struct FunctionLookup {
  const char* name;
  Dart_NativeFunction function;
};

FunctionLookup function_list[] = {
    {"OracleConnection_Connect", OracleConnection_Connect},
    {"OracleConnection_CreateStatement", OracleConnection_CreateStatement},
    {"OracleStatement_Execute", OracleStatement_Execute},
    {"OracleStatement_SetInt", OracleStatement_SetInt},
    {"OracleStatement_SetString", OracleStatement_SetString},
    {"OracleResultset_GetString", OracleResultset_GetString},
    {"OracleResultset_GetInt", OracleResultset_GetInt},
    {"OracleResultset_GetDouble", OracleResultset_GetDouble},
    {"OracleResultset_GetFloat", OracleResultset_GetFloat},
    {"OracleResultset_Next", OracleResultset_Next},
    {"OracleResultset_GetMetadataVector", OracleResultset_GetMetadataVector},
    {"OracleMetadataVector_GetSize", OracleMetadataVector_GetSize},

    {NULL, NULL}};

Dart_NativeFunction ResolveName(Dart_Handle name,
                                int argc,
                                bool* auto_setup_scope) {
  if (!Dart_IsString(name)) return NULL;
  Dart_NativeFunction result = NULL;
  if (auto_setup_scope == NULL) return NULL;
  *auto_setup_scope = true;
  Dart_EnterScope();
  const char* cname;
  HandleError(Dart_StringToCString(name, &cname));

  for (int i=0; function_list[i].name != NULL; ++i) {
    if (strcmp(function_list[i].name, cname) == 0) {
      result = function_list[i].function;
      break;
    }
  }
  Dart_ExitScope();
  return result;
}
<commit_msg>Fixing parameters types<commit_after>// Copyright (c) 2014, Alexander Aprelev.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>

#include <occi.h>

#include "include/dart_api.h"
#include "include/dart_native_api.h"

Dart_NativeFunction ResolveName(Dart_Handle name,
                                int argc,
                                bool* auto_setup_scope);

DART_EXPORT Dart_Handle oracledart_extension_Init(Dart_Handle parent_library) {
  if (Dart_IsError(parent_library)) { return parent_library; }

  Dart_Handle result_code = Dart_SetNativeResolver(parent_library, ResolveName, NULL);
  if (Dart_IsError(result_code)) return result_code;

  return Dart_Null();
}

Dart_Handle HandleError(Dart_Handle handle) {
  if (Dart_IsError(handle)) Dart_PropagateError(handle);
  return handle;
}

struct OracleConnection {
  oracle::occi::Environment *env;
  oracle::occi::Connection *conn;

  OracleConnection(std::string user, std::string password, std::string db) {
    env = oracle::occi::Environment::createEnvironment(oracle::occi::Environment::DEFAULT);
    conn = env->createConnection(user, password, db);
  }

  void Terminate() {
    env->terminateConnection(conn);
    oracle::occi::Environment::terminateEnvironment(env);
    conn = NULL;
    env = NULL;
  }
};

struct OracleStatement {
  OracleConnection *connection;
  oracle::occi::Statement *statement;

  OracleStatement(OracleConnection *connection,
                  oracle::occi::Statement *statement):
      connection(connection),
      statement(statement) {}

  void Close() {
    if (connection != NULL && connection->conn != NULL) {
      connection->conn->terminateStatement(statement);
      connection = NULL;
      statement = NULL;
    }
  }
};

struct OracleResultset {
  OracleStatement *statement;
  oracle::occi::ResultSet *resultset;

  OracleResultset(OracleStatement *statement,
                  oracle::occi::ResultSet *resultset):
      statement(statement),
      resultset(resultset) {}

  void Close() {
    if (statement != NULL
      && resultset != NULL
      && statement->statement != NULL
      && statement->connection->conn != NULL) {
      statement->statement->closeResultSet(resultset);
      statement = NULL;
      resultset = NULL;
	  }
  }
};

struct OracleMetadataVector {
  std::vector<oracle::occi::MetaData> v_metadata;

  OracleMetadataVector(std::vector<oracle::occi::MetaData> _v_metadata):v_metadata(_v_metadata) {}
};

static void OracleConnectionFinalizer(void* isolate_callback_data,
                                      Dart_WeakPersistentHandle handle,
                                      void* pvoid_oracle_connection) {
  OracleConnection* oracle_connection =
      static_cast<OracleConnection*>(pvoid_oracle_connection);
  oracle_connection->Terminate();
}

static void OracleStatementFinalizer(void* isolate_callback_data,
                                     Dart_WeakPersistentHandle handle,
                                     void* pvoid_oracle_statement) {
  OracleStatement* oracle_statement =
     static_cast<OracleStatement*>(pvoid_oracle_statement);
  oracle_statement->Close();
}

static void OracleResultsetFinalizer(void* isolate_callback_data,
                                     Dart_WeakPersistentHandle handle,
                                     void* pvoid_oracle_resultset) {
  OracleResultset* oracle_resultset =
      static_cast<OracleResultset*>(pvoid_oracle_resultset);
  oracle_resultset->Close();
}

void OracleConnection_Connect(Dart_NativeArguments arguments) {
  Dart_EnterScope();

  Dart_Handle connection_obj = Dart_GetNativeArgument(arguments, 0);

  Dart_Handle username_object = HandleError(Dart_GetNativeArgument(arguments, 1));
  const char* username;
  HandleError(Dart_StringToCString(username_object, &username));
  Dart_Handle password_object = HandleError(Dart_GetNativeArgument(arguments, 2));
  const char* password;
  HandleError(Dart_StringToCString(password_object, &password));
  Dart_Handle db_object = HandleError(Dart_GetNativeArgument(arguments, 3));
  const char* db;
  HandleError(Dart_StringToCString(db_object, &db));

  OracleConnection* connection = NULL;
  try {
   connection = new OracleConnection(username, password, db);
  } catch(oracle::occi::SQLException exception) {
    Dart_PropagateError(Dart_NewUnhandledExceptionError(Dart_NewStringFromCString(exception.getMessage().c_str())));
  }

  HandleError(Dart_SetNativeInstanceField(
      connection_obj,
      0,
      reinterpret_cast<intptr_t>(connection)));

  Dart_NewWeakPersistentHandle(
      connection_obj,
      connection,
      0,
      OracleConnectionFinalizer);

  Dart_ExitScope();
}

void OracleConnection_CreateStatement(Dart_NativeArguments arguments) {
  Dart_EnterScope();

  Dart_Handle connection_obj = HandleError(Dart_GetNativeArgument(arguments, 0));
  OracleConnection* connection;
  HandleError(Dart_GetNativeInstanceField(
      connection_obj,
      0,
      reinterpret_cast<intptr_t*>(&connection)));

  Dart_Handle statement_obj = HandleError(Dart_GetNativeArgument(arguments, 1));

  Dart_Handle query_obj = HandleError(Dart_GetNativeArgument(arguments, 2));
  const char* query;
  HandleError(Dart_StringToCString(query_obj, &query));

  OracleStatement* oracleStatement = NULL;
  try {
    oracle::occi::Statement* stmt = connection->conn->createStatement(query);
    oracleStatement = new OracleStatement(connection, stmt);
  } catch(oracle::occi::SQLException exception) {
    Dart_PropagateError(Dart_NewUnhandledExceptionError(Dart_NewStringFromCString(exception.getMessage().c_str())));
  }

  HandleError(Dart_SetNativeInstanceField(
      statement_obj,
      0,
      reinterpret_cast<intptr_t>(oracleStatement)));

  Dart_NewWeakPersistentHandle(
      statement_obj,
      oracleStatement,
      0,
      OracleStatementFinalizer);

  Dart_ExitScope();
}

void OracleStatement_Execute(Dart_NativeArguments arguments) {
  Dart_EnterScope();

  Dart_Handle statement_obj = HandleError(Dart_GetNativeArgument(arguments, 0));
  OracleStatement* oracleStatement;
  HandleError(Dart_GetNativeInstanceField(
      statement_obj,
      0,
      reinterpret_cast<intptr_t*>(&oracleStatement)));

  Dart_Handle resultset_obj = HandleError(Dart_GetNativeArgument(arguments, 1));
  oracle::occi::ResultSet *rset = NULL;
  try {
    rset = oracleStatement->statement->executeQuery();
  } catch(oracle::occi::SQLException exception) {
    Dart_PropagateError(Dart_NewUnhandledExceptionError(Dart_NewStringFromCString(exception.getMessage().c_str())));
  }

  OracleResultset* resultset = new OracleResultset(oracleStatement, rset);
  HandleError(Dart_SetNativeInstanceField(
      resultset_obj,
      0,
      reinterpret_cast<intptr_t>(resultset)));

  Dart_NewWeakPersistentHandle(
      resultset_obj,
      resultset,
      0,
      OracleResultsetFinalizer);

  Dart_ExitScope();
}

void OracleStatement_SetInt(Dart_NativeArguments arguments) {
  Dart_EnterScope();

  Dart_Handle statement_obj = HandleError(Dart_GetNativeArgument(arguments, 0));
  OracleStatement* oracleStatement;
  HandleError(Dart_GetNativeInstanceField(
      statement_obj,
      0,
      reinterpret_cast<intptr_t*>(&oracleStatement)));

  Dart_Handle index_obj = HandleError(Dart_GetNativeArgument(arguments, 1));
  int64_t index;
  HandleError(Dart_IntegerToInt64(index_obj, &index));

  Dart_Handle value_obj = HandleError(Dart_GetNativeArgument(arguments, 2));
  int64_t value;
  HandleError(Dart_IntegerToInt64(value_obj, &value));

  try {
    oracleStatement->statement->setInt(index, value);
  } catch(oracle::occi::SQLException exception) {
    Dart_PropagateError(Dart_NewUnhandledExceptionError(Dart_NewStringFromCString(exception.getMessage().c_str())));
  }

  Dart_ExitScope();
}

void OracleStatement_SetString(Dart_NativeArguments arguments) {
  Dart_EnterScope();

  Dart_Handle statement_obj = HandleError(Dart_GetNativeArgument(arguments, 0));
  OracleStatement* oracleStatement;
  HandleError(Dart_GetNativeInstanceField(
      statement_obj,
      0,
      reinterpret_cast<intptr_t*>(&oracleStatement)));

  Dart_Handle index_obj = HandleError(Dart_GetNativeArgument(arguments, 1));
  int64_t index;
  HandleError(Dart_IntegerToInt64(index_obj, &index));

  Dart_Handle value_obj = HandleError(Dart_GetNativeArgument(arguments, 2));
  const char* value;
  HandleError(Dart_StringToCString(value_obj, &value));

  try {
    oracleStatement->statement->setString(index, value);
  } catch(oracle::occi::SQLException exception) {
    Dart_PropagateError(Dart_NewUnhandledExceptionError(Dart_NewStringFromCString(exception.getMessage().c_str())));
  }

  Dart_ExitScope();
}

void OracleResultset_Next(Dart_NativeArguments arguments) {
  Dart_EnterScope();

  Dart_Handle resultset_obj = HandleError(Dart_GetNativeArgument(arguments, 0));
  OracleResultset* resultset;
  HandleError(Dart_GetNativeInstanceField(
    resultset_obj,
    0,
    reinterpret_cast<intptr_t*>(&resultset)));

  try {
    Dart_Handle result = HandleError(Dart_NewBoolean(resultset->resultset->next()));
    Dart_SetReturnValue(arguments, result);
  } catch(oracle::occi::SQLException exception) {
    Dart_PropagateError(Dart_NewUnhandledExceptionError(Dart_NewStringFromCString(exception.getMessage().c_str())));
  }

  Dart_ExitScope();
}

void OracleResultset_Get(Dart_NativeArguments arguments, oracle::occi::Type type) {
  Dart_EnterScope();

  Dart_Handle resultset_obj = HandleError(Dart_GetNativeArgument(arguments, 0));
  OracleResultset* resultset;
  HandleError(Dart_GetNativeInstanceField(
    resultset_obj,
    0,
    reinterpret_cast<intptr_t*>(&resultset)));

  Dart_Handle index_obj = HandleError(Dart_GetNativeArgument(arguments, 1));
  int64_t index;
  HandleError(Dart_IntegerToInt64(index_obj, &index));

  Dart_Handle result = NULL;
  try {
    switch(type) {
      case oracle::occi::OCCIINT:
        result = HandleError(Dart_NewInteger(resultset->resultset->getInt(index)));
        break;
      case oracle::occi::OCCISTRING:
      {
        std::string s = resultset->resultset->getString(index);
        result = Dart_NewStringFromCString(s.c_str());
        break;
      }
      case oracle::occi::OCCIDOUBLE:
        result = Dart_NewDouble(resultset->resultset->getDouble(index));
        break;
      case oracle::occi::OCCIFLOAT:
        result = Dart_NewDouble(resultset->resultset->getFloat(index));
        break;
      default:
        Dart_PropagateError(Dart_NewApiError("Requested type is not supported by OracleDart."));
        break;
    }
  } catch(oracle::occi::SQLException exception) {
    Dart_PropagateError(
      Dart_NewUnhandledExceptionError(
        Dart_NewStringFromCString(
          exception.getMessage().c_str())));
  }
  Dart_SetReturnValue(arguments, result);
  Dart_ExitScope();
}

void OracleResultset_GetInt(Dart_NativeArguments arguments) {
  return OracleResultset_Get(arguments, oracle::occi::OCCIINT);
}

void OracleResultset_GetString(Dart_NativeArguments arguments) {
  return OracleResultset_Get(arguments, oracle::occi::OCCISTRING);
}

void OracleResultset_GetDouble(Dart_NativeArguments arguments) {
  return OracleResultset_Get(arguments, oracle::occi::OCCIDOUBLE);
}

void OracleResultset_GetFloat(Dart_NativeArguments arguments) {
  return OracleResultset_Get(arguments, oracle::occi::OCCIFLOAT);
}

void OracleResultset_GetMetadataVector(Dart_NativeArguments arguments) {
  Dart_EnterScope();

  Dart_Handle resultset_obj = HandleError(Dart_GetNativeArgument(arguments, 0));
  OracleResultset* resultset;
  HandleError(Dart_GetNativeInstanceField(
    resultset_obj,
    0,
    reinterpret_cast<intptr_t*>(&resultset)));

  Dart_Handle metadata_vector_obj = HandleError(Dart_GetNativeArgument(arguments, 1));

  OracleMetadataVector* metadata_vector = NULL;
  try {
    metadata_vector = new OracleMetadataVector(
        resultset->resultset->getColumnListMetaData());
  } catch(oracle::occi::SQLException exception) {
    Dart_PropagateError(
        Dart_NewUnhandledExceptionError(
            Dart_NewStringFromCString(
                exception.getMessage().c_str())));
  }

  HandleError(Dart_SetNativeInstanceField(
      metadata_vector_obj,
      0,
      reinterpret_cast<intptr_t>(metadata_vector)));

  Dart_ExitScope();
}

void OracleMetadataVector_GetSize(Dart_NativeArguments arguments) {
  Dart_EnterScope();

  Dart_Handle metadata_vector_obj = HandleError(Dart_GetNativeArgument(arguments, 0));
  OracleMetadataVector* metadata_vector;
  HandleError(Dart_GetNativeInstanceField(
    metadata_vector_obj,
    0,
    reinterpret_cast<intptr_t*>(&metadata_vector)));

  Dart_Handle result = NULL;
  result = HandleError(Dart_NewInteger(metadata_vector->v_metadata.size()));

  Dart_SetReturnValue(arguments, result);
  Dart_ExitScope();
}

struct FunctionLookup {
  const char* name;
  Dart_NativeFunction function;
};

FunctionLookup function_list[] = {
    {"OracleConnection_Connect", OracleConnection_Connect},
    {"OracleConnection_CreateStatement", OracleConnection_CreateStatement},
    {"OracleStatement_Execute", OracleStatement_Execute},
    {"OracleStatement_SetInt", OracleStatement_SetInt},
    {"OracleStatement_SetString", OracleStatement_SetString},
    {"OracleResultset_GetString", OracleResultset_GetString},
    {"OracleResultset_GetInt", OracleResultset_GetInt},
    {"OracleResultset_GetDouble", OracleResultset_GetDouble},
    {"OracleResultset_GetFloat", OracleResultset_GetFloat},
    {"OracleResultset_Next", OracleResultset_Next},
    {"OracleResultset_GetMetadataVector", OracleResultset_GetMetadataVector},
    {"OracleMetadataVector_GetSize", OracleMetadataVector_GetSize},

    {NULL, NULL}};

Dart_NativeFunction ResolveName(Dart_Handle name,
                                int argc,
                                bool* auto_setup_scope) {
  if (!Dart_IsString(name)) return NULL;
  Dart_NativeFunction result = NULL;
  if (auto_setup_scope == NULL) return NULL;
  *auto_setup_scope = true;
  Dart_EnterScope();
  const char* cname;
  HandleError(Dart_StringToCString(name, &cname));

  for (int i=0; function_list[i].name != NULL; ++i) {
    if (strcmp(function_list[i].name, cname) == 0) {
      result = function_list[i].function;
      break;
    }
  }
  Dart_ExitScope();
  return result;
}
<|endoftext|>


<commit_before>// -*- mode: c++; coding: utf-8 -*-
/*! @file simulation.cpp
    @brief Inplementation of Simulation class
*/
#include "model.hpp"

#include <cstdlib>
#include <algorithm>

#include <boost/filesystem.hpp>
#include <boost/math/distributions/normal.hpp>
#include <boost/coroutine2/coroutine.hpp>

#define EIGEN_NO_DEBUG
#include "Eigen/Core"

#include <cxxwtils/iostr.hpp>
#include <cxxwtils/getopt.hpp>
#include <cxxwtils/prandom.hpp>
#include <cxxwtils/algorithm.hpp>
#include <cxxwtils/os.hpp>
#include <cxxwtils/gz.hpp>
#include <cxxwtils/eigen.hpp>

namespace lmpp {

namespace bmath = boost::math;
namespace fs = boost::filesystem;
namespace po = boost::program_options;

inline po::options_description general_desc() {HERE;
    po::options_description description("General");
    description.add_options()
        ("help,h", po::value<bool>()->default_value(false)->implicit_value(true), "print this help")
        ("verbose,v", po::value<bool>()->default_value(false)->implicit_value(true), "verbose output")
        ("test", po::value<int>()->default_value(0)->implicit_value(1));
    return description;
}

po::options_description Model::options_desc() {HERE;
    po::options_description description("Simulation");
    description.add_options()
        ("write,w", po::value<bool>(&WRITE_TO_FILES)->default_value(WRITE_TO_FILES)->implicit_value(true))
        ("out_dir,o", po::value<std::string>(&OUT_DIR)->default_value(OUT_DIR))
        ("seed", po::value<unsigned int>(&SEED)->default_value(SEED));
    return description;
}

po::options_description Model::positional_desc() {HERE;
    po::options_description description("Positional");
    description.add_options()
        ("epsilon", po::value(&epsilon_)->default_value(epsilon_))
        ("threshold", po::value(&threshold_)->default_value(threshold_));
    return description;
}

void Model::help_and_exit() {HERE;
    auto description = general_desc();
    description.add(options_desc());
    // do not print positional arguments as options
    std::cout << "Usage: tumopp [options] nsam howmany\n" << std::endl;
    description.print(std::cout);
    throw wtl::ExitSuccess();
}

//! Unit test for each class
inline void test(const int flg) {HERE;
    switch (flg) {
      case 0:
        break;
      case 1:
        throw wtl::ExitSuccess();
      default:
        throw std::runtime_error("Unknown argument for --test");
    }
}

Model::Model(const std::vector<std::string>& arguments) {HERE;
    std::ios::sync_with_stdio(false);
    std::cin.tie(0);
    std::cout.precision(15);
    std::cerr.precision(6);
    COMMAND_ARGS = wtl::str_join(arguments, " ");
    OUT_DIR = wtl::strftime("tumopp_%Y%m%d_%H%M_") + std::to_string(::getpid());

    auto description = general_desc();
    description.add(options_desc());
    description.add(positional_desc());
    po::positional_options_description positional;
    positional.add("nsam", 1)
              .add("howmany", 1);
    po::variables_map vm;
    po::store(po::command_line_parser(arguments).
              options(description).
              positional(positional).run(), vm);
    if (vm["help"].as<bool>()) {help_and_exit();}
    po::notify(vm);
    wtl::sfmt().seed(SEED);

    // CONFIG_STRING = wtl::flags_into_string(vm);
    if (vm["verbose"].as<bool>()) {
        std::cerr << wtl::iso8601datetime() << std::endl;
        std::cerr << CONFIG_STRING << std::endl;
    }
    test(vm["test"].as<int>());
    OUT_DIR = fs::system_complete(OUT_DIR).string();
}

inline double normal_cdf(const double x, const double mean, const double sd, const bool complement=false) {
    if (complement) {
        return bmath::cdf(bmath::complement(bmath::normal(mean, sd), x));
    } else {
        return bmath::cdf(bmath::normal(mean, sd), x);
    }
}

inline double Model::normal_ccdf(double score, const double sd) {
    return normal_cdf(threshold_, score += epsilon_, sd, true);
}

inline bool equals_one(double x) {
    return std::fabs(x - 1.0) < std::numeric_limits<double>::epsilon();
}

template <class value_type>
class BruteForce {
  public:
    typedef boost::coroutines2::coroutine<value_type> coro_t;
    BruteForce() = delete;
    BruteForce(const value_type& axis, const size_t dimensions):
        dimensions_(dimensions),
        level_(dimensions),
        current_(dimensions),
        axis_(axis) {}

    typename coro_t::pull_type generate() {
        return typename coro_t::pull_type([this](typename coro_t::push_type& yield){source(yield);});
    }

  private:
    void source(typename coro_t::push_type& yield) {
        if (--level_ > 0) {
            for (const auto x: axis_) {
                current_[level_] = x;
                source(yield);
            }
            ++level_;
        } else {
            for (const auto x: axis_) {
                current_[level_] = x;
                yield(value_type(current_));
            }
            ++level_;
        }
    }

    const double dimensions_;
    size_t level_;
    value_type current_;
    value_type axis_;
};

template <class T>
BruteForce<T> brute_force(const T& axis, const size_t dimensions) {
    return BruteForce<T>(axis, dimensions);
}

class SimplexIterator;

class Simplex {
  public:
    typedef std::vector<double> value_type;
    typedef SimplexIterator iterator;
    typedef boost::coroutines2::coroutine<value_type> coro_t;
    Simplex() = delete;
    Simplex(const value_type& axis, const size_t dimensions): bf_(axis, dimensions) {}

    iterator begin();
    iterator end();
    Simplex& operator++() {
        return *this;
    }
    typename coro_t::pull_type generate() {
        return typename coro_t::pull_type([this](typename coro_t::push_type& yield){source(yield);});
    }

  private:
    void source(typename coro_t::push_type& yield) {
        const double e = std::numeric_limits<double>::epsilon();
        for (const auto& v: bf_.generate()) {
            if (std::fabs(wtl::sum(v) - 1.0) < e) {yield(v);}
        }
    }
    BruteForce<value_type> bf_;
};

class SimplexIterator: public std::iterator<std::forward_iterator_tag, double> {
  public:
    SimplexIterator(Simplex* x): ptr_(x) {}
    Simplex& operator*() const {
        return *ptr_;
    }
    Simplex* operator->() const {
        return ptr_;
    }
    SimplexIterator& operator++() {
        ptr_->operator++();
        return *this;
    }
    bool operator!= (const SimplexIterator& it) const {
        return (ptr_ != it.ptr_);
    }
  private:
    Simplex* ptr_;
};

SimplexIterator Simplex::begin() {return SimplexIterator(this);}
SimplexIterator Simplex::end() {return SimplexIterator(this);}

template <class T>
inline void nested_loop(const T& range, size_t nest=3, T current={}) {
    if (current.empty()) current.assign(nest, 0);
    if (--nest > 0) {
        for (const auto& x: range) {
            current[nest] = x;
            nested_loop(range, nest, current);
        }
    } else {
        for (const auto& x: range) {
            current[nest] = x;
            std::cout << current << std::endl;
        }
    }
}

template <>
inline void nested_loop<Eigen::VectorXd>(const Eigen::VectorXd& range, size_t nest, Eigen::VectorXd current) {
    if (current.size() == 0) current.resize(nest);
    auto end = range.data() + range.size();
    if (--nest > 0) {
        for (auto p=range.data(); p<end; ++p) {
            current[nest] = *p;
            nested_loop(range, nest, current);
        }
    } else {
        for (auto p=range.data(); p<end; ++p) {
            current[nest] = *p;
            std::cout << wtl::eigen::as_vector(current) << std::endl;
        }
    }
}

void Model::genotype2score() {HERE;
    size_t dimensions = 2;
    size_t num_samples = 4;
    Eigen::VectorXd parameter(dimensions);
    Eigen::MatrixXd genotype(num_samples, dimensions);
    parameter << 0.3, 0.4;
    genotype << 0, 0,
        1, 0,
        0, 1,
        1, 1;
    std::cout << genotype * parameter << std::endl;
    std::cout << normal_ccdf(0.1, 0.5) << std::endl;
    std::cout << normal_ccdf(0.3, 0.5) << std::endl;
    std::cout << normal_ccdf(0.4, 0.5) << std::endl;
    std::cout << normal_ccdf(0.5, 0.5) << std::endl;
    std::cout << normal_ccdf(0.7, 0.5) << std::endl;
}

void Model::run() {HERE;
    // genotype2score();
    Eigen::VectorXd vxd = Eigen::VectorXd::LinSpaced(3, 0.0, 1.0);
    auto vd = wtl::eigen::as_vector(vxd);
    auto bf = brute_force(vd, 3);
    for (const auto& x: bf.generate()) {
        std::cout << x << std::endl;
    }

    Simplex sim(vd, 3);
    for (const auto& x: sim.generate()) {
        std::cout << x << std::endl;
    }
}

void Model::write() const {HERE;
    auto mat = Eigen::Matrix3d::Random();
    std::ofstream("test.tsv") << mat.format(wtl::eigen::tsv());
    std::cout << wtl::eigen::read_matrix<double>("test.tsv").format(wtl::eigen::tsv()) << std::endl;
    if (WRITE_TO_FILES) {
        derr("mkdir && cd to " << OUT_DIR << std::endl);
        fs::create_directory(OUT_DIR);
        wtl::cd(OUT_DIR);
        wtl::Fout{"program_options.conf"} << CONFIG_STRING;
        std::cerr << wtl::iso8601datetime() << std::endl;
    }
}

} // namespace tumopp
<commit_msg>Upgrade BruteForce to ExpandGrid<commit_after>// -*- mode: c++; coding: utf-8 -*-
/*! @file simulation.cpp
    @brief Inplementation of Simulation class
*/
#include "model.hpp"

#include <cstdlib>
#include <algorithm>

#include <boost/filesystem.hpp>
#include <boost/math/distributions/normal.hpp>
#include <boost/coroutine2/coroutine.hpp>

#define EIGEN_NO_DEBUG
#include "Eigen/Core"

#include <cxxwtils/iostr.hpp>
#include <cxxwtils/getopt.hpp>
#include <cxxwtils/prandom.hpp>
#include <cxxwtils/algorithm.hpp>
#include <cxxwtils/os.hpp>
#include <cxxwtils/gz.hpp>
#include <cxxwtils/eigen.hpp>

namespace lmpp {

namespace bmath = boost::math;
namespace fs = boost::filesystem;
namespace po = boost::program_options;

inline po::options_description general_desc() {HERE;
    po::options_description description("General");
    description.add_options()
        ("help,h", po::value<bool>()->default_value(false)->implicit_value(true), "print this help")
        ("verbose,v", po::value<bool>()->default_value(false)->implicit_value(true), "verbose output")
        ("test", po::value<int>()->default_value(0)->implicit_value(1));
    return description;
}

po::options_description Model::options_desc() {HERE;
    po::options_description description("Simulation");
    description.add_options()
        ("write,w", po::value<bool>(&WRITE_TO_FILES)->default_value(WRITE_TO_FILES)->implicit_value(true))
        ("out_dir,o", po::value<std::string>(&OUT_DIR)->default_value(OUT_DIR))
        ("seed", po::value<unsigned int>(&SEED)->default_value(SEED));
    return description;
}

po::options_description Model::positional_desc() {HERE;
    po::options_description description("Positional");
    description.add_options()
        ("epsilon", po::value(&epsilon_)->default_value(epsilon_))
        ("threshold", po::value(&threshold_)->default_value(threshold_));
    return description;
}

void Model::help_and_exit() {HERE;
    auto description = general_desc();
    description.add(options_desc());
    // do not print positional arguments as options
    std::cout << "Usage: tumopp [options] nsam howmany\n" << std::endl;
    description.print(std::cout);
    throw wtl::ExitSuccess();
}

//! Unit test for each class
inline void test(const int flg) {HERE;
    switch (flg) {
      case 0:
        break;
      case 1:
        throw wtl::ExitSuccess();
      default:
        throw std::runtime_error("Unknown argument for --test");
    }
}

Model::Model(const std::vector<std::string>& arguments) {HERE;
    std::ios::sync_with_stdio(false);
    std::cin.tie(0);
    std::cout.precision(15);
    std::cerr.precision(6);
    COMMAND_ARGS = wtl::str_join(arguments, " ");
    OUT_DIR = wtl::strftime("tumopp_%Y%m%d_%H%M_") + std::to_string(::getpid());

    auto description = general_desc();
    description.add(options_desc());
    description.add(positional_desc());
    po::positional_options_description positional;
    positional.add("nsam", 1)
              .add("howmany", 1);
    po::variables_map vm;
    po::store(po::command_line_parser(arguments).
              options(description).
              positional(positional).run(), vm);
    if (vm["help"].as<bool>()) {help_and_exit();}
    po::notify(vm);
    wtl::sfmt().seed(SEED);

    // CONFIG_STRING = wtl::flags_into_string(vm);
    if (vm["verbose"].as<bool>()) {
        std::cerr << wtl::iso8601datetime() << std::endl;
        std::cerr << CONFIG_STRING << std::endl;
    }
    test(vm["test"].as<int>());
    OUT_DIR = fs::system_complete(OUT_DIR).string();
}

inline double normal_cdf(const double x, const double mean, const double sd, const bool complement=false) {
    if (complement) {
        return bmath::cdf(bmath::complement(bmath::normal(mean, sd), x));
    } else {
        return bmath::cdf(bmath::normal(mean, sd), x);
    }
}

inline double Model::normal_ccdf(double score, const double sd) {
    return normal_cdf(threshold_, score += epsilon_, sd, true);
}

inline bool equals_one(double x) {
    return std::fabs(x - 1.0) < std::numeric_limits<double>::epsilon();
}

template <class value_type>
class ExpandGrid {
  public:
    typedef boost::coroutines2::coroutine<value_type> coro_t;
    ExpandGrid() = delete;
    ExpandGrid(const std::vector<value_type>& columns):
        columns_(columns),
        dimensions_(columns_.size()),
        level_(dimensions_),
        current_(dimensions_) {}

    typename coro_t::pull_type generate() {
        return typename coro_t::pull_type([this](typename coro_t::push_type& yield){source(yield);});
    }

  private:
    void source(typename coro_t::push_type& yield) {
        if (--level_ > 0) {
            for (const auto x: columns_[level_]) {
                current_[level_] = x;
                source(yield);
            }
            ++level_;
        } else {
            for (const auto x: columns_[level_]) {
                current_[level_] = x;
                yield(value_type(current_));
            }
            ++level_;
        }
    }

    const std::vector<value_type> columns_;
    const double dimensions_;
    size_t level_;
    value_type current_;
};

template <class T>
ExpandGrid<T> expand_grid(const std::vector<T>& columns) {
    return ExpandGrid<T>(columns);
}

class SimplexIterator;

class Simplex {
  public:
    typedef std::vector<double> value_type;
    typedef SimplexIterator iterator;
    typedef boost::coroutines2::coroutine<value_type> coro_t;
    Simplex() = delete;
    Simplex(const std::vector<value_type>& columns): grid_(columns) {}

    iterator begin();
    iterator end();
    Simplex& operator++() {
        return *this;
    }
    typename coro_t::pull_type generate() {
        return typename coro_t::pull_type([this](typename coro_t::push_type& yield){source(yield);});
    }

  private:
    void source(typename coro_t::push_type& yield) {
        const double e = std::numeric_limits<double>::epsilon();
        for (const auto& v: grid_.generate()) {
            if (std::fabs(wtl::sum(v) - 1.0) < e) {yield(v);}
        }
    }
    ExpandGrid<value_type> grid_;
};

class SimplexIterator {
  public:
    SimplexIterator(Simplex* x): ptr_(x) {}
    Simplex& operator*() const {
        return *ptr_;
    }
    Simplex* operator->() const {
        return ptr_;
    }
    SimplexIterator& operator++() {
        ptr_->operator++();
        return *this;
    }
    bool operator!= (const SimplexIterator& it) const {
        return (ptr_ != it.ptr_);
    }
  private:
    Simplex* ptr_;
};

SimplexIterator Simplex::begin() {return SimplexIterator(this);}
SimplexIterator Simplex::end() {return SimplexIterator(this);}

template <class T>
inline void nested_loop(const T& range, size_t nest=3, T current={}) {
    if (current.empty()) current.assign(nest, 0);
    if (--nest > 0) {
        for (const auto& x: range) {
            current[nest] = x;
            nested_loop(range, nest, current);
        }
    } else {
        for (const auto& x: range) {
            current[nest] = x;
            std::cout << current << std::endl;
        }
    }
}

template <>
inline void nested_loop<Eigen::VectorXd>(const Eigen::VectorXd& range, size_t nest, Eigen::VectorXd current) {
    if (current.size() == 0) current.resize(nest);
    auto end = range.data() + range.size();
    if (--nest > 0) {
        for (auto p=range.data(); p<end; ++p) {
            current[nest] = *p;
            nested_loop(range, nest, current);
        }
    } else {
        for (auto p=range.data(); p<end; ++p) {
            current[nest] = *p;
            std::cout << wtl::eigen::as_vector(current) << std::endl;
        }
    }
}

void Model::genotype2score() {HERE;
    size_t dimensions = 2;
    size_t num_samples = 4;
    Eigen::VectorXd parameter(dimensions);
    Eigen::MatrixXd genotype(num_samples, dimensions);
    parameter << 0.3, 0.4;
    genotype << 0, 0,
        1, 0,
        0, 1,
        1, 1;
    std::cout << genotype * parameter << std::endl;
    std::cout << normal_ccdf(0.1, 0.5) << std::endl;
    std::cout << normal_ccdf(0.3, 0.5) << std::endl;
    std::cout << normal_ccdf(0.4, 0.5) << std::endl;
    std::cout << normal_ccdf(0.5, 0.5) << std::endl;
    std::cout << normal_ccdf(0.7, 0.5) << std::endl;
}

void Model::run() {HERE;
    // genotype2score();
    Eigen::VectorXd vxd = Eigen::VectorXd::LinSpaced(3, 0.0, 1.0);
    auto vd = wtl::eigen::as_vector(vxd);
    std::vector<std::vector<double>> columns{vd, vd, vd};
    auto bf = expand_grid(columns);
    for (const auto& x: bf.generate()) {
        std::cout << x << std::endl;
    }

    Simplex sim(columns);
    for (const auto& x: sim.generate()) {
        std::cout << x << std::endl;
    }
}

void Model::write() const {HERE;
    auto mat = Eigen::Matrix3d::Random();
    std::ofstream("test.tsv") << mat.format(wtl::eigen::tsv());
    std::cout << wtl::eigen::read_matrix<double>("test.tsv").format(wtl::eigen::tsv()) << std::endl;
    if (WRITE_TO_FILES) {
        derr("mkdir && cd to " << OUT_DIR << std::endl);
        fs::create_directory(OUT_DIR);
        wtl::cd(OUT_DIR);
        wtl::Fout{"program_options.conf"} << CONFIG_STRING;
        std::cerr << wtl::iso8601datetime() << std::endl;
    }
}

} // namespace tumopp
<|endoftext|>