Example usage for org.apache.commons.lang3.time DateUtils truncate

List of usage examples for org.apache.commons.lang3.time DateUtils truncate

Introduction

In this page you can find the example usage for org.apache.commons.lang3.time DateUtils truncate.

Prototype

public static Date truncate(final Object date, final int field) 

Source Link

Document

Truncates a date, leaving the field specified as the most significant field.

For example, if you had the date-time of 28 Mar 2002 13:45:01.231, if you passed with HOUR, it would return 28 Mar 2002 13:00:00.000.

Usage

From source file:eu.ggnet.dwoss.report.eao.ReportLineEao.java

/**
 * Generates a list of {@link DailyRevenue} that hold report data for INVOICES - ANNULATION_INVOICES in a date range containing daily summed prices
 * for specific {@link PositionType}s./* ww  w. j a  va  2  s . com*/
 * <p>
 * @param posTypes the {@link PositionType} that is searched for
 * @param start    the starting date range for the collected data
 * @param end      the end date range for the collected data
 * @return a list of {@link DailyRevenue} that hold report data for INVOICES - ANNULATION_INVOICES in a date range containing daily summed prices
 *         for specific {@link PositionType}s
 */
public List<Set<DailyRevenue>> findRevenueDataByPositionTypesAndDate(List<PositionType> posTypes, Date start,
        Date end) {
    try {
        L.info("Attempt to find revenue report data with posType={}, start={}, end={}", posTypes, start, end);

        List<Integer> posTypeOrdinals = new ArrayList<>();
        for (PositionType positionType : posTypes) {
            posTypeOrdinals.add(positionType.ordinal());
        }
        Query q = em.createNativeQuery("SELECT reportingDate, documentTypeName, sum(price), salesChannelName"
                + " FROM ReportLine rl WHERE rl.positionType in(:positions) and rl.reportingDate >= :start"
                + " and rl.reportingDate <= :end and rl.documentType in(1,3) GROUP BY rl.reportingDate, rl.documentTypeName, rl.salesChannelName");
        q.setParameter("positions", posTypeOrdinals);
        q.setParameter("start", start);
        q.setParameter("end", end);
        List<Object[]> data = q.getResultList();
        List<DailyRevenue> reportData = new ArrayList<>();
        for (Object[] object : data) {
            reportData.add(new DailyRevenue((Date) object[0], (String) object[1], (double) object[2],
                    (String) object[3]));
        }

        Map<Date, Set<DailyRevenue>> revReports = new HashMap<>();
        for (DailyRevenue revenueReportCarrier : reportData) {
            Date d = DateUtils.truncate(revenueReportCarrier.getReportingDate(), Calendar.DATE);
            Set<DailyRevenue> neededSet = revReports.get(d);
            if (neededSet == null) {
                neededSet = new HashSet<>();
                neededSet.add(revenueReportCarrier);
                revReports.put(d, neededSet);
            } else {
                neededSet.add(revenueReportCarrier);
            }
        }

        return new ArrayList<>(revReports.values());
    } catch (Exception e) {
        L.error(ExceptionUtils.getStackTrace(e));
        return null;
    }
}

From source file:com.bellman.bible.service.common.CommonUtils.java

public static Date getTruncatedDate() {
    return DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH);
}

From source file:de.tor.tribes.util.algo.types.TimeFrame.java

public List<Range<Long>> arriveTimespansToRanges() {
    List<Range<Long>> ranges = new LinkedList<>();
    Date arriveDate = DateUtils.truncate(new Date(arriveNotBefore), Calendar.DAY_OF_MONTH);

    for (TimeSpan span : arriveTimeSpans) {
        if (!span.isValidAtEveryDay()) {
            Range<Long> range;
            //just copy range
            range = Range.between(span.getSpan().getMinimum(), span.getSpan().getMaximum());

            if (range.getMaximum() > System.currentTimeMillis()) {
                if (range.getMinimum() <= System.currentTimeMillis()) {
                    //rebuild Range
                    range = Range.between(System.currentTimeMillis(), range.getMaximum());
                }/*ww w  .ja  v a 2 s.co  m*/
                //add range only if it is in future
                ranges.add(range);
            }
        } else {
            //span is valid for every day
            Date thisDate = new Date(arriveDate.getTime());
            //go through all days from start to end
            while (thisDate.getTime() < arriveNotAfter) {
                long spanStart = thisDate.getTime() + span.getSpan().getMinimum();
                long spanEnd = thisDate.getTime() + span.getSpan().getMaximum();
                Range<Long> newRange = null;
                //check span location relative to start frame
                if (spanStart >= arriveNotBefore && spanEnd > arriveNotBefore && spanStart < arriveNotAfter
                        && spanEnd <= arriveNotAfter) {
                    //|----------| (startNotBefore - startNotAfter)
                    //  |----| (SpanStart - SpanEnd)
                    newRange = Range.between(spanStart, spanEnd);
                } else if (spanStart < arriveNotBefore && spanEnd > arriveNotBefore
                        && spanStart < arriveNotAfter && spanEnd <= arriveNotAfter) {
                    //  |----------| (startNotBefore - startNotAfter)
                    //|----| (SpanStart - SpanEnd)
                    //set span start to 'startNotBefore'
                    newRange = Range.between(arriveNotBefore, spanEnd);
                } else if (spanStart <= arriveNotBefore && spanEnd > arriveNotBefore
                        && spanStart > arriveNotAfter && spanEnd >= arriveNotAfter) {
                    //  |----------| (startNotBefore - startNotAfter)
                    //|--------------| (SpanStart - SpanEnd)
                    //set span start to 'startNotBefore'
                    newRange = Range.between(arriveNotBefore, arriveNotAfter);
                } else if (spanStart >= arriveNotBefore && spanEnd > arriveNotBefore
                        && spanStart < arriveNotAfter && spanEnd >= arriveNotAfter) {
                    //|----------| (startNotBefore - startNotAfter)
                    //    |---------| (SpanStart - SpanEnd)
                    //set span start to 'startNotBefore'
                    newRange = Range.between(spanStart, arriveNotAfter);
                }

                if (newRange != null) {
                    if (newRange.getMinimum() < System.currentTimeMillis()) {
                        //check minimum as current minimum is in past
                        if (newRange.getMaximum() > System.currentTimeMillis()) {
                            newRange = Range.between(System.currentTimeMillis(), newRange.getMaximum());
                            ranges.add(newRange);
                        } //ignore as entire range is in past
                    } else {
                        //add range as it is in future
                        ranges.add(newRange);
                    }
                }
                //increment current date by one day
                thisDate = DateUtils.addDays(thisDate, 1);
            }
        }
    }
    Collections.sort(ranges, new Comparator<Range<Long>>() {
        @Override
        public int compare(Range<Long> o1, Range<Long> o2) {
            return o1.getMinimum().compareTo(o2.getMinimum());
        }
    });
    return ranges;
}

From source file:de.tor.tribes.ui.components.DatePicker.java

private void fireTodayAction(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fireTodayAction
    selectedDate = DateUtils.truncate(new Date(), Calendar.DATE);
    buildCalendar();/*from  w  ww  .  j  av a2 s.c o  m*/
}

From source file:com.saax.gestorweb.TarefaTest.java

/**
 * Testa o cadastro completo de uma tarefa, com todos os campos disponiveis
 * na//w w w .  j a  va  2s  .com
 */
@Test
public void cadastrarTarefaCompleta() {

    System.out.println("Testando cadastro completo de uma tarefa");

    Usuario loggedUser = (Usuario) GestorSession.getAttribute(SessionAttributesEnum.USUARIO_LOGADO);
    Usuario usuarioResponsavel = (Usuario) GestorEntityManagerProvider.getEntityManager()
            .createNamedQuery("Usuario.findByLogin").setParameter("login", "rodrigo.ccn2005@gmail.com")
            .getSingleResult();

    HierarquiaProjetoDetalhe categoriaDefaultMeta = model.getCategoriaDefaultTarefa();
    presenter.createTask(categoriaDefaultMeta, loggedUser.getEmpresas().get(0).getEmpresa());

    String nome = "Teste Cadastro Tarefa #2";

    // ---------------------------------------------------------------------
    // Setando os campos
    //        private Integer id;
    //        private HierarquiaProjetoDetalhe hierarquia;
    HierarquiaProjeto hierarquiaProjetoDefault = (HierarquiaProjeto) GestorEntityManagerProvider
            .getEntityManager().createNamedQuery("HierarquiaProjeto.findByNome").setParameter("nome", "Norma")
            .getSingleResult();

    for (HierarquiaProjetoDetalhe categoria : hierarquiaProjetoDefault.getCategorias()) {
        if (categoria.getNivel() == 2) {
            view.getHierarquiaCombo().setValue(categoria);
        }
    }
    //        private Empresa empresa;
    view.getEmpresaCombo().setValue(loggedUser.getEmpresas().get(0).getEmpresa());
    //        private String nome;
    view.getNomeTarefaTextField().setValue(nome);
    //        private PrioridadeTarefa prioridade;
    view.getPrioridadeCombo().setValue(PrioridadeTarefa.ALTA);
    //        private StatusTarefa status;
    //        private ProjecaoTarefa projecao;
    //        private int andamento;
    //        private String descricao;
    view.getDescricaoTextArea().setValue("Descrio da Tarefa #2");
    //        private boolean apontamentoHoras;
    view.getApontamentoHorasCheckBox().setValue(Boolean.TRUE);
    //        private boolean orcamentoControlado;
    view.getControleOrcamentoChechBox().setValue(Boolean.FALSE);
    //        private CentroCusto centroCusto;
    CentroCusto centroCusto = DAOAleatorio
            .getCentroCustoAleatorio(GestorEntityManagerProvider.getEntityManager());
    view.getCentroCustoCombo().setValue(centroCusto);
    //        private Departamento departamento;
    Departamento departamento = DAOAleatorio.getDepartamentoAleatorio(
            GestorEntityManagerProvider.getEntityManager(), loggedUser.getEmpresas().get(0).getEmpresa());
    view.getDepartamentoCombo().setValue(departamento);
    //        private FilialEmpresa filialEmpresa;
    //        private EmpresaCliente empresaCliente;
    EmpresaCliente empresaCliente = DAOAleatorio.getEmpresaClienteAleatoria(
            GestorEntityManagerProvider.getEntityManager(), loggedUser.getEmpresas().get(0).getEmpresa());
    view.getEmpresaClienteCombo().setValue(empresaCliente);
    //        private List<Tarefa> subTarefas;
    //        private Tarefa proximaTarefa;
    //        private TipoTarefa tipoRecorrencia;
    view.getControleRecorrenciaButton().getCaption().equals("RECORRENTE");
    //view.getTipoRecorrenciaCombo().select(TipoTarefa.RECORRENTE);
    //        private Tarefa tarefaPai;
    //        private LocalDate dataInicio;
    Date dataInicio = DAOAleatorio.getDataByOffset(20, true); // hoje + 20 dias
    view.getDataInicioDateField().setValue(dataInicio);
    //        private LocalDate dataTermino;
    //        private LocalDate dataFim;
    Date dataFim = DAOAleatorio.getDataByOffset(30, true); // hoje + 30 dias
    view.getDataFimDateField().setValue(dataFim);
    //        private Usuario usuarioInclusao;
    //        private Usuario usuarioSolicitante;
    //        private Usuario usuarioResponsavel;
    view.getUsuarioResponsavelCombo().setValue(usuarioResponsavel);
    //        private List<ParticipanteTarefa> participantes;
    Usuario usuarioParticipante_0 = (Usuario) GestorEntityManagerProvider.getEntityManager()
            .createNamedQuery("Usuario.findByLogin").setParameter("login", "fernando.saax@gmail.com")
            .getSingleResult();
    view.getParticipantesCombo().setValue(usuarioParticipante_0);
    Usuario usuarioParticipante_1 = (Usuario) GestorEntityManagerProvider.getEntityManager()
            .createNamedQuery("Usuario.findByLogin").setParameter("login", "danielstavale@gmail.com")
            .getSingleResult();
    view.getParticipantesCombo().setValue(usuarioParticipante_1);
    //        private List<AvaliacaoMetaTarefa> avaliacoes;
    //        private List<OrcamentoTarefa> orcamentos;
    view.getValorOrcadoRealizadoTextField().setValue("123.34");
    view.getObservacaoOrcamentoTextField().setValue("v0");
    OrcamentoTarefa orcamentoTarefa_0 = new OrcamentoTarefa();
    try {
        orcamentoTarefa_0 = view.getOrcamentoTarefa();
    } catch (FieldGroup.CommitException ex) {
        fail(ex.getMessage());
    }
    view.getImputarOrcamentoButton().click();

    view.getValorOrcadoRealizadoTextField().setValue("254.67");
    view.getObservacaoOrcamentoTextField().setValue("v1");
    OrcamentoTarefa orcamentoTarefa_1 = new OrcamentoTarefa();
    try {
        orcamentoTarefa_1 = view.getOrcamentoTarefa();
    } catch (FieldGroup.CommitException ex) {
        fail(ex.getMessage());
    }
    view.getImputarOrcamentoButton().click();
    //        private List<ApontamentoTarefa> apontamentos;
    view.getHorasApontadasTextField().setValue("135:00");
    view.getCustoHoraApontamentoTextField().setValue("14.36"); // 1938.6
    ApontamentoTarefa apontamento_0 = new ApontamentoTarefa();
    try {
        apontamento_0 = view.getApontamentoTarefa();
    } catch (FieldGroup.CommitException ex) {
        fail(ex.getMessage());
    }
    view.getAdicionarApontamentoButton().click();

    view.getHorasApontadasTextField().setValue("214:30"); // 3080.22
    ApontamentoTarefa apontamento_1 = new ApontamentoTarefa();
    try {
        apontamento_1 = view.getApontamentoTarefa();
    } catch (FieldGroup.CommitException ex) {
        fail(ex.getMessage());
    }
    view.getAdicionarApontamentoButton().click();
    //        private List<AnexoTarefa> anexos;
    //        private List<AndamentoTarefa> andamentos;
    //        private List<BloqueioTarefa> bloqueios;
    //        private List<HistoricoTarefa> historico;
    //        private LocalDateTime dataHoraInclusao;

    try {
        view.getTarefaFieldGroup().commit();
    } catch (FieldGroup.CommitException ex) {
        fail(ex.getMessage());
    }
    view.getGravarButton().click();

    Tarefa t = (Tarefa) GestorEntityManagerProvider.getEntityManager().createNamedQuery("Tarefa.findByNome")
            .setParameter("nome", nome).setParameter("empresa", loggedUser.getEmpresas().get(0).getEmpresa())
            .getSingleResult();

    // ---------------------------------------------------------------------
    // Conferindo resultado
    // ---------------------------------------------------------------------
    //        private Integer id;
    //        private int nivel;
    Assert.assertEquals(2, t.getHierarquia().getNivel());
    //        private String titulo;
    Assert.assertEquals("Tarefa", t.getHierarquia().getCategoria());
    //        private String nome;
    Assert.assertEquals(nome, t.getNome());
    //        private PrioridadeTarefa prioridade;
    Assert.assertEquals(PrioridadeTarefa.ALTA, t.getPrioridade());
    //        private StatusTarefa status;
    Assert.assertEquals(StatusTarefa.NAO_ACEITA, t.getStatus());
    //        private ProjecaoTarefa projecao;
    //        private int andamento;
    Assert.assertEquals(0, t.getAndamento());
    //        private String descricao;
    Assert.assertEquals("Descrio da Tarefa #2", t.getDescricao());
    //        private boolean apontamentoHoras;
    Assert.assertEquals(true, t.isApontamentoHoras());
    //        private boolean orcamentoControlado;
    Assert.assertEquals(false, t.isOrcamentoControlado());
    //        private CentroCusto centroCusto;
    Assert.assertEquals(centroCusto, t.getCentroCusto());
    //        private Departamento departamento;
    Assert.assertEquals(departamento, t.getDepartamento());
    //        private Empresa empresa;
    Assert.assertEquals(loggedUser.getEmpresas().get(0).getEmpresa(), t.getEmpresa());
    //        private FilialEmpresa filialEmpresa;
    //        private EmpresaCliente empresaCliente;
    Assert.assertEquals(empresaCliente, t.getEmpresaCliente());
    //        private List<Tarefa> subTarefas;
    //        private Tarefa proximaTarefa;
    //        private TipoTarefa tipoRecorrencia;
    Assert.assertEquals(TipoTarefa.UNICA, t.getTipoRecorrencia());
    //        private Tarefa tarefaPai;
    Assert.assertNull(t.getTarefaPai());
    //        private LocalDate dataTermino;
    //        private LocalDate dataInicio;
    Assert.assertEquals(DateUtils.truncate(dataInicio, Calendar.DATE),
            DateTimeConverters.toDate(t.getDataInicio()));
    //        private LocalDate dataFim;
    Assert.assertEquals(DateUtils.truncate(dataFim, Calendar.DATE), DateTimeConverters.toDate(t.getDataFim()));
    //        private Usuario usuarioInclusao;
    Assert.assertEquals(loggedUser, t.getUsuarioInclusao());
    //        private Usuario usuarioSolicitante;
    Assert.assertEquals(loggedUser, t.getUsuarioSolicitante());
    //        private Usuario usuarioResponsavel;
    Assert.assertEquals(usuarioResponsavel, t.getUsuarioResponsavel());
    //        private List<ParticipanteTarefa> participantes;
    Assert.assertEquals(usuarioParticipante_0, t.getParticipantes().get(0).getUsuarioParticipante());
    Assert.assertEquals(usuarioParticipante_1, t.getParticipantes().get(1).getUsuarioParticipante());
    //        private List<AvaliacaoMetaTarefa> avaliacoes;
    //        private List<OrcamentoTarefa> orcamentos;
    Assert.assertEquals(orcamentoTarefa_0.getCredito(), t.getOrcamentos().get(0).getCredito());
    Assert.assertEquals(orcamentoTarefa_0.getSaldo(), t.getOrcamentos().get(0).getSaldo());
    Assert.assertEquals(orcamentoTarefa_1.getCredito(), t.getOrcamentos().get(1).getCredito());
    Assert.assertEquals(orcamentoTarefa_1.getSaldo(), t.getOrcamentos().get(1).getSaldo());
    //        private List<ApontamentoTarefa> apontamentos;
    Assert.assertEquals(apontamento_0.getCreditoHoras(), t.getApontamentos().get(0).getCreditoHoras());
    Assert.assertEquals(apontamento_0.getCreditoValor(), t.getApontamentos().get(0).getCreditoValor());
    Assert.assertEquals(apontamento_0.getSaldoHoras(), t.getApontamentos().get(0).getSaldoHoras());
    Assert.assertEquals(apontamento_1.getCreditoHoras(), t.getApontamentos().get(1).getCreditoHoras());
    Assert.assertEquals(apontamento_1.getCreditoValor(), t.getApontamentos().get(1).getCreditoValor());
    Assert.assertEquals(apontamento_1.getSaldoHoras(), t.getApontamentos().get(1).getSaldoHoras());
    //        private List<AnexoTarefa> anexos;
    //        private List<AndamentoTarefa> andamentos;
    //        private List<BloqueioTarefa> bloqueios;
    //        private List<HistoricoTarefa> historico;
    //        private LocalDateTime dataHoraInclusao;
    Assert.assertNotNull(t.getDataHoraInclusao());

}

From source file:com.saax.gestorweb.TarefaTest.java

/**
 * Testa a edio da tarefa completa/*from  w  w w .j  av a  2s.  c  o  m*/
 *
 */
@Test
public void editarTarefaCompleta() {

    System.out.println("Testando a edio (alterao) da tarefa completa");

    Usuario loggedUser = (Usuario) GestorSession.getAttribute(SessionAttributesEnum.USUARIO_LOGADO);
    Usuario usuarioResponsavel = (Usuario) GestorEntityManagerProvider.getEntityManager()
            .createNamedQuery("Usuario.findByLogin").setParameter("login", "danielstavale@gmail.com")
            .getSingleResult();

    String nome = "editarTarefaCompleta";
    TestUtils.cadastrarTarefaSimples(nome);

    String novonome = "Teste Cadastro Tarefa #2 - Alterada";

    Tarefa t = (Tarefa) GestorEntityManagerProvider.getEntityManager().createNamedQuery("Tarefa.findByNome")
            .setParameter("nome", nome).setParameter("empresa", loggedUser.getEmpresas().get(0).getEmpresa())
            .getSingleResult();

    Assert.assertNotNull(t);
    presenter.editar(t);

    // ---------------------------------------------------------------------
    // Alterando os campos
    //        private String nome;
    view.getNomeTarefaTextField().setValue(novonome);
    view.getNomeTarefaTextField().commit();
    //        private PrioridadeTarefa prioridade;
    view.getPrioridadeCombo().setValue(PrioridadeTarefa.BAIXA);
    //        private StatusTarefa status;
    view.getStatusTarefaPopUpButton().click();
    //        private ProjecaoTarefa projecao;
    //        private int andamento;
    //        private String descricao;
    view.getDescricaoTextArea().setValue("Descrio da Tarefa #2 - Alterada");
    //        private boolean apontamentoHoras;
    view.getApontamentoHorasCheckBox().setValue(Boolean.FALSE);
    //        private boolean orcamentoControlado;
    view.getControleOrcamentoChechBox().setValue(Boolean.TRUE);
    //        private CentroCusto centroCusto;
    CentroCusto centroCusto = DAOAleatorio
            .getCentroCustoAleatorio(GestorEntityManagerProvider.getEntityManager());
    view.getCentroCustoCombo().setValue(centroCusto);
    //        private Departamento departamento;
    Departamento departamento = DAOAleatorio.getDepartamentoAleatorio(
            GestorEntityManagerProvider.getEntityManager(), loggedUser.getEmpresas().get(0).getEmpresa());
    view.getDepartamentoCombo().setValue(departamento);
    //        private Empresa empresa;
    view.getEmpresaCombo().setValue(loggedUser.getEmpresas().get(0).getEmpresa());
    //        private FilialEmpresa filialEmpresa;
    //        private EmpresaCliente empresaCliente;
    EmpresaCliente empresaCliente = DAOAleatorio.getEmpresaClienteAleatoria(
            GestorEntityManagerProvider.getEntityManager(), loggedUser.getEmpresas().get(0).getEmpresa());
    view.getEmpresaClienteCombo().setValue(empresaCliente);
    //        private List<Tarefa> subTarefas;
    //        private Tarefa proximaTarefa;
    //        private TipoTarefa tipoRecorrencia;
    //view.getTipoRecorrenciaCombo().select(TipoTarefa.UNICA);
    view.getControleRecorrenciaButton().getCaption().equals("NICA");
    //        private Tarefa tarefaPai;
    //        private LocalDate dataInicio;
    Date dataInicio = DAOAleatorio.getDataByOffset(10, true); // hoje + 10 dias
    view.getDataInicioDateField().setValue(dataInicio);
    //        private LocalDate dataTermino;
    //        private LocalDate dataFim;
    Date dataFim = DAOAleatorio.getDataByOffset(35, true); // hoje + 35 dias
    view.getDataFimDateField().setValue(dataFim);
    //        private Usuario usuarioInclusao;
    //        private Usuario usuarioSolicitante;
    //        private Usuario usuarioResponsavel;
    view.getUsuarioResponsavelCombo().setValue(usuarioResponsavel);

    try {
        view.getTarefaFieldGroup().commit();
    } catch (FieldGroup.CommitException ex) {
        fail(ex.getMessage());
    }
    view.getGravarButton().click();

    // obtem novamente a tarefa do banco
    t = (Tarefa) GestorEntityManagerProvider.getEntityManager().createNamedQuery("Tarefa.findByNome")
            .setParameter("nome", novonome)
            .setParameter("empresa", loggedUser.getEmpresas().get(0).getEmpresa()).getSingleResult();

    // ---------------------------------------------------------------------
    // Conferindo resultado
    // ---------------------------------------------------------------------
    //        private Integer id;
    //        private int nivel;
    Assert.assertEquals(2, t.getHierarquia().getNivel());
    //        private String titulo;
    Assert.assertEquals("Tarefa", t.getHierarquia().getCategoria());
    //        private String nome;
    Assert.assertEquals(novonome, t.getNome());
    //        private PrioridadeTarefa prioridade;
    Assert.assertEquals(PrioridadeTarefa.BAIXA, t.getPrioridade());
    //        private StatusTarefa status;
    Assert.assertEquals(StatusTarefa.NAO_INICIADA, t.getStatus());
    //        private ProjecaoTarefa projecao;
    //        private int andamento;
    Assert.assertEquals(0, t.getAndamento());
    //        private String descricao;
    Assert.assertEquals("Descrio da Tarefa #2 - Alterada", t.getDescricao());
    //        private boolean apontamentoHoras;
    Assert.assertEquals(false, t.isApontamentoHoras());
    //        private boolean orcamentoControlado;
    Assert.assertEquals(true, t.isOrcamentoControlado());
    //        private CentroCusto centroCusto;
    Assert.assertEquals(centroCusto, t.getCentroCusto());
    //        private Departamento departamento;
    Assert.assertEquals(departamento, t.getDepartamento());
    //        private Empresa empresa;
    Assert.assertEquals(loggedUser.getEmpresas().get(0).getEmpresa(), t.getEmpresa());
    //        private FilialEmpresa filialEmpresa;
    //        private EmpresaCliente empresaCliente;
    Assert.assertEquals(empresaCliente, t.getEmpresaCliente());
    //        private List<Tarefa> subTarefas;
    //        private Tarefa proximaTarefa;
    //        private TipoTarefa tipoRecorrencia;
    Assert.assertEquals(TipoTarefa.UNICA, t.getTipoRecorrencia());
    //        private Tarefa tarefaPai;
    Assert.assertNull(t.getTarefaPai());
    //        private LocalDate dataTermino;
    //        private LocalDate dataInicio;
    Assert.assertEquals(DateUtils.truncate(dataInicio, Calendar.DATE),
            DateTimeConverters.toDate(t.getDataInicio()));
    //        private LocalDate dataFim;
    Assert.assertEquals(DateUtils.truncate(dataFim, Calendar.DATE), DateTimeConverters.toDate(t.getDataFim()));
    //        private Usuario usuarioInclusao;
    Assert.assertEquals(loggedUser, t.getUsuarioInclusao());
    //        private Usuario usuarioSolicitante;
    Assert.assertEquals(loggedUser, t.getUsuarioSolicitante());
    //        private Usuario usuarioResponsavel;
    Assert.assertEquals(usuarioResponsavel, t.getUsuarioResponsavel());

}

From source file:alfio.controller.api.admin.EventApiController.java

@RequestMapping(value = "/events/{eventName}/ticket-sold-statistics", method = GET)
public List<TicketSoldStatistic> getTicketSoldStatistics(@PathVariable("eventName") String eventName,
        @RequestParam(value = "from", required = false) String f,
        @RequestParam(value = "to", required = false) String t, Principal principal) throws ParseException {
    Event event = loadEvent(eventName, principal);
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    //TODO: cleanup
    Date from = DateUtils.truncate(f == null ? new Date(0) : format.parse(f), Calendar.HOUR);
    Date to = DateUtils// www. j  a  v a 2s.c o  m
            .addMilliseconds(DateUtils.ceiling(t == null ? new Date() : format.parse(t), Calendar.DATE), -1);
    //

    return eventStatisticsManager.getTicketSoldStatistics(event.getId(), from, to);
}

From source file:com.webbfontaine.valuewebb.action.rimm.RefSelect.java

/**
 * Retrieves Rate object for requested currency and date
 *
 * @param forDate  null means today. Every value is truncated - seconds, minutes, hours are removed.
 * @param currency requested currency/*from ww w . ja  v  a  2s  . c o  m*/
 * @return {@link com.webbfontaine.valuewebb.model.rimm.Rate#EMPTY_INSTANCE} object if rate does not exist for currency
 */
public Rate getRate(Date forDate, String currency) {
    if (Utils.getNationalCurrencyName().equals(currency)) {
        return getNationalCurrencyRate();
    }

    if (forDate == null || currency == null) {
        return Rate.EMPTY_INSTANCE;
    }

    Query query = Utils.getEntityManager().createNamedQuery("rateByCurrencyAndDate");
    query.setHint("org.hibernate.cacheable", false);
    query.setParameter("cod", currency);
    query.setParameter("date", DateUtils.truncate(forDate, Calendar.DAY_OF_MONTH));

    try {
        return (Rate) query.getSingleResult();
    } catch (Exception e) {
        LOGGER.warn("Rate for currency [{0}] couldn't be obtained", currency);
    }
    return Rate.EMPTY_INSTANCE;
}

From source file:org.apache.cassandra.cql3.validation.operations.AggregationTest.java

@Test
public void testNestedFunctions() throws Throwable {
    createTable("CREATE TABLE %s (a int primary key, b timeuuid, c double, d double)");

    String copySign = createFunction(KEYSPACE, "double, double",
            "CREATE OR REPLACE FUNCTION %s(magnitude double, sign double) " + "RETURNS NULL ON NULL INPUT "
                    + "RETURNS double " + "LANGUAGE JAVA "
                    + "AS 'return Double.valueOf(Math.copySign(magnitude, sign));';");

    assertColumnNames(execute("SELECT max(a), max(toUnixTimestamp(b)) FROM %s"), "system.max(a)",
            "system.max(system.tounixtimestamp(b))");
    assertRows(execute("SELECT max(a), max(toUnixTimestamp(b)) FROM %s"), row(null, null));
    assertColumnNames(execute("SELECT max(a), toUnixTimestamp(max(b)) FROM %s"), "system.max(a)",
            "system.tounixtimestamp(system.max(b))");
    assertRows(execute("SELECT max(a), toUnixTimestamp(max(b)) FROM %s"), row(null, null));

    assertColumnNames(execute("SELECT max(" + copySign + "(c, d)) FROM %s"),
            "system.max(" + copySign + "(c, d))");
    assertRows(execute("SELECT max(" + copySign + "(c, d)) FROM %s"), row((Object) null));

    execute("INSERT INTO %s (a, b, c, d) VALUES (1, maxTimeuuid('2011-02-03 04:05:00+0000'), -1.2, 2.1)");
    execute("INSERT INTO %s (a, b, c, d) VALUES (2, maxTimeuuid('2011-02-03 04:06:00+0000'), 1.3, -3.4)");
    execute("INSERT INTO %s (a, b, c, d) VALUES (3, maxTimeuuid('2011-02-03 04:10:00+0000'), 1.4, 1.2)");

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    format.setTimeZone(TimeZone.getTimeZone("GMT"));
    Date date = format.parse("2011-02-03 04:10:00");
    date = DateUtils.truncate(date, Calendar.MILLISECOND);

    assertRows(execute("SELECT max(a), max(toUnixTimestamp(b)) FROM %s"), row(3, date.getTime()));
    assertRows(execute("SELECT max(a), toUnixTimestamp(max(b)) FROM %s"), row(3, date.getTime()));

    assertRows(execute("SELECT " + copySign + "(max(c), min(c)) FROM %s"), row(-1.4));
    assertRows(execute("SELECT " + copySign + "(c, d) FROM %s"), row(1.2), row(-1.3), row(1.4));
    assertRows(execute("SELECT max(" + copySign + "(c, d)) FROM %s"), row(1.4));
    assertRows(execute("SELECT " + copySign + "(c, max(c)) FROM %s"), row(1.2));
    assertRows(execute("SELECT " + copySign + "(max(c), c) FROM %s"), row(-1.4));
    ;/*  w  ww. ja  va 2s. c o  m*/
}

From source file:org.apache.lens.cube.metadata.TimePartition.java

private Date truncate(Date date, UpdatePeriod updatePeriod) {
    if (updatePeriod.equals(UpdatePeriod.WEEKLY)) {
        Date truncDate = DateUtils.truncate(date, Calendar.DAY_OF_MONTH);
        Calendar cal = Calendar.getInstance();
        cal.setTime(truncDate);/*  w  ww  .  ja v  a 2  s.co  m*/
        cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
        return cal.getTime();
    } else if (updatePeriod.equals(UpdatePeriod.QUARTERLY)) {
        Date dt = DateUtils.truncate(date, updatePeriod.calendarField());
        dt.setMonth(dt.getMonth() - dt.getMonth() % 3);
        return dt;
    } else {
        return DateUtils.truncate(date, updatePeriod.calendarField());
    }
}