Example usage for org.joda.time.format DateTimeFormatter parseDateTime

List of usage examples for org.joda.time.format DateTimeFormatter parseDateTime

Introduction

In this page you can find the example usage for org.joda.time.format DateTimeFormatter parseDateTime.

Prototype

public DateTime parseDateTime(String text) 

Source Link

Document

Parses a date-time from the given text, returning a new DateTime.

Usage

From source file:com.vimbox.hr.CreateEmployeeController.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w w  w.  j ava  2 s.  c o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json;charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd");
    JsonObject jsonOutput = new JsonObject();

    // Validating fields //
    String errorMsg = "";

    String employeeType = request.getParameter("employeeType");
    if (employeeType == null) {
        errorMsg += "Please select the employee type";
    } else {
        String user_first_name = request.getParameter("user_first_name");
        String user_last_name = request.getParameter("user_last_name");
        if (user_first_name.isEmpty()) {
            errorMsg += "Please enter employee's first name<br>";
        }
        if (user_last_name.isEmpty()) {
            errorMsg += "Please enter employee's last name<br>";
        }

        String user_nric = request.getParameter("user_nric");
        if (user_nric.isEmpty()) {
            errorMsg += "Please enter employee's NRIC<br>";
        } else {
            boolean exist = UserDAO.checkNric(user_nric);
            if (exist) {
                errorMsg += "An employee has been created under the same NRIC<br>";
            }
        }

        String user_dj = request.getParameter("user_dj");
        Date dj = null;
        if (user_dj.isEmpty()) {
            errorMsg += "Please enter employee's date joined<br>";
        } else {
            try {
                dj = format.parse(user_dj);

                DateTime employee_dateJoined = dtf.parseDateTime(user_dj);
                DateTime now_date = new DateTime();
                if (now_date.isBefore(employee_dateJoined)) {
                    errorMsg += "Employee's date joined cannot be a future date<br>";
                }
            } catch (Exception e) {
                errorMsg += "Please enter a valid employee's date joined<br>";
            }
        }

        String user_madd = request.getParameter("user_madd");
        if (user_madd.isEmpty()) {
            errorMsg += "Please enter employees's mailing address<br>";
        }

        String user_radd = request.getParameter("user_radd");

        boolean phoneEmpty = false;
        String user_phone = request.getParameter("user_phone");
        if (user_phone.isEmpty()) {
            phoneEmpty = true;
            user_phone = "0";
        } else {
            if (user_phone.length() < 8) {
                errorMsg += "Please enter a valid phone number<br>";
            }
        }

        String user_fax = request.getParameter("user_fax");
        if (user_fax.isEmpty()) {
            user_fax = "0";
        } else {
            if (user_fax.length() < 8) {
                errorMsg += "Please enter a valid fax number<br>";
            }
        }

        boolean homeEmpty = false;
        String user_home = request.getParameter("user_home");
        if (user_home.isEmpty()) {
            homeEmpty = true;
            user_home = "0";
        } else {
            if (user_home.length() < 8) {
                errorMsg += "Please enter a valid home number<br>";
            }
        }

        if (phoneEmpty && homeEmpty) {
            errorMsg += "Please enter either a phone or home number<br>";
        }

        ApplicationPart filePart = (ApplicationPart) request.getPart("driverLicense");
        String fileName = "";
        String path = "";

        if (filePart != null) {
            String fName = filePart.getSubmittedFileName();
            if (fName != null) {
                boolean fileCheck = fileValidation(filePart);
                if (!fileCheck) {
                    errorMsg += "Please upload a valid file (png, jpg, bmp or pdf)<br>";
                } else {
                    String fileExt = fName.substring(fName.lastIndexOf("."));
                    fileName = user_nric + "-driver-license" + fileExt;
                    path = System.getProperty("user.dir") + "/documents/licenses/" + fileName;
                }
            }
        }

        String user_designation = request.getParameter("user_designation");
        String user_department = "";
        String fullTime = request.getParameter("fulltime_user_department");
        String partTime = request.getParameter("parttime_user_department");
        if (user_designation == null) {
            errorMsg += "Please enter employee's department<br>";
        } else {
            if (fullTime == null) {
                user_department = partTime;
            } else {
                user_department = fullTime;
            }
        }

        String user_salary = request.getParameter("user_salary");
        if (user_salary.isEmpty()) {
            errorMsg += "Please enter the employee's basic salary<br>";
        }

        String emergency_name = request.getParameter("emergency_name");

        String emergency_relationship = request.getParameter("emergency_relationship");

        String emergency_contact = request.getParameter("emergency_contact");
        if (emergency_contact.isEmpty()) {
            emergency_contact = "0";
        }

        String emergency_office = request.getParameter("emergency_office");
        if (emergency_office.isEmpty()) {
            emergency_office = "0";
        }

        String user_username = null;
        String user_password = null;
        if (employeeType.equals("Full")) {
            user_username = request.getParameter("user_username");
            user_password = request.getParameter("user_password");
        }
        if (user_username != null && !user_username.contains("@")) {
            errorMsg += "Please enter a valid email address<br>";
        } else {
            boolean exist = UserDAO.checkUsername(user_username);
            if (exist) {
                errorMsg += "An account has been created under the same username<br>";
            }
        }
        if (user_password != null && user_password.isEmpty()) {
            errorMsg += "Please enter a password<br>";
        }

        String user_payment_mode = request.getParameter("user_payment");

        String user_bank_name = request.getParameter("user_bank_name");
        if (user_bank_name.isEmpty()) {
            errorMsg += "Please enter employee's bank name<br>";
        }

        String user_account_name = request.getParameter("user_account_name");
        if (user_account_name.isEmpty()) {
            errorMsg += "Please enter employee's account name<br>";
        }

        String user_account_no = request.getParameter("user_account_no");
        if (user_account_no.isEmpty()) {
            errorMsg += "Please enter employee's account number<br>";
        }

        if (errorMsg.isEmpty()) {
            OutputStream outpt = null;
            InputStream filecontent = null;
            try {
                if (!path.isEmpty()) {
                    outpt = new FileOutputStream(new File(path));
                    filecontent = filePart.getInputStream();

                    int read = 0;
                    final byte[] bytes = new byte[1024];

                    while ((read = filecontent.read(bytes)) != -1) {
                        outpt.write(bytes, 0, read);
                    }
                }

                UserDAO.createUser(user_nric, user_first_name, user_last_name, dj, user_madd, user_radd,
                        fileName, user_department, user_designation, Integer.parseInt(user_salary),
                        employeeType);
                UserDAO.createUserContact(user_nric, Integer.parseInt(user_phone), Integer.parseInt(user_fax),
                        Integer.parseInt(user_home));
                UserDAO.createUserEmergency(user_nric, emergency_name, emergency_relationship,
                        Integer.parseInt(emergency_contact), Integer.parseInt(emergency_office));
                UserDAO.createUserBank(user_nric, user_payment_mode, user_bank_name, user_account_name,
                        user_account_no);
                if (employeeType.equals("Full")) {
                    UserDAO.createUserAccount(user_nric, user_username, user_password);
                    UserDAO.createUserLeave(user_nric, dj);
                }

                jsonOutput.addProperty("status", "SUCCESS");
                jsonOutput.addProperty("message", "Employee added!");
            } catch (FileNotFoundException fne) {
                errorMsg += "Error reading uploaded image<br>";
            } finally {
                if (outpt != null) {
                    outpt.close();
                }
                if (filecontent != null) {
                    filecontent.close();
                }
            }
        }
    }

    if (!errorMsg.isEmpty()) {
        jsonOutput.addProperty("status", "ERROR");
        jsonOutput.addProperty("message", errorMsg);
    }
    out.println(jsonOutput);
}

From source file:com.vmware.photon.controller.model.adapters.azure.stats.AzureComputeStatsGatherer.java

License:Open Source License

/**
 * Get the metric definitions from Azure using the Endpoint "/metricDefinitions"
 * The request and response of the API is as described in
 * {@link https://msdn.microsoft.com/en-us/library/azure/dn931939.aspx} Insights REST.
 * @param statsData/*from  w w  w . j  a  va  2 s .c o  m*/
 * @throws URISyntaxException
 * @throws IOException
 */
private void getMetricDefinitions(AzureStatsDataHolder statsData) throws URISyntaxException, IOException {
    String azureInstanceId = statsData.computeDesc.id;
    URI uri = UriUtils.buildUri(new URI(AzureConstants.BASE_URI_FOR_REST), azureInstanceId,
            AzureConstants.METRIC_DEFINITIONS_ENDPOINT);
    // Adding a filter to avoid huge data flow on the network
    /*
     * VSYM-656: https://jira-hzn.eng.vmware.com/browse/VSYM-656
     * Remove the filter when Unit of a metric is required.
     */
    uri = UriUtils.extendUriWithQuery(uri, AzureConstants.QUERY_PARAM_API_VERSION,
            AzureConstants.DIAGNOSTIC_SETTING_API_VERSION, AzureConstants.QUERY_PARAM_FILTER,
            AzureConstants.METRIC_DEFINITIONS_MEMORY_FILTER);
    Operation operation = Operation.createGet(uri);
    operation.addRequestHeader(Operation.ACCEPT_HEADER, Operation.MEDIA_TYPE_APPLICATION_JSON);
    operation.addRequestHeader(Operation.AUTHORIZATION_HEADER,
            AzureConstants.AUTH_HEADER_BEARER_PREFIX + statsData.credentials.getToken());
    operation.setCompletion((op, ex) -> {
        if (ex != null) {
            AdapterUtils.sendFailurePatchToProvisioningTask(this, statsData.statsRequest.taskReference, ex);
        }
        MetricDefinitions metricDefinitions = op.getBody(MetricDefinitions.class);
        DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(AzureConstants.METRIC_TIME_FORMAT);
        if (metricDefinitions.getValues() != null && !metricDefinitions.getValues().isEmpty()) {
            for (MetricAvailability metricAvailability : metricDefinitions.getValues().get(0)
                    .getMetricAvailabilities()) {
                if (metricAvailability.getTimeGrain().equals(AzureConstants.METRIC_TIME_GRAIN_1_MINUTE)) {
                    Location location = metricAvailability.getLocation();
                    Date mostRecentTableDate = null;
                    for (TableInfo tableInfo : location.getTableInfo()) {
                        Date startDate = dateTimeFormatter.parseDateTime(tableInfo.getStartTime()).toDate();
                        if (mostRecentTableDate == null || startDate.after(mostRecentTableDate)) {
                            mostRecentTableDate = startDate;
                            statsData.tableName = tableInfo.getTableName();
                        }
                    }
                    statsData.partitionValue = location.getPartitionKey();
                }
            }
        }
        if (statsData.tableName != null && statsData.tableName.length() > 0) {
            try {
                getMetrics(statsData);
            } catch (Exception e) {
                AdapterUtils.sendFailurePatchToProvisioningTask(this, statsData.statsRequest.taskReference, e);
            }
        } else {
            patchEmptyResponse(statsData);
        }
    });
    sendRequest(operation);
}

From source file:com.vmware.photon.controller.model.adapters.azure.stats.AzureStatsService.java

License:Open Source License

/**
 * Get the metric definitons from Azure using the Endpoint "/metricDefinitions"
 * The request and response of the API is as described in
 * {@link https://msdn.microsoft.com/en-us/library/azure/dn931939.aspx} Insights REST.
 * @param statsData/*w  ww.j av  a2s .c  o m*/
 * @throws URISyntaxException
 * @throws IOException
 */
private void getMetricDefinitions(AzureStatsDataHolder statsData) throws URISyntaxException, IOException {
    String azureInstanceId = statsData.computeDesc.id;
    URI uri = UriUtils.buildUri(new URI(AzureConstants.BASE_URI_FOR_REST), azureInstanceId,
            AzureConstants.METRIC_DEFINITIONS_ENDPOINT);
    // Adding a filter to avoid huge data flow on the network
    /*
     * VSYM-656: https://jira-hzn.eng.vmware.com/browse/VSYM-656
     * Remove the filter when Unit of a metric is required.
     */
    uri = UriUtils.extendUriWithQuery(uri, AzureConstants.QUERY_PARAM_API_VERSION,
            AzureConstants.DIAGNOSTIC_SETTING_API_VERSION, AzureConstants.QUERY_PARAM_FILTER,
            AzureConstants.METRIC_DEFINITIONS_MEMORY_FILTER);
    Operation operation = Operation.createGet(uri);
    operation.addRequestHeader(Operation.ACCEPT_HEADER, Operation.MEDIA_TYPE_APPLICATION_JSON);
    operation.addRequestHeader(Operation.AUTHORIZATION_HEADER,
            AzureConstants.AUTH_HEADER_BEARER_PREFIX + statsData.credentials.getToken());
    operation.setCompletion((op, ex) -> {
        if (ex != null) {
            AdapterUtils.sendFailurePatchToProvisioningTask(this, statsData.statsRequest.taskReference, ex);
        }
        MetricDefinitions metricDefinitions = op.getBody(MetricDefinitions.class);
        DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(AzureConstants.METRIC_TIME_FORMAT);
        if (metricDefinitions.getValues() != null && !metricDefinitions.getValues().isEmpty()) {
            for (MetricAvailability metricAvailability : metricDefinitions.getValues().get(0)
                    .getMetricAvailabilities()) {
                if (metricAvailability.getTimeGrain().equals(AzureConstants.METRIC_TIME_GRAIN_1_MINUTE)) {
                    Location location = metricAvailability.getLocation();
                    Date mostRecentTableDate = null;
                    for (TableInfo tableInfo : location.getTableInfo()) {
                        Date startDate = dateTimeFormatter.parseDateTime(tableInfo.getStartTime()).toDate();
                        if (mostRecentTableDate == null || startDate.after(mostRecentTableDate)) {
                            mostRecentTableDate = startDate;
                            statsData.tableName = tableInfo.getTableName();
                        }
                    }
                    statsData.partitionValue = location.getPartitionKey();
                }
            }
        }
        if (!StringUtils.isEmpty(statsData.tableName)) {
            try {
                getMetrics(statsData);
            } catch (Exception e) {
                AdapterUtils.sendFailurePatchToProvisioningTask(this, statsData.statsRequest.taskReference, e);
            }
        } else {
            // Patch back to the Parent with empty response
            ComputeStatsResponse respBody = new ComputeStatsResponse();
            statsData.statsResponse.computeLink = statsData.computeDesc.documentSelfLink;
            respBody.taskStage = statsData.statsRequest.nextStage;
            respBody.statsList = new ArrayList<>();
            this.sendRequest(Operation.createPatch(statsData.statsRequest.taskReference).setBody(respBody));
        }
    });
    sendRequest(operation);
}

From source file:com.wlami.mibox.server.services.MetadataNotifier.java

License:Open Source License

/**
 * Get an array of all metadata filenames which have been updated since the
 * specified datetime. Used for synchronization of metadata.
 * /*from  ww w.  j av  a 2 s . c o  m*/
 * @param datetimeAsString
 *            Only names of metadata files which have been updated since
 *            this datetime will be returned.
 * @return An array of new updated metadata filenames.
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
public JSONArray listUpdatedMetadataSince(@PathParam("datetime") String datetimeAsString,
        @Context HttpHeaders headers) {
    // Check whether user is properly logged in
    User user = HttpHeaderUtil.getUserFromHttpHeaders(headers, em);
    if (user == null) {
        throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build());
    }

    DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.basicDateTime();
    DateTime datetime = null;
    try {
        datetime = dateTimeFormatter.parseDateTime(datetimeAsString);
    } catch (IllegalArgumentException e) {
        log.warn("listUpdatedMetadataSince: Date time format not recognized!", e.getMessage());
        throw new WebApplicationException(
                Response.status(Status.BAD_REQUEST).entity("Could not parse date").build());
    }
    List<String> names = user.getByLastUpdatedSince(datetime, em);
    return new JSONArray(names);
}

From source file:com.wookler.server.river.MessageBlockBackup.java

License:Apache License

private long windowtime(File dir) throws BlockBackupException {
    String dts = windowdir(dir);/*from   w w  w . ja  v a 2 s  . c om*/

    if (!StringUtils.isEmpty(dts)) {
        try {
            DateTimeFormatter fmt = DateTimeFormat.forPattern(Constants.DIR_DATETIME_FORMAT);
            DateTime t = fmt.parseDateTime(dts);

            return t.getMillis();
        } catch (IllegalArgumentException e) {
            return -1;
        }
    }
    return -1;
}

From source file:com.wso2telco.dep.reportingservice.dao.BillingDAO.java

License:Open Source License

/**
 * Convert to local time./* w ww  .  jav a 2 s  . c  o  m*/
 *
 * @param timeOffset the time offset
 * @param time the time
 * @return the string
 */
public String convertToLocalTime(String timeOffset, String time) {
    Integer offsetValue = Integer.parseInt(timeOffset);

    log.debug("Offset value = " + offsetValue);
    DateTimeZone systemTimeZone = DateTimeZone.getDefault();
    log.debug("system time zone " + systemTimeZone.toString());
    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
    DateTime systemDateTime = formatter.parseDateTime(time);
    log.debug("system date time " + systemDateTime.toString());
    systemDateTime = systemDateTime.withZoneRetainFields(systemTimeZone);
    log.debug("system date time after adding systemtimezone === " + systemDateTime.toString());

    int hours = -1 * offsetValue / 60;
    int minutes = offsetValue % 60;
    minutes = Math.abs(minutes);

    DateTimeZone localTimeZone = DateTimeZone.forOffsetHoursMinutes(hours, minutes);

    log.debug("Local time zone ==== " + localTimeZone.toString());

    DateTime convertedDateTime = systemDateTime.withZone(localTimeZone);

    String convertedDateTimeString = formatter.print(convertedDateTime);

    log.debug("converted time  :" + convertedDateTimeString);

    return convertedDateTimeString;

}

From source file:com.yahoo.sql4d.TimeUtils.java

License:Open Source License

public static DateTime tryFormat(String timeStr, DateTimeFormatter formatter) {
    DateTime result = null;/*w  w w  .j a v a  2s. co  m*/
    try {
        result = formatter.parseDateTime(timeStr);
    } catch (UnsupportedOperationException | IllegalArgumentException e) {
        //TODO: Log this instead of dumping to console.
        //System.err.println("Date Format error " + e);
    }
    return result;
}

From source file:com.yahoo.sql4d.TimeUtils.java

License:Open Source License

public static String tryAndGetFormat(String timeStr, DateTimeFormatter formatter) {
    String result = null;//from w w w. j  a v  a  2s  . c  om
    try {
        formatter.parseDateTime(timeStr);
        result = formatterMap.get(formatter);
    } catch (UnsupportedOperationException | IllegalArgumentException e) {
        //TODO: Log this instead of dumping to console.
        //System.err.println("Date Format error " + e);
    }
    return result;
}

From source file:controllers.ReporteFechaController.java

public ModelAndView buscarEnHistorialFechas(Request request, Response response) {
    ResultSet rs;// w ww .  j a  v  a 2s .  c o  m
    List<Busqueda> listaF = RepoBusquedas.GetInstancia().getListaBusqueda();
    RepoBusquedas.GetInstancia().setListaBusqueda("vacia");
    try {
        String queryBusquedas = "SELECT * FROM busquedas ORDER BY fechayhora";
        Statement st = UsuarioController.GetInstancia().getConexion().getConexion().createStatement();
        rs = st.executeQuery(queryBusquedas);
        if (!rs.equals(null)) {
            int i = 0;
            while (rs.next()) {
                String fecha = rs.getString("fechayhora");
                org.joda.time.format.DateTimeFormatter format = DateTimeFormat
                        .forPattern("yyyy-MM-dd HH:mm:ss.S");
                DateTime time = format.parseDateTime(fecha);
                String usuario = rs.getString("usuario");
                String parametros = rs.getString("parametros");
                int cantresultados = rs.getInt("cantresultados");
                String poisresultados = rs.getString("poisresultado");
                Busqueda bus = new Busqueda(time, usuario, parametros, cantresultados, poisresultados);
                RepoBusquedas.GetInstancia().addBusqueda(bus);
                listaF = RepoBusquedas.GetInstancia().getListaBusqueda();
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }

    ReportePorFecha reporte = new ReportePorFecha();

    DateTime fechaAnterior = listaF.get(0).getFechaYhora();
    int cantBusquedas = 0;
    Iterator<Busqueda> iterator = listaF.listIterator();
    while (iterator.hasNext()) {
        // Consigo el proximo elemento
        Busqueda actual = iterator.next();

        // si la fecha coincide incremento, sino, pase a otra fecha: agrego
        // la entrada y vuelvo a 0 la cantBusquedas
        if (actual.mismaFecha(fechaAnterior)) {
            cantBusquedas++;
        } else {
            reporte.agregarEntrada(fechaAnterior, cantBusquedas);
            cantBusquedas = 1;// cambie a cero por uno
            fechaAnterior = actual.getFechaYhora();
        }
    }
    // quedo una fecha sin agregar
    reporte.agregarEntrada(fechaAnterior, cantBusquedas);

    String str = construirStringLista(reporte.getInfoReporte());
    response.redirect(str);

    return null;

}

From source file:controllers.ReporteUsuarioController.java

public ModelAndView buscarEnHistorialUsuario(Request request, Response response) {
    ResultSet rs;/*from   w  ww . j  a  v  a  2s  . c  om*/
    List<Busqueda> busquedas = RepoBusquedas.GetInstancia().getListaBusqueda();
    RepoBusquedas.GetInstancia().setListaBusqueda("vacia");
    try {
        String queryBusquedas = "SELECT * FROM busquedas ORDER BY usuario";
        Statement st = UsuarioController.GetInstancia().getConexion().getConexion().createStatement();
        rs = st.executeQuery(queryBusquedas);
        if (!rs.equals(null)) {
            int i = 0;
            while (rs.next()) {
                String fecha = rs.getString("fechayhora");
                org.joda.time.format.DateTimeFormatter format = DateTimeFormat
                        .forPattern("yyyy-MM-dd HH:mm:ss.S");
                DateTime time = format.parseDateTime(fecha);
                String usuario = rs.getString("usuario");
                String parametros = rs.getString("parametros");
                int cantresultados = rs.getInt("cantresultados");
                String poisresultados = rs.getString("poisresultado");
                Busqueda bus = new Busqueda(time, usuario, parametros, cantresultados, poisresultados);
                RepoBusquedas.GetInstancia().addBusqueda(bus);
                busquedas = RepoBusquedas.GetInstancia().getListaBusqueda();
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    List<Busqueda> busquedasOrdenadas = ordenarBusquedas(busquedas);
    ReportePorTerminal reporte = new ReportePorTerminal();
    Busqueda busquedaAnterior = busquedasOrdenadas.get(0);
    int cantResultados = 0;
    Iterator<Busqueda> iterator = busquedasOrdenadas.listIterator();
    while (iterator.hasNext()) {
        Busqueda actual = iterator.next();
        if (actual.mismaTerminal(busquedaAnterior)) {
            cantResultados = cantResultados + actual.getCantResultados();
        } else {
            reporte.agregarEntrada(busquedaAnterior.getUsuario(), cantResultados);
            cantResultados = actual.getCantResultados();
            busquedaAnterior = actual;
        }
    }
    reporte.agregarEntrada(busquedaAnterior.getUsuario(), cantResultados);
    String str = construirStringLista(reporte.getInfoReporte());
    response.redirect(str);
    return null;
}