Example usage for java.sql Date valueOf

List of usage examples for java.sql Date valueOf

Introduction

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

Prototype

@SuppressWarnings("deprecation")
public static Date valueOf(LocalDate date) 

Source Link

Document

Obtains an instance of Date from a LocalDate object with the same year, month and day of month value as the given LocalDate .

Usage

From source file:Main.java

public static void main(String[] args) {
    System.out.println(convertToEntityAttribute(Date.valueOf("2000-01-12")));
}

From source file:Main.java

public static void main(String[] args) {
    Date date = Date.valueOf("2015-12-25");
    System.out.println(date);/*  w  w  w  .  j  a v a 2s  . com*/

    Calendar cal = new GregorianCalendar();
    cal.setTime(date);
    System.out.println(cal.getTime());
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    Date date = new Date(0);
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctutorial", "root", "root");

    PreparedStatement prest = con.prepareStatement("INSERT Records VALUES(?,?,?)");
    prest.setInt(1, 1);//  w w w .  j  a v a2 s  .  c  o m
    prest.setString(2, "R");
    prest.setDate(3, date.valueOf("1998-1-17"));
    int row = prest.executeUpdate();
}

From source file:CalcoloRitardiLotti.java

public static void main(String[] args) {
    String id_ref = "cbededce-269f-48d2-8c25-2359bf246f42";
    String requestString = "http://dati.openexpo2015.it/catalog/api/action/datastore_search?resource_id="
            + id_ref;//from   www. ja  v a  2 s  .c o  m
    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet(requestString);
    try {

        HttpResponse response = client.execute(request);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String result = "";
        String resline = "";
        Calendar c = Calendar.getInstance();
        Date current = Date.valueOf(
                c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.DAY_OF_MONTH));
        while ((resline = rd.readLine()) != null)
            result += resline;

        //System.out.println(jsonObject.toString());
        if (result != null) {
            JSONObject jsonObject = new JSONObject(result);
            JSONObject resultJson = (JSONObject) jsonObject.get("result");
            JSONArray records = (JSONArray) resultJson.get("records");
            Date temp1, temp2;
            //System.out.printf(records.toString());
            long diffInizioFineLavori;
            long ritardo;
            long den = (24 * 60 * 60 * 1000);
            JSONObject temp;

            DefaultCategoryDataset cdata = new DefaultCategoryDataset();
            String partialQuery;
            DefaultPieDataset data = new DefaultPieDataset();

            String totalQuery = "";
            int countSospesi = 0;
            int countConclusi = 0;
            int countVerifica = 0;
            int countInCorso = 0;
            int countCollaudo = 0;
            String stato;
            for (int i = 0; i < records.length(); i++) {
                temp = (JSONObject) records.get(i);
                temp1 = Date.valueOf((temp.getString("Data Consegna Lavori")).substring(0, 10));
                temp2 = Date.valueOf((temp.getString("Data Fine lavori")).substring(0, 10));
                diffInizioFineLavori = (long) (temp2.getTime() - temp1.getTime()) / den;
                stato = temp.getString("STATO");
                if (stato.equals("Concluso"))
                    countConclusi++;
                else if (stato.equals("In corso"))
                    countInCorso++;
                else if (stato.contains("Verifiche"))
                    countVerifica++;
                else if (stato.contains("Collaudo sospeso") || stato.contains("sospeso"))
                    countSospesi++;
                else
                    countCollaudo++;

                if (!temp.getString("STATO").equals("Concluso") && temp2.getTime() < current.getTime())
                    ritardo = (long) (current.getTime() - temp2.getTime()) / den;
                else
                    ritardo = 0;

                cdata.setValue(ritardo, String.valueOf(i + 1), String.valueOf(i + 1));
                System.out.println(
                        "Opera: " + temp.getString("Oggetto del lotto") + " | id: " + temp.getInt("_id"));
                System.out.println("Data consegna lavoro: " + temp.getString("Data Consegna Lavori")
                        + " | Data fine lavoro: " + temp.getString("Data Fine lavori"));
                System.out.println("STATO: " + temp.getString("STATO"));
                System.out.println("Differenza in giorni: " + diffInizioFineLavori
                        + " | Numero giorni contrattuali: " + temp.getString("numero di giorni contrattuali"));
                System.out.println("Ritardo accumulato: " + ritardo);

                System.out.println("----------------------------------");

                partialQuery = "\nid: " + temp.getInt("_id") + "\nOpera:" + temp.getString("Oggetto del lotto")
                        + "\n" + "Data consegna lavoro: " + temp.getString("Data Consegna Lavori")
                        + "Data fine lavoro: " + temp.getString("Data Fine lavori") + "\n" + "STATO: "
                        + temp.getString("STATO") + "\n" + "Differenza in giorni: " + diffInizioFineLavori
                        + " - Numero giorni contrattuali: " + temp.getString("numero di giorni contrattuali")
                        + "\n" + "Ritardo accumulato: " + ritardo + "\n"
                        + "----------------------------------\n";
                totalQuery = totalQuery + partialQuery;

            }

            JFreeChart chart1 = ChartFactory.createBarChart3D("RITARDI AL " + current, "Id lotto",
                    "ritardo(in giorni)", cdata);
            ChartRenderingInfo info = null;
            ChartUtilities.saveChartAsPNG(
                    new File(System.getProperty("user.dir") + "/istogramma" + current + ".png"), chart1, 1500,
                    1500, info, true, 10);
            FileUtils.writeStringToFile(new File(current + "_1.txt"), totalQuery);

            data.setValue("Conclusi: " + countConclusi, countConclusi);
            data.setValue("Sospeso: " + countSospesi, countSospesi);
            data.setValue("In Corso: " + countInCorso, countInCorso);
            data.setValue("Verifica: " + countVerifica, countVerifica);
            data.setValue("Collaudo: " + countCollaudo, countCollaudo);
            JFreeChart chart2 = ChartFactory.createPieChart3D("Statistiche del " + current, data, true, true,
                    true);
            ChartUtilities.saveChartAsPNG(new File(System.getProperty("user.dir") + "/pie" + current + ".png"),
                    chart2, 800, 450);

        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.khartec.waltz.jobs.sample.ServerGenerator.java

public static void main(String[] args) {

    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(DIConfiguration.class);
    ServerInformationDao serverDao = ctx.getBean(ServerInformationDao.class);
    DSLContext dsl = ctx.getBean(DSLContext.class);

    dsl.delete(SERVER_INFORMATION).where(SERVER_INFORMATION.PROVENANCE.eq("RANDOM_GENERATOR")).execute();

    List<ServerInformation> servers = ListUtilities.newArrayList();

    IntStream/*from   w w  w . j a  v a2  s  .  c  o m*/
            .range(0,
                    10_000)
            .forEach(
                    i -> servers
                            .add(ImmutableServerInformation.builder().hostname(mkHostName(i))
                                    .environment(randomPick(SampleData.environments))
                                    .location(randomPick(SampleData.locations))
                                    .operatingSystem(randomPick(SampleData.operatingSystems))
                                    .operatingSystemVersion(randomPick(SampleData.operatingSystemVersions))
                                    .country(
                                            "UK")
                                    .assetCode(
                                            "wltz-0" + rnd.nextInt(4000))
                                    .hardwareEndOfLifeDate(rnd.nextInt(10) > 5
                                            ? Date.valueOf(
                                                    LocalDate.now().plusMonths(rnd.nextInt(12 * 6) - (12 * 3)))
                                            : null)
                                    .operatingSystemEndOfLifeDate(rnd.nextInt(10) > 5
                                            ? Date.valueOf(
                                                    LocalDate.now().plusMonths(rnd.nextInt(12 * 6) - (12 * 3)))
                                            : null)
                                    .virtual(rnd.nextInt(10) > 7).provenance("RANDOM_GENERATOR").build()));

    // servers.forEach(System.out::println);
    serverDao.bulkSave(servers);

}

From source file:com.l2jfree.loginserver.tools.L2AccountManager.java

/**
 * Launches the interactive account manager.
 * /*from   w w  w  .  j a v  a  2  s .c o  m*/
 * @param args ignored
 */
public static void main(String[] args) {
    // LOW rework this crap
    Util.printSection("Account Management");

    _log.info("Please choose:");
    //_log.info("list - list registered accounts");
    _log.info("reg - register a new account");
    _log.info("rem - remove a registered account");
    _log.info("prom - promote a registered account");
    _log.info("dem - demote a registered account");
    _log.info("ban - ban a registered account");
    _log.info("unban - unban a registered account");
    _log.info("quit - exit this application");

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    L2AccountManager acm = new L2AccountManager();

    String line;
    try {
        while ((line = br.readLine()) != null) {
            line = line.trim();
            Connection con = null;
            switch (acm.getState()) {
            case USER_NAME:
                line = line.toLowerCase();
                try {
                    con = L2Database.getConnection();
                    PreparedStatement ps = con
                            .prepareStatement("SELECT superuser FROM account WHERE username LIKE ?");
                    ps.setString(1, line);
                    ResultSet rs = ps.executeQuery();
                    if (!rs.next()) {
                        acm.setUser(line);

                        _log.info("Desired password:");
                        acm.setState(ManagerState.PASSWORD);
                    } else {
                        _log.info("User name already in use.");
                        acm.setState(ManagerState.INITIAL_CHOICE);
                    }
                    rs.close();
                    ps.close();
                } catch (SQLException e) {
                    _log.error("Could not access database!", e);
                    acm.setState(ManagerState.INITIAL_CHOICE);
                } finally {
                    L2Database.close(con);
                }
                break;
            case PASSWORD:
                try {
                    MessageDigest sha = MessageDigest.getInstance("SHA");
                    byte[] pass = sha.digest(line.getBytes("US-ASCII"));
                    acm.setPass(HexUtil.bytesToHexString(pass));
                } catch (NoSuchAlgorithmException e) {
                    _log.fatal("SHA1 is not available!", e);
                    Shutdown.exit(TerminationStatus.ENVIRONMENT_MISSING_COMPONENT_OR_SERVICE);
                } catch (UnsupportedEncodingException e) {
                    _log.fatal("ASCII is not available!", e);
                    Shutdown.exit(TerminationStatus.ENVIRONMENT_MISSING_COMPONENT_OR_SERVICE);
                }
                _log.info("Super user: [y/n]");
                acm.setState(ManagerState.SUPERUSER);
                break;
            case SUPERUSER:
                try {
                    if (line.length() != 1)
                        throw new IllegalArgumentException("One char required.");
                    else if (line.charAt(0) == 'y')
                        acm.setSuper(true);
                    else if (line.charAt(0) == 'n')
                        acm.setSuper(false);
                    else
                        throw new IllegalArgumentException("Invalid choice.");

                    _log.info("Date of birth: [yyyy-mm-dd]");
                    acm.setState(ManagerState.DOB);
                } catch (IllegalArgumentException e) {
                    _log.info("[y/n]?");
                }
                break;
            case DOB:
                try {
                    Date d = Date.valueOf(line);
                    if (d.after(new Date(System.currentTimeMillis())))
                        throw new IllegalArgumentException("Future date specified.");
                    acm.setDob(d);

                    _log.info("Ban reason ID or nothing:");
                    acm.setState(ManagerState.SUSPENDED);
                } catch (IllegalArgumentException e) {
                    _log.info("[yyyy-mm-dd] in the past:");
                }
                break;
            case SUSPENDED:
                try {
                    if (line.length() > 0) {
                        int id = Integer.parseInt(line);
                        acm.setBan(L2BanReason.getById(id));
                    } else
                        acm.setBan(null);

                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con.prepareStatement(
                                "INSERT INTO account (username, password, superuser, birthDate, banReason) VALUES (?, ?, ?, ?, ?)");
                        ps.setString(1, acm.getUser());
                        ps.setString(2, acm.getPass());
                        ps.setBoolean(3, acm.isSuper());
                        ps.setDate(4, acm.getDob());
                        L2BanReason lbr = acm.getBan();
                        if (lbr == null)
                            ps.setNull(5, Types.INTEGER);
                        else
                            ps.setInt(5, lbr.getId());
                        ps.executeUpdate();
                        _log.info("Account " + acm.getUser() + " has been registered.");
                        ps.close();
                    } catch (SQLException e) {
                        _log.error("Could not register an account!", e);
                    } finally {
                        L2Database.close(con);
                    }
                    acm.setState(ManagerState.INITIAL_CHOICE);
                } catch (NumberFormatException e) {
                    _log.info("Ban reason ID or nothing:");
                }
                break;
            case REMOVE:
                acm.setUser(line.toLowerCase());
                try {
                    con = L2Database.getConnection();
                    PreparedStatement ps = con.prepareStatement("DELETE FROM account WHERE username LIKE ?");
                    ps.setString(1, acm.getUser());
                    int cnt = ps.executeUpdate();
                    if (cnt > 0)
                        _log.info("Account " + acm.getUser() + " has been removed.");
                    else
                        _log.info("Account " + acm.getUser() + " does not exist!");
                    ps.close();
                } catch (SQLException e) {
                    _log.error("Could not remove an account!", e);
                } finally {
                    L2Database.close(con);
                }
                acm.setState(ManagerState.INITIAL_CHOICE);
                break;
            case PROMOTE:
                acm.setUser(line.toLowerCase());
                try {
                    con = L2Database.getConnection();
                    PreparedStatement ps = con
                            .prepareStatement("UPDATE account SET superuser = ? WHERE username LIKE ?");
                    ps.setBoolean(1, true);
                    ps.setString(2, acm.getUser());
                    int cnt = ps.executeUpdate();
                    if (cnt > 0)
                        _log.info("Account " + acm.getUser() + " has been promoted.");
                    else
                        _log.info("Account " + acm.getUser() + " does not exist!");
                    ps.close();
                } catch (SQLException e) {
                    _log.error("Could not promote an account!", e);
                } finally {
                    L2Database.close(con);
                }
                acm.setState(ManagerState.INITIAL_CHOICE);
                break;
            case DEMOTE:
                acm.setUser(line.toLowerCase());
                try {
                    con = L2Database.getConnection();
                    PreparedStatement ps = con
                            .prepareStatement("UPDATE account SET superuser = ? WHERE username LIKE ?");
                    ps.setBoolean(1, false);
                    ps.setString(2, acm.getUser());
                    int cnt = ps.executeUpdate();
                    if (cnt > 0)
                        _log.info("Account " + acm.getUser() + " has been demoted.");
                    else
                        _log.info("Account " + acm.getUser() + " does not exist!");
                    ps.close();
                } catch (SQLException e) {
                    _log.error("Could not demote an account!", e);
                } finally {
                    L2Database.close(con);
                }
                acm.setState(ManagerState.INITIAL_CHOICE);
                break;
            case UNBAN:
                acm.setUser(line.toLowerCase());
                try {
                    con = L2Database.getConnection();
                    PreparedStatement ps = con
                            .prepareStatement("UPDATE account SET banReason = ? WHERE username LIKE ?");
                    ps.setNull(1, Types.INTEGER);
                    ps.setString(2, acm.getUser());
                    int cnt = ps.executeUpdate();
                    if (cnt > 0)
                        _log.info("Account " + acm.getUser() + " has been unbanned.");
                    else
                        _log.info("Account " + acm.getUser() + " does not exist!");
                    ps.close();
                } catch (SQLException e) {
                    _log.error("Could not demote an account!", e);
                } finally {
                    L2Database.close(con);
                }
                acm.setState(ManagerState.INITIAL_CHOICE);
                break;
            case BAN:
                line = line.toLowerCase();
                try {
                    con = L2Database.getConnection();
                    PreparedStatement ps = con
                            .prepareStatement("SELECT superuser FROM account WHERE username LIKE ?");
                    ps.setString(1, line);
                    ResultSet rs = ps.executeQuery();
                    if (rs.next()) {
                        acm.setUser(line);

                        _log.info("Ban reason ID:");
                        acm.setState(ManagerState.REASON);
                    } else {
                        _log.info("Account does not exist.");
                        acm.setState(ManagerState.INITIAL_CHOICE);
                    }
                    rs.close();
                    ps.close();
                } catch (SQLException e) {
                    _log.error("Could not access database!", e);
                    acm.setState(ManagerState.INITIAL_CHOICE);
                } finally {
                    L2Database.close(con);
                }
                break;
            case REASON:
                try {
                    int ban = Integer.parseInt(line);
                    con = L2Database.getConnection();
                    PreparedStatement ps = con
                            .prepareStatement("UPDATE account SET banReason = ? WHERE username LIKE ?");
                    ps.setInt(1, ban);
                    ps.setString(2, acm.getUser());
                    ps.executeUpdate();
                    _log.info("Account " + acm.getUser() + " has been banned.");
                    ps.close();
                } catch (NumberFormatException e) {
                    _log.info("Ban reason ID:");
                } catch (SQLException e) {
                    _log.error("Could not ban an account!", e);
                } finally {
                    L2Database.close(con);
                }
                acm.setState(ManagerState.INITIAL_CHOICE);
                break;
            default:
                line = line.toLowerCase();
                if (line.equals("reg")) {
                    _log.info("Desired user name:");
                    acm.setState(ManagerState.USER_NAME);
                } else if (line.equals("rem")) {
                    _log.info("User name:");
                    acm.setState(ManagerState.REMOVE);
                } else if (line.equals("prom")) {
                    _log.info("User name:");
                    acm.setState(ManagerState.PROMOTE);
                } else if (line.equals("dem")) {
                    _log.info("User name:");
                    acm.setState(ManagerState.DEMOTE);
                } else if (line.equals("unban")) {
                    _log.info("User name:");
                    acm.setState(ManagerState.UNBAN);
                } else if (line.equals("ban")) {
                    _log.info("User name:");
                    acm.setState(ManagerState.BAN);
                } else if (line.equals("quit"))
                    Shutdown.exit(TerminationStatus.MANUAL_SHUTDOWN);
                else
                    _log.info("Incorrect command.");
                break;
            }
        }
    } catch (IOException e) {
        _log.fatal("Could not process input!", e);
    } finally {
        IOUtils.closeQuietly(br);
    }
}

From source file:Main.java

public static Date convertToDatabaseColumn(LocalDate localDate) {
    return Date.valueOf(localDate);
}

From source file:Controller.PresensiController.java

@RequestMapping(value = "PresensiToday.htm")
public String getPresensiToday(ModelMap modelMap) {
    PresensiImplement pi = new PresensiImplement();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Calendar cal = Calendar.getInstance();
    Date tgl = Date.valueOf(sdf.format(cal.getTime()));
    List<Presensi> lp = pi.getByTgl(tgl);
    modelMap.put("listPresensiToday", lp);
    return "Presensi";
}

From source file:org.apache.hive.storage.jdbc.spitter.DateIntervalSplitter.java

@Override
public List<MutablePair<String, String>> getIntervals(String lowerBound, String upperBound, int numPartitions,
        TypeInfo typeInfo) {//  w  ww.  j a v  a2  s .  c  o  m
    List<MutablePair<String, String>> intervals = new ArrayList<>();
    Date dateLower = Date.valueOf(lowerBound);
    Date dateUpper = Date.valueOf(upperBound);
    double dateInterval = (dateUpper.getTime() - dateLower.getTime()) / (double) numPartitions;
    Date splitDateLower, splitDateUpper;
    for (int i = 0; i < numPartitions; i++) {
        splitDateLower = new Date(Math.round(dateLower.getTime() + dateInterval * i));
        splitDateUpper = new Date(Math.round(dateLower.getTime() + dateInterval * (i + 1)));
        if (splitDateLower.compareTo(splitDateUpper) < 0) {
            intervals
                    .add(new MutablePair<String, String>(splitDateLower.toString(), splitDateUpper.toString()));
        }
    }
    return intervals;
}

From source file:svc.data.citations.datasources.mock.MockCitationDataSource.java

@Override
public List<Citation> getByCitationNumberAndDOB(String citationNumber, LocalDate dob) {
    try {/*from w  w w.  ja v  a2 s.  co m*/
        Map<String, Object> parameterMap = new HashMap<String, Object>();
        parameterMap.put("citationNumber", citationNumber);
        parameterMap.put("dob", Date.valueOf(dob));
        String sql = "SELECT * FROM citations WHERE citation_number = :citationNumber AND date_of_birth = :dob";
        List<Citation> citations = jdbcTemplate.query(sql, parameterMap, new CitationSQLMapper());

        return populateViolations(citations);
    } catch (Exception e) {
        LogSystem.LogDBException(e);
        return null;
    }
}