Example usage for java.util GregorianCalendar setTimeInMillis

List of usage examples for java.util GregorianCalendar setTimeInMillis

Introduction

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

Prototype

public void setTimeInMillis(long millis) 

Source Link

Document

Sets this Calendar's current time from the given long value.

Usage

From source file:org.apache.juddi.webconsole.hub.UddiHub.java

/**
 * Returns bootstrap stylized html representing all changes in the last
 * refresh// w  w  w.  j  av a2 s .  c  o  m
 *
 * @param lastRefresh
 * @return formatted html
 * @throws DatatypeConfigurationException
 */
public String GetNewsFeed(XMLGregorianCalendar lastRefresh) throws DatatypeConfigurationException {
    if (GetToken() == null) {
        return ToErrorAlert(ResourceLoader.GetResource(session, "errors.notsignedin"));
    }
    if (df == null) {
        df = DatatypeFactory.newInstance();
    }
    List<Subscription> subscriptions = new ArrayList<Subscription>();
    try {
        try {
            subscriptions = subscription.getSubscriptions(GetToken());

        } catch (Exception ex) {
            if (isExceptionExpiration(ex)) {
                token = null;

                subscriptions = subscription.getSubscriptions(GetToken());

            } else {
                throw ex;
            }
        }
    } catch (Exception ex) {
        return HandleException(ex);
    }

    GregorianCalendar gcal = new GregorianCalendar();
    gcal.setTimeInMillis(System.currentTimeMillis());

    GetSubscriptionResults r = new GetSubscriptionResults();
    r.setAuthInfo(GetToken());
    r.setCoveragePeriod(new CoveragePeriod());
    r.getCoveragePeriod().setEndPoint(df.newXMLGregorianCalendar(gcal));

    r.getCoveragePeriod().setStartPoint(lastRefresh);
    StringBuilder sb = new StringBuilder();
    if (subscriptions.isEmpty()) {
        return ToErrorAlert(ResourceLoader.GetResource(session, "errors.subscriptionfeed.nosubs"));
    }
    for (int k = 0; k < subscriptions.size(); k++) {

        r.setSubscriptionKey(subscriptions.get(k).getSubscriptionKey());
        SubscriptionResultsList subscriptionResults = null;
        try {
            try {
                subscriptionResults = subscription.getSubscriptionResults(r);

            } catch (Exception ex) {
                if (isExceptionExpiration(ex)) {
                    token = null;
                    r.setAuthInfo(GetToken());
                    subscriptionResults = subscription.getSubscriptionResults(r);

                } else {
                    throw ex;
                }
            }
        } catch (Exception ex) {
            return HandleException(ex);
        }

        if (subscriptionResults != null) {
            //    subscriptionResults.getAssertionStatusReport().
            if (subscriptionResults.getAssertionStatusReport() != null) {
                sb.append(ResourceLoader.GetResource(session, "items.subscriptions.assertion"))
                        .append("<table class=\"table table-hover\">");
                for (int i = 0; i < subscriptionResults.getAssertionStatusReport().getAssertionStatusItem()
                        .size(); i++) {
                    sb.append("<tr><td>");
                    sb.append(StringEscapeUtils.escapeHtml(subscriptionResults.getAssertionStatusReport()
                            .getAssertionStatusItem().get(i).getFromKey()));
                    sb.append("</td><td>");
                    sb.append(StringEscapeUtils.escapeHtml(subscriptionResults.getAssertionStatusReport()
                            .getAssertionStatusItem().get(i).getToKey()));
                    sb.append("</td><td>");
                    sb.append(StringEscapeUtils.escapeHtml(subscriptionResults.getAssertionStatusReport()
                            .getAssertionStatusItem().get(i).getCompletionStatus().toString()));
                    sb.append("</td></tr>");
                }
                sb.append("</table><br>");
            }
            if (subscriptionResults.getBindingDetail() != null) {
                sb.append(ResourceLoader.GetResource(session, "items.subscriptions.bindings"))
                        .append("<table class=\"table table-hover\">");
                for (int i = 0; i < subscriptionResults.getBindingDetail().getBindingTemplate().size(); i++) {
                    sb.append("<tr><td>");
                    sb.append(StringEscapeUtils.escapeHtml(subscriptionResults.getBindingDetail()
                            .getBindingTemplate().get(i).getServiceKey()));
                    sb.append("</td><td>");
                    sb.append(StringEscapeUtils.escapeHtml(subscriptionResults.getBindingDetail()
                            .getBindingTemplate().get(i).getBindingKey()));
                    sb.append("</td></tr>");
                }
                sb.append("</table><br>");
            }
            if (subscriptionResults.getBusinessDetail() != null) {
                sb.append(ResourceLoader.GetResource(session, "items.subscriptions.business"))
                        .append("<table class=\"table table-hover\">");
                for (int i = 0; i < subscriptionResults.getBusinessDetail().getBusinessEntity().size(); i++) {
                    sb.append("<tr><td><a href=\"businessEditor2.jsp?id=");
                    sb.append(StringEscapeUtils.escapeHtml(subscriptionResults.getBusinessDetail()
                            .getBusinessEntity().get(i).getBusinessKey()));
                    sb.append("\">");
                    sb.append(StringEscapeUtils.escapeHtml(subscriptionResults.getBusinessDetail()
                            .getBusinessEntity().get(i).getBusinessKey()));
                    sb.append("<i class=\"icon-large icon-edit\"></i></a></td></tr>");
                }
                sb.append("</table><br>");
            }
            if (subscriptionResults.getRelatedBusinessesList() != null) {
                sb.append(ResourceLoader.GetResource(session, "items.subscriptions.assertion2"))
                        .append("<table class=\"table table-hover\">");
                // for (int i = 0; i < subscriptionResults.getRelatedBusinessesList().getBusinessKey().size(); i++) {
                sb.append("<tr><td>");
                sb.append(StringEscapeUtils
                        .escapeHtml(subscriptionResults.getRelatedBusinessesList().getBusinessKey()));
                sb.append("</td></tr>");
                //}
                sb.append("</table><br>");
            }
            if (subscriptionResults.getServiceDetail() != null) {
                sb.append(ResourceLoader.GetResource(session, "items.subscriptions.services"))
                        .append("<table class=\"table table-hover\">");
                for (int i = 0; i < subscriptionResults.getServiceDetail().getBusinessService().size(); i++) {
                    sb.append("<tr><td><a href=\"serviceEditor.jsp?id=");
                    sb.append(StringEscapeUtils.escapeHtml(subscriptionResults.getServiceDetail()
                            .getBusinessService().get(i).getServiceKey()));
                    sb.append("\">");
                    sb.append(StringEscapeUtils.escapeHtml(subscriptionResults.getServiceDetail()
                            .getBusinessService().get(i).getServiceKey()));
                    sb.append("<i class=\"icon-large icon-edit\"></i></a></td></tr>");
                }
                sb.append("</table><br>");
            }
            if (subscriptionResults.getServiceList() != null) {
                sb.append(ResourceLoader.GetResource(session, "items.subscriptions.servicelist"))
                        .append("<table class=\"table table-hover\">");
                for (int i = 0; i < subscriptionResults.getServiceList().getServiceInfos().getServiceInfo()
                        .size(); i++) {
                    sb.append("<tr><td>");
                    sb.append(StringEscapeUtils.escapeHtml(subscriptionResults.getServiceList()
                            .getServiceInfos().getServiceInfo().get(i).getServiceKey()));

                    sb.append("</td><td>");
                    sb.append(StringEscapeUtils.escapeHtml(Printers.ListNamesToString(subscriptionResults
                            .getServiceList().getServiceInfos().getServiceInfo().get(i).getName())));
                    sb.append("</td></tr>");
                }
                sb.append("</table><br>");
            }
            if (subscriptionResults.getTModelDetail() != null) {
                sb.append(ResourceLoader.GetResource(session, "items.subscriptions.tmodels"))
                        .append("<br><table class=\"table table-hover\">");
                for (int i = 0; i < subscriptionResults.getTModelDetail().getTModel().size(); i++) {
                    sb.append("<tr><td>");
                    sb.append(StringEscapeUtils.escapeHtml(
                            subscriptionResults.getTModelDetail().getTModel().get(i).getTModelKey()));
                    sb.append("</td><td>");
                    sb.append(StringEscapeUtils.escapeHtml(
                            (subscriptionResults.getTModelDetail().getTModel().get(i).getName().getValue())));
                    sb.append("</td></tr>");
                }
                sb.append("</table><br>");
            }
            if (subscriptionResults.getTModelList() != null) {
                sb.append(ResourceLoader.GetResource(session, "items.subscriptions.tmodels2"))
                        .append("<table class=\"table table-hover\">");
                for (int i = 0; i < subscriptionResults.getTModelList().getTModelInfos().getTModelInfo()
                        .size(); i++) {
                    sb.append("<tr><td><a href=\"serviceEditor.jsp?id=");
                    sb.append(StringEscapeUtils.escapeHtml(subscriptionResults.getTModelList().getTModelInfos()
                            .getTModelInfo().get(i).getTModelKey()));
                    sb.append("\">");
                    sb.append(StringEscapeUtils.escapeHtml(subscriptionResults.getTModelList().getTModelInfos()
                            .getTModelInfo().get(i).getTModelKey()));
                    sb.append("<i class=\"icon-large icon-edit\"></i></a></td><td>");
                    sb.append(StringEscapeUtils.escapeHtml((subscriptionResults.getTModelList().getTModelInfos()
                            .getTModelInfo().get(i).getName().getValue())));
                    sb.append("</td></tr>");
                }
                sb.append("</table>");
            }

        }
    }
    return sb.toString();
}

From source file:org.exoplatform.calendar.service.impl.JCRDataStorage.java

public Map<String, String> checkFreeBusy(EventQuery eventQuery, Date date) throws Exception {
    Node eventFolder = getEventFolder(date);
    Map<String, String> participantMap = new HashMap<String, String>();
    eventQuery.setCalendarPath(eventFolder.getPath());
    eventQuery.setOrderBy(new String[] { Utils.EXO_FROM_DATE_TIME });
    QueryManager qm = getSession(createSystemProvider()).getWorkspace().getQueryManager();
    String[] pars = eventQuery.getParticipants();
    Query query;/*from  ww  w. j a v a  2  s. co  m*/
    Node event;
    String from;
    String to;
    for (String par : pars) {
        eventQuery.setParticipants(new String[] { par });
        query = qm.createQuery(eventQuery.getQueryStatement(), Query.XPATH);
        QueryResult result = query.execute();
        NodeIterator it = result.getNodes();
        StringBuilder timeValues = new StringBuilder();
        while (it.hasNext()) {
            event = it.nextNode();
            if (event.hasProperty(Utils.EXO_EVENT_STATE) && !CalendarEvent.ST_AVAILABLE
                    .equals(event.getProperty(Utils.EXO_EVENT_STATE).getValue().getString())) {
                java.util.Calendar fromCal = event.getProperty(Utils.EXO_FROM_DATE_TIME).getDate();
                java.util.Calendar toCal = event.getProperty(Utils.EXO_TO_DATE_TIME).getDate();
                if (fromCal.getTimeInMillis() < eventQuery.getFromDate().getTimeInMillis())
                    from = String.valueOf(eventQuery.getFromDate().getTimeInMillis());
                else
                    from = String.valueOf(fromCal.getTimeInMillis());
                if (toCal.getTimeInMillis() > eventQuery.getToDate().getTimeInMillis()) {
                    GregorianCalendar cal = new GregorianCalendar();
                    cal.setTimeInMillis(eventQuery.getToDate().getTimeInMillis() - 1000);
                    to = String.valueOf(cal.getTimeInMillis());
                } else
                    to = String.valueOf(toCal.getTimeInMillis());

                if (timeValues != null && timeValues.length() > 0)
                    timeValues.append(",");
                timeValues.append(from).append(",").append(to);
                participantMap.put(par, timeValues.toString());
            }
        }
    }
    return participantMap;
}

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);
        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);// w  w w. j  a va2  s .c  o m
        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: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);
    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 {/*from  w  w w.  ja v a2s . co  m*/
        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.calendar.impl.BaseCalendarService.java

/**
 * Collect the fields that need to be stored outside the XML (for the resource).
 * //w w w.j  a  v  a2s .c  om
 * @return An array of field values to store in the record outside the XML (for the resource).
 */
public Object[] storageFields(Entity r) {
    Object[] rv = new Object[4];
    TimeRange range = ((CalendarEvent) r).getRange();
    rv[0] = range.firstTime(); // %%% fudge?
    rv[1] = range.lastTime(); // %%% fudge?

    // we use hours rather than ms for the range to reduce the index size in the database
    // I dont what to use days just incase we want sub day range finds
    long oneHour = 60L * 60L * 1000L;
    rv[2] = (int) (range.firstTime().getTime() / oneHour);
    rv[3] = (int) (range.lastTime().getTime() / oneHour);

    // find the end of the sequence
    RecurrenceRuleBase rr = (RecurrenceRuleBase) ((CalendarEvent) r).getRecurrenceRule();
    if (rr != null) {
        Time until = rr.getUntil();
        if (until != null) {
            rv[3] = (int) (until.getTime() / oneHour);
        } else {
            int count = rr.getCount();
            int interval = rr.getInterval();
            long endevent = range.lastTime().getTime();
            if (count == 0) {
                rv[3] = Integer.MAX_VALUE - 1; // hours since epoch, this represnts 9 Oct 246953 07:00:00
            } else {
                String frequency = rr.getFrequency();
                GregorianCalendar c = new GregorianCalendar();
                c.setTimeInMillis(endevent);
                c.add(rr.getRecurrenceType(), count * interval);
                rv[3] = (int) (c.getTimeInMillis() / oneHour);
            }
        }
    }
    return rv;
}

From source file:gov.nih.nci.cadsr.sentinel.database.DBAlertOracle.java

/**
 * Get the Alerts which are active for the target date provided.
 *
 * @param target_// w w  w .  j  a v  a2 s . c  o  m
 *        The target date, typically the date an Auto Run process is
 *        started.
 * @return null if an error, otherwise the list of valid alert definitions.
 */
public AlertRec[] selectAlerts(Timestamp target_) {
    String select = "select al_idseq, name, created_by " + "from sbrext.sn_alert_view_ext "
            + "where al_status <> 'I' AND " + "(auto_freq_unit = 'D' OR "
            + "(auto_freq_unit = 'W' AND auto_freq_value = ?) OR "
            + "(auto_freq_unit = 'M' AND auto_freq_value = ?)) "
            + "order by upper(created_by) asc, upper(name) asc";

    // Get day and date from target to qualify the select.
    GregorianCalendar tdate = new GregorianCalendar();
    tdate.setTimeInMillis(target_.getTime());
    int dayWeek = tdate.get(Calendar.DAY_OF_WEEK);
    int dayMonth = tdate.get(Calendar.DAY_OF_MONTH);

    PreparedStatement pstmt = null;
    ResultSet rs = null;
    AlertRec[] recs = null;
    try {
        // Set SQL arguments
        pstmt = _conn.prepareStatement(select);
        pstmt.setInt(1, dayWeek);
        pstmt.setInt(2, dayMonth);

        // Retrieve all applicable definition ids.
        rs = pstmt.executeQuery();
        Vector<String> list = new Vector<String>();
        while (rs.next()) {
            list.add(rs.getString(1));
        }
        rs.close();
        rs = null;
        pstmt.close();
        pstmt = null;

        // There may be nothing to do.
        if (list.size() == 0)
            recs = new AlertRec[0];
        else {
            // retrieve the full alert definition, we will need it.
            recs = new AlertRec[list.size()];
            int keep = 0;
            int ndx;
            for (ndx = 0; ndx < recs.length; ++ndx) {
                // Be sure we can read the Alert Definition.
                recs[keep] = selectAlert((String) list.get(ndx));
                if (recs[keep] == null)
                    return null;

                // Check the date. We do this here and not in the SQL because
                // 99.99% of the time this will return true and complicating the
                // SQL isn't necessary.
                if (recs[keep].isActive(target_))
                    ++keep;

                // In the RARE situation that the alert is inactive at this
                // point,
                // we reset the object pointer to release the memory.
                else
                    recs[keep] = null;
            }

            // Return the results. It is possible that sometimes the last entry
            // in the
            // list will be null. Consequently the use of the list should be in
            // a loop
            // with the following condition: "cnt < recs.length && recs[cnt] !=
            // null"
            if (keep != ndx) {
                // Only process the ones that are Active.
                AlertRec trecs[] = new AlertRec[keep];
                for (ndx = 0; ndx < keep; ++ndx)
                    trecs[ndx] = recs[ndx];
                recs = trecs;
            }
        }
    } catch (SQLException ex) {
        _errorCode = DBAlertUtil.getSQLErrorCode(ex);
        _errorMsg = _errorCode + ": " + select + "\n\n" + ex.toString();
        _logger.error(_errorMsg);
    } finally {
        closeCursors(pstmt, rs);
    }
    return recs;
}

From source file:com.lp.server.fertigung.ejbfac.FertigungFacBean.java

@TransactionAttribute(TransactionAttributeType.NEVER)
public KapazitaetsvorschauDto getKapazitaetsvorschau(TheClientDto theClientDto) throws EJBExceptionLP {
    KapazitaetsvorschauDto kapDto = null;
    Session session = null;/* w ww.j av a  2  s .  c om*/
    try {

        // ------------------------------------------------------------------
        // -----
        // Benoetigte Parameter holen
        // ------------------------------------------------------------------
        // -----
        // Default Sicht nach Wochen
        // final int iSicht = FertigungFac.KAPAZITAETSVORSCHAU_NACH_WOCHEN;
        // Anzahl der angezeigten Vatergruppen. Alles andere wird nach
        // "Sonstige" verdichtet
        final ParametermandantDto parameterAnzahlGruppen = getParameterFac().getMandantparameter(
                theClientDto.getMandant(), ParameterFac.KATEGORIE_FERTIGUNG,
                ParameterFac.PARAMETER_FERTIGUNG_KAPAZITAETSVORSCHAU_ANZAHL_GRUPPEN);
        final int iParamAnzahlGruppen = (Integer) parameterAnzahlGruppen.getCWertAsObject();
        // Angezeigter Zeitraum = Anzahl der Spalten
        final ParametermandantDto parameterZeitraum = getParameterFac().getMandantparameter(
                theClientDto.getMandant(), ParameterFac.KATEGORIE_FERTIGUNG,
                ParameterFac.PARAMETER_FERTIGUNG_KAPAZITAETSVORSCHAU_ZEITRAUM);
        final int iParamZeitraum = (Integer) parameterZeitraum.getCWertAsObject();

        // ------------------------------------------------------------------
        // -----
        // Hibernate-Session erstellen
        // ------------------------------------------------------------------
        // -----
        SessionFactory factory = FLRSessionFactory.getFactory();
        session = factory.openSession();
        // ------------------------------------------------------------------
        // -----
        // Artikel- / Maschinen-Vatergruppen holen
        // ------------------------------------------------------------------
        // -----
        // Alle Artikel-Vatergruppen
        Criteria cArtikelVatergruppen = session.createCriteria(FLRArtikelgruppe.class);
        cArtikelVatergruppen.add(Restrictions.isNull(ArtikelFac.FLR_ARTIKELGRUPPE_FLRARTIKELGRUPPE));
        List<?> listArtikelgruppen = cArtikelVatergruppen.list();
        // Alle Maschinen-Vatergruppen
        Criteria cMaschinengruppen = session.createCriteria(FLRMaschinengruppe.class);
        List<?> listMaschinengruppen = cMaschinengruppen.list();
        // ------------------------------------------------------------------
        // -----
        // Anzahl der sub-Diagramme bestimmen
        // das ist grundsaetzlich (iParamAnzahlGruppen + 1) x 2 ...
        // (Anzahl d. anzuzeigenden Vatergruppen + Sonstige) f. AZ und
        // Maschinen
        // wenn es weniger Vatergruppen als anzuzeigende gibt, reduziert
        // sich das aber
        // Gibt es keine Vatergruppe, wird daher alles nach "Sonstige"
        // verdichtet
        // ------------------------------------------------------------------
        // -----
        final int iAnzuzeigendeArtikelgruppen = Math.min(iParamAnzahlGruppen, listArtikelgruppen.size());

        final int iAnzuzeigendeMaschinengruppen = Math.min(iParamAnzahlGruppen, listMaschinengruppen.size());

        final int iAnzahlZeilen = iAnzuzeigendeArtikelgruppen + 1 + iAnzuzeigendeMaschinengruppen + 1;

        // ------------------------------------------------------------------
        // -----
        // Dto initialisieren
        // ------------------------------------------------------------------
        // -----
        kapDto = new KapazitaetsvorschauDto(iAnzahlZeilen, iParamZeitraum);
        // ------------------------------------------------------------------
        // -----
        // Beschriftung der x-Achse ermitteln. das sind die Kalenderwochen
        // ------------------------------------------------------------------
        // -----
        HashMap<Integer, Integer> hmKWIndizes = new HashMap<Integer, Integer>();

        String[] kw = new String[iParamZeitraum];
        GregorianCalendar gc = new GregorianCalendar();
        for (int i = 0; i < kw.length; i++) {
            int iKw = gc.get(GregorianCalendar.WEEK_OF_YEAR);
            kw[i] = "" + iKw;
            kapDto.setISpaltenueberschrift(i, kw[i]);
            hmKWIndizes.put(gc.get(GregorianCalendar.WEEK_OF_YEAR), i);
            gc.setTimeInMillis(gc.getTimeInMillis() + 7 * 24 * 60 * 60 * 1000); // 1 Woche dazu
        }
        // ------------------------------------------------------------------
        // -----
        // Beschriftung der y-Achse ermitteln. das sind die Namen der
        // Vatergruppen bzw. 2 x "Sonstige".
        // Weiters werden die Indizes im Daten-Array fuer die jeweiligen
        // Gruppen festgelegt.
        // ------------------------------------------------------------------
        // -----
        String sSonstige = getTextRespectUISpr("lp.sonstige", theClientDto.getMandant(),
                theClientDto.getLocUi());

        HashMap<Integer, Integer> hmArtikelGruppenIndizes = new HashMap<Integer, Integer>();
        HashMap<Integer, Integer> hmMaschinenGruppenIndizes = new HashMap<Integer, Integer>();

        // zuerst die Artikelvatergruppen
        for (int i = 0; i < iAnzuzeigendeArtikelgruppen; i++) {
            FLRArtikelgruppe item = (FLRArtikelgruppe) listArtikelgruppen.get(i);
            kapDto.setIZeilenueberschrift(i, item.getC_nr());
            hmArtikelGruppenIndizes.put(item.getI_id(), i);
        }
        // Dann Sonstige Artikelgruppen
        final int indexSonstigeArtikelGruppen = iAnzuzeigendeArtikelgruppen;
        kapDto.setIZeilenueberschrift(indexSonstigeArtikelGruppen, sSonstige);
        // Maschinengruppen
        for (int i = 0; i < iAnzuzeigendeMaschinengruppen; i++) {
            FLRMaschinengruppe item = (FLRMaschinengruppe) listMaschinengruppen.get(i);
            int index = iAnzuzeigendeArtikelgruppen + 1 + i;
            kapDto.setIZeilenueberschrift(index, item.getC_bez());
            hmMaschinenGruppenIndizes.put(item.getI_id(), index);
        }
        // zuletzt Sonstige Maschinengruppen
        final int indexSonstigeMaschinenGruppen = iAnzuzeigendeArtikelgruppen + 1
                + iAnzuzeigendeMaschinengruppen;
        kapDto.setIZeilenueberschrift(indexSonstigeMaschinenGruppen, sSonstige);

        // ------------------------------------------------------------------
        // -----
        // Lose holen
        // ------------------------------------------------------------------
        // -----
        Criteria cLose = session.createCriteria(FLRLos.class);
        // Filter nach Mandant
        cLose.add(Restrictions.eq(FertigungFac.FLR_LOS_MANDANT_C_NR, theClientDto.getMandant()));
        // Alle Stati ausser Erledigt, Gestoppt, Storniert
        Collection<String> cLoseStati = new LinkedList<String>();
        cLoseStati.add(FertigungFac.STATUS_ERLEDIGT);
        cLoseStati.add(FertigungFac.STATUS_GESTOPPT);
        cLoseStati.add(FertigungFac.STATUS_STORNIERT);
        cLose.add(Restrictions.not(Restrictions.in(FertigungFac.FLR_LOS_STATUS_C_NR, cLoseStati)));
        List<?> listLose = cLose.list();
        // ------------------------------------------------------------------
        // -----
        // Auswertungszeitraum und verfuegbare Kapazitaeten ermitteln
        // ------------------------------------------------------------------
        // -----

        // 3 Monate in die zukunft
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(System.currentTimeMillis());
        c.set(Calendar.MONTH, c.get(Calendar.MONTH) + 3);
        java.util.Date dMax = Helper.cutDate(new java.sql.Date(c.getTimeInMillis()));

        java.sql.Timestamp tVon = Helper.cutTimestamp(new java.sql.Timestamp(System.currentTimeMillis()));
        java.sql.Timestamp tBis = Helper.cutTimestamp(new java.sql.Timestamp(dMax.getTime()));
        // Verfuegbare Zeiten holen
        SollverfuegbarkeitDto[] oVerfuegbar = getZeiterfassungFac().getVerfuegbareSollzeit(tVon, tBis,
                theClientDto);
        // diese nun aufteilen
        for (int i = 0; i < oVerfuegbar.length; i++) {
            SollverfuegbarkeitDto svDto = oVerfuegbar[i];
            // "normale" AZ
            if (svDto.isBMannarbeitszeit()) {
                // die sind einer Artikelgruppe zugeordnet
                if (svDto.getIGruppeid() != null) {
                    Integer iZeile = hmArtikelGruppenIndizes.get(svDto.getIGruppeid());
                    // ist das eine sichtbare Gruppe
                    if (iZeile != null) {
                        for (int iSpalte = 0; iSpalte < kapDto.getDetails()[iZeile].length; iSpalte++) {
                            // mal 5 Tage
                            kapDto.addBdVerfuegbareStunden(iZeile, iSpalte,
                                    svDto.getNSollstunden().multiply(new BigDecimal(5)));
                        }
                    }
                    // wenn nicht, dann zu den sonstigen
                    else {
                        for (int iSpalte = 0; iSpalte < kapDto
                                .getDetails()[indexSonstigeArtikelGruppen].length; iSpalte++) {
                            // mal 5 Tage
                            kapDto.addBdVerfuegbareStunden(indexSonstigeArtikelGruppen, iSpalte,
                                    svDto.getNSollstunden().multiply(new BigDecimal(5)));
                        }
                    }
                }
                // Rest = Sonstige Artikelgruppen
                else {
                    if (svDto.getTDatum() != null) {
                        // Die KW dieses Datums ermitteln, damit das
                        // zugeordnet werden kann
                        GregorianCalendar gcSV = new GregorianCalendar();
                        gcSV.setTime(svDto.getTDatum());
                        int kwSV = gcSV.get(Calendar.WEEK_OF_YEAR);
                        Integer iIndexDerKW = hmKWIndizes.get(kwSV);
                        if (iIndexDerKW != null) {
                            // Hier nicht mit 5 multiplizieren, da es fuer
                            // jeden Tag einen eigenen Eintrag gibt
                            kapDto.addBdVerfuegbareStunden(indexSonstigeArtikelGruppen, iIndexDerKW,
                                    svDto.getNSollstunden());
                        } else {
                            // diese KW wird nicht mehr angezeigt - brauch
                            // ich nicht einrechnen
                        }
                    }
                }
            }
            // Maschinenzeit - die Verfuegbarkeit ist jeden Tag gleich
            else {
                Integer iZeile = hmMaschinenGruppenIndizes.get(svDto.getIGruppeid());
                // ist das eine sichtbare Gruppe
                if (iZeile != null) {
                    for (int iSpalte = 0; iSpalte < kapDto.getDetails()[iZeile].length; iSpalte++) {
                        // mal 5 Tage
                        kapDto.addBdVerfuegbareStunden(iZeile, iSpalte,
                                svDto.getNSollstunden().multiply(new BigDecimal(5)));
                    }
                }
                // wenn nicht, dann zu den sonstigen
                else {
                    for (int iSpalte = 0; iSpalte < kapDto
                            .getDetails()[indexSonstigeMaschinenGruppen].length; iSpalte++) {
                        // mal 5 Tage
                        kapDto.addBdVerfuegbareStunden(indexSonstigeMaschinenGruppen, iSpalte,
                                svDto.getNSollstunden().multiply(new BigDecimal(5)));
                    }
                }
            }
        }
        // ------------------------------------------------------------------
        // -----
        // Offene Zeiten ermitteln
        // ------------------------------------------------------------------
        // -----
        for (Iterator<?> iter = listLose.iterator(); iter.hasNext();) {
            FLRLos los = (FLRLos) iter.next();
            // Offene Menge ermitteln
            BigDecimal bdOffen = los.getN_losgroesse();
            for (Iterator<?> iterAblieferung = los.getAblieferungset().iterator(); iterAblieferung.hasNext();) {
                FLRLosablieferung item = (FLRLosablieferung) iterAblieferung.next();
                bdOffen = bdOffen.subtract(item.getN_menge());
            }
            // nur Lose mit tatsaechlich offener Menge>0
            if (bdOffen.compareTo(new BigDecimal(0)) > 0) {
                // Faktor zur Berechnung der offenen Zeiten = offene Menge /
                // Losgroesse. 2 Nachkommastellen sollten reichen.
                BigDecimal bdFaktor = bdOffen.divide(los.getN_losgroesse(), 2, BigDecimal.ROUND_HALF_EVEN);
                // Arbeitsplan holen
                Criteria cLosAZ = session.createCriteria(FLRLossollarbeitsplan.class);
                cLosAZ.add(Restrictions.eq(FertigungFac.FLR_LOSSOLLARBEITSPLAN_LOS_I_ID, los.getI_id()));
                List<?> listLosAZ = cLosAZ.list();
                // fuer alle Taetigkeiten
                for (Iterator<?> iterAZ = listLosAZ.iterator(); iterAZ.hasNext();) {
                    FLRLossollarbeitsplan losAZ = (FLRLossollarbeitsplan) iterAZ.next();
                    BigDecimal bdOffeneStunden = losAZ.getN_gesamtzeit().multiply(bdFaktor);
                    // ------------------------------------------------------
                    // -----------------
                    // Index der Gruppe bestimmen, der ich das zuordnen muss
                    // ------------------------------------------------------
                    // -----------------
                    int iZeilenIndex;
                    // 1. nach Maschinengruppe
                    // 2. nach Artikelgruppe der Taetigkeit
                    FLRMaschine flrMaschine = losAZ.getFlrmaschine();
                    Integer iMaschinengruppeIId = null;
                    Integer iArtikelgruppeIId = null;
                    if (flrMaschine != null) {
                        FLRMaschinengruppe flrMaschinengruppe = flrMaschine.getFlrmaschinengruppe();
                        if (flrMaschinengruppe != null) {
                            // Wenn diese Maschinengruppe dargestellt wird,
                            // dann kommt hier der index raus.
                            Integer i = hmMaschinenGruppenIndizes.get(flrMaschinengruppe.getI_id());
                            iMaschinengruppeIId = flrMaschinengruppe.getI_id();
                            if (i != null) {
                                iZeilenIndex = i;
                            }
                            // wenn nicht -> sonstige.
                            else {
                                iZeilenIndex = indexSonstigeMaschinenGruppen;
                            }
                        }
                        // Maschinen ohne Maschinengruppe werden nach
                        // "Sonstige" verdichtet.
                        else {
                            iZeilenIndex = indexSonstigeMaschinenGruppen;
                        }
                    } else {
                        FLRArtikel flrArtikel = losAZ.getFlrartikel();
                        FLRArtikelgruppe flrArtikelgruppe = flrArtikel.getFlrartikelgruppe();
                        if (flrArtikelgruppe != null) {
                            // Wenn diese Artikelgruppe dargestellt wird,
                            // dann kommt hier der index raus.
                            Integer i = hmArtikelGruppenIndizes.get(flrArtikelgruppe.getI_id());
                            iArtikelgruppeIId = flrArtikelgruppe.getI_id();
                            if (i != null) {
                                iZeilenIndex = i;
                            }
                            // wenn nicht -> sonstige.
                            else {
                                iZeilenIndex = indexSonstigeArtikelGruppen;
                            }
                        }
                        // Taetigkeiten ohne Artikelgruppe werden nach
                        // "Sonstige" verdichtet.
                        else {
                            iZeilenIndex = indexSonstigeArtikelGruppen;
                        }
                    }
                    // ------------------------------------------------------
                    // -----------------
                    // Jetzt hab ich die Gruppe, der ich das zuordnen muss
                    // nun muss die Zeit aufgeteilt werden
                    // ------------------------------------------------------
                    // -----------------
                    java.util.Date tLosStarttermin = los.getT_produktionsbeginn();
                    java.util.Date tLosEndetermin = los.getT_produktionsende();
                    // beide Termine duerfen nicht vor heute liegen
                    if (tLosStarttermin.before(getDate())) {
                        tLosStarttermin = getDate();
                    }
                    if (tLosEndetermin.before(getDate())) {
                        tLosEndetermin = getDate();
                    }
                    // Anzahl der betroffenen Kalenderwochen bestimmen
                    GregorianCalendar gcStart = new GregorianCalendar();
                    gcStart.setTime(tLosStarttermin);
                    GregorianCalendar gcEnde = new GregorianCalendar();
                    gcEnde.setTime(tLosEndetermin);
                    int iStartKW = gcStart.get(Calendar.WEEK_OF_YEAR);
                    int iEndeKW = gcEnde.get(Calendar.WEEK_OF_YEAR);
                    int iAnzahlKW = 1 + iEndeKW - iStartKW;
                    // nun auf die Wochen aufteilen
                    BigDecimal bdOffeneStundenJeWoche = bdOffeneStunden;

                    if (iAnzahlKW > 0) {
                        bdOffeneStundenJeWoche = bdOffeneStunden.divide(new BigDecimal(iAnzahlKW), 2,
                                RoundingMode.HALF_UP);
                    }

                    for (int iAktuelleKW = iStartKW; iAktuelleKW <= iEndeKW; iAktuelleKW++) {
                        Integer indexDerKW = hmKWIndizes.get(iAktuelleKW);
                        // wird diese Woche auch angezeigt?
                        if (indexDerKW != null) {
                            KapazitaetsvorschauDetailDto detailDto = new KapazitaetsvorschauDetailDto();
                            detailDto.setArtikelgruppeIId(iArtikelgruppeIId);
                            detailDto.setArtikelIIdTaetigkeit(losAZ.getFlrartikel().getI_id());
                            detailDto.setBdDauer(bdOffeneStundenJeWoche);
                            detailDto.setLosIId(los.getI_id());
                            detailDto.setLossollarbeitsplanIId(losAZ.getI_id());
                            detailDto.setMaschinengruppeIId(iMaschinengruppeIId);
                            kapDto.addDetail(iZeilenIndex, indexDerKW, detailDto);
                        }
                    }
                }
            }
        }

        // ------------------------------------------------------------------
        // -----
        // Diagramm aus den Daten erstellen
        // ------------------------------------------------------------------
        // -----
        SymbolAxis xAchse = new SymbolAxis("KW", kw);
        CombinedDomainXYPlot plot = new CombinedDomainXYPlot(xAchse);
        for (int iZeile = 0; iZeile < kapDto.getDetails().length; iZeile++) {
            XYSeries datenZeile = new XYSeries(kapDto.getIZeilenueberschrift(iZeile));
            // Balkenfarben festlegen ( >100% = rot, sonst hellgrau)
            // fuer jede zeile und jede spalte
            Paint[][] paints = new Paint[1][kapDto.getDetails()[iZeile].length];
            for (int iSpalte = 0; iSpalte < kapDto.getDetails()[iZeile].length; iSpalte++) {
                BigDecimal bdVerfuegbar = kapDto.getBdVerfuegbareStunden()[iZeile][iSpalte];
                BigDecimal bdBenoetigt = new BigDecimal(0);
                // Benoetigte Zeit jet Gruppe je Woche ermitteln
                for (Iterator<?> iter = kapDto.getDetails()[iZeile][iSpalte].iterator(); iter.hasNext();) {
                    KapazitaetsvorschauDetailDto item = (KapazitaetsvorschauDetailDto) iter.next();
                    bdBenoetigt = bdBenoetigt.add(item.getBdDauer());
                }
                BigDecimal value = new BigDecimal(0);
                if (bdVerfuegbar.compareTo(new BigDecimal(0)) > 0) {
                    value = (bdBenoetigt.multiply(new BigDecimal(100))).divide(bdVerfuegbar, 4,
                            BigDecimal.ROUND_HALF_EVEN);
                    if (value.doubleValue() > 100.0) {
                        paints[0][iSpalte] = Color.red;
                    } else {
                        paints[0][iSpalte] = Color.lightGray;
                    }
                }
                // tage ohne Verfuegbarkeit mach ich 100% und weisz
                else {
                    value = new BigDecimal(100.0);
                    // Wochen ohne Kapazitaet aber mit geplanter Zeit
                    if (bdBenoetigt.compareTo(new BigDecimal(0)) > 0) {
                        paints[0][iSpalte] = Color.MAGENTA;
                    }
                    // Wenn nichts verfuegbar aber auch nichts benoetigt ->
                    // weiss
                    else {
                        paints[0][iSpalte] = Color.white;
                    }
                }
                XYDataItem data = new XYDataItem(iSpalte, value.doubleValue());
                datenZeile.add(data);
            }
            // Zur Collection
            XYSeriesCollection xyDataset = new XYSeriesCollection();
            xyDataset.addSeries(datenZeile);

            // subplot erstellen
            XYItemRenderer renderer1 = new CustomXYBarRenderer(paints);

            // renderer1.setItemLabelsVisible(true);
            // Legende nicht anzeigen
            renderer1.setBaseSeriesVisibleInLegend(false);
            NumberAxis zeilenAchse = new NumberAxis(kapDto.getIZeilenueberschrift(iZeile));
            // Beschriftung der Y-Achse um 90 grad drehen
            zeilenAchse.setLabelAngle(Math.PI / 2.0);
            zeilenAchse.setAutoRange(true);
            XYPlot subplot1 = new XYPlot(xyDataset, null, zeilenAchse, renderer1);
            subplot1.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
            // Markierung bei 100%
            final Marker target = new ValueMarker(100.0);
            target.setPaint(Color.darkGray);
            // target.setLabel("100 %"); // Label
            // target.setLabelAnchor(RectangleAnchor.TOP_RIGHT);
            // target.setLabelTextAnchor(TextAnchor.BOTTOM_RIGHT);
            subplot1.addRangeMarker(target);

            plot.add(subplot1); // plot.add(subplot1, 1);
        }
        JFreeChart lStackedBarChart = new JFreeChart(plot);

        kapDto.setJfcKapazitaetsvorschau(lStackedBarChart);
    } catch (RemoteException ex) {
        throwEJBExceptionLPRespectOld(ex);
    } finally {
        if (session != null) {
            session.close();
        }
    }
    return kapDto;
}

From source file:org.sakaiproject.assignment.impl.BaseAssignmentService.java

public Map<String, String> transferCopyEntitiesRefMigrator(String fromContext, String toContext,
        List resourceIds) {/* w  ww .  ja va2 s.co  m*/
    Map<String, String> transversalMap = new HashMap<String, String>();
    // import Assignment objects
    Iterator oAssignments = getAssignmentsForContext(fromContext);
    while (oAssignments.hasNext()) {
        Assignment oAssignment = (Assignment) oAssignments.next();
        String oAssignmentId = oAssignment.getId();

        boolean toBeImported = true;
        if (resourceIds != null && resourceIds.size() > 0) {
            // if there is a list for import assignments, only import those assignments and relative submissions
            toBeImported = false;
            for (int m = 0; m < resourceIds.size() && !toBeImported; m++) {
                if (((String) resourceIds.get(m)).equals(oAssignmentId)) {
                    toBeImported = true;
                }
            }
        }

        if (toBeImported) {
            AssignmentEdit nAssignment = null;
            AssignmentContentEdit nContent = null;

            if (!m_assignmentStorage.check(oAssignmentId)) {

            } else {
                try {
                    // add new Assignment content
                    String oContentReference = oAssignment.getContentReference();
                    String oContentId = contentId(oContentReference);
                    if (!m_contentStorage.check(oContentId))
                        throw new IdUnusedException(oContentId);
                    else {
                        AssignmentContent oContent = getAssignmentContent(oContentReference);
                        nContent = addAssignmentContent(toContext);
                        // attributes
                        nContent.setAllowAttachments(oContent.getAllowAttachments());
                        nContent.setContext(toContext);
                        nContent.setGroupProject(oContent.getGroupProject());
                        nContent.setHonorPledge(oContent.getHonorPledge());
                        nContent.setHideDueDate(oContent.getHideDueDate());
                        nContent.setIndividuallyGraded(oContent.individuallyGraded());
                        // replace all occurrence of old context with new context inside instruction text
                        String instructions = oContent.getInstructions();
                        if (instructions.indexOf(fromContext) != -1) {
                            instructions = instructions.replaceAll(fromContext, toContext);
                        }
                        nContent.setInstructions(instructions);
                        nContent.setMaxGradePoint(oContent.getMaxGradePoint());
                        nContent.setFactor(oContent.getFactor());
                        nContent.setReleaseGrades(oContent.releaseGrades());
                        nContent.setTimeLastModified(oContent.getTimeLastModified());
                        nContent.setTitle(oContent.getTitle());
                        nContent.setTypeOfGrade(oContent.getTypeOfGrade());
                        nContent.setTypeOfSubmission(oContent.getTypeOfSubmission());
                        // review service
                        nContent.setAllowReviewService(oContent.getAllowReviewService());
                        // properties
                        ResourcePropertiesEdit p = nContent.getPropertiesEdit();
                        p.clear();
                        p.addAll(oContent.getProperties());
                        // update live properties
                        addLiveProperties(p);
                        // attachment
                        List oAttachments = oContent.getAttachments();
                        List nAttachments = m_entityManager.newReferenceList();
                        for (int n = 0; n < oAttachments.size(); n++) {
                            Reference oAttachmentRef = (Reference) oAttachments.get(n);
                            String oAttachmentId = ((Reference) oAttachments.get(n)).getId();
                            if (oAttachmentId.indexOf(fromContext) != -1) {
                                // transfer attachment, replace the context string and add new attachment if necessary
                                transferAttachment(fromContext, toContext, nAttachments, oAttachmentId);
                            } else {
                                nAttachments.add(oAttachmentRef);
                            }
                        }
                        nContent.replaceAttachments(nAttachments);
                        // complete the edit
                        m_contentStorage.commit(nContent);
                        ((BaseAssignmentContentEdit) nContent).closeEdit();
                    }
                } catch (Exception e) {
                    if (M_log.isWarnEnabled())
                        M_log.warn(" transferCopyEntities " + e.toString() + " oAssignmentId=" + oAssignmentId);
                }

                if (nContent != null) {
                    try {
                        // add new assignment
                        nAssignment = addAssignment(toContext);
                        // attribute
                        nAssignment.setCloseTime(oAssignment.getCloseTime());
                        nAssignment.setContentReference(nContent.getReference());
                        nAssignment.setContext(toContext);

                        // when importing, refer to property to determine draft status
                        if ("false".equalsIgnoreCase(
                                m_serverConfigurationService.getString("import.importAsDraft"))) {
                            nAssignment.setDraft(oAssignment.getDraft());
                        } else {
                            nAssignment.setDraft(true);
                        }

                        nAssignment.setGroup(oAssignment.isGroup());
                        nAssignment.setDropDeadTime(oAssignment.getDropDeadTime());
                        nAssignment.setDueTime(oAssignment.getDueTime());
                        nAssignment.setOpenTime(oAssignment.getOpenTime());
                        nAssignment.setSection(oAssignment.getSection());
                        nAssignment.setTitle(oAssignment.getTitle());
                        nAssignment.setPosition_order(oAssignment.getPosition_order());

                        nAssignment.setAllowPeerAssessment(nAssignment.getAllowPeerAssessment());
                        nAssignment.setPeerAssessmentAnonEval(oAssignment.getPeerAssessmentAnonEval());
                        nAssignment.setPeerAssessmentInstructions(oAssignment.getPeerAssessmentInstructions());
                        nAssignment.setPeerAssessmentNumReviews(oAssignment.getPeerAssessmentNumReviews());
                        nAssignment.setPeerAssessmentStudentViewReviews(
                                oAssignment.getPeerAssessmentStudentViewReviews());
                        nAssignment.setPeerAssessmentPeriod(oAssignment.getPeerAssessmentPeriod());
                        if (nAssignment.getPeerAssessmentPeriod() == null
                                && nAssignment.getCloseTime() != null) {
                            // set the peer period time to be 10 mins after accept until date
                            GregorianCalendar c = new GregorianCalendar();
                            c.setTimeInMillis(nAssignment.getCloseTime().getTime());
                            c.add(GregorianCalendar.MINUTE, 10);
                            nAssignment.setPeerAssessmentPeriod(TimeService.newTime(c.getTimeInMillis()));
                        }
                        // properties
                        ResourcePropertiesEdit p = nAssignment.getPropertiesEdit();
                        p.clear();
                        p.addAll(oAssignment.getProperties());

                        // one more touch on the gradebook-integration link    
                        String associatedGradebookAssignment = StringUtils
                                .trimToNull(p.getProperty(PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT));
                        if (associatedGradebookAssignment != null) {
                            // see if the old assignment's associated gradebook item is an internal gradebook entry or externally defined
                            boolean isExternalAssignmentDefined = m_gradebookExternalAssessmentService
                                    .isExternalAssignmentDefined(oAssignment.getContent().getContext(),
                                            associatedGradebookAssignment);
                            if (isExternalAssignmentDefined) {
                                // if this is an external defined (came from assignment)
                                // mark the link as "add to gradebook" for the new imported assignment, since the assignment is still of draft state
                                //later when user posts the assignment, the corresponding assignment will be created in gradebook.    
                                p.removeProperty(PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
                                p.addProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, GRADEBOOK_INTEGRATION_ADD);
                            }
                        }

                        // remove the link btw assignment and announcement item. One can announce the open date afterwards
                        p.removeProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE);
                        p.removeProperty("new_assignment_open_date_announced");
                        p.removeProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID);

                        // remove the link btw assignment and calendar item. One can add the due date to calendar afterwards
                        p.removeProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE);
                        p.removeProperty("new_assignment_due_date_scheduled");
                        p.removeProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID);

                        // update live properties
                        addLiveProperties(p);
                        // complete the edit
                        m_assignmentStorage.commit(nAssignment);
                        ((BaseAssignmentEdit) nAssignment).closeEdit();

                        transversalMap.put("assignment/" + oAssignment.getId(),
                                "assignment/" + nAssignment.getId());
                        M_log.info("old assignment id:" + oAssignment.getId() + " - new assignment id:"
                                + nAssignment.getId());

                        try {
                            if (m_taggingManager.isTaggable()) {
                                for (TaggingProvider provider : m_taggingManager.getProviders()) {
                                    provider.transferCopyTags(
                                            m_assignmentActivityProducer.getActivity(oAssignment),
                                            m_assignmentActivityProducer.getActivity(nAssignment));
                                }
                            }
                        } catch (PermissionException pe) {
                            M_log.error(this + " transferCopyEntities " + pe.toString() + " oAssignmentId="
                                    + oAssignment.getId() + " nAssignmentId=" + nAssignment.getId());
                        }
                    } catch (Exception ee) {
                        M_log.error(this + " transferCopyEntities " + ee.toString() + " oAssignmentId="
                                + oAssignment.getId() + " nAssignmentId=" + nAssignment.getId());
                    }
                }
            } // if-else
        } // if
    } // for
    return transversalMap;
}

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

/**
 * supplement item related information/*from  ww w. ja v a 2s  .c  o m*/
 * @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:org.sakaiproject.assignment.tool.AssignmentAction.java

/**
 * Action is to show the edit assignment screen
 *///w  w w . j a va2s . c o m
public void doEdit_assignment(RunData data) {
    SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
    ParameterParser params = data.getParameters();

    String assignmentId = StringUtils.trimToNull(params.getString("assignmentId"));
    if (AssignmentService.allowUpdateAssignment(assignmentId)) {
        Assignment a = getAssignment(assignmentId, "doEdit_assignment", state);
        if (a != null) {
            // whether the user can modify the assignment
            state.setAttribute(EDIT_ASSIGNMENT_ID, assignmentId);

            // for the non_electronice assignment, submissions are auto-generated by the time that assignment is created;
            // don't need to go through the following checkings.
            if (a.getContent().getTypeOfSubmission() != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) {
                Iterator submissions = AssignmentService.getSubmissions(a).iterator();
                if (submissions.hasNext()) {
                    // any submitted?
                    boolean anySubmitted = false;
                    for (; submissions.hasNext() && !anySubmitted;) {
                        AssignmentSubmission s = (AssignmentSubmission) submissions.next();
                        if (s.getSubmitted() && s.getTimeSubmitted() != null) {
                            anySubmitted = true;
                        }
                    }

                    // any draft submission
                    boolean anyDraft = false;
                    for (; submissions.hasNext() && !anyDraft;) {
                        AssignmentSubmission s = (AssignmentSubmission) submissions.next();
                        if (!s.getSubmitted()) {
                            anyDraft = true;
                        }
                    }
                    if (anySubmitted) {
                        // if there is any submitted submission to this assignment, show alert
                        addAlert(state, rb.getFormattedMessage("hassum", new Object[] { a.getTitle() }));
                    }

                    if (anyDraft) {
                        // otherwise, show alert about someone has started working on the assignment, not necessarily submitted
                        addAlert(state, rb.getString("hasDraftSum"));
                    }
                }
            }

            // SECTION MOD
            state.setAttribute(STATE_SECTION_STRING, a.getSection());

            // put the names and values into vm file
            state.setAttribute(NEW_ASSIGNMENT_TITLE, a.getTitle());
            state.setAttribute(NEW_ASSIGNMENT_ORDER, a.getPosition_order());

            if (Boolean
                    .valueOf(ServerConfigurationService.getBoolean("assignment.visible.date.enabled", false))) {
                putTimePropertiesInState(state, a.getVisibleTime(), NEW_ASSIGNMENT_VISIBLEMONTH,
                        NEW_ASSIGNMENT_VISIBLEDAY, NEW_ASSIGNMENT_VISIBLEYEAR, NEW_ASSIGNMENT_VISIBLEHOUR,
                        NEW_ASSIGNMENT_VISIBLEMIN);
                state.setAttribute(NEW_ASSIGNMENT_VISIBLETOGGLE, a.getVisibleTime() != null);
            }

            putTimePropertiesInState(state, a.getOpenTime(), NEW_ASSIGNMENT_OPENMONTH, NEW_ASSIGNMENT_OPENDAY,
                    NEW_ASSIGNMENT_OPENYEAR, NEW_ASSIGNMENT_OPENHOUR, NEW_ASSIGNMENT_OPENMIN);
            // generate alert when editing an assignment past open date
            if (a.getOpenTime().before(TimeService.newTime())) {
                addAlert(state, rb.getString("youarenot20"));
            }

            putTimePropertiesInState(state, a.getDueTime(), NEW_ASSIGNMENT_DUEMONTH, NEW_ASSIGNMENT_DUEDAY,
                    NEW_ASSIGNMENT_DUEYEAR, NEW_ASSIGNMENT_DUEHOUR, NEW_ASSIGNMENT_DUEMIN);
            // generate alert when editing an assignment past due date
            if (a.getDueTime().before(TimeService.newTime())) {
                addAlert(state, rb.getString("youarenot17"));
            }

            if (a.getCloseTime() != null) {
                state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, Boolean.valueOf(true));
                putTimePropertiesInState(state, a.getCloseTime(), NEW_ASSIGNMENT_CLOSEMONTH,
                        NEW_ASSIGNMENT_CLOSEDAY, NEW_ASSIGNMENT_CLOSEYEAR, NEW_ASSIGNMENT_CLOSEHOUR,
                        NEW_ASSIGNMENT_CLOSEMIN);
            } else {
                state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, Boolean.valueOf(false));
                state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, state.getAttribute(NEW_ASSIGNMENT_DUEMONTH));
                state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, state.getAttribute(NEW_ASSIGNMENT_DUEDAY));
                state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, state.getAttribute(NEW_ASSIGNMENT_DUEYEAR));
                state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, state.getAttribute(NEW_ASSIGNMENT_DUEHOUR));
                state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, state.getAttribute(NEW_ASSIGNMENT_DUEMIN));
            }
            state.setAttribute(NEW_ASSIGNMENT_SECTION, a.getSection());

            state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE,
                    Integer.valueOf(a.getContent().getTypeOfSubmission()));
            state.setAttribute(NEW_ASSIGNMENT_CATEGORY, getAssignmentCategoryAsInt(a));
            int typeOfGrade = a.getContent().getTypeOfGrade();
            state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, Integer.valueOf(typeOfGrade));
            if (typeOfGrade == 3) {
                state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, a.getContent().getMaxGradePointDisplay());
            }
            state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, a.getContent().getInstructions());
            state.setAttribute(NEW_ASSIGNMENT_CHECK_HIDE_DUE_DATE,
                    Boolean.valueOf(a.getContent().getHideDueDate()).toString());
            ResourceProperties properties = a.getProperties();
            state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE,
                    properties.getProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE));

            state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE,
                    properties.getProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE));

            String defaultNotification = ServerConfigurationService
                    .getString("announcement.default.notification", "n");
            if (defaultNotification.equalsIgnoreCase("r")) {
                state.setAttribute(Assignment.ASSIGNMENT_OPENDATE_NOTIFICATION,
                        Assignment.ASSIGNMENT_OPENDATE_NOTIFICATION_HIGH);
            } else if (defaultNotification.equalsIgnoreCase("o")) {
                state.setAttribute(Assignment.ASSIGNMENT_OPENDATE_NOTIFICATION,
                        Assignment.ASSIGNMENT_OPENDATE_NOTIFICATION_LOW);
            } else {
                state.setAttribute(Assignment.ASSIGNMENT_OPENDATE_NOTIFICATION,
                        Assignment.ASSIGNMENT_OPENDATE_NOTIFICATION_NONE);
            }

            state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE,
                    Integer.toString(a.getContent().getHonorPledge()));

            state.setAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK,
                    properties.getProperty(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK));
            state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT,
                    properties.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT));

            state.setAttribute(ATTACHMENTS, a.getContent().getAttachments());

            // submission notification option
            if (properties.getProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) != null) {
                state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE,
                        properties.getProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE));
            }
            // release grade notification option
            if (properties.getProperty(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE) != null) {
                state.setAttribute(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE,
                        properties.getProperty(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE));
            }

            // group setting
            if (a.getAccess().equals(Assignment.AssignmentAccess.SITE)) {
                state.setAttribute(NEW_ASSIGNMENT_RANGE, "site");
            } else {
                state.setAttribute(NEW_ASSIGNMENT_RANGE, "groups");
            }

            // SAK-17606
            state.setAttribute(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING,
                    properties.getProperty(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING));

            // put the resubmission option into state
            assignment_resubmission_option_into_state(a, null, state);

            // set whether we use peer assessment or not
            Time peerAssessmentPeriod = a.getPeerAssessmentPeriod();
            //check if peer assessment time exist? if not, this could be an old assignment, so just set it
            //to 10 min after accept until date
            if (peerAssessmentPeriod == null && a.getCloseTime() != null) {
                // set the peer period time to be 10 mins after accept until date
                GregorianCalendar c = new GregorianCalendar();
                c.setTimeInMillis(a.getCloseTime().getTime());
                c.add(GregorianCalendar.MINUTE, 10);
                peerAssessmentPeriod = TimeService.newTime(c.getTimeInMillis());
            }
            if (peerAssessmentPeriod != null) {
                state.setAttribute(NEW_ASSIGNMENT_USE_PEER_ASSESSMENT,
                        Boolean.valueOf(a.getAllowPeerAssessment()).toString());
                putTimePropertiesInState(state, peerAssessmentPeriod, NEW_ASSIGNMENT_PEERPERIODMONTH,
                        NEW_ASSIGNMENT_PEERPERIODDAY, NEW_ASSIGNMENT_PEERPERIODYEAR,
                        NEW_ASSIGNMENT_PEERPERIODHOUR, NEW_ASSIGNMENT_PEERPERIODMIN);
                state.setAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_ANON_EVAL,
                        Boolean.valueOf(a.getPeerAssessmentAnonEval()).toString());
                state.setAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_STUDENT_VIEW_REVIEWS,
                        Boolean.valueOf(a.getPeerAssessmentStudentViewReviews()).toString());
                state.setAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_NUM_REVIEWS, a.getPeerAssessmentNumReviews());
                state.setAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_INSTRUCTIONS,
                        a.getPeerAssessmentInstructions());
            }
            if (!allowPeerAssessment) {
                state.setAttribute(NEW_ASSIGNMENT_USE_PEER_ASSESSMENT, false);
            }
            // set whether we use the review service or not
            state.setAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE,
                    Boolean.valueOf(a.getContent().getAllowReviewService()).toString());

            //set whether students can view the review service results
            state.setAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW,
                    Boolean.valueOf(a.getContent().getAllowStudentViewReport()).toString());

            state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_RADIO,
                    a.getContent().getSubmitReviewRepo());
            state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_RADIO,
                    a.getContent().getGenerateOriginalityReport());
            state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_TURNITIN,
                    Boolean.valueOf(a.getContent().isCheckTurnitin()).toString());
            state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INTERNET,
                    Boolean.valueOf(a.getContent().isCheckInternet()).toString());
            state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_PUB,
                    Boolean.valueOf(a.getContent().isCheckPublications()).toString());
            state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INSTITUTION,
                    Boolean.valueOf(a.getContent().isCheckInstitution()).toString());
            //exclude bibliographic
            state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_BIBLIOGRAPHIC,
                    Boolean.valueOf(a.getContent().isExcludeBibliographic()).toString());
            //exclude quoted
            state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_QUOTED,
                    Boolean.valueOf(a.getContent().isExcludeQuoted()).toString());
            //exclude type
            state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_TYPE, a.getContent().getExcludeType());
            //exclude value
            state.setAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_VALUE, a.getContent().getExcludeValue());

            state.setAttribute(NEW_ASSIGNMENT_GROUPS, a.getGroups());

            state.setAttribute(NEW_ASSIGNMENT_GROUP_SUBMIT, a.isGroup() ? "1" : "0");

            // get all supplement item info into state
            setAssignmentSupplementItemInState(state, a);

            state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT);
        }
    } else {
        addAlert(state, rb.getString("youarenot6"));
    }

}