Example usage for java.util Date setTime

List of usage examples for java.util Date setTime

Introduction

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

Prototype

public void setTime(long time) 

Source Link

Document

Sets this Date object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT.

Usage

From source file:org.ejbca.core.protocol.ws.EjbcaWS.java

public List<Certificate> getCertificatesByExpirationTime(long days, int maxNumberOfResults)
        throws EjbcaException {
    Date findDate = new Date();
    long millis = (days * 24 * 60 * 60 * 1000);
    findDate.setTime(findDate.getTime() + millis);
    Collection<java.security.cert.Certificate> certs = certificateStoreSession
            .findCertificatesByExpireTimeWithLimit(findDate, maxNumberOfResults);

    ArrayList<Certificate> ret = new ArrayList<Certificate>();
    for (java.security.cert.Certificate cert : certs) {
        try {/*from   w  ww. j  a va  2s .c om*/
            ret.add(new Certificate(cert));
        } catch (CertificateEncodingException e) {
            throw EjbcaWSHelper.getInternalException(e, TransactionLogger.getPatternLogger());
        }
    }
    return ret;
}

From source file:org.ejbca.core.protocol.ws.EjbcaWS.java

public List<Certificate> getCertificatesByExpirationTimeAndIssuer(long days, String issuer,
        int maxNumberOfResults) throws EjbcaException {
    Date findDate = new Date();
    long millis = (days * 24 * 60 * 60 * 1000);
    findDate.setTime(findDate.getTime() + millis);
    Collection<java.security.cert.Certificate> certs = certificateStoreSession
            .findCertificatesByExpireTimeAndIssuerWithLimit(findDate, issuer, maxNumberOfResults);

    ArrayList<Certificate> ret = new ArrayList<Certificate>();
    for (java.security.cert.Certificate cert : certs) {
        try {// w w w  .j a va  2s . c  o m
            ret.add(new Certificate(cert));
        } catch (CertificateEncodingException e) {
            throw EjbcaWSHelper.getInternalException(e, TransactionLogger.getPatternLogger());
        }
    }
    return ret;
}

From source file:org.ejbca.core.protocol.ws.EjbcaWS.java

public List<Certificate> getCertificatesByExpirationTimeAndType(long days, int certificateType,
        int maxNumberOfResults) throws EjbcaException {
    Date findDate = new Date();
    long millis = (days * 24 * 60 * 60 * 1000);
    findDate.setTime(findDate.getTime() + millis);
    Collection<java.security.cert.Certificate> certs = certificateStoreSession
            .findCertificatesByExpireTimeAndTypeWithLimit(findDate, certificateType, maxNumberOfResults);

    ArrayList<Certificate> ret = new ArrayList<Certificate>();
    for (java.security.cert.Certificate cert : certs) {
        try {//  ww w . j  a  v  a 2s . co m
            ret.add(new Certificate(cert));
        } catch (CertificateEncodingException e) {
            throw EjbcaWSHelper.getInternalException(e, TransactionLogger.getPatternLogger());
        }
    }
    return ret;
}

From source file:it.infn.ct.wrf.Wrf.java

private void sendHTMLEmail(String USERNAME, String TO, String FROM, String SMTP_HOST, String ApplicationAcronym,
        String GATEWAY) {/* w ww .  j a  va 2s.co m*/

    log.info("\n- Sending email notification to the user " + USERNAME + " [ " + TO + " ]");

    log.info("\n- SMTP Server = " + SMTP_HOST);
    log.info("\n- Sender = " + FROM);
    log.info("\n- Receiver = " + TO);
    log.info("\n- Application = " + ApplicationAcronym);
    log.info("\n- Gateway = " + GATEWAY);

    // Assuming you are sending email from localhost
    String HOST = "localhost";

    // Get system properties
    Properties properties = System.getProperties();
    properties.setProperty(SMTP_HOST, HOST);

    // Get the default Session object.
    Session session = Session.getDefaultInstance(properties);

    try {
        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(FROM));

        // Set To: header field of the header.
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO));
        //message.addRecipient(Message.RecipientType.CC, new InternetAddress(FROM));

        // Set Subject: header field
        message.setSubject(" [liferay-sg-gateway] - [ " + GATEWAY + " ] ");

        Date currentDate = new Date();
        currentDate.setTime(currentDate.getTime());

        // Send the actual HTML message, as big as you like
        message.setContent("<br/><H4>"
                + "<img src=\"http://fbcdn-profile-a.akamaihd.net/hprofile-ak-snc6/195775_220075701389624_155250493_n.jpg\" width=\"100\">Science Gateway Notification"
                + "</H4><hr><br/>" + "<b>Description:</b> Notification for the application <b>[ "
                + ApplicationAcronym + " ]</b><br/><br/>"
                + "<i>The application has been successfully submitted from the [ " + GATEWAY
                + " ]</i><br/><br/>" + "<b>TimeStamp:</b> " + currentDate + "<br/><br/>"
                + "<b>Disclaimer:</b><br/>"
                + "<i>This is an automatic message sent by the Science Gateway based on Liferay technology.<br/>"
                + "If you did not submit any jobs through the Science Gateway, please " + "<a href=\"mailto:"
                + FROM + "\">contact us</a></i>", "text/html");

        // Send message
        Transport.send(message);
    } catch (MessagingException mex) {
        mex.printStackTrace();
    }
}

From source file:org.apache.manifoldcf.crawler.connectors.sharepoint.SharePointRepository.java

protected static int unpackDate(String value, int index, Date theDate) {
    if (value.length() > index) {
        if (value.charAt(index++) == '+') {
            StringBuilder sb = new StringBuilder();
            index = unpack(sb, value, index, '+');
            if (sb.length() > 0) {
                theDate.setTime(new Long(sb.toString()).longValue());
            }//from  www .  j a  v a2  s  .c  o  m
        }
    }
    return index;
}

From source file:org.celllife.idart.gui.packaging.NewPatientPackaging.java

/**
 * Method savePackageAndPackagedDrugs./*from ww  w.  j  a  v  a 2s  . c  o  m*/
 * 
 * @param dispenseNow
 *            boolean
 * @param allPackageDrugsList
 *            java.util.List<PackageDrugInfo>
 * @throws Exception
 */
private void savePackageAndPackagedDrugs(boolean dispenseNow,
        java.util.List<PackageDrugInfo> allPackageDrugsList) throws Exception {

    // if pack date is today, store the time too, else store 12am
    Date today = new Date();
    Date packDate = new Date();
    packDate.setTime(newPack.getPackDate().getTime());

    if (DateFieldComparator.compare(today, packDate, Calendar.DAY_OF_MONTH) == 0) {
        newPack.setPickupDate(new Date());
    }

    newPack.setPackageId(newPack.getPrescription().getPrescriptionId() + "-" + lblIndex.getText());
    newPack.setModified('T');

    int numPeriods = getSelectedWeekSupply();
    getLog().info("getSelectedWeekSupply() called");
    newPack.setWeekssupply(numPeriods);
    /*
     * If the pharmacist is giving the drugs to the patient now, set the
     * dateLeft, dateReceived and pickupDate to today. Else ... set these
     * attributes to null (they will be set when the packages have left the
     * pharmacy, arrived at the remote clinic, and when the patient has
     * picked up their medications
     */
    if (dispenseNow) {
        newPack.setDateLeft(newPack.getPackDate());
        newPack.setDateReceived(newPack.getPackDate());
        newPack.setPickupDate(newPack.getPackDate());
    } else {
        if (iDartProperties.downReferralMode.equalsIgnoreCase(iDartProperties.OFFLINE_DOWNREFERRAL_MODE)) {
            newPack.setDateLeft(newPack.getPackDate());
            newPack.setDateReceived(newPack.getPackDate());
            newPack.setPickupDate(null);
        } else {
            newPack.setDateLeft(null);
            newPack.setDateReceived(null);
            newPack.setPickupDate(null);
        }
    }

    // Make up a set of package drugs for this particular package
    java.util.List<PackagedDrugs> packagedDrugsList = new ArrayList<PackagedDrugs>();

    for (int i = 0; i < allPackageDrugsList.size(); i++) {

        PackageDrugInfo pdi = allPackageDrugsList.get(i);
        PackagedDrugs pd = new PackagedDrugs();
        pd.setAmount(pdi.getDispensedQty());
        pd.setParentPackage(newPack);
        pd.setStock(StockManager.getStock(getHSession(), pdi.getStockId()));
        pd.setModified('T');
        packagedDrugsList.add(pd);
        if (rdBtnDispenseNow.getSelection()) {
            pdi.setDateExpectedString(sdf.format(btnNextAppDate.getDate()));
        } else {

            Appointment nextApp = PatientManager
                    .getLatestAppointmentForPatient(newPack.getPrescription().getPatient(), true);

            if (nextApp != null)
                pdi.setDateExpectedString(sdf.format(nextApp.getAppointmentDate()));
        }
        pdi.setPackagedDrug(pd);
        pdi.setNotes(localPatient.getCurrentClinic().getNotes());
        pdi.setPackageId(newPack.getPackageId());

    }

    newPack.setPackagedDrugs(packagedDrugsList);
    newPack.setAccumulatedDrugs(getAccumDrugsToSave());

    // de-normalise table to speed up reports 
    if (newPack.hasARVDrug())
        newPack.setDrugTypes("ARV");

    PackageManager.savePackage(getHSession(), newPack);

    //Add interoperability with OpenMRS through Rest Web Services
    RestClient restClient = new RestClient();

    Date dtPickUp = newPack.getPickupDate();

    //EncounterDatetime
    String strPickUp = RestUtils.castDateToString(dtPickUp);

    //Patient NID 
    String nid = newPack.getPrescription().getPatient().getPatientId().trim();

    String nidRest = restClient
            .getOpenMRSResource(iDartProperties.REST_GET_PATIENT + StringUtils.replace(nid, " ", "%20"));

    //Patient NID uuid 
    String nidUuid = nidRest.substring(21, 57);

    String strProvider = newPack.getPrescription().getDoctor().getFirstname().trim() + " "
            + newPack.getPrescription().getDoctor().getLastname().trim();

    String providerWithNoAccents = org.apache.commons.lang3.StringUtils.stripAccents(strProvider);

    String response = restClient.getOpenMRSResource(
            iDartProperties.REST_GET_PERSON + StringUtils.replace(providerWithNoAccents, " ", "%20"));

    //Provider
    String providerUuid = response.substring(21, 57);

    String facility = newPack.getClinic().getClinicName().trim();

    //Location
    String strFacility = restClient
            .getOpenMRSResource(iDartProperties.REST_GET_LOCATION + StringUtils.replace(facility, " ", "%20"));

    //Health Facility
    String strFacilityUuid = strFacility.substring(21, 57);

    //Regimen
    String regimenAnswer = newPack.getPrescription().getRegimeTerapeutico().getRegimenomeespecificado().trim();

    String strRegimenAnswer = restClient
            .getOpenMRSResource("concept?q=" + StringUtils.replace(regimenAnswer, " ", "%20"));

    //Regimen answer Uuid
    String strRegimenAnswerUuid = strRegimenAnswer.substring(21, 57);

    List<PrescribedDrugs> prescribedDrugs = newPack.getPrescription().getPrescribedDrugs();

    //Next pick up date
    Date dtNextPickUp = btnNextAppDate.getDate();

    String strNextPickUp = RestUtils.castDateToString(dtNextPickUp);

    /*if (restClient.postOpenMRSEncounter(strPickUp, nidUuid, encounterType, 
    strFacilityUuid, filaUuid, providerUuid, regimeUuid, strRegimenAnswerUuid, 
    dispensedAmountUuid, packSize, dosageUuid, customizedDosage, returnVisitUuid, strNextPickUp)) {
              
    PackageManager.savePackage(getHSession(), newPack);
    } else {
            
    showMessage(MessageDialog.ERROR,
          "O Paciente no pode ser dispensado.",
          "Entre em contacto com o Administrador do sistema.");
    }*/

    try {
        restClient.postOpenMRSEncounter(strPickUp, nidUuid, iDartProperties.ENCOUNTER_TYPE_PHARMACY,
                strFacilityUuid, iDartProperties.FORM_FILA, providerUuid, iDartProperties.REGIME,
                strRegimenAnswerUuid, iDartProperties.DISPENSED_AMOUNT, prescribedDrugs, iDartProperties.DOSAGE,
                iDartProperties.VISIT_UUID, strNextPickUp);
    } catch (Exception e) {
        getLog().info(e.getMessage());
    }
}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.MobileServiceSyncTableTests.java

public void testincrementalSyncUsesSkipWhenMaxUpdateAtIsSame()
        throws MalformedURLException, InterruptedException, ExecutionException, MobileServiceException {

    MobileServiceLocalStoreMock store = new MobileServiceLocalStoreMock();
    ServiceFilterContainer serviceFilterContainer = new ServiceFilterContainer();
    String queryKey = "QueryKey";
    String incrementalPullStrategyTable = "__incrementalPullData";

    MobileServiceClient client = new MobileServiceClient(appUrl, appKey,
            getInstrumentation().getTargetContext());

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

    Date d = new Date();
    String updatedAt1 = sdf.format(d);
    d.setTime(d.getTime() + 1000L);
    String updatedAt2 = sdf.format(d);

    client = client.withFilter(getTestFilter(serviceFilterContainer, false,
            "[{\"id\":\"abc\",\"String\":\"Hey\",\"__updatedAt\":\"" + updatedAt1 + "\"},"
                    + "{\"id\":\"def\",\"String\":\"World\",\"__updatedAt\":\"" + updatedAt1 + "\"}]",
            "[{\"id\":\"abc\",\"String\":\"Hey\",\"__updatedAt\":\"" + updatedAt1 + "\"},"
                    + "{\"id\":\"def\",\"String\":\"World\",\"__updatedAt\":\"" + updatedAt1 + "\"}]",
            "[{\"id\":\"abc\",\"String\":\"Hey\",\"__updatedAt\":\"" + updatedAt2 + "\"},"
                    + "{\"id\":\"def\",\"String\":\"World\",\"__updatedAt\":\"" + updatedAt2 + "\"}]"));

    client.getSyncContext().initialize(store, new SimpleSyncHandler()).get();

    MobileServiceSyncTable<StringIdType> table = client.getSyncTable(StringIdType.class);

    Query query = QueryOperations.field("String").eq("Hey");

    table.pull(query, queryKey).get();//from  w  w w.  j  a v  a2 s  . c  o m

    // Skip added
    assertEquals(serviceFilterContainer.Requests.get(2).Url, EncodingUtilities.percentEncodeSpaces(
            "http://myapp.com/tables/stringidtype?$filter=String%20eq%20('Hey')%20and%20(__updatedAt%20ge%20(datetimeoffset'"
                    + updatedAt1 + "'))" + "&$top=50&$skip=2&"
                    + "$orderby=__updatedAt%20asc&__includeDeleted=true&__systemproperties=__updatedAt,__version,__deleted"));
    // Skip removed
    assertEquals(serviceFilterContainer.Requests.get(3).Url, EncodingUtilities.percentEncodeSpaces(
            "http://myapp.com/tables/stringidtype?$filter=String%20eq%20('Hey')%20and%20(__updatedAt%20ge%20(datetimeoffset'"
                    + updatedAt2 + "'))"
                    + "&$top=50&$orderby=__updatedAt%20asc&__includeDeleted=true&__systemproperties=__updatedAt,__version,__deleted"));
}

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

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

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

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

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

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

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

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

From source file:org.sofun.core.sport.SportsGraphLifeCycleManager.java

/**
 * Checks sports graph elements (Season, Stage, Round and Game) and
 * transitioning their status when needed.
 * //from   ww  w.  j  a  va2 s .c o m
 * @throws Exception
 */
// XXX DISABLED
// @Schedule(minute = "*/5", hour = "*", persistent = false)
public void check() throws Exception {

    if (!available) {
        return;
    } else {
        available = false;
    }

    try {
        final Calendar ref = getReferenceTime();
        log.debug("Reference time for end of predictions " + ref.getTime().toString());

        // Check scheduled games: This is important for this manager to
        // handle the `scheduled` to `on_going` transition (versus feed
        // provider component). This status conditions the ability for a
        // player to place a bet.
        for (TournamentGame game : sports.getTournamentGamesByStatus(TournamentGameStatus.SCHEDULED)) {
            final Date startDate = game.getStartDate();
            if (startDate != null) {
                final Calendar calStartDate = Calendar.getInstance();
                calStartDate.setTime(startDate);
                if (ref.compareTo(calStartDate) >= 0) {
                    log.info("End of predictions for game with uuid=" + game.getUUID() + " starting @ "
                            + calStartDate.getTime().toString());
                    game.setGameStatus(TournamentGameStatus.ON_GOING);
                }
            }
        }
        // Check for games that do not have any status. Let's not assume the
        // third party provider never does mistakes.
        for (TournamentGame game : sports.getTournamentGamesByStatus(null)) {
            final Date startDate = game.getStartDate();
            if (startDate != null) {
                final Calendar calStartDate = Calendar.getInstance();
                calStartDate.setTime(startDate);
                if (ref.compareTo(calStartDate) < 0) {
                    log.info("Marking game with uuid=" + game.getUUID()
                            + " as scheduled. Former status was unknown.");
                    game.setGameStatus(TournamentGameStatus.SCHEDULED);
                } else {
                    log.info("Marking game with uuid=" + game.getUUID()
                            + " as terminated. Former status was unknown.");
                    game.setGameStatus(TournamentGameStatus.TERMINATED);
                }
            }
        }
        // Subsequent transitions (closed, cancelled, postponed, etc.) will
        // he handled by the component implementing the third party
        // external feed provider (see sofun-platform-opta for instance)

        // Check rounds: `scheduled` -> `on going` -> `terminated`
        for (TournamentRound round : sports.getTournamentRoundsByStatus(TournamentRoundStatus.SCHEDULED)) {
            boolean terminated = true;
            boolean onGoing = false;
            if (round.getGames().size() > 0) {
                for (TournamentGame game : round.getGames()) {
                    final String gameStatus = game.getGameStatus();
                    if (!(TournamentGameStatus.TERMINATED.equals(gameStatus)
                            || TournamentGameStatus.CANCELLED.equals(gameStatus))) {
                        // One game is still scheduled. Nothing to do.
                        terminated = false;
                        break;
                    }
                    if (TournamentGameStatus.ON_GOING.equals(gameStatus)) {
                        // One game is ongoing and the game is marked as
                        // scheduled. Let's transition round
                        onGoing = true;
                        break;
                    }
                }
                if (terminated) {
                    // All games for this round are terminated. Marking
                    // round as terminated.
                    log.info("All games for round w/ UUID=" + String.valueOf(round.getUUID())
                            + " are marked as terminated. Marking round terminated");
                    round.setStatus(TournamentRoundStatus.TERMINATED);
                }
                if (onGoing) {
                    log.info("At least one game in round w/ UUID=" + String.valueOf(round.getUUID())
                            + " is marked as ON_GOING. Marking round as ON_GOING");
                    round.setStatus(TournamentRoundStatus.ON_GOING);
                }
            } else {
                // Handle case of a rounds with no games. (CY, F1, etc.)
                final Calendar startDate = Calendar.getInstance();
                startDate.setTime(round.getStartDate());
                if (ref.compareTo(startDate) >= 0
                        && TournamentRoundStatus.SCHEDULED.equals(round.getStatus())) {
                    log.info("Round w/ UUID=" + String.valueOf(round.getUUID()) + " is marked as ON_GOING.");
                    round.setStatus(TournamentRoundStatus.ON_GOING);
                }
            }
        }
        // Check rounds: unknown status
        for (TournamentRound round : sports.getTournamentRoundsByStatus(null)) {
            boolean onGoing = false;
            boolean scheduled = false;
            for (TournamentGame game : round.getGames()) {
                final String gameStatus = game.getGameStatus();
                if (TournamentGameStatus.ON_GOING.equals(gameStatus)) {
                    onGoing = true;
                    break;
                } else if (TournamentGameStatus.SCHEDULED.equals(gameStatus)
                        || TournamentGameStatus.POSTPONED.equals(gameStatus)) {
                    scheduled = true;
                }
            }
            if (onGoing) {
                if (!TournamentRoundStatus.ON_GOING.equals(round.getStatus())) {
                    log.info("At least one game in round w/ UUID=" + String.valueOf(round.getUUID())
                            + " is marked as ON_GOING. Marking round as "
                            + "ON_GOING. Former status was unknown");
                    round.setStatus(TournamentRoundStatus.ON_GOING);
                }
            } else if (scheduled) {
                if (!TournamentRoundStatus.SCHEDULED.equals(round.getStatus())) {
                    log.info("At least one game in round w/ UUID=" + String.valueOf(round.getUUID())
                            + " is marked as SCHEDULED. Marking round as "
                            + "SCHEDULED. Former status was unknown");
                    round.setStatus(TournamentRoundStatus.SCHEDULED);
                }
            } else {
                if (!TournamentRoundStatus.TERMINATED.equals(round.getStatus())) {
                    log.info("No game in round w/ UUID=" + String.valueOf(round.getUUID())
                            + " is marked as SCHEDULED, ON_GOING or " + "POSPONED Marking round as "
                            + "TERMINATED. Former status was unknown");
                    round.setStatus(TournamentRoundStatus.TERMINATED);
                }
            }

        }

        // Check stages: `scheduled` -> `on going` -> `terminated`
        List<TournamentStage> stages = sports.getTournamentStagesByStatus(TournamentStageStatus.SCHEDULED);
        stages.addAll(sports.getTournamentStagesByStatus(TournamentStageStatus.ON_GOING));
        for (TournamentStage stage : stages) {
            boolean terminated = true;
            boolean onGoing = false;
            for (TournamentRound round : stage.getRounds()) {
                final String roundStatus = round.getStatus();
                if (TournamentRoundStatus.ON_GOING.equals(roundStatus)) {
                    // One round is ongoing and the stage is marked as
                    // scheduled. Let's transition stage
                    terminated = false;
                    onGoing = true;
                    break;
                }
                if (!(TournamentRoundStatus.TERMINATED.equals(roundStatus)
                        || TournamentRoundStatus.CANCELLED.equals(roundStatus))) {
                    // One round is still scheduled. Nothing to do.
                    terminated = false;
                    break;
                }
            }
            if (terminated) {
                // All rounds for this stage are terminated. Marking stage
                // as terminated.
                if (!TournamentStageStatus.TERMINATED.equals(stage.getStatus())) {
                    log.info("All rounds for stage w/ UUID=" + String.valueOf(stage.getUUID())
                            + " are marked as terminated. Marking stage terminated");
                    stage.setStatus(TournamentStageStatus.TERMINATED);
                }
            }
            if (onGoing) {
                if (!TournamentStageStatus.ON_GOING.equals(stage.getStatus())) {
                    log.info("At least one round in stage w/ UUID=" + String.valueOf(stage.getUUID())
                            + " is marked as ON_GOING. Marking stage as ON_GOING");
                    stage.setStatus(TournamentStageStatus.ON_GOING);
                }
            }
        }
        // Check stages: unknown status
        for (TournamentStage stage : sports.getTournamentStagesByStatus(null)) {
            boolean onGoing = false;
            boolean scheduled = false;
            for (TournamentRound round : stage.getRounds()) {
                final String roundStatus = round.getStatus();
                if (TournamentRoundStatus.ON_GOING.equals(roundStatus)) {
                    onGoing = true;
                    break;
                } else if (TournamentRoundStatus.SCHEDULED.equals(roundStatus)
                        || TournamentRoundStatus.POSTPONED.equals(roundStatus)) {
                    scheduled = true;
                }
            }
            if (onGoing) {
                log.info("At least one round in stage w/ UUID=" + String.valueOf(stage.getUUID())
                        + " is marked as ON_GOING. Marking stage as " + "ON_GOING. Former status was unknown");
                stage.setStatus(TournamentStageStatus.ON_GOING);
            } else if (scheduled) {
                log.info("At least one round in stage w/ UUID=" + String.valueOf(stage.getUUID())
                        + " is marked as SCHEDULED. Marking stage as "
                        + "SCHEDULED. Former status was unknown");
                stage.setStatus(TournamentStageStatus.SCHEDULED);
            } else {
                log.info("No round in stage w/ UUID=" + String.valueOf(stage.getUUID())
                        + " is marked as SCHEDULED, ON_GOING or " + "POSPONED Marking stage as "
                        + "TERMINATED. Former status was unknown");
                stage.setStatus(TournamentStageStatus.TERMINATED);
            }

        }

        // Check seasons: `scheduled` -> `on going` -> `terminated`
        for (TournamentSeason season : sports.getTournamentSeasonsByStatus(TournamentSeasonStatus.SCHEDULED)) {
            boolean terminated = true;
            boolean onGoing = false;
            for (TournamentStage stage : season.getStages()) {
                final String stageStatus = stage.getStatus();
                if (TournamentStageStatus.ON_GOING.equals(stageStatus)) {
                    // One stage is ongoing and the season is marked as
                    // scheduled. Let's transition stage
                    onGoing = true;
                    terminated = false;
                    break;
                }
                if (!(TournamentStageStatus.TERMINATED.equals(stageStatus)
                        || TournamentStageStatus.CANCELLED.equals(stageStatus))) {
                    // One stage is still scheduled. Nothing to do.
                    terminated = false;
                    break;
                }
            }
            if (terminated) {
                // All stages for this stage are terminated. Marking season
                // as terminated.
                log.info("All stages for season w/ UUID=" + String.valueOf(season.getUUID())
                        + " are marked as terminated. Marking season terminated");
                season.setStatus(TournamentSeasonStatus.TERMINATED);
            }
            if (onGoing) {
                log.info("At least one stage in season w/ UUID=" + String.valueOf(season.getUUID())
                        + " is marked as ON_GOING. Marking season as ON_GOING");
                season.setStatus(TournamentSeasonStatus.ON_GOING);
            }
        }
        // Check seasons: unknown status
        for (TournamentSeason season : sports.getTournamentSeasonsByStatus(null)) {
            boolean onGoing = false;
            boolean scheduled = false;
            for (TournamentStage stage : season.getStages()) {
                final String stageStatus = stage.getStatus();
                if (TournamentStageStatus.ON_GOING.equals(stageStatus)) {
                    onGoing = true;
                    break;
                } else if (TournamentStageStatus.SCHEDULED.equals(stageStatus)
                        || TournamentStageStatus.POSTPONED.equals(stageStatus)) {
                    scheduled = true;
                }
            }
            if (onGoing) {
                log.info("At least one stage in season w/ UUID=" + String.valueOf(season.getUUID())
                        + " is marked as ON_GOING. Marking season as " + "ON_GOING. Former status was unknown");
                season.setStatus(TournamentSeasonStatus.ON_GOING);
            } else if (scheduled) {
                log.info("At least one stage in season w/ UUID=" + String.valueOf(season.getUUID())
                        + " is marked as SCHEDULED. Marking season as "
                        + "SCHEDULED. Former status was unknown");
                season.setStatus(TournamentSeasonStatus.SCHEDULED);
            } else {
                log.info("No stage in season w/ UUID=" + String.valueOf(season.getUUID())
                        + " is marked as SCHEDULED, ON_GOING or " + "POSPONED Marking season as "
                        + "TERMINATED. Former status was unknown");
                season.setStatus(TournamentSeasonStatus.TERMINATED);
            }

        }
    } finally {
        available = true;
    }

}

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

private Document createAnwesenheit(Klasse kl, String kopf, Date parsedFrom, Date parsedTo, OutputStream out,
        int filter1Id, int filter2Id) throws ParseException, IOException, DocumentException {
    Document document = new Document();
    /* Basic PDF Creation inside servlet */
    PdfWriter writer = PdfWriter.getInstance(document, out);
    StringBuilder htmlString = new StringBuilder();
    htmlString.append(kopf);/*from   w  ww .  j  ava 2  s  .  c  o m*/
    /* Anwesenheit einfgen */
    TypedQuery<AnwesenheitEintrag> query = em.createNamedQuery("findAnwesenheitbyKlasse",
            AnwesenheitEintrag.class);
    query.setParameter("paramKName", kl.getKNAME());
    query.setParameter("paramFromDate", new java.sql.Date(parsedFrom.getTime()));
    query.setParameter("paramToDate", new java.sql.Date(parsedTo.getTime()));

    Log.d("setze From auf " + new java.sql.Date(parsedFrom.getTime()));
    List<AnwesenheitObjekt> anwesenheit = getData(query);

    /**
     * Termindaten holen
     */
    Termine t1 = null;
    Termine t2 = null;
    if (filter1Id != -1) {
        t1 = em.find(Termine.class, filter1Id);

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

    Log.d("Result List:" + anwesenheit);
    GregorianCalendar c = (GregorianCalendar) GregorianCalendar.getInstance();
    c.setTime(parsedFrom);

    String tagZeile = "";
    document.open();
    Query q = em.createNamedQuery("findSchuelerEinerBenanntenKlasse");
    q.setParameter("paramNameKlasse", kl.getKNAME());
    List<Schueler> schueler = q.getResultList();
    Date current = new Date(parsedFrom.getTime());
    Log.d("Current=" + current + " TO=" + parsedTo + " From=" + parsedFrom + " Termine=" + termine.size());
    int spalte = 0;

    for (spalte = 0; spalte < termine.size(); spalte++) {
        tagZeile += "<table  align='center' width='100%' style=\"border: 2px solid black; border-collapse: collapse;\">\n";
        tagZeile += ("<tr >\n");
        tagZeile += ("<td width='25%' style=\"font-size: 14;border: 1px solid black;\"><b>Name</b></td>\n");
        // Zeile f.  Tage (Headline)
        Log.d("Spalte ist nun " + spalte);
        int i = 0;
        for (i = 0; i < 7 && spalte + i < termine.size(); i++) {
            current = new Date(termine.get(spalte + i).getDate().getTime());
            c.setTime(current);
            if (c.get(GregorianCalendar.DAY_OF_WEEK) == 1 || c.get(GregorianCalendar.DAY_OF_WEEK) == 7) {
                tagZeile += ("<td align=\"center\" style=\"padding:5px; background-color: #cccccc; font-size: 12;border: 1px solid black;\">"
                        + DatumUtil.getWochentag(c.get(GregorianCalendar.DAY_OF_WEEK)) + "<br></br>"
                        + c.get(GregorianCalendar.DATE) + "." + (c.get(GregorianCalendar.MONTH) + 1) + "."
                        + c.get(GregorianCalendar.YEAR) + "</td>\n");
            } else {
                tagZeile += ("<td align=\"center\" style=\"padding: 5px; font-size: 12;border: 1px solid black;\">"
                        + DatumUtil.getWochentag(c.get(GregorianCalendar.DAY_OF_WEEK)) + "<br></br>"
                        + c.get(GregorianCalendar.DATE) + "." + (c.get(GregorianCalendar.MONTH) + 1) + "."
                        + c.get(GregorianCalendar.YEAR) + "</td>\n");
            }
            Log.d("Spalte " + (i + spalte) + " Datum=" + current);
        }
        Log.d("Head aufgebaut");
        tagZeile += "</tr>\n";

        // Zeile pro Name
        for (Schueler s : schueler) {
            tagZeile += "<tr>\n";
            tagZeile += ("<td width='20%' style=\"padding: 5px;font-size: 12;border: 1px solid black;\"><b>"
                    + s.getVNAME() + " " + s.getNNAME() + "</b></td>\n");
            // Zeile f.  Tage
            //Log.d("Zeile f. Schler " + s.getNNAME());
            for (i = 0; i < 7 && spalte + i < termine.size(); i++) {
                current = new Date(termine.get(spalte + i).getDate().getTime());
                c.setTime(current);
                if (c.get(GregorianCalendar.DAY_OF_WEEK) == 1 || c.get(GregorianCalendar.DAY_OF_WEEK) == 7) {
                    tagZeile += ("<td style=\"background-color:#cccccc;font-size: 11;border: 1px solid black;\">"
                            + findVermerk(s.getId(), current, anwesenheit) + "</td>\n");
                } else {
                    tagZeile += ("<td style=\"font-size: 11;border: 1px solid black;\">"
                            + findVermerk(s.getId(), current, anwesenheit) + "</td>\n");
                }
                Log.d("Zeile f. Schler " + s.getNNAME() + " Datum " + current);
            }
            tagZeile += "</tr>\n";
        }
        Log.d("Rumpf aufgebaut");

        spalte = spalte + i - 1;

        // neue Seite bei 7 Terminen
        if (i == 7) {
            tagZeile += "</table>\n";
            htmlString.append(tagZeile);
            InputStream is = new ByteArrayInputStream(htmlString.toString().getBytes());
            // Bild einfgen
            String url = "http://www.mmbbs.de/fileadmin/template/mmbbs/gfx/mmbbs_logo_druck.gif";
            Image image = Image.getInstance(url);
            image.setAbsolutePosition(45f, 720f);
            image.scalePercent(50f);
            document.add(image);
            XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
            document.newPage();
            Log.d("neue Seite");
            htmlString = new StringBuilder();
            tagZeile = "";
            htmlString.append(kopf);
        }
        Log.d("SPalte ist " + spalte + " Termine=" + termine.size());

    }
    Log.d("Ende der ForSchleife spalte=" + spalte);
    // den Rest der Seite noch drucken
    if (spalte % 7 != 0) {
        tagZeile += "</table>\n";
        htmlString.append(tagZeile);
        Log.d("Rest Seite erzeugen");
        //Log.d("html String =" + htmlString.toString());
        //document.add(new Paragraph("Tutorial to Generate PDF using Servlet"));

        InputStream is = new ByteArrayInputStream(htmlString.toString().getBytes());
        // Bild einfgen
        String url = "http://www.mmbbs.de/fileadmin/template/mmbbs/gfx/mmbbs_logo_druck.gif";
        Image image = Image.getInstance(url);
        image.setAbsolutePosition(45f, 720f);
        image.scalePercent(50f);
        document.add(image);
        Log.d("writer=" + writer + " document=" + document + " is=" + is);
        XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);

    }

    document.close();
    return document;
}