Example usage for java.sql Timestamp Timestamp

List of usage examples for java.sql Timestamp Timestamp

Introduction

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

Prototype

public Timestamp(long time) 

Source Link

Document

Constructs a Timestamp object using a milliseconds time value.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    String driverName = "com.jnetdirect.jsql.JSQLDriver";
    Class.forName(driverName);// w ww.j  a  v  a  2 s  .c o  m

    String serverName = "127.0.0.1";
    String portNumber = "1433";
    String mydatabase = serverName + ":" + portNumber;
    String url = "jdbc:JSQLConnect://" + mydatabase;
    String username = "username";
    String password = "password";

    Connection connection = DriverManager.getConnection(url, username, password);
    String sql = "INSERT INTO mysql_all_table(" + "col_boolean," + "col_byte," + "col_short," + "col_int,"
            + "col_long," + "col_float," + "col_double," + "col_bigdecimal," + "col_string," + "col_date,"
            + "col_time," + "col_timestamp," + "col_asciistream," + "col_binarystream," + "col_blob) "
            + "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
    PreparedStatement pstmt = connection.prepareStatement(sql);

    pstmt.setBoolean(1, true);
    pstmt.setByte(2, (byte) 123);
    pstmt.setShort(3, (short) 123);
    pstmt.setInt(4, 123);
    pstmt.setLong(5, 123L);
    pstmt.setFloat(6, 1.23F);
    pstmt.setDouble(7, 1.23D);
    pstmt.setBigDecimal(8, new BigDecimal(1.23));
    pstmt.setString(9, "a string");
    pstmt.setDate(10, new java.sql.Date(System.currentTimeMillis()));
    pstmt.setTime(11, new Time(System.currentTimeMillis()));
    pstmt.setTimestamp(12, new Timestamp(System.currentTimeMillis()));

    File file = new File("infilename1");
    FileInputStream is = new FileInputStream(file);
    pstmt.setAsciiStream(13, is, (int) file.length());

    file = new File("infilename2");
    is = new FileInputStream(file);
    pstmt.setBinaryStream(14, is, (int) file.length());

    file = new File("infilename3");
    is = new FileInputStream(file);
    pstmt.setBinaryStream(15, is, (int) file.length());

    pstmt.executeUpdate();
}

From source file:hydrograph.server.service.HydrographServiceClient.java

public static void main(String[] args) {
    HydrographServiceClient client = new HydrographServiceClient();
    try {/*  w w w.  j a  va2 s  .  co m*/
        System.out.println("+++ Start: " + new Timestamp((new Date()).getTime()));
        // client.calltoReadService();
        // client.calltoFilterService();
        //  client.calltoReadMetastore();
        client.chcekConnectionStatus();
        // client.calltoDeleteLocalDebugService();

        System.out.println("done:");
        System.out.println("+++ End: " + new Timestamp((new Date()).getTime()));
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:module.entities.NameFinder.RegexNameFinder.java

/**
 * @param args the command line arguments
 *//*from   w w w  . j av a2 s.  co  m*/
public static void main(String[] args) throws SQLException, IOException {

    if (args.length == 1) {
        Config.configFile = args[0];
    }
    long lStartTime = System.currentTimeMillis();
    Timestamp startTime = new Timestamp(lStartTime);
    System.out.println("Regex Name Finder process started at: " + startTime);
    DB.initPostgres();
    regexerId = DB.LogRegexFinder(lStartTime);
    initLexicons();
    JSONObject obj = new JSONObject();
    TreeMap<Integer, String> consultations = DB.getDemocracitConsultationBody();
    Document doc;
    int count = 0;
    TreeMap<Integer, String> consFoundNames = new TreeMap<>();
    TreeMap<Integer, String> consFoundRoles = new TreeMap<>();
    for (int consId : consultations.keySet()) {
        String consBody = consultations.get(consId);
        String signName = "", roleName = "";
        doc = Jsoup.parse(consBody);
        Elements allPars = new Elements();
        Elements paragraphs = doc.select("p");
        for (Element par : paragraphs) {
            if (par.html().contains("<br>")) {
                String out = "<p>" + par.html().replaceAll("<br>", "</p><p>") + "</p>";
                Document internal_doc = Jsoup.parse(out);
                Elements subparagraphs = internal_doc.select("p");
                allPars.addAll(subparagraphs);
            } else {
                allPars.add(par);
            }
            //                System.out.println(formatedText);
        }
        String signature = getSignatureFromParagraphs(allPars);
        //            System.out.println(signature);
        if (signature.contains("#")) {
            String[] sign_tokens = signature.split("#");
            signName = sign_tokens[0];
            if (sign_tokens.length > 1) {
                roleName = sign_tokens[1];
            }
            consFoundNames.put(consId, signName.trim());
            consFoundRoles.put(consId, roleName.trim());
            count++;
        } else {
            System.err.println("--" + consId);
        }
        //           
    }
    DB.insertDemocracitConsultationMinister(consFoundNames, consFoundRoles);

    TreeMap<Integer, String> consultationsCompletedText = DB.getDemocracitCompletedConsultationBody();
    Document doc2;
    TreeMap<Integer, String> complConsFoundNames = new TreeMap<>();
    int count2 = 0;
    for (int consId : consultationsCompletedText.keySet()) {
        String consBody = consultationsCompletedText.get(consId);
        String signName = "", roleName = "";
        doc2 = Jsoup.parse(consBody);
        //            if (doc.text().contains("<br>")) {
        //                doc.text().replaceAll("(<[Bb][Rr]>)+", "<p>");
        //            }
        Elements allPars = new Elements();
        Elements paragraphs = doc2.select("p");
        for (Element par : paragraphs) {

            if (par.html().contains("<br>")) {
                String out = "<p>" + par.html().replaceAll("<br>", "</p><p>") + "</p>";
                Document internal_doc = Jsoup.parse(out);
                Elements subparagraphs = internal_doc.select("p");
                allPars.addAll(subparagraphs);
            } else {
                allPars.add(par);
            }
        }
        String signature = getSignatureFromParagraphs(allPars);
        if (signature.contains("#")) {
            String[] sign_tokens = signature.split("#");
            signName = sign_tokens[0];
            if (sign_tokens.length > 1) {
                roleName = sign_tokens[1];
            }
            consFoundNames.put(consId, signName.trim());
            consFoundRoles.put(consId, roleName.trim());
            //                System.out.println(consId);
            //                System.out.println(signName.trim());
            //                System.out.println("***************");
            count2++;
        } else {
            System.err.println("++" + consId);
        }
    }
    DB.insertDemocracitConsultationMinister(complConsFoundNames, consFoundRoles);
    long lEndTime = System.currentTimeMillis();
    System.out.println("Regex Name Finder process finished at: " + startTime);
    obj.put("message", "Regex Name Finder finished with no errors");
    obj.put("details", "");
    DB.UpdateLogRegexFinder(lEndTime, regexerId, obj);
    DB.close();
}

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

public static void main(String[] args) throws IOException {

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

    List<String> lines = readLines(OrgUnitGenerator.class.getResourceAsStream("/org-units.csv"));

    System.out.println("Deleting existing OU's");
    dsl.deleteFrom(ORGANISATIONAL_UNIT).execute();

    List<OrganisationalUnitRecord> records = lines.stream().skip(1)
            .map(line -> StringUtils.splitPreserveAllTokens(line, ",")).filter(cells -> cells.length == 4)
            .map(cells -> {/*  w  w  w  .j ava  2  s.  c o  m*/
                OrganisationalUnitRecord record = new OrganisationalUnitRecord();
                record.setId(longVal(cells[0]));
                record.setParentId(longVal(cells[1]));
                record.setName(cells[2]);
                record.setDescription(cells[3]);
                record.setUpdatedAt(new Timestamp(System.currentTimeMillis()));

                System.out.println(record);
                return record;
            }).collect(Collectors.toList());

    System.out.println("Inserting new OU's");
    dsl.batchInsert(records).execute();

    System.out.println("Done");

}

From source file:com.mvdb.etl.actions.ExtractDBChanges.java

public static void main(String[] args) throws JSONException {

    ActionUtils.setUpInitFileProperty();
    //        boolean success = ActionUtils.markActionChainBroken("Just Testing");        
    //        System.exit(success ? 0 : 1);
    ActionUtils.assertActionChainNotBroken();
    ActionUtils.assertEnvironmentSetupOk();
    ActionUtils.assertFileExists("~/.mvdb", "~/.mvdb missing. Existing.");
    ActionUtils.assertFileExists("~/.mvdb/status.InitCustomerData.complete",
            "300init-customer-data.sh not executed yet. Exiting");
    //This check is not required as data can be modified any number of times
    //ActionUtils.assertFileDoesNotExist("~/.mvdb/status.ModifyCustomerData.complete", "ModifyCustomerData already done. Start with 100init.sh if required. Exiting");

    ActionUtils.createMarkerFile("~/.mvdb/status.ExtractDBChanges.start", true);

    //String schemaDescription = "{ 'root' : [{'table' : 'orders', 'keyColumn' : 'order_id', 'updateTimeColumn' : 'update_time'}]}";

    String customerName = null;/*  w  w  w . j av a 2s .  co m*/
    final CommandLineParser cmdLinePosixParser = new PosixParser();
    final Options posixOptions = constructPosixOptions();
    CommandLine commandLine;
    try {
        commandLine = cmdLinePosixParser.parse(posixOptions, args);
        if (commandLine.hasOption("customer")) {
            customerName = commandLine.getOptionValue("customer");
        }
    } catch (ParseException parseException) // checked exception
    {
        System.err.println(
                "Encountered exception while parsing using PosixParser:\n" + parseException.getMessage());
    }

    if (customerName == null) {
        System.err.println("Could not find customerName. Aborting...");
        System.exit(1);
    }

    ApplicationContext context = Top.getContext();

    final OrderDAO orderDAO = (OrderDAO) context.getBean("orderDAO");
    final ConfigurationDAO configurationDAO = (ConfigurationDAO) context.getBean("configurationDAO");
    final GenericDAO genericDAO = (GenericDAO) context.getBean("genericDAO");
    File snapshotDirectory = getSnapshotDirectory(configurationDAO, customerName);
    try {
        FileUtils.writeStringToFile(new File("/tmp/etl.extractdbchanges.directory.txt"),
                snapshotDirectory.getName(), false);
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
        return;
    }
    long currentTime = new Date().getTime();
    Configuration lastRefreshTimeConf = configurationDAO.find(customerName, "last-refresh-time");
    Configuration schemaDescriptionConf = configurationDAO.find(customerName, "schema-description");
    long lastRefreshTime = Long.parseLong(lastRefreshTimeConf.getValue());
    OrderJsonFileConsumer orderJsonFileConsumer = new OrderJsonFileConsumer(snapshotDirectory);
    Map<String, ColumnMetadata> metadataMap = orderDAO.findMetadata();
    //write file schema-orders.dat in snapshotDirectory
    genericDAO.fetchMetadata("orders", snapshotDirectory);
    //writes files: header-orders.dat, data-orders.dat in snapshotDirectory
    JSONObject json = new JSONObject(schemaDescriptionConf.getValue());
    JSONArray rootArray = json.getJSONArray("root");
    int length = rootArray.length();
    for (int i = 0; i < length; i++) {
        JSONObject jsonObject = rootArray.getJSONObject(i);
        String table = jsonObject.getString("table");
        String keyColumnName = jsonObject.getString("keyColumn");
        String updateTimeColumnName = jsonObject.getString("updateTimeColumn");
        System.out.println("table:" + table + ", keyColumn: " + keyColumnName + ", updateTimeColumn: "
                + updateTimeColumnName);
        genericDAO.fetchAll2(snapshotDirectory, new Timestamp(lastRefreshTime), table, keyColumnName,
                updateTimeColumnName);
    }

    //Unlikely failure
    //But Need to factor this into a separate task so that extraction does not have to be repeated. 
    //Extraction is an expensive task. 
    try {
        String sourceDirectoryAbsolutePath = snapshotDirectory.getAbsolutePath();

        File sourceRelativeDirectoryPath = getRelativeSnapShotDirectory(configurationDAO,
                sourceDirectoryAbsolutePath);
        String hdfsRoot = ActionUtils.getConfigurationValue(ConfigurationKeys.GLOBAL_CUSTOMER,
                ConfigurationKeys.GLOBAL_HDFS_ROOT);
        String targetDirectoryFullPath = hdfsRoot + "/data" + sourceRelativeDirectoryPath;

        ActionUtils.copyLocalDirectoryToHdfsDirectory(sourceDirectoryAbsolutePath, targetDirectoryFullPath);
        String dirName = snapshotDirectory.getName();
        ActionUtils.setConfigurationValue(customerName, ConfigurationKeys.LAST_COPY_TO_HDFS_DIRNAME, dirName);
    } catch (Throwable e) {
        e.printStackTrace();
        logger.error("Objects Extracted from database. But copy of snapshot directory<"
                + snapshotDirectory.getAbsolutePath() + "> to hdfs <" + ""
                + ">failed. Fix the problem and redo extract.", e);
        System.exit(1);
    }

    //Unlikely failure
    //But Need to factor this into a separate task so that extraction does not have to be repeated. 
    //Extraction is an expensive task. 
    String targetZip = null;
    try {
        File targetZipDirectory = new File(snapshotDirectory.getParent(), "archives");
        if (!targetZipDirectory.exists()) {
            boolean success = targetZipDirectory.mkdirs();
            if (success == false) {
                logger.error("Objects copied to hdfs. But able to create archive directory <"
                        + targetZipDirectory.getAbsolutePath() + ">. Fix the problem and redo extract.");
                System.exit(1);
            }
        }
        targetZip = new File(targetZipDirectory, snapshotDirectory.getName() + ".zip").getAbsolutePath();
        ActionUtils.zipFullDirectory(snapshotDirectory.getAbsolutePath(), targetZip);
    } catch (Throwable e) {
        e.printStackTrace();
        logger.error("Objects copied to hdfs. But zipping of snapshot directory<"
                + snapshotDirectory.getAbsolutePath() + "> to  <" + targetZip
                + ">failed. Fix the problem and redo extract.", e);
        System.exit(1);
    }

    //orderDAO.findAll(new Timestamp(lastRefreshTime), orderJsonFileConsumer);
    Configuration updateRefreshTimeConf = new Configuration(customerName, "last-refresh-time",
            String.valueOf(currentTime));
    configurationDAO.update(updateRefreshTimeConf, String.valueOf(lastRefreshTimeConf.getValue()));
    ActionUtils.createMarkerFile("~/.mvdb/status.ExtractDBChanges.complete", true);

}

From source file:de.prozesskraft.pkraft.Waitinstance.java

public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException {

    /*----------------------------
      get options from ini-file//w w  w.j  a v  a 2s . c om
    ----------------------------*/
    java.io.File inifile = new java.io.File(WhereAmI.getInstallDirectoryAbsolutePath(Waitinstance.class) + "/"
            + "../etc/pkraft-waitinstance.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option ohelp = new Option("help", "print this message");
    Option ov = new Option("v", "prints version and build-date");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option oinstance = OptionBuilder.withArgName("FILE").hasArg().withDescription(
            "[mandatory if no -scandir] instance file (process.pmb) that this program will wait till its status is 'error' or 'finished'")
            //            .isRequired()
            .create("instance");

    Option oscandir = OptionBuilder.withArgName("DIR").hasArg().withDescription(
            "[mandatory if no -instance] directory tree with instances (process.pmb). the first instance found will be tracked.")
            //            .isRequired()
            .create("scandir");

    Option omaxrun = OptionBuilder.withArgName("INTEGER").hasArg().withDescription(
            "[optional, default: 4320] time period (in minutes, default: 3 days) this program waits till it aborts further waiting.")
            //            .isRequired()
            .create("maxrun");

    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(oinstance);
    options.addOption(oscandir);
    options.addOption(omaxrun);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    // parse the command line arguments
    commandline = parser.parse(options, args);

    /*----------------------------
      usage/help
    ----------------------------*/
    if (commandline.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("waitinstance", options);
        System.exit(0);
    }

    if (commandline.hasOption("v")) {
        System.out.println("author:  alexander.vogel@caegroup.de");
        System.out.println("version: [% version %]");
        System.out.println("date:    [% date %]");
        System.exit(0);
    }
    /*----------------------------
      ueberpruefen ob eine schlechte kombination von parametern angegeben wurde
    ----------------------------*/
    Integer maxrun = new Integer(4320);
    String pathInstance = null;
    String pathScandir = null;

    // instance & scandir
    if (!(commandline.hasOption("instance")) && !(commandline.hasOption("scandir"))) {
        System.err.println("one of the options -instance/-scandir is mandatory");
        exiter();
    } else if ((commandline.hasOption("instance")) && (commandline.hasOption("scandir"))) {
        System.err.println("both options -instance/-scandir are not allowed");
        exiter();
    } else if (commandline.hasOption("instance")) {
        pathInstance = commandline.getOptionValue("instance");
    } else if (commandline.hasOption("scandir")) {
        pathScandir = commandline.getOptionValue("scandir");
    }

    // maxrun
    if (commandline.hasOption("maxrun")) {
        maxrun = new Integer(commandline.getOptionValue("maxrun"));
    }
    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/

    // scannen nach dem ersten process.pmb 
    if ((pathScandir != null) && (pathInstance == null)) {
        String[] allBinariesOfScanDir = getProcessBinaries(pathScandir);

        if (allBinariesOfScanDir.length == 0) {
            System.err.println("no instance (process.pmb) found in directory tree " + pathScandir);
            exiter();
        } else {
            pathInstance = allBinariesOfScanDir[0];
            System.err.println("found instance: " + pathInstance);
        }
    }

    // ueberpruefen ob instance file existiert
    java.io.File fileInstance = new java.io.File(pathInstance);

    if (!fileInstance.exists()) {
        System.err.println("instance file does not exist: " + fileInstance.getAbsolutePath());
        exiter();
    }

    if (!fileInstance.isFile()) {
        System.err.println("instance file is not a file: " + fileInstance.getAbsolutePath());
        exiter();
    }

    // zeitpunkt wenn spaetestens beendet werden soll
    long runTill = System.currentTimeMillis() + (maxrun * 60 * 1000);

    // logging
    System.err.println("waiting for instance: " + fileInstance.getAbsolutePath());
    System.err.println("checking its status every 5 minutes");
    System.err.println("now is: " + new Timestamp(startInMillis).toString());
    System.err.println("maxrun till: " + new Timestamp(runTill).toString());

    // instanz einlesen
    Process p1 = new Process();
    p1.setInfilebinary(fileInstance.getAbsolutePath());
    Process p2 = p1.readBinary();

    // schleife, die prozess einliest und ueberprueft ob er noch laeuft
    while (!(p2.getStatus().equals("error") || p2.getStatus().equals("finished"))) {
        // logging
        System.err.println(new Timestamp(System.currentTimeMillis()) + " instance status: " + p2.getStatus());

        // 5 minuten schlafen: 300000 millis
        try {
            Thread.sleep(300000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // ist die maximale laufzeit von this erreicht, dann soll beendet werden (3 tage)
        if (System.currentTimeMillis() > runTill) {
            System.err
                    .println("exiting because of maxrun. now is: " + new Timestamp(System.currentTimeMillis()));
            System.exit(2);
        }

        // den prozess frisch einlesen
        p2 = p1.readBinary();
    }

    System.err.println("exiting because instance status is: " + p2.getStatus());
    System.err.println("now is: " + new Timestamp(System.currentTimeMillis()).toString());
    System.exit(0);

}

From source file:Util.java

public static Timestamp getToday() {
    return new Timestamp(Calendar.getInstance().getTime().getTime());
}

From source file:Main.java

public static String buildTimeStampString() {
    return new Timestamp(System.currentTimeMillis()).toString();
}

From source file:Main.java

public static Timestamp getCurrentTimestamp() {
    return new Timestamp(System.currentTimeMillis());
}

From source file:Main.java

public static String getSeconds1() {

    Timestamp stamp1 = new Timestamp(System.currentTimeMillis());
    return stamp1.toString();
}