Example usage for java.util Calendar getInstance

List of usage examples for java.util Calendar getInstance

Introduction

In this page you can find the example usage for java.util Calendar getInstance.

Prototype

public static Calendar getInstance() 

Source Link

Document

Gets a calendar using the default time zone and locale.

Usage

From source file:ArrayToVector.java

public static void main(String[] args) {
    Object[] a1d = { "Hello World", new Date(), Calendar.getInstance(), };
    // Arrays.asList(Object[]) --> List
    List l = Arrays.asList(a1d);

    // Vector contstructor takes Collection
    // List is a subclass of Collection
    Vector v;//from w  ww. j  a v a2 s .c om
    v = new Vector(l);

    // Or, more simply:
    v = new Vector(Arrays.asList(a1d));

    // Just to prove that it worked.
    Enumeration e = v.elements();
    while (e.hasMoreElements()) {
        System.out.println(e.nextElement());
    }
}

From source file:com.rmzone.core.App.java

public static void main(String[] args) {
    // set up mongo
    ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig.class);
    MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");

    // create and save some users
    List<User> users = new ArrayList<User>();
    users.add(new User("1001", "foo", "bar"));
    users.add(new User("1002", "mickey", "mouse"));

    for (User user : users)
        mongoOperation.save("users", user);

    // create and save some documents
    Tire tire = new Tire("Michelin", "Alpine", 1, users.get(0), Calendar.getInstance().getTime(), 14, 12, 3);
    mongoOperation.save("documents", tire);

    Engine engine = new Engine("Model T", "Wow", 1, users.get(0), Calendar.getInstance().getTime());
    engine.setHorsePower(16.4f);/*ww w.  j av a2  s  .co  m*/
    mongoOperation.save("documents", engine);

    Car car = new Car("Pinto", "don't touch me!", 1, users.get(0), Calendar.getInstance().getTime());
    car.setMake("Ford");
    car.setColor("Blue");
    car.setEngine(engine);

    // sorry not very elegant
    car.setTires(new ArrayList<Tire>());
    for (int i = 0; i < 4; i++)
        car.getTires().add(tire);
    mongoOperation.save("documents", car);

    // dump all the data        
    List<User> listUser = mongoOperation.getCollection("users", User.class);
    System.out.println("Number of users = " + listUser.size());
    for (User user : listUser)
        System.out.println(user.toString());

    List<DocumentMaster> listDocument = mongoOperation.getCollection("documents", DocumentMaster.class);
    System.out.println("Number of documents = " + listDocument.size());
    for (DocumentMaster document1 : listDocument)
        System.out.println(document1.toString());

    // delete everything
    mongoOperation.dropCollection("users");
    mongoOperation.dropCollection("documents");
}

From source file:bookChapter.theoretical.AnalyzeTheoreticalMSMSCalculation.java

/**
 *
 * @param args// ww  w . ja v a  2  s.c  om
 * @throws IOException
 * @throws FileNotFoundException
 * @throws ClassNotFoundException
 * @throws InterruptedException
 * @throws MzMLUnmarshallerException
 */
public static void main(String[] args) throws IOException, FileNotFoundException, ClassNotFoundException,
        IOException, InterruptedException, MzMLUnmarshallerException {
    Logger l = Logger.getLogger("AnalyzeTheoreticalMSMSCalculation");
    Date date = Calendar.getInstance().getTime();
    DateFormat formatter = new SimpleDateFormat("EEEE, dd MMMM yyyy, hh:mm:ss.SSS a");
    String now = formatter.format(date);
    l.log(Level.INFO, "Calculation starts at {0}", now);
    double precursorTolerance = ConfigHolder.getInstance().getDouble("precursor.tolerance"),
            fragmentTolerance = ConfigHolder.getInstance().getDouble("fragment.tolerance");
    String databaseName = ConfigHolder.getInstance().getString("database.name"),
            spectraName = ConfigHolder.getInstance().getString("spectra.name"),
            output = ConfigHolder.getInstance().getString("output");
    int correctionFactor = ConfigHolder.getInstance().getInt("correctionFactor");
    boolean theoFromAllCharges = ConfigHolder.getInstance().getBoolean("hasAllPossCharge");
    BufferedWriter bw = new BufferedWriter(new FileWriter(output));
    bw.write("SpectrumTitle" + "\t" + "PrecursorMZ" + "\t" + "PrecursorCharge" + "\t" + "Observed Mass (M+H)"
            + "\t" + "AndromedaLikeScore" + "\t" + "SequestLikeScore" + "\t" + "PeptideByAndromedaLikeScore"
            + "\t" + "PeptideBySequestLikeScore" + "\t" + "LevenshteinDistance" + "\t" + "TotalScoredPeps"
            + "\t" + "isCorrectMatchByAndromedaLike" + "\t" + "isCorrectMatchBySequestLikeScore" + "\n");
    l.info("Getting database entries");
    // first load all sequences into the memory 
    HashSet<DBEntry> dbEntries = getDBEntries(databaseName);
    // for every spectrum-calculate both score...
    // now convert to binExperimental spectrum
    int num = 0;
    SpectrumFactory fct = SpectrumFactory.getInstance();
    num = 0;
    File f = new File(spectraName);
    if (spectraName.endsWith(".mgf")) {
        fct.addSpectra(f, new WaitingHandlerCLIImpl());
        l.log(Level.INFO, "Spectra scoring starts at {0}", now);
        for (String title : fct.getSpectrumTitles(f.getName())) {
            num++;
            MSnSpectrum ms = (MSnSpectrum) fct.getSpectrum(f.getName(), title);
            // here calculate all except this is an empty spectrum...
            if (ms.getPeakList().size() > 2) {
                // to check a spectrum with negative values..
                String text = result(ms, precursorTolerance, dbEntries, fragmentTolerance, correctionFactor,
                        theoFromAllCharges);
                if (!text.isEmpty()) {
                    bw.write(text);
                }
            }
            if (num % 500 == 0) {
                l.info("Running " + num + " spectra." + Calendar.getInstance().getTime());
            }
        }
    }
    l.info("Program finished at " + Calendar.getInstance().getTime());

    bw.close();
}

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  www .j  a  va 2s.  c  o m
    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: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;/* w w  w .j a va 2 s  .  co 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:fr.itinerennes.bundler.integration.onebusaway.GenerateStaticObaApiResults.java

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

    final String url = args[0];
    final String key = args[1];
    final String gtfsFile = args[2];
    final String out = args[3].replaceAll("/$", "");

    final Map<String, String> agencyMapping = new HashMap<String, String>();
    agencyMapping.put("1", "2");
    final GtfsDao gtfs = GtfsUtils.load(new File(gtfsFile), agencyMapping);

    oba = new JsonOneBusAwayClient(new DefaultHttpClient(), url, key);
    gson = OneBusAwayGsonFactory.newInstance(true);

    final Calendar end = Calendar.getInstance();
    end.set(2013, 11, 22, 0, 0);//from  w  ww .ja  va  2 s .c  om

    final Calendar start = Calendar.getInstance();
    start.set(2013, 10, 4, 0, 0);

    final Calendar current = Calendar.getInstance();
    current.setTime(start.getTime());

    while (current.before(end) || current.equals(end)) {
        System.out.println(current.getTime());
        for (final Stop stop : gtfs.getAllStops()) {
            final String stopId = stop.getId().toString();
            final String dateDir = String.format("%04d/%02d/%02d", current.get(Calendar.YEAR),
                    current.get(Calendar.MONTH) + 1, current.get(Calendar.DAY_OF_MONTH));
            final String methodDir = String.format("%s/schedule-for-stop", out);

            final File outDir = new File(String.format("%s/%s", methodDir, dateDir));
            outDir.mkdirs();
            final File f = new File(outDir, String.format("%s.json", stopId));

            final StopSchedule ss = oba.getScheduleForStop(stopId, current.getTime());
            final String json = gson.toJson(ss);

            final Writer w = new PrintWriter(f);
            w.write(json);
            w.close();
        }
        current.add(Calendar.DAY_OF_MONTH, 1);
    }

    final File outDir = new File(String.format("%s/trip-details", out));
    outDir.mkdirs();
    for (final Trip trip : gtfs.getAllTrips()) {
        final String tripId = trip.getId().toString();
        final File f = new File(outDir, String.format("%s.json", tripId));

        final TripSchedule ts = oba.getTripDetails(tripId);
        final String json = gson.toJson(ts);

        final Writer w = new PrintWriter(f);
        w.write(json);
        w.close();
    }
}

From source file:com.ebay.maven.cli.CliWrapper.java

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

    long begin = Calendar.getInstance().getTimeInMillis();

    CliWrapper wrapper = new CliWrapper();
    InputParams input = wrapper.processCliArguments(args);

    wrapper.process(input);/* w w w .j av  a 2s  .  c  o m*/

    long end = Calendar.getInstance().getTimeInMillis();
    long diff = end - begin;
    System.out.println("Time taken " + diff + " ms");
}

From source file:FormatterDates.java

public static void main(String[] args) {

    // Format number as dates e.g., 2004-06-28
    System.out.printf("%1$4d-%2$02d-%3$2d%n", 2004, 6, 28);

    // Format fields directly from a Date object: multiple fields from "1$"
    // (hard-coded formatting for Date not advisable; see I18N chapter)
    Date today = Calendar.getInstance().getTime();
    System.out.printf("Today is %1$tB %1$td, %1$tY%n", today); // e.g., July
    // 4, 2004//  w w w  .  j  a v  a  2  s. c o m
}

From source file:org.lieuofs.extraction.commune.mutation.ExtracteurMutation.java

public static void main(String[] args) throws IOException {
    ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "beans_extraction.xml" });
    ExtracteurMutation extracteur = (ExtracteurMutation) context.getBean("extracteurMutation");
    Calendar cal = Calendar.getInstance();
    cal.set(2013, Calendar.JANUARY, 1);
    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream("MutationCommune2013.txt"), "Windows-1252"));
    extracteur.extraireMutation(cal.getTime(), writer);
}

From source file:com.isoftstone.proxy.Program.java

public static void main(String[] args) throws IOException {
    int insertIntervalTime = Integer.valueOf(Config.getValue("proxy_insert_minutes"));
    int checkIntervalTime = Integer.valueOf(Config.getValue("proxy_check_minute"));
    SchedulerFactory sf = new StdSchedulerFactory();
    Scheduler sched;/*from  w w  w.  j a  v a  2 s  . com*/
    try {
        sched = sf.getScheduler();

        // ????
        JobDetail parseProxyJob = JobBuilder.newJob(ParseProxyJob.class).withIdentity("parseProxyJob", "Group")
                .build();

        SimpleTrigger parseProxyTrigger = (SimpleTrigger) TriggerBuilder
                .newTrigger().withIdentity("parseProxyJob", "Group").withSchedule(SimpleScheduleBuilder
                        .simpleSchedule().withIntervalInMinutes(insertIntervalTime).repeatForever())
                .startAt(new Date()).build();

        sched.scheduleJob(parseProxyJob, parseProxyTrigger);

        // ??
        JobDetail checkProxyJob = JobBuilder.newJob(CheckProxyJob.class).withIdentity("checkProxyJob", "Group")
                .build();

        /**
         * 10s?.
         */
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND, 10);

        SimpleTrigger checkProxyTrigger = (SimpleTrigger) TriggerBuilder.newTrigger()
                .withIdentity("checkProxyJob", "Group").withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        .withIntervalInMinutes(checkIntervalTime).repeatForever())
                .startAt(calendar.getTime()).build();

        sched.scheduleJob(checkProxyJob, checkProxyTrigger);

        sched.start();

        String uriHost = Config.getValue("http_server_host");
        URI baseUri = UriBuilder.fromUri(uriHost).port(9998).build();
        ResourceConfig config = new ResourceConfig(HttpProxyServer.class);
        HttpServer server = GrizzlyHttpServerFactory.createHttpServer(baseUri, config);

    } catch (SchedulerException e) {
        LOG.error("SchedulerException", e);
    }
}