Example usage for org.joda.time DateTime parse

List of usage examples for org.joda.time DateTime parse

Introduction

In this page you can find the example usage for org.joda.time DateTime parse.

Prototype

public static DateTime parse(String str, DateTimeFormatter formatter) 

Source Link

Document

Parses a DateTime from the specified string using a formatter.

Usage

From source file:com.esofthead.mycollab.common.service.ibatis.TimelineTrackingServiceImpl.java

License:Open Source License

@Override
public Map<String, List<GroupItem>> findTimelineItems(String fieldGroup, List<String> groupVals, Date start,
        Date end, TimelineTrackingSearchCriteria criteria) {
    try {/*from   w  w  w .  j ava 2s .  co  m*/
        DateTime startDate = new DateTime(start);
        final DateTime endDate = new DateTime(end);
        if (startDate.isAfter(endDate)) {
            throw new UserInvalidInputException("Start date must be greater than end date");
        }
        List<Date> dates = boundDays(startDate, endDate.minusDays(1));
        Map<String, List<GroupItem>> items = new HashMap<>();
        criteria.setFieldgroup(StringSearchField.and(fieldGroup));
        List<GroupItem> cacheTimelineItems = timelineTrackingCachingMapperExt.findTimelineItems(groupVals,
                dates, criteria);

        DateTime calculatedDate = startDate.toDateTime();
        if (cacheTimelineItems.size() > 0) {
            GroupItem item = cacheTimelineItems.get(cacheTimelineItems.size() - 1);
            String dateValue = item.getGroupname();
            calculatedDate = DateTime.parse(dateValue, DateTimeFormat.forPattern("yyyy-MM-dd"));

            for (GroupItem map : cacheTimelineItems) {
                String groupVal = map.getGroupid();
                Object obj = items.get(groupVal);
                if (obj == null) {
                    List<GroupItem> itemLst = new ArrayList<>();
                    itemLst.add(map);
                    items.put(groupVal, itemLst);
                } else {
                    List<GroupItem> itemLst = (List<GroupItem>) obj;
                    itemLst.add(map);
                }
            }
        }

        dates = boundDays(calculatedDate.plusDays(1), endDate);
        if (dates.size() > 0) {
            boolean isValidForBatchSave = true;
            final String type = criteria.getType().getValue();
            SetSearchField<Integer> extraTypeIds = criteria.getExtraTypeIds();
            Integer tmpExtraTypeId = null;
            if (extraTypeIds != null) {
                if (extraTypeIds.getValues().size() == 1) {
                    tmpExtraTypeId = extraTypeIds.getValues().iterator().next();
                } else {
                    isValidForBatchSave = false;
                }
            }
            final Integer extraTypeId = tmpExtraTypeId;

            final List<Map> timelineItems = timelineTrackingMapperExt.findTimelineItems(groupVals, dates,
                    criteria);
            if (isValidForBatchSave) {
                final Integer sAccountId = (Integer) criteria.getSaccountid().getValue();
                final String itemFieldGroup = criteria.getFieldgroup().getValue();
                JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

                final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
                final List<Map> filterCollections = new ArrayList<>(
                        Collections2.filter(timelineItems, new Predicate<Map>() {
                            @Override
                            public boolean apply(Map input) {
                                String dateStr = (String) input.get("groupname");
                                DateTime dt = formatter.parseDateTime(dateStr);
                                return !dt.equals(endDate);
                            }
                        }));
                jdbcTemplate.batchUpdate(
                        "INSERT INTO `s_timeline_tracking_cache`(type, fieldval,extratypeid,sAccountId,"
                                + "forDay, fieldgroup,count) VALUES(?,?,?,?,?,?,?)",
                        new BatchPreparedStatementSetter() {
                            @Override
                            public void setValues(PreparedStatement preparedStatement, int i)
                                    throws SQLException {
                                Map item = filterCollections.get(i);
                                preparedStatement.setString(1, type);
                                String fieldVal = (String) item.get("groupid");
                                preparedStatement.setString(2, fieldVal);
                                preparedStatement.setInt(3, extraTypeId);
                                preparedStatement.setInt(4, sAccountId);
                                String dateStr = (String) item.get("groupname");
                                DateTime dt = formatter.parseDateTime(dateStr);
                                preparedStatement.setDate(5, new java.sql.Date(dt.toDate().getTime()));
                                preparedStatement.setString(6, itemFieldGroup);
                                int value = ((BigDecimal) item.get("value")).intValue();
                                preparedStatement.setInt(7, value);
                            }

                            @Override
                            public int getBatchSize() {
                                return filterCollections.size();
                            }
                        });
            }

            for (Map map : timelineItems) {
                String groupVal = (String) map.get("groupid");
                GroupItem item = new GroupItem();
                item.setValue(((BigDecimal) map.get("value")).doubleValue());
                item.setGroupid((String) map.get("groupid"));
                item.setGroupname((String) map.get("groupname"));
                Object obj = items.get(groupVal);
                if (obj == null) {
                    List<GroupItem> itemLst = new ArrayList<>();
                    itemLst.add(item);
                    items.put(groupVal, itemLst);
                } else {
                    List<GroupItem> itemLst = (List<GroupItem>) obj;
                    itemLst.add(item);
                }
            }
        }

        return items;
    } catch (Exception e) {
        LOG.error("Error", e);
        return null;
    }
}

From source file:com.gst.infrastructure.reportmailingjob.service.ReportMailingJobWritePlatformServiceImpl.java

License:Apache License

/**
 * create the next recurring DateTime from recurrence pattern, start DateTime and current DateTime
 * // w w w .j  av a2s.c o  m
 * @param recurrencePattern
 * @param startDateTime
 * @return DateTime object
 */
private DateTime createNextRecurringDateTime(final String recurrencePattern, final DateTime startDateTime) {
    DateTime nextRecurringDateTime = null;

    // the recurrence pattern/rule cannot be empty
    if (StringUtils.isNotBlank(recurrencePattern) && startDateTime != null) {
        final LocalDate nextDayLocalDate = startDateTime.plus(1).toLocalDate();
        final LocalDate nextRecurringLocalDate = CalendarUtils.getNextRecurringDate(recurrencePattern,
                startDateTime.toLocalDate(), nextDayLocalDate);
        final String nextDateTimeString = nextRecurringLocalDate + " " + startDateTime.getHourOfDay() + ":"
                + startDateTime.getMinuteOfHour() + ":" + startDateTime.getSecondOfMinute();
        final DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(DATETIME_FORMAT);

        nextRecurringDateTime = DateTime.parse(nextDateTimeString, dateTimeFormatter);
    }

    return nextRecurringDateTime;
}

From source file:com.hamdikavak.humanmobility.modeling.test.DataHelper.java

License:Open Source License

private static ExtendedLocationTrace convertLineToAExtendedLocationTraceObject(String line) {
    String[] columnValues;//from  w ww. j a  va  2 s  .  c  o  m
    ExtendedLocationTrace trace = new ExtendedLocationTrace();

    // a line in the csv file {user_id,utc_time,latitude,longitude}

    columnValues = line.split(",");

    String dtString = columnValues[1].replace("\"", "") + "00"; // 00 added to conform time zone format
    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ssZ");

    String userId = columnValues[0];
    DateTime dt = DateTime.parse(dtString, formatter);
    Double latitude = Double.parseDouble(columnValues[2]);
    Double longitude = Double.parseDouble(columnValues[3]);

    trace.setUserId(userId);
    trace.setUTCTime(dt);
    trace.setLocalTime(dt.toLocalDateTime());
    trace.setCoordinate(new GeoCoordinate(latitude, longitude));

    return trace;
}

From source file:com.hihexo.epp.controller.NSDomainController.java

License:Open Source License

/**
 * <code>NSDomain.sendDomainRenew</code> command.
 *///from   w ww.  ja v a  2  s .c om
@ApiOperation(value = "renew", notes = "")
@RequestMapping(value = "/renew", method = RequestMethod.POST)
@SystemControllerLog(description = "??")
@ResponseBody
public ResultVo doDomainRenew(HttpServletRequest request, @RequestBody NSDomainRenewParam params) {
    printStart("doDomainRenew");

    EPPSession theSession = null;
    EPPDomainRenewResp theResponse = null;
    try {
        theSession = this.borrowSession();
        com.verisign.epp.namestore.interfaces.NSDomain theDomain = new com.verisign.epp.namestore.interfaces.NSDomain(
                theSession);

        try {
            theDomain.setTransId(getClientTransId(request));

            String theDomainName = this.makeDomainName();

            logger.debug("\ndomainRenew: Domain " + theDomainName + " renew");

            theDomain.addDomainName(params.getDomainName());
            theDomain.setSubProductID(params.getDomainProductID());

            DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
            DateTime dateTime = DateTime.parse(params.getExpiretime(), format);
            theDomain.setExpirationDate(dateTime.toDate());

            theDomain.setPeriodLength(params.getPeriod());
            theDomain.setPeriodUnit(params.getPeriodUnit());

            if (StringUtils.isNotEmpty(params.getAllocationToken())) {
                theDomain.setAllocationToken(params.getAllocationToken());
            }

            theResponse = theDomain.sendRenew();

            // -- Output all of the response attributes
            logger.debug("domainRenew: Response = [" + theResponse + "]\n\n");

            // -- Output response attributes using accessors
            logger.debug("domainRenew: name = " + theResponse.getName());

            logger.debug("domainRenew: expiration date = " + theResponse.getExpirationDate());
        }

        catch (EPPCommandException ex) {
            TestUtil.handleException(theSession, ex);
            return renderError(ex.getMessage());
        }

        this.handleResponse(theResponse);
        return renderSuccess(theResponse);
    } catch (InvalidateSessionException ex) {
        this.invalidateSession(theSession);
        theSession = null;
    } finally {
        if (theSession != null)
            this.returnSession(theSession);
    }

    printEnd("doDomainRenew");
    return renderError("unknown");
}

From source file:com.hihexo.epp.controller.NSDomainController.java

License:Open Source License

/**
 * <code>NSDomain.sendRestoreReport</code> command.
 *///from  w w  w .  j  av a2 s.  c o  m
@ApiOperation(value = "?????", notes = "")
@RequestMapping(value = "/restorereport", method = RequestMethod.POST)
@SystemControllerLog(description = "restore")
@ResponseBody
public ResultVo doDomainRestoreReport(HttpServletRequest request,
        @RequestBody NSDomainRestoreReportParam params) {
    printStart("doDomainRestoreReport");

    EPPSession theSession = null;
    EPPResponse theResponse = null;
    try {
        theSession = this.borrowSession();
        com.verisign.epp.namestore.interfaces.NSDomain theDomain = new com.verisign.epp.namestore.interfaces.NSDomain(
                theSession);
        String theDomainName = params.getDomainName();

        try {
            theDomain.setTransId(getClientTransId(request));

            logger.debug("\ndomainRestoreReport: Domain " + theDomainName + " restore request");

            theDomain.addDomainName(theDomainName);
            theDomain.setSubProductID(params.getDomainProductID());

            EPPRgpExtReport theReport = new EPPRgpExtReport();
            theReport.setPreData(params.getPreData());
            theReport.setPostData(params.getPostData());

            DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
            DateTime dateTime = DateTime.parse(params.getDeleteTime(), format);

            theReport.setDeleteTime(dateTime.toDate());
            dateTime = DateTime.parse(params.getRestoreTime(), format);
            theReport.setRestoreTime(dateTime.toDate());

            theReport.setRestoreReason(new EPPRgpExtReportText(params.getRestoreReason()));

            theReport.setStatement1(new EPPRgpExtReportText(params.getRestoreStatement1()));

            theReport.setStatement2(new EPPRgpExtReportText(params.getRestoreStatement2()));

            theReport.setOther(params.getOtherStuff());

            // Execute restore report
            theDomain.setReport(theReport);
            theResponse = theDomain.sendRestoreReport();

            // -- Output all of the response attributes
            logger.debug("domainRestoreReport: Response = [" + theResponse + "]\n\n");
            this.handleResponse(theResponse);
            return renderSuccess(theResponse);
        } catch (EPPCommandException ex) {
            TestUtil.handleException(theSession, ex);
            return renderError(ex.getMessage());
        }

    } catch (InvalidateSessionException ex) {
        this.invalidateSession(theSession);
        theSession = null;
    } finally {
        if (theSession != null)
            this.returnSession(theSession);
    }

    printEnd("doDomainRestoreReport");
    return renderError("fail");
}

From source file:com.huang.rp.common.utils.TimeUtils.java

License:Apache License

/**
 * ?DateTime/*  w  w  w.  jav  a2  s  .c o  m*/
 * @param dateStr
 * @return
 */
public static DateTime getDateTime(String dateStr) {
    if (dateStr.matches(yyyyMMddFormtterRegex)) {
        return DateTime.parse(dateStr, DateTimeFormat.forPattern(yyyyMMddFormtter));
    } else if (dateStr.matches(yyyyMMddHHmmssFormtterRegex)) {
        return DateTime.parse(dateStr, DateTimeFormat.forPattern(yyyMMddHHmmssFormtter));
    }
    return null;
}

From source file:com.ideaspymes.tesakaplugin.importacion.jpa.RetencionGenerada.java

public RetencionGenerada(Datos d, RecepcionImp r) {

    this.uuid = d.getAtributos().getUuid();

    this.fechaCreacion = LocalDate
            .parse(d.getAtributos().getFechaCreacion(), DateTimeFormat.forPattern("yyyy-MM-dd")).toDate();
    this.fechaHoraCreacion = DateTime
            .parse(d.getAtributos().getFechaHoraCreacion(), DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"))
            .toDate();//ww  w.ja  va  2 s.  co m

    this.codigoEstablecimiento = d.getInformante().getCodigoEstablecimiento();
    this.timbradoComprobante = d.getInformante().getTimbradoComprobante();
    this.puntoExpedicionComprobante = d.getInformante().getPuntoExpedicionComprobante();
    this.establecimiento = d.getInformante().getEstablecimiento();

    this.condicionCompra = d.getTransaccion().getCondicionCompra();
    this.tipoComprobante = d.getTransaccion().getTipoComprobante();
    this.numeroTimbradoFactura = d.getTransaccion().getNumeroTimbrado();
    this.numeroComprobanteVenta = d.getTransaccion().getNumeroComprobanteVenta();
    this.fechaFactura = LocalDate.parse(d.getTransaccion().getFecha(), DateTimeFormat.forPattern("yyyy-MM-dd"))
            .toDate();
    this.proveedorRuc = d.getInformado().getRuc();
    this.proveedorDv = d.getInformado().getDv();
    this.proveedorNombre = d.getInformado().getNombre();
    this.proveedorTipoIdentificacion = d.getInformado().getTipoIdentificacionNombre();
    this.proveedorIdentificacion = d.getInformado().getIdentificacion();
    this.proveedorSituacion = d.getInformado().getSituacion();
    this.proveedorCorreo = d.getInformado().getCorreoElectronico();
    this.proveedorDomicilio = d.getInformado().getDomicilio() == null ? d.getInformado().getDireccion()
            : d.getInformado().getDomicilio();

    Double total = 0d;
    for (DetalleImp dt : d.getDetalle()) {
        total += (dt.getPrecioUnitario() * dt.getCantidad());
    }

    this.totalFactura = total;

    this.fechaRetencion = LocalDate.parse(d.getRetencion().getFecha(), DateTimeFormat.forPattern("yyyy-MM-dd"))
            .toDate();
    this.moneda = d.getRetencion().getMoneda();
    this.tipoCambio = d.getRetencion().getTipoCambio();
    this.retencionIva = d.getRetencion().getRetencionIva();
    this.retencionRenta = d.getRetencion().getRetencionRenta();
    this.conceptoRenta = d.getRetencion().getConceptoRenta();
    this.conceptoIva = d.getRetencion().getConceptoIva();
    this.habilitadoRentaCabezas = d.getRetencion().getHabilitadoRentaCabezas();
    this.habilitadoRentaToneladas = d.getRetencion().getHabilitadoRentaToneladas();
    this.ivaBase5 = d.getRetencion().getIvaBase5();
    this.ivaTotal5 = d.getRetencion().getIvaTotal5();
    this.ivaBase10 = d.getRetencion().getIvaBase10();
    this.ivaTotal10 = d.getRetencion().getIvaTotal10();
    this.ivaTotal = d.getRetencion().getIvaTotal();
    this.rentaBase = d.getRetencion().getRentaBase();
    this.rentaTotal = d.getRetencion().getRentaTotal();
    this.rentaCabezasBase = d.getRetencion().getRentaCabezasBase();
    this.rentaCabezasCantidad = d.getRetencion().getRentaCabezasCantidad();
    this.rentaCabezasTotal = d.getRetencion().getRentaCabezasTotal();
    this.rentaToneladasBase = d.getRetencion().getRentaToneladasBase();
    this.rentaToneladasCantidad = d.getRetencion().getRentaToneladasCantidad();
    this.rentaToneladasTotal = d.getRetencion().getRentaToneladasTotal();
    this.retencionIvaTotal = d.getRetencion().getRetencionIvaTotal();
    this.retencionRentaTotal = d.getRetencion().getRetencionRentaTotal();
    this.retencionTotal = d.getRetencion().getRetencionTotal();
    this.rentaPorcentaje = d.getRetencion().getRentaPorcentaje();
    this.conceptoIvaNombre = d.getRetencion().getConceptoIvaNombre();
    this.conceptoRentaNombre = d.getRetencion().getConceptoRentaNombre();
    this.ivaPorcentaje5 = d.getRetencion().getIvaPorcentaje5();
    this.ivaPorcentaje10 = d.getRetencion().getIvaPorcentaje10();
    this.monedaNombre = d.getRetencion().getMonedaNombre();
    //totales
    this.impuestoTotalExento = d.getTotales().getImpuestoTotalExento();
    this.impuestoTotalAl5 = d.getTotales().getImpuestoTotalAl5();
    this.impuestoTotalAl10 = d.getTotales().getImpuestoTotalAl10();
    this.valorTotalExento = d.getTotales().getValorTotalExento();
    this.valorTotalAl5 = d.getTotales().getValorTotalAl5();
    this.valorTotalAl10 = d.getTotales().getValorTotalAl10();
    this.impuestoTotal = d.getTotales().getImpuestoTotal();
    this.valorTotal = d.getTotales().getValorTotal();

    String[] anumero = r.getNumeroComprobante().split("-");

    this.fechaProceso = DateTime.parse(r.getFechaProceso(), DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:SSS"))
            .toDate();
    this.numeroComprobante = anumero[2];
    this.fechaEmision = LocalDate.parse(r.getFechaEmision(), DateTimeFormat.forPattern("yyyy-MM-dd")).toDate();
    this.cadenaControl = r.getCadenaControl();
    this.numero = anumero[2];
    this.fechaRecepcion = DateTime
            .parse(r.getFechaRecepcion(), DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:SSS")).toDate();
    this.hashString = r.getHash();
    this.recepcionCorrecta = r.getRecepcionCorrecta();
    this.mensajeRecepcion = r.getMensajeRecepcion();
    this.procesamientoCorrecto = r.getProcesamientoCorrecto();
    this.mensajeProcesamiento = r.getMensajeProcesamiento();
    this.migrado = false;
}

From source file:com.iniesta.ftests.stream.taxi.TaxiRide.java

License:Apache License

public static TaxiRide fromString(String line) {

    String[] tokens = line.split(",");
    if (tokens.length != 9) {
        throw new RuntimeException("Invalid record: " + line);
    }//from w  ww.  ja  va2s  .co  m

    TaxiRide ride = new TaxiRide();

    try {
        ride.rideId = Long.parseLong(tokens[0]);
        ride.time = DateTime.parse(tokens[1], timeFormatter);
        ride.startLon = tokens[3].length() > 0 ? Float.parseFloat(tokens[3]) : 0.0f;
        ride.startLat = tokens[4].length() > 0 ? Float.parseFloat(tokens[4]) : 0.0f;
        ride.endLon = tokens[5].length() > 0 ? Float.parseFloat(tokens[5]) : 0.0f;
        ride.endLat = tokens[6].length() > 0 ? Float.parseFloat(tokens[6]) : 0.0f;
        ride.passengerCnt = Short.parseShort(tokens[7]);
        ride.travelDistance = tokens[8].length() > 0 ? Float.parseFloat(tokens[8]) : 0.0f;

        if (tokens[2].equals("START")) {
            ride.isStart = true;
        } else if (tokens[2].equals("END")) {
            ride.isStart = false;
        } else {
            throw new RuntimeException("Invalid record: " + line);
        }

    } catch (NumberFormatException nfe) {
        throw new RuntimeException("Invalid record: " + line, nfe);
    }

    return ride;
}

From source file:com.kixeye.kixmpp.date.XmppDateUtils.java

License:Apache License

/**
  * Parse a string into a DateTime.//from w  ww .j a va 2s.  com
  * 
  * @param dateTime
  * @return
  */
public static DateTime parse(String dateTime) {
    return DateTime.parse(dateTime, xmppDateTimeFormatter);
}

From source file:com.ligadata.kamanja.financial.SubscriberUsageAlert.java

License:Apache License

private int getMonth(String dt) {
    DateTime jdt = DateTime.parse(dt, DateTimeFormat.forPattern("yyyyMMdd").withLocale(Locale.US));
    return jdt.monthOfYear().get();
}