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:org.agnitas.dao.impl.RecipientDaoImpl.java

/**
 * Load complete Subscriber-Data from DB. customerID must be set first for this method.
 *
 * @return Map with Key/Value-Pairs of customer data
 *///from   ww w . j a va  2s.c  o m
@Override
public CaseInsensitiveMap<Object> getCustomerDataFromDb(int companyID, int customerID) {
    String aName = null;
    String aValue = null;
    int a;
    java.sql.Timestamp aTime = null;
    Recipient cust = (Recipient) applicationContext.getBean("Recipient");

    if (cust.getCustParameters() == null) {
        cust.setCustParameters(new CaseInsensitiveMap<Object>());
    }

    String getCust = "SELECT * FROM customer_" + companyID + "_tbl WHERE customer_id=" + customerID;

    if (cust.getCustDBStructure() == null) {
        cust.loadCustDBStructure();
    }

    DataSource ds = (DataSource) this.applicationContext.getBean("dataSource");
    Connection con = DataSourceUtils.getConnection(ds);

    try {
        Statement stmt = con.createStatement();
        ResultSet rset = stmt.executeQuery(getCust);

        if (logger.isInfoEnabled()) {
            logger.info("getCustomerDataFromDb: " + getCust);
        }

        if (rset.next()) {
            ResultSetMetaData aMeta = rset.getMetaData();

            for (a = 1; a <= aMeta.getColumnCount(); a++) {
                aValue = null;
                aName = aMeta.getColumnName(a).toLowerCase();
                switch (aMeta.getColumnType(a)) {
                case java.sql.Types.TIMESTAMP:
                case java.sql.Types.TIME:
                case java.sql.Types.DATE:
                    try {
                        aTime = rset.getTimestamp(a);
                    } catch (Exception e) {
                        aTime = null;
                    }
                    if (aTime == null) {
                        cust.getCustParameters().put(aName + "_DAY_DATE", "");
                        cust.getCustParameters().put(aName + "_MONTH_DATE", "");
                        cust.getCustParameters().put(aName + "_YEAR_DATE", "");
                        cust.getCustParameters().put(aName + "_HOUR_DATE", "");
                        cust.getCustParameters().put(aName + "_MINUTE_DATE", "");
                        cust.getCustParameters().put(aName + "_SECOND_DATE", "");
                        cust.getCustParameters().put(aName, "");
                    } else {
                        GregorianCalendar aCal = new GregorianCalendar();
                        aCal.setTime(aTime);
                        cust.getCustParameters().put(aName + "_DAY_DATE",
                                Integer.toString(aCal.get(GregorianCalendar.DAY_OF_MONTH)));
                        cust.getCustParameters().put(aName + "_MONTH_DATE",
                                Integer.toString(aCal.get(GregorianCalendar.MONTH) + 1));
                        cust.getCustParameters().put(aName + "_YEAR_DATE",
                                Integer.toString(aCal.get(GregorianCalendar.YEAR)));
                        cust.getCustParameters().put(aName + "_HOUR_DATE",
                                Integer.toString(aCal.get(GregorianCalendar.HOUR_OF_DAY)));
                        cust.getCustParameters().put(aName + "_MINUTE_DATE",
                                Integer.toString(aCal.get(GregorianCalendar.MINUTE)));
                        cust.getCustParameters().put(aName + "_SECOND_DATE",
                                Integer.toString(aCal.get(GregorianCalendar.SECOND)));
                        SimpleDateFormat bdfmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        cust.getCustParameters().put(aName, bdfmt.format(aCal.getTime()));
                    }
                    break;

                default:
                    aValue = rset.getString(a);
                    if (aValue == null) {
                        aValue = "";
                    }
                    cust.getCustParameters().put(aName, aValue);
                    break;
                }
            }
        }
        rset.close();
        stmt.close();

    } catch (Exception e) {
        logger.error("getCustomerDataFromDb: " + getCust, e);
        AgnUtils.sendExceptionMail("sql:" + getCust, e);
    }
    DataSourceUtils.releaseConnection(con, ds);
    cust.setChangeFlag(false);
    Map<String, Object> result = cust.getCustParameters();
    if (result instanceof CaseInsensitiveMap) {
        return (CaseInsensitiveMap<Object>) result;
    } else {
        return new CaseInsensitiveMap<Object>(result);
    }
}

From source file:org.ramadda.util.Utils.java

/**
 * _more_/*from w  w  w. j  av  a2 s.c  om*/
 *
 * @param date _more_
 *
 * @return _more_
 */
public static int getYear(Date date) {
    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(date);

    return cal.get(cal.YEAR);
}

From source file:org.ramadda.util.Utils.java

/**
 * _more_//from  w w  w .  j  a v a  2s .  co m
 *
 * @param date _more_
 *
 * @return _more_
 */
public static int getMonth(Date date) {
    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(date);

    return cal.get(cal.MONTH);
}

From source file:org.apache.unomi.persistence.elasticsearch.ElasticSearchPersistenceServiceImpl.java

public void start() throws Exception {

    loadPredefinedMappings(bundleContext, false);

    // on startup
    new InClassLoaderExecute<Object>() {
        public Object execute(Object... args) throws Exception {
            logger.info("Connecting to ElasticSearch persistence backend using cluster name " + clusterName
                    + " and index name " + indexName + "...");

            bulkProcessorName = System.getProperty(BULK_PROCESSOR_NAME, bulkProcessorName);
            bulkProcessorConcurrentRequests = System.getProperty(BULK_PROCESSOR_CONCURRENT_REQUESTS,
                    bulkProcessorConcurrentRequests);
            bulkProcessorBulkActions = System.getProperty(BULK_PROCESSOR_BULK_ACTIONS,
                    bulkProcessorBulkActions);
            bulkProcessorBulkSize = System.getProperty(BULK_PROCESSOR_BULK_SIZE, bulkProcessorBulkSize);
            bulkProcessorFlushInterval = System.getProperty(BULK_PROCESSOR_FLUSH_INTERVAL,
                    bulkProcessorFlushInterval);
            bulkProcessorBackoffPolicy = System.getProperty(BULK_PROCESSOR_BACKOFF_POLICY,
                    bulkProcessorBackoffPolicy);

            Settings transportSettings = Settings.builder().put(CLUSTER_NAME, clusterName).build();
            client = new PreBuiltTransportClient(transportSettings);
            for (String elasticSearchAddress : elasticSearchAddressList) {
                String[] elasticSearchAddressParts = elasticSearchAddress.split(":");
                String elasticSearchHostName = elasticSearchAddressParts[0];
                int elasticSearchPort = Integer.parseInt(elasticSearchAddressParts[1]);
                try {
                    client.addTransportAddress(new InetSocketTransportAddress(
                            InetAddress.getByName(elasticSearchHostName), elasticSearchPort));
                } catch (UnknownHostException e) {
                    String message = "Error resolving address " + elasticSearchAddress
                            + " ElasticSearch transport client not connected";
                    throw new Exception(message, e);
                }//from w  w  w  . jav a  2s.  c  om
            }

            // let's now check the versions of all the nodes in the cluster, to make sure they are as expected.
            try {
                NodesInfoResponse nodesInfoResponse = client.admin().cluster().prepareNodesInfo().all()
                        .execute().get();

                org.elasticsearch.Version minimalVersion = org.elasticsearch.Version
                        .fromString(minimalElasticSearchVersion);
                org.elasticsearch.Version maximalVersion = org.elasticsearch.Version
                        .fromString(maximalElasticSearchVersion);
                for (NodeInfo nodeInfo : nodesInfoResponse.getNodes()) {
                    org.elasticsearch.Version version = nodeInfo.getVersion();
                    if (version.before(minimalVersion) || version.equals(maximalVersion)
                            || version.after(maximalVersion)) {
                        throw new Exception(
                                "ElasticSearch version on node " + nodeInfo.getHostname() + " is not within ["
                                        + minimalVersion + "," + maximalVersion + "), aborting startup !");
                    }
                }
            } catch (InterruptedException e) {
                throw new Exception("Error checking ElasticSearch versions", e);
            } catch (ExecutionException e) {
                throw new Exception("Error checking ElasticSearch versions", e);
            }

            // @todo is there a better way to detect index existence than to wait for it to startup ?
            boolean indexExists = false;
            int tries = 0;

            while (!indexExists && tries < 20) {

                IndicesExistsResponse indicesExistsResponse = client.admin().indices().prepareExists(indexName)
                        .execute().actionGet();
                indexExists = indicesExistsResponse.isExists();
                tries++;
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    logger.error("Interrupted", e);
                }
            }
            if (!indexExists) {
                logger.info("{} index doesn't exist yet, creating it...", indexName);
                Map<String, String> indexMappings = new HashMap<String, String>();
                indexMappings.put("_default_", mappings.get("_default_"));
                for (Map.Entry<String, String> entry : mappings.entrySet()) {
                    if (!itemsMonthlyIndexed.contains(entry.getKey())
                            && !indexNames.containsKey(entry.getKey())) {
                        indexMappings.put(entry.getKey(), entry.getValue());
                    }
                }

                internalCreateIndex(indexName, indexMappings);
            } else {
                logger.info("Found index {}, ElasticSearch started successfully.", indexName);
                for (Map.Entry<String, String> entry : mappings.entrySet()) {
                    createMapping(entry.getKey(), entry.getValue());
                }
            }

            client.admin().indices().preparePutTemplate(indexName + "_monthlyindex")
                    .setTemplate(indexName + "-*").setOrder(1)
                    .setSettings(Settings.builder()
                            .put(NUMBER_OF_SHARDS, Integer.parseInt(monthlyIndexNumberOfShards))
                            .put(NUMBER_OF_REPLICAS, Integer.parseInt(monthlyIndexNumberOfReplicas)).build())
                    .execute().actionGet();

            getMonthlyIndex(new Date(), true);

            if (client != null && bulkProcessor == null) {
                bulkProcessor = getBulkProcessor();
            }

            refreshExistingIndexNames();

            logger.info("Waiting for GREEN cluster status...");

            client.admin().cluster().prepareHealth().setWaitForGreenStatus().get();

            logger.info("Cluster status is GREEN");

            return true;
        }
    }.executeInClassLoader();

    bundleContext.addBundleListener(this);

    timer = new Timer();

    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            GregorianCalendar gc = new GregorianCalendar();
            int thisMonth = gc.get(Calendar.MONTH);
            gc.add(Calendar.DAY_OF_MONTH, 1);
            if (gc.get(Calendar.MONTH) != thisMonth) {
                String monthlyIndex = getMonthlyIndex(gc.getTime(), true);
                existingIndexNames.add(monthlyIndex);
            }
        }
    }, 10000L, 24L * 60L * 60L * 1000L);

    // load predefined mappings and condition dispatchers of any bundles that were started before this one.
    for (Bundle existingBundle : bundleContext.getBundles()) {
        if (existingBundle.getBundleContext() != null) {
            loadPredefinedMappings(existingBundle.getBundleContext(), true);
        }
    }

    logger.info(this.getClass().getName() + " service started successfully.");
}

From source file:org.eevolution.form.CRP.java

/**
 * Create Category Dataset based on date start and resource
 * @param start/*from  w w  w  . ja v  a2  s  .c o  m*/
 * @param resource
 * @return CategoryDataset
 */
protected CategoryDataset createDataset(Timestamp start, MResource resource) {
    GregorianCalendar gc1 = new GregorianCalendar();
    gc1.setTimeInMillis(start.getTime());
    gc1.clear(Calendar.MILLISECOND);
    gc1.clear(Calendar.SECOND);
    gc1.clear(Calendar.MINUTE);
    gc1.clear(Calendar.HOUR_OF_DAY);

    Timestamp date = start;
    String namecapacity = Msg.translate(Env.getCtx(), "Capacity");
    String nameload = Msg.translate(Env.getCtx(), "Load");
    String namesummary = Msg.translate(Env.getCtx(), "Summary");
    MResourceType t = MResourceType.get(Env.getCtx(), resource.getS_ResourceType_ID());
    int days = 1;
    long hours = t.getTimeSlotHours();

    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    //      Long Hours = new Long(hours);                            
    int C_UOM_ID = DB.getSQLValue(null, "SELECT C_UOM_ID FROM M_Product WHERE S_Resource_ID = ? ",
            resource.getS_Resource_ID());
    MUOM uom = MUOM.get(Env.getCtx(), C_UOM_ID);
    if (!uom.isHour()) {
        return dataset;
    }
    long summary = 0;

    while (days < 32) {
        String day = new String(new Integer(date.getDate()).toString());
        long HoursLoad = getLoad(resource, date).longValue();
        Long Hours = new Long(hours);

        switch (gc1.get(Calendar.DAY_OF_WEEK)) {
        case Calendar.SUNDAY:
            days++;
            if (t.isOnSunday()) {
                dataset.addValue(hours, namecapacity, day);
                dataset.addValue(HoursLoad, nameload, day);
                dataset.addValue(summary, namesummary, day);
                summary = summary + Hours.intValue() - (HoursLoad);
                gc1.add(Calendar.DATE, 1);
                date = new Timestamp(gc1.getTimeInMillis());
                break;
            } else {
                dataset.addValue(0, namecapacity, day);
                dataset.addValue(HoursLoad, nameload, day);
                dataset.addValue(summary, namesummary, day);
                summary = summary - (HoursLoad);
                gc1.add(Calendar.DATE, 1);
                date = new Timestamp(gc1.getTimeInMillis());
                break;
            }
        case Calendar.MONDAY:
            days++;
            if (t.isOnMonday()) {
                dataset.addValue(hours, namecapacity, day);
                dataset.addValue(HoursLoad, nameload, day);
                dataset.addValue(summary, namesummary, day);
                summary = summary + Hours.intValue() - (HoursLoad);
                gc1.add(Calendar.DATE, 1);
                date = new Timestamp(gc1.getTimeInMillis());
                break;
            } else {
                dataset.addValue(0, namecapacity, day);
                dataset.addValue(HoursLoad, nameload, day);
                dataset.addValue(summary, namesummary, day);
                summary = summary - (HoursLoad);
                gc1.add(Calendar.DATE, 1);
                date = new Timestamp(gc1.getTimeInMillis());
                break;
            }
        case Calendar.TUESDAY:
            days++;
            if (t.isOnTuesday()) {
                dataset.addValue(hours, namecapacity, day);
                dataset.addValue(HoursLoad, nameload, day);
                dataset.addValue(summary, namesummary, day);
                summary = summary + Hours.intValue() - (HoursLoad);
                gc1.add(Calendar.DATE, 1);
                date = new Timestamp(gc1.getTimeInMillis());
                break;
            } else {
                dataset.addValue(0, namecapacity, day);
                dataset.addValue(HoursLoad, nameload, day);
                dataset.addValue(summary, namesummary, day);
                summary = summary - (HoursLoad);
                gc1.add(Calendar.DATE, 1);
                date = new Timestamp(gc1.getTimeInMillis());
                break;
            }
        case Calendar.WEDNESDAY:
            days++;
            if (t.isOnWednesday()) {
                dataset.addValue(hours, namecapacity, day);
                dataset.addValue(HoursLoad, nameload, day);
                dataset.addValue(summary, namesummary, day);
                summary = summary + Hours.intValue() - (HoursLoad);
                gc1.add(Calendar.DATE, 1);
                date = new Timestamp(gc1.getTimeInMillis());
                break;
            } else {
                dataset.addValue(0, namecapacity, day);
                dataset.addValue(HoursLoad, nameload, day);
                dataset.addValue(summary, namesummary, day);
                summary = summary - (HoursLoad);
                gc1.add(Calendar.DATE, 1);
                date = new Timestamp(gc1.getTimeInMillis());
                break;
            }
        case Calendar.THURSDAY:
            days++;
            if (t.isOnThursday()) {
                dataset.addValue(hours, namecapacity, day);
                dataset.addValue(HoursLoad, nameload, day);
                dataset.addValue(summary, namesummary, day);
                summary = summary + Hours.intValue() - (HoursLoad);
                gc1.add(Calendar.DATE, 1);
                date = new Timestamp(gc1.getTimeInMillis());
                break;
            } else {
                dataset.addValue(0, namecapacity, day);
                dataset.addValue(HoursLoad, nameload, day);
                dataset.addValue(summary, namesummary, day);
                summary = summary - (HoursLoad);
                gc1.add(Calendar.DATE, 1);
                date = new Timestamp(gc1.getTimeInMillis());
                break;
            }
        case Calendar.FRIDAY:
            days++;
            if (t.isOnFriday()) {
                dataset.addValue(hours, namecapacity, day);
                dataset.addValue(HoursLoad, nameload, day);
                dataset.addValue(summary, namesummary, day);
                summary = summary + Hours.intValue() - (HoursLoad);
                gc1.add(Calendar.DATE, 1);
                date = new Timestamp(gc1.getTimeInMillis());
                break;
            } else {

                dataset.addValue(0, namecapacity, day);
                dataset.addValue(HoursLoad, nameload, day);
                dataset.addValue(summary, namesummary, day);
                summary = summary - (HoursLoad);
                gc1.add(Calendar.DATE, 1);
                date = new Timestamp(gc1.getTimeInMillis());
                break;
            }
        case Calendar.SATURDAY:
            days++;
            if (t.isOnSaturday()) {
                dataset.addValue(hours, namecapacity, day);
                dataset.addValue(HoursLoad, nameload, day);
                dataset.addValue(summary, namesummary, day);
                summary = summary + Hours.intValue() - (HoursLoad);
                gc1.add(Calendar.DATE, 1);
                date = new Timestamp(gc1.getTimeInMillis());
                break;
            } else {
                dataset.addValue(0, namecapacity, day);
                dataset.addValue(HoursLoad, nameload, day);
                dataset.addValue(summary, namesummary, day);
                summary = summary - (HoursLoad);
                gc1.add(Calendar.DATE, 1);
                date = new Timestamp(gc1.getTimeInMillis());
                break;
            }
        }

    }
    return dataset;
}

From source file:edu.stanford.muse.util.Util.java

public static List<Date> getYearlyIntervals(Date start, Date end) {
    List<Date> intervals = new ArrayList<Date>();
    GregorianCalendar c = new GregorianCalendar();
    c.setTime(start);// w w w .  j a v a2 s  .  c o m
    int startYear = c.get(Calendar.YEAR);
    int year = startYear;

    intervals.add(start);
    while (true) {
        year++;
        c = new GregorianCalendar(year, 0, 1, 0, 0, 0);
        intervals.add(c.getTime());
        if (c.getTime().after(end))
            break;
    }
    return intervals;
}

From source file:edu.stanford.muse.util.Util.java

public static List<Date> getMonthlyIntervals(Date start, Date end) {
    List<Date> intervals = new ArrayList<Date>();
    GregorianCalendar c = new GregorianCalendar();
    c.setTime(start);//from w  ww  .j  a v  a2 s  . c  o m
    int startMonth = c.get(Calendar.MONTH);
    int year = c.get(Calendar.YEAR);
    int month = startMonth;

    intervals.add(start);
    while (true) {
        month++;
        if (month == 12) {
            month = 0;
            year++;
        }

        c = new GregorianCalendar(year, month, 1, 0, 0, 0);
        intervals.add(c.getTime());
        if (c.getTime().after(end))
            break;
    }
    return intervals;
}

From source file:phenoviewer.ReNameJFrame.java

private String replaceTokens(Date date, int counter, String path) {
    GregorianCalendar gc = new GregorianCalendar();
    gc.setTime(date);//from w w w. j  a  v  a 2 s  .c  o  m

    Map<String, Object> tokens = new HashMap<String, Object>();
    tokens.put("ERA", getText(gc.get(Calendar.ERA), "BC", "AD"));
    tokens.put("YEAR", getString(gc.get(Calendar.YEAR), 4, "0"));
    tokens.put("MONTH", getString(gc.get(Calendar.MONTH) + 1, 2, "0"));
    tokens.put("WEEK_OF_YEAR", getString(gc.get(Calendar.WEEK_OF_YEAR), 2, "0"));
    tokens.put("WEEK_OF_MONTH", getString(gc.get(Calendar.WEEK_OF_MONTH), 0, ""));
    tokens.put("DATE", getString(gc.get(Calendar.DATE), 2, "0"));
    tokens.put("DAY_OF_MONTH", getString(gc.get(Calendar.DAY_OF_MONTH), 2, "0"));
    tokens.put("DAY_OF_YEAR", getString(gc.get(Calendar.DAY_OF_YEAR), 3, "0"));
    tokens.put("DAY_OF_WEEK", getString(gc.get(Calendar.DAY_OF_WEEK), 0, ""));
    tokens.put("DAY_OF_WEEK_IN_MONTH", getString(gc.get(Calendar.DAY_OF_WEEK_IN_MONTH), 0, ""));
    tokens.put("AM_PM", getText(gc.get(Calendar.AM_PM), "AM", "PM"));
    tokens.put("HOUR", getString(gc.get(Calendar.HOUR), 2, "0"));
    tokens.put("HOUR_OF_DAY", getString(gc.get(Calendar.HOUR_OF_DAY), 2, "0"));
    tokens.put("MINUTE", getString(gc.get(Calendar.MINUTE), 2, "0"));
    tokens.put("SECOND", getString(gc.get(Calendar.SECOND), 2, "0"));
    tokens.put("MILLISECOND", getString(gc.get(Calendar.MILLISECOND), 3, "0"));
    // tokens.put("ZONE_OFFSET", getString((gc.get(Calendar.ZONE_OFFSET)/(60*60*1000)), 0, ""));
    // tokens.put("DST_OFFSET", getString((gc.get(Calendar.DST_OFFSET)/(60*60*1000)), 0, ""));
    tokens.put("COUNTER", getString(counter, 0, ""));

    return processParams(path, tokens);
}

From source file:de.tuttas.servlets.DokuServlet.java

private MyTableDataModel getModelAnwesenheit(Klasse kl, Date parsedFrom, Date parsedTo, int filter1Id,
        int filter2Id) {
    TypedQuery<AnwesenheitEintrag> query = em.createNamedQuery("findAnwesenheitbyKlasse",
            AnwesenheitEintrag.class);
    query.setParameter("paramKName", kl.getKNAME());
    query.setParameter("paramFromDate", new java.sql.Date(parsedFrom.getTime()));
    query.setParameter("paramToDate", new java.sql.Date(parsedTo.getTime()));
    Log.d("setze From auf " + new java.sql.Date(parsedFrom.getTime()));
    List<AnwesenheitObjekt> anwesenheit = getData(query);

    Query q = em.createNamedQuery("findSchuelerEinerBenanntenKlasse");
    q.setParameter("paramNameKlasse", kl.getKNAME());
    List<Schueler> schueler = q.getResultList();

    /**/*w  w w. j  a v  a 2s  .  co  m*/
     * Termindaten holen
     */
    Termine t1 = null;
    Termine t2 = null;
    if (filter1Id != -1) {
        t1 = em.find(Termine.class, filter1Id);

    }
    if (filter2Id != -1) {
        t2 = em.find(Termine.class, filter2Id);
    }
    List<Termin> termine = null;
    TypedQuery<Termin> tquery = null;
    if (filter1Id != 0) {
        // zwei Filter
        if (filter2Id != 0) {
            tquery = em.createNamedQuery("findAllTermineTwoFilters", Termin.class);
            tquery.setParameter("filter1", t1.getId());
            tquery.setParameter("filter2", t2.getId());
            tquery.setParameter("fromDate", new java.sql.Date(parsedFrom.getTime()));
            tquery.setParameter("toDate", new java.sql.Date(parsedTo.getTime()));
            termine = tquery.getResultList();
        } // nur Filter1
        else {
            tquery = em.createNamedQuery("findAllTermineOneFilter", Termin.class);
            tquery.setParameter("filter1", t1.getId());
            tquery.setParameter("fromDate", new java.sql.Date(parsedFrom.getTime()));
            tquery.setParameter("toDate", new java.sql.Date(parsedTo.getTime()));
            termine = tquery.getResultList();
        }
    } else {
        // nur Filter2
        if (filter2Id != 0) {
            tquery = em.createNamedQuery("findAllTermineOneFilter", Termin.class);
            tquery.setParameter("filter1", t2.getId());
            tquery.setParameter("fromDate", new java.sql.Date(parsedFrom.getTime()));
            tquery.setParameter("toDate", new java.sql.Date(parsedTo.getTime()));
            termine = tquery.getResultList();
        } // kein Filter, Termine so generieren
        else {
            termine = new ArrayList<>();
            Date current = new Date(parsedFrom.getTime());
            parsedTo.setTime(parsedTo.getTime() + 1000);
            while (current.before(parsedTo)) {
                termine.add(new Termin(new Timestamp(current.getTime())));
                Log.d("Erzeuge neuen Termin:" + new Termin(new Timestamp(current.getTime())));
                current.setTime(current.getTime() + 24 * 60 * 60 * 1000);
            }
        }
    }

    Log.d("Result List:" + anwesenheit);

    List<String> sb = new ArrayList<>();
    GregorianCalendar c = (GregorianCalendar) GregorianCalendar.getInstance();

    for (Termin t : termine) {
        c.setTime(new Date(t.getDate().getTime()));
        sb.add("" + DatumUtil.getWochentag(c.get(GregorianCalendar.DAY_OF_WEEK)) + ":"
                + c.get(GregorianCalendar.DATE) + "." + (c.get(GregorianCalendar.MONTH) + 1) + "."
                + c.get(GregorianCalendar.YEAR));
    }
    Log.d("Es werden " + sb.size() + " Tage dargestellt");
    sb.add(0, "Name");
    String[] cols = new String[sb.size()];
    for (int i = 0; i < cols.length; i++) {
        cols[i] = sb.get(i);
    }
    MyTableDataModel mo = new MyTableDataModel(schueler.size(), cols);
    Schueler s;
    for (int y = 0; y < schueler.size(); y++) {
        s = schueler.get(y);
        mo.setData(0, y, s.getVNAME() + " " + s.getNNAME());
        int x = 1;
        for (Termin t : termine) {
            mo.setData(x, y, findVermerk(s.getId(), t.getDate(), anwesenheit));
            x++;
        }
    }
    return mo;
}

From source file:com.zimbra.cs.mailbox.calendar.ZRecur.java

public List<Date> expandRecurrenceOverRange(ParsedDateTime dtStart, long rangeStart, long rangeEnd)
        throws ServiceException {
    List<Date> toRet = new LinkedList<Date>();

    Date rangeStartDate = new Date(rangeStart);
    // subtract 1000ms (1sec) because the code in the method treats
    // end time as inclusive while the rangeEnd input argument is
    // exclusive value
    Date rangeEndDate = new Date(rangeEnd - 1000);
    Date dtStartDate = new Date(dtStart.getUtcTime());

    Date earliestDate;//from w w w  .  j a v a 2 s . c o  m
    if (dtStartDate.after(rangeStartDate))
        earliestDate = dtStartDate;
    else
        earliestDate = rangeStartDate;

    if (mUntil != null) {
        Date until = mUntil.getDateForRecurUntil(dtStart.getTimeZone());
        if (until.before(rangeEndDate))
            rangeEndDate = until;
    }

    // Set limit of expansion count.
    int maxInstancesFromConfig = sExpansionLimits.maxInstances;
    int maxInstancesExpanded;
    if (maxInstancesFromConfig <= 0)
        maxInstancesExpanded = mCount;
    else if (mCount <= 0)
        maxInstancesExpanded = maxInstancesFromConfig;
    else
        maxInstancesExpanded = Math.min(mCount, maxInstancesFromConfig);
    int numInstancesExpanded = 1; // initially 1 rather than 0 because DTSTART is always included

    // Set hard limit of expansion time range.  (bug 21989)
    ParsedDateTime earliestDateTime = ParsedDateTime.fromUTCTime(earliestDate.getTime());
    Date hardEndDate = getEstimatedEndTime(earliestDateTime);
    if (hardEndDate.before(rangeEndDate))
        rangeEndDate = hardEndDate;

    if (rangeEndDate.before(earliestDate)) {
        ZimbraLog.calendar.debug(
                "Expanding recurrence over range where range end %s is before earliest date %s",
                DateUtil.formatDate(rangeEndDate), DateUtil.formatDate(earliestDate));
        return toRet;
    }

    GregorianCalendar cur = dtStart.getCalendarCopy();
    int baseMonthDay = cur.get(Calendar.DAY_OF_MONTH);
    boolean baseIsLeapDay = ((baseMonthDay == 29) && (cur.get(Calendar.MONTH) == Calendar.FEBRUARY));

    // until we hit rangeEnd, or we've SAVED count entries:
    //
    //     gather each set {
    //
    //
    //
    //        curDate forward one INTERVAL
    //
    //     }
    //     check Set against BYSETPOS & ranges & count
    //

    int interval = mInterval;
    if (interval <= 0)
        interval = 1;

    // DTSTART is always part of the expansion, as long as it falls within
    // the range.
    if (!dtStartDate.before(earliestDate) && !dtStartDate.after(rangeEndDate))
        toRet.add(dtStartDate);

    int numConsecutiveIterationsWithoutMatchingInstance = 0;
    boolean pastHardEndTime = false;
    long numIterations = 0; // track how many times we looped
    while (!pastHardEndTime && (maxInstancesExpanded <= 0 || numInstancesExpanded < maxInstancesExpanded)) {
        numIterations++;
        boolean curIsAtOrAfterEarliestDate = !cur.getTime().before(earliestDate);
        boolean curIsAfterEndDate = cur.getTime().after(rangeEndDate);
        List<Calendar> addList = new LinkedList<Calendar>();

        switch (mFreq) {
        case HOURLY:
            /*
             * BYSECOND - for each listed second
             * BYMINUTE - for each listed minute in hour
             * BYHOUR - match iff in hour list
             * BYDAY - for each day listed
             * BYMONTHDAY - only those monthdays
             * BYYEARDAY - only those yeardays
             * BYMONTH - only those months
             */
            if (!checkMonthList(cur))
                continue;

            if (!checkYearDayList(cur))
                continue;

            if (!checkMonthDayList(cur))
                continue;

            if (!checkDayList(cur))
                continue;

            if (!checkHourList(cur))
                continue;

            addList.add((Calendar) (cur.clone()));

            cur.add(Calendar.HOUR_OF_DAY, interval);

            addList = expandHourList(addList);
            addList = expandMinuteList(addList);
            addList = expandSecondList(addList);

            break;
        case DAILY:
            /*
             * BYSECOND - for each listed second in day
             * BYMINUTE - for each listed minute in day
             * BYHOUR - for each listed hour in day
             * BYDAY - no ordinal allowed, match iff in day list
             * BYMONTHDAY - only that day
             * BYYEARDAY - only that day
             * BYWEEKNO -- YEARLY ONLY
             * BYMONTH - only that month
             *
             * while (count check & until check & rangeEnd check) {
             *    if (byMonth && !month matches)
             *      curDay = set MONTH to matching month
             *
             *    if (byYearDay && !yearday matches)
             *      curDay = set DAY to next matching yearday
             *
             *    if (byMonthday && !monthday matches)
             *      curDay = skip to next matching monthday
             *
             *    if (byDay && !day in list)
             *      curDay = skip to next mathcing byDay
             *
             *    if (!byHour or FOR EACH HOUR IN HOURLIST)
             *      if (!byMinute or FOR EACH MINUTE IN MINLIST)
             *        if (!bySecond or FOR EACH SECOND IN LIST)
             *          ----add to list---
             *
             *     check against BYSETPOS
             *
             *     curDay+=1 day
             * }
             *
             */

            if (!checkMonthList(cur))
                continue;

            if (!checkYearDayList(cur))
                continue;

            if (!checkMonthDayList(cur))
                continue;

            if (!checkDayList(cur))
                continue;

            addList.add((Calendar) (cur.clone()));

            cur.add(Calendar.DAY_OF_YEAR, interval);

            addList = expandHourList(addList);
            addList = expandMinuteList(addList);
            addList = expandSecondList(addList);
            break;
        case WEEKLY:
            /*
             * BYSECOND - for every listed second
             * BYMINUTE - for every listed minute
             * BYHOUR - for every listed hour
             * BYDAY - for every listed day
             * BYMONTHDAY - MAYBE once a month
             * BYYEARDAY - MAYBE once a year
             * BYMONTH - iff month matches
             *
             *  for each (INTERVAL)WEEK{
             *    if (byMonth && !month matches)
             *      curDay = set MONTH to DtStart in next matching month
             *
             *    if (byYearDay && !yearday matches)
             *      curDay = set date to next matching yearday
             *
             *    if (byMonthDay && !monthday matches)
             *      curDay = skip to next matching monthday
             *
             *    if (!byDay or FOREACH day in list)
             *      if (!byHour or FOREACH hour in list)
             *        if (!byMinute or FOREACH minute in list)
             *          if (!bySecond or FOREACH second in list)
             *            ----add to list----
             *
             *    check against BYSETPOS
             *
             *    curDay += 1 week
             * } while (count check & until check & rangeEnd check)
             *
             */
            if (!checkMonthList(cur))
                continue;

            if (!checkYearDayList(cur))
                continue;

            if (!checkMonthDayList(cur))
                continue;

            addList.add((Calendar) (cur.clone()));

            cur.add(Calendar.WEEK_OF_YEAR, interval);

            addList = expandDayListForWeekly(addList);
            addList = expandHourList(addList);
            addList = expandMinuteList(addList);
            addList = expandSecondList(addList);
            break;
        case MONTHLY:
            if (!checkMonthList(cur))
                continue;

            if (!checkYearDayList(cur))
                continue;

            addList.add((Calendar) (cur.clone()));

            cur.set(Calendar.DAY_OF_MONTH, 1);
            cur.add(Calendar.MONTH, interval);
            int daysInMonth = cur.getActualMaximum(Calendar.DAY_OF_MONTH);
            cur.set(Calendar.DAY_OF_MONTH, Math.min(baseMonthDay, daysInMonth));

            addList = expandMonthDayList(addList);
            addList = expandDayListForMonthlyYearly(addList);
            addList = expandHourList(addList);
            addList = expandMinuteList(addList);
            addList = expandSecondList(addList);

            break;
        case YEARLY:
            /*
             * BYSECOND
             * BYMINUTE
             * BYHOUR
             * BYDAY
             * BYMONTHDAY
             * BYYEARDAY
             * BYWEEKNO - specified week
             * BYMONTH - once
             */
            if (baseIsLeapDay) {
                // previously adding a year to a leap day will have rounded down to the 28th.
                // If this happened, we need to be sure that if we are back in a leap
                // year, it is back at 29th
                cur.set(Calendar.DAY_OF_MONTH, cur.getActualMaximum(Calendar.DAY_OF_MONTH));
            }
            if (ignoreYearForRecurrenceExpansion(cur, baseIsLeapDay)) {
                cur.add(Calendar.YEAR, interval);
                break;
            }
            addList.add((Calendar) (cur.clone()));

            cur.add(Calendar.YEAR, interval);

            addList = expandMonthList(addList);
            addList = expandYearDayList(addList);

            addList = expandMonthDayList(addList);
            addList = expandDayListForMonthlyYearly(addList);
            addList = expandHourList(addList);
            addList = expandMinuteList(addList);
            addList = expandSecondList(addList);

            break;
        default:
            // MINUTELY and SECONDLY are intentionally not supported for performance reasons.
            return toRet;
        }

        addList = handleSetPos(addList);

        boolean noInstanceFound = true;
        boolean foundInstancePastEndDate = false;
        // add all the ones that match!
        for (Calendar addCal : addList) {
            Date toAdd = addCal.getTime();

            // We already counted DTSTART before the main loop, so don't
            // count it twice.
            if (toAdd.compareTo(dtStartDate) == 0) {
                noInstanceFound = false;
                continue;
            }

            // we still have expanded this instance, even if it isn't in our
            // current date window
            if (toAdd.after(dtStartDate))
                numInstancesExpanded++;

            if (!toAdd.after(rangeEndDate)) {
                if (!toAdd.before(earliestDate)) {
                    toRet.add(toAdd);
                    noInstanceFound = false;
                }
            } else {
                foundInstancePastEndDate = true;
                break;
            }

            if (maxInstancesExpanded > 0 && numInstancesExpanded >= maxInstancesExpanded)
                break;
        }

        // Detect invalid rule.  If the rule was invalid the current iteration, which is for the current
        // frequency interval, would have found no matching instance.  The next iteration will also find
        // no matching instance, and there is no need to keep iterating until we go past the hard end
        // time or COUNT/UNTIL limit.
        //
        // However, we have to make an exception for leap year.  An yearly rule looking for February 29th
        // will find no instance in up to 3 consecutive years before finding Feb 29th in the fourth year.
        //
        // So the invalid rule detection must look for at least 4 consecutive failed iterations.
        if (curIsAtOrAfterEarliestDate) {
            if (noInstanceFound)
                numConsecutiveIterationsWithoutMatchingInstance++;
            else
                numConsecutiveIterationsWithoutMatchingInstance = 0;
            if (numConsecutiveIterationsWithoutMatchingInstance >= 4) {
                ZimbraLog.calendar.warn("Invalid recurrence rule: " + toString());
                return toRet;
            }
        }

        pastHardEndTime = foundInstancePastEndDate || (noInstanceFound && curIsAfterEndDate);
    }

    return toRet;
}