Example usage for java.util GregorianCalendar setTime

List of usage examples for java.util GregorianCalendar setTime

Introduction

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

Prototype

public final void setTime(Date date) 

Source Link

Document

Sets this Calendar's time with the given Date.

Usage

From source file:org.tolven.gen.model.RepeatScenario.java

/**
 * To apply this scenario, we will modify the start time of the scenario to repeat to
 * be the selected event time. For example, if the repeat interval is one year (in milliseconds), 
 * and apply is called with a start time around 1992, then the child scenario is called
 * with a start time of 1977, 1978, to the end-time (present day or death being most common
 * for chronic diseases or the duration of the disease for acute diseases).
 * Since most repeat scenarios represent followup activity, the start date is often offset 
 * by some interval. Thus, with a startOffset of 12 (months), and the 
 * startDate were to be 1976, then the first "repeat" will be around 1977. 
 */// w  ww  . j av a 2 s .com
public boolean apply(GenMedical patient, Date startTime, Date endTime, RandomData rng) {
    GregorianCalendar clock = new GregorianCalendar();
    clock.setTime(startTime);
    boolean rslt = false;
    int count = -startOffset;
    //      TolvenLogger.info( getTitle() + " of " + getScenarioToRepeat().getTitle() + " Ranging from " + clock.getTime() + " to " + endTime, RepeatScenario.class); 
    while (true) {
        if (count++ >= MAX_REPEAT)
            throw new IllegalArgumentException("Maximum repeat for scenario " + getTitle());
        if (count > maxCount)
            break;
        // Now pick a random time around that clock setting unless this is the first instance or there is no deviation
        Date instanceTime;
        if (getDeviation() == 0.0 || count <= 0) {
            instanceTime = new Date(clock.getTimeInMillis());
        } else {
            instanceTime = new Date(((long) rng.nextGaussian(clock.getTimeInMillis(), getDeviationMs())));
        }
        // Needs to be before the end time, otherwise, we're done.
        if (instanceTime.after(endTime))
            break;
        // Now apply the instance (if we're past the startOffset)
        if (count > 0) {
            getScenarioToRepeat().apply(patient, instanceTime, endTime, rng);
        }
        // Reset the clock if requested
        if (resetClock)
            clock.setTime(instanceTime);
        // Advance the clock with no randomness
        clock.add(intervalType, intervalValue);
        rslt = true;
    }
    // If there's a future count, then we keep going by calling the futureScenario
    // Note: Logic is similar but not identical to above.
    for (int x = 0; x < getFutureCount(); x++) {
        Date instanceTime;
        if (getDeviation() == 0.0) {
            instanceTime = new Date(clock.getTimeInMillis());
        } else {
            instanceTime = new Date(((long) rng.nextGaussian(clock.getTimeInMillis(), getDeviationMs())));
        }
        // 
        // In the future, start and end time are the same.
        getFutureScenario().apply(patient, instanceTime, instanceTime, rng);
        // Reset the clock if requested
        if (resetClock)
            clock.setTime(instanceTime);
        // Advance the clock with no randomness
        clock.add(intervalType, intervalValue);
    }
    return rslt;
}

From source file:uk.nhs.cfh.dsp.srth.demographics.person.utils.PatientUtilsServiceImpl.java

public Calendar getDateRelativeToPatientAge(Patient p, int ageYears, int ageMonths, int ageDays) {

    GregorianCalendar gc = new GregorianCalendar();
    // get dob of patient
    gc.setTime(p.getDob().getTime());
    // forward time using given parameters
    gc.add(Calendar.YEAR, ageYears);
    gc.add(Calendar.MONTH, ageMonths);
    gc.add(Calendar.DATE, ageDays);

    return gc;//  w  w  w . ja  v a  2 s.c o m
}

From source file:org.callimachusproject.sql.SqlTupleResult.java

private Value value(int col) throws SQLException {
    int type = md.getColumnType(col);
    String str = rs.getString(col);
    if (str == null)
        return null;
    switch (type) {
    case java.sql.Types.NULL:
        return null;
    case java.sql.Types.DATALINK:
        return vf.createURI(str);
    case java.sql.Types.BINARY:
    case java.sql.Types.VARBINARY:
    case java.sql.Types.BIT:
    case java.sql.Types.BLOB:
    case java.sql.Types.LONGVARBINARY:
    case java.sql.Types.JAVA_OBJECT:
        return vf.createLiteral(Hex.encodeHexString(rs.getBytes(col)), XMLSchema.HEXBINARY);
    case java.sql.Types.DECIMAL:
    case java.sql.Types.NUMERIC:
        return vf.createLiteral(str, XMLSchema.DECIMAL);
    case java.sql.Types.TINYINT:
    case java.sql.Types.SMALLINT:
    case java.sql.Types.INTEGER:
    case java.sql.Types.BIGINT:
        return vf.createLiteral(str, XMLSchema.INTEGER);
    case java.sql.Types.DOUBLE:
    case java.sql.Types.FLOAT:
    case java.sql.Types.REAL:
        return vf.createLiteral(str, XMLSchema.DOUBLE);
    case java.sql.Types.BOOLEAN:
        return vf.createLiteral(rs.getBoolean(col));
    case java.sql.Types.DATE:
        GregorianCalendar date = new GregorianCalendar();
        date.setTime(rs.getDate(col));
        date.clear(Calendar.AM_PM);
        date.clear(Calendar.HOUR);
        date.clear(Calendar.HOUR_OF_DAY);
        date.clear(Calendar.MINUTE);
        date.clear(Calendar.SECOND);
        date.clear(Calendar.MILLISECOND);
        return vf.createLiteral(df.newXMLGregorianCalendar(date));
    case java.sql.Types.TIME:
        GregorianCalendar time = new GregorianCalendar();
        time.setTime(rs.getTime(col));// w w  w. j  a va2s.  com
        time.clear(Calendar.ERA);
        time.clear(Calendar.YEAR);
        time.clear(Calendar.MONTH);
        time.clear(Calendar.WEEK_OF_YEAR);
        time.clear(Calendar.WEEK_OF_MONTH);
        time.clear(Calendar.DATE);
        time.clear(Calendar.DAY_OF_MONTH);
        time.clear(Calendar.DAY_OF_YEAR);
        time.clear(Calendar.DAY_OF_WEEK);
        time.clear(Calendar.DAY_OF_WEEK_IN_MONTH);
        return vf.createLiteral(df.newXMLGregorianCalendar(time));
    case java.sql.Types.TIMESTAMP:
        return vf.createLiteral(rs.getTimestamp(col));
    case java.sql.Types.SQLXML:
        return vf.createLiteral(str, RDF.XMLLITERAL);
    case java.sql.Types.ARRAY:
    case java.sql.Types.CHAR:
    case java.sql.Types.CLOB:
    case java.sql.Types.DISTINCT:
    case java.sql.Types.LONGNVARCHAR:
    case java.sql.Types.NCHAR:
    case java.sql.Types.NCLOB:
    case java.sql.Types.NVARCHAR:
    case java.sql.Types.OTHER:
    case java.sql.Types.REF:
    case java.sql.Types.ROWID:
    case java.sql.Types.STRUCT:
    case java.sql.Types.VARCHAR:
    default:
        return vf.createLiteral(str);
    }
}

From source file:org.squale.welcom.outils.DateUtil.java

/**
 * @param beginDate date de dbut de la priode en Date
 * @param endDate date de fin de la priode en Date
 * @param weekend true pour que les jours fris tombant un week end soient comtabilis, false sinon.
 * @return retourne le nombre de jours fris dans la priode.
 *///from w  ww .  j a  v  a2 s.  com
public static int getNbPublicHolliday(final Date beginDate, final Date endDate, final boolean weekend) {
    if ((beginDate == null) || (endDate == null)) {
        return 0;
    }
    final GregorianCalendar gc = new GregorianCalendar();
    // recupere l'anne de debut
    int by = getYearOfDate(gc, beginDate);

    // Recupere l'anne de fin
    int ey = getYearOfDate(gc, endDate);

    // Recupere les jours de vacance des 2 annes
    ArrayList ph = getPublicHolliday(by, ey);

    int nbph = 0;

    for (final Iterator iter = ph.iterator(); iter.hasNext();) {
        final Date d = (Date) iter.next();
        gc.setTime(d);

        // Si les WEEK-END sont compatbili , les ajouter au compteur
        if (weekend) {
            if (isBetween(d, beginDate, endDate)) {
                nbph++;
            }
        } else {
            // Verifie que ce n'est pas un Samedi ou un dimance pour ompatibilit
            if ((gc.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY)
                    && (gc.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY)) {
                if (isBetween(d, beginDate, endDate)) {
                    nbph++;
                }
            }
        }
    }

    return nbph;
}

From source file:edu.umm.radonc.ca_dash.controllers.D3PieChartController.java

public void onSelectTimePeriod() {
    endDate = new Date();
    GregorianCalendar gc = new GregorianCalendar();
    gc.setTime(endDate);

    switch (interval) {
    case "1wk":
        gc.add(Calendar.DATE, -7);
        startDate = gc.getTime();//from ww w.ja v a 2  s. com
        break;
    case "1m":
        gc.add(Calendar.MONTH, -1);
        startDate = gc.getTime();
        break;
    case "3m":
        gc.add(Calendar.MONTH, -3);
        startDate = gc.getTime();
        break;
    case "6m":
        gc.add(Calendar.MONTH, -6);
        startDate = gc.getTime();
        break;
    case "1y":
        gc.add(Calendar.YEAR, -1);
        startDate = gc.getTime();
        break;
    case "2y":
        gc.add(Calendar.YEAR, -2);
        startDate = gc.getTime();
        break;
    case "3y":
        gc.add(Calendar.YEAR, -3);
        startDate = gc.getTime();
        break;
    case "Q1":
        gc.setTime(FiscalDate.getQuarter(1));
        startDate = gc.getTime();
        gc.add(Calendar.MONTH, 3);
        endDate = gc.getTime();
        break;
    case "Q2":
        gc.setTime(FiscalDate.getQuarter(2));
        startDate = gc.getTime();
        gc.add(Calendar.MONTH, 3);
        endDate = gc.getTime();
        break;
    case "Q3":
        gc.setTime(FiscalDate.getQuarter(3));
        startDate = gc.getTime();
        gc.add(Calendar.MONTH, 3);
        endDate = gc.getTime();
        break;
    case "Q4":
        gc.setTime(FiscalDate.getQuarter(4));
        startDate = gc.getTime();
        gc.add(Calendar.MONTH, 3);
        endDate = gc.getTime();
        break;
    }
}

From source file:be.fedict.eidviewer.lib.file.Version4XMLFileIdentity.java

public void toIdentity(Identity eidIdentity) throws ParseException {
    DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
    eidIdentity.nationalNumber = getNationalNumber();

    GregorianCalendar birthDateCalendar = new GregorianCalendar();
    birthDateCalendar.setTime(dateFormat.parse(getDateOfBirth()));
    eidIdentity.dateOfBirth = birthDateCalendar;
    eidIdentity.gender = getGender().equals("male") ? Gender.MALE : Gender.FEMALE;

    if (getNobleCondition() != null)
        eidIdentity.nobleCondition = getNobleCondition();

    if (getSpecialStatus() != null)
        eidIdentity.specialStatus = SpecialStatus.valueOf(getSpecialStatus());
    else/*from   ww w . jav a  2  s.  c  o  m*/
        eidIdentity.specialStatus = SpecialStatus.NO_STATUS;

    if (getDuplicate() != null)
        eidIdentity.duplicate = getDuplicate();

    eidIdentity.name = getName();
    eidIdentity.firstName = getFirstName();
    eidIdentity.middleName = getMiddleNames();
    eidIdentity.nationality = getNationality();
    eidIdentity.placeOfBirth = getPlaceOfBirth();
}

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

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

From source file:ejava.projects.edmv.bl.DataGen.java

protected Person createXMLPerson(DMVPerson person) {
    Person xmlPerson = new Person();
    PersonNameType name = new PersonNameType();
    name.setPersonGivenName(new PersonNameTextType());
    name.setPersonMiddleName(new PersonNameTextType());
    name.setPersonSurName(new PersonNameTextType());
    name.setPersonSuffixName(new TextType());
    xmlPerson.setPersonName(name);/*from  w  ww  .j a  v  a2  s.co  m*/
    xmlPerson.setPersonBirthDate(new Date());

    xmlPerson.setSourceIDText("" + person.getId());
    xmlPerson.setId("p" + ++id);
    name.getPersonGivenName().setValue(person.getGivenName());
    name.getPersonMiddleName().setValue(person.getMiddleName());
    name.getPersonSurName().setValue(person.getSurName());
    name.getPersonSuffixName().setValue(person.getSuffixName());

    java.util.Date dob = person.getPhysicalDetails().getDob();
    if (dob != null) {
        GregorianCalendar cal = new GregorianCalendar();
        cal.setTime(dob);
        XMLGregorianCalendar xDate = dtf.newXMLGregorianCalendar();
        xDate.setYear(cal.get(GregorianCalendar.YEAR));
        xDate.setMonth(cal.get(GregorianCalendar.MONTH) + 1);
        xDate.setDay(cal.get(GregorianCalendar.DAY_OF_MONTH));
        xmlPerson.getPersonBirthDate().setValue(xDate);
    }

    xmlPerson.setPersonPhysicalDetails(createXMLPhysicalDetails(person.getPhysicalDetails()));

    for (DMVResidence residence : person.getResidences()) {
        ResidenceType xmlResidence = createXMLResidence(residence);
        xmlPerson.getResidence().add(xmlResidence);
    }
    return xmlPerson;
}

From source file:Index.RegisterUserServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w w w.j av  a 2s  .co m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    PrintWriter out = response.getWriter();

    try {
        String errorMessage;

        if (request.getParameter("user") != null && request.getParameter("password") != null
                && request.getParameter("email") != null && request.getParameter("passwordConfirmation") != null
                && request.getParameter("name") != null && request.getParameter("address") != null
                && request.getParameter("lastName") != null && request.getParameter("dateBorn") != null) {

            String user = request.getParameter("user");
            String password = request.getParameter("password");
            String passwordConfirmation = request.getParameter("passwordConfirmation");
            String email = request.getParameter("email");
            String name = request.getParameter("name");
            String address = request.getParameter("address");
            String lastName = request.getParameter("lastName");
            String dateBorn = request.getParameter("dateBorn");

            if (user.equalsIgnoreCase("") || password.equalsIgnoreCase("")
                    || passwordConfirmation.equalsIgnoreCase("") || email.equalsIgnoreCase("")
                    || name.equalsIgnoreCase("")) {

                errorMessage = "Ingrese todos los datos.";
                request.setAttribute("error", errorMessage);
                request.setAttribute("funcionalidad", "Registro");

                request.getRequestDispatcher("/Login.jsp").forward(request, response);
            } else {
                if (password.equals(passwordConfirmation)) {
                    QuickOrderWebService webService = new QuickOrderWebService();
                    ControllerInterface port = webService.getQuickOrderWebServicePort();
                    webservice.Cliente listCli = port.infoCliente(user);

                    if (listCli != null && listCli.getApellido() != null) {

                        errorMessage = "Ya existe un usuario con ese nickname";
                        request.setAttribute("error", errorMessage);
                        request.setAttribute("funcionalidad", "Registro");
                        request.getRequestDispatcher("/Login.jsp").forward(request, response);
                    } else {
                        webservice.Cliente usr = new webservice.Cliente();
                        usr.setNickname(user);
                        usr.setNombre(name);
                        usr.setEmail(email);
                        usr.setDireccion(address);
                        usr.setImagen(user + ".jpg");
                        usr.setApellido(lastName);

                        //PORCEDIMIENTO PARA ENCRIPTAR LA CLAVE INGRESADA CUANDO INICIA SESIN UN USUARIO.
                        String encriptMD5 = DigestUtils.md5Hex(password);
                        password = "md5:" + encriptMD5;

                        usr.setPassword(password);
                        Date dt;
                        try {
                            dt = new Date(dateBorn);
                        } catch (Exception ex) {
                            dt = Date.from(Instant.now());
                        }

                        GregorianCalendar c = new GregorianCalendar();
                        c.setTime(dt);
                        XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
                        usr.setFechaNac(date2);

                        String result = port.registrarCliente(usr);

                        if (result.equals("")) {
                            request.setAttribute("error", null);
                            request.setAttribute("funcionalidad", "Imagen");
                            request.getSession().setAttribute("userName", user);
                        } else {
                            request.setAttribute("error", "Surgio un error al registrar el cliente");
                            request.setAttribute("funcionalidad", "Registro");
                        }
                        request.getRequestDispatcher("/Login.jsp").forward(request, response);
                    }
                } else {
                    errorMessage = "Las contraseas no cohinciden";
                    request.setAttribute("error", errorMessage);
                    request.setAttribute("funcionalidad", "Registro");
                    request.getRequestDispatcher("/Login.jsp").forward(request, response);
                }

            }
        } else {
            errorMessage = "Error al realizar el registro.";
            request.setAttribute("error", errorMessage);
            request.setAttribute("funcionalidad", "Registro");
            request.getRequestDispatcher("/Login.jsp").forward(request, response);
        }
    } catch (Exception ex) {
        out.print("Error en proceso de registro: " + ex.getMessage());
    } finally {
        out.close();
    }
}

From source file:ejava.projects.edmv.bl.DataGen.java

private VehicleRegistration createXMLRegistration(DMVVehicleRegistration reg, PersonsType people) {
    VehicleRegistration xmlReg = new VehicleRegistration();
    xmlReg.setVehicle(new VehicleType());
    xmlReg.getVehicle().setVehicleColorPrimaryCode(new VCOType());
    xmlReg.getVehicle().setVehicleID(new IDType());
    xmlReg.getVehicle().getVehicleID().setID(new TextType());
    xmlReg.getVehicle().setVehicleMakeCode(new VMAType());
    xmlReg.getVehicle().setVehicleModelCode(new VMOType());
    xmlReg.getVehicle().setVehicleModelYearDate(new GYear());
    xmlReg.getVehicle().getVehicleModelYearDate().setValue(dtf.newXMLGregorianCalendar());
    xmlReg.setVehicleLicensePlateID(new IDType());
    xmlReg.getVehicleLicensePlateID().setID(new TextType());
    xmlReg.setVehicleRegistrationDecal(new DecalType());
    xmlReg.getVehicleRegistrationDecal().setDecalMonthDate(new GMonth());
    xmlReg.getVehicleRegistrationDecal().getDecalMonthDate().setValue(dtf.newXMLGregorianCalendar());
    xmlReg.getVehicleRegistrationDecal().setDecalYearDate(new GYear());
    xmlReg.getVehicleRegistrationDecal().getDecalYearDate().setValue(dtf.newXMLGregorianCalendar());

    xmlReg.setId("vr" + ++id);
    xmlReg.setSourceIDText("" + reg.getId());

    xmlReg.getVehicle().getVehicleColorPrimaryCode().setValue(reg.getColor());
    xmlReg.getVehicle().getVehicleID().getID().setValue(reg.getVin());
    xmlReg.getVehicle().getVehicleMakeCode().setValue(reg.getMake());
    xmlReg.getVehicle().getVehicleModelCode().setValue(reg.getModel());
    xmlReg.getVehicle().getVehicleModelYearDate().getValue().setYear(Integer.parseInt(reg.getYear()));

    xmlReg.getVehicleLicensePlateID().getID().setValue(reg.getTagNo());
    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(reg.getExpiration());
    xmlReg.getVehicleRegistrationDecal().getDecalMonthDate().getValue()
            .setMonth(cal.get(GregorianCalendar.MONTH) + 1);
    xmlReg.getVehicleRegistrationDecal().getDecalYearDate().getValue().setYear(cal.get(GregorianCalendar.YEAR));

    log.debug("vehicle has " + reg.getOwners().size() + " owners");
    for (DMVPerson o : reg.getOwners()) {
        for (Person p : people.getPerson()) {
            if (p.getSourceIDText().equals("" + o.getId())) {
                xmlReg.getVehicle().getPropertyOwnerPerson().add(new ReferenceType(p));
            }//from  ww  w. j  a  va2  s.c o  m
        }
    }
    return xmlReg;
}