Example usage for java.util Calendar setTimeInMillis

List of usage examples for java.util Calendar setTimeInMillis

Introduction

In this page you can find the example usage for java.util Calendar 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:com.eryansky.common.utils.DateUtil.java

/**
 * /*from  w  w w . j  a  va 2  s .  co m*/
 * ??? ? 2008-08-08 16:16:34
 */
public static String addHours(String startDate, int intHour) {
    try {
        DateFormat df = DateFormat.getDateTimeInstance();
        Date date = df.parse(startDate);
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        long longMills = cal.getTimeInMillis() + intHour * 60 * 60 * 1000;
        cal.setTimeInMillis(longMills);

        // 
        return df.format(cal.getTime());
    } catch (Exception Exp) {
        return null;
    }
}

From source file:com.eryansky.common.utils.DateUtil.java

/**
 * //  w  w w.  ja va 2 s .c o  m
 * ???? ? 2008-08-08 16:16:34
 */
public static String delHours(String startDate, int intHour) {
    try {
        DateFormat df = DateFormat.getDateTimeInstance();
        Date date = df.parse(startDate);
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        long longMills = cal.getTimeInMillis() - intHour * 60 * 60 * 1000;
        cal.setTimeInMillis(longMills);

        // 
        return df.format(cal.getTime());
    } catch (Exception Exp) {
        return null;
    }
}

From source file:com.hangum.tadpole.commons.admin.core.dialogs.users.ModifyUserDialog.java

/**
 *  ??  .//from  www  .jav  a  2s.c  o m
 */
private void initData() {

    textEmail.setText(userDAO.getEmail());
    textName.setText(userDAO.getName());
    textAllowIP.setText(userDAO.getAllow_ip());
    textCreateDate.setText(userDAO.getCreate_time());

    comboIsRegistDB.setText(userDAO.getIs_regist_db());

    comboIsSharedDB.setText(userDAO.getIs_shared_db());
    textIntLimtCnt.setText("" + userDAO.getLimit_add_db_cnt());
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(userDAO.getService_end().getTime());
    endDate.setDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH));
    endTime.setTime(cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND));

    comboApproval.setText(userDAO.getApproval_yn());
    comboUserConfirm.setText(userDAO.getIs_email_certification());
    comboDel.setText(userDAO.getDelYn());
}

From source file:fr.paris.lutece.plugins.workflow.modules.appointment.service.ICalService.java

/**
 * Send an appointment to a user by email.
 * @param strEmailAttendee Comma separated list of users that will attend
 *            the appointment/* w  ww  .  j ava  2s .  c  o  m*/
 * @param strEmailOptionnal Comma separated list of users that will be
 *            invited to the appointment, but who are not required.
 * @param strSubject The subject of the appointment.
 * @param strBodyContent The body content that describes the appointment
 * @param strLocation The location of the appointment
 * @param strSenderName The name of the sender
 * @param strSenderEmail The email of the sender
 * @param appointment The appointment
 * @param bCreate True to notify the creation of the appointment, false to
 *            notify its removal
 */
public void sendAppointment(String strEmailAttendee, String strEmailOptionnal, String strSubject,
        String strBodyContent, String strLocation, String strSenderName, String strSenderEmail,
        Appointment appointment, boolean bCreate) {

    AppointmentSlot slot = AppointmentSlotHome.findByPrimaryKey(appointment.getIdSlot());
    Calendar calendarStart = new GregorianCalendar(Locale.FRENCH);

    calendarStart.setTime(appointment.getDateAppointment());
    calendarStart.add(Calendar.HOUR, slot.getStartingHour());
    calendarStart.add(Calendar.MINUTE, slot.getStartingMinute());

    int nAppDurationMinutes = ((slot.getEndingHour() - slot.getStartingHour()) * 60)
            + (slot.getEndingMinute() - slot.getStartingMinute());
    int nDurationAppointmentHours = nAppDurationMinutes / 60;
    int nDurationAppointmentMinutes = nAppDurationMinutes % 60;

    int nDurationAppointmentDays = nDurationAppointmentHours / 24;
    nDurationAppointmentHours %= 24;

    //       Dur duration = new Dur( nDurationAppointmentDays, nDurationAppointmentHours, nDurationAppointmentMinutes, 0 );

    //        TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
    //        TimeZone timezone = registry.getTimeZone("Europe/Paris");

    DateTime beginningDateTime = new DateTime(calendarStart.getTimeInMillis());
    beginningDateTime.setTimeZone(getParisZone());

    Calendar endCal = new GregorianCalendar();
    endCal.setTimeInMillis(calendarStart.getTimeInMillis());
    endCal.add(Calendar.MINUTE, nAppDurationMinutes);

    DateTime endingDateTime = new DateTime(endCal.getTimeInMillis());
    endingDateTime.setTimeZone(getParisZone());

    VEvent event = new VEvent(beginningDateTime, endingDateTime,
            (strSubject != null) ? strSubject : StringUtils.EMPTY);

    calendarStart.add(Calendar.MINUTE, nAppDurationMinutes);

    //  event.getProperties(  ).add( new DtEnd( endingDateTime ) );

    try {
        event.getProperties()
                .add(new Uid(Appointment.APPOINTMENT_RESOURCE_TYPE + appointment.getIdAppointment()));

        String strEmailSeparator = AppPropertiesService.getProperty(PROPERTY_MAIL_LIST_SEPARATOR, ";");
        if (StringUtils.isNotEmpty(strEmailAttendee)) {
            StringTokenizer st = new StringTokenizer(strEmailAttendee, strEmailSeparator);

            while (st.hasMoreTokens()) {
                addAttendee(event, st.nextToken(), true);
            }
        }

        if (StringUtils.isNotEmpty(strEmailOptionnal)) {
            StringTokenizer st = new StringTokenizer(strEmailOptionnal, strEmailSeparator);

            while (st.hasMoreTokens()) {
                addAttendee(event, st.nextToken(), false);
            }
        }

        Organizer organizer = new Organizer(strSenderEmail);
        organizer.getParameters().add(new Cn(strSenderName));
        event.getProperties().add(organizer);
        event.getProperties().add(new Location(strLocation));
        event.getProperties().add(new Description(strBodyContent));
    } catch (URISyntaxException e) {
        AppLogService.error(e.getMessage(), e);
    }

    net.fortuna.ical4j.model.Calendar iCalendar = new net.fortuna.ical4j.model.Calendar();
    iCalendar.getProperties().add(bCreate ? Method.REQUEST : Method.CANCEL);
    iCalendar.getProperties().add(new ProdId(AppPropertiesService.getProperty(PROPERTY_ICAL_PRODID)));
    iCalendar.getProperties().add(Version.VERSION_2_0);
    iCalendar.getProperties().add(CalScale.GREGORIAN);

    iCalendar.getComponents().add(event);

    MailService.sendMailCalendar(strEmailAttendee, strEmailOptionnal, null, strSenderName, strSenderEmail,
            (strSubject != null) ? strSubject : StringUtils.EMPTY, strBodyContent, iCalendar.toString(),
            bCreate);
}

From source file:com.projity.contrib.calendar.ContribIntervals.java

void eliminateWeekdayDuplicates(boolean weekDays[]) {
    Calendar cal = calendarInstance();
    for (Iterator i = iterator(); i.hasNext();) { //a more optimized version can be found
        DateSpan interval = (DateSpan) i.next();
        cal.setTimeInMillis(interval.getStart());
        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK) - 1;

        // remove any days which correspond to a selected week day
        for (int d = 0; d < 7; d++) {
            if (weekDays[d] && d == dayOfWeek) {
                i.remove();/*  w  w w.j ava2s.  c  o m*/
            }
        }
    }
}

From source file:com.adito.tunnels.JDBCTunnelDatabase.java

Tunnel buildTunnel(ResultSet rs) throws Exception {
    Timestamp cd = rs.getTimestamp("date_created");
    Calendar c = Calendar.getInstance();
    c.setTimeInMillis(cd == null ? System.currentTimeMillis() : cd.getTime());
    Timestamp ad = rs.getTimestamp("date_amended");
    Calendar a = Calendar.getInstance();
    a.setTimeInMillis(ad == null ? System.currentTimeMillis() : ad.getTime());
    return new DefaultTunnel(rs.getInt("realm_id"), rs.getString("name"), rs.getString("description"),
            rs.getInt("tunnel_id"), rs.getInt("type"), rs.getBoolean("auto_start"), rs.getString("transport"),
            rs.getString("username"), rs.getInt("source_port"),
            new HostService(rs.getString("destination_host"), rs.getInt("destination_port")),
            rs.getString("source_interface"), c, a);
}

From source file:iphonestalker.util.FindMyIPhoneReader.java

public String connect(String username, String password) {

    numDevices = 0;//  w ww . j  a  va2s  .c  om

    // Setup HTTP parameters
    HttpParams params = new BasicHttpParams();
    params.setParameter("http.useragent", "Find iPhone/1.1 MeKit (iPhone: iPhone OS/4.2.1)");
    client = new DefaultHttpClient(params);

    // Construct the post
    post = new HttpPost("https://fmipmobile.me.com/fmipservice/device/" + username);
    post.addHeader("X-Client-Uuid", "0000000000000000000000000000000000000000");
    post.addHeader("X-Client-Name", "My iPhone");
    Header[] headers = { new BasicHeader("X-Apple-Find-Api-Ver", "2.0"),
            new BasicHeader("X-Apple-Authscheme", "UserIdGuest"),
            new BasicHeader("X-Apple-Realm-Support", "1.0"),
            new BasicHeader("Content-Type", "application/json; charset=utf-8"),
            new BasicHeader("Accept-Language", "en-us"), new BasicHeader("Pragma", "no-cache"),
            new BasicHeader("Connection", "keep-alive"), new BasicHeader("Authorization",
                    "Basic " + new String(Base64.encodeBase64((username + ":" + password).getBytes()))) };
    post.setHeaders(headers);

    HttpResponse response = null;
    try {
        // Execute
        response = client.execute(post);

        // We should get a redirect
        if (response.getStatusLine().getStatusCode() == 330) {
            String newHost = (((Header[]) response.getHeaders("X-Apple-MME-Host"))[0]).getValue();
            try {
                post.setURI(new URI("https://" + newHost + "/fmipservice/device/" + username + "/initClient"));
            } catch (URISyntaxException ex) {
                logger.log(Level.SEVERE, null, ex);
                return "Couldn't post URI: " + ex;
            }

            // Dump the data so we can execute a new post
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
            JSONObject object = (JSONObject) JSONValue.parse(reader);

            // This post should get us our data
            response = client.execute(post);
            reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));

            // Read the data
            object = (JSONObject) JSONValue.parse(reader);
            JSONArray array = ((JSONArray) object.get("content"));
            numDevices = array.size();

            // Setup the route data
            iPhoneRouteList = new ArrayList<IPhoneRoute>();

            for (int i = 0; i < numDevices; i++) {
                // Get the device data
                object = (JSONObject) array.get(i);
                IPhoneLocation iPhoneLocation = getLocation(object);

                // Add route data
                IPhoneRoute iPhoneRoute = new IPhoneRoute();
                String modelDisplayName = (String) object.get("modelDisplayName");
                String deviceModelName = (String) object.get("deviceModel");
                String name = (String) object.get("name");

                Calendar cal = Calendar.getInstance();
                cal.setTimeInMillis(System.currentTimeMillis());
                iPhoneRoute.name = "[FMI #" + (i + 1) + "]" + name + ":" + modelDisplayName + " "
                        + deviceModelName;
                iPhoneRoute.lastBackupDate = cal.getTime();
                iPhoneRoute.setFMI(true);

                if (iPhoneLocation != null) {
                    iPhoneRoute.addLocation(iPhoneLocation);
                }
                iPhoneRouteList.add(iPhoneRoute);
            }

        } else {
            logger.log(Level.WARNING, "Couldn\'t retrieve iPhone data: " + response.getStatusLine().toString());
            return "Couldn't retrieve iPhone data: " + response.getStatusLine().toString();
        }
    } catch (ClientProtocolException ex) {
        logger.log(Level.SEVERE, null, ex);
        return "Couldn't retrieve iPhone data: " + ex;
    } catch (IOException ex) {
        logger.log(Level.SEVERE, null, ex);
        return "Couldn't retrieve iPhone data: " + ex;
    }

    return null;
}

From source file:com.algomedica.service.LicenseManagerServiceImpl.java

private String getTime(long lsExipryDays) {

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Calendar c = Calendar.getInstance();
    c.setTimeInMillis(lsExipryDays); // Now use today date.
    return sdf.format(c.getTime());
}

From source file:com.qualogy.qafe.core.datastore.Data.java

protected String toLogString() {
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(lastTouched);
    StringBuilder builder = new StringBuilder(255);
    builder.append("Last touched > " + cal.getTime() + (!elements.isEmpty() ? "\n" : ""));

    DataToLogStringBuilder.build(elements, builder);
    return builder.toString();
}

From source file:com.evolveum.midpoint.web.security.MidPointAuthenticationProvider.java

private Authentication authenticateUserPassword(MidPointPrincipal principal, String password)
        throws BadCredentialsException {
    if (StringUtils.isBlank(password)) {
        throw new BadCredentialsException("web.security.provider.access.denied");
    }/*from   ww  w  . j a v  a  2s. c  om*/

    if (principal == null || principal.getUser() == null || principal.getUser().getCredentials() == null) {
        throw new BadCredentialsException("web.security.provider.invalid");
    }

    if (!principal.isEnabled()) {
        throw new BadCredentialsException("web.security.provider.disabled");
    }

    UserType userType = principal.getUser();
    CredentialsType credentials = userType.getCredentials();

    PasswordType passwordType = credentials.getPassword();
    int failedLogins = passwordType.getFailedLogins() != null ? passwordType.getFailedLogins() : 0;
    if (maxFailedLogins > 0 && failedLogins >= maxFailedLogins) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(MiscUtil.asDate(passwordType.getLastFailedLogin().getTimestamp()).getTime());
        calendar.add(Calendar.MINUTE, loginTimeout);
        long lockedTill = calendar.getTimeInMillis();

        if (lockedTill > System.currentTimeMillis()) {
            throw new BadCredentialsException("web.security.provider.locked");
        }
    }

    ProtectedStringType protectedString = passwordType.getValue();
    if (protectedString == null) {
        throw new BadCredentialsException("web.security.provider.password.bad");
    }

    if (StringUtils.isEmpty(password)) {
        throw new BadCredentialsException("web.security.provider.password.encoding");
    }

    Collection<Authorization> authorizations = principal.getAuthorities();
    if (authorizations == null || authorizations.isEmpty()) {
        throw new BadCredentialsException("web.security.provider.access.denied");
    }

    for (Authorization auth : authorizations) {
        if (auth.getAction() == null || auth.getAction().isEmpty()) {
            throw new BadCredentialsException("web.security.provider.access.denied");
        }
    }

    try {
        String decoded;
        if (protectedString.getEncryptedDataType() != null) {
            decoded = protector.decryptString(protectedString);
        } else {
            LOGGER.warn("Authenticating user based on clear value. Please check objects, "
                    + "this should not happen. Protected string should be encrypted.");
            decoded = protectedString.getClearValue();
        }
        if (password.equals(decoded)) {
            // Good password
            if (failedLogins > 0) {
                passwordType.setFailedLogins(0);
            }
            XMLGregorianCalendar systemTime = MiscUtil
                    .asXMLGregorianCalendar(new Date(System.currentTimeMillis()));
            LoginEventType event = new LoginEventType();
            event.setTimestamp(systemTime);
            event.setFrom(getRemoteHost());

            passwordType.setPreviousSuccessfulLogin(passwordType.getLastSuccessfulLogin());
            passwordType.setLastSuccessfulLogin(event);

            userProfileService.updateUser(principal);
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal,
                    password, principal.getAuthorities());
            return token;
        } else {
            // Bad password               
            passwordType.setFailedLogins(++failedLogins);
            XMLGregorianCalendar systemTime = MiscUtil
                    .asXMLGregorianCalendar(new Date(System.currentTimeMillis()));
            LoginEventType event = new LoginEventType();
            event.setTimestamp(systemTime);
            event.setFrom(getRemoteHost());
            passwordType.setLastFailedLogin(event);
            userProfileService.updateUser(principal);

            throw new BadCredentialsException("web.security.provider.invalid");
        }
    } catch (EncryptionException ex) {
        throw new AuthenticationServiceException("web.security.provider.unavailable", ex);
    }
}