Example usage for java.sql ResultSet getDouble

List of usage examples for java.sql ResultSet getDouble

Introduction

In this page you can find the example usage for java.sql ResultSet getDouble.

Prototype

double getDouble(String columnLabel) throws SQLException;

Source Link

Document

Retrieves the value of the designated column in the current row of this ResultSet object as a double in the Java programming language.

Usage

From source file:com.l2jserver.model.template.NPCTemplateConverter.java

private static Object[] fillNPC(ResultSet rs) throws SQLException, IOException {
    final ObjectFactory factory = new ObjectFactory();

    final NPCTemplate template = factory.createNPCTemplate();
    template.setID(new NPCTemplateID(rs.getInt("idTemplate"), null));

    template.setController(controllers.get(rs.getString("type")));
    if (template.getController() == null)
        template.setController(NotImplementedNPCController.class);
    template.setInfo(factory.createNPCTemplateInfo());

    template.getInfo().setName(factory.createNPCTemplateInfoName());
    template.getInfo().getName().setValue(rs.getString("name"));
    // template.getInfo().getName().setDisplay(rs.getBoolean("show_name"));
    template.getInfo().getName().setSend(rs.getBoolean("serverSideName"));

    template.getInfo().setTitle(factory.createNPCTemplateInfoTitle());
    template.getInfo().getTitle().setValue(rs.getString("title"));
    template.getInfo().getTitle().setSend(rs.getBoolean("serverSideTitle"));

    if (template.getInfo().getName().getValue().length() == 0)
        template.getInfo().setName(null);
    if (template.getInfo().getTitle().getValue().length() == 0)
        template.getInfo().setTitle(null);

    template.getInfo().setLevel(rs.getInt("level"));
    template.getInfo().setRace(getRace(rs.getInt("race")));
    if (!rs.getString("sex").equals("etc"))
        template.getInfo().setSex(ActorSex.valueOf(rs.getString("sex").toUpperCase()));
    // template.info.attackable = rs.getBoolean("attackable");
    // template.getInfo().setTargetable(rs.getBoolean("targetable"));
    template.getInfo().setTargetable(true);
    // template.getInfo().setAggressive(rs.getBoolean("aggro"));
    template.getInfo().setAggressive(true);
    template.getInfo().setAttackable(true); // FIXME

    template.getInfo().setStats(factory.createNPCTemplateInfoStats());

    template.getInfo().getStats().setHp(factory.createNPCTemplateInfoStatsHp());
    template.getInfo().getStats().getHp().setMax(rs.getDouble("hp"));
    template.getInfo().getStats().getHp().setRegen(rs.getDouble("hpreg"));

    template.getInfo().getStats().setMp(factory.createNPCTemplateInfoStatsMp());
    template.getInfo().getStats().getMp().setMax(rs.getDouble("mp"));
    template.getInfo().getStats().getMp().setRegen(rs.getDouble("mpreg"));

    template.getInfo().getStats().setAttack(factory.createNPCTemplateInfoStatsAttack());
    template.getInfo().getStats().getAttack().setRange(rs.getInt("attackrange"));
    template.getInfo().getStats().getAttack().setCritical(rs.getInt("critical"));

    template.getInfo().getStats().getAttack().setPhysical(factory.createNPCTemplateInfoStatsAttackPhysical());
    template.getInfo().getStats().getAttack().getPhysical().setDamage(rs.getDouble("patk"));
    template.getInfo().getStats().getAttack().getPhysical().setSpeed(rs.getDouble("atkspd"));

    template.getInfo().getStats().getAttack().setMagical(factory.createNPCTemplateInfoStatsAttackMagical());
    template.getInfo().getStats().getAttack().getMagical().setDamage(rs.getDouble("matk"));
    template.getInfo().getStats().getAttack().getMagical().setSpeed(rs.getDouble("matkspd"));

    template.getInfo().getStats().setDefense(factory.createNPCTemplateInfoStatsDefense());
    template.getInfo().getStats().getDefense().setPhysical(factory.createNPCTemplateInfoStatsDefensePhysical());
    template.getInfo().getStats().getDefense().getPhysical().setValue(rs.getDouble("pdef"));
    template.getInfo().getStats().getDefense().setMagical(factory.createNPCTemplateInfoStatsDefenseMagical());
    template.getInfo().getStats().getDefense().getMagical().setValue(rs.getDouble("mdef"));

    template.getInfo().getStats().setMove(factory.createNPCTemplateInfoStatsMove());
    template.getInfo().getStats().getMove().setRun(rs.getDouble("runspd"));
    template.getInfo().getStats().getMove().setWalk(rs.getDouble("walkspd"));

    template.getInfo().getStats().setBase(factory.createNPCTemplateInfoStatsBase());
    template.getInfo().getStats().getBase().setInt(rs.getInt("int"));
    template.getInfo().getStats().getBase().setStr(rs.getInt("str"));
    template.getInfo().getStats().getBase().setCon(rs.getInt("con"));
    template.getInfo().getStats().getBase().setDex(rs.getInt("dex"));
    template.getInfo().getStats().getBase().setWit(rs.getInt("wit"));
    template.getInfo().getStats().getBase().setMen(rs.getInt("men"));

    template.getInfo().setExperience(rs.getLong("exp"));
    template.getInfo().setSp(rs.getInt("sp"));

    if (rs.getInt("rhand") > 0 || rs.getInt("lhand") > 0)
        template.getInfo().setItem(factory.createNPCTemplateInfoItem());
    if (rs.getInt("rhand") > 0)
        template.getInfo().getItem().setRightHand(new ItemTemplateID(rs.getInt("rhand"), null));
    if (rs.getInt("lhand") > 0)
        template.getInfo().getItem().setLeftHand(new ItemTemplateID(rs.getInt("lhand"), null));

    template.getInfo().setCollision(factory.createNPCTemplateInfoCollision());
    template.getInfo().getCollision().setRadius(rs.getDouble("collision_radius"));
    template.getInfo().getCollision().setHeigth(rs.getDouble("collision_height"));

    template.setDroplist(fillDropList(factory, rs, template.getID().getID()));
    template.setSkills(fillSkillList(factory, rs, template.getID().getID()));
    template.setTalk(fillHtmlChat(factory, template.getID().getID()));

    return new Object[] { template, createParentType(rs.getString("type")) };
}

From source file:nl.tudelft.stocktrader.derby.DerbyCustomerDAO.java

public List<Order> getCompletedOrders(String userId) throws DAOException {
    PreparedStatement selectClosedOrders = null;
    PreparedStatement updateClosedOrders = null;
    try {//from  w w w. j a  v a  2s. c o m
        selectClosedOrders = sqlConnection.prepareStatement(SQL_SELECT_COMPLETED_ORDERS);
        selectClosedOrders.setString(1, userId);
        ResultSet rs = selectClosedOrders.executeQuery();
        List<Order> closedOrders = new ArrayList<Order>();

        try {
            while (rs.next()) {
                int orderId = rs.getInt(1);
                Calendar openDate = StockTraderUtility.convertToCalendar(rs.getDate(4));
                Calendar completionDate = null;
                try {
                    completionDate = StockTraderUtility.convertToCalendar(rs.getDate(5));
                } catch (SQLException e) {
                    logger.debug("", e);
                    completionDate = Calendar.getInstance();
                    completionDate.setTimeInMillis(0);
                }
                Order closedOrderBean = new Order(orderId, rs.getString(2), rs.getString(3), openDate,
                        completionDate, rs.getDouble(6), rs.getBigDecimal(7), rs.getBigDecimal(8),
                        rs.getString(9));
                closedOrderBean.setOrderStatus(StockTraderUtility.ORDER_STATUS_CLOSED);
                closedOrders.add(closedOrderBean);
            }
        } finally {
            try {
                rs.close();
            } catch (SQLException e) {
                logger.debug("", e);
            }
        }

        if (!closedOrders.isEmpty()) {
            updateClosedOrders = sqlConnection.prepareStatement(SQL_UPDATE_CLOSED_ORDERS);
            updateClosedOrders.setString(1, userId);
            updateClosedOrders.executeUpdate();
        }

        return closedOrders;
    } catch (SQLException e) {
        throw new DAOException("", e);
    } finally {
        if (selectClosedOrders != null) {
            try {
                selectClosedOrders.close();
            } catch (SQLException e) {
                logger.debug("", e);
            }
        }
        if (updateClosedOrders != null) {
            try {
                selectClosedOrders.close();
            } catch (SQLException e) {
                logger.debug("", e);
            }
        }

    }
}

From source file:ResultSetIterator.java

/**
 * Convert a <code>ResultSet</code> column into an object.  Simple 
 * implementations could just call <code>rs.getObject(index)</code> while
 * more complex implementations could perform type manipulation to match 
 * the column's type to the bean property type.
 * /*  w  ww .  ja v a  2  s .c  o  m*/
 * <p>
 * This implementation calls the appropriate <code>ResultSet</code> getter 
 * method for the given property type to perform the type conversion.  If 
 * the property type doesn't match one of the supported 
 * <code>ResultSet</code> types, <code>getObject</code> is called.
 * </p>
 * 
 * @param rs The <code>ResultSet</code> currently being processed.  It is
 * positioned on a valid row before being passed into this method.
 * 
 * @param index The current column index being processed.
 * 
 * @param propType The bean property type that this column needs to be
 * converted into.
 * 
 * @throws SQLException if a database access error occurs
 * 
 * @return The object from the <code>ResultSet</code> at the given column
 * index after optional type processing or <code>null</code> if the column
 * value was SQL NULL.
 */
protected Object processColumn(ResultSet rs, int index, Class propType) throws SQLException {

    if (!propType.isPrimitive() && rs.getObject(index) == null) {
        return null;
    }

    if (propType.equals(String.class)) {
        return rs.getString(index);

    } else if (propType.equals(Integer.TYPE) || propType.equals(Integer.class)) {
        return new Integer(rs.getInt(index));

    } else if (propType.equals(Boolean.TYPE) || propType.equals(Boolean.class)) {
        return new Boolean(rs.getBoolean(index));

    } else if (propType.equals(Long.TYPE) || propType.equals(Long.class)) {
        return new Long(rs.getLong(index));

    } else if (propType.equals(Double.TYPE) || propType.equals(Double.class)) {
        return new Double(rs.getDouble(index));

    } else if (propType.equals(Float.TYPE) || propType.equals(Float.class)) {
        return new Float(rs.getFloat(index));

    } else if (propType.equals(Short.TYPE) || propType.equals(Short.class)) {
        return new Short(rs.getShort(index));

    } else if (propType.equals(Byte.TYPE) || propType.equals(Byte.class)) {
        return new Byte(rs.getByte(index));

    } else if (propType.equals(Timestamp.class)) {
        return rs.getTimestamp(index);

    } else {
        return rs.getObject(index);
    }

}

From source file:com.wso2telco.dep.ratecardservice.dao.TariffDAO.java

public TariffDTO getTariff(int tariffId) throws BusinessException {

    TariffDTO tariff = null;//from  ww  w .j  a  va2  s .co  m

    Connection con = null;
    ResultSet rs = null;
    PreparedStatement ps = null;

    try {

        con = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_RATE_DB);
        if (con == null) {

            log.error("unable to open " + DataSourceNames.WSO2TELCO_RATE_DB + " database connection");
            throw new BusinessException(ServiceError.SERVICE_ERROR_OCCURED);
        }

        StringBuilder query = new StringBuilder(
                "select tariffid, tariffname, tariffdesc, tariffdefaultval, tariffmaxcount, tariffexcessrate, tariffdefrate, tariffspcommission, tariffadscommission, tariffopcocommission, tariffsurchargeval, tariffsurchargeAds, tariffsurchargeOpco, createdby from ");
        query.append(DatabaseTables.TARIFF.getTObject());
        query.append(" where tariffid = ?");

        ps = con.prepareStatement(query.toString());

        log.debug("sql query in getTariff : " + ps);

        ps.setInt(1, tariffId);

        rs = ps.executeQuery();

        while (rs.next()) {

            tariff = new TariffDTO();

            tariff.setTariffId(rs.getInt("tariffid"));
            tariff.setTariffName(rs.getString("tariffname"));
            tariff.setTariffDescription(rs.getString("tariffdesc"));
            tariff.setTariffDefaultVal(rs.getDouble("tariffdefaultval"));
            tariff.setTariffMaxCount(rs.getInt("tariffmaxcount"));
            tariff.setTariffExcessRate(rs.getDouble("tariffexcessrate"));
            tariff.setTariffDefRate(rs.getDouble("tariffdefrate"));
            tariff.setTariffSPCommission(rs.getDouble("tariffspcommission"));
            tariff.setTariffAdsCommission(rs.getDouble("tariffadscommission"));
            tariff.setTariffOpcoCommission(rs.getDouble("tariffopcocommission"));
            tariff.setTariffSurChargeval(rs.getDouble("tariffsurchargeval"));
            tariff.setTariffSurChargeAds(rs.getDouble("tariffsurchargeAds"));
            tariff.setTariffSurChargeOpco(rs.getDouble("tariffsurchargeOpco"));
            tariff.setCreatedBy(rs.getString("createdby"));
        }
    } catch (SQLException e) {

        log.error("database operation error in getTariff : ", e);
        throw new BusinessException(ServiceError.SERVICE_ERROR_OCCURED);
    } catch (Exception e) {

        log.error("error in getTariff : ", e);
        throw new BusinessException(ServiceError.SERVICE_ERROR_OCCURED);
    } finally {

        DbUtils.closeAllConnections(ps, con, rs);
    }

    return tariff;
}

From source file:com.l2jfree.gameserver.datatables.NpcTable.java

private boolean fillNpcTable(ResultSet NpcData) throws Exception {
    boolean loaded = false;
    while (NpcData.next()) {
        StatsSet npcDat = new StatsSet();
        int id = NpcData.getInt("id");

        if (Config.ASSERT)
            assert id < 1000000;

        npcDat.set("npcId", id);
        npcDat.set("idTemplate", NpcData.getInt("idTemplate"));
        int level = NpcData.getInt("level");
        npcDat.set("level", level);
        npcDat.set("jClass", NpcData.getString("class"));

        npcDat.set("baseShldDef", 0);
        npcDat.set("baseShldRate", 0);
        npcDat.set("baseCritRate", 38);

        npcDat.set("name", NpcData.getString("name"));
        npcDat.set("serverSideName", NpcData.getBoolean("serverSideName"));
        npcDat.set("title", NpcData.getString("title"));
        npcDat.set("serverSideTitle", NpcData.getBoolean("serverSideTitle"));
        npcDat.set("collision_radius", NpcData.getDouble("collision_radius"));
        npcDat.set("collision_height", NpcData.getDouble("collision_height"));
        npcDat.set("fcollision_radius", NpcData.getDouble("collision_radius"));
        npcDat.set("fcollision_height", NpcData.getDouble("collision_height"));
        npcDat.set("sex", NpcData.getString("sex"));
        if (!Config.ALLOW_NPC_WALKERS && NpcData.getString("type").equalsIgnoreCase("L2NpcWalker"))
            npcDat.set("type", "L2Npc");
        else//w  w w  .  j ava2  s . com
            npcDat.set("type", NpcData.getString("type"));
        npcDat.set("baseAtkRange", NpcData.getInt("attackrange"));
        npcDat.set("rewardExp", NpcData.getInt("exp"));
        npcDat.set("rewardSp", NpcData.getInt("sp"));
        npcDat.set("basePAtkSpd", NpcData.getInt("atkspd"));
        npcDat.set("baseMAtkSpd", NpcData.getInt("matkspd"));
        npcDat.set("aggroRange", NpcData.getInt("aggro"));
        npcDat.set("rhand", NpcData.getInt("rhand"));
        npcDat.set("lhand", NpcData.getInt("lhand"));
        npcDat.set("armor", NpcData.getInt("armor"));
        npcDat.set("baseWalkSpd", NpcData.getInt("walkspd"));
        npcDat.set("baseRunSpd", NpcData.getInt("runspd"));

        npcDat.safeSet("baseSTR", NpcData.getInt("str"), 0, Formulas.MAX_STAT_VALUE,
                "Loading NPC template; ID: " + npcDat.getString("idTemplate"));
        npcDat.safeSet("baseCON", NpcData.getInt("con"), 0, Formulas.MAX_STAT_VALUE,
                "Loading NPC template; ID: " + npcDat.getString("idTemplate"));
        npcDat.safeSet("baseDEX", NpcData.getInt("dex"), 0, Formulas.MAX_STAT_VALUE,
                "Loading NPC template; ID: " + npcDat.getString("idTemplate"));
        npcDat.safeSet("baseINT", NpcData.getInt("int"), 0, Formulas.MAX_STAT_VALUE,
                "Loading NPC template; ID: " + npcDat.getString("idTemplate"));
        npcDat.safeSet("baseWIT", NpcData.getInt("wit"), 0, Formulas.MAX_STAT_VALUE,
                "Loading NPC template; ID: " + npcDat.getString("idTemplate"));
        npcDat.safeSet("baseMEN", NpcData.getInt("men"), 0, Formulas.MAX_STAT_VALUE,
                "Loading NPC template; ID: " + npcDat.getString("idTemplate"));

        npcDat.set("baseHpMax", NpcData.getInt("hp"));
        npcDat.set("baseCpMax", 0);
        npcDat.set("baseMpMax", NpcData.getInt("mp"));
        npcDat.set("baseHpReg",
                NpcData.getFloat("hpreg") > 0 ? NpcData.getFloat("hpreg") : 1.5 + ((level - 1) / 10.0));
        npcDat.set("baseMpReg",
                NpcData.getFloat("mpreg") > 0 ? NpcData.getFloat("mpreg") : 0.9 + 0.3 * ((level - 1) / 10.0));
        npcDat.set("basePAtk", NpcData.getInt("patk"));
        npcDat.set("basePDef", NpcData.getInt("pdef"));
        npcDat.set("baseMAtk", NpcData.getInt("matk"));
        npcDat.set("baseMDef", NpcData.getInt("mdef"));

        npcDat.set("factionId", NpcData.getString("faction_id"));
        npcDat.set("factionRange", NpcData.getInt("faction_range"));

        npcDat.set("isUndead", NpcData.getString("isUndead"));

        npcDat.set("absorb_level", NpcData.getString("absorb_level"));
        npcDat.set("absorb_type", NpcData.getString("absorb_type"));

        npcDat.set("ss", NpcData.getInt("ss"));
        npcDat.set("bss", NpcData.getInt("bss"));
        npcDat.set("ssRate", NpcData.getInt("ss_rate"));

        npcDat.set("AI", NpcData.getString("AI"));
        npcDat.set("drop_herbs", Boolean.valueOf(NpcData.getString("drop_herbs")));

        if (Config.FACTION_ENABLED) {
            Faction faction;
            for (int i = 0; i < FactionManager.getInstance().getFactions().size(); i++) {
                faction = FactionManager.getInstance().getFactions().get(i);
                if (faction.getNpcList().contains(id)) {
                    npcDat.set("NPCFaction", faction.getId());
                    npcDat.set("NPCFactionName", faction.getName());
                }
            }
        }

        L2NpcTemplate template = new L2NpcTemplate(npcDat);
        template.addVulnerability(Stats.BOW_WPN_VULN, 1);
        template.addVulnerability(Stats.CROSSBOW_WPN_VULN, 1);
        template.addVulnerability(Stats.BLUNT_WPN_VULN, 1);
        template.addVulnerability(Stats.DAGGER_WPN_VULN, 1);

        _npcs.set(id, template);

        loaded = true;
    }
    return loaded;
}

From source file:lineage2.gameserver.model.instances.PetInstance.java

/**
 * Method restore.//  w ww.  j a  va  2  s .co  m
 * @param control ItemInstance
 * @param template NpcTemplate
 * @param owner Player
 * @return PetInstance
 */
public static final PetInstance restore(ItemInstance control, NpcTemplate template, Player owner) {
    PetInstance pet = null;
    Connection con = null;
    PreparedStatement statement = null;
    ResultSet rset = null;
    try {
        con = DatabaseFactory.getInstance().getConnection();
        statement = con.prepareStatement(
                "SELECT objId, name, level, curHp, curMp, exp, sp, fed FROM pets WHERE item_obj_id=?");
        statement.setInt(1, control.getObjectId());
        rset = statement.executeQuery();
        if (!rset.next()) {
            if (PetDataTable.isBabyPet(template.getNpcId())
                    || PetDataTable.isImprovedBabyPet(template.getNpcId())) {
                pet = new PetBabyInstance(IdFactory.getInstance().getNextId(), template, owner, control);
            } else {
                pet = new PetInstance(IdFactory.getInstance().getNextId(), template, owner, control);
            }
            return pet;
        }
        if (PetDataTable.isBabyPet(template.getNpcId())
                || PetDataTable.isImprovedBabyPet(template.getNpcId())) {
            pet = new PetBabyInstance(rset.getInt("objId"), template, owner, control, rset.getInt("level"),
                    rset.getLong("exp"));
        } else {
            pet = new PetInstance(rset.getInt("objId"), template, owner, control, rset.getInt("level"),
                    rset.getLong("exp"));
        }
        pet.setRespawned(true);
        String name = rset.getString("name");
        pet.setName((name == null) || name.isEmpty() ? template.name : name);
        pet.setCurrentHpMp(rset.getDouble("curHp"), rset.getInt("curMp"), true);
        pet.setCurrentCp(pet.getMaxCp());
        pet.setSp(rset.getInt("sp"));
        pet.setCurrentFed(rset.getInt("fed"));
    } catch (Exception e) {
        _log.error("Could not restore Pet data from item: " + control + "!", e);
        return null;
    } finally {
        DbUtils.closeQuietly(con, statement, rset);
    }
    return pet;
}

From source file:net.tradelib.misc.StrategyText.java

public static List<InstrumentText> buildList(Connection con, String strategy, LocalDate date, String csvPath,
        char csvSep) throws Exception {
    // public static List<InstrumentText> buildList(Connection con, String strategy, LocalDate date) throws Exception {
    ArrayList<InstrumentText> result = new ArrayList<InstrumentText>();

    CSVPrinter printer = null;/*from w w  w .  jav  a2  s . c  om*/
    if (csvPath != null) {
        // Add withHeader for headers
        printer = CSVFormat.DEFAULT.withDelimiter(csvSep).print(new BufferedWriter(new FileWriter(csvPath)));
    }

    int numCsvColumns = 12;

    int rollMethod = 2;

    DatabaseMetaData dmd = con.getMetaData();
    String driverName = dmd.getDriverName();
    String query = "";
    if (driverName.startsWith("MySQL")) {
        query = STRATEGY_QUERY_MYSQL;
    } else {
        query = STRATEGY_QUERY;
    }

    String prevCategory = "";
    PreparedStatement pstmt = con.prepareStatement(query);
    pstmt.setString(1, strategy);
    pstmt.setTimestamp(2, Timestamp.valueOf(date.atStartOfDay()));
    ResultSet rs = pstmt.executeQuery();
    while (rs.next()) {
        String category = rs.getString(2);
        if (!category.equals(prevCategory)) {
            result.add(InstrumentText.makeSection(category));
            prevCategory = category;

            if (printer != null) {
                printer.print(category);
                for (int ii = 1; ii < numCsvColumns; ++ii) {
                    printer.print("");
                }
                printer.println();
            }
        }
        String name = rs.getString(3);
        String symbol = rs.getString(4);
        String contract = "";
        if (rollMethod == 1) {
            // Uses current_contract and trading_days
            int ndays = rs.getInt(12);
            if (ndays > 1) {
                contract = rs.getString(10);
            } else {
                contract = "Roll to " + rs.getString(11);
            }
        } else if (rollMethod == 2) {
            // Uses current_contract2 and roll_today
            int rollToday = rs.getInt(14);
            if (rollToday == 0) {
                contract = rs.getString(13);
            } else {
                contract = "Roll to " + rs.getString(13);
            }
        }

        if (printer != null) {
            printer.print(name);
            printer.print(symbol);
            printer.print(contract);
        }

        String signal;
        long position = (long) rs.getDouble(5);
        JsonObject jo = new Gson().fromJson(rs.getString(9), JsonObject.class);
        if (position > 0.0) {
            BigDecimal entryPrice;
            double pnl;
            try {
                entryPrice = jo.get("entry_price").getAsBigDecimal();
                pnl = jo.get("pnl").getAsDouble();
            } catch (Exception e) {
                entryPrice = BigDecimal.valueOf(Double.MIN_VALUE);
                pnl = Double.MIN_VALUE;
            }
            signal = String.format("Long [%d] since %s [at %s].", position, rs.getString(6),
                    formatBigDecimal(entryPrice));
            if (printer != null)
                printer.print(signal);
            String openProfit = String.format("Open equity profit %,d.", (int) Math.floor(pnl));
            signal += " " + openProfit;
            if (printer != null)
                printer.print(openProfit);
        } else if (position < 0.0) {
            BigDecimal entryPrice;
            double pnl;
            try {
                entryPrice = jo.get("entry_price").getAsBigDecimal();
                pnl = jo.get("pnl").getAsDouble();
            } catch (Exception e) {
                entryPrice = BigDecimal.valueOf(-1);
                pnl = -1;
            }
            signal = String.format("Short [%d] since %s [at %s].", Math.abs(position), rs.getString(6),
                    formatBigDecimal(entryPrice));
            if (printer != null)
                printer.print(signal);
            String openProfit = String.format("Open equity profit %,d.", (int) Math.floor(pnl));
            signal += " " + openProfit;
            if (printer != null)
                printer.print(openProfit);
        } else {
            signal = "Out.";
            if (printer != null) {
                printer.print(signal);
                // An empty column follows the status if there is no position - there is no profit.
                printer.print("");
            }
        }

        boolean hasOrder = false;
        JsonArray ja = jo.get("orders").getAsJsonArray();
        double entryRisk;
        try {
            entryRisk = jo.get("entry_risk").getAsDouble();
        } catch (Exception ee) {
            entryRisk = Double.NaN;
        }
        String profitTarget;
        Double profitTargetDbl;
        try {
            profitTarget = formatBigDecimal(jo.get("profit_target").getAsBigDecimal());
            profitTargetDbl = jo.get("profit_target").getAsDouble();
        } catch (Exception ee) {
            profitTarget = null;
            profitTargetDbl = null;
        }
        String stopLoss;
        Double stopLossDbl;
        try {
            stopLoss = formatBigDecimal(jo.get("stop_loss").getAsBigDecimal());
            stopLossDbl = jo.get("stop_loss").getAsDouble();
        } catch (Exception ee) {
            stopLoss = null;
            stopLossDbl = null;
        }

        Double lastClose;
        try {
            lastClose = jo.get("last_close").getAsDouble();
        } catch (Exception ee) {
            lastClose = null;
        }

        // Currently maximum one entry and maximum one exit are supported.
        String entryStr = "";
        String exitStr = "";
        String contractRiskStr = "";

        for (int ii = 0; ii < ja.size(); ++ii) {
            JsonObject jorder = ja.get(ii).getAsJsonObject();

            switch (jorder.get("type").getAsString()) {
            case "EXIT_LONG_STOP":
                exitStr = "Exit long at stop " + formatBigDecimal(jorder.get("stop_price").getAsBigDecimal())
                        + ".";
                signal += " " + exitStr;
                break;

            case "EXIT_SHORT_STOP":
                exitStr = "Exit short at stop " + formatBigDecimal(jorder.get("stop_price").getAsBigDecimal())
                        + ".";
                signal += " " + exitStr;
                break;

            case "ENTER_LONG":
                if (!Double.isNaN(entryRisk)) {
                    entryStr = String.format("Enter long at open. Contract risk is %s.",
                            formatDouble(entryRisk, 0, 0));
                    signal += " " + entryStr;
                } else {
                    entryStr = "Enter long at open.";
                    signal += " " + entryStr;
                }
                break;

            case "ENTER_SHORT":
                if (!Double.isNaN(entryRisk)) {
                    entryStr = String.format("Enter short at open. Contract risk is %s.",
                            formatDouble(entryRisk, 0, 0));
                    signal += " " + entryStr;
                } else {
                    entryStr = "Enter short at open.";
                    signal += " " + entryStr;
                }
                break;

            case "ENTER_LONG_STOP":
                position = jorder.get("quantity").getAsLong();
                entryStr = String.format("Enter long [%d] at stop %s [%s%%].", position,
                        formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()),
                        formatPercentage(jorder.get("stop_price").getAsDouble() / lastClose * 100 - 100));
                signal += " " + entryStr;
                if (!Double.isNaN(entryRisk)) {
                    contractRiskStr = String.format(" Contract risk is %s.", formatDouble(entryRisk, 0, 0));
                    signal += " " + contractRiskStr;
                }
                break;

            case "ENTER_LONG_STOP_LIMIT":
                position = jorder.get("quantity").getAsLong();
                entryStr = String.format("Enter long [%d] at limit %s, stop at %s [%s%%].", position,
                        formatBigDecimal(jorder.get("limit_price").getAsBigDecimal()),
                        formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()),
                        formatPercentage(jorder.get("stop_price").getAsDouble() / lastClose * 100 - 100));
                signal += " " + entryStr;
                if (!Double.isNaN(entryRisk)) {
                    contractRiskStr = String.format(" Contract risk is %s.", formatDouble(entryRisk, 0, 0));
                    signal += contractRiskStr;
                }
                break;

            case "ENTER_SHORT_STOP":
                // signal += " Enter short at stop " + formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()) + ".";
                position = jorder.get("quantity").getAsLong();
                entryStr = String.format("Enter short [%d] at stop %s [%s%%].", Math.abs(position),
                        formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()),
                        formatPercentage(jorder.get("stop_price").getAsDouble() / lastClose * 100 - 100));
                signal += " " + entryStr;
                if (!Double.isNaN(entryRisk)) {
                    contractRiskStr = String.format(" Contract risk is %s.", formatDouble(entryRisk, 0, 0));
                    signal += " " + contractRiskStr;
                }
                break;

            case "ENTER_SHORT_STOP_LIMIT":
                position = jorder.get("quantity").getAsLong();
                entryStr = String.format("Enter short [%d] at limit %s, stop at %s [%s%%].", Math.abs(position),
                        formatBigDecimal(jorder.get("limit_price").getAsBigDecimal()),
                        formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()),
                        formatPercentage(jorder.get("stop_price").getAsDouble() / lastClose * 100 - 100));
                signal += " " + entryStr;
                if (!Double.isNaN(entryRisk)) {
                    contractRiskStr = String.format(" Contract risk is %s.", formatDouble(entryRisk, 0, 0));
                    signal += " " + contractRiskStr;
                }
                break;

            case "EXIT_LONG":
                exitStr = "Exit long at open.";
                signal += " " + exitStr;
                break;

            case "EXIT_SHORT":
                exitStr = "Exit short at open.";
                signal += " " + exitStr;
                break;

            case "EXIT_SHORT_STOP_LIMIT":
                exitStr = "Exit short at limit " + formatBigDecimal(jorder.get("limit_price").getAsBigDecimal())
                        + ", stop at " + formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()) + " ["
                        + formatPercentage(jorder.get("stop_price").getAsDouble() / lastClose * 100 - 100)
                        + "%]" + ".";
                signal += " " + exitStr;
                break;

            case "EXIT_LONG_STOP_LIMIT":
                exitStr = "Exit long at limit " + formatBigDecimal(jorder.get("limit_price").getAsBigDecimal())
                        + ", stop at " + formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()) + " ["
                        + formatPercentage(jorder.get("stop_price").getAsDouble() / lastClose * 100 - 100)
                        + "%]" + ".";
                signal += " " + exitStr;
                break;
            }
            hasOrder = true;
        }

        String lastCloseStr = "Last close at " + formatBigDecimal(jo.get("last_close").getAsBigDecimal()) + ".";
        String stopLossStr = "";
        String profitTargetStr = "";

        if (hasOrder) {
            signal += " " + lastCloseStr;
        }

        if (stopLoss != null) {
            stopLossStr = "Stop loss at " + stopLoss;
            if (lastClose != null && stopLossDbl != null) {
                stopLossStr += " [" + formatPercentage(stopLossDbl / lastClose * 100 - 100) + "%]";
            }
            stopLossStr += ".";
            signal += " " + stopLossStr;
        }

        if (profitTarget != null) {
            profitTargetStr = "Profit target at about " + profitTarget;
            if (profitTargetDbl != null && lastClose != null) {
                profitTargetStr += " [" + formatPercentage(profitTargetDbl / lastClose * 100 - 100) + "%]";
            }
            profitTargetStr += ".";
            signal += " " + profitTargetStr;
        }

        if (printer != null) {
            printer.print(exitStr);
            printer.print(entryStr);
            printer.print(contractRiskStr);
            printer.print(lastCloseStr);
            printer.print(stopLossStr);
            printer.print(profitTargetStr);
            printer.println();
        }

        result.add(InstrumentText.make(name, symbol, contract, signal));
    }

    rs.close();
    pstmt.close();

    if (printer != null)
        printer.flush();

    return result;
}

From source file:org.meerkat.services.WebApp.java

/**
 * //from w  w  w  . j a v  a2  s .  c o m
 * getLatencyIndicator
 * @return    1 if last latency higher than latency average
 *          -1 if last latency lower than latency average
 *          0 if they are equal
 *          (No decimal plates considered)
 */
public double getLatencyIndicator() {
    double doubleLatencyAverage = getLatencyAverage();
    BigDecimal bd = new BigDecimal(doubleLatencyAverage);
    bd = bd.setScale(0, BigDecimal.ROUND_DOWN);
    double latencyAverage = bd.doubleValue();

    // get the value of last event
    double lastLatency = 0;
    PreparedStatement ps;
    ResultSet rs = null;
    int maxID = embDB.getMaxIDofApp(this.name);

    try {
        ps = conn.prepareStatement("SELECT ID, LATENCY " + "FROM MEERKAT.EVENTS " + "WHERE APPNAME LIKE '"
                + this.name + "' " + "AND ID = " + maxID);

        rs = ps.executeQuery();

        while (rs.next()) {
            lastLatency = rs.getDouble(2);
        }

        rs.close();
        ps.close();
        conn.commit();

    } catch (SQLException e) {
        log.error("Failed query average availability from application " + this.getName());
        log.error("", e);
    }

    BigDecimal bd1 = new BigDecimal(lastLatency);
    bd1 = bd1.setScale(2, BigDecimal.ROUND_DOWN);
    lastLatency = bd1.doubleValue();

    if (lastLatency > latencyAverage) {
        return 1;
    } else if (lastLatency < latencyAverage) {
        return -1;
    }

    return 0;
}

From source file:org.meerkat.services.WebApp.java

/**
 * getLoadTimeIndicator/*  w w w  . ja  v a2s  . co m*/
 * @return    1 if last load time higher than load time average
 *          -1 if last load time lower than load time average
 *          0 if they are equal
 *          (No decimal plates considered)
 */
public double getLoadTimeIndicator() {
    double doubleLoadTimeAverage = getAppLoadTimeAVG();
    BigDecimal bd = new BigDecimal(doubleLoadTimeAverage);
    bd = bd.setScale(0, BigDecimal.ROUND_DOWN);
    double loadTimeAverage = bd.doubleValue();

    // get the value of last event
    double lastLoadTime = 0;
    PreparedStatement ps;
    ResultSet rs = null;
    int maxID = embDB.getMaxIDofApp(this.name);

    try {
        ps = conn.prepareStatement("SELECT ID, LOADTIME " + "FROM MEERKAT.EVENTS " + "WHERE APPNAME LIKE '"
                + this.name + "' " + "AND ID = " + maxID);

        rs = ps.executeQuery();

        while (rs.next()) {
            lastLoadTime = rs.getDouble(2);
        }

        rs.close();
        ps.close();
        conn.commit();

    } catch (SQLException e) {
        log.error("Failed query average load time from application " + this.getName());
        log.error("", e);
    }

    BigDecimal bd1 = new BigDecimal(lastLoadTime);
    bd1 = bd1.setScale(3, BigDecimal.ROUND_DOWN);
    lastLoadTime = bd1.doubleValue();

    if (lastLoadTime > loadTimeAverage) {
        return 1;
    } else if (lastLoadTime < loadTimeAverage) {
        return -1;
    }

    return 0;
}

From source file:PVGraph.java

public java.util.List<YearsData> getYearsData() {
    Statement stmt = null;/*from w  w  w .  ja v  a2s  .c om*/
    String query = "select * from DayData where CurrentPower != 0 order by DateTime";
    Map<String, YearsData> result = new HashMap<String, YearsData>();
    GregorianCalendar gc = new GregorianCalendar();
    try {
        getDatabaseConnection();
        stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        while (rs.next()) {
            String serial = rs.getString("serial");
            YearsData yd = result.get(serial);
            if (yd == null) {
                yd = new YearsData();
                yd.serial = serial;
                yd.inverter = rs.getString("inverter");
                yd.startTotalPower = rs.getDouble("ETotalToday");
                result.put(serial, yd);
            }
            gc.setTime(rs.getTimestamp("DateTime"));
            int year = gc.get(Calendar.YEAR);
            double totalPower = rs.getDouble("ETotalToday");
            yd.powers.put(year, totalPower);
            yd.endTotalPower = totalPower;
        }
    } catch (SQLException e) {
        System.err.println("Query failed: " + e.getMessage());
    } finally {
        try {
            stmt.close();
        } catch (SQLException e) {
            // relax
        }
    }
    return new java.util.ArrayList<YearsData>(result.values());
}