Example usage for java.text SimpleDateFormat format

List of usage examples for java.text SimpleDateFormat format

Introduction

In this page you can find the example usage for java.text SimpleDateFormat format.

Prototype

public final String format(Date date) 

Source Link

Document

Formats a Date into a date-time string.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    SimpleDateFormat broken = new SimpleDateFormat("kk:mm:ss");
    broken.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
    SimpleDateFormat working = new SimpleDateFormat("HH:mm:ss");
    working.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));

    Date epoch = new Date(0);

    System.out.println(broken.format(epoch));
    System.out.println(working.format(epoch));
}

From source file:javasnack.cli.CliDbUnitCsvExportDemo.java

public static void main(String[] args) throws Exception {
    String driver = System.getProperty("CliDbUnitCsvExportDemo.driver", "org.h2.Driver");
    Class.forName(driver);//from  w  w  w .j  av  a  2 s . com
    String url = System.getProperty("CliDbUnitCsvExportDemo.url", "jdbc:h2:mem:CliDbUnitCsvExportDemo");
    String dbUser = System.getProperty("CliDbUnitCsvExportDemo.dbUser", "sa");
    String dbPassword = System.getProperty("CliDbUnitCsvExportDemo.dbPassword", "");
    Connection conn = DriverManager.getConnection(url, dbUser, dbPassword);

    CliDbUnitCsvExportDemo demo = new CliDbUnitCsvExportDemo();
    demo.setup(conn);

    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
    Calendar c = Calendar.getInstance();
    File outDir = new File(sdf1.format(c.getTime()));
    outDir.mkdir();

    IDatabaseConnection dbunit_conn = new DatabaseConnection(conn);
    IDataSet dataSet = dbunit_conn.createDataSet();

    CsvBase64BinarySafeDataSetWriter.write(dataSet, outDir);

    conn.close();
}

From source file:ie.aib.nbp.zosresttest.RunTest.java

/**
 * @param args the command line arguments
 *//*from  w  ww . jav a  2s.  co  m*/
public static void main(String[] args) {
    PrintStream printer = null;

    if (args.length < 2) {
        System.out.println("***************************************************************************");
        System.out.println("*                   Z/OS REST SERVICES PERFORMANCE TESTER                 *");
        System.out.println("*                                                                         *");
        System.out.println("* At least 2 run parameters are required:                                 *");
        System.out.println("*  1 username: your mainframe username                                    *");
        System.out.println("*  2 password: your mainframe passeord                                    *");
        System.out.println("*  3 runtime behaviour switch: 1 - active, everything else - inactive     *");
        System.out.println("*    this parameter is optional and causes the app to run the test or not *");
        System.out.println("*    lack of it assings default value: 0                                  *");
        System.out.println("*    which triggers the service discovery feature                         *");
        System.out.println("*    and displays all currently available services                        *");
        System.out.println("*  4 output type:                                                         *");
        System.out.println("*     F - output to file (then fifth parameter hold the file location)    *");
        System.out.println("*     Everything else (including no parameter at all) outputs to console  *");
        System.out.println("***************************************************************************");
        return;
    }

    readConfig(CONFIG_FILE_PATH);
    String username = args[0];
    String password = args[1];

    String runPerformanceTest;
    try {
        runPerformanceTest = args[2];
    } catch (ArrayIndexOutOfBoundsException ex) {
        runPerformanceTest = "0";
    }

    String outputType;
    String outputFileLocation;
    try {
        outputType = args[3]; // F saves to file, everything else output to console            
    } catch (ArrayIndexOutOfBoundsException ex) {
        outputType = "C";
    }

    if (outputType.equalsIgnoreCase("F")) { // write to file
        String outputFile;
        try {
            outputFile = args[4]; // if prev param is F then this one may contain the file name (default name instead)
        } catch (ArrayIndexOutOfBoundsException ex) {
            SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy-HHmmssZ");
            outputFile = "ZosPerformanceTest".concat("-".concat(sdf.format(new Date()))).concat(".txt");
        }
        try {
            String filePath = config.getProperty("OUT_FILE_PATH").concat(outputFile);
            printer = new PrintStream(new FileOutputStream(filePath, true));
        } catch (FileNotFoundException ex) {
            Logger.getLogger(RunTest.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else { // othewise write to java console
        printer = new PrintStream(System.out);
    }

    if (runPerformanceTest.equals("1"))
        runPerformanceTest(username, password, printer, true, false);
    else
        runServiceDiscovery(username, password, printer);
}

From source file:airnowgrib2tojson.AirNowGRIB2toJSON.java

/**
 * @param args the command line arguments
 *//*from w w w.  j a v  a  2 s .c  o m*/
public static void main(String[] args) {

    SimpleDateFormat GMT = new SimpleDateFormat("yyMMddHH");
    GMT.setTimeZone(TimeZone.getTimeZone("GMT-2"));

    System.out.println(GMT.format(new Date()));

    FTPClient ftpClient = new FTPClient();
    FileOutputStream fos = null;

    try {
        //Connecting to AirNow FTP server to get the fresh AQI data  
        ftpClient.connect("ftp.airnowapi.org");
        ftpClient.login("pixelshade", "GZDN8uqduwvk");
        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        //downloading .grib2 file
        File of = new File("US-" + GMT.format(new Date()) + "_combined.grib2");
        OutputStream outstr = new BufferedOutputStream(new FileOutputStream(of));
        InputStream instr = ftpClient
                .retrieveFileStream("GRIB2/US-" + GMT.format(new Date()) + "_combined.grib2");
        byte[] bytesArray = new byte[4096];
        int bytesRead = -1;
        while ((bytesRead = instr.read(bytesArray)) != -1) {
            outstr.write(bytesArray, 0, bytesRead);
        }

        //Close used resources
        ftpClient.completePendingCommand();
        outstr.close();
        instr.close();

        // logout the user 
        ftpClient.logout();

    } catch (SocketException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            //disconnect from AirNow server
            ftpClient.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    try {
        //Open .grib2 file
        final File AQIfile = new File("US-" + GMT.format(new Date()) + "_combined.grib2");
        final GridDataset gridDS = GridDataset.open(AQIfile.getAbsolutePath());

        //The data type needed - AQI; since it isn't defined in GRIB2 standard,
        //Aerosol type is used instead; look AirNow API documentation for details.
        GridDatatype AQI = gridDS.findGridDatatype("Aerosol_type_msl");

        //Get the coordinate system for selected data type;
        //cut the rectangle to work with - time and height axes aren't present in these files
        //and latitude/longitude go "-1", which means all the data provided.
        GridCoordSystem AQIGCS = AQI.getCoordinateSystem();
        List<CoordinateAxis> AQI_XY = AQIGCS.getCoordinateAxes();
        Array AQIslice = AQI.readDataSlice(0, 0, -1, -1);

        //Variables for iterating through coordinates
        VariableDS var = AQI.getVariable();
        Index index = AQIslice.getIndex();

        //Variables for counting lat/long from the indices provided
        double stepX = (AQI_XY.get(2).getMaxValue() - AQI_XY.get(2).getMinValue()) / index.getShape(1);
        double stepY = (AQI_XY.get(1).getMaxValue() - AQI_XY.get(1).getMinValue()) / index.getShape(0);
        double curX = AQI_XY.get(2).getMinValue();
        double curY = AQI_XY.get(1).getMinValue();

        //Output details
        OutputStream ValLog = new FileOutputStream("USA_AQI.json");
        Writer ValWriter = new OutputStreamWriter(ValLog);

        for (int j = 0; j < index.getShape(0); j++) {
            for (int i = 0; i < index.getShape(1); i++) {
                float val = AQIslice.getFloat(index.set(j, i));

                //Write the AQI value and its coordinates if it's present by i/j indices
                if (!Float.isNaN(val))
                    ValWriter.write("{\r\n\"lat\":" + curX + ",\r\n\"lng\":" + curY + ",\r\n\"AQI\":" + val
                            + ",\r\n},\r\n");

                curX += stepX;
            }
            curY += stepY;
            curX = AQI_XY.get(2).getMinValue();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:FastDateFormat.java

public static void main(String[] args) {
    String format = "yyyy-MM-dd HH:mm:ss.SSS";
    if (args.length > 0)
        format = args[0];/* w  w w.  j  a v a2s.co m*/
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    FastDateFormat fdf = new FastDateFormat(sdf);
    Date d = new Date();

    d.setTime(1);
    System.out.println(fdf.format(d) + "\t" + sdf.format(d));
    d.setTime(20);
    System.out.println(fdf.format(d) + "\t" + sdf.format(d));
    d.setTime(500);
    System.out.println(fdf.format(d) + "\t" + sdf.format(d));
    d.setTime(543);
    System.out.println(fdf.format(d) + "\t" + sdf.format(d));
    d.setTime(999);
    System.out.println(fdf.format(d) + "\t" + sdf.format(d));
    d.setTime(1050);
    System.out.println(fdf.format(d) + "\t" + sdf.format(d));
    d.setTime(2543);
    System.out.println(fdf.format(d) + "\t" + sdf.format(d));
    d.setTime(12345);
    System.out.println(fdf.format(d) + "\t" + sdf.format(d));
    d.setTime(12340);
    System.out.println(fdf.format(d) + "\t" + sdf.format(d));

    final int reps = 100000;
    {
        long start = System.currentTimeMillis();
        for (int i = 0; i < reps; i++) {
            d.setTime(System.currentTimeMillis());
            fdf.format(d);
        }
        long elap = System.currentTimeMillis() - start;
        System.out.println("fast: " + elap + " elapsed");
        System.out.println(fdf.format(d));
    }
    {
        long start = System.currentTimeMillis();
        for (int i = 0; i < reps; i++) {
            d.setTime(System.currentTimeMillis());
            sdf.format(d);
        }
        long elap = System.currentTimeMillis() - start;
        System.out.println("slow: " + elap + " elapsed");
        System.out.println(sdf.format(d));
    }
}

From source file:com.payne.test.DateFormateTest.java

public static void main(String[] args) throws ParseException {
    //        String a = null;
    //        boolean ismmediated = a == null || DateUtils.parseDate(null,"yyyy-MM-dd HH:mm").compareTo(new Date()) <= 0;
    //        /*from  w  w w . jav a 2 s .c om*/
    //        System.out.println(""+ismmediated);
    //        System.out.println(""+System.currentTimeMillis());
    //            
    //              String randomNum = String.valueOf(Math.random());
    //        randomNum = randomNum.replace(".", "");
    //        randomNum = randomNum.substring(0, 8);
    //        
    //        System.out.println(""+Integer.valueOf(randomNum.toString()));
    //        
    //        Integer a = 1000000000;

    //        BigDecimal b = new BigDecimal("3000000000");
    //        System.out.println(""+b.longValue());
    //        System.out.println(""+b.intValue());

    SimpleDateFormat sdf = new SimpleDateFormat("");
    //        Calendar c = Calendar.getInstance();
    //        c.setTime(new Date());
    //        c.set(Calendar.MINUTE, 0);
    //        c.set(Calendar.SECOND, 0);
    //        c.set(Calendar.MILLISECOND, 0);
    //        

    System.out.println(sdf.format(new Date()));

}

From source file:io.druid.examples.rabbitmq.RabbitMQProducerMain.java

public static void main(String[] args) throws Exception {
    // We use a List to keep track of option insertion order. See below.
    final List<Option> optionList = new ArrayList<Option>();

    optionList.add(OptionBuilder.withLongOpt("help").withDescription("display this help message").create("h"));
    optionList.add(OptionBuilder.withLongOpt("hostname").hasArg()
            .withDescription("the hostname of the AMQP broker [defaults to AMQP library default]").create("b"));
    optionList.add(OptionBuilder.withLongOpt("port").hasArg()
            .withDescription("the port of the AMQP broker [defaults to AMQP library default]").create("n"));
    optionList.add(OptionBuilder.withLongOpt("username").hasArg()
            .withDescription("username to connect to the AMQP broker [defaults to AMQP library default]")
            .create("u"));
    optionList.add(OptionBuilder.withLongOpt("password").hasArg()
            .withDescription("password to connect to the AMQP broker [defaults to AMQP library default]")
            .create("p"));
    optionList.add(OptionBuilder.withLongOpt("vhost").hasArg()
            .withDescription("name of virtual host on the AMQP broker [defaults to AMQP library default]")
            .create("v"));
    optionList.add(OptionBuilder.withLongOpt("exchange").isRequired().hasArg()
            .withDescription("name of the AMQP exchange [required - no default]").create("e"));
    optionList.add(OptionBuilder.withLongOpt("key").hasArg()
            .withDescription("the routing key to use when sending messages [default: 'default.routing.key']")
            .create("k"));
    optionList.add(OptionBuilder.withLongOpt("type").hasArg()
            .withDescription("the type of exchange to create [default: 'topic']").create("t"));
    optionList.add(OptionBuilder.withLongOpt("durable")
            .withDescription("if set, a durable exchange will be declared [default: not set]").create("d"));
    optionList.add(OptionBuilder.withLongOpt("autodelete")
            .withDescription("if set, an auto-delete exchange will be declared [default: not set]")
            .create("a"));
    optionList.add(OptionBuilder.withLongOpt("single")
            .withDescription("if set, only a single message will be sent [default: not set]").create("s"));
    optionList.add(OptionBuilder.withLongOpt("start").hasArg()
            .withDescription("time to use to start sending messages from [default: 2010-01-01T00:00:00]")
            .create());/*from   w  w  w . ja  v a2 s. c om*/
    optionList.add(OptionBuilder.withLongOpt("stop").hasArg().withDescription(
            "time to use to send messages until (format: '2013-07-18T23:45:59') [default: current time]")
            .create());
    optionList.add(OptionBuilder.withLongOpt("interval").hasArg()
            .withDescription("the interval to add to the timestamp between messages in seconds [default: 10]")
            .create());
    optionList.add(OptionBuilder.withLongOpt("delay").hasArg()
            .withDescription("the delay between sending messages in milliseconds [default: 100]").create());

    // An extremely silly hack to maintain the above order in the help formatting.
    HelpFormatter formatter = new HelpFormatter();
    // Add a comparator to the HelpFormatter using the ArrayList above to sort by insertion order.
    formatter.setOptionComparator(new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            // I know this isn't fast, but who cares! The list is short.
            return optionList.indexOf(o1) - optionList.indexOf(o2);
        }
    });

    // Now we can add all the options to an Options instance. This is dumb!
    Options options = new Options();
    for (Option option : optionList) {
        options.addOption(option);
    }

    CommandLine cmd = null;

    try {
        cmd = new BasicParser().parse(options, args);

    } catch (ParseException e) {
        formatter.printHelp("RabbitMQProducerMain", e.getMessage(), options, null);
        System.exit(1);
    }

    if (cmd.hasOption("h")) {
        formatter.printHelp("RabbitMQProducerMain", options);
        System.exit(2);
    }

    ConnectionFactory factory = new ConnectionFactory();

    if (cmd.hasOption("b")) {
        factory.setHost(cmd.getOptionValue("b"));
    }
    if (cmd.hasOption("u")) {
        factory.setUsername(cmd.getOptionValue("u"));
    }
    if (cmd.hasOption("p")) {
        factory.setPassword(cmd.getOptionValue("p"));
    }
    if (cmd.hasOption("v")) {
        factory.setVirtualHost(cmd.getOptionValue("v"));
    }
    if (cmd.hasOption("n")) {
        factory.setPort(Integer.parseInt(cmd.getOptionValue("n")));
    }

    String exchange = cmd.getOptionValue("e");
    String routingKey = "default.routing.key";
    if (cmd.hasOption("k")) {
        routingKey = cmd.getOptionValue("k");
    }

    boolean durable = cmd.hasOption("d");
    boolean autoDelete = cmd.hasOption("a");
    String type = cmd.getOptionValue("t", "topic");
    boolean single = cmd.hasOption("single");
    int interval = Integer.parseInt(cmd.getOptionValue("interval", "10"));
    int delay = Integer.parseInt(cmd.getOptionValue("delay", "100"));

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    Date stop = sdf.parse(cmd.getOptionValue("stop", sdf.format(new Date())));

    Random r = new Random();
    Calendar timer = Calendar.getInstance();
    timer.setTime(sdf.parse(cmd.getOptionValue("start", "2010-01-01T00:00:00")));

    String msg_template = "{\"utcdt\": \"%s\", \"wp\": %d, \"gender\": \"%s\", \"age\": %d}";

    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(exchange, type, durable, autoDelete, null);

    do {
        int wp = (10 + r.nextInt(90)) * 100;
        String gender = r.nextBoolean() ? "male" : "female";
        int age = 20 + r.nextInt(70);

        String line = String.format(msg_template, sdf.format(timer.getTime()), wp, gender, age);

        channel.basicPublish(exchange, routingKey, null, line.getBytes());

        System.out.println("Sent message: " + line);

        timer.add(Calendar.SECOND, interval);

        Thread.sleep(delay);
    } while ((!single && stop.after(timer.getTime())));

    connection.close();
}

From source file:GIST.IzbirkomExtractor.IzbirkomExtractor.java

/**
 * @param args//from  w  w  w  .  ja va2s . c  o m
 */
public static void main(String[] args) {

    // process command-line options
    Options options = new Options();
    options.addOption("n", "noaddr", false, "do not do any address matching (for testing)");
    options.addOption("i", "info", false, "create and populate address information table");
    options.addOption("h", "help", false, "this message");

    // database connection
    options.addOption("s", "server", true, "database server to connect to");
    options.addOption("d", "database", true, "OSM database name");
    options.addOption("u", "user", true, "OSM database user name");
    options.addOption("p", "pass", true, "OSM database password");

    // logging options
    options.addOption("l", "logdir", true, "log file directory (default './logs')");
    options.addOption("e", "loglevel", true, "log level (default 'FINEST')");

    // automatically generate the help statement
    HelpFormatter help_formatter = new HelpFormatter();

    // database URI for connection
    String dburi = null;

    // Information message for help screen
    String info_msg = "IzbirkomExtractor [options] <html_directory>";

    try {
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption('h') || cmd.getArgs().length != 1) {
            help_formatter.printHelp(info_msg, options);
            System.exit(1);
        }

        /* prohibit n and i together */
        if (cmd.hasOption('n') && cmd.hasOption('i')) {
            System.err.println("Options 'n' and 'i' cannot be used together.");
            System.exit(1);
        }

        /* require database arguments without -n */
        if (cmd.hasOption('n')
                && (cmd.hasOption('s') || cmd.hasOption('d') || cmd.hasOption('u') || cmd.hasOption('p'))) {
            System.err.println("Options 'n' and does not need any databse parameters.");
            System.exit(1);
        }

        /* require all 4 database options to be used together */
        if (!cmd.hasOption('n')
                && !(cmd.hasOption('s') && cmd.hasOption('d') && cmd.hasOption('u') && cmd.hasOption('p'))) {
            System.err.println(
                    "For database access all of the following arguments have to be specified: server, database, user, pass");
            System.exit(1);
        }

        /* useful variables */
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm");
        String dateString = formatter.format(new Date());

        /* setup logging */
        File logdir = new File(cmd.hasOption('l') ? cmd.getOptionValue('l') : "logs");
        FileUtils.forceMkdir(logdir);
        File log_file_name = new File(
                logdir + "/" + IzbirkomExtractor.class.getName() + "-" + formatter.format(new Date()) + ".log");
        FileHandler log_file = new FileHandler(log_file_name.getPath());

        /* create "latest" link to currently created log file */
        Path latest_log_link = Paths.get(logdir + "/latest");
        Files.deleteIfExists(latest_log_link);
        Files.createSymbolicLink(latest_log_link, Paths.get(log_file_name.getName()));

        log_file.setFormatter(new SimpleFormatter());
        LogManager.getLogManager().reset(); // prevents logging to console
        logger.addHandler(log_file);
        logger.setLevel(cmd.hasOption('e') ? Level.parse(cmd.getOptionValue('e')) : Level.FINEST);

        // open directory with HTML files and create file list
        File dir = new File(cmd.getArgs()[0]);
        if (!dir.isDirectory()) {
            System.err.println("Unable to find directory '" + cmd.getArgs()[0] + "', exiting");
            System.exit(1);
        }
        PathMatcher pmatcher = FileSystems.getDefault()
                .getPathMatcher("glob:?  * ?*.html");
        ArrayList<File> html_files = new ArrayList<>();
        for (Path file : Files.newDirectoryStream(dir.toPath()))
            if (pmatcher.matches(file.getFileName()))
                html_files.add(file.toFile());
        if (html_files.size() == 0) {
            System.err.println("No matching HTML files found in '" + dir.getAbsolutePath() + "', exiting");
            System.exit(1);
        }

        // create csvResultSink
        FileOutputStream csvout_file = new FileOutputStream("parsed_addresses-" + dateString + ".csv");
        OutputStreamWriter csvout = new OutputStreamWriter(csvout_file, "UTF-8");
        ResultSink csvResultSink = new CSVResultSink(csvout, new CSVStrategy('|', '"', '#'));

        // Connect to DB and osmAddressMatcher
        AddressMatcher osmAddressMatcher;
        DBSink dbSink = null;
        DBInfoSink dbInfoSink = null;
        if (cmd.hasOption('n')) {
            osmAddressMatcher = new DummyAddressMatcher();
        } else {
            dburi = "jdbc:postgresql://" + cmd.getOptionValue('s') + "/" + cmd.getOptionValue('d');
            Connection con = DriverManager.getConnection(dburi, cmd.getOptionValue('u'),
                    cmd.getOptionValue('p'));
            osmAddressMatcher = new OsmAddressMatcher(con);
            dbSink = new DBSink(con);
            if (cmd.hasOption('i'))
                dbInfoSink = new DBInfoSink(con);
        }

        /* create resultsinks */
        SinkMultiplexor sm = SinkMultiplexor.newSinkMultiplexor();
        sm.addResultSink(csvResultSink);
        if (dbSink != null) {
            sm.addResultSink(dbSink);
            if (dbInfoSink != null)
                sm.addResultSink(dbInfoSink);
        }

        // create tableExtractor
        TableExtractor te = new TableExtractor(osmAddressMatcher, sm);

        // TODO: printout summary of options: processing date/time, host, directory of HTML files, jdbc uri, command line with parameters

        // iterate through files
        logger.info("Start processing " + html_files.size() + " files in " + dir);
        for (int i = 0; i < html_files.size(); i++) {
            System.err.println("Parsing #" + i + ": " + html_files.get(i));
            te.processHTMLfile(html_files.get(i));
        }

        System.err.println("Processed " + html_files.size() + " HTML files");
        logger.info("Finished processing " + html_files.size() + " files in " + dir);

    } catch (ParseException e1) {
        System.err.println("Failed to parse CLI: " + e1.getMessage());
        help_formatter.printHelp(info_msg, options);
        System.exit(1);
    } catch (IOException e) {
        System.err.println("I/O Exception: " + e.getMessage());
        e.printStackTrace();
        System.exit(1);
    } catch (SQLException e) {
        System.err.println("Database '" + dburi + "': " + e.getMessage());
        System.exit(1);
    } catch (ResultSinkException e) {
        System.err.println("Failed to initialize ResultSink: " + e.getMessage());
        System.exit(1);
    } catch (TableExtractorException e) {
        System.err.println("Failed to initialize Table Extractor: " + e.getMessage());
        System.exit(1);
    } catch (CloneNotSupportedException | IllegalAccessException | InstantiationException e) {
        System.err.println("Something really odd happened: " + e.getMessage());
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:info.usbo.skypetwitter.Run.java

public static void main(String[] args) {
    System.out.println("Working Directory = " + System.getProperty("user.dir"));
    Properties props;/*from w w  w .j  av a2  s  .  com*/
    props = (Properties) System.getProperties().clone();
    //loadProperties(props, "D:\\Data\\Java\\classpath\\twitter.props");
    work_dir = System.getProperty("user.dir");
    loadProperties(props, work_dir + "\\twitter.props");
    twitter_user_id = props.getProperty("twitter.user");
    twitter_timeout = Integer.parseInt(props.getProperty("twitter.timeout"));
    System.out.println("Twitter user: " + twitter_user_id);
    System.out.println("Twitter timeout: " + twitter_timeout);
    if ("".equals(twitter_user_id)) {
        return;
    }
    if (load_file() == 0) {
        System.out.println("File not found");
        return;
    }
    while (true) {
        bChanged = 0;
        /*
        create_id();
        Chat ch = Chat.getInstance(chat_group_id);
        ch.send("!");
        */
        SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm");
        System.out.println("Looking at " + sdf.format(Calendar.getInstance().getTime()));
        Chat ch = Chat.getInstance(chat_group_id);
        Twitter twitter = new TwitterFactory().getInstance();
        try {
            List<Status> statuses;
            statuses = twitter.getUserTimeline(twitter_user_id);
            //System.out.println("Showing @" + twitter_user_id + "'s user timeline.");
            String sText;
            for (Status status : statuses) {
                //System.out.println(status.getId());
                Date d = status.getCreatedAt();
                //   ?
                Calendar cal = Calendar.getInstance();
                cal.setTime(d);
                cal.add(Calendar.HOUR_OF_DAY, 7);
                d = cal.getTime();
                sText = "@" + status.getUser().getScreenName() + "  " + sdf.format(d)
                        + " ( https://twitter.com/" + twitter_user_id + "/status/" + status.getId() + " ): \r\n"
                        + status.getText() + "\r\n***";
                for (URLEntity e : status.getURLEntities()) {
                    sText = sText.replaceAll(e.getURL(), e.getExpandedURL());
                }
                for (MediaEntity e : status.getMediaEntities()) {
                    sText = sText.replaceAll(e.getURL(), e.getMediaURL());
                }
                if (twitter_ids.indexOf(status.getId()) == -1) {
                    System.out.println(sText);
                    ch.send(sText);
                    twitter_ids.add(status.getId());
                    bChanged = 1;
                }
            }
        } catch (TwitterException te) {
            te.printStackTrace();
            System.out.println("Failed to get timeline: " + te.getMessage());
            //System.exit(-1);
        } catch (SkypeException ex) {
            ex.printStackTrace();
            System.out.println("Failed to send message: " + ex.getMessage());
        }

        // VK
        try {
            vk();
            for (VK v : vk) {
                if (vk_ids.indexOf(v.getId()) == -1) {
                    Date d = v.getDate();
                    //   ?
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(d);
                    cal.add(Calendar.HOUR_OF_DAY, 7);
                    d = cal.getTime();
                    String sText = "@Depersonilized (VK)  " + sdf.format(d)
                            + " ( http://vk.com/Depersonilized?w=wall-0_" + v.getId() + " ): \r\n"
                            + v.getText();
                    if (!"".equals(v.getAttachment())) {
                        sText += "\r\n" + v.getAttachment();
                    }
                    sText += "\r\n***";
                    System.out.println(sText);
                    ch.send(sText);
                    vk_ids.add(v.getId());
                    bChanged = 1;
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
            System.out.println("Failed to get vk: " + e.getMessage());
            //System.exit(-1);
        } catch (SkypeException ex) {
            ex.printStackTrace();
            System.out.println("Failed to send message: " + ex.getMessage());
        }
        if (bChanged == 1) {
            save_file();
        }
        try {
            Thread.sleep(1000 * 60 * twitter_timeout);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
            System.out.println("Failed to sleep: " + ex.getMessage());
        }
    }
}

From source file:Pathway2RDFv2.java

public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException,
        ServiceException, ClassNotFoundException, IDMapperException, ParseException {

    int softwareVersion = 0;
    int schemaVersion = 0;
    int latestRevision = 0;

    BioDataSource.init();/*from  w w  w . j  a va2  s  . c  o  m*/
    Class.forName("org.bridgedb.rdb.IDMapperRdb");
    File dir = new File("/Users/andra/Downloads/bridge");
    File[] bridgeDbFiles = dir.listFiles();
    IDMapperStack mapper = new IDMapperStack();
    for (File bridgeDbFile : bridgeDbFiles) {
        System.out.println(bridgeDbFile.getAbsolutePath());
        mapper.addIDMapper("idmapper-pgdb:" + bridgeDbFile.getAbsolutePath());
    }

    Model bridgeDbmodel = ModelFactory.createDefaultModel();
    InputStream in = new FileInputStream("/tmp/BioDataSource.ttl");
    bridgeDbmodel.read(in, "", "TURTLE");

    WikiPathwaysClient client = new WikiPathwaysClient(
            new URL("http://www.wikipathways.org/wpi/webservice/webservice.php"));

    basicCalls.printMemoryStatus();

    //Map wikipathway organisms to NCBI organisms
    HashMap<String, String> organismTaxonomy = wpRelatedCalls.getOrganismsTaxonomyMapping();
    //HashMap<String, String> miriamSources = new HashMap<String, String>();
    //      HashMap<String, Str ing> miriamLinks = basicCalls.getMiriamUriBridgeDb();

    //Document wikiPathwaysDom = basicCalls.openXmlFile(args[0]);
    Document wikiPathwaysDom = basicCalls.openXmlFile("/tmp/WpGPML.xml");

    //initiate the Jena model to be populated
    Model model = ModelFactory.createDefaultModel();
    Model voidModel = ModelFactory.createDefaultModel();

    voidModel.setNsPrefix("xsd", XSD.getURI());
    voidModel.setNsPrefix("void", Void.getURI());
    voidModel.setNsPrefix("wprdf", "http://rdf.wikipathways.org/");
    voidModel.setNsPrefix("pav", Pav.getURI());
    voidModel.setNsPrefix("prov", Prov.getURI());
    voidModel.setNsPrefix("dcterms", DCTerms.getURI());
    voidModel.setNsPrefix("biopax", Biopax_level3.getURI());
    voidModel.setNsPrefix("gpml", Gpml.getURI());
    voidModel.setNsPrefix("wp", Wp.getURI());
    voidModel.setNsPrefix("foaf", FOAF.getURI());
    voidModel.setNsPrefix("hmdb", "http://identifiers.org/hmdb/");
    voidModel.setNsPrefix("freq", Freq.getURI());
    voidModel.setNsPrefix("dc", DC.getURI());
    setModelPrefix(model);

    //Populate void.ttl
    Calendar now = Calendar.getInstance();
    Literal nowLiteral = voidModel.createTypedLiteral(now);
    Literal titleLiteral = voidModel.createLiteral("WikiPathways-RDF VoID Description", "en");
    Literal descriptionLiteral = voidModel
            .createLiteral("This is the VoID description for a WikiPathwyas-RDF dataset.", "en");
    Resource voidBase = voidModel.createResource("http://rdf.wikipathways.org/");
    Resource identifiersOrg = voidModel.createResource("http://identifiers.org");
    Resource wpHomeBase = voidModel.createResource("http://www.wikipathways.org/");
    Resource authorResource = voidModel
            .createResource("http://semantics.bigcat.unimaas.nl/figshare/search_author.php?author=waagmeester");
    Resource apiResource = voidModel
            .createResource("http://www.wikipathways.org/wpi/webservice/webservice.php");
    Resource mainDatadump = voidModel.createResource("http://rdf.wikipathways.org/wpContent.ttl.gz");
    Resource license = voidModel.createResource("http://creativecommons.org/licenses/by/3.0/");
    Resource instituteResource = voidModel.createResource("http://dbpedia.org/page/Maastricht_University");
    voidBase.addProperty(RDF.type, Void.Dataset);
    voidBase.addProperty(DCTerms.title, titleLiteral);
    voidBase.addProperty(DCTerms.description, descriptionLiteral);
    voidBase.addProperty(FOAF.homepage, wpHomeBase);
    voidBase.addProperty(DCTerms.license, license);
    voidBase.addProperty(Void.uriSpace, voidBase);
    voidBase.addProperty(Void.uriSpace, identifiersOrg);
    voidBase.addProperty(Pav.importedBy, authorResource);
    voidBase.addProperty(Pav.importedFrom, apiResource);
    voidBase.addProperty(Pav.importedOn, nowLiteral);
    voidBase.addProperty(Void.dataDump, mainDatadump);
    voidBase.addProperty(Voag.frequencyOfChange, Freq.Irregular);
    voidBase.addProperty(Pav.createdBy, authorResource);
    voidBase.addProperty(Pav.createdAt, instituteResource);
    voidBase.addLiteral(Pav.createdOn, nowLiteral);
    voidBase.addProperty(DCTerms.subject, Biopax_level3.Pathway);
    voidBase.addProperty(Void.exampleResource,
            voidModel.createResource("http://identifiers.org/ncbigene/2678"));
    voidBase.addProperty(Void.exampleResource,
            voidModel.createResource("http://identifiers.org/pubmed/15215856"));
    voidBase.addProperty(Void.exampleResource,
            voidModel.createResource("http://identifiers.org/hmdb/HMDB02005"));
    voidBase.addProperty(Void.exampleResource, voidModel.createResource("http://rdf.wikipathways.org/WP15"));
    voidBase.addProperty(Void.exampleResource,
            voidModel.createResource("http://identifiers.org/obo.chebi/17242"));

    for (String organism : organismTaxonomy.values()) {
        voidBase.addProperty(DCTerms.subject,
                voidModel.createResource("http://dbpedia.org/page/" + organism.replace(" ", "_")));
    }
    voidBase.addProperty(Void.vocabulary, Biopax_level3.NAMESPACE);
    voidBase.addProperty(Void.vocabulary, voidModel.createResource(Wp.getURI()));
    voidBase.addProperty(Void.vocabulary, voidModel.createResource(Gpml.getURI()));
    voidBase.addProperty(Void.vocabulary, FOAF.NAMESPACE);
    voidBase.addProperty(Void.vocabulary, Pav.NAMESPACE);
    //Custom Properties
    String baseUri = "http://rdf.wikipathways.org/";
    NodeList pathwayElements = wikiPathwaysDom.getElementsByTagName("Pathway");

    //BioDataSource.init();
    for (int i = 0; i < pathwayElements.getLength(); i++) {
        Model pathwayModel = createPathwayModel();
        String wpId = pathwayElements.item(i).getAttributes().getNamedItem("identifier").getTextContent();
        String revision = pathwayElements.item(i).getAttributes().getNamedItem("revision").getTextContent();
        String pathwayOrganism = "";
        if (pathwayElements.item(i).getAttributes().getNamedItem("Organism") != null)
            pathwayOrganism = pathwayElements.item(i).getAttributes().getNamedItem("Organism").getTextContent()
                    .trim();
        if (Integer.valueOf(revision) > latestRevision) {
            latestRevision = Integer.valueOf(revision);
        }
        File f = new File("/tmp/" + args[0] + "/" + wpId + "_r" + revision + ".ttl");
        System.out.println(f.getName());
        if (!f.exists()) {

            Resource voidPwResource = wpRelatedCalls.addVoidTriples(voidModel, voidBase,
                    pathwayElements.item(i), client);
            Resource pwResource = wpRelatedCalls.addPathwayLevelTriple(pathwayModel, pathwayElements.item(i),
                    organismTaxonomy);

            // Get the comments
            NodeList commentElements = ((Element) pathwayElements.item(i)).getElementsByTagName("Comment");
            wpRelatedCalls.addCommentTriples(pathwayModel, pwResource, commentElements, wpId, revision);
            // Get the Groups
            NodeList groupElements = ((Element) pathwayElements.item(i)).getElementsByTagName("Group");
            for (int n = 0; n < groupElements.getLength(); n++) {
                wpRelatedCalls.addGroupTriples(pathwayModel, pwResource, groupElements.item(n), wpId, revision);
            }
            // Get all the Datanodes
            NodeList dataNodesElement = ((Element) pathwayElements.item(i)).getElementsByTagName("DataNode");
            for (int j = 0; j < dataNodesElement.getLength(); j++) {
                wpRelatedCalls.addDataNodeTriples(pathwayModel, pwResource, dataNodesElement.item(j), wpId,
                        revision, bridgeDbmodel, mapper);
            }
            // Get all the lines
            NodeList linesElement = ((Element) pathwayElements.item(i)).getElementsByTagName("Line");
            for (int k = 0; k < linesElement.getLength(); k++) {
                wpRelatedCalls.addLineTriples(pathwayModel, pwResource, linesElement.item(k), wpId, revision);
            }
            //Get all the labels
            NodeList labelsElement = ((Element) pathwayElements.item(i)).getElementsByTagName("Label");
            for (int l = 0; l < labelsElement.getLength(); l++) {
                wpRelatedCalls.addLabelTriples(pathwayModel, pwResource, labelsElement.item(l), wpId, revision);
            }
            NodeList referenceElements = ((Element) pathwayElements.item(i))
                    .getElementsByTagName("bp:PublicationXref");
            for (int m = 0; m < referenceElements.getLength(); m++) {
                wpRelatedCalls.addReferenceTriples(pathwayModel, pwResource, referenceElements.item(m), wpId,
                        revision);
            }
            NodeList referenceElements2 = ((Element) pathwayElements.item(i))
                    .getElementsByTagName("bp:publicationXref");
            for (int m = 0; m < referenceElements2.getLength(); m++) {
                wpRelatedCalls.addReferenceTriples(pathwayModel, pwResource, referenceElements2.item(m), wpId,
                        revision);
            }
            NodeList referenceElements3 = ((Element) pathwayElements.item(i))
                    .getElementsByTagName("bp:PublicationXRef");
            for (int m = 0; m < referenceElements3.getLength(); m++) {
                wpRelatedCalls.addReferenceTriples(pathwayModel, pwResource, referenceElements3.item(m), wpId,
                        revision);
            }

            NodeList ontologyElements = ((Element) pathwayElements.item(i))
                    .getElementsByTagName("bp:openControlledVocabulary");
            for (int n = 0; n < ontologyElements.getLength(); n++) {
                wpRelatedCalls.addPathwayOntologyTriples(pathwayModel, pwResource, ontologyElements.item(n));
            }
            System.out.println(wpId);
            basicCalls.saveRDF2File(pathwayModel, "/tmp/" + args[0] + "/" + wpId + "_r" + revision + ".ttl",
                    "TURTLE");

            model.add(pathwayModel);
            pathwayModel.removeAll();
        }
    }
    Date myDate = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    String myDateString = sdf.format(myDate);
    FileUtils.writeStringToFile(new File("latestVersion.txt"),
            "v" + schemaVersion + "." + softwareVersion + "." + latestRevision + "_" + myDateString);
    basicCalls.saveRDF2File(model, "/tmp/wpContent_v" + schemaVersion + "." + softwareVersion + "."
            + latestRevision + "_" + myDateString + ".ttl", "TURTLE");
    basicCalls.saveRDF2File(voidModel, "/tmp/void.ttl", "TURTLE");
}