Example usage for java.util GregorianCalendar get

List of usage examples for java.util GregorianCalendar get

Introduction

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

Prototype

public int get(int field) 

Source Link

Document

Returns the value of the given calendar field.

Usage

From source file:de.ribeiro.android.gso.core.UntisProvider.java

/**
 * Synchronisiert alle verfgbaren WeekDatas im Stupid
 *
 * @param logger/* w  w w  .j  a v a  2  s  .  c  o m*/
 * @param selectedStringDate
 * @param selectedElement
 * @param myType
 * @param htmlResponse
 * @param stupid
 * @return
 * @throws Exception
 */
public static List<ICalEvent> syncWeekData(GregorianCalendar gc, String selectedElement, Type myType,
        HtmlResponse htmlResponse, Stupid stupid) throws Exception {

    List<ICalEvent> result = new ArrayList<ICalEvent>();

    int currentDayOfWeek = gc.get(Calendar.DAY_OF_WEEK);
    // den currentDay auf den folge Montag setzen
    if (currentDayOfWeek < 2) {
        // 1000*60*60*24 = 1 Tag!
        gc.setTimeInMillis(gc.getTimeInMillis() + (1000 * 60 * 60 * 24 * (2 - currentDayOfWeek)));
    }
    if (currentDayOfWeek > 6) {
        // 1000*60*60*24 = 1 Tag!
        gc.setTimeInMillis(gc.getTimeInMillis() + (1000 * 60 * 60 * 24 * 2));
    }

    String date = ConvertToStupidDateString(gc);

    String selectedType = myType.type;
    String selectedClassIndex = getIndexOfSelectorValue(myType.elementList, selectedElement);
    if (selectedClassIndex == "-1" || selectedType.equalsIgnoreCase("")) {
        throw new Exception(selectedElement + " kann nicht synchronisiert werden! " + selectedElement
                + " wurde nicht in der Liste der verfgbaren Elemente gefunden!");
    }
    while (selectedClassIndex.length() < 3) {
        selectedClassIndex = "0" + selectedClassIndex;
    }

    WeekData weekData = new WeekData(stupid);
    try {

        // URL setzten
        URL url = new URL(
                "https://webuntis.stadt-koeln.de/WebUntis/Ical.do?school=K175055&ajaxCommand=renderTimetable&rpt_sd="
                        + date + "&type=" + 1 + "&elemId=" + selectedClassIndex + "&elemType=" + selectedType);

        htmlResponse.dataReceived = false;

        htmlResponse.xmlContent = XmlOPs.readFromURL(url, Const.CONNECTIONTIMEOUT);

        if (htmlResponse.xmlContent.length() < 50) {
            // ende
            return null;
        }

        _logger.Info("Week downloaded!");
        List<ICalEvent> events = Ical.Parse(htmlResponse.xmlContent);

        weekData.syncTime = new GregorianCalendar().getTimeInMillis();
        weekData.addParameter("syncTime", String.valueOf(weekData.syncTime));
        weekData.date = (Calendar) gc.clone();
        weekData.elementId = selectedElement;
        weekData.addParameter("classId", selectedElement);
        weekData.events = events;
        weekData.weekId = String.valueOf(gc.get(Calendar.WEEK_OF_YEAR));
        weekData.addParameter("weekId", weekData.weekId);
        weekData.typeId = myType.type;
        weekData.addParameter("typeId", weekData.typeId);
        weekData.weekDataVersion = "2";
        weekData.addParameter("weekDataVersion", weekData.weekDataVersion);
        // stupid.stupidData.add(wd);

    } catch (Exception e) {
        throw e;
    }

    // prfen, ob bereits die Woche fr die Klasse und den typ vorliegt:

    WeekData existWeekData = null;
    // alle bestehden Wochen abrufen:
    for (int y = 0; y < stupid.stupidData.size(); y++) {
        existWeekData = stupid.stupidData.get(y);
        // prfen, ob das bestehende Element, dem neu hinzuzufgenden
        // entspricht(klasse,KW,Typ)
        if (existWeekData.elementId.equalsIgnoreCase(weekData.elementId)
                && existWeekData.weekId.equalsIgnoreCase(weekData.weekId)
                && existWeekData.typeId.equalsIgnoreCase(weekData.typeId)) {
            // ja,es ist eine gleiche Woche bereits vorhanden
            // jedes event der neuen woche prfen, ob dieses schon existiert
            for (int ev = 0; ev < weekData.events.size(); ev++) {
                ICalEvent newevent = weekData.events.get(ev);
                // die schulstunde vom neuen event heraussuchen
                int schulstunde = GetSchulstundeOfEvent(newevent);
                // damit die schulstunde vom bestenden stundeplan abrufen
                ICalEvent existingevent = GetSchulstunde(existWeekData,
                        newevent.DTSTART.get(Calendar.DAY_OF_WEEK), schulstunde);
                if (existingevent != null)
                    newevent.UID = existingevent.UID;
                // beide schulstunden vergleichen
                if (compareEvents(existingevent, newevent)) {
                    // unterschiede gefunden
                    newevent.UID = "diff";
                    if (existingevent == null)
                        _logger.Info("Es wurden Unterschiede in den Events gefunden: Neues Event "
                                + newevent.DESCRIPTION + " , " + newevent.SUMMARY
                                + " , kein altes Event vorhanden!");
                    else {
                        _logger.Info("Es wurden Unterschiede in den Events gefunden: Neues Event "
                                + newevent.DESCRIPTION + " , " + newevent.SUMMARY + " , Altes Event "
                                + existingevent.DESCRIPTION + " , " + existingevent.SUMMARY);
                    }
                    // ber unterschiede benachrichtigen
                    result.add(newevent);
                }
                // das existierende event aus dem datensatz lschen
                existWeekData.events.remove(existingevent);
            }
            for (ICalEvent event : existWeekData.events) {
                event.UID = "deleted";
                weekData.events.add(event);
            }
            // alle verbleibenden events aus dem existierenden datensatz
            // sind ausgefallene stunden

            // existiert schon...ersetzen
            weekData.isDirty = true;
            stupid.stupidData.set(y, weekData);
            return SummarizeChanges(result);
        }
    }

    stupid.stupidData.add(weekData); // fgt die geparste Woche den
    // // Hauptdaten
    // // hinzu
    stupid.sort();
    return SummarizeChanges(result);
}

From source file:op.tools.SYSCalendar.java

/**
 * Setzt die Zeitkomponente eines GregorianCalendars. Das heisst ganz einfach,
 * wenn man ein Datum hat (in einem GC) und in einem anderen GC steht die Uhrzeit, dann
 * fgt diese Methode die beiden Komponenten zu einem Datum und Uhrzeit Wert zusammen
 * und gibt diesen zurck./*  w  w w . ja v a  2 s.  c  o  m*/
 *
 * @param date - Datumsanteil
 * @param time - Uhrzeitanzeil
 * @return Datum und Uhrzeit kombiniert.
 */
public static GregorianCalendar addTime2Date(GregorianCalendar date, GregorianCalendar time) {
    date.set(GregorianCalendar.HOUR_OF_DAY, time.get(GregorianCalendar.HOUR_OF_DAY));
    date.set(GregorianCalendar.MINUTE, time.get(GregorianCalendar.MINUTE));
    date.set(GregorianCalendar.SECOND, time.get(GregorianCalendar.SECOND));
    date.set(GregorianCalendar.MILLISECOND, time.get(GregorianCalendar.MILLISECOND));
    return (GregorianCalendar) date.clone();
}

From source file:op.tools.SYSCalendar.java

public static GregorianCalendar setDate2Time(GregorianCalendar source, GregorianCalendar target) {
    target.set(GregorianCalendar.DATE, source.get(GregorianCalendar.DATE));
    target.set(GregorianCalendar.MONTH, source.get(GregorianCalendar.MONTH));
    target.set(GregorianCalendar.YEAR, source.get(GregorianCalendar.YEAR));
    return (GregorianCalendar) target.clone();
}

From source file:org.apache.eagle.jpm.mr.history.crawler.JHFCrawlerDriverImpl.java

private boolean isToday() {
    GregorianCalendar today = new GregorianCalendar(timeZone);

    if (today.get(Calendar.YEAR) == this.processDate.year && today.get(Calendar.MONTH) == this.processDate.month
            && today.get(Calendar.DAY_OF_MONTH) == this.processDate.day) {
        return true;
    }/*w w w. j  a  v a2 s  .  c om*/
    return false;
}

From source file:no.dusken.aranea.web.control.HeaderController.java

@RequestMapping("/header.do")
public String handleHeaderMenu(
        @RequestParam(value = "section", required = false, defaultValue = "") String sectionUrl,
        @RequestParam(value = "subsection", required = false, defaultValue = "") String subSectionUrl,
        Model model) {//from www. jav a 2 s.  c om

    Section section = sectionService.getSectionByUrl(sectionUrl, null);
    model.addAttribute("selectedSection", section);

    if (subSectionUrl != null && !subSectionUrl.equals("")) {
        Section subsection = sectionService.getSectionByUrl(subSectionUrl, section);
        model.addAttribute("selectedSubsection", subsection);
    }

    if (section != null) {
        List<Section> children = section.getActiveChildren();
        if (children != null && children.size() > 0) {
            model.addAttribute("children", children);
        }
    }

    GregorianCalendar now = new GregorianCalendar();
    model.addAttribute("now", now);
    List<Section> sections = sectionService.getTopLevelSections(false);
    model.addAttribute("sections", sections);
    model.addAttribute("years", now.get(Calendar.YEAR) - 1914);
    return "no/dusken/aranea/base/web/header/view";
}

From source file:Controllers.CompteController.java

@RequestMapping(value = "validation", method = RequestMethod.POST)
public ModelAndView inscription(HttpServletRequest request, HttpServletResponse response) throws Exception {

    // Cration du modelAndView de la page de connexion
    ModelAndView mv = new ModelAndView("connexion");

    // Rcupration des donnes
    String result;//from w  w w .  j a v  a 2  s  .c o  m
    String nom = request.getParameter("nom");
    String prenom = request.getParameter("prenom");
    String login = request.getParameter("login");
    String password = request.getParameter("password");
    String mail = request.getParameter("mail");
    String age = request.getParameter("ddn");

    // Vrification de la validit des donnes
    if (login.isEmpty() || password.isEmpty() || mail.isEmpty() || nom.isEmpty() || prenom.isEmpty()) {
        // Si les champs sont mal remplis, 
        // on raffiche la page d'inscription
        mv = new ModelAndView("inscription");
        result = "Veuillez renseigner tous les champs...";
        mv.addObject("inscriptionMessage", result);
        return mv;
    }

    // Calcul de l'age de la personne
    Integer ageInscription = null;
    if (age != null && age.length() != 0) {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");

        // A faire : Vrification des paramtres.
        GregorianCalendar gcBirth = new GregorianCalendar(Integer.parseInt(age.split("/")[2]),
                Integer.parseInt(age.split("/")[1]) - 1, Integer.parseInt(age.split("/")[0]));

        GregorianCalendar now = new GregorianCalendar();

        long diff = now.getTimeInMillis() - gcBirth.getTimeInMillis();

        ageInscription = now.get(Calendar.YEAR) - gcBirth.get(Calendar.YEAR);
    }

    // Gestion des doublons
    if (profilService.exists(login)) {
        mv = new ModelAndView("inscription");
        result = "Le login " + login + " existe dj! veuillez le changer";
        mv.addObject("inscriptionMessage", result);
        return mv;

    } else { // Ajout de la personne
        inscriptionService.add(nom, prenom, login, password, mail, ageInscription);
        result = "Vous vous tes bien inscrit, veuillez vous connecter";
        mv.addObject("inscriptionMessage", result);
        return mv;
    }
}

From source file:op.tools.SYSCalendar.java

public static Date parseDate(String input) throws NumberFormatException {
    if (input == null || input.equals("")) {
        throw new NumberFormatException("empty");
    }//  w  w  w.ja v  a 2 s  . c o  m
    if (input.indexOf(".") + input.indexOf(",") + input.indexOf("-") + input.indexOf("/") == -4) {
        input += "."; // er war zu faul auch nur einen punkt anzuhngen.
    }
    StringTokenizer st = new StringTokenizer(input, "/,.-");
    if (st.countTokens() == 1) { // Vielleicht fehlen ja nur die Monats- und Jahresangaben. Dann hngen wir sie einach an.
        input += (SYSCalendar.today().get(GregorianCalendar.MONTH) + 1) + "."
                + SYSCalendar.today().get(GregorianCalendar.YEAR);
        st = new StringTokenizer(input, "/,.-"); // dann nochmal aufteilen...
    }
    if (st.countTokens() == 2) { // Vielleicht fehlt ja nur die Jahresangabe. Dann hngen wir es einfach an.

        if (!input.trim().substring(input.length() - 1).equals(".")
                && !input.trim().substring(input.length() - 1).equals(",")) {
            input += "."; // er war zu faul den letzten Punkt anzuhngen.
        }
        input += SYSCalendar.today().get(GregorianCalendar.YEAR);
        st = new StringTokenizer(input, "/,.-"); // dann nochmal aufteilen...
    }
    if (st.countTokens() != 3) {
        throw new NumberFormatException("wrong format");
    }
    String sTag = st.nextToken();
    String sMonat = st.nextToken();
    String sJahr = st.nextToken();
    int tag, monat, jahr;

    // Year 2010 Problem
    GregorianCalendar now = new GregorianCalendar();
    int decade = (now.get(GregorianCalendar.YEAR) / 10) * 10;
    int century = (now.get(GregorianCalendar.YEAR) / 100) * 100;

    try {
        tag = Integer.parseInt(sTag);
    } catch (NumberFormatException nfe) {
        throw new NumberFormatException("day");
    }
    try {
        monat = Integer.parseInt(sMonat);
    } catch (NumberFormatException nfe) {
        throw new NumberFormatException("month");
    }
    try {
        jahr = Integer.parseInt(sJahr);
    } catch (NumberFormatException nfe) {
        throw new NumberFormatException("year");
    }

    if (jahr < 0) {
        throw new NumberFormatException("year");
    }
    if (jahr > 9999) {
        throw new NumberFormatException("year");
    }
    if (jahr < 10) {
        jahr += decade;
    }
    if (jahr < 100) {
        jahr += century;
    }
    if (monat < 1 || monat > 12) {
        throw new NumberFormatException("month");
    }

    if (tag < 1 || tag > eom(new GregorianCalendar(jahr, monat - 1, 1))) {
        throw new NumberFormatException("month");
    }

    return new DateMidnight(jahr, monat, tag).toDate();
}

From source file:org.sakaiproject.content.impl.serialize.impl.test.GMTDateformatterTest.java

/**
 * Test method for//from  w  w w  . j  a  v a 2 s.  c  o m
 * {@link org.sakaiproject.content.impl.util.GMTDateformatter#parse(java.lang.String)}.
 */
@Test
public final void testParse() {
    // String format = "yyyyMMddHHmmssSSS";
    String[] testPattern = new String[20000];
    Date[] result = new Date[testPattern.length];
    String[] formatPattern = new String[20000];
    for (int i = 0; i < testPattern.length; i++) {
        int year = 1980 + (i % 200);
        int month = 1 + (i % 12);
        int day = 1 + (i % 28);
        int hour = (i % 24);
        int minute = (i % 60);
        int second = 59 - (i % 60);
        int millis = (i % 1000);
        StringBuilder sb = new StringBuilder();
        sb.append(pad(year, 4));
        sb.append(pad(month, 2));
        sb.append(pad(day, 2));
        sb.append(pad(hour, 2));
        sb.append(pad(minute, 2));
        sb.append(pad(second, 2));
        sb.append(pad(millis, 3));

        testPattern[i] = sb.toString();
    }
    {
        long start = System.currentTimeMillis();
        for (int i = 0; i < testPattern.length; i++) {
            result[i] = GMTDateformatter.parse(testPattern[i]);
        }
        long end = System.currentTimeMillis();
        double ms = 1.0 * (end - start) / (1.0 * testPattern.length);
        log.info(" Took " + (end - start) + " ms " + ms + " per parse");
    }
    {
        long start = System.currentTimeMillis();
        for (int i = 0; i < testPattern.length; i++) {
            formatPattern[i] = GMTDateformatter.format(result[i]);
        }
        long end = System.currentTimeMillis();
        double ms = 1.0 * (end - start) / (1.0 * testPattern.length);
        log.info(" Took " + (end - start) + " ms " + ms + " per format");
    }

    for (int i = 0; i < testPattern.length; i++) {
        int year = 1980 + (i % 200);
        int month = 1 + (i % 12);
        int day = 1 + (i % 28);
        int hour = (i % 24);
        int minute = (i % 60);
        int second = 59 - (i % 60);
        int millis = (i % 1000);
        GregorianCalendar gc = new GregorianCalendar(TimeZone.getTimeZone("GMT"));

        gc.setTime(result[i]);
        Assert.assertEquals(testPattern[i] + " year", year, gc.get(Calendar.YEAR));
        Assert.assertEquals(testPattern[i] + " month", month, gc.get(Calendar.MONTH) + 1);
        Assert.assertEquals(testPattern[i] + " day", day, gc.get(Calendar.DATE));
        Assert.assertEquals(testPattern[i] + " hour", hour, gc.get(Calendar.HOUR_OF_DAY));
        Assert.assertEquals(testPattern[i] + " minute", minute, gc.get(Calendar.MINUTE));
        Assert.assertEquals(testPattern[i] + " second", second, gc.get(Calendar.SECOND));
        Assert.assertEquals(testPattern[i] + " millis", millis, gc.get(Calendar.MILLISECOND));
        Assert.assertEquals("Format Check ", testPattern[i], GMTDateformatter.format(result[i]));
    }
}

From source file:de.randi2.services.ChartsServiceImpl.java

@Override
@Transactional(propagation = Propagation.REQUIRED)
public ChartData generateRecruitmentChart(Trial trial) {
    trial = trialDao.refresh(trial);/*  w w  w  .  ja v a  2  s .  com*/
    ChartData tempD = new ChartData();

    int plannedSubjects = 0;
    for (TreatmentArm arm : trial.getTreatmentArms()) {
        plannedSubjects += arm.getPlannedSubjects();
    }

    List<double[]> data = new ArrayList<double[]>();
    GregorianCalendar startDate = trial.getStartDate();
    GregorianCalendar endDate = trial.getEndDate();
    int monthStart = startDate.get(GregorianCalendar.MONTH);
    int monthEnd = endDate.get(GregorianCalendar.MONTH);
    ArrayList<String> xL = new ArrayList<String>();

    for (int year = startDate.get(GregorianCalendar.YEAR); year <= endDate
            .get(GregorianCalendar.YEAR); year++) {

        if (year != endDate.get(GregorianCalendar.YEAR)) {
            monthEnd = startDate.getMaximum(GregorianCalendar.MONTH);
        } else {
            monthEnd = endDate.get(GregorianCalendar.MONTH);
        }
        for (int month = monthStart; month <= monthEnd; month++) {
            double[] values = new double[2];
            values[0] = 0;
            if (data.size() > 0) {
                values[1] = data.get(data.size() - 1)[1];
            } else
                values[1] = 0;

            for (TrialSubject subject : trial.getSubjects()) {
                if (subject.getCreatedAt().get(GregorianCalendar.MONTH) == month
                        && subject.getCreatedAt().get(GregorianCalendar.YEAR) == year) {
                    values[1] = values[1] + 1.0;
                }
            }
            xL.add((month + 1) + "." + year);
            data.add(values);
        }
        monthStart = startDate.getMinimum(GregorianCalendar.MONTH);
    }

    for (int i = 1; i <= data.size(); i++) {
        data.get(i - 1)[0] = i * (plannedSubjects / data.size());
    }

    tempD.setXLabels(xL);
    tempD.setData(data);
    return tempD;
}

From source file:ru.apertum.qsystem.server.model.calendar.CalendarTableModel.java

/**
 * ?    //from   w  w w.java  2  s .c  o  m
 * @param year
 */
public void dropCalendar(int year) {
    QLog.l().logger().debug("? ");
    final ArrayList<FreeDay> del = new ArrayList<>();
    final GregorianCalendar gc = new GregorianCalendar();
    for (FreeDay freeDay : days) {
        gc.setTime(freeDay.getDate());
        if (gc.get(GregorianCalendar.YEAR) == year) {
            del.add(freeDay);
        }
    }
    days.removeAll(del);
    fireTableDataChanged();
}