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.versatus.jwebshield.securitylock.SecurityLock.java

public Date getTimeWhenUnlock() {
    Date res = null;/*w  w w  .  j  a  v  a2 s.c om*/
    Calendar cal = Calendar.getInstance();
    if (getLockTimestamp() != null) {
        long lockCreated = getLockTimestamp().getTime();

        long remTime = lockCreated + (SecurityCheckListener.getTimeToLock() * 60 * 1000);
        if (remTime > 0) {
            cal.setTimeInMillis(remTime);
            res = cal.getTime();
        }
    }
    return res;
}

From source file:com.taurus.compratae.appservice.impl.GeneracionArchivoConciliacionServiceImpl.java

@Override
public void generarArchivo(Transaccion transaccion) throws ErrorTAEException {
    //Primero se debe validar que exista archivo para ese da
    //transaccion = transaccionDbService.buscarPorId(19);/////////////////////esto es para pruebas
    Date fecha = transaccion.getFecha();

    SimpleDateFormat formatoDelTexto = new SimpleDateFormat("yyyy-MM-dd");
    String fechaFormtat = formatoDelTexto.format(fecha);

    Date fecha1 = null;/*www.  j  a v a 2  s.co m*/

    try {
        fecha1 = formatoDelTexto.parse(fechaFormtat);
    } catch (ParseException ex) {
        //throw new ErrorTAEException(ex.getMessage());
    }

    Calendar cal = new GregorianCalendar();
    cal.setTimeInMillis(fecha1.getTime());
    cal.add(Calendar.MINUTE, 1439);
    Date fecha2 = new java.sql.Date(cal.getTimeInMillis());
    Archivo archivo = archivoService.buscarEntreFechas(fecha1, fecha2);

    //Si no existe, crear tanto registro en bd como el archivo en directorio y abrir el archivo
    if (archivo == null) {
        archivo = generarNuevo(fecha);//guardar nuevo registro en bd
        String cabecera = generarCabecera(archivo);
        guardarArchivo(archivo, cabecera, false);
    }
    //Generar String que contendr lnea a escribir en el archivo
    String linea = generarLineaRegistro(transaccion, archivo);
    //Ya existe (o exista), abrir archivo y escribir lnea
    guardarArchivo(archivo, linea, true);
    //Actualizar registro de archivo, con numRegistos++ y archivo.montoTotal += transaccion.getMonto (hacerlo bien)
    int numRegistros = archivo.getNumregistros();
    numRegistros++;
    archivo.setNumregistros(numRegistros);
    int monto = transaccion.getIdMonto().getMonto();
    int total = archivo.getTotal();
    int totalActualizado = total + monto;
    archivo.setTotal(totalActualizado);
    archivoService.guardarNuevoArchivo(archivo);
    transaccion.setIdArchivo(archivo);
}

From source file:com.taurus.compratae.appservice.impl.GeneracionArchivoConciliacionServiceImpl.java

@Override
public Archivo generarFooter() {
    //obtener fecha actual
    Date fecha = new Date();

    SimpleDateFormat format = new SimpleDateFormat("HH");
    String horaS = format.format(fecha);
    int hora = Integer.valueOf(horaS);
    String fechaNombre;/*ww  w .ja va 2  s . com*/

    ////LA SIGUIENTE CONDICION DEPENDE DE LA HORA EN QUE SE CORRA EL JOB//
    if (hora >= 0 && hora <= 20) {
        //buscar el de ayer
        Calendar cal = new GregorianCalendar();
        cal.setTimeInMillis(fecha.getTime());
        cal.add(Calendar.DATE, -1);
        Date fecha2 = new java.sql.Date(cal.getTimeInMillis());
        format = new SimpleDateFormat("ddMMyyyy");
        fechaNombre = format.format(fecha2);
    } else {
        //buscar el de hoy
        format = new SimpleDateFormat("ddMMyyyy");
        fechaNombre = format.format(fecha);
    }
    //////////////Esto es de prueba, quitar!!!!!!//////////

    format = new SimpleDateFormat("ddMMyyyy");
    fechaNombre = format.format(fecha);

    /////////////////////////////////////////////////////////
    ParametroArchivo paramArchivoNombre = obtenerParametrosArchivo(PATH);
    StringBuilder sb = new StringBuilder(paramArchivoNombre.getValor());
    paramArchivoNombre = obtenerParametrosArchivo(NOMBRE_ARCHIVO);
    sb.append(paramArchivoNombre.getValor());
    String nombreArchivo = (sb.append(fechaNombre).append(".txt")).toString();
    Archivo archivo = archivoService.buscarPorNombre(nombreArchivo);
    if (archivo != null) {
        String footer = generarLineaFooter(archivo);
        guardarArchivo(archivo, footer, true);
    }
    return archivo;
}

From source file:fr.aliasource.webmail.server.proxy.client.http.AbstractMessageMethod.java

protected ClientMessage parseMessage(Calendar cal, Element me) {

    String subject = DOMUtils.getElementText(me, "subject");
    cal.setTimeInMillis(Long.parseLong(me.getAttribute("date")));
    Date d = cal.getTime();/*w ww.ja  va2s.  c  o  m*/
    String[][] sender = DOMUtils.getAttributes(me, "from", new String[] { "addr", "displayName" });
    EmailAddress from = new EmailAddress(sender[0][1], sender[0][0]);

    List<EmailAddress> to = new LinkedList<EmailAddress>();
    Element recip = DOMUtils.getUniqueElement(me, "to");
    loadRecipient(to, recip);

    List<EmailAddress> cc = new LinkedList<EmailAddress>();
    recip = DOMUtils.getUniqueElement(me, "cc");
    loadRecipient(cc, recip);

    List<EmailAddress> bcc = new LinkedList<EmailAddress>();
    recip = DOMUtils.getUniqueElement(me, "bcc");
    loadRecipient(bcc, recip);

    List<EmailAddress> dispositionNotification = new LinkedList<EmailAddress>();
    recip = DOMUtils.getUniqueElement(me, "disposition-notification");
    if (recip != null) {
        loadRecipient(dispositionNotification, recip);
    }

    Element attachements = DOMUtils.getUniqueElement(me, "attachements");

    String[][] aIds = DOMUtils.getAttributes(attachements, "a", new String[] { "id" });
    int aCount = aIds.length;
    String[] attachs = new String[aCount];
    for (int i = 0; i < aCount; i++) {
        attachs[i] = aIds[i][0];
    }
    Body body = parseBody(me);

    ClientMessage cm = new ClientMessage(from, to, subject, body, attachs, d, null, null);

    if (body.isEmpty()) {
        cm.setLoaded(false);
    }

    cm.setUid(new MessageId(Long.valueOf(me.getAttribute("uid"))));
    cm.setRead("true".equals(me.getAttribute("read")));
    cm.setStarred("true".equals(me.getAttribute("starred")));
    cm.setAnswered("true".equals(me.getAttribute("answered")));
    cm.setHighPriority("true".equals(me.getAttribute("hp")));
    cm.setCc(cc);
    cm.setBcc(bcc);
    cm.setDispositionNotification(dispositionNotification);

    return cm;
}

From source file:com.orange.oidc.tim.service.TokensKeys.java

Calendar fromStringToDate(String s) {
    if (s != null && s.length() > 0) {
        try {//  ww  w .  j a va2 s .  co  m
            long d = Long.parseLong(s);
            Calendar c = Calendar.getInstance();
            c.setTimeZone(TimeZone.getTimeZone("GMT"));
            c.setTimeInMillis(d * 1000);
            return c;

        } catch (Exception e) {
        }
    }
    return null;
}

From source file:net.sourceforge.msscodefactory.cfacc.v2_0.CFAccXMsgClient.CFAccXMsgClientSchema.java

public static Calendar convertTimestampString(String val) {
    if ((val == null) || (val.length() == 0)) {
        return (null);
    } else if (val.length() != 19) {
        throw CFLib.getDefaultExceptionFactory().newUsageException(CFAccXMsgClientSchema.class,
                "convertTimestampString",
                "Value must be in YYYY-MM-DD HH24:MI:SS format \"" + val + "\" is invalid");
    } else if (((val.charAt(0) >= '0') && (val.charAt(0) <= '9'))
            && ((val.charAt(1) >= '0') && (val.charAt(1) <= '9'))
            && ((val.charAt(2) >= '0') && (val.charAt(2) <= '9'))
            && ((val.charAt(3) >= '0') && (val.charAt(3) <= '9')) && (val.charAt(4) == '-')
            && ((val.charAt(5) >= '0') && (val.charAt(5) <= '1'))
            && ((val.charAt(6) >= '0') && (val.charAt(6) <= '9')) && (val.charAt(7) == '-')
            && ((val.charAt(8) >= '0') && (val.charAt(8) <= '3'))
            && ((val.charAt(9) >= '0') && (val.charAt(9) <= '9')) && (val.charAt(10) == ' ')
            && ((val.charAt(11) >= '0') && (val.charAt(11) <= '2'))
            && ((val.charAt(12) >= '0') && (val.charAt(12) <= '9')) && (val.charAt(13) == ':')
            && ((val.charAt(14) >= '0') && (val.charAt(14) <= '5'))
            && ((val.charAt(15) >= '0') && (val.charAt(15) <= '9')) && (val.charAt(16) == ':')
            && ((val.charAt(17) >= '0') && (val.charAt(17) <= '5'))
            && ((val.charAt(18) >= '0') && (val.charAt(18) <= '9'))) {
        /*//from  w  w  w  .j  a  v  a 2  s  . c  o  m
         *   NOTE:
         *      .Net uses substring( startcol, lengthOfSubstring )
         *      Java uses substring( startcol, endcol ) and does not
         *         include charAt( endcol );
         */
        int year = Integer.parseInt(val.substring(0, 4));
        int month = Integer.parseInt(val.substring(5, 7));
        int day = Integer.parseInt(val.substring(8, 10));
        int hour = Integer.parseInt(val.substring(11, 13));
        int minute = Integer.parseInt(val.substring(14, 16));
        int second = Integer.parseInt(val.substring(17, 19));
        Calendar retval = new GregorianCalendar(CFLibDbUtil.getDbServerTimeZone());
        retval.set(Calendar.YEAR, year);
        retval.set(Calendar.MONTH, month - 1);
        retval.set(Calendar.DAY_OF_MONTH, day);
        retval.set(Calendar.HOUR_OF_DAY, hour);
        retval.set(Calendar.MINUTE, minute);
        retval.set(Calendar.SECOND, second);
        Calendar local = new GregorianCalendar();
        local.setTimeInMillis(retval.getTimeInMillis());
        return (local);
    } else {
        throw CFLib.getDefaultExceptionFactory().newUsageException(CFAccXMsgClientSchema.class,
                "convertTimestampString",
                "Value must be in YYYY-MM-DD HH24:MI:SS format \"" + val + "\" is invalid");
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.RoomSiteViewerDispatchAction.java

public ActionForward roomViewer(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    User userView = getUserView(request);

    String roomName = request.getParameter("roomName");
    if (roomName == null) {
        roomName = (String) request.getAttribute("roomName");
    }/*from   www. j av a 2s  .  c om*/
    request.setAttribute("roomName", roomName);
    RoomKey roomKey = null;

    if (roomName != null) {
        roomKey = new RoomKey(roomName);

        ISiteComponent bodyComponent = new InfoSiteRoomTimeTable();
        DynaActionForm indexForm = (DynaActionForm) form;
        Integer indexWeek = (Integer) indexForm.get("indexWeek");
        // Integer executionPeriodID = (Integer)
        // indexForm.get("selectedExecutionPeriodID");
        String executionPeriodIDString = request.getParameter("selectedExecutionPeriodID");
        if (executionPeriodIDString == null) {
            executionPeriodIDString = (String) request.getAttribute("selectedExecutionPeriodID");
        }
        String executionPeriodID = (executionPeriodIDString != null) ? executionPeriodIDString : null;
        if (executionPeriodID == null) {
            try {
                // executionPeriodID = (Integer)
                // indexForm.get("selectedExecutionPeriodID");
                executionPeriodID = indexForm.get("selectedExecutionPeriodID").equals("") ? null
                        : (String) indexForm.get("selectedExecutionPeriodID");
            } catch (IllegalArgumentException ex) {
            }
        }
        Calendar today = new DateMidnight().toCalendar(null);
        ArrayList weeks = new ArrayList();

        InfoExecutionPeriod executionPeriod;
        if (executionPeriodID == null) {
            executionPeriod = ReadCurrentExecutionPeriod.run();
            executionPeriodID = executionPeriod.getExternalId();
            try {
                indexForm.set("selectedExecutionPeriodID", executionPeriod.getExternalId().toString());
            } catch (IllegalArgumentException ex) {
            }
        } else {
            executionPeriod = ReadExecutionPeriodByOID.run(executionPeriodID);
        }

        // weeks
        Calendar begin = Calendar.getInstance();
        begin.setTime(executionPeriod.getBeginDate());
        Calendar end = Calendar.getInstance();
        end.setTime(executionPeriod.getEndDate());
        ArrayList weeksLabelValueList = new ArrayList();
        begin.add(Calendar.DATE, Calendar.MONDAY - begin.get(Calendar.DAY_OF_WEEK));
        int i = 0;
        boolean selectedWeek = false;
        while (begin.before(end) || begin.before(Calendar.getInstance())) {
            Calendar day = Calendar.getInstance();
            day.setTimeInMillis(begin.getTimeInMillis());
            weeks.add(day);
            String beginWeekString = DateFormatUtils.format(begin.getTime(), "dd/MM/yyyy");
            begin.add(Calendar.DATE, 5);
            String endWeekString = DateFormatUtils.format(begin.getTime(), "dd/MM/yyyy");
            weeksLabelValueList.add(
                    new LabelValueBean(beginWeekString + " - " + endWeekString, new Integer(i).toString()));
            begin.add(Calendar.DATE, 2);
            if (!selectedWeek && indexWeek == null && Calendar.getInstance().before(begin)) {
                indexForm.set("indexWeek", new Integer(i));
                selectedWeek = true;
            }
            i++;
        }

        final Collection<ExecutionSemester> executionSemesters = rootDomainObject.getExecutionPeriodsSet();
        final List<LabelValueBean> executionPeriodLabelValueBeans = new ArrayList<LabelValueBean>();
        for (final ExecutionSemester ep : executionSemesters) {
            if (ep.getState().equals(PeriodState.OPEN) || ep.getState().equals(PeriodState.CURRENT)) {
                executionPeriodLabelValueBeans.add(new LabelValueBean(
                        ep.getName() + " " + ep.getExecutionYear().getYear(), ep.getExternalId().toString()));
            }
        }
        request.setAttribute(PresentationConstants.LABELLIST_EXECUTIONPERIOD, executionPeriodLabelValueBeans);

        request.setAttribute(PresentationConstants.LABELLIST_WEEKS, weeksLabelValueList);
        if (indexWeek != null) {
            final int xpto = indexWeek.intValue();
            if (xpto < weeks.size()) {
                today = (Calendar) weeks.get(xpto);
            } else {
                today = (Calendar) weeks.iterator().next();
                indexForm.set("indexWeek", new Integer(0));
            }
        }

        try {
            SiteView siteView = (SiteView) RoomSiteComponentServiceByExecutionPeriodID.run(bodyComponent,
                    roomKey, today, executionPeriodID);

            request.setAttribute("siteView", siteView);

        } catch (NonExistingServiceException e) {
            throw new NonExistingActionException(e);
        } catch (FenixServiceException e) {
            throw new FenixActionException(e);
        }
        return mapping.findForward("roomViewer");
    }
    throw new FenixActionException();

}

From source file:fr.syncarnet.tasks.Task.java

public void unJsonify(String json) {
    try {/*from ww  w .  j  av  a 2  s .  co  m*/
        JSONObject jsonTask = new JSONObject(json);
        this.description = jsonTask.getString("description");
        String project = jsonTask.getString("project");
        this.project = !project.equals("VAR_NULL") ? project : null;
        this.priority = Priority.valueOf(jsonTask.getString("priority"));
        this.uuid = UUID.fromString(jsonTask.getString("uuid"));
        Calendar due = null;
        long dueMillis = jsonTask.getLong("due");
        if (dueMillis != 0) {
            due = Calendar.getInstance();
            due.setTimeInMillis(dueMillis);
        }
        this.due = due;
        this.entry = jsonTask.getLong("entry");
        this.modified = jsonTask.getLong("modified");
    } catch (JSONException e) {
        Log.e(TAG, "Exception while unjsonifying");
    }
}

From source file:helper.lang.DateHelperTest.java

@Test
public void testMillisToNextHour() {
    long now = System.currentTimeMillis();
    long millis = DateHelper.millisToNextHour();
    Calendar cal = Calendar.getInstance();
    assertEquals(now, System.currentTimeMillis());// only valid test if time calls all happened w/in same millisecond
    cal.setTimeInMillis(now + millis);
    assertEquals(0, cal.get(Calendar.MINUTE));
    assertEquals(0, cal.get(Calendar.SECOND));
    assertEquals(0, cal.get(Calendar.MILLISECOND));
}

From source file:com.krayzk9s.imgurholo.ui.AccountFragment.java

public void onGetObject(Object data, String tag) {
    refreshedCount++;//from w w  w . j  a v  a2s .co  m
    if (refreshedCount == 5) {
        mPullToRefreshLayout.setRefreshComplete();
    }
    try {
        if (data == null) {
            return;
        }
        JSONObject jsonData;

        /*int duration = Toast.LENGTH_SHORT;
            Toast toast;
        MainActivity activity = (MainActivity) getActivity();
        toast = Toast.makeText(activity, "User not found", duration);
        toast.show();
        activity.getFragmentManager().popBackStack();*/

        if (tag.equals(ACCOUNTDATA)) {
            jsonData = ((JSONObject) data).getJSONObject("data");
            if (jsonData.has("error"))
                return;
            Calendar accountCreationDate = Calendar.getInstance();
            accountCreationDate.setTimeInMillis((long) jsonData.getInt("created") * 1000);
            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
            String accountcreated = sdf.format(accountCreationDate.getTime());
            created.setText(accountcreated);
            reputation.setText(Integer.toString(jsonData.getInt("reputation")));
            if (jsonData.getString("bio") != null && !jsonData.getString("bio").equals("null")
                    && !jsonData.getString("bio").equals(""))
                biography.setText(jsonData.getString("bio"));
            else
                biography.setText("No Biography");
        } else if (tag.equals(COUNTDATA)) {
            jsonData = ((JSONObject) data);
            if (jsonData.has("error"))
                return;
            if (jsonData.getInt("status") == 200)
                mMenuList[1] = mMenuList[1] + " (" + Integer.toString(jsonData.getInt("data")) + ")";
            else
                mMenuList[1] = mMenuList[1] + " (0)";
        } else if (tag.equals(ALBUMDATA)) {
            jsonData = ((JSONObject) data);
            if (jsonData.has("error"))
                return;
            if (jsonData.getInt("status") == 200)
                mMenuList[0] = mMenuList[0] + " (" + Integer.toString(jsonData.getJSONArray("data").length())
                        + ")";
            else
                mMenuList[0] = mMenuList[0] + " (0)";
        } else if (tag.equals(LIKEDATA)) {
            JSONArray jsonArray = ((JSONObject) data).getJSONArray("data");
            mMenuList[2] = mMenuList[2] + " (" + String.valueOf(jsonArray.length()) + ")";
        } else if (tag.equals(COMMENTDATA)) {
            jsonData = ((JSONObject) data);
            mMenuList[3] = mMenuList[3] + " (" + String.valueOf(jsonData.getInt("data")) + ")";
        }
        adapter.notifyDataSetChanged();
    } catch (JSONException e) {
        Log.e("Error!", e.toString());
    }
}