List of usage examples for java.sql Date Date
public Date(long date)
From source file:Main.java
public static void main(String[] argv) throws Exception { Date timeToRun = new Date(System.currentTimeMillis() + numberOfMillisecondsInTheFuture); Timer timer = new Timer(); timer.schedule(new TimerTask() { public void run() { System.out.println("doing"); }//from w w w. j a va 2 s . c o m }, timeToRun); }
From source file:Main.java
public static void main(String[] args) { Date oneDate = new Date(new java.util.Date().getTime()); System.out.println(df.format(oneDate)); }
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);//from w w w . j ava2 s. com prest.setString(2, "R"); prest.setDate(3, date.valueOf("1998-1-17")); int row = prest.executeUpdate(); }
From source file:MainClass.java
public static void main(String[] args) throws ParseException { Calendar currenttime = Calendar.getInstance(); Date sqldate = new Date((currenttime.getTime()).getTime()); }
From source file:com.home.ln_spring.ch8.sample.AnnotationJdbcDaoSample.java
public static void main(String[] args) { GenericXmlApplicationContext context = new GenericXmlApplicationContext(); context.load("classpath:ch8/app-context-annotation.xml"); context.refresh();/*w ww. j a v a2s.c om*/ ContactDao contactDao = context.getBean("contactDao", ContactDao.class); List<Contact> contacts = contactDao.findAll(); listContacts(contacts); System.out.println("Find by first name: "); contacts = contactDao.findByFirstName("Clarence"); listContacts(contacts); // System.out.println("Update contact with id : "); // Contact contact = new Contact(); // contact.setId(2); // contact.setFirstName("Jack"); // contact.setLastName("Rodwell"); // contact.setBirthDate( // new Date((new GregorianCalendar(1987, 1, 8)).getTime().getTime())); // contactDao.update(contact); // // contacts = contactDao.findAll(); // listContacts(contacts); // System.out.println("Insert contact"); // System.out.println(); // Contact contact1 = new Contact(); // contact1.setFirstName("Rod"); // contact1.setLastName("Johnson"); // contact1.setBirthDate( // new Date((new GregorianCalendar(1987, 1, 8)).getTime().getTime())); // contactDao.insert(contact1); // // contacts = contactDao.findAll(); // listContacts(contacts); System.out.println("Insert with BatchSqlUpdate"); System.out.println(); Contact contact2 = new Contact(); contact2.setFirstName("Michael"); contact2.setLastName("Jackson"); contact2.setBirthDate(new Date((new GregorianCalendar(1964, 10, 1)).getTime().getTime())); List<ContactTelDetail> contactTelDetails = new ArrayList<ContactTelDetail>(); ContactTelDetail contactTelDetail = new ContactTelDetail(); contactTelDetail.setTelType("Home"); contactTelDetail.setTelNumber("111111"); contactTelDetails.add(contactTelDetail); contactTelDetail = new ContactTelDetail(); contactTelDetail.setTelType("Mobile"); contactTelDetail.setTelNumber("222222"); contactTelDetails.add(contactTelDetail); contact2.setContactTelDetails(contactTelDetails); contactDao.insertWithDetail(contact2); contacts = contactDao.findAllWithDetail(); listContacts(contacts); }
From source file:com.job.portal.utils.AbstractDAO.java
public static void main(String[] args) { java.util.Date date = new java.util.Date(); System.out.println(date);//from w w w . j a v a 2 s. com Date d = new Date(date.getTime()); System.out.println(d); }
From source file:org.apache.carbondata.examples.sdk.CarbonReaderExample.java
public static void main(String[] args) { String path = "./testWriteFiles"; try {// www .java 2 s . c om FileUtils.deleteDirectory(new File(path)); CarbonProperties.getInstance() .addProperty(CarbonCommonConstants.CARBON_TIMESTAMP_FORMAT, CarbonCommonConstants.CARBON_TIMESTAMP_DEFAULT_FORMAT) .addProperty(CarbonCommonConstants.CARBON_DATE_FORMAT, CarbonCommonConstants.CARBON_DATE_DEFAULT_FORMAT); Field[] fields = new Field[11]; fields[0] = new Field("stringField", DataTypes.STRING); fields[1] = new Field("shortField", DataTypes.SHORT); fields[2] = new Field("intField", DataTypes.INT); fields[3] = new Field("longField", DataTypes.LONG); fields[4] = new Field("doubleField", DataTypes.DOUBLE); fields[5] = new Field("boolField", DataTypes.BOOLEAN); fields[6] = new Field("dateField", DataTypes.DATE); fields[7] = new Field("timeField", DataTypes.TIMESTAMP); fields[8] = new Field("decimalField", DataTypes.createDecimalType(8, 2)); fields[9] = new Field("varcharField", DataTypes.VARCHAR); fields[10] = new Field("arrayField", DataTypes.createArrayType(DataTypes.STRING)); CarbonWriter writer = CarbonWriter.builder().outputPath(path) .withLoadOption("complex_delimiter_level_1", "#").withCsvInput(new Schema(fields)) .writtenBy("CarbonReaderExample").build(); for (int i = 0; i < 10; i++) { String[] row2 = new String[] { "robot" + (i % 10), String.valueOf(i % 10000), String.valueOf(i), String.valueOf(Long.MAX_VALUE - i), String.valueOf((double) i / 2), String.valueOf(true), "2019-03-02", "2019-02-12 03:03:34", "12.345", "varchar", "Hello#World#From#Carbon" }; writer.write(row2); } writer.close(); File[] dataFiles = new File(path).listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { if (name == null) { return false; } return name.endsWith("carbonindex"); } }); if (dataFiles == null || dataFiles.length < 1) { throw new RuntimeException("Carbon index file not exists."); } Schema schema = CarbonSchemaReader.readSchema(dataFiles[0].getAbsolutePath()).asOriginOrder(); // Transform the schema String[] strings = new String[schema.getFields().length]; for (int i = 0; i < schema.getFields().length; i++) { strings[i] = (schema.getFields())[i].getFieldName(); } // Read data CarbonReader reader = CarbonReader.builder(path, "_temp").projection(strings).build(); System.out.println("\nData:"); long day = 24L * 3600 * 1000; int i = 0; while (reader.hasNext()) { Object[] row = (Object[]) reader.readNextRow(); System.out.println(String.format("%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t", i, row[0], row[1], row[2], row[3], row[4], row[5], new Date((day * ((int) row[6]))), new Timestamp((long) row[7] / 1000), row[8], row[9])); Object[] arr = (Object[]) row[10]; for (int j = 0; j < arr.length; j++) { System.out.print(arr[j] + " "); } assert (arr[0].equals("Hello")); assert (arr[3].equals("Carbon")); System.out.println(); i++; } reader.close(); // Read data CarbonReader reader2 = CarbonReader.builder(path, "_temp").build(); System.out.println("\nData:"); i = 0; while (reader2.hasNext()) { Object[] row = (Object[]) reader2.readNextRow(); System.out.print(String.format("%s\t%s\t%s\t%s\t%s\t", i, row[0], new Date((day * ((int) row[1]))), new Timestamp((long) row[2] / 1000), row[3])); Object[] arr = (Object[]) row[4]; for (int j = 0; j < arr.length; j++) { System.out.print(arr[j] + " "); } System.out.println(String.format("\t%s\t%s\t%s\t%s\t%s\t%s\t", row[5], row[6], row[7], row[8], row[9], row[10])); i++; } reader2.close(); } catch (Throwable e) { e.printStackTrace(); assert (false); System.out.println(e.getMessage()); } finally { try { FileUtils.deleteDirectory(new File(path)); } catch (IOException e) { e.printStackTrace(); } } }
From source file:com.l2jfree.loginserver.tools.L2AccountManager.java
/** * Launches the interactive account manager. * /*w w w .j a va2 s . co 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:examples.KafkaStreamsDemo.java
public static void main(String[] args) throws InterruptedException, SQLException { /**//from ww w. j av a 2 s .c om * The example assumes the following SQL schema * * DROP DATABASE IF EXISTS beer_sample_sql; * CREATE DATABASE beer_sample_sql CHARACTER SET utf8 COLLATE utf8_general_ci; * USE beer_sample_sql; * * CREATE TABLE breweries ( * id VARCHAR(256) NOT NULL, * name VARCHAR(256), * description TEXT, * country VARCHAR(256), * city VARCHAR(256), * state VARCHAR(256), * phone VARCHAR(40), * updated_at DATETIME, * PRIMARY KEY (id) * ); * * * CREATE TABLE beers ( * id VARCHAR(256) NOT NULL, * brewery_id VARCHAR(256) NOT NULL, * name VARCHAR(256), * category VARCHAR(256), * style VARCHAR(256), * description TEXT, * abv DECIMAL(10,2), * ibu DECIMAL(10,2), * updated_at DATETIME, * PRIMARY KEY (id) * ); */ try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.err.println("Failed to load MySQL JDBC driver"); } Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/beer_sample_sql", "root", "secret"); final PreparedStatement insertBrewery = connection.prepareStatement( "INSERT INTO breweries (id, name, description, country, city, state, phone, updated_at)" + " VALUES (?, ?, ?, ?, ?, ?, ?, ?)" + " ON DUPLICATE KEY UPDATE" + " name=VALUES(name), description=VALUES(description), country=VALUES(country)," + " country=VALUES(country), city=VALUES(city), state=VALUES(state)," + " phone=VALUES(phone), updated_at=VALUES(updated_at)"); final PreparedStatement insertBeer = connection.prepareStatement( "INSERT INTO beers (id, brewery_id, name, description, category, style, abv, ibu, updated_at)" + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)" + " ON DUPLICATE KEY UPDATE" + " brewery_id=VALUES(brewery_id), name=VALUES(name), description=VALUES(description)," + " category=VALUES(category), style=VALUES(style), abv=VALUES(abv)," + " ibu=VALUES(ibu), updated_at=VALUES(updated_at)"); String schemaRegistryUrl = "http://localhost:8081"; Properties props = new Properties(); props.put(StreamsConfig.APPLICATION_ID_CONFIG, "streams-test"); props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(StreamsConfig.ZOOKEEPER_CONNECT_CONFIG, "localhost:2181"); props.put(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, schemaRegistryUrl); props.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, KeyAvroSerde.class); props.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, ValueAvroSerde.class); props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); KStreamBuilder builder = new KStreamBuilder(); KStream<String, GenericRecord> source = builder.stream("streaming-topic-beer-sample"); KStream<String, JsonNode>[] documents = source.mapValues(new ValueMapper<GenericRecord, JsonNode>() { @Override public JsonNode apply(GenericRecord value) { ByteBuffer buf = (ByteBuffer) value.get("content"); try { JsonNode doc = MAPPER.readTree(buf.array()); return doc; } catch (IOException e) { return null; } } }).branch(new Predicate<String, JsonNode>() { @Override public boolean test(String key, JsonNode value) { return "beer".equals(value.get("type").asText()) && value.has("brewery_id") && value.has("name") && value.has("description") && value.has("category") && value.has("style") && value.has("abv") && value.has("ibu") && value.has("updated"); } }, new Predicate<String, JsonNode>() { @Override public boolean test(String key, JsonNode value) { return "brewery".equals(value.get("type").asText()) && value.has("name") && value.has("description") && value.has("country") && value.has("city") && value.has("state") && value.has("phone") && value.has("updated"); } }); documents[0].foreach(new ForeachAction<String, JsonNode>() { @Override public void apply(String key, JsonNode value) { try { insertBeer.setString(1, key); insertBeer.setString(2, value.get("brewery_id").asText()); insertBeer.setString(3, value.get("name").asText()); insertBeer.setString(4, value.get("description").asText()); insertBeer.setString(5, value.get("category").asText()); insertBeer.setString(6, value.get("style").asText()); insertBeer.setBigDecimal(7, new BigDecimal(value.get("abv").asText())); insertBeer.setBigDecimal(8, new BigDecimal(value.get("ibu").asText())); insertBeer.setDate(9, new Date(DATE_FORMAT.parse(value.get("updated").asText()).getTime())); insertBeer.execute(); } catch (SQLException e) { System.err.println("Failed to insert record: " + key + ". " + e); } catch (ParseException e) { System.err.println("Failed to insert record: " + key + ". " + e); } } }); documents[1].foreach(new ForeachAction<String, JsonNode>() { @Override public void apply(String key, JsonNode value) { try { insertBrewery.setString(1, key); insertBrewery.setString(2, value.get("name").asText()); insertBrewery.setString(3, value.get("description").asText()); insertBrewery.setString(4, value.get("country").asText()); insertBrewery.setString(5, value.get("city").asText()); insertBrewery.setString(6, value.get("state").asText()); insertBrewery.setString(7, value.get("phone").asText()); insertBrewery.setDate(8, new Date(DATE_FORMAT.parse(value.get("updated").asText()).getTime())); insertBrewery.execute(); } catch (SQLException e) { System.err.println("Failed to insert record: " + key + ". " + e); } catch (ParseException e) { System.err.println("Failed to insert record: " + key + ". " + e); } } }); final KafkaStreams streams = new KafkaStreams(builder, props); streams.start(); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { streams.close(); } })); }
From source file:Main.java
public static String getDateTime(long milliseconds) { Date date = new Date(milliseconds); //return DateFormat.getDateTimeInstance().format(new Date()); return date.toLocaleString(); }