Example usage for java.util Calendar HOUR

List of usage examples for java.util Calendar HOUR

Introduction

In this page you can find the example usage for java.util Calendar HOUR.

Prototype

int HOUR

To view the source code for java.util Calendar HOUR.

Click Source Link

Document

Field number for get and set indicating the hour of the morning or afternoon.

Usage

From source file:org.apache.tuscany.sca.binding.rest.provider.RESTBindingInvoker.java

public Message invoke(Message msg) {

    Object entity = null;//  ww  w .  ja va  2 s  .com
    Object[] args = msg.getBody();

    URI uri = URI.create(endpointReference.getDeployedURI());
    UriBuilder uriBuilder = UriBuilder.fromUri(uri);

    Method method = ((JavaOperation) operation).getJavaMethod();

    if (method.isAnnotationPresent(Path.class)) {
        // Only for resource method
        uriBuilder.path(method);
    }

    if (!JAXRSHelper.isResourceMethod(method)) {
        // This is RPC over GET
        uriBuilder.replaceQueryParam("method", method.getName());
    }

    Map<String, Object> pathParams = new HashMap<String, Object>();
    Map<String, Object> matrixParams = new HashMap<String, Object>();
    Map<String, Object> queryParams = new HashMap<String, Object>();
    Map<String, Object> headerParams = new HashMap<String, Object>();
    Map<String, Object> formParams = new HashMap<String, Object>();
    Map<String, Object> cookieParams = new HashMap<String, Object>();

    for (int i = 0; i < method.getParameterTypes().length; i++) {
        boolean isEntity = true;
        Annotation[] annotations = method.getParameterAnnotations()[i];
        PathParam pathParam = getAnnotation(annotations, PathParam.class);
        if (pathParam != null) {
            isEntity = false;
            pathParams.put(pathParam.value(), args[i]);
        }
        MatrixParam matrixParam = getAnnotation(annotations, MatrixParam.class);
        if (matrixParam != null) {
            isEntity = false;
            matrixParams.put(matrixParam.value(), args[i]);
        }
        QueryParam queryParam = getAnnotation(annotations, QueryParam.class);
        if (queryParam != null) {
            isEntity = false;
            queryParams.put(queryParam.value(), args[i]);
        }
        HeaderParam headerParam = getAnnotation(annotations, HeaderParam.class);
        if (headerParam != null) {
            isEntity = false;
            headerParams.put(headerParam.value(), args[i]);
        }
        FormParam formParam = getAnnotation(annotations, FormParam.class);
        if (formParam != null) {
            isEntity = false;
            formParams.put(formParam.value(), args[i]);
        }
        CookieParam cookieParam = getAnnotation(annotations, CookieParam.class);
        if (cookieParam != null) {
            isEntity = false;
            cookieParams.put(cookieParam.value(), args[i]);
        }
        isEntity = (getAnnotation(annotations, Context.class) == null);
        if (isEntity) {
            entity = args[i];
        }
    }

    for (Map.Entry<String, Object> p : queryParams.entrySet()) {
        uriBuilder.replaceQueryParam(p.getKey(), p.getValue());
    }
    for (Map.Entry<String, Object> p : matrixParams.entrySet()) {
        uriBuilder.replaceMatrixParam(p.getKey(), p.getValue());
    }

    uri = uriBuilder.buildFromMap(pathParams);
    Resource resource = restClient.resource(uri);

    for (Map.Entry<String, Object> p : headerParams.entrySet()) {
        resource.header(p.getKey(), String.valueOf(p.getValue()));
    }

    for (Map.Entry<String, Object> p : cookieParams.entrySet()) {
        Cookie cookie = new Cookie(p.getKey(), String.valueOf(p.getValue()));
        resource.cookie(cookie);
    }

    resource.contentType(getContentType());
    resource.accept(getAccepts());

    //handles declarative headers configured on the composite
    for (HTTPHeader header : binding.getHttpHeaders()) {
        //treat special headers that need to be calculated
        if (header.getName().equalsIgnoreCase("Expires")) {
            GregorianCalendar calendar = new GregorianCalendar();
            calendar.setTime(new Date());

            calendar.add(Calendar.HOUR, Integer.parseInt(header.getValue()));

            resource.header("Expires", HTTPCacheContext.RFC822DateFormat.format(calendar.getTime()));
        } else {
            //default behaviour to pass the header value to HTTP response
            resource.header(header.getName(), header.getValue());
        }
    }

    Object result = resource.invoke(httpMethod, responseType, entity);
    msg.setBody(result);
    return msg;
}

From source file:com.iflytek.cssp.SwiftAPI.SwiftClient.java

private String gettime(String newtime) {
    String test4 = newtime.substring(0, newtime.indexOf("."));
    String test5 = test4.replaceAll("T", " ");
    DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Calendar rightNow1 = Calendar.getInstance();
    Date date3 = new Date();
    try {/*from  w w  w. j a  v a  2 s  .c o  m*/
        date3 = format2.parse(test5);
    } catch (ParseException e1) {
        logger.error("[change the GMT to yyyy-MM-dd HH:mm:ss: error]");
    }
    rightNow1.setTime(date3);
    rightNow1.add(Calendar.HOUR, 8);
    Date dt2 = rightNow1.getTime();
    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    return sdf1.format(dt2);
}

From source file:org.mitre.openid.connect.token.TofuUserApprovalHandler.java

@Override
public AuthorizationRequest updateAfterApproval(AuthorizationRequest authorizationRequest,
        Authentication userAuthentication) {

    String userId = userAuthentication.getName();
    String clientId = authorizationRequest.getClientId();
    ClientDetails client = clientDetailsService.loadClientByClientId(clientId);

    // This must be re-parsed here because SECOAUTH forces us to call things in a strange order
    if (Boolean.parseBoolean(authorizationRequest.getApprovalParameters().get("user_oauth_approval"))) {

        authorizationRequest.setApproved(true);

        // process scopes from user input
        Set<String> allowedScopes = Sets.newHashSet();
        Map<String, String> approvalParams = authorizationRequest.getApprovalParameters();

        Set<String> keys = approvalParams.keySet();

        for (String key : keys) {
            if (key.startsWith("scope_")) {
                //This is a scope parameter from the approval page. The value sent back should
                //be the scope string. Check to make sure it is contained in the client's
                //registered allowed scopes.

                String scope = approvalParams.get(key);
                Set<String> approveSet = Sets.newHashSet(scope);

                //Make sure this scope is allowed for the given client
                if (systemScopes.scopesMatch(client.getScope(), approveSet)) {

                    // If it's structured, assign the user-specified parameter
                    SystemScope systemScope = systemScopes.getByValue(scope);
                    if (systemScope != null && systemScope.isStructured()) {
                        String paramValue = approvalParams.get("scopeparam_" + scope);
                        allowedScopes.add(scope + ":" + paramValue);
                        // .. and if it's unstructured, we're all set
                    } else {
                        allowedScopes.add(scope);
                    }//  w  w w . j  a va  2 s. c  o m
                }

            }
        }

        // inject the user-allowed scopes into the auth request
        authorizationRequest.setScope(allowedScopes);

        //Only store an ApprovedSite if the user has checked "remember this decision":
        String remember = authorizationRequest.getApprovalParameters().get("remember");
        if (!Strings.isNullOrEmpty(remember) && !remember.equals("none")) {

            Date timeout = null;
            if (remember.equals("one-hour")) {
                // set the timeout to one hour from now
                Calendar cal = Calendar.getInstance();
                cal.add(Calendar.HOUR, 1);
                timeout = cal.getTime();
            }

            ApprovedSite newSite = approvedSiteService.createApprovedSite(clientId, userId, timeout,
                    allowedScopes);
            String newSiteId = newSite.getId().toString();
            authorizationRequest.getExtensions().put(APPROVED_SITE, newSiteId);
        }

        setAuthTime(authorizationRequest);

    }

    return authorizationRequest;
}

From source file:me.crime.database.Crime.java

/**
  * //from ww w. j  av a 2 s  . c o m
  */
 public void save() {
     CrimeDao dao = CrimeDao.class.cast(DaoBeanFactory.create().getDaoBean(CrimeDao.class));

     try {

         if (this.getStartDate() == null && this.getCounty().compareTo("Vienna") == 0) {
             String name = this.getFile().substring(0, this.getFile().indexOf('.'));

             String[] date = name.split("-");

             Calendar cal = Calendar.getInstance();

             cal.set(Calendar.MONTH, Integer.parseInt(date[0]));
             cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(date[1]));
             cal.set(Calendar.YEAR, Integer.parseInt(date[2]));
             cal.set(Calendar.HOUR, 12);
             cal.set(Calendar.MINUTE, 0);
             cal.set(Calendar.SECOND, 0);
             cal.set(Calendar.MILLISECOND, 0);
             cal.set(Calendar.AM_PM, 0);

             this.setStartDate(cal);
         } else if (this.getStartDate() == null) {
             this.setStartDate(Calendar.getInstance());
         } else if (this.getStartDate().get(Calendar.YEAR) < 1999) {
             this.getStartDate().set(Calendar.YEAR, 1999);
         } else if (this.getStartDate().get(Calendar.YEAR) > 2009) {
             this.getStartDate().set(Calendar.YEAR, 2009);
         }

         if (isValidState(this.getAddress().getState())) {

             double dts = this.getStartDate().getTimeInMillis() / 86400000.0; // divide milliseconds per day to get
             // days.fraction_of_day
             double dayOrd = Math.floor(dts); // truncate to get whole days
             double timeOrd = (dts - dayOrd) * 24; // track time as hour.fraction_of_hour

             this.setTime(timeOrd);

             AddressDao locDao = AddressDao.class.cast(DaoBeanFactory.create().getDaoBean(AddressDao.class));

             Address location = locDao.loadAddress(this.getAddress().getLocation());
             if (location != null) {
                 this.setAddress(location);
             } else {
                 locDao.save(this.getAddress());
             }

             dao.save(this);
         }

     } catch (SQLException e) {

         log_.warn("Unable to save crime: " + this.getCrimeNumber() + "removing arrested");
         try {
             dao.save(this);
         } catch (SQLException e1) {
             log_.error("Unable to save crime: " + this.getCrimeNumber(), e);
         }

     }
 }

From source file:edu.depaul.armada.dao.ContainerLogDaoHibernate.java

@Override
public void deleteOldData(int interval) {
    Query query = sessionFactory.getCurrentSession()
            .createQuery("delete from ContainerLog c where c.timestamp <= :timestamp");

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.HOUR, interval * -1);

    query.setTimestamp("timestamp", new Timestamp(cal.getTimeInMillis()));
    query.executeUpdate();/*from   ww w.j a v a  2 s.com*/
}

From source file:com.cws.esolutions.core.utils.EmailUtils.java

/**
 * Processes and sends an email message as generated by the requesting
 * application. This method is utilized with a JNDI datasource.
 *
 * @param dataSource - The email message
 * @param authRequired - <code>true</code> if authentication is required, <code>false</code> otherwise
 * @param authList - If authRequired is true, this must be populated with the auth info
 * @return List - The list of email messages in the mailstore
 * @throws MessagingException {@link javax.mail.MessagingException} if an exception occurs during processing
 *///from  w  w w  .  ja  v  a 2  s.com
public static final synchronized List<EmailMessage> readEmailMessages(final Properties dataSource,
        final boolean authRequired, final List<String> authList) throws MessagingException {
    final String methodName = EmailUtils.CNAME
            + "#readEmailMessages(final Properties dataSource, final boolean authRequired, final List<String> authList) throws MessagingException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("dataSource: {}", dataSource);
        DEBUGGER.debug("authRequired: {}", authRequired);
        DEBUGGER.debug("authList: {}", authList);
    }

    Folder mailFolder = null;
    Session mailSession = null;
    Folder archiveFolder = null;
    List<EmailMessage> emailMessages = null;

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.HOUR, -24);

    final Long TIME_PERIOD = cal.getTimeInMillis();
    final URLName URL_NAME = (authRequired)
            ? new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"),
                    Integer.parseInt(dataSource.getProperty("port")), null, authList.get(0), authList.get(1))
            : new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"),
                    Integer.parseInt(dataSource.getProperty("port")), null, null, null);

    if (DEBUG) {
        DEBUGGER.debug("timePeriod: {}", TIME_PERIOD);
        DEBUGGER.debug("URL_NAME: {}", URL_NAME);
    }

    try {
        // Set up mail session
        mailSession = (authRequired) ? Session.getDefaultInstance(dataSource, new SMTPAuthenticator())
                : Session.getDefaultInstance(dataSource);

        if (DEBUG) {
            DEBUGGER.debug("mailSession: {}", mailSession);
        }

        if (mailSession == null) {
            throw new MessagingException("Unable to configure email services");
        }

        mailSession.setDebug(DEBUG);
        Store mailStore = mailSession.getStore(URL_NAME);
        mailStore.connect();

        if (DEBUG) {
            DEBUGGER.debug("mailStore: {}", mailStore);
        }

        if (!(mailStore.isConnected())) {
            throw new MessagingException("Failed to connect to mail service. Cannot continue.");
        }

        mailFolder = mailStore.getFolder("inbox");
        archiveFolder = mailStore.getFolder("archive");

        if (!(mailFolder.exists())) {
            throw new MessagingException("Requested folder does not exist. Cannot continue.");
        }

        mailFolder.open(Folder.READ_WRITE);

        if ((!(mailFolder.isOpen())) || (!(mailFolder.hasNewMessages()))) {
            throw new MessagingException("Failed to open requested folder. Cannot continue");
        }

        if (!(archiveFolder.exists())) {
            archiveFolder.create(Folder.HOLDS_MESSAGES);
        }

        Message[] mailMessages = mailFolder.getMessages();

        if (mailMessages.length == 0) {
            throw new MessagingException("No messages were found in the provided store.");
        }

        emailMessages = new ArrayList<EmailMessage>();

        for (Message message : mailMessages) {
            if (DEBUG) {
                DEBUGGER.debug("MailMessage: {}", message);
            }

            // validate the message here
            String messageId = message.getHeader("Message-ID")[0];
            Long messageDate = message.getReceivedDate().getTime();

            if (DEBUG) {
                DEBUGGER.debug("messageId: {}", messageId);
                DEBUGGER.debug("messageDate: {}", messageDate);
            }

            // only get emails for the last 24 hours
            // this should prevent us from pulling too
            // many emails
            if (messageDate >= TIME_PERIOD) {
                // process it
                Multipart attachment = (Multipart) message.getContent();
                Map<String, InputStream> attachmentList = new HashMap<String, InputStream>();

                for (int x = 0; x < attachment.getCount(); x++) {
                    BodyPart bodyPart = attachment.getBodyPart(x);

                    if (!(Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()))) {
                        continue;
                    }

                    attachmentList.put(bodyPart.getFileName(), bodyPart.getInputStream());
                }

                List<String> toList = new ArrayList<String>();
                List<String> ccList = new ArrayList<String>();
                List<String> bccList = new ArrayList<String>();
                List<String> fromList = new ArrayList<String>();

                for (Address from : message.getFrom()) {
                    fromList.add(from.toString());
                }

                if ((message.getRecipients(RecipientType.TO) != null)
                        && (message.getRecipients(RecipientType.TO).length != 0)) {
                    for (Address to : message.getRecipients(RecipientType.TO)) {
                        toList.add(to.toString());
                    }
                }

                if ((message.getRecipients(RecipientType.CC) != null)
                        && (message.getRecipients(RecipientType.CC).length != 0)) {
                    for (Address cc : message.getRecipients(RecipientType.CC)) {
                        ccList.add(cc.toString());
                    }
                }

                if ((message.getRecipients(RecipientType.BCC) != null)
                        && (message.getRecipients(RecipientType.BCC).length != 0)) {
                    for (Address bcc : message.getRecipients(RecipientType.BCC)) {
                        bccList.add(bcc.toString());
                    }
                }

                EmailMessage emailMessage = new EmailMessage();
                emailMessage.setMessageTo(toList);
                emailMessage.setMessageCC(ccList);
                emailMessage.setMessageBCC(bccList);
                emailMessage.setEmailAddr(fromList);
                emailMessage.setMessageAttachments(attachmentList);
                emailMessage.setMessageDate(message.getSentDate());
                emailMessage.setMessageSubject(message.getSubject());
                emailMessage.setMessageBody(message.getContent().toString());
                emailMessage.setMessageSources(message.getHeader("Received"));

                if (DEBUG) {
                    DEBUGGER.debug("emailMessage: {}", emailMessage);
                }

                emailMessages.add(emailMessage);

                if (DEBUG) {
                    DEBUGGER.debug("emailMessages: {}", emailMessages);
                }
            }

            // archive it
            archiveFolder.open(Folder.READ_WRITE);

            if (archiveFolder.isOpen()) {
                mailFolder.copyMessages(new Message[] { message }, archiveFolder);
                message.setFlag(Flags.Flag.DELETED, true);
            }
        }
    } catch (IOException iox) {
        throw new MessagingException(iox.getMessage(), iox);
    } catch (MessagingException mex) {
        throw new MessagingException(mex.getMessage(), mex);
    } finally {
        try {
            if ((mailFolder != null) && (mailFolder.isOpen())) {
                mailFolder.close(true);
            }

            if ((archiveFolder != null) && (archiveFolder.isOpen())) {
                archiveFolder.close(false);
            }
        } catch (MessagingException mx) {
            ERROR_RECORDER.error(mx.getMessage(), mx);
        }
    }

    return emailMessages;
}

From source file:gov.nih.nci.cadsr.sentinel.tool.AlertRec.java

/**
 * Return the date as a string in the form mm/dd/yyyy. The time is
 * optionally included. Time is returned in AM/PM format. The output can be
 * a simple string or formated with HTML tags.
 * /*from  w  w  w.j av  a2  s  . c o  m*/
 * @param var_
 *        The time stamp to format.
 * @param flag_
 *        true for the date and time, false for the date only.
 * @param html_
 *        true to include HTML tags, false for a simple string.
 * @return String date in String format
 */
static public String dateToString(Timestamp var_, boolean flag_, boolean html_) {
    // Be sure we have an object.
    if (var_ == null)
        return (html_) ? "<i>&lt;null&gt;</i>" : "";
    Calendar cal = Calendar.getInstance();
    cal.setTime(var_);

    // Always render in Month/Day/Year format.
    String date = (formatInt(cal.get(Calendar.MONTH) + 1)) + "/" + formatInt(cal.get(Calendar.DATE)) + "/"
            + formatInt(cal.get(Calendar.YEAR));

    // Do we include time?
    if (flag_) {
        date = date + ((html_) ? "&nbsp;" : " ");
        if (cal.get(Calendar.HOUR) == 0)
            date = date + "12";
        else
            date = date + cal.get(Calendar.HOUR);

        // Put is all together.
        date = date + ":" + formatInt(cal.get(Calendar.MINUTE)) + ":" + formatInt(cal.get(Calendar.SECOND))
                + ((html_) ? "&nbsp;" : " ") + ((cal.get(Calendar.AM_PM) == 0) ? "AM" : "PM");
    }
    return date;
}

From source file:es.udc.fic.test.model.CerrarMangaTest.java

@Test
public void cerrarMangaTRealPenalizado() {
    //Creamos una sola regata con la instancia de todos los objetos en memoria
    Regata regata = new Regata();
    regata.setNombre("Mock Regata");
    regata.setDescripcion("Mock Desc");
    regataDao.save(regata);/*w  w w .ja v  a2s .  c om*/

    Tipo tipoVLigera = new Tipo("Vela ligera", "Desc Vela ligera", true);
    tipoDao.save(tipoVLigera);
    Tipo tipoLanchas = new Tipo("Lanchas", "Desc Lanchas", true);
    tipoDao.save(tipoLanchas);

    Barco b1 = new Barco(204566, "Juan Sebastian El Cano", tipoVLigera, null, "Laser Standar");
    inscripcionService.inscribir(regata, b1, "Iago Surez");

    Barco b2 = new Barco(199012, "El Holandes Errante", tipoVLigera, null, "Laser Radial");
    inscripcionService.inscribir(regata, b2, "Samu Paredes");
    Barco b3 = new Barco(201402, "La Perla Negra", tipoVLigera, null, "Laser 4.7");
    inscripcionService.inscribir(regata, b3, "Adrian Pallas");
    Barco b4 = new Barco(202102, "La Pinta", tipoVLigera, null, "Laser 4.7");
    inscripcionService.inscribir(regata, b4, "Pedro Cabalar");
    Barco b5 = new Barco(182345, "Venus", tipoVLigera, null, "Laser Standar");
    //Ponemos otro tipo para ver como funciona la clasificacion
    inscripcionService.inscribir(regata, b5, "Jesus Lopez");
    Barco b6 = new Barco(206745, "Apolo", tipoLanchas, null, "Motora");
    inscripcionService.inscribir(regata, b6, "Diego Bascoy");

    Calendar dia1 = Calendar.getInstance();
    dia1.add(Calendar.DAY_OF_YEAR, -18);

    Calendar dia2 = Calendar.getInstance();
    dia2.add(Calendar.DAY_OF_YEAR, -18);
    dia2.add(Calendar.HOUR, 2);

    Calendar dia3 = Calendar.getInstance();
    dia3.add(Calendar.DAY_OF_YEAR, -17);

    // COMPROBAMOS LAS DESCALIFICACIONES QUE NO ACARREAN EL MAX DE PUNT.
    Manga manga1 = new Manga(dia1, regata, null, 100);

    List<Posicion> posManga1 = new ArrayList<Posicion>();

    //NAN -> 0 penal
    //ZFP -> 20% penal
    //SCP RDG DPI -> Penal en tiempo
    //Velas Ligeras
    // ZFP 3600s -> Tercero
    posManga1.add(new Posicion((long) 3000, Posicion.Penalizacion.ZFP, manga1, b1, (long) 0));
    //SCP 3450s -> Segundo
    posManga1.add(new Posicion((long) 3300, Posicion.Penalizacion.SCP, manga1, b2, (long) 150));
    //NAN 3400 -> Primero
    posManga1.add(new Posicion((long) 3400, Posicion.Penalizacion.NAN, manga1, b3, (long) 0));
    //RDG 3750 -> Cuarto
    posManga1.add(new Posicion((long) 3750, Posicion.Penalizacion.RDG, manga1, b4, (long) 0));
    //DPI 3860 -> Ultimo
    posManga1.add(new Posicion((long) 3800, Posicion.Penalizacion.DPI, manga1, b5, (long) 60));
    //Lanchas
    //Primero -> Puntos 1
    posManga1.add(new Posicion((long) 3300, Posicion.Penalizacion.ZFP, manga1, b6, (long) 0));

    manga1.setPosiciones(posManga1);
    mangaService.cerrarYGuardarManga(manga1);
    regata.addManga(manga1);

    //Comprobamos que todas las posiciones tienen puntos mayores que 0
    for (Posicion p : manga1.getPosiciones()) {
        assertTrue(p.getPuntos() > 0);
    }

    //Comprobamos que los puntos son correctos
    //Guardamos las posiciones por tipos
    Map<Barco, Posicion> posPorBarco = new HashMap<Barco, Posicion>();
    for (Posicion p : manga1.getPosiciones()) {
        //Aadimos la posicionActual
        posPorBarco.put(p.getBarco(), p);
    }

    //Velas Ligeras
    // ZFP 3600s -> Tercero
    assertEquals(posPorBarco.get(b1).getPuntos(), 3);
    //SCP 3450s -> Segundo
    assertEquals(posPorBarco.get(b2).getPuntos(), 2);
    //NAN 3400 -> Primero 
    assertEquals(posPorBarco.get(b3).getPuntos(), 1);
    //RDG 3750 -> Cuarto
    assertEquals(posPorBarco.get(b4).getPuntos(), 4);
    //DPI 3860 -> Ultimo
    assertEquals(posPorBarco.get(b5).getPuntos(), 5);
    //Lanchas
    //Primero
    assertEquals(posPorBarco.get(b6).getPuntos(), 1);

    // COMPROBAMOS LAS DESCALIFICACIONES QUE ACARREAN EL MAX DE PUNT.
    Manga manga2 = new Manga(dia2, regata, null, 100);

    List<Posicion> posManga2 = new ArrayList<Posicion>();

    //DNC DNS -> No Salio                
    // DNF RET DSQ -> No termino / Retirado / Descalificado 
    // DNE DGM -> Descalificaciones Graves
    // BFD -> Bandera negra
    //Velas Ligeras
    // ZFP 3600s -> Primero (unico el llegar)
    posManga2.add(new Posicion((long) 3000, Posicion.Penalizacion.ZFP, manga1, b1, (long) 0));
    //DNF No termino -> Ultimo -> 6 Puntos
    posManga2.add(new Posicion((long) 3300, Posicion.Penalizacion.DNF, manga1, b2, null));
    //DNE Descalificado -> Ultimo -> 6 Puntos
    posManga2.add(new Posicion((long) 3400, Posicion.Penalizacion.DNE, manga1, b3, null));
    //DNE Descalificado -> Ultimo -> 6 Puntos
    posManga2.add(new Posicion((long) 3750, Posicion.Penalizacion.DNE, manga1, b4, null));
    //DGM Descalificado -> Ultimo -> 6 Puntos
    posManga2.add(new Posicion((long) 3800, Posicion.Penalizacion.DGM, manga1, b5, null));
    //Lanchas
    //RET Retirado -> Puntos 2
    posManga2.add(new Posicion((long) 3300, Posicion.Penalizacion.RET, manga1, b6, null));

    manga2.setPosiciones(posManga2);
    mangaService.cerrarYGuardarManga(manga2);
    regata.addManga(manga2);

    //Comprobamos que todas las posiciones tienen puntos mayores que 0
    for (Posicion p : manga2.getPosiciones()) {
        assertTrue(p.getPuntos() > 0);
    }

    //Comprobamos que los puntos son correctos
    //Guardamos las posiciones por tipos
    Map<Barco, Posicion> posPorBarco2 = new HashMap<Barco, Posicion>();
    for (Posicion p : manga2.getPosiciones()) {
        //Aadimos la posicionActual
        posPorBarco2.put(p.getBarco(), p);
    }

    //ZFP 3600s -> Primero (unico el llegar)
    assertEquals(posPorBarco2.get(b1).getPuntos(), 1);
    //DNF No termino -> Ultimo -> 5 Puntos
    assertEquals(posPorBarco2.get(b2).getPuntos(), 6);
    //DNE Descalificado -> Ultimo -> 5 Puntos
    assertEquals(posPorBarco2.get(b3).getPuntos(), 6);
    //BFD Bandera Negra -> Ultimo -> 5 Puntos
    assertEquals(posPorBarco2.get(b4).getPuntos(), 6);
    //DGM Descalificado -> Ultimo -> 5 Puntos
    assertEquals(posPorBarco2.get(b5).getPuntos(), 6);
    //Lanchas
    //Primero
    assertEquals(posPorBarco2.get(b6).getPuntos(), 2);
}

From source file:com.floreantpos.actions.ClockInOutAction.java

public void performDriverIn(User user) {
    try {/*  w  ww . j av a 2  s  .  co  m*/
        if (user == null) {
            return;
        }
        if (!user.isClockedIn()) {
            POSMessageDialog.showMessage(POSUtil.getFocusedWindow(), Messages.getString("ClockInOutAction.2")); //$NON-NLS-1$
            return;
        }

        EmployeeInOutHistoryDAO attendenceHistoryDAO = new EmployeeInOutHistoryDAO();
        EmployeeInOutHistory attendenceHistory = attendenceHistoryDAO.findDriverHistoryByClockedInTime(user);
        if (attendenceHistory == null) {
            attendenceHistory = new EmployeeInOutHistory();
            Date lastClockOutTime = user.getLastClockOutTime();
            Calendar c = Calendar.getInstance();
            c.setTime(lastClockOutTime);
            attendenceHistory.setOutTime(lastClockOutTime);
            attendenceHistory.setOutHour(Short.valueOf((short) c.get(Calendar.HOUR)));
            attendenceHistory.setUser(user);
            attendenceHistory.setTerminal(Application.getInstance().getTerminal());
            attendenceHistory.setShift(user.getCurrentShift());
        }

        Shift shift = user.getCurrentShift();
        Calendar calendar = Calendar.getInstance();

        user.setAvailableForDelivery(true);

        attendenceHistory.setClockOut(false);
        attendenceHistory.setInTime(calendar.getTime());
        attendenceHistory.setInHour(Short.valueOf((short) calendar.get(Calendar.HOUR_OF_DAY)));

        UserDAO.getInstance().saveDriverIn(user, attendenceHistory, shift, calendar);

        POSMessageDialog.showMessage(
                "Driver " + user.getFirstName() + " " + user.getLastName() + " is in after delivery"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    } catch (Exception e) {
        POSMessageDialog.showError(Application.getPosWindow(), e.getMessage(), e);
    }
}

From source file:DateParser.java

/**
 * Check if a given date is an iso8601 date.
 * /*from  ww  w.  j av  a2 s . c o m*/
 * @param iso8601Date The date to be checked.
 * @return <code>true</code> if the date is an iso8601 date.
 * @throws InvalidDateException 
 */
private Calendar getCalendar(String iso8601Date) throws InvalidDateException {
    // YYYY-MM-DDThh:mm:ss.sTZD
    StringTokenizer st = new StringTokenizer(iso8601Date, "-T:.+Z", true);
    if (!st.hasMoreTokens()) {
        throw new InvalidDateException("Empty Date");
    }
    Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
    calendar.clear();
    try {
        // Year
        if (st.hasMoreTokens()) {
            int year = Integer.parseInt(st.nextToken());
            calendar.set(Calendar.YEAR, year);
        } else {
            return calendar;
        }
        // Month
        if (checkValueAndNext(st, "-")) {
            int month = Integer.parseInt(st.nextToken()) - 1;
            calendar.set(Calendar.MONTH, month);
        } else {
            return calendar;
        }
        // Day
        if (checkValueAndNext(st, "-")) {
            int day = Integer.parseInt(st.nextToken());
            calendar.set(Calendar.DAY_OF_MONTH, day);
        } else {
            return calendar;
        }
        // Hour
        if (checkValueAndNext(st, "T")) {
            int hour = Integer.parseInt(st.nextToken());
            calendar.set(Calendar.HOUR_OF_DAY, hour);
        } else {
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            return calendar;
        }
        // Minutes
        if (checkValueAndNext(st, ":")) {
            int minutes = Integer.parseInt(st.nextToken());
            calendar.set(Calendar.MINUTE, minutes);
        } else {
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            return calendar;
        }
        if (!st.hasMoreTokens()) {
            return calendar;
        }
        // Not mandatory now
        // Seconds
        String tok = st.nextToken();
        if (tok.equals(":")) { // seconds
            if (st.hasMoreTokens()) {
                int secondes = Integer.parseInt(st.nextToken());
                calendar.set(Calendar.SECOND, secondes);
                if (!st.hasMoreTokens()) {
                    return calendar;
                }
                // decimal fraction of a second
                tok = st.nextToken();
                if (tok.equals(".")) {
                    String nt = st.nextToken();
                    while (nt.length() < 3) {
                        nt += "0";
                    }
                    if (nt.length() > 3) {
                        // check the other part from the decimal fraction to be formed only from digits
                        for (int i = 3; i < nt.length(); i++) {
                            if (!Character.isDigit(nt.charAt(i))) {
                                throw new InvalidDateException(
                                        "Invalid digit in the decimal fraction of a second: " + nt.charAt(i));
                            }
                        }
                    }
                    nt = nt.substring(0, 3); //Cut trailing chars..
                    int millisec = Integer.parseInt(nt);
                    calendar.set(Calendar.MILLISECOND, millisec);
                    if (!st.hasMoreTokens()) {
                        return calendar;
                    }
                    tok = st.nextToken();
                } else {
                    calendar.set(Calendar.MILLISECOND, 0);
                }
            } else {
                throw new InvalidDateException("No secondes specified");
            }
        } else {
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
        }
        // Time zone
        if (!tok.equals("Z")) { // UTC
            if (!(tok.equals("+") || tok.equals("-"))) {
                throw new InvalidDateException("only Z, + or - allowed");
            }
            boolean plus = tok.equals("+");
            if (!st.hasMoreTokens()) {
                throw new InvalidDateException("Missing hour field");
            }
            int tzhour = Integer.parseInt(st.nextToken());
            int tzmin = 0;
            if (checkValueAndNext(st, ":")) {
                tzmin = Integer.parseInt(st.nextToken());
            } else {
                throw new InvalidDateException("Missing minute field");
            }
            if (plus) {
                calendar.add(Calendar.HOUR, -tzhour);
                calendar.add(Calendar.MINUTE, -tzmin);
            } else {
                calendar.add(Calendar.HOUR, tzhour);
                calendar.add(Calendar.MINUTE, tzmin);
            }
        } else {
            if (st.hasMoreTokens()) {
                throw new InvalidDateException(
                        "Unexpected field at the end of the date field: " + st.nextToken());
            }
        }
    } catch (NumberFormatException ex) {
        throw new InvalidDateException("[" + ex.getMessage() + "] is not an integer");
    }
    return calendar;
}