Example usage for java.util GregorianCalendar GregorianCalendar

List of usage examples for java.util GregorianCalendar GregorianCalendar

Introduction

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

Prototype

public GregorianCalendar() 

Source Link

Document

Constructs a default GregorianCalendar using the current time in the default time zone with the default Locale.Category#FORMAT FORMAT locale.

Usage

From source file:CalendarTest.java

public static void main(String[] args) {
    // construct d as current date
    GregorianCalendar d = new GregorianCalendar();

    int today = d.get(Calendar.DAY_OF_MONTH);
    int month = d.get(Calendar.MONTH);

    // set d to start date of the month
    d.set(Calendar.DAY_OF_MONTH, 1);

    int weekday = d.get(Calendar.DAY_OF_WEEK);

    // get first day of week (Sunday in the U.S.)
    int firstDayOfWeek = d.getFirstDayOfWeek();

    // determine the required indentation for the first line
    int indent = 0;
    while (weekday != firstDayOfWeek) {
        indent++;/*ww  w. java  2  s  . com*/
        d.add(Calendar.DAY_OF_MONTH, -1);
        weekday = d.get(Calendar.DAY_OF_WEEK);
    }

    // print weekday names
    String[] weekdayNames = new DateFormatSymbols().getShortWeekdays();
    do {
        System.out.printf("%4s", weekdayNames[weekday]);
        d.add(Calendar.DAY_OF_MONTH, 1);
        weekday = d.get(Calendar.DAY_OF_WEEK);
    } while (weekday != firstDayOfWeek);
    System.out.println();

    for (int i = 1; i <= indent; i++)
        System.out.print("    ");

    d.set(Calendar.DAY_OF_MONTH, 1);
    do {
        // print day
        int day = d.get(Calendar.DAY_OF_MONTH);
        System.out.printf("%3d", day);

        // mark current day with *
        if (day == today)
            System.out.print("*");
        else
            System.out.print(" ");

        // advance d to the next day
        d.add(Calendar.DAY_OF_MONTH, 1);
        weekday = d.get(Calendar.DAY_OF_WEEK);

        // start a new line at the start of the week
        if (weekday == firstDayOfWeek)
            System.out.println();
    } while (d.get(Calendar.MONTH) == month);
    // the loop exits when d is day 1 of the next month

    // print final end of line if necessary
    if (weekday != firstDayOfWeek)
        System.out.println();
}

From source file:Logging.java

public static void main(String args[]) throws Exception {
    FileOutputStream errors = new FileOutputStream("StdErr.txt", true);
    PrintStream stderr = new PrintStream(errors);
    PrintWriter errLog = new PrintWriter(errors, true);
    System.setErr(stderr);/*from  ww  w.  j a v a 2 s  .  c o  m*/

    String query = "SELECT Name,Description,Qty,Cost,Sell_Price FROM Stock";

    try {
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        Connection con = DriverManager.getConnection("jdbc:odbc:Inventory");
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        while (rs.next()) {
            String name = rs.getString("Name");
            String desc = rs.getString("Description");
            int qty = rs.getInt("Qty");
            float cost = rs.getFloat("Cost");
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace(errLog);
    } catch (SQLException e) {
        System.err.println((new GregorianCalendar()).getTime());
        System.err.println("Thread: " + Thread.currentThread());
        System.err.println("ErrorCode: " + e.getErrorCode());
        System.err.println("SQLState:  " + e.getSQLState());
        System.err.println("Message:   " + e.getMessage());
        System.err.println("NextException: " + e.getNextException());
        e.printStackTrace(errLog);
        System.err.println();
    }
    stderr.close();
}

From source file:com.discursive.jccook.lang.builders.reflect.PoliticalCandidate.java

public static void main(String[] args) {
    // START lang-ex-sample-1
    // Create a State
    State va = new State("VA", "Virginia");

    // Create a Birth Date
    Calendar calendar = new GregorianCalendar();
    calendar.set(Calendar.YEAR, 1743);
    calendar.set(Calendar.MONTH, Calendar.APRIL);
    calendar.set(Calendar.DAY_OF_MONTH, 13);
    Date dob = calendar.getTime();

    BigDecimal moneyRaised = new BigDecimal(293829292.93);

    // Create a Political Candidate
    PoliticalCandidate candidate = new PoliticalCandidate("Jefferson", "Thomas", dob, moneyRaised, va);

    System.out.println(candidate);
    // END lang-ex-sample-1
}

From source file:com.discursive.jccook.lang.builders.customized.PoliticalCandidate.java

public static void main(String[] args) {
    // Create a State
    State va = new State("VA", "Virginia");

    // Create a Birth Date
    Calendar calendar = new GregorianCalendar();
    calendar.set(Calendar.YEAR, 1743);
    calendar.set(Calendar.MONTH, Calendar.APRIL);
    calendar.set(Calendar.DAY_OF_MONTH, 13);
    Date dob = calendar.getTime();

    BigDecimal moneyRaised = new BigDecimal(293829292.93);

    // Create a Political Candidate
    PoliticalCandidate candidate = new PoliticalCandidate("Jefferson", "Thomas", dob, moneyRaised, va);

    System.out.println(candidate);
}

From source file:camera.Camera.java

/**
 * @param args the command line arguments
 *///from  ww  w. j  a  v a  2 s.c  o  m
public static void main(String[] args) throws Exception {
    System.out.println("start compass.");
    //   Compass c = new Compass();
    //   c.start();
    System.out.println("start camera.");
    Camera cam = new Camera();
    cam.snapshot();
    // regelmssig zu festen Sekunden Foto schiessen. Thread.
    int phase;
    int lastPhase = -1;
    while (true) {
        Calendar cal = new GregorianCalendar();
        int stunde = cal.get(Calendar.HOUR_OF_DAY);
        int STUNDE_VON = 7;
        int STUNDE_BIS = 23;
        if ((stunde < STUNDE_VON) || (stunde > STUNDE_BIS)) {
            Thread.sleep(1000);
            continue;
        }
        // regelmssig Fotos
        int sekunde = cal.get(Calendar.SECOND);
        phase = sekunde / 10; // alle 10 sekunden wechsel  jede volle zehner wechselt
        //phase = phase % 4; // 4 phasen wenn ma unterteilen wollte

        if (phase == lastPhase) {
            //    Thread.sleep(300);
            //      continue;
        }
        lastPhase = phase;
        // zeit fr ein Foto.
        cam.snapshot();

    }
}

From source file:ScheduleCampaign.java

public static void main(String[] args) {
    System.out.println("Executing Schedule Campaign");
    try {//from ww w  .  j  a va 2s.com
        URL marketoSoapEndPoint = new URL("CHANGE ME" + "?WSDL");
        String marketoUserId = "CHANGE ME";
        String marketoSecretKey = "CHANGE ME";

        QName serviceName = new QName("http://www.marketo.com/mktows/", "MktMktowsApiService");
        MktMktowsApiService service = new MktMktowsApiService(marketoSoapEndPoint, serviceName);
        MktowsPort port = service.getMktowsApiSoapPort();

        // Create Signature
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        String text = df.format(new Date());
        String requestTimestamp = text.substring(0, 22) + ":" + text.substring(22);
        String encryptString = requestTimestamp + marketoUserId;

        SecretKeySpec secretKey = new SecretKeySpec(marketoSecretKey.getBytes(), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(secretKey);
        byte[] rawHmac = mac.doFinal(encryptString.getBytes());
        char[] hexChars = Hex.encodeHex(rawHmac);
        String signature = new String(hexChars);

        // Set Authentication Header
        AuthenticationHeader header = new AuthenticationHeader();
        header.setMktowsUserId(marketoUserId);
        header.setRequestTimestamp(requestTimestamp);
        header.setRequestSignature(signature);

        // Create Request
        ParamsScheduleCampaign request = new ParamsScheduleCampaign();

        request.setProgramName("Trav-Demo-Program");
        request.setCampaignName("Batch Campaign Example");

        // Create setCampaignRunAt timestamp
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTimeInMillis(new Date().getTime());

        DatatypeFactory factory = DatatypeFactory.newInstance();
        ObjectFactory objectFactory = new ObjectFactory();
        JAXBElement<XMLGregorianCalendar> setCampaignRunAtValue = objectFactory
                .createParamsScheduleCampaignCampaignRunAt(factory.newXMLGregorianCalendar(gc));
        request.setCampaignRunAt(setCampaignRunAtValue);

        request.setCloneToProgramName("TestProgramCloneFromSOAP");

        ArrayOfAttrib aoa = new ArrayOfAttrib();

        Attrib attrib = new Attrib();
        attrib.setName("{{my.message}}");
        attrib.setValue("Updated message");

        aoa.getAttribs().add(attrib);

        JAXBElement<ArrayOfAttrib> arrayOfAttrib = objectFactory
                .createParamsScheduleCampaignProgramTokenList(aoa);
        request.setProgramTokenList(arrayOfAttrib);

        SuccessScheduleCampaign result = port.scheduleCampaign(request, header);

        JAXBContext context = JAXBContext.newInstance(SuccessScheduleCampaign.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.marshal(result, System.out);

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

From source file:GetLeadChanges.java

public static void main(String[] args) {
    System.out.println("Executing Get Lead Changes");
    try {//  www.j a  v a 2 s.  c  om
        URL marketoSoapEndPoint = new URL("CHANGE ME" + "?WSDL");
        String marketoUserId = "CHANGE ME";
        String marketoSecretKey = "CHANGE ME";

        QName serviceName = new QName("http://www.marketo.com/mktows/", "MktMktowsApiService");
        MktMktowsApiService service = new MktMktowsApiService(marketoSoapEndPoint, serviceName);
        MktowsPort port = service.getMktowsApiSoapPort();

        // Create Signature
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        String text = df.format(new Date());
        String requestTimestamp = text.substring(0, 22) + ":" + text.substring(22);
        String encryptString = requestTimestamp + marketoUserId;

        SecretKeySpec secretKey = new SecretKeySpec(marketoSecretKey.getBytes(), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(secretKey);
        byte[] rawHmac = mac.doFinal(encryptString.getBytes());
        char[] hexChars = Hex.encodeHex(rawHmac);
        String signature = new String(hexChars);

        // Set Authentication Header
        AuthenticationHeader header = new AuthenticationHeader();
        header.setMktowsUserId(marketoUserId);
        header.setRequestTimestamp(requestTimestamp);
        header.setRequestSignature(signature);

        // Create Request
        ParamsGetLeadChanges request = new ParamsGetLeadChanges();

        ObjectFactory objectFactory = new ObjectFactory();
        JAXBElement<Integer> batchSize = objectFactory.createParamsGetLeadActivityBatchSize(10);
        request.setBatchSize(batchSize);

        ArrayOfString activities = new ArrayOfString();
        activities.getStringItems().add("Visit Webpage");
        activities.getStringItems().add("Click Link");

        JAXBElement<ArrayOfString> activityFilter = objectFactory
                .createParamsGetLeadChangesActivityNameFilter(activities);
        request.setActivityNameFilter(activityFilter);

        // Create oldestCreateAt timestamp from 5 days ago
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTimeInMillis(new Date().getTime());
        gc.add(GregorianCalendar.DAY_OF_YEAR, -5);

        DatatypeFactory factory = DatatypeFactory.newInstance();
        JAXBElement<XMLGregorianCalendar> oldestCreateAtValue = objectFactory
                .createStreamPositionOldestCreatedAt(factory.newXMLGregorianCalendar(gc));

        StreamPosition sp = new StreamPosition();
        sp.setOldestCreatedAt(oldestCreateAtValue);
        request.setStartPosition(sp);

        SuccessGetLeadChanges result = port.getLeadChanges(request, header);

        JAXBContext context = JAXBContext.newInstance(SuccessGetLeadChanges.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.marshal(result, System.out);

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

From source file:org.openplans.delayfeeder.LoadFeeds.java

public static void main(String args[]) throws HibernateException, IOException {
    if (args.length != 1) {
        System.out.println("expected one argument: the path to a csv of agency,route,url");
    }/*  ww w .ja  va 2s.  c o m*/
    GenericApplicationContext context = new GenericApplicationContext();
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(context);
    xmlReader.loadBeanDefinitions("org/openplans/delayfeeder/application-context.xml");
    xmlReader.loadBeanDefinitions("data-sources.xml");

    SessionFactory sessionFactory = (SessionFactory) context.getBean("sessionFactory");

    Session session = sessionFactory.getCurrentSession();
    Transaction tx = session.beginTransaction();

    FileReader fileReader = new FileReader(new File(args[0]));
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    while (bufferedReader.ready()) {
        String line = bufferedReader.readLine().trim();
        if (line.startsWith("#")) {
            continue;
        }
        if (line.length() < 3) {
            //blank or otherwise broken line
            continue;
        }

        String[] parts = line.split(",");
        String agency = parts[0];
        String route = parts[1];
        String url = parts[2];
        Query query = session.createQuery("from RouteFeed where agency = :agency and route = :route");
        query.setParameter("agency", agency);
        query.setParameter("route", route);
        @SuppressWarnings("rawtypes")
        List list = query.list();
        RouteFeed feed;
        if (list.size() == 0) {
            feed = new RouteFeed();
            feed.agency = agency;
            feed.route = route;
            feed.lastEntry = new GregorianCalendar();
        } else {
            feed = (RouteFeed) list.get(0);
        }
        if (!url.equals(feed.url)) {
            feed.url = url;
            feed.lastEntry.setTimeInMillis(0);
        }
        session.saveOrUpdate(feed);
    }
    tx.commit();
}

From source file:Easter.java

/** Main program, when used as a standalone application */
public static void main(String[] argv) {

    if (argv.length == 0) {
        int thisYear = new GregorianCalendar().get(Calendar.YEAR);
        Calendar c = Easter.findHolyDay(thisYear);
        System.out.println(c.getTime());
    } else// w w w.j  av a 2s.co  m
        for (int i = 0; i < argv.length; i++) {
            int year = 0;
            try {
                year = Integer.parseInt(argv[i]);
                System.out.println(Easter.findHolyDay(year).getTime());
            } catch (IllegalArgumentException e) {
                System.err.println("Year " + argv[i] + " invalid (" + e.getMessage() + ").");
            }
        }
}

From source file:edu.lternet.pasta.portal.statistics.GrowthStats.java

public static void main(String[] args) {

    ConfigurationListener.configure();/*from  www  .  jav  a2  s  .co  m*/
    GregorianCalendar now = new GregorianCalendar();

    GrowthStats gs = new GrowthStats();
    System.out.print(gs.getGoogleChartJson(now, Calendar.MONTH));

}