Example usage for java.sql Timestamp valueOf

List of usage examples for java.sql Timestamp valueOf

Introduction

In this page you can find the example usage for java.sql Timestamp valueOf.

Prototype

@SuppressWarnings("deprecation")
public static Timestamp valueOf(LocalDateTime dateTime) 

Source Link

Document

Obtains an instance of Timestamp from a LocalDateTime object, with the same year, month, day of month, hours, minutes, seconds and nanos date-time value as the provided LocalDateTime .

Usage

From source file:com.lrazvan.server.connection.ApplicationServer.java

/**
 * This method handles any messages received from the client.
 *
 * @param msg    The message received from the client.
 * @param client The connection from which the message originated.
 *///from  w ww.  j av  a  2  s  . co  m
public void handleMessageFromClient(Object msg, ConnectionToClient client) {
    JSONObject jsonObject = new JSONObject((String) msg);
    String subject = jsonObject.getString("Subject");
    System.out.println("Message received: " + subject + " from " + client);

    JSONObject response;

    switch (subject) {
    case "GetAllPatients":
        List<PatientDTO> patientDTOList = api.findAllPatients();
        response = new JSONObject();
        response.put("Subject", "PatientList");
        response.put("Body", patientDTOList);
        try {
            client.sendToClient(response.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        break;
    case "GetPatientConsultations":
        PatientDTO patientDTO = Commons.jsonObjectToPatientDTO(jsonObject.getJSONObject("patientDTO"));
        List<ConsultationDTO> consultationDTOList = api.getPatientConsultations(patientDTO);
        response = new JSONObject();
        response.put("Subject", "PatientConsultationList");
        response.put("ConsultationList", consultationDTOList);
        try {
            client.sendToClient(response.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        break;
    case "GetScheduledConsultations":
        String doctorUsername = jsonObject.getString("doctorUsername");
        consultationDTOList = api.getScheduledConsultations(doctorUsername);
        response = new JSONObject();
        response.put("Subject", "PatientConsultationList");
        response.put("ConsultationList", consultationDTOList);
        try {
            client.sendToClient(response.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        break;
    case "GetDoctorPatients":
        doctorUsername = jsonObject.getString("doctorUsername");
        patientDTOList = api.getDoctorPatients(doctorUsername);
        response = new JSONObject();
        response.put("Subject", "DoctorPatientList");
        response.put("patientList", patientDTOList);
        try {
            client.sendToClient(response.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        break;
    case "GetAllSecretaries":
        List<SecretaryDTO> secretaryDTOList = api.getAllSecretaries();
        response = new JSONObject();
        response.put("Subject", "SecretaryList");
        response.put("SecretaryList", secretaryDTOList);
        try {
            client.sendToClient(response.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        break;
    case "GetAllDoctors":
        List<DoctorDTO> doctorDTOList = api.getAllDoctors();
        response = new JSONObject();
        response.put("Subject", "DoctorList");
        response.put("DoctorList", doctorDTOList);
        try {
            client.sendToClient(response.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        break;
    case "GetAvailableDoctors":
        Timestamp date = Timestamp.valueOf(jsonObject.getString("date"));
        doctorDTOList = api.getAvailableDoctors(date);
        response = new JSONObject();
        response.put("Subject", "AvailableDoctors");
        response.put("DoctorList", doctorDTOList);
        try {
            client.sendToClient(response.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        break;
    case "SaveConsultation":
        ConsultationDTO consultationDTO = Commons
                .jsonObjectToConsultationDTO(jsonObject.getJSONObject("consultationDTO"));
        api.saveConsultation(consultationDTO);
        break;
    case "SavePatient":
        patientDTO = Commons.jsonObjectToPatientDTO(jsonObject.getJSONObject("patientDTO"));
        api.savePatientDTO(patientDTO);
        break;
    case "SaveSecretary":
        SecretaryDTO secretaryDTO = Commons.jsonObjectToSecretaryDTO(jsonObject.getJSONObject("secretaryDTO"));
        api.saveSecretaryDTO(secretaryDTO);
        break;
    case "DeleteSecretary":
        secretaryDTO = Commons.jsonObjectToSecretaryDTO(jsonObject.getJSONObject("secretaryDTO"));
        api.deleteSecretaryDTO(secretaryDTO);
        break;
    case "DeleteConsultation":
        consultationDTO = Commons.jsonObjectToConsultationDTO(jsonObject.getJSONObject("consultationDTO"));
        api.deleteConsultation(consultationDTO);
        break;
    case "SaveDoctor":
        DoctorDTO doctorDTO = Commons.jsonObjectToDoctorDTO(jsonObject.getJSONObject("doctorDTO"));
        api.saveDoctorDTO(doctorDTO);
        break;
    case "DeleteDoctor":
        doctorDTO = Commons.jsonObjectToDoctorDTO(jsonObject.getJSONObject("doctorDTO"));
        api.deleteDoctorDTO(doctorDTO);
        break;
    case "Authenticate":
        String role = jsonObject.getString("role");
        String username = jsonObject.getString("username");
        String password = jsonObject.getString("password");
        Boolean authenticated = false;

        switch (role) {
        case Commons.SECRETARY_ROLE:
            authenticated = api.authenticateSecretary(username, password);
            break;
        case Commons.DOCTOR_ROLE:
            authenticated = api.authenticateDoctor(username, password);
            break;
        case Commons.ADMIN_ROLE:
            authenticated = api.authenticateAdmin(username, password);
            break;
        }

        response = new JSONObject();
        response.put("Subject", "Authenticate Result");
        response.put("result", authenticated.toString());
        response.put("username", username);
        response.put("role", role);
        try {
            client.sendToClient(response.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        break;
    default:
        System.out.println("Unknown command: " + subject);
    }

    //this.sendToAllClients(msg);
}

From source file:com.gs.obevo.db.impl.platforms.h2.H2DeployerTest.java

private void validateResults(Map<String, Object> map, Integer aId, Integer bId, String stringField,
        String timestampField, Integer cId) {

    assertEquals(aId, map.get("A_ID"));
    assertEquals(bId, map.get("B_ID"));
    assertEquals(stringField, map.get("STRING_FIELD"));
    Timestamp millis = timestampField == null ? null : Timestamp.valueOf(timestampField);
    assertEquals(millis, map.get("TIMESTAMP_FIELD"));
    assertEquals(cId, map.get("C_ID"));
}

From source file:pt.ist.fenixedu.contracts.tasks.giafsync.ImportPersonContractSituationsFromGiaf.java

@Override
public List<Modification> processChanges(GiafMetadata metadata, PrintWriter log, Logger logger)
        throws Exception {
    List<Modification> modifications = new ArrayList<>();
    PersistentSuportGiaf oracleConnection = PersistentSuportGiaf.getInstance();
    PreparedStatement preparedStatement = oracleConnection.prepareStatement(getQuery());
    ResultSet result = preparedStatement.executeQuery();
    int count = 0;
    int news = 0;
    int notImported = 0;
    int dontExist = 0;
    int deleted = 0;
    int totalInFenix = 0;
    int repeted = 0;
    Set<Person> importedButInvalid = new HashSet<Person>();
    while (result.next()) {
        count++;/*from  w  w w.  j  a v  a2s  . com*/
        String numberString = result.getString("emp_num");
        Person person = metadata.getPerson(numberString, logger);
        if (person == null) {
            logger.debug("Invalid person with number: " + numberString);
            dontExist++;
            continue;
        }
        PersonProfessionalData personProfessionalData = person.getPersonProfessionalData();
        if (personProfessionalData == null) {
            logger.debug("Empty personProfessionalData: " + numberString);
            dontExist++;
            continue;
        }
        final GiafProfessionalData giafProfessionalData = personProfessionalData
                .getGiafProfessionalDataByGiafPersonIdentification(numberString);
        if (giafProfessionalData == null) {
            logger.debug("Empty giafProfessionalData: " + numberString);
            dontExist++;
            continue;
        }

        final String contractSituationGiafId = result.getString("emp_sit");
        final ContractSituation contractSituation = metadata.situation(contractSituationGiafId);
        if (contractSituation == null) {
            logger.debug("Invalid situation: " + contractSituationGiafId);
            importedButInvalid.add(person);
        }

        final String categoryGiafId = result.getString("emp_cat_func");
        final ProfessionalCategory category = metadata.category(categoryGiafId);
        if (category == null && (!StringUtils.isEmpty(categoryGiafId))) {
            logger.debug("Empty category: " + categoryGiafId + ". Person number: " + numberString);
            importedButInvalid.add(person);
        }
        if (category == null && (contractSituation == null || contractSituation.getEndSituation() == false)) {
            logger.debug("Empty catefory on a non end situation: " + numberString + " . Situation: "
                    + contractSituationGiafId);
            importedButInvalid.add(person);
        }

        String beginDateString = result.getString("dt_inic");
        final LocalDate beginDate = StringUtils.isEmpty(beginDateString) ? null
                : new LocalDate(Timestamp.valueOf(beginDateString));
        if (beginDate == null) {
            logger.debug("Empty beginDate: " + numberString + " . Situation: " + contractSituationGiafId);
            importedButInvalid.add(person);
        }
        String endDateString = result.getString("dt_fim");
        final LocalDate endDate = StringUtils.isEmpty(endDateString) ? null
                : new LocalDate(Timestamp.valueOf(endDateString));
        if (endDate != null) {
            if (beginDate != null && beginDate.isAfter(endDate)) {
                logger.debug("BeginDate after EndDate: " + numberString + " begin: " + beginDate + " end:"
                        + endDate);
                importedButInvalid.add(person);
            }
        }
        String creationDateString = result.getString("data_criacao");
        if (StringUtils.isEmpty(creationDateString)) {
            logger.debug("Empty creationDate: " + numberString + " . Situation: " + contractSituationGiafId);
            notImported++;
            continue;
        }
        final DateTime creationDate = new DateTime(Timestamp.valueOf(creationDateString));

        String modifiedDateString = result.getString("data_alteracao");
        final DateTime modifiedDate = StringUtils.isEmpty(modifiedDateString) ? null
                : new DateTime(Timestamp.valueOf(modifiedDateString));

        final String step = result.getString("emp_escalao");

        if (!hasPersonContractSituation(giafProfessionalData, beginDate, endDate, creationDate, modifiedDate,
                step, contractSituation, contractSituationGiafId, category, categoryGiafId)) {
            modifications.add(new Modification() {
                @Override
                public void execute() {
                    new PersonContractSituation(giafProfessionalData, beginDate, endDate, step,
                            contractSituation, contractSituationGiafId, category, categoryGiafId, creationDate,
                            modifiedDate);
                }
            });
            news++;
        }

    }
    result.close();
    preparedStatement.close();

    for (GiafProfessionalData giafProfessionalData : Bennu.getInstance().getGiafProfessionalDataSet()) {
        for (final PersonContractSituation personContractSituation : giafProfessionalData
                .getPersonContractSituationsSet()) {
            if (personContractSituation.getAnulationDate() == null) {
                int countThisPersonContractSituationOnGiaf = countThisPersonContractSituationOnGiaf(
                        oracleConnection, personContractSituation, logger);
                if (countThisPersonContractSituationOnGiaf == 0) {
                    modifications.add(new Modification() {
                        @Override
                        public void execute() {
                            personContractSituation.setAnulationDate(new DateTime());
                        }
                    });
                    deleted++;
                } else {
                    totalInFenix++;
                    if (countThisPersonContractSituationOnGiaf > 1) {
                        repeted += countThisPersonContractSituationOnGiaf - 1;
                    }
                }
            }
        }
    }

    oracleConnection.closeConnection();
    log.println("-- Contract situations --");
    log.println("Total GIAF: " + count);
    log.println("New: " + news);
    log.println("Deleted: " + deleted);
    log.println("Not imported: " + notImported);
    log.println("Imported with errors: " + importedButInvalid.size());
    log.println("Repeted: " + repeted);
    log.println("Invalid persons: " + dontExist);
    log.println("Total Fnix: " + totalInFenix);
    log.println("Total Fnix without errors: " + (totalInFenix - importedButInvalid.size()));
    log.println("Missing in Fnix: " + (count - totalInFenix));

    return modifications;
}

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;// ww w.  j a  v  a  2s .  c o  m
    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:com.alibaba.wasp.jdbc.TestPreparedStatement.java

public void testDateTimeTimestampWithCalendar() throws SQLException {
    Statement stat = conn.createStatement();
    stat.execute("create table ts(x timestamp primary key)");
    stat.execute("create table t(x time primary key)");
    stat.execute("create table d(x date)");
    Calendar utcCalendar = new GregorianCalendar(new SimpleTimeZone(0, "Z"));
    TimeZone old = TimeZone.getDefault();
    DateTimeUtils.resetCalendar();/*from   w w w. j  a v  a2s.  c  o m*/
    TimeZone.setDefault(TimeZone.getTimeZone("PST"));
    try {
        Timestamp ts1 = Timestamp.valueOf("2010-03-13 18:15:00");
        Time t1 = new Time(ts1.getTime());
        Date d1 = new Date(ts1.getTime());
        // when converted to UTC, this is 03:15, which doesn't actually exist
        // because of summer time change at that day
        Timestamp ts2 = Timestamp.valueOf("2010-03-13 19:15:00");
        Time t2 = new Time(ts2.getTime());
        Date d2 = new Date(ts2.getTime());
        PreparedStatement prep;
        ResultSet rs;
        prep = conn.prepareStatement("insert into ts values(?)");
        prep.setTimestamp(1, ts1, utcCalendar);
        prep.execute();
        prep.setTimestamp(1, ts2, utcCalendar);
        prep.execute();
        prep = conn.prepareStatement("insert into t values(?)");
        prep.setTime(1, t1, utcCalendar);
        prep.execute();
        prep.setTime(1, t2, utcCalendar);
        prep.execute();
        prep = conn.prepareStatement("insert into d values(?)");
        prep.setDate(1, d1, utcCalendar);
        prep.execute();
        prep.setDate(1, d2, utcCalendar);
        prep.execute();
        rs = stat.executeQuery("select * from ts order by x");
        rs.next();
        assertEquals("2010-03-14 02:15:00.0", rs.getString(1));
        assertEquals("2010-03-13 18:15:00.0", rs.getTimestamp(1, utcCalendar).toString());
        assertEquals("2010-03-14 03:15:00.0", rs.getTimestamp(1).toString());
        assertEquals("2010-03-14 02:15:00.0", rs.getString("x"));
        assertEquals("2010-03-13 18:15:00.0", rs.getTimestamp("x", utcCalendar).toString());
        assertEquals("2010-03-14 03:15:00.0", rs.getTimestamp("x").toString());
        rs.next();
        assertEquals("2010-03-14 03:15:00.0", rs.getString(1));
        assertEquals("2010-03-13 19:15:00.0", rs.getTimestamp(1, utcCalendar).toString());
        assertEquals("2010-03-14 03:15:00.0", rs.getTimestamp(1).toString());
        assertEquals("2010-03-14 03:15:00.0", rs.getString("x"));
        assertEquals("2010-03-13 19:15:00.0", rs.getTimestamp("x", utcCalendar).toString());
        assertEquals("2010-03-14 03:15:00.0", rs.getTimestamp("x").toString());
        rs = stat.executeQuery("select * from t order by x");
        rs.next();
        assertEquals("02:15:00", rs.getString(1));
        assertEquals("18:15:00", rs.getTime(1, utcCalendar).toString());
        assertEquals("02:15:00", rs.getTime(1).toString());
        assertEquals("02:15:00", rs.getString("x"));
        assertEquals("18:15:00", rs.getTime("x", utcCalendar).toString());
        assertEquals("02:15:00", rs.getTime("x").toString());
        rs.next();
        assertEquals("03:15:00", rs.getString(1));
        assertEquals("19:15:00", rs.getTime(1, utcCalendar).toString());
        assertEquals("03:15:00", rs.getTime(1).toString());
        assertEquals("03:15:00", rs.getString("x"));
        assertEquals("19:15:00", rs.getTime("x", utcCalendar).toString());
        assertEquals("03:15:00", rs.getTime("x").toString());
        rs = stat.executeQuery("select * from d order by x");
        rs.next();
        assertEquals("2010-03-14", rs.getString(1));
        assertEquals("2010-03-13", rs.getDate(1, utcCalendar).toString());
        assertEquals("2010-03-14", rs.getDate(1).toString());
        assertEquals("2010-03-14", rs.getString("x"));
        assertEquals("2010-03-13", rs.getDate("x", utcCalendar).toString());
        assertEquals("2010-03-14", rs.getDate("x").toString());
        rs.next();
        assertEquals("2010-03-14", rs.getString(1));
        assertEquals("2010-03-13", rs.getDate(1, utcCalendar).toString());
        assertEquals("2010-03-14", rs.getDate(1).toString());
        assertEquals("2010-03-14", rs.getString("x"));
        assertEquals("2010-03-13", rs.getDate("x", utcCalendar).toString());
        assertEquals("2010-03-14", rs.getDate("x").toString());
    } finally {
        TimeZone.setDefault(old);
        DateTimeUtils.resetCalendar();
    }
    stat.execute("drop table ts");
    stat.execute("drop table t");
    stat.execute("drop table d");
}

From source file:NoSQLvsSQL.SqlDB.java

public Date getRandomDate() throws ParseException {
    long offset = Timestamp.valueOf("2000-01-01 00:00:00").getTime();
    long end = Timestamp.valueOf("2016-01-01 00:00:00").getTime();
    long diff = end - offset + 1;
    Timestamp rand = new Timestamp(offset + (long) (Math.random() * diff));

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd");
    return simpleDateFormat.parse(rand.toString());
}

From source file:org.intermine.api.tracker.xml.TemplateTrackBinding.java

/**
 * {@inheritDoc}/*from   w w w .jav a  2  s .  co m*/
 */
@Override
public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
    if (TemplateTrackBinding.TEMPLATETRACKS.equals(qName)) {
        try {
            connection = ((ObjectStoreWriterInterMineImpl) osw).getConnection();
            // Creating a template tracker will create an empty table if it doesn't exist
            TemplateTracker.getInstance(connection, new LinkedList<Track>());
            stm = connection.prepareStatement(
                    "INSERT INTO " + TrackerUtil.TEMPLATE_TRACKER_TABLE + " VALUES(?, ?, ?, ?)");
        } catch (SQLException sqle) {
            new BuildException("Problem to retrieve the connection", sqle);
        }
    }
    if (TemplateTrackBinding.TEMPLATETRACK.equals(qName)) {
        try {
            stm.setString(1, attrs.getValue("templatename"));
            stm.setString(2, attrs.getValue("username"));
            stm.setString(3, attrs.getValue("sessionidentifier"));
            stm.setTimestamp(4, Timestamp.valueOf(attrs.getValue("timestamp")));
            stm.executeUpdate();
        } catch (SQLException sqle) {
            throw new BuildException("problems during update", sqle);
        }
    }
}

From source file:com.hp.action.InterruptedTimeAction.java

public String discoverInterruption() throws ParseException {
    HttpServletRequest request = (HttpServletRequest) ActionContext.getContext()
            .get(ServletActionContext.HTTP_REQUEST);
    HttpSession session = request.getSession();

    user = (User) session.getAttribute("USER");

    //Authorize/*from  w  w  w .jav  a2s. co  m*/
    if (!userDAO.authorize((String) session.getAttribute("user_name"),
            (String) session.getAttribute("user_password"))) {
        return LOGIN;
    }

    pushInfo.setManagerID((String) session.getAttribute("giamdocId"));
    pushInfo.setStaffID((String) session.getAttribute("staffId"));
    pushInfo.setCustomerID((String) session.getAttribute("khachhangId"));

    userListGiamDoc = userDAO.getListUser(2);
    userListStaff = staffDAO.getListUser(pushInfo.getManagerID());

    List<List<RoadManagement>> lists = new ArrayList<List<RoadManagement>>();
    lists = roadManagementDAO.getRoad(pushInfo.getManagerID(), pushInfo.getStaffID(), "", startDate, endDate);

    System.out.println("lists: " + lists.size());

    if (lists != null && lists.size() > 0)
        for (int i = 0; i < lists.size(); i++) {
            List<RoadManagement> list = lists.get(i);
            for (int j = 0; j < list.size(); j++) {
                if (list.size() > (j + 1)) {
                    RoadManagement last = list.get(j);
                    RoadManagement updated = list.get(j + 1);

                    DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
                    DateFormat dfTimestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    if (j == 0) {

                        try {
                            Date startDate = df.parse(df.format(last.getThoiGian()));
                            long rangeStart = last.getThoiGian().getTime() - startDate.getTime();
                            if (rangeStart > INTERRUPTED_TIME) {
                                //getAddress(last);
                                interruptedTimeList.add(new InterruptedTime(
                                        new RoadManagement(last.getMaNhanVien(), last.getTenNhanVien(),
                                                Timestamp.valueOf(dfTimestamp.format(startDate))),
                                        last, rangeStart / (1000 * 60), "", ""));
                            }
                        } catch (ParseException ex) {
                            Logger.getLogger(InterruptedTimeAction.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }

                    long range = updated.getThoiGian().getTime() - last.getThoiGian().getTime();
                    //System.out.println("range " + range);
                    if (range > INTERRUPTED_TIME) {
                        //getAddress(last);
                        interruptedTimeList
                                .add(new InterruptedTime(last, updated, range / (1000 * 60), "", ""));
                    }

                    if (j == (list.size() - 2)) {
                        try {
                            Date endDate = df.parse(df.format(updated.getThoiGian()));
                            Calendar c = Calendar.getInstance();
                            c.setTime(endDate);

                            c.add(Calendar.DAY_OF_MONTH, 1);
                            c.add(Calendar.SECOND, -1);

                            endDate = c.getTime();

                            long rangeEnd = endDate.getTime() - updated.getThoiGian().getTime();
                            //System.out.println("range " + range);
                            if (rangeEnd > INTERRUPTED_TIME) {
                                //getAddress(last);
                                interruptedTimeList.add(new InterruptedTime(updated,
                                        new RoadManagement(updated.getMaNhanVien(), updated.getTenNhanVien(),
                                                Timestamp.valueOf(dfTimestamp.format(endDate))),
                                        rangeEnd / (1000 * 60), "", ""));
                            }
                        } catch (ParseException ex) {
                            Logger.getLogger(InterruptedTimeAction.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
            }
        }

    System.out.println("interruptedTimeList: " + interruptedTimeList.size());

    session.setAttribute("interruptedTimeList", interruptedTimeList);
    session.setAttribute("startDate", startDate);
    session.setAttribute("endDate", endDate);

    return SUCCESS;
}

From source file:org.freebxml.omar.server.persistence.rdb.AuditableEventDAO.java

protected void loadObject(Object obj, ResultSet rs) throws RegistryException {
    try {//from w  w w .j av  a  2  s.  c  o  m
        if (!(obj instanceof AuditableEvent)) {
            throw new RegistryException(ServerResourceBundle.getInstance()
                    .getString("message.AuditableEventExpected", new Object[] { obj }));
        }

        AuditableEvent ae = (AuditableEvent) obj;
        super.loadObject(obj, rs);

        //TODO: Fix so requestId is properly supported
        String requestId = rs.getString("requestId");
        if (requestId == null) {
            requestId = "Unknown";
        }
        ae.setRequestId(requestId);

        String eventType = rs.getString("eventType");
        ae.setEventType(eventType);

        //Workaround for bug in PostgreSQL 7.2.2 JDBC driver
        //java.sql.Timestamp timeStamp = rs.getTimestamp("timeStamp_"); --old
        String timestampStr = rs.getString("timeStamp_").substring(0, 19);
        Timestamp timeStamp = Timestamp.valueOf(timestampStr);
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(timeStamp.getTime());
        ae.setTimestamp(cal);

        String userId = rs.getString("user_");
        ObjectRef ref = bu.rimFac.createObjectRef();
        ref.setId(userId);
        context.getObjectRefs().add(ref);
        ae.setUser(userId);

        AffectedObjectDAO affectedDAO = new AffectedObjectDAO(context);
        affectedDAO.setParent(ae);
        List affectedObjects = affectedDAO.getByParent();
        ObjectRefListType orefList = BindingUtility.getInstance().rimFac.createObjectRefListType();
        orefList.getObjectRef().addAll(affectedObjects);
        ae.setAffectedObjects(orefList);

    } catch (SQLException e) {
        log.error(ServerResourceBundle.getInstance().getString("message.CaughtException1"), e);
        throw new RegistryException(e);
    } catch (JAXBException e) {
        log.error(ServerResourceBundle.getInstance().getString("message.CaughtException1"), e);
        throw new RegistryException(e);
    }
}

From source file:org.flockdata.transform.ExpressionHelper.java

public static Long parseDate(ColumnDefinition colDef, String value) {
    if (value == null || value.equals(""))
        return null;
    if (colDef.isDateEpoc()) {
        return Long.parseLong(value) * 1000;
    }//from w ww  .j  a  va  2s  .  com

    if (colDef.getDateFormat() == null || colDef.getDateFormat().equalsIgnoreCase("automatic")) {
        try {
            return Date.parse(value);
        } catch (IllegalArgumentException e) {
            // Try other formats
        }
    }
    if (colDef.getDateFormat() != null && colDef.getDateFormat().equalsIgnoreCase("timestamp")) {
        try {
            return Timestamp.valueOf(value).getTime();
        } catch (IllegalArgumentException e) {
            // attempt other conversions
        }
    }

    if (NumberUtils.isDigits(value)) // plain old java millis
        return Long.parseLong(value);

    // Custom Date formats
    String tz = colDef.getTimeZone();
    if (tz == null)
        tz = TimeZone.getDefault().getID();

    try {

        // Try first as DateTime
        return new SimpleDateFormat(colDef.getDateFormat()).parse(value).getTime();
    } catch (DateTimeParseException | IllegalArgumentException | ParseException e) {
        // Just a plain date
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern(colDef.getDateFormat(), Locale.ENGLISH);
        LocalDate date = LocalDate.parse(value, pattern);
        return new DateTime(date.toString(), DateTimeZone.forID(tz)).getMillis();
    }
}