Example usage for java.util GregorianCalendar getTime

List of usage examples for java.util GregorianCalendar getTime

Introduction

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

Prototype

public final Date getTime() 

Source Link

Document

Returns a Date object representing this Calendar's time value (millisecond offset from the Epoch").

Usage

From source file:org.redis.shop.test.InitData.java

@Test
public void ay_addPrice() throws Exception {
    List<Center> centers = centerService.getAll();
    //      List<Center> centers1 = centerService.getByProperty(
    //            centerService.getAll(), "name", "????");

    List<Category> categorys = categoryService.getByBasicProperty(categoryService.getAll(), "level", 2);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date parse = sdf.parse("2014-11-01");

    Date today = new Date();
    today = sdf.parse(sdf.format(today));

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(parse);/*from   w  w w.  j av a  2 s .  co m*/
    long time1 = calendar.getTimeInMillis();
    calendar.setTime(today);
    long time2 = calendar.getTimeInMillis();
    long betweenDays = (time2 - time1) / (1000 * 3600 * 24);

    GregorianCalendar cal = new GregorianCalendar();
    List<Price> prices = new ArrayList<Price>();
    for (int i = 0; i <= betweenDays; i++) {
        for (Center center : centers) {

            for (Category category : categorys) {
                cal.setTime(parse);
                cal.add(Calendar.DATE, i);
                Date dateNow = cal.getTime();

                Price price = new Price();
                price.setCreateDate(dateNow);
                price.setUpdateDate(dateNow);
                price.setCreator("jack");
                price.setSite(null);
                price.setUnit("?");
                price.setCenter(center);
                price.setCategory(category);
                price.setIsNewest("0");
                if (i == betweenDays) {

                    price.setIsNewest("1");
                }
                price.setIsGuidencePrice("1");//?
                price.setPrice(DataUtil.getRandm(100, 500));
                prices.add(price);
                //               priceService.save(price);
            }
        }
    }
    priceService.save(prices);

    centers = centerService.getByProperty(centerService.getAll(), "name",
            "????1");
    for (int i = 0; i <= 10; i++) {
        for (Category category : categorys) {
            Price price = new Price();
            price.setCreateDate(new Date());
            price.setUpdateDate(new Date());
            price.setCreator("jack");
            price.setSite(null);
            price.setUnit("?");
            price.setCenter(centers.get(0));
            price.setIsGuidencePrice("1");//?
            price.setCategory(category);
            price.setIsNewest("0");
            price.setPrice(DataUtil.getRandm(100, 500));
            priceService.save(price);
        }
    }

    List<Category> list = categoryService.getByBasicProperty(categoryService.getAll(), "level", 1);
    List<Site> sites = siteService.getAll();
    for (Site site : sites) {
        for (Category category : list) {
            Price price = new Price();
            price.setCreateDate(new Date());
            price.setUpdateDate(new Date());
            price.setCreator("jack");
            price.setSite(site);
            price.setUnit("?");
            price.setCenter(null);
            price.setCategory(category);
            price.setIsNewest("1");
            price.setIsGuidencePrice("1");//?
            price.setPrice(DataUtil.getRandm(100, 500));
            priceService.save(price);
        }
    }

}

From source file:org.redis.shop.test.InitData.java

@Test
public void bc_addTagAndTransaction() throws ParseException {
    Tag tag = null;/*from   w  w w  . j  av a 2  s .com*/
    Transaction transaction = null;
    Category category1 = categoryService.getList("name", "?").get(1);
    Category category2 = categoryService.getList("name", "").get(0);
    Category category3 = categoryService.getList("name", "").get(0);
    Category category4 = categoryService.getList("name", "").get(1);
    Category category5 = categoryService.getList("name", "?").get(0);
    PlateformScale plateformScale = plateformScaleService.get("plateformScaleNum", "TB-0001");
    Vechile vechile1 = vechileService.get("vechileNum", "CH-0001");
    Vechile vechile2 = vechileService.get("vechileNum", "CH-0002");
    Vechile vechile3 = vechileService.get("vechileNum", "CH-0003");
    Vechile vechile4 = vechileService.get("vechileNum", "CH-0004");
    Vechile vechile5 = vechileService.get("vechileNum", "CH-0005");
    Site site1 = siteService.get("user.name", "s1");
    Center center1 = centerService.get("user.name", "c1");
    Site site2 = siteService.get("user.name", "s2");
    Center center2 = centerService.get("user.name", "c2");
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date before = sdf.parse("2015-01-01");
    Date today = sdf.parse(sdf.format(new Date()));
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(before);
    long beforeTime = calendar.getTimeInMillis();
    calendar.setTime(today);
    long todayTime = calendar.getTimeInMillis();
    long betweenDays = (todayTime - beforeTime) / (1000 * 3600 * 24);
    GregorianCalendar cal = new GregorianCalendar();
    float weight1 = 1000f;
    float weight2 = 2000f;
    float weight3 = 3000f;
    float weight4 = 2500f;
    float weight5 = 2800f;
    for (int i = 0; i <= betweenDays; i++) {
        cal.setTime(before);
        cal.add(Calendar.DATE, i);
        Date dateNow = cal.getTime();
        List<Tag> tags = new ArrayList<>();
        if (i % 5 == 0) {
            tag = new Tag();
            tag.setTime(dateNow);
            tag.setWeight(weight1);
            tag.setPrice(10f);
            tag.setType(Enum_TagType.WR);
            tag.setCategory(category1);
            tag.setTagNum("RFID-1" + i);
            tag.setVechile(vechileService.get("vechileNum", "CH-0001"));
            tag.setPlateformScale(plateformScale);
            //            String tagId = (String) tagService.save(tag);
            tags.add(tag);
            transaction = new Transaction();
            transaction.setTags(tags);
            transaction.setPrice(tag.getPrice());
            transaction.setTotalPrice(tag.getPrice() * tag.getWeight());
            transaction.setState(Enum_Transaction.IT);
            transaction.setInTime(dateNow);
            transaction.setOutTime(dateNow);
            transaction.setVechile(vechile1);
            transaction.setTransactionProperty(Enum_TransactionProperty.HAO);
            if (i % 2 == 0) {
                transaction.setCenter(center1);
                transaction.setSite(site1);
            } else {
                transaction.setCenter(center2);
                transaction.setSite(site2);
            }
            tagService.save(tag);
            transactionService.save(transaction);
            tag.setTransaction(transaction);
            tagService.update(tag);
        } else if (i % 5 == 1) {
            tag = new Tag();
            tag.setTime(dateNow);
            tag.setVechile(vechileService.get("vechileNum", "CH-0002"));
            tag.setWeight(weight2);
            tag.setPrice(10f);
            tag.setType(Enum_TagType.WR);
            tag.setCategory(category2);
            tag.setTagNum("RFID-2" + i);
            tag.setPlateformScale(plateformScale);
            //            String tagId = (String) tagService.save(tag);
            tags.add(tag);
            transaction = new Transaction();
            transaction.setTags(tags);
            transaction.setPrice(tag.getPrice());
            transaction.setTotalPrice(tag.getPrice() * tag.getWeight());
            transaction.setState(Enum_Transaction.IT);
            transaction.setInTime(dateNow);
            transaction.setOutTime(dateNow);
            transaction.setVechile(vechile2);
            transaction.setTransactionProperty(Enum_TransactionProperty.HAO);
            if (i % 2 == 0) {
                transaction.setCenter(center1);
                transaction.setSite(site1);
            } else {
                transaction.setCenter(center2);
                transaction.setSite(site2);
            }
            tagService.save(tag);
            transactionService.save(transaction);
            tag.setTransaction(transaction);
            tagService.update(tag);
        } else if (i % 5 == 2) {
            tag = new Tag();
            tag.setTime(dateNow);
            tag.setWeight(weight3);
            tag.setPrice(10f);
            tag.setVechile(vechileService.get("vechileNum", "CH-0003"));
            tag.setType(Enum_TagType.AR);
            tag.setCategory(category3);
            tag.setTagNum("RFID-3" + i);
            tag.setPlateformScale(plateformScale);
            //            String tagId = (String) tagService.save(tag);
            tags.add(tag);
            transaction = new Transaction();
            transaction.setTags(tags);
            transaction.setPrice(tag.getPrice());

            transaction.setTotalPrice(tag.getPrice() * tag.getWeight());
            transaction.setState(Enum_Transaction.IT);
            transaction.setInTime(dateNow);
            transaction.setOutTime(dateNow);
            transaction.setVechile(vechile3);
            transaction.setTransactionProperty(Enum_TransactionProperty.HAO);
            if (i % 2 == 0) {
                transaction.setCenter(center1);
                transaction.setSite(site1);
            } else {
                transaction.setCenter(center2);
                transaction.setSite(site2);
            }
            tagService.save(tag);
            transactionService.save(transaction);
            tag.setTransaction(transaction);
            tagService.update(tag);
        } else if (i % 5 == 3) {
            tag = new Tag();
            tag.setTime(dateNow);
            tag.setWeight(weight4);
            tag.setPrice(10f);
            tag.setType(Enum_TagType.AR);
            tag.setCategory(category4);
            tag.setVechile(vechileService.get("vechileNum", "CH-0004"));
            tag.setTagNum("RFID-4" + i);
            tag.setPlateformScale(plateformScale);
            //            String tagId = (String) tagService.save(tag);
            tags.add(tag);
            transaction = new Transaction();
            transaction.setTags(tags);
            transaction.setPrice(tag.getPrice());
            transaction.setTotalPrice(tag.getPrice() * tag.getWeight());
            transaction.setState(Enum_Transaction.IT);
            transaction.setInTime(dateNow);
            transaction.setOutTime(dateNow);
            transaction.setVechile(vechile4);
            transaction.setTransactionProperty(Enum_TransactionProperty.HAO);
            if (i % 2 == 0) {
                transaction.setCenter(center1);
                transaction.setSite(site1);
            } else {
                transaction.setCenter(center2);
                transaction.setSite(site2);
            }
            tagService.save(tag);
            transactionService.save(transaction);
            tag.setTransaction(transaction);
            tagService.update(tag);
        } else {
            tag = new Tag();
            tag.setTime(dateNow);
            tag.setWeight(weight5);
            tag.setPrice(10f);
            tag.setType(Enum_TagType.WR);
            tag.setCategory(category5);
            tag.setVechile(vechileService.get("vechileNum", "CH-0005"));
            tag.setTagNum("RFID-5" + i);
            tag.setPlateformScale(plateformScale);
            //            String tagId = (String) tagService.save(tag);
            tags.add(tag);
            transaction = new Transaction();
            transaction.setTags(tags);
            transaction.setPrice(tag.getPrice());
            transaction.setTotalPrice(tag.getPrice() * tag.getWeight());
            transaction.setState(Enum_Transaction.IT);
            transaction.setInTime(dateNow);
            transaction.setOutTime(dateNow);
            transaction.setVechile(vechile5);
            transaction.setTransactionProperty(Enum_TransactionProperty.HAO);
            if (i % 2 == 0) {
                transaction.setCenter(center1);
                transaction.setSite(site1);
            } else {
                transaction.setCenter(center2);
                transaction.setSite(site2);
            }
            tagService.save(tag);
            transactionService.save(transaction);
            tag.setTransaction(transaction);
            tagService.update(tag);
        }
        weight1 += 3f;
        weight2 += 2f;
        weight3 += 2.5f;
        weight4 += 1.5f;
        weight5 += 1.7f;
    }
    /*List<Transaction> transactions = new ArrayList<Transaction>();
    transactions = transactionService.getAll();
    for(Transaction t : transactions){
       if(t.getTags()!=null&&t.getTags().size()!=0){
    for(Tag tt : t.getTags()){
       if(tt.getCategory()!=null){
          if(tt.getCategory().getParentCategory()!=null){
             if(tt.getCategory().getParentCategory().getParentCategory()!=null){
                if(tt.getCategory().getParentCategory().getParentCategory().getParentCategory()!=null){
                   t.setCategoryName(tt.getCategory().getParentCategory().getParentCategory().getParentCategory().getName());
                }else{
                   t.setCategoryName(tt.getCategory().getParentCategory().getParentCategory().getName());
                }
             }else{
                t.setCategoryName(tt.getCategory().getParentCategory().getName());
             }
          }else{
             t.setCategoryName(tt.getCategory().getName());
          }
       }
       transactionService.update(t);
    }
       }
    }*/
}

From source file:org.redis.shop.test.InitData.java

@Test
public void br_addStockRemoval() {
    List<Category> categories = categoryService.getByProperty(categoryService.getAll(), "level", 3);
    List<Center> centers = centerService.getAll();
    List<Enterprise> enterprises = enterpriseService.getAll();

    GregorianCalendar cal = new GregorianCalendar();

    for (int i = 0; i < categories.size(); i++) {
        cal.setTime(new Date());
        cal.add(Calendar.DATE, 0 - i);
        for (int j = 0; j < centers.size(); j++) {
            for (int k = 0; k < enterprises.size(); k++) {
                StockRemoval stockRemoval = new StockRemoval();
                stockRemoval.setCategory(categories.get(i));
                stockRemoval.setCenter(centers.get(j));
                stockRemoval.setEnterprise(enterprises.get(k));
                stockRemoval.setInTime(cal.getTime());
                stockRemoval.setOutTime(cal.getTime());
                stockRemoval.setPrice(i * j * k + 1);
                stockRemoval.setWeight((i * j * k + 1) * 2);
                stockRemoval.setState(Enum_Transaction.CL);
                stockRemovalService.save(stockRemoval);
            }//from w w  w. j  av  a 2s .com
        }
    }

}

From source file:net.spfbl.http.ServerHTTP.java

private static void buildQueryRow(Locale locale, StringBuilder builder, DateFormat dateFormat,
        GregorianCalendar calendar, long time, User.Query query, boolean highlight) {
    if (query != null) {
        calendar.setTimeInMillis(time);//from www. j a  va  2s.co  m
        String ip = query.getIP();
        String hostname = query.getValidHostname();
        String sender = query.getSender();
        String from = query.getFrom();
        String replyto = query.getReplyTo();
        String subject = query.getSubject();
        String malware = query.getMalware();
        String recipient = query.getRecipient();
        String result = query.getResult();
        builder.append("        <tr id=\"");
        builder.append(time);
        builder.append("\"");
        if (highlight) {
            builder.append(" class=\"highlight\"");
        } else {
            builder.append(" class=\"click\"");
        }
        builder.append(" onclick=\"view('");
        builder.append(time);
        builder.append("')\">\n");
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("          <td style=\"width:120px;\">");
        } else {
            builder.append("          <td style=\"width:160px;\">");
        }
        builder.append(dateFormat.format(calendar.getTime()));
        builder.append("<br>");
        builder.append(query.getClient());
        builder.append("</td>\n");
        builder.append("          <td>");
        if (hostname == null) {
            String helo = query.getHELO();
            if (helo == null) {
                builder.append(ip);
            } else if (Subnet.isValidIP(helo)) {
                builder.append(ip);
            } else {
                builder.append(ip);
                builder.append("<br>");
                builder.append("<strike>");
                builder.append(helo);
                builder.append("</strike>");
            }
        } else if (Generic.containsDynamicDomain(hostname)) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("<small><i>Dinmico</i></small>");
            } else {
                builder.append("<small><i>Dynamic</i></small>");
            }
            builder.append("<br>");
            builder.append(hostname);
        } else if (Generic.containsGenericDomain(hostname)) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("<small><i>Genrico</i></small>");
            } else {
                builder.append("<small><i>Generic</i></small>");
            }
            builder.append("<br>");
            builder.append(hostname);
        } else if (Provider.containsDomain(hostname)) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("<small><i>Provedor</i></small>");
            } else {
                builder.append("<small><i>Provider</i></small>");
            }
            builder.append("<br>");
            builder.append(hostname);
        } else {
            builder.append(hostname);
        }
        builder.append("</td>\n");
        TreeSet<String> senderSet = new TreeSet<String>();
        builder.append("          <td>");
        if (sender == null) {
            builder.append("MAILER-DAEMON");
        } else {
            senderSet.add(sender);
            String qualifier = query.getQualifierName();
            if (qualifier.equals("PASS")) {
                if (locale.getLanguage().toLowerCase().equals("pt")) {
                    builder.append("<small><i>Comprovadamente autntico</i></small>");
                } else {
                    builder.append("<small><i>Proved genuine</i></small>");
                }
            } else if (qualifier.equals("FAIL")) {
                if (locale.getLanguage().toLowerCase().equals("pt")) {
                    builder.append("<small><i>Comprovadamente falso</i></small>");
                } else {
                    builder.append("<small><i>Proved false</i></small>");
                }
            } else if (qualifier.equals("SOFTFAIL")) {
                if (locale.getLanguage().toLowerCase().equals("pt")) {
                    builder.append("<small><i>Pode ser falso</i></small>");
                } else {
                    builder.append("<small><i>May be false</i></small>");
                }
            } else {
                if (locale.getLanguage().toLowerCase().equals("pt")) {
                    builder.append("<small><i>Pode ser autntico</i></small>");
                } else {
                    builder.append("<small><i>May be genuine</i></small>");
                }
            }
            builder.append("<br>");
            builder.append(sender);
        }
        boolean lineSeparator = false;
        if (from != null && !senderSet.contains(from)) {
            senderSet.add(from);
            builder.append("<hr style=\"height:0px;visibility:hidden;margin-bottom:0px;\">");
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("<small><b>De:</b> ");
            } else {
                builder.append("<small><b>From:</b> ");
            }
            builder.append(from);
            builder.append("</small>");
            lineSeparator = true;
        }
        if (replyto != null && !senderSet.contains(replyto)) {
            senderSet.add(replyto);
            if (lineSeparator) {
                builder.append("<br>");
            } else {
                builder.append("<hr style=\"height:0px;visibility:hidden;margin-bottom:0px;\">");
            }
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("<small><b>Responder para:</b> ");
            } else {
                builder.append("<small><b>Reply to:</b> ");
            }
            builder.append(replyto);
            builder.append("</small>");
        }
        builder.append("</td>\n");
        builder.append("          <td>");
        if (subject != null) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("<small><b>Assunto:</b> ");
            } else {
                builder.append("<small><b>Subject:</b> ");
            }
            builder.append(subject);
            builder.append("</small>");
            builder.append("<hr style=\"height:0px;visibility:hidden;margin-bottom:0px;\">");
        }
        if (malware == null) {
            TreeSet<String> linkSet = query.getLinkSet();
            if (linkSet == null) {
                if (locale.getLanguage().toLowerCase().equals("pt")) {
                    builder.append("<small><i>Corpo no verificado</i></small>");
                } else {
                    builder.append("<small><i>Body not verified</i></small>");
                }
            } else if (linkSet.isEmpty()) {
                if (locale.getLanguage().toLowerCase().equals("pt")) {
                    builder.append("<small><i>Sem links</i></small>");
                } else {
                    builder.append("<small><i>No links</i></small>");
                }
            } else {
                String link = linkSet.pollFirst();
                if (query.isLinkBlocked(link)) {
                    builder.append("<font color=\"DarkRed\"><b>");
                    builder.append(link);
                    builder.append("</b></font>");
                } else {
                    builder.append(link);
                }
                while (!linkSet.isEmpty()) {
                    builder.append("<br>");
                    link = linkSet.pollFirst();
                    if (query.isLinkBlocked(link)) {
                        builder.append("<font color=\"DarkRed\"><b>");
                        builder.append(link);
                        builder.append("</b></font>");
                    } else {
                        builder.append(link);
                    }
                }
            }
        } else {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("<small><i>Malware encontrado</i></small>");
            } else {
                builder.append("<small><i>Malware found</i></small>");
            }
            if (!malware.equals("FOUND")) {
                builder.append("<br>");
                builder.append("<font color=\"DarkRed\"><b>");
                builder.append(malware);
                builder.append("</b></font>");
            }
        }
        builder.append("</td>\n");
        builder.append("          <td>");
        if (result.equals("REJECT")) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Rejeitada pelo contedo");
            } else {
                builder.append("Rejected by content");
            }
            if (recipient != null) {
                builder.append("<br>");
                builder.append(recipient);
            }
        } else if (result.equals("BLOCK") || result.equals("BLOCKED")) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Rejeitada por bloqueio");
            } else {
                builder.append("Rejected by blocking");
            }
            if (recipient != null) {
                builder.append("<br>");
                builder.append(recipient);
            }
        } else if (result.equals("FAIL") || result.equals("FAILED")) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Rejeitada por falsidade");
            } else {
                builder.append("Rejected by falseness");
            }
        } else if (result.equals("INVALID")) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Rejeitada por origem invlida");
            } else {
                builder.append("Rejected by invalid source");
            }
        } else if (result.equals("GREYLIST")) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Atrasada por greylisting");
            } else {
                builder.append("Delayed by greylisting");
            }
            if (recipient != null) {
                builder.append("<br>");
                builder.append(recipient);
            }
        } else if (result.equals("SPAMTRAP") || result.equals("TRAP")) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Descartado pela armadilha");
            } else {
                builder.append("Discarded by spamtrap");
            }
            if (recipient != null) {
                builder.append("<br>");
                builder.append(recipient);
            }
        } else if (result.equals("INEXISTENT")) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Rejeitada por inexistncia");
            } else {
                builder.append("Rejected by non-existence");
            }
            if (recipient != null) {
                builder.append("<br>");
                builder.append(recipient);
            }
        } else if (result.equals("WHITE")) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Entrega prioritria");
            } else {
                builder.append("Priority delivery");
            }
            if (recipient != null) {
                builder.append("<br>");
                builder.append(recipient);
            }
        } else if (result.equals("ACCEPT")) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Entrega aceita");
            } else {
                builder.append("Accepted for delivery");
            }
            if (recipient != null) {
                builder.append("<br>");
                builder.append(recipient);
            }
        } else if (result.equals("FLAG")) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Marcada como suspeita");
            } else {
                builder.append("Marked as suspect");
            }
            if (recipient != null) {
                builder.append("<br>");
                builder.append(recipient);
            }
        } else if (result.equals("HOLD")) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Entrega retida");
            } else {
                builder.append("Delivery retained");
            }
            if (recipient != null) {
                builder.append("<br>");
                builder.append(recipient);
            }
        } else if (result.equals("NXDOMAIN")) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Rejeitada por domnio inexistente");
            } else {
                builder.append("Rejected by non-existent domain");
            }
        } else if (result.equals("NXSENDER")) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Rejeitada por remetente inexistente");
            } else {
                builder.append("Rejected by non-existent sender");
            }
        } else {
            builder.append(result);
            if (recipient != null) {
                builder.append("<br>");
                builder.append(recipient);
            }
        }
        builder.append("</td>\n");
        builder.append("        </tr>\n");
    }
}

From source file:org.sakaiproject.calendar.impl.BaseCalendarService.java

/**
 * Calculate the number of days in a range of time given two dates.
 * //from  www  .j  a  v a2s.  c o m
 * @param startMonth
 *        (zero based, 0-11)
 * @param startDay
 *        (one based, 1-31)
 * @param endYear
 *        (one based, 1-31)
 * @param endMonth
 *        (zero based, 0-11
 */
protected long getNumberDaysGivenTwoDates(int startYear, int startMonth, int startDay, int endYear,
        int endMonth, int endDay) {
    GregorianCalendar startDate = new GregorianCalendar();
    GregorianCalendar endDate = new GregorianCalendar();

    startDate.set(startYear, startMonth, startDay, 0, 0, 0);
    endDate.set(endYear, endMonth, endDay, 0, 0, 0);

    long duration = endDate.getTime().getTime() - startDate.getTime().getTime();

    // Allow for daylight savings time.
    return ((duration + MILLISECONDS_IN_HOUR) / (24 * MILLISECONDS_IN_HOUR)) + 1;
}

From source file:ru.apertum.qsystem.client.forms.FAdmin.java

private void buttonExportToCSVActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonExportToCSVActionPerformed
        final JFileChooser fc = new JFileChooser();
        fc.setDialogTitle(getLocaleMessage("save.statictic"));
        fc.setFileFilter(new FileFilter() {

            @Override/*from   w w w . j av  a 2 s  . co  m*/
            public boolean accept(File f) {
                return !f.isFile() || f.getAbsolutePath().toLowerCase().endsWith(".csv");
            }

            @Override
            public String getDescription() {
                return getLocaleMessage("files.type.csv");
            }
        });
        //fc.setCurrentDirectory(new File("config"));
        //fc.setSelectedFile(new File(configuration.getSystemName()));
        fc.setDialogType(JFileChooser.SAVE_DIALOG);
        if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            final File file;
            //This is where a real application would open the file.
            if (!fc.getSelectedFile().getAbsolutePath().toLowerCase().endsWith(".csv")) {
                file = new File(fc.getSelectedFile().getAbsoluteFile() + ".csv");
            } else {
                file = fc.getSelectedFile();
            }

            Spring.getInstance().getHt().getSessionFactory().openSession().doWork((Connection connection) -> {
                final GregorianCalendar gc = new GregorianCalendar();
                gc.setTime(dateChooserStartCsv.getDate());
                gc.set(GregorianCalendar.HOUR_OF_DAY, 0);
                gc.set(GregorianCalendar.MINUTE, 0);
                gc.set(GregorianCalendar.SECOND, 0);
                gc.set(GregorianCalendar.MILLISECOND, 0);
                final String std = Uses.format_for_rep.format(gc.getTime());
                gc.setTime(dateChooserFinishCsv.getDate());
                gc.set(GregorianCalendar.HOUR_OF_DAY, 0);
                gc.set(GregorianCalendar.MINUTE, 0);
                gc.set(GregorianCalendar.SECOND, 0);
                gc.set(GregorianCalendar.MILLISECOND, 0);
                gc.add(GregorianCalendar.HOUR, 24);
                final String find = Uses.format_for_rep.format(gc.getTime());
                final String sql = " SELECT " + "    s.client_id as id, "
                        + "    concat(c.service_prefix , c.number) as num, " + "    c.input_data as inp,  "
                        + "    DATE_FORMAT(s.client_stand_time, '%d.%m.%y %H:%i') as stnd, "
                        + "    sv.name as srv, " + "    DATE_FORMAT(s.user_start_time, '%d.%m.%y %H:%i') as strt, "
                        + "    DATE_FORMAT(s.user_finish_time, '%d.%m.%y %H:%i') as fin, " + "    u.name as usr, "
                        + "    s.client_wait_period as wt, " + "    s.user_work_period as wrk, "
                        + "    IFNULL(r.name, '') as res "
                        + " FROM statistic s left join results r on s.results_id=r.id, clients c, users u, services sv "
                        + " WHERE s.client_id=c.id and s.user_id=u.id and s.service_id=sv.id "
                        + "    and s.client_stand_time>='" + std + "' and s.client_stand_time<='" + find + "'";
                try (ResultSet set = connection.createStatement().executeQuery(sql)) {
                    final Writer writer;
                    try {
                        writer = new OutputStreamWriter(new FileOutputStream(file), "cp1251").append("");
                        writer.append("");
                        writer.append(cbSeparateCSV.getSelectedItem().toString());
                        writer.append(getLocaleMessage("csv.number"));
                        writer.append(cbSeparateCSV.getSelectedItem().toString());
                        writer.append(getLocaleMessage("csv.data"));
                        writer.append(cbSeparateCSV.getSelectedItem().toString());
                        writer.append(getLocaleMessage("csv.stand_time"));
                        writer.append(cbSeparateCSV.getSelectedItem().toString());
                        writer.append(getLocaleMessage("csv.service_name"));
                        writer.append(cbSeparateCSV.getSelectedItem().toString());
                        writer.append(getLocaleMessage("csv.start_time"));
                        writer.append(cbSeparateCSV.getSelectedItem().toString());
                        writer.append(getLocaleMessage("csv.finish_time"));
                        writer.append(cbSeparateCSV.getSelectedItem().toString());
                        writer.append(getLocaleMessage("csv.user"));
                        writer.append(cbSeparateCSV.getSelectedItem().toString());
                        writer.append(getLocaleMessage("csv.wait"));
                        writer.append(cbSeparateCSV.getSelectedItem().toString());
                        writer.append(getLocaleMessage("csv.work"));
                        writer.append(cbSeparateCSV.getSelectedItem().toString());
                        writer.append(getLocaleMessage("csv.result"));
                        writer.append('\n');

                        while (set.next()) {
                            writer.append(set.getString("id"));
                            writer.append(cbSeparateCSV.getSelectedItem().toString());
                            writer.append(set.getString("num"));
                            writer.append(cbSeparateCSV.getSelectedItem().toString());
                            writer.append(set.getString("inp"));
                            writer.append(cbSeparateCSV.getSelectedItem().toString());
                            writer.append(set.getString("stnd"));
                            writer.append(cbSeparateCSV.getSelectedItem().toString());
                            writer.append(
                                    set.getString("srv").replace(cbSeparateCSV.getSelectedItem().toString(), " "));
                            writer.append(cbSeparateCSV.getSelectedItem().toString());
                            writer.append(set.getString("strt"));
                            writer.append(cbSeparateCSV.getSelectedItem().toString());
                            writer.append(set.getString("fin"));
                            writer.append(cbSeparateCSV.getSelectedItem().toString());
                            writer.append(set.getString("usr"));
                            writer.append(cbSeparateCSV.getSelectedItem().toString());
                            writer.append(set.getString("wt"));
                            writer.append(cbSeparateCSV.getSelectedItem().toString());
                            writer.append(set.getString("wrk"));
                            writer.append(cbSeparateCSV.getSelectedItem().toString());
                            writer.append(set.getString("res"));
                            writer.append('\n');
                        }
                        //generate whatever data you want

                        writer.flush();
                        writer.close();
                    } catch (IOException ex) {
                        throw new ClientException(ex);
                    }
                }
                JOptionPane.showMessageDialog(fc, getLocaleMessage("stat.saved"), getLocaleMessage("stat.saving"),
                        JOptionPane.INFORMATION_MESSAGE);
            });

        }
    }

From source file:net.spfbl.http.ServerHTTP.java

private static String getControlPanel(Locale locale, Query query, long time) {
    DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, locale);
    GregorianCalendar calendar = new GregorianCalendar();
    calendar.setTimeInMillis(time);//w  ww  .ja  va2s .  c  o  m
    StringBuilder builder = new StringBuilder();
    //        builder.append("<!DOCTYPE html>\n");
    builder.append("<html lang=\"");
    builder.append(locale.getLanguage());
    builder.append("\">\n");
    builder.append("  <head>\n");
    builder.append("    <meta charset=\"UTF-8\">\n");
    if (locale.getLanguage().toLowerCase().equals("pt")) {
        builder.append("    <title>Painel de controle do SPFBL</title>\n");
    } else {
        builder.append("    <title>SPFBL control panel</title>\n");
    }
    // Styled page.
    builder.append("    <style type=\"text/css\">\n");
    builder.append("      body {");
    builder.append("        background: #b4b9d2;\n");
    builder.append("      }\n");
    builder.append("      .button {\n");
    builder.append("          background-color: #4CAF50;\n");
    builder.append("          border: none;\n");
    builder.append("          color: white;\n");
    builder.append("          padding: 16px 32px;\n");
    builder.append("          text-align: center;\n");
    builder.append("          text-decoration: none;\n");
    builder.append("          display: inline-block;\n");
    builder.append("          font-size: 16px;\n");
    builder.append("          margin: 4px 2px;\n");
    builder.append("          -webkit-transition-duration: 0.4s;\n");
    builder.append("          transition-duration: 0.4s;\n");
    builder.append("          cursor: pointer;\n");
    builder.append("      }\n");
    builder.append("      .white {\n");
    builder.append("          background-color: white; \n");
    builder.append("          color: black; \n");
    builder.append("          border: 2px solid #4CAF50;\n");
    builder.append("          font-weight: bold;\n");
    builder.append("      }\n");
    builder.append("      .white:hover {\n");
    builder.append("          background-color: #4CAF50;\n");
    builder.append("          color: white;\n");
    builder.append("      }\n");
    builder.append("      .block {\n");
    builder.append("          background-color: white; \n");
    builder.append("          color: black; \n");
    builder.append("          border: 2px solid #f44336;\n");
    builder.append("          font-weight: bold;\n");
    builder.append("      }\n");
    builder.append("      .block:hover {\n");
    builder.append("          background-color: #f44336;\n");
    builder.append("          color: white;\n");
    builder.append("      }\n");
    builder.append("      .recipient {\n");
    builder.append("          background-color: white; \n");
    builder.append("          color: black; \n");
    builder.append("          border: 2px solid #555555;\n");
    builder.append("          font-weight: bold;\n");
    builder.append("      }\n");
    builder.append("      .recipient:hover {\n");
    builder.append("          background-color: #555555;\n");
    builder.append("          color: white;\n");
    builder.append("      }\n");
    builder.append("    </style>\n");
    builder.append("  </head>\n");
    // Body.
    builder.append("  <body>\n");
    if (locale.getLanguage().toLowerCase().equals("pt")) {
        builder.append("    <b>Recepo:</b> ");
    } else {
        builder.append("    <b>Reception:</b> ");
    }
    builder.append(dateFormat.format(calendar.getTime()));
    builder.append("<br>\n");
    String sender = query.getSenderSimplified(false, false);
    if (sender == null) {
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("    <b>Remetente:</b> MAILER-DAEMON");
        } else {
            builder.append("    <b>Sender:</b> MAILER-DAEMON");
        }
    } else if (query.getQualifierName().equals("PASS")) {
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("    <b>Remetente autntico:</b> ");
        } else {
            builder.append("    <b>Genuine sender:</b> ");
        }
        builder.append(sender);
    } else if (query.getQualifierName().equals("FAIL")) {
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("    <b>Remetente falso:</b> ");
        } else {
            builder.append("    <b>False sender:</b> ");
        }
        builder.append(sender);
    } else {
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("    <b>Remetente suspeito:</b> ");
        } else {
            builder.append("    <b>Suspect sender:</b> ");
        }
        builder.append(sender);
    }
    builder.append("<br>\n");
    if (locale.getLanguage().toLowerCase().equals("pt")) {
        builder.append("    <b>Recebe por:</b> ");
    } else {
        builder.append("    <b>Receives for:</b> ");
    }
    String validator = query.getValidator(true);
    Situation situationWhite = query.getSenderWhiteSituation();
    Situation situationBlock = query.getSenderBlockSituation();
    try {
        TreeSet<String> mxDomainSet = query.getSenderMXDomainSet();
        if (mxDomainSet.isEmpty()) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("nenhum sistema");
            } else {
                builder.append("no system");
            }
        } else {
            builder.append(mxDomainSet);
        }
    } catch (NameNotFoundException ex) {
        validator = null;
        situationWhite = query.getOriginWhiteSituation();
        situationBlock = query.getOriginBlockSituation();
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("domnio inexistente");
        } else {
            builder.append("non-existent domain");
        }
    } catch (NamingException ex) {
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("erro ao tentar consultar");
        } else {
            builder.append("error when trying to query");
        }
    }
    builder.append("<br>\n");
    URL unsubscribe = query.getUnsubscribeURL();
    if (unsubscribe == null) {
        builder.append("    <br>\n");
    } else {
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("     <b>Cancelar inscrio:</b> ");
        } else {
            builder.append("     <b>List unsubscribe:</b> ");
        }
        builder.append("<a target=\"_blank\" href=\"");
        builder.append(unsubscribe);
        builder.append("\">");
        builder.append(unsubscribe.getHost());
        builder.append(unsubscribe.getPath());
        builder.append("</a><br>\n");
    }
    if (locale.getLanguage().toLowerCase().equals("pt")) {
        builder.append("    <b>Politica vigente:</b> ");
    } else {
        builder.append("    <b>Current policy:</b> ");
    }
    String recipient = query.getRecipient();
    Long trapTime = query.getTrapTime();
    boolean blocked = false;
    if (trapTime == null && situationWhite == Situation.SAME) {
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("entrega prioritria na mesma situao, exceto malware");
        } else {
            builder.append("priority delivery of ");
            builder.append(query.getSenderSimplified(false, true));
            builder.append(" in the same situation, except malware");
        }
    } else if (trapTime == null && situationWhite == Situation.AUTHENTIC) {
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("entrega prioritria de ");
            builder.append(query.getSenderSimplified(false, true));
            builder.append(" quando comprovadamente autntico, exceto malware");
        } else {
            builder.append("priority delivery of ");
            builder.append(query.getSenderSimplified(false, true));
            builder.append(" when proven authentic, except malware");
        }
        if (query.isBlock()) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append(", porm bloqueado para outras situaes");
            } else {
                builder.append(", however blocked to other situations");
            }
        }
    } else if (trapTime == null && situationWhite == Situation.ZONE) {
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("entrega prioritria de ");
            builder.append(query.getSenderSimplified(false, true));
            builder.append(" quando disparado por ");
        } else {
            builder.append("priority delivery of ");
            builder.append(query.getSenderSimplified(false, true));
            builder.append(" when shot by ");
        }
        builder.append(validator);
        if (query.isBlock()) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append(", porm bloqueado para outras situaes");
            } else {
                builder.append(", however blocked to other situations");
            }
        }
    } else if (trapTime == null && situationWhite == Situation.IP) {
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("entrega prioritria de ");
            builder.append(query.getSenderSimplified(false, true));
            builder.append(" when shot by IP ");
        } else {
            builder.append("priority delivery of ");
            builder.append(query.getSenderSimplified(false, true));
            builder.append(" when coming from the IP ");
        }
        builder.append(validator);
        if (query.isBlock()) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append(", porm bloqueado para outras situaes");
            } else {
                builder.append(", however blocked to other situations");
            }
        }
    } else if (trapTime == null && situationWhite == Situation.ORIGIN) {
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("entrega prioritria pela mesma origem");
        } else {
            builder.append("priority delivery the same origin");
        }
    } else if (situationBlock == Situation.DOMAIN) {
        blocked = true;
        String domain = query.getSenderSimplified(true, false);
        if (domain == null) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("bloquear na mesma situao");
            } else {
                builder.append("block in the same situation");
            }
        } else {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("bloquear ");
                builder.append(domain);
                builder.append(" em qualquer situao");
            } else {
                builder.append("block ");
                builder.append(domain);
                builder.append(" in any situation");
            }
        }
    } else if (situationBlock == Situation.ALL) {
        blocked = true;
        String domain = query.getOriginDomain(false);
        if (domain == null) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("bloquear na mesma situao");
            } else {
                builder.append("block in the same situation");
            }
        } else {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("bloquear ");
                builder.append(domain);
                builder.append(" em qualquer situao");
            } else {
                builder.append("block ");
                builder.append(domain);
                builder.append(" in any situation");
            }
        }
    } else if (situationBlock == Situation.SAME) {
        blocked = true;
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("bloquear na mesma situao");
        } else {
            builder.append("block in the same situation");
        }
    } else if ((situationBlock == Situation.ZONE || situationBlock == Situation.IP)
            && !query.getQualifierName().equals("PASS")) {
        blocked = true;
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("bloquear ");
            builder.append(query.getSenderDomain(false));
            builder.append(" quando no for autntico");
        } else {
            builder.append("block ");
            builder.append(query.getSenderDomain(false));
            builder.append(" when not authentic");
        }
    } else if (situationBlock == Situation.ORIGIN) {
        blocked = true;
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("bloquear quando disparado pela mesma origem");
        } else {
            builder.append("block when shot by the same source");
        }
    } else if (query.isFail()) {
        blocked = true;
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("rejeitar entrega por falsificao");
        } else {
            builder.append("reject delivery of forgery");
        }
    } else if (trapTime != null) {
        if (System.currentTimeMillis() > trapTime) {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("descartar mensagem por armadilha");
            } else {
                builder.append("discard message by spamtrap");
            }
        } else {
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("rejeitar entrega por destinatrio inexistente");
            } else {
                builder.append("reject delivery by inexistent recipient");
            }
        }
    } else if (query.hasTokenRed() || query.hasClusterRed()) {
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("marcar como suspeita e entregar, sem considerar o contedo");
        } else {
            builder.append("flag as suspected and deliver, regardless of content");
        }
    } else if (query.isSoftfail() || query.hasYellow()) {
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("atrasar entrega na mesma situao, sem considerar o contedo");
        } else {
            builder.append("delay delivery in the same situation, regardless of content");
        }
    } else {
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("aceitar entrega na mesma situao, sem considerar o contedo");
        } else {
            builder.append("accept delivery in the same situation, regardless of content");
        }
    }
    builder.append(".<br>\n");
    builder.append("    <form method=\"POST\">\n");
    if (validator == null) {
        if (situationWhite != Situation.ORIGIN) {
            builder.append(
                    "      <button type=\"submit\" class=\"white\" name=\"POLICY\" value=\"WHITE_ORIGIN\">");
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Entrega prioritria quando for da mesma origem\n");
            } else {
                builder.append("Priority delivery when the same origin\n");
            }
            builder.append("</button>\n");
        }
        if (situationWhite != Situation.NONE || situationBlock != Situation.ALL) {
            if (situationBlock != Situation.ORIGIN) {
                builder.append(
                        "      <button type=\"submit\" class=\"block\" name=\"POLICY\" value=\"BLOCK_ORIGIN\">");
                if (locale.getLanguage().toLowerCase().equals("pt")) {
                    builder.append("Bloquear se for da mesma origem");
                } else {
                    builder.append("Block if the same origin");
                }
                builder.append("</button>\n");
            }
            String domain = query.getOriginDomain(false);
            if (domain != null) {
                builder.append(
                        "      <button type=\"submit\" class=\"block\" name=\"POLICY\" value=\"BLOCK_ALL\">");
                if (locale.getLanguage().toLowerCase().equals("pt")) {
                    builder.append("Bloquear ");
                    builder.append(domain);
                    builder.append(" em qualquer situao");
                } else {
                    builder.append("Block ");
                    builder.append(domain);
                    builder.append(" in any situation");
                }
                builder.append("</button>\n");
            }
        }
    } else if (validator.equals("PASS")) {
        if (situationWhite != Situation.AUTHENTIC) {
            builder.append(
                    "      <button type=\"submit\" class=\"white\" name=\"POLICY\" value=\"WHITE_AUTHENTIC\">");
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Entrega prioritria quando comprovadamente autntico\n");
            } else {
                builder.append("Priority delivery when proven authentic\n");
            }
            builder.append("</button>\n");
        }
    } else if (Subnet.isValidIP(validator)) {
        if (situationWhite != Situation.IP) {
            builder.append("      <button type=\"submit\" class=\"white\" name=\"POLICY\" value=\"WHITE_IP\">");
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Entrega prioritria quando disparado pelo IP ");
            } else {
                builder.append("Priority delivery when shot by IP ");
            }
            builder.append(validator);
            builder.append("</button>\n");
        }
        if (situationBlock != Situation.IP && situationBlock != Situation.DOMAIN) {
            builder.append("      <button type=\"submit\" class=\"block\" name=\"POLICY\" value=\"BLOCK_IP\">");
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Bloquear ");
                builder.append(query.getSenderDomain(false));
                builder.append(" quando no for autntico");
            } else {
                builder.append("Block ");
                builder.append(query.getSenderDomain(false));
                builder.append(" when not authentic");
            }
            builder.append("</button>\n");
        }
    } else if (Domain.isHostname(validator)) {
        if (situationWhite != Situation.ZONE) {
            builder.append(
                    "      <button type=\"submit\" class=\"white\" name=\"POLICY\" value=\"WHITE_ZONE\">");
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Entrega prioritria quando disparado por ");
            } else {
                builder.append("Priority delivery when shot by ");
            }
            builder.append(validator);
            builder.append("</button>\n");
        }
        if (situationBlock != Situation.ZONE && situationBlock != Situation.DOMAIN) {
            builder.append(
                    "      <button type=\"submit\" class=\"block\" name=\"POLICY\" value=\"BLOCK_ZONE\">");
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append("Bloquear ");
                builder.append(query.getSenderDomain(false));
                builder.append(" quando no for autntico");
            } else {
                builder.append("Block ");
                builder.append(query.getSenderDomain(false));
                builder.append(" when not authentic");
            }
            builder.append("</button>\n");
        }
    }
    if (situationBlock != Situation.DOMAIN && validator != null) {
        builder.append("      <button type=\"submit\" class=\"block\" name=\"POLICY\" value=\"BLOCK_DOMAIN\">");
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("Bloquear ");
            builder.append(query.getSenderSimplified(true, false));
            builder.append(" em qualquer situao");
        } else {
            builder.append("Block ");
            builder.append(query.getSenderSimplified(true, false));
            builder.append(" in any situation");
        }
        builder.append("</button>\n");
    }
    if (!blocked && recipient != null && trapTime != null && query.getUser().isPostmaster()) {
        builder.append(
                "      <button type=\"submit\" class=\"recipient\" name=\"POLICY\" value=\"WHITE_RECIPIENT\">");
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("Tornar ");
            builder.append(recipient);
            builder.append(" existente");
        } else {
            builder.append("Make ");
            builder.append(recipient);
            builder.append(" existent");
        }
        builder.append("</button>\n");
    }
    builder.append("    </form>\n");
    builder.append("  </body>\n");
    builder.append("</html>\n");
    return builder.toString();
}

From source file:org.sakaiproject.assignment.tool.AssignmentAction.java

/**
 * supplement item related information//from w ww.j  a  v  a  2 s .c  om
 * @param state
 * @param params
 * @param siteId
 * @param a
 */
private void saveAssignmentSupplementItem(SessionState state, ParameterParser params, String siteId,
        AssignmentEdit a) {
    // assignment supplement items
    String aId = a.getId();
    //model answer
    if (state.getAttribute(MODELANSWER_TO_DELETE) != null
            && "true".equals((String) state.getAttribute(MODELANSWER_TO_DELETE))) {
        // to delete the model answer
        AssignmentModelAnswerItem mAnswer = m_assignmentSupplementItemService.getModelAnswer(aId);
        if (mAnswer != null) {
            m_assignmentSupplementItemService.cleanAttachment(mAnswer);
            m_assignmentSupplementItemService.removeModelAnswer(mAnswer);
        }
    } else if (state.getAttribute(MODELANSWER_TEXT) != null) {
        // edit/add model answer
        AssignmentModelAnswerItem mAnswer = m_assignmentSupplementItemService.getModelAnswer(aId);
        if (mAnswer == null) {
            mAnswer = m_assignmentSupplementItemService.newModelAnswer();
            m_assignmentSupplementItemService.saveModelAnswer(mAnswer);
        }
        mAnswer.setAssignmentId(a.getId());
        mAnswer.setText((String) state.getAttribute(MODELANSWER_TEXT));
        mAnswer.setShowTo(state.getAttribute(MODELANSWER_SHOWTO) != null
                ? Integer.parseInt((String) state.getAttribute(MODELANSWER_SHOWTO))
                : 0);
        mAnswer.setAttachmentSet(
                getAssignmentSupplementItemAttachment(state, mAnswer, MODELANSWER_ATTACHMENTS));
        m_assignmentSupplementItemService.saveModelAnswer(mAnswer);
    }
    // note
    if (state.getAttribute(NOTE_TO_DELETE) != null
            && "true".equals((String) state.getAttribute(NOTE_TO_DELETE))) {
        // to remove note item
        AssignmentNoteItem nNote = m_assignmentSupplementItemService.getNoteItem(aId);
        if (nNote != null)
            m_assignmentSupplementItemService.removeNoteItem(nNote);
    } else if (state.getAttribute(NOTE_TEXT) != null) {
        // edit/add private note
        AssignmentNoteItem nNote = m_assignmentSupplementItemService.getNoteItem(aId);
        if (nNote == null)
            nNote = m_assignmentSupplementItemService.newNoteItem();
        nNote.setAssignmentId(a.getId());
        nNote.setNote((String) state.getAttribute(NOTE_TEXT));
        nNote.setShareWith(state.getAttribute(NOTE_SHAREWITH) != null
                ? Integer.parseInt((String) state.getAttribute(NOTE_SHAREWITH))
                : 0);
        nNote.setCreatorId(UserDirectoryService.getCurrentUser().getId());
        m_assignmentSupplementItemService.saveNoteItem(nNote);
    }
    // all purpose
    if (state.getAttribute(ALLPURPOSE_TO_DELETE) != null
            && "true".equals((String) state.getAttribute(ALLPURPOSE_TO_DELETE))) {
        // to remove allPurpose item
        AssignmentAllPurposeItem nAllPurpose = m_assignmentSupplementItemService.getAllPurposeItem(aId);
        if (nAllPurpose != null) {
            m_assignmentSupplementItemService.cleanAttachment(nAllPurpose);
            m_assignmentSupplementItemService.cleanAllPurposeItemAccess(nAllPurpose);
            m_assignmentSupplementItemService.removeAllPurposeItem(nAllPurpose);
        }
    } else if (state.getAttribute(ALLPURPOSE_TITLE) != null) {
        // edit/add private note
        AssignmentAllPurposeItem nAllPurpose = m_assignmentSupplementItemService.getAllPurposeItem(aId);
        if (nAllPurpose == null) {
            nAllPurpose = m_assignmentSupplementItemService.newAllPurposeItem();
            m_assignmentSupplementItemService.saveAllPurposeItem(nAllPurpose);
        }
        nAllPurpose.setAssignmentId(a.getId());
        nAllPurpose.setTitle((String) state.getAttribute(ALLPURPOSE_TITLE));
        nAllPurpose.setText((String) state.getAttribute(ALLPURPOSE_TEXT));

        boolean allPurposeShowFrom = state.getAttribute(ALLPURPOSE_SHOW_FROM) != null
                ? ((Boolean) state.getAttribute(ALLPURPOSE_SHOW_FROM)).booleanValue()
                : false;
        boolean allPurposeShowTo = state.getAttribute(ALLPURPOSE_SHOW_TO) != null
                ? ((Boolean) state.getAttribute(ALLPURPOSE_SHOW_TO)).booleanValue()
                : false;
        boolean allPurposeHide = state.getAttribute(ALLPURPOSE_HIDE) != null
                ? ((Boolean) state.getAttribute(ALLPURPOSE_HIDE)).booleanValue()
                : false;
        nAllPurpose.setHide(allPurposeHide);
        // save the release and retract dates
        if (allPurposeShowFrom && !allPurposeHide) {
            // save release date
            Time releaseTime = getTimeFromState(state, ALLPURPOSE_RELEASE_MONTH, ALLPURPOSE_RELEASE_DAY,
                    ALLPURPOSE_RELEASE_YEAR, ALLPURPOSE_RELEASE_HOUR, ALLPURPOSE_RELEASE_MIN);
            GregorianCalendar cal = new GregorianCalendar();
            cal.setTimeInMillis(releaseTime.getTime());
            nAllPurpose.setReleaseDate(cal.getTime());
        } else {
            nAllPurpose.setReleaseDate(null);
        }
        if (allPurposeShowTo && !allPurposeHide) {
            // save retract date
            Time retractTime = getTimeFromState(state, ALLPURPOSE_RETRACT_MONTH, ALLPURPOSE_RETRACT_DAY,
                    ALLPURPOSE_RETRACT_YEAR, ALLPURPOSE_RETRACT_HOUR, ALLPURPOSE_RETRACT_MIN);
            GregorianCalendar cal = new GregorianCalendar();
            cal.setTimeInMillis(retractTime.getTime());
            nAllPurpose.setRetractDate(cal.getTime());
        } else {
            nAllPurpose.setRetractDate(null);
        }
        nAllPurpose.setAttachmentSet(
                getAssignmentSupplementItemAttachment(state, nAllPurpose, ALLPURPOSE_ATTACHMENTS));

        // clean the access list first
        if (state.getAttribute(ALLPURPOSE_ACCESS) != null) {
            // get the access settings
            List<String> accessList = (List<String>) state.getAttribute(ALLPURPOSE_ACCESS);

            m_assignmentSupplementItemService.cleanAllPurposeItemAccess(nAllPurpose);
            Set<AssignmentAllPurposeItemAccess> accessSet = new HashSet<AssignmentAllPurposeItemAccess>();
            try {
                AuthzGroup realm = authzGroupService.getAuthzGroup(SiteService.siteReference(siteId));
                Set<Role> roles = realm.getRoles();
                for (Iterator iRoles = roles.iterator(); iRoles.hasNext();) {
                    // iterator through roles first
                    Role r = (Role) iRoles.next();
                    if (accessList.contains(r.getId())) {
                        AssignmentAllPurposeItemAccess access = m_assignmentSupplementItemService
                                .newAllPurposeItemAccess();
                        access.setAccess(r.getId());
                        access.setAssignmentAllPurposeItem(nAllPurpose);
                        m_assignmentSupplementItemService.saveAllPurposeItemAccess(access);
                        accessSet.add(access);
                    } else {
                        // if the role is not selected, iterate through the users with this role
                        Set userIds = realm.getUsersHasRole(r.getId());
                        for (Iterator iUserIds = userIds.iterator(); iUserIds.hasNext();) {
                            String userId = (String) iUserIds.next();
                            if (accessList.contains(userId)) {
                                AssignmentAllPurposeItemAccess access = m_assignmentSupplementItemService
                                        .newAllPurposeItemAccess();
                                access.setAccess(userId);
                                access.setAssignmentAllPurposeItem(nAllPurpose);
                                m_assignmentSupplementItemService.saveAllPurposeItemAccess(access);
                                accessSet.add(access);
                            }
                        }
                    }
                }
            } catch (Exception e) {
                M_log.warn(this + ":post_save_assignment " + e.toString() + "error finding authzGroup for = "
                        + siteId);
            }
            nAllPurpose.setAccessSet(accessSet);
        }
        m_assignmentSupplementItemService.saveAllPurposeItem(nAllPurpose);
    }
}

From source file:com.aimluck.eip.schedule.util.ScheduleUtils.java

public static boolean isDuplicateFacilitySchedule(EipTSchedule schedule, List<Integer> facilityIdList,
        Integer _old_scheduleid, Date _old_viewDate) {
    /*  */// w ww.j  a  v  a2s .  c o m
    GregorianCalendar cald = new GregorianCalendar();

    boolean result = false;
    {

        Date start_date;
        Date end_date;
        String repeat_pattern;
        String repeat_type;
        String repeat_week = null;
        boolean week_0;
        boolean week_1;
        boolean week_2;
        boolean week_3;
        boolean week_4;
        boolean week_5;
        boolean week_6;
        boolean day_of_week_in_month_1;
        boolean day_of_week_in_month_2;
        boolean day_of_week_in_month_3;
        boolean day_of_week_in_month_4;
        boolean day_of_week_in_month_5;
        boolean[] day_of_week_in_month_array = new boolean[5];
        String limit_flag;
        int month_day = -1;
        int year_month = -1;
        int year_day = -1;
        Integer db_scheduleid = null;
        boolean[] week_array = new boolean[7];
        boolean unlimited_repeat = false;
        try {
            start_date = schedule.getStartDate();

            end_date = schedule.getEndDate();

            repeat_pattern = schedule.getRepeatPattern();

            repeat_type = repeat_pattern.substring(0, 1);

            day_of_week_in_month_1 = repeat_pattern.matches("W.......1.?");

            day_of_week_in_month_2 = repeat_pattern.matches("W.......2.?");

            day_of_week_in_month_3 = repeat_pattern.matches("W.......3.?");

            day_of_week_in_month_4 = repeat_pattern.matches("W.......4.?");

            day_of_week_in_month_5 = repeat_pattern.matches("W.......5.?");

            if (repeat_type.equals("W")) {
                if (repeat_pattern.length() == 9) {
                    repeat_week = "0";
                    day_of_week_in_month_1 = true;
                    day_of_week_in_month_2 = true;
                    day_of_week_in_month_3 = true;
                    day_of_week_in_month_4 = true;
                    day_of_week_in_month_5 = true;
                } else {
                    repeat_week = repeat_pattern.substring(8, 9);
                }
            }

            limit_flag = repeat_pattern.substring(repeat_pattern.length() - 1);

            week_0 = repeat_pattern.matches("W1........?");

            week_1 = repeat_pattern.matches("W.1.......?");

            week_2 = repeat_pattern.matches("W..1......?");

            week_3 = repeat_pattern.matches("W...1.....?");

            week_4 = repeat_pattern.matches("W....1....?");

            week_5 = repeat_pattern.matches("W.....1...?");

            week_6 = repeat_pattern.matches("W......1..?");

            if (repeat_pattern.startsWith("M")) {
                month_day = Integer.parseInt(repeat_pattern.substring(1, 3));
            }

            if (repeat_pattern.startsWith("Y")) {
                year_month = Integer.parseInt(repeat_pattern.substring(1, 3));
                year_day = Integer.parseInt(repeat_pattern.substring(3, 5));
            }
            // ???1??????
            if (repeat_pattern.startsWith("N")) {
                Calendar cal = Calendar.getInstance();
                cal.setTime(start_date);
                int dow = cal.get(Calendar.DAY_OF_WEEK);
                week_0 = (dow == Calendar.SUNDAY);
                week_1 = (dow == Calendar.MONDAY);
                week_2 = (dow == Calendar.TUESDAY);
                week_3 = (dow == Calendar.WEDNESDAY);
                week_4 = (dow == Calendar.THURSDAY);
                week_5 = (dow == Calendar.FRIDAY);
                week_6 = (dow == Calendar.SATURDAY);
                month_day = cal.get(Calendar.DAY_OF_MONTH);
                int dowim = cal.get(Calendar.DAY_OF_WEEK_IN_MONTH);
                day_of_week_in_month_1 = (dowim == 1);
                day_of_week_in_month_2 = (dowim == 2);
                day_of_week_in_month_3 = (dowim == 3);
                day_of_week_in_month_4 = (dowim == 4);
                day_of_week_in_month_5 = (dowim == 5);
                year_month = cal.get(Calendar.MONTH) + 1;
                year_day = cal.get(Calendar.DAY_OF_MONTH);
            } else if (repeat_pattern.endsWith("N")) {
                unlimited_repeat = true;
            }

            week_array[0] = week_0;
            week_array[1] = week_1;
            week_array[2] = week_2;
            week_array[3] = week_3;
            week_array[4] = week_4;
            week_array[5] = week_5;
            week_array[6] = week_6;

            day_of_week_in_month_array[0] = day_of_week_in_month_1;
            day_of_week_in_month_array[1] = day_of_week_in_month_2;
            day_of_week_in_month_array[2] = day_of_week_in_month_3;
            day_of_week_in_month_array[3] = day_of_week_in_month_4;
            day_of_week_in_month_array[4] = day_of_week_in_month_5;

        } catch (RuntimeException e) {
            logger.error("schedule", e);
            return false;
        } catch (Exception e) {
            logger.error("schedule", e);
            return false;
        }

        if (repeat_type.equals("S")) {
            // ??0:00:00?????23:59:59??
            Calendar cal = Calendar.getInstance();
            cal.setTime(end_date);
            cal.add(Calendar.DATE, 1);
            cal.add(Calendar.MINUTE, -1);
            end_date = cal.getTime();
        }

        // ???
        if (facilityIdList.size() > 0) {//
            List<Integer> fids = facilityIdList;
            SelectQuery<EipTScheduleMap> fquery = Database.query(EipTScheduleMap.class);
            Expression fexp1 = ExpressionFactory.inExp(EipTScheduleMap.USER_ID_PROPERTY, fids);
            fquery.setQualifier(fexp1);

            Expression fexp2 = ExpressionFactory.matchExp(EipTScheduleMap.TYPE_PROPERTY,
                    ScheduleUtils.SCHEDULEMAP_TYPE_FACILITY);
            fquery.andQualifier(fexp2);

            Expression oneexp = null;// 1
            Expression spanexp = null;// 
            Expression rdexp = null;// 
            Expression rwexp = null;// 
            Expression rwexp2 = null;
            // Expression rwlexp = null;
            Expression rmexp = null;// 
            Expression ryexp = null;

            { // ?
                Expression exp100 = ExpressionFactory.matchExp(
                        EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "." + EipTSchedule.REPEAT_PATTERN_PROPERTY,
                        "N");

                try {
                    if (!unlimited_repeat) {
                        Expression exp101 = ExpressionFactory.lessOrEqualExp(
                                EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "." + EipTSchedule.START_DATE_PROPERTY,
                                end_date);// EipTSchedule.START_DATE_PROPERTY <= end_date
                        Expression exp102 = ExpressionFactory.greaterExp(
                                EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "." + EipTSchedule.END_DATE_PROPERTY,
                                start_date);// EipTSchedule.END_DATE_PROPERTY > start_date

                        oneexp = exp100.andExp(exp101.andExp(exp102));

                    } else {
                        oneexp = exp100;
                    }
                } catch (Exception e) {

                }
            }

            { // ?
                Expression exp200 = ExpressionFactory.matchExp(
                        EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "." + EipTSchedule.REPEAT_PATTERN_PROPERTY,
                        "S");

                try {
                    if (!unlimited_repeat) {
                        // ??00:00??????
                        Calendar cal_end = Calendar.getInstance();
                        cal_end.setTime(end_date);
                        cal_end = DateUtils.truncate(cal_end, Calendar.DAY_OF_MONTH);
                        Expression exp201 = ExpressionFactory.lessOrEqualExp(
                                EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "." + EipTSchedule.START_DATE_PROPERTY,
                                cal_end.getTime());
                        // EipTSchedule.START_DATE_PROPERTY <= end_date
                        Calendar cal_start = Calendar.getInstance();
                        cal_start.setTime(start_date);
                        cal_start = DateUtils.truncate(cal_start, Calendar.DAY_OF_MONTH);
                        Expression exp202 = ExpressionFactory.greaterOrEqualExp(
                                EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "." + EipTSchedule.END_DATE_PROPERTY,
                                cal_start.getTime());
                        // EipTSchedule.END_DATE_PROPERTY >= start_date

                        spanexp = exp200.andExp(exp201.andExp(exp202));

                    } else {
                        spanexp = exp200;
                    }
                } catch (Exception e) {

                }
            }

            { // ??
              // char lim = 'N';
                if ("ON".equals(limit_flag)) {
                    // lim = 'L';
                }

                { // "D".equals(repeat_type.getValue())
                    Expression dexp01 = ExpressionFactory.likeExp(
                            EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "." + EipTSchedule.REPEAT_PATTERN_PROPERTY,
                            "D_");
                    rdexp = dexp01;
                }

                { // "W".equals(repeat_type.getValue())
                    Expression wexp = null;
                    List<Expression> wexps = new ArrayList<Expression>();
                    if (week_0 == true) {
                        wexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W1_______");
                        wexps.add(wexp);
                    }
                    if (week_1 == true) {
                        wexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W_1______");
                        wexps.add(wexp);
                    }
                    if (week_2 == true) {
                        wexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W__1_____");
                        wexps.add(wexp);
                    }
                    if (week_3 == true) {
                        wexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W___1____");
                        wexps.add(wexp);
                    }
                    if (week_4 == true) {
                        wexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W____1___");
                        wexps.add(wexp);
                    }
                    if (week_5 == true) {
                        wexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W_____1__");
                        wexps.add(wexp);
                    }
                    if (week_6 == true) {
                        wexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W______1_");
                        wexps.add(wexp);
                    }
                    if (wexps.size() > 0) {
                        rwexp = wexps.get(0);
                        int wexpssize = wexps.size();
                        for (int k = 1; k < wexpssize; k++) {
                            rwexp = rwexp.orExp(wexps.get(k));
                        }
                    } else {
                        rwexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W________");
                    }
                }
                {
                    Expression wexp2 = null;
                    List<Expression> wexps2 = new ArrayList<Expression>();
                    Expression wnexp = null;
                    List<Expression> wnexp2 = new ArrayList<Expression>();

                    if (week_0 == true) {
                        wexp2 = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W1________");
                        wexps2.add(wexp2);
                    }
                    if (week_1 == true) {
                        wexp2 = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W_1_______");
                        wexps2.add(wexp2);
                    }
                    if (week_2 == true) {
                        wexp2 = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W__1______");
                        wexps2.add(wexp2);
                    }
                    if (week_3 == true) {
                        wexp2 = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W___1_____");
                        wexps2.add(wexp2);
                    }
                    if (week_4 == true) {
                        wexp2 = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W____1____");
                        wexps2.add(wexp2);
                    }
                    if (week_5 == true) {
                        wexp2 = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W_____1___");
                        wexps2.add(wexp2);
                    }
                    if (week_6 == true) {
                        wexp2 = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W______1__");
                        wexps2.add(wexp2);
                    }
                    if (repeat_week != null && repeat_week.equals("1") || day_of_week_in_month_1) {
                        wnexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W_______1_");
                        wnexp2.add(wnexp);
                    }
                    if (repeat_week != null && repeat_week.equals("2") || day_of_week_in_month_2) {
                        wnexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W_______2_");
                        wnexp2.add(wnexp);
                    }
                    if (repeat_week != null && repeat_week.equals("3") || day_of_week_in_month_3) {
                        wnexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W_______3_");
                        wnexp2.add(wnexp);
                    }
                    if (repeat_week != null && repeat_week.equals("4") || day_of_week_in_month_4) {
                        wnexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W_______4_");
                        wnexp2.add(wnexp);
                    }
                    if (repeat_week != null && repeat_week.equals("5") || day_of_week_in_month_5) {
                        wnexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W_______5_");
                        wnexp2.add(wnexp);
                    }
                    if (wexps2.size() > 0 && wnexp2.size() > 0) {
                        for (int k = 0; k < wexps2.size(); k++) {
                            for (int l = 0; l < wnexp2.size(); l++) {
                                if (k == 0 && l == 0) {
                                    rwexp2 = wexps2.get(k).andExp(wnexp2.get(l));
                                } else {
                                    rwexp2 = rwexp2.orExp(wexps2.get(k).andExp(wnexp2.get(l)));
                                }
                            }
                        }
                    } else {
                        rwexp2 = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "W_________");
                    }

                }

                { // "M".equals(repeat_type.getValue())
                    if (month_day > 0) { // ????????
                        DecimalFormat exF = new DecimalFormat("00");
                        String md_str = exF.format(month_day);
                        rmexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "M" + md_str + "_");

                    } else if (year_day > 0 && year_month > 0) { // ??
                        DecimalFormat exG = new DecimalFormat("00");
                        String yd_str = exG.format(year_day);
                        rmexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "M" + yd_str + "_");
                    } else {
                        rmexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "M___");
                    }
                }

                { // "Y".equals(repeat_type.getValue())
                    if (year_day > 0 && year_month > 0) { // ????????
                        DecimalFormat exG = new DecimalFormat("00");
                        String ym_str = exG.format(year_month);
                        String yd_str = exG.format(year_day);

                        ryexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "Y" + ym_str + yd_str + "_");
                    } else if (month_day > 0) { // ??
                        DecimalFormat exF = new DecimalFormat("00");
                        String md_str = exF.format(month_day);
                        ryexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "Y__" + md_str + "_");
                    } else {
                        ryexp = ExpressionFactory.likeExp(EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "."
                                + EipTSchedule.REPEAT_PATTERN_PROPERTY, "Y_____");
                    }
                }

                Expression repeatexp = oneexp;
                if (rdexp != null) {
                    repeatexp = repeatexp.orExp(rdexp);
                }
                if (rwexp != null) {
                    repeatexp = repeatexp.orExp(rwexp);
                }
                if (rwexp2 != null) {
                    repeatexp = repeatexp.orExp(rwexp2);
                }
                if (rmexp != null) {
                    repeatexp = repeatexp.orExp(rmexp);
                }
                if (spanexp != null) {
                    repeatexp = repeatexp.orExp(spanexp);
                }
                if (ryexp != null) {
                    repeatexp = repeatexp.orExp(ryexp);
                }
                fquery.andQualifier(repeatexp);
            }

            db_scheduleid = schedule.getScheduleId();
            if (db_scheduleid != null && db_scheduleid >= 0) {
                Expression exp00 = ExpressionFactory.noMatchDbExp(
                        EipTScheduleMap.EIP_TSCHEDULE_PROPERTY + "." + EipTSchedule.SCHEDULE_ID_PK_COLUMN,
                        db_scheduleid);
                fquery.andQualifier(exp00);
            }

            fquery.distinct(true);
            List<EipTScheduleMap> f_list = fquery.fetchList();
            if (f_list != null && f_list.size() > 0) {
                // ?????
                boolean existFacility = false;
                int f_list_size = f_list.size();
                for (int i = 0; i < f_list_size; i++) {
                    EipTScheduleMap map = f_list.get(i);

                    Date dbStartDate = map.getEipTSchedule().getStartDate();
                    Date dbEndDate = map.getEipTSchedule().getEndDate();

                    boolean containtsRs = false;
                    // ??????
                    String ptn = map.getEipTSchedule().getRepeatPattern();
                    if (ptn.charAt(0) == 'S') { // 
                        try {
                            // ??0:00:00?????23:59:59??
                            Calendar cal = Calendar.getInstance();
                            cal.setTime(dbEndDate);
                            cal.add(Calendar.DATE, 1);
                            cal.add(Calendar.MINUTE, -1);
                            dbEndDate = cal.getTime();

                            if ((end_date.after(dbStartDate) && start_date.before(dbEndDate))
                                    || unlimited_repeat) {
                                containtsRs = true;
                            }
                        } catch (Exception e) {
                            containtsRs = false;
                        }
                    } else if (ptn.charAt(0) == 'N') { // ?
                        if ("D".equals(repeat_type) || "N".equals(repeat_type)) { //  or
                            // ?
                            try {
                                if ((dbStartDate.before(end_date) && dbEndDate.after(start_date))
                                        || unlimited_repeat) {
                                    containtsRs = true;
                                }
                            } catch (Exception e) {
                                containtsRs = false;
                            }
                        } else {
                            if ((dbStartDate.before(end_date) && dbEndDate.after(start_date))
                                    || unlimited_repeat) {
                                containtsRs = true;
                            }
                        }
                    } else if (ptn.charAt(0) == 'D') {// 
                        if (ptn.charAt(1) == 'L') {
                            try {
                                if ((dbStartDate.before(end_date) && dbEndDate.after(start_date))
                                        || unlimited_repeat) {
                                    containtsRs = true;
                                }
                            } catch (Exception e) {
                                containtsRs = false;
                            }
                        } else {
                            containtsRs = true;
                        }
                    } else if (ptn.charAt(0) == 'W') {
                        if (ptn.length() == 9) {
                            if (ptn.charAt(8) == 'L') {
                                try {
                                    if ((dbStartDate.before(end_date) && dbEndDate.after(start_date))
                                            || unlimited_repeat) {
                                        containtsRs = true;
                                    }
                                } catch (Exception e) {
                                    containtsRs = false;
                                }
                            } else {
                                containtsRs = true;
                            }
                        } else if (ptn.length() == 10) {
                            if (ptn.charAt(9) == 'L') {
                                try {
                                    if ((dbStartDate.before(end_date) && dbEndDate.after(start_date))
                                            || unlimited_repeat) {
                                        containtsRs = true;
                                    }
                                } catch (Exception e) {
                                    containtsRs = false;
                                }
                            } else {
                                containtsRs = true;
                            }
                        }
                    } else if (ptn.charAt(0) == 'M') {
                        if (ptn.charAt(3) == 'L') {
                            try {
                                if ((dbStartDate.before(end_date) && dbEndDate.after(start_date))
                                        || unlimited_repeat) {
                                    containtsRs = true;
                                }
                            } catch (Exception e) {
                                containtsRs = false;
                            }
                        } else {
                            containtsRs = true;
                        }
                    } else if (ptn.charAt(0) == 'Y') {
                        if (ptn.charAt(5) == 'L') {
                            try {
                                if ((dbStartDate.before(end_date) && dbEndDate.after(start_date))
                                        || unlimited_repeat) {
                                    containtsRs = true;
                                }
                            } catch (Exception e) {
                                containtsRs = false;
                            }
                        } else {
                            containtsRs = true;
                        }
                    } else {
                        containtsRs = true;
                    }

                    if (containtsRs) {
                        /* ?????? */
                        int ss_flg = ScheduleUtils.compareTime(start_date, dbEndDate);
                        int se_flg = ScheduleUtils.compareTime(end_date, dbStartDate);
                        if (ss_flg > 0 && se_flg < 0) {
                            /* ???????????? */
                            if (!"N".equals(ptn) && ptn.endsWith("N") && unlimited_repeat) {// ?(?????&&???)&&????
                                existFacility = true;
                            } else {
                                Date _start_date = null;
                                Date _end_date = null;

                                if (!"N".equals(ptn) && ptn.endsWith("N") && !unlimited_repeat) {// ?(??&&???)&&???
                                    _start_date = (Date) start_date.clone();
                                    _end_date = (Date) end_date.clone();
                                } else if (("N".equals(ptn) || !ptn.endsWith("N")) && unlimited_repeat) {// ?(?||??)&&????
                                    _start_date = (Date) dbStartDate.clone();
                                    _end_date = (Date) dbEndDate.clone();
                                } else if (("N".equals(ptn) || !ptn.endsWith("N")) && !unlimited_repeat) {// ?(?||??)&&???

                                    if (dbStartDate.after(start_date)) {
                                        _start_date = (Date) dbStartDate.clone();
                                    } else {
                                        _start_date = (Date) start_date.clone();
                                    }

                                    if (dbEndDate.before(end_date)) {
                                        _end_date = (Date) dbEndDate.clone();
                                    } else {
                                        _end_date = (Date) end_date.clone();
                                    }

                                }

                                if ((_start_date == null) || (_end_date == null)) {
                                    continue;
                                }

                                /* ??? */
                                Expression dexp1 = ExpressionFactory.matchExp(EipTSchedule.NAME_PROPERTY,
                                        "dummy");// 

                                Expression dexp2 = ExpressionFactory.matchExp(EipTSchedule.PARENT_ID_PROPERTY,
                                        map.getScheduleId());

                                if (db_scheduleid != null) {
                                    Expression dexp21 = ExpressionFactory
                                            .matchExp(EipTSchedule.PARENT_ID_PROPERTY, db_scheduleid);
                                    dexp2 = dexp2.orExp(dexp21);
                                }
                                Expression dexp3 = null;

                                cald.setTime(_start_date);
                                cald.set(Calendar.MILLISECOND, 0);
                                cald.set(Calendar.SECOND, 0);
                                cald.set(Calendar.MINUTE, 0);
                                cald.set(Calendar.HOUR_OF_DAY, 0);
                                Date ddate = cald.getTime();// _start_date?
                                List<EipTSchedule> temp = null;

                                if ("N".equals(repeat_pattern)) {
                                    /* ?????????????? */
                                    if ((_old_scheduleid != null) && (_old_viewDate != null)) {
                                        if ((_old_scheduleid.intValue() == map.getScheduleId().intValue())
                                                && compareToDate(_start_date, _old_viewDate) == 0) {
                                            continue;
                                        }
                                    }

                                    try {
                                        dexp3 = ExpressionFactory.matchExp(EipTSchedule.START_DATE_PROPERTY,
                                                ddate);
                                        temp = Database
                                                .query(EipTSchedule.class, dexp1.andExp(dexp2).andExp(dexp3))
                                                .fetchList();
                                        if (temp == null || temp.size() <= 0) {
                                            existFacility = true;
                                            break;
                                        }
                                    } catch (Exception e) {
                                        logger.error("[DuplicateFacilityCheck]: ", e);
                                        existFacility = true;
                                        break;
                                    }
                                } else if (repeat_pattern.startsWith("D")) {
                                    while (!ddate.after(_end_date)) {
                                        if (matchDay(cald, ptn)) {
                                            try {
                                                dexp3 = ExpressionFactory
                                                        .matchExp(EipTSchedule.START_DATE_PROPERTY, ddate);
                                                temp = Database.query(EipTSchedule.class,
                                                        dexp1.andExp(dexp2).andExp(dexp3)).fetchList();
                                                if (temp == null || temp.size() <= 0) {
                                                    existFacility = true;
                                                    break;
                                                }
                                            } catch (Exception e) {
                                                logger.error("[DuplicateFacilityCheck]: ", e);
                                                existFacility = true;
                                                break;
                                            }
                                        }
                                        cald.add(Calendar.DATE, 1);
                                        ddate = cald.getTime();
                                    }
                                } else if (repeat_pattern.startsWith("S")) {
                                    while (!ddate.after(_end_date)) {
                                        try {
                                            dexp3 = ExpressionFactory.matchExp(EipTSchedule.START_DATE_PROPERTY,
                                                    ddate);
                                            temp = Database.query(EipTSchedule.class,
                                                    dexp1.andExp(dexp2).andExp(dexp3)).fetchList();
                                            if (temp == null || temp.size() <= 0) {
                                                existFacility = true;
                                                break;
                                            }
                                        } catch (Exception e) {
                                            logger.error("[DuplicateFacilityCheck]: ", e);
                                            existFacility = true;
                                            break;
                                        }
                                        cald.add(Calendar.DATE, 1);
                                        ddate = cald.getTime();
                                    }
                                } else if (repeat_pattern.startsWith("W")) {
                                    /* ? */
                                    int wlen = week_array.length;
                                    int wlen2 = day_of_week_in_month_array.length;
                                    if (wlen < 1 || wlen2 < 1) {
                                        continue;
                                    }
                                    int k;
                                    int l;
                                    while (!ddate.after(_end_date)) {
                                        k = (cald.get(Calendar.DAY_OF_WEEK) - 1) % wlen;
                                        l = (cald.get(Calendar.DAY_OF_WEEK_IN_MONTH) - 1) % wlen2;
                                        if ((week_array[k] == true) && (day_of_week_in_month_array[l] == true)
                                                && matchDay(cald, ptn)) {
                                            try {
                                                dexp3 = ExpressionFactory
                                                        .matchExp(EipTSchedule.START_DATE_PROPERTY, ddate);
                                                temp = Database.query(EipTSchedule.class,
                                                        dexp1.andExp(dexp2).andExp(dexp3)).fetchList();// SQL
                                                if (temp == null || temp.size() <= 0) {
                                                    existFacility = true;// true????
                                                    break;
                                                }
                                            } catch (Exception e) {
                                                logger.error("[DuplicateFacilityCheck]: ", e);
                                                existFacility = true;
                                                break;
                                            }
                                        }
                                        cald.add(Calendar.DATE, 1);
                                        ddate = cald.getTime();
                                    }
                                } else if (repeat_pattern.startsWith("M")) {
                                    /* ?? */
                                    cald.setTime(dbStartDate);
                                    cald.set(Calendar.MILLISECOND, 0);
                                    cald.set(Calendar.SECOND, 0);
                                    cald.set(Calendar.MINUTE, 0);
                                    cald.set(Calendar.HOUR_OF_DAY, 0);

                                    if (month_day > 0) {
                                        cald.set(Calendar.DAY_OF_MONTH, month_day);
                                    } else {
                                        continue;
                                    }
                                    Date tmp_date = cald.getTime();
                                    while (tmp_date.before(ddate)) {
                                        cald.add(Calendar.MONTH, 1);
                                        /* ???????????????? */
                                        while (month_day > cald.getActualMaximum(Calendar.DAY_OF_MONTH)) {
                                            cald.add(Calendar.MONTH, 1);
                                            cald.set(Calendar.DAY_OF_MONTH, month_day);
                                            if (tmp_date.before(tmp_date)) {
                                                break;
                                            }
                                        }
                                        tmp_date = cald.getTime();
                                    }
                                    ddate = tmp_date;
                                    /*  */
                                    while (!ddate.after(_end_date)) {
                                        if (matchDay(cald, ptn)) {
                                            try {
                                                dexp3 = ExpressionFactory
                                                        .matchExp(EipTSchedule.START_DATE_PROPERTY, ddate);
                                                temp = Database.query(EipTSchedule.class,
                                                        dexp1.andExp(dexp2).andExp(dexp3)).fetchList();
                                                if (temp == null || temp.size() <= 0) {
                                                    existFacility = true;
                                                    break;
                                                }

                                            } catch (Exception e) {
                                                logger.error("[DuplicateFacilityCheck]: ", e);
                                                existFacility = true;
                                                break;
                                            }
                                        }
                                        cald.add(Calendar.MONTH, 1);
                                        /* ???????????????? */
                                        while (month_day > cald.getActualMaximum(Calendar.DAY_OF_MONTH)) {
                                            cald.add(Calendar.MONTH, 1);
                                            cald.set(Calendar.DAY_OF_MONTH, month_day);
                                            if (!ddate.after(_end_date)) {
                                                break;
                                            }
                                        }
                                        ddate = cald.getTime();
                                    }
                                } else if (repeat_pattern.startsWith("Y")) {
                                    /* ?? */
                                    cald.setTime(dbStartDate);
                                    cald.set(Calendar.MILLISECOND, 0);
                                    cald.set(Calendar.SECOND, 0);
                                    cald.set(Calendar.MINUTE, 0);
                                    cald.set(Calendar.HOUR_OF_DAY, 0);

                                    if (year_month > 0 && year_day > 0) {
                                        cald.set(Calendar.MONTH, year_month - 1);
                                        cald.set(Calendar.DAY_OF_MONTH, year_day);
                                    } else {
                                        continue;
                                    }
                                    Date tmp_date = cald.getTime();
                                    while (tmp_date.before(ddate)) {
                                        cald.add(Calendar.MONTH, 1);
                                        /* ???????????????? */
                                        while (year_day > cald.getActualMaximum(Calendar.DAY_OF_MONTH)) {
                                            cald.add(Calendar.MONTH, 1);
                                            cald.set(Calendar.DAY_OF_MONTH, year_day);
                                            if (tmp_date.before(tmp_date)) {
                                                break;
                                            }
                                        }
                                        tmp_date = cald.getTime();
                                    }
                                    ddate = tmp_date;
                                    /*  */
                                    while (!ddate.after(_end_date)) {
                                        if (matchDay(cald, ptn)) {
                                            try {
                                                dexp3 = ExpressionFactory
                                                        .matchExp(EipTSchedule.START_DATE_PROPERTY, ddate);
                                                temp = Database.query(EipTSchedule.class,
                                                        dexp1.andExp(dexp2).andExp(dexp3)).fetchList();
                                                if (temp == null || temp.size() <= 0) {
                                                    existFacility = true;
                                                    break;
                                                }
                                            } catch (Exception e) {
                                                logger.error("[DuplicateFacilityCheck]: ", e);
                                                existFacility = true;
                                                break;
                                            }
                                        }
                                        cald.add(Calendar.MONTH, 1);
                                        /* ???????????????? */
                                        while (year_day > cald.getActualMaximum(Calendar.DAY_OF_MONTH)) {
                                            cald.add(Calendar.MONTH, 1);
                                            cald.set(Calendar.DAY_OF_MONTH, year_day);
                                            if (!ddate.after(_end_date)) {
                                                break;
                                            }
                                        }
                                        ddate = cald.getTime();
                                    }
                                } else {
                                    continue;
                                }
                            }
                        }
                    }
                    if (existFacility) {
                        break;
                    }
                }
                if (existFacility) {
                    return existFacility;
                }
            }
        }
    }
    return result;
}

From source file:pt.fct.di.benchmarks.TPCW_Riak.database.TPCW_Riak_Executor.java

public void CustomerRegistration(String costumer_id) throws Exception {

    String name = (BenchmarkUtil.getRandomAString(8, 13) + " " + BenchmarkUtil.getRandomAString(8, 15));
    String[] names = name.split(" ");
    Random r = new Random();
    int random_int = r.nextInt(1000);

    String key = names[0] + "_" + (costumer_id);

    String pass = names[0].charAt(0) + names[1].charAt(0) + "" + random_int;

    String first_name = names[0];

    String last_name = names[1];//from  w  ww  .j  a va2s . c o m

    int phone = r.nextInt(999999999 - 100000000) + 100000000;

    String email = key + "@" + BenchmarkUtil.getRandomAString(2, 9) + ".com";

    double discount = r.nextDouble();

    String adress = "Street: "
            + (BenchmarkUtil.getRandomAString(8, 15) + " " + BenchmarkUtil.getRandomAString(8, 15))
            + " number: " + r.nextInt(500);

    double C_BALANCE = 0.00;

    double C_YTD_PMT = (double) BenchmarkUtil.getRandomInt(0, 99999) / 100.0;

    GregorianCalendar cal = new GregorianCalendar();
    cal.add(Calendar.DAY_OF_YEAR, -1 * BenchmarkUtil.getRandomInt(1, 730));

    java.sql.Date C_SINCE = new java.sql.Date(cal.getTime().getTime());

    cal.add(Calendar.DAY_OF_YEAR, BenchmarkUtil.getRandomInt(0, 60));
    if (cal.after(new GregorianCalendar())) {
        cal = new GregorianCalendar();
    }

    java.sql.Date C_LAST_LOGIN = new java.sql.Date(cal.getTime().getTime());

    java.sql.Timestamp C_LOGIN = new java.sql.Timestamp(System.currentTimeMillis());

    cal = new GregorianCalendar();
    cal.add(Calendar.HOUR, 2);

    java.sql.Timestamp C_EXPIRATION = new java.sql.Timestamp(cal.getTime().getTime());

    cal = BenchmarkUtil.getRandomDate(1880, 2000);
    java.sql.Date C_BIRTHDATE = new java.sql.Date(cal.getTime().getTime());

    String C_DATA = BenchmarkUtil.getRandomAString(100, 500);

    String address_id = insertAdress();

    Customer c = new Customer(costumer_id, key, pass, last_name, first_name, phone + "", email,
            C_SINCE.toString(), C_LAST_LOGIN.toString(), C_LOGIN.toString(), C_EXPIRATION.toString(), C_BALANCE,
            C_YTD_PMT, C_BIRTHDATE.toString(), C_DATA, discount, address_id);

    insert(costumer_id, "customer", c);

}