Example usage for java.sql Date valueOf

List of usage examples for java.sql Date valueOf

Introduction

In this page you can find the example usage for java.sql Date valueOf.

Prototype

@SuppressWarnings("deprecation")
public static Date valueOf(LocalDate date) 

Source Link

Document

Obtains an instance of Date from a LocalDate object with the same year, month and day of month value as the given LocalDate .

Usage

From source file:org.openvpms.report.openoffice.OpenOfficeIMReportTestCase.java

/**
 * Tests reporting.//from   w  ww  .  j a va 2  s . co  m
 *
 * @throws IOException for any I/O error
 */
@Test
public void testReport() throws IOException {
    Document doc = getDocument("src/test/reports/act.customerEstimation.odt", DocFormats.ODT_TYPE);

    Functions functions = applicationContext.getBean(Functions.class);
    IMReport<IMObject> report = new OpenOfficeIMReport<IMObject>(doc, getArchetypeService(), getLookupService(),
            getHandlers(), functions);
    Map<String, Object> fields = new HashMap<String, Object>();
    Party practice = (Party) create(PracticeArchetypes.PRACTICE);
    practice.setName("Vets R Us");
    fields.put("OpenVPMS.practice", practice);

    Party party = createCustomer();
    ActBean act = createAct("act.customerEstimation");
    Date startTime = Date.valueOf("2006-08-04");
    act.setValue("startTime", startTime);
    act.setValue("lowTotal", new BigDecimal("100"));
    act.setParticipant("participation.customer", party);

    List<IMObject> objects = Arrays.asList((IMObject) act.getAct());
    Document result = report.generate(objects, null, fields, DocFormats.ODT_TYPE);
    Map<String, String> userFields = getUserFields(result);
    String expectedStartTime = DateFormat.getDateInstance(DateFormat.MEDIUM).format(startTime);
    assertEquals(expectedStartTime, userFields.get("startTime"));
    assertEquals("$100.00", userFields.get("lowTotal"));
    assertEquals("J", userFields.get("firstName"));
    assertEquals("Zoo", userFields.get("lastName"));
    assertEquals("2.00", userFields.get("expression"));
    assertEquals("1234 Foo St\nMelbourne VIC 3001", userFields.get("address"));
    assertEquals("Vets R Us", userFields.get("practiceName"));
    assertEquals("Invalid property name: invalid", userFields.get("invalid"));
}

From source file:cheladocs.controlo.DocumentoServlet.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("application/pdf; application/msword; application/excel");

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

    if (comando == null) {
        comando = "principal";
    }/*  w  w  w.j av  a2 s . c om*/

    DocumentoDAO documentoDAO;
    Documento documento = new Documento();

    if (comando == null || !comando.equalsIgnoreCase("principal")) {
        try {
            idDocumento = request.getParameter("numero_protocolo");
            if (idDocumento != null) {
                documento.setNumeroProtocolo(Integer.parseInt(idDocumento));
            }

        } catch (NumberFormatException ex) {
            System.err.println("Erro ao converter dado: " + ex.getMessage());
        }
    }

    try {

        documentoDAO = new DocumentoDAO();

        if (comando.equalsIgnoreCase("guardar")) {

            documento.getRequerente().setIdRequerente(Integer.parseInt(request.getParameter("requerente")));
            documento.setDataEntrada(Date.valueOf(request.getParameter("data_entrada")));
            documento.setOrigem(request.getParameter("origem_documento"));
            documento.setDescricaoAssunto(request.getParameter("descricao_assunto"));
            documento.getNaturezaAssunto()
                    .setIdNaturezaAssunto(Integer.parseInt(request.getParameter("natureza_assunto")));
            documento.getTipoExpediente()
                    .setIdTipoExpediente(Integer.parseInt(request.getParameter("tipo_expediente")));
            Part ficheiro = request.getPart("ficheiro");
            if (ficheiro != null) {
                byte[] ficheiroDados = IOUtils.toByteArray(ficheiro.getInputStream());
                documento.setConteudoDocumento(ficheiroDados);
                documento.setUrlFicheiroDocumento(ficheiro.getSubmittedFileName());
                doUpload(ficheiro, request);
            }
            documentoDAO.save(documento);
            response.sendRedirect("paginas/gerir_documento.jsp");

        } else if (comando.equalsIgnoreCase("editar")) {

            documento.setNumeroProtocolo(Integer.parseInt(request.getParameter("requerente")));

            documento.getRequerente().setIdRequerente(Integer.parseInt(request.getParameter("requerente")));
            documento.setDataEntrada(Date.valueOf(request.getParameter("data_entrada")));
            documento.setOrigem(request.getParameter("origem_documento"));
            documento.setDescricaoAssunto(request.getParameter("descricao_assunto"));
            documento.getNaturezaAssunto()
                    .setIdNaturezaAssunto(Integer.parseInt(request.getParameter("natureza_assunto")));
            documento.getTipoExpediente()
                    .setIdTipoExpediente(Integer.parseInt(request.getParameter("tipo_expediente")));
            Part ficheiro = request.getPart("ficheiro");
            if (ficheiro != null) {
                byte[] ficheiroDados = IOUtils.toByteArray(ficheiro.getInputStream());
                documento.setConteudoDocumento(ficheiroDados);
                documento.setUrlFicheiroDocumento(ficheiro.getSubmittedFileName());
                doUpload(ficheiro, request);
            }

            documentoDAO.update(documento);
            response.sendRedirect("paginas/gerir_documento.jsp");

        } else if (comando.equalsIgnoreCase("eliminar")) {
            documentoDAO.delete(documento);
            response.sendRedirect("paginas/gerir_documento.jsp");

        } else if (comando.equalsIgnoreCase("prepara_editar")) {
            documento = documentoDAO.findById(documento.getNumeroProtocolo());
            request.setAttribute("documento", documento);

            RequestDispatcher rd = request.getRequestDispatcher("paginas/documento_editar.jsp");
            rd.forward(request, response);
        } else if (comando.equalsIgnoreCase("listar")) {

            response.sendRedirect("paginas/gerir_documento.jsp");
        } else if (comando.equalsIgnoreCase("imprimir_todos") || comando.equalsIgnoreCase("imprimir_by_id")) {
            ReporteUtil reporte = new ReporteUtil();
            File caminhoRelatorio = null;
            HashMap hashMap = new HashMap();

            if (comando.equalsIgnoreCase("imprimir_todos")) {
                caminhoRelatorio = new File(getServletConfig().getServletContext()
                        .getRealPath("/WEB-INF/relatorios/DocumentoListar.jasper"));
                reporte.geraRelatorio(caminhoRelatorio.getPath(), hashMap, response);
            } else {
                hashMap.put("codigo_documento", Integer.parseInt(idDocumento));
                caminhoRelatorio = new File(getServletConfig().getServletContext()
                        .getRealPath("/WEB-INF/relatorios/Ficha_Documento.jasper"));
                reporte.geraRelatorio(caminhoRelatorio.getPath(), hashMap, response);
            }
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:svc.data.citations.datasources.mock.MockCitationDataSource.java

@Override
public List<Citation> getByNameAndMunicipalitiesAndDOB(String lastName, List<Long> municipalities,
        LocalDate dob) {//w  w  w.ja  v  a  2s  .  c  o m
    try {
        Map<String, Object> parameterMap = new HashMap<>();
        parameterMap.put("lastName", lastName.toLowerCase());
        parameterMap.put("dob", Date.valueOf(dob));
        parameterMap.put("municipalities", municipalities);

        List<Citation> citations = jdbcTemplate.query(getSql("citation/get-by-location.sql"), parameterMap,
                new CitationSQLMapper());

        return populateViolations(citations);
    } catch (Exception e) {
        LogSystem.LogDBException(e);
        return null;
    }
}

From source file:edu.cornell.kfs.fp.businessobject.USBankRecordFieldUtils.java

/**
 * Extracts a Date from a substring less any ending whitespace for a given beginning and ending position.
 * //  w w w. j a va 2 s  . c  om
 * @param line Superstring
 * @param begin Beginning index
 * @param end Ending index
 * @param lineCount The current line number
 * @return The Date parsed from the trimmed substring
 * @throws ParseException When unable to parse the date
 */
public static Date extractDate(String line, int begin, int end, int lineCount) throws ParseException {
    Date theDate;
    try {
        String sub = line.substring(begin, end);
        String year = sub.substring(0, 4);
        String month = sub.substring(4, 6);
        String day = sub.substring(6, 8);
        theDate = Date.valueOf(year + "-" + month + "-" + day);
    } catch (StringIndexOutOfBoundsException | IllegalArgumentException e) {
        // May encounter a StringIndexOutOfBoundsException if the string bounds do not match or 
        // an IllegalArgumentException if the Date does not parse correctly
        throw new ParseException(
                "Unable to parse date from the value " + line.substring(begin, end) + " on line " + lineCount,
                lineCount);
    }
    return theDate;
}

From source file:org.rti.zcore.dar.struts.action.report.StockChangesAction.java

/**
 * Process the specified HTTP request, and create the corresponding HTTP
 * response (or forward to another web component that will create it).
 * Return an <code>ActionForward</code> instance describing where and how
 * control should be forwarded, or <code>null</code> if the response has
 * already been completed./*from   ww w  .  j av  a  2 s. c o m*/
 *
 * @param mapping  The ActionMapping used to select this instance
 * @param form     The optional ActionForm bean for this request (if any)
 * @param request  The HTTP request we are processing
 * @param response The HTTP response we are creating
 * @return Action to forward to
 * @throws Exception if an input/output error or servlet exception occurs
 */
protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Connection conn = DatabaseUtils.getAdminConnection();
    Long itemId = null;
    int siteId = 0;
    Date beginDate = null;
    Date endDate = null;
    String code = null;
    if (request.getParameter("code") != null) {
        code = request.getParameter("code");
    }
    if (request.getParameter("itemId") != null && !request.getParameter("itemId").equals("")) {
        itemId = Long.valueOf(request.getParameter("itemId"));
    }
    if (request.getParameter("siteId") != null) {
        siteId = Integer.valueOf(request.getParameter("siteId"));
    }
    if (request.getParameter("beginDate") != null) {
        beginDate = Date.valueOf(String.valueOf(request.getParameter("beginDate")));
    }
    if (request.getParameter("endDate") != null) {
        endDate = Date.valueOf(String.valueOf(request.getParameter("endDate")));
    }
    beginDate = Date.valueOf("1900-01-01");
    endDate = DateUtils.getNow();

    boolean redirectError = false;
    if (itemId == null) {
        if (code != null) {
            // Create a map with Item id, name
            ArrayList<Item> items = (ArrayList<Item>) EncountersDAO.getAll(conn, Long.valueOf(131),
                    "SQL_RETRIEVE_ALL_ADMIN_PAGER131", Item.class);
            for (Item item : items) {
                String itemCode = item.getCode();
                if (code.equals(itemCode)) {
                    itemId = item.getId();
                }
            }
            if (itemId == null) {
                redirectError = true;
            }
        } else {
            redirectError = true;
        }
    }
    if (redirectError) {
        request.setAttribute("exception",
                "Unable to find itemID for this item. ItemId: " + itemId + "; code: " + code);
        return mapping.findForward("error");
    }
    List<StockControl> stockChanges = InventoryDAO.getStockEncounterChanges(conn, itemId, siteId, beginDate,
            endDate, null, null);
    StockReport stockReport = InventoryDAO.generateStockSummary(conn, itemId, beginDate, stockChanges, false);
    //int size = stockChanges.size();
    /*stockChanges.add(size,stockControlAdditions);
    stockChanges.add(size+1,stockControlDeletions);
    stockChanges.add(size+2,stockControlIssued);*/

    request.setAttribute("stockReport", stockReport);
    // request.setAttribute("stockControlIssuedTotal", stockControlIssuedTotal);
    request.setAttribute("stockChanges", stockChanges);
    // request.setAttribute("beginDate", beginDate);
    request.setAttribute("endDate", endDate);
    Class itemClazz = Class.forName("org.rti.zcore.dar.gen.Item");
    Item stockItem = (Item) EncountersDAO.getOne(conn, itemId, "SQL_RETRIEVE_ONE_ADMIN131", itemClazz);
    String detailName = stockItem.getName();
    request.setAttribute("detailName", detailName);
    return mapping.findForward("success");
}

From source file:cz.muni.fi.javaseminar.kafa.bookregister.BookManagerImpl.java

@Override
@Transactional(readOnly = false)/* w  w w  . ja v  a  2  s . co m*/
public void createBook(Book book) {
    validate(book);
    if (book.getId() != null) {
        throw new IllegalArgumentException("book id is already set");
    }

    KeyHolder keyHolder = new GeneratedKeyHolder();
    int updated = jdbcTemplate.update((Connection connection) -> {
        PreparedStatement ps = connection.prepareStatement(
                "INSERT INTO BOOK (name,isbn,published,author_id) VALUES (?,?,?,?)",
                Statement.RETURN_GENERATED_KEYS);
        ps.setString(1, book.getName());
        ps.setString(2, book.getIsbn());
        Date date = Date.valueOf(book.getPublished());
        ps.setDate(3, date);
        if (book.getAuthorId() == null) {
            ps.setNull(4, Types.BIGINT);
        } else {
            ps.setLong(4, book.getAuthorId());
        }
        return ps;
    }, keyHolder);

    book.setId(keyHolder.getKey().longValue());

    DBUtils.checkUpdatesCount(updated, book, true);
}

From source file:com.impetus.kundera.property.accessor.SQLDateAccessor.java

@Override
public Date fromString(Class targetClass, String s) {

    if (s == null) {
        return null;
    }//from   ww w.j  a v a 2 s .c o  m
    if (StringUtils.isNumeric(s)) {
        return new Date(Long.parseLong(s));
    }
    Date d = Date.valueOf(s);
    return d;
}

From source file:com.cnd.greencube.web.base.filter.parameter.converter.SqlDateConverter.java

/**
 * Convert the specified input object into an output object of the specified
 * type./*from   w ww.j  a  va2s .c  o  m*/
 * 
 * @param type Data type to which this value should be converted
 * @param value The input value to be converted
 * @exception ConversionException if conversion cannot be performed
 *                successfully
 */
public Object convert(Class type, Object value) {
    if (value == null) {
        if (useDefault) {
            return (defaultValue);
        } else {
            throw new ConversionException("No value specified");
        }
    }
    if (value instanceof Date) {
        return (value);
    }

    String sDate = value.toString().trim();
    // null
    if (sDate.length() == 0) {
        if (useDefault) {
            return (defaultValue);
        } else {
            throw new ConversionException("No value specified");
        }
    }

    try {
        return (Date.valueOf(sDate));
    } catch (Exception e) {
        if (useDefault) {
            return (defaultValue);
        } else {
            throw new ConversionException(e);
        }
    }

}

From source file:org.rti.zcore.dar.dao.PersistenceDAOImpl.java

/**
 * Updates non-patient values and accommodates other situations where you need to refresh the SessionPatient.
 * @param conn//from w  w  w.  j a va 2  s . c o m
 * @param formFieldId
 * @param encounter
 * @param value
 * @param session
 * @throws SQLException
 * @throws ServletException
 */
public void updateValues(Connection conn, int formFieldId, BaseEncounter encounter, Object value,
        HttpSession session) throws SQLException, ServletException {

    switch (formFieldId) {
    case 2244: // Expiry Date
        try {
            Date expiryDate = Date.valueOf((String) value);
            StockControl sc = (StockControl) encounter;
            sc.setExpiry_date(expiryDate);
            // check if the expiry date if within the limits. Remove from the roll if it is.
            Long itemId = sc.getItem_id();
            Long siteId = encounter.getSiteId();
            // refreshes the StockAlertList.
            StockControlDAO.prepareStockforAlertList(conn, sc, null, itemId);
        } catch (ObjectNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassCastException e1) {
            log.debug(e1);
        }
        break;
    case 201: // Patient status type of change

        if (session != null) {
            //clear the session data from the previous patient.
            SessionUtil.getInstance(session).setSessionPatient(null);
            // load the sessionPatient
            try {
                SessionSubject sessionPatient = SessionPatientDAO.updateSessionPatient(conn,
                        encounter.getPatientId(), encounter.getEventUuid(), session);
            } catch (AttributeNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ObjectNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        break;
    }
}

From source file:com.github.binarywang.demo.spring.controller.WebController.java

/**
 * 8:30 ~ 11:30/*from   ww  w .j a  v a  2 s  .co  m*/
 * 2:00 ~ 4:00
 * 5 vehicles per hour
 * ???2
 * ?2
 * ?
 * @param session
 * @param file1
 * @param name
 * @param chepai
 * @param date
 * @param tel
 * @param file2
 * @return
 */
@RequestMapping("/uploader/yuyue")
@ResponseBody
public Map<String, Object> yuyue(HttpSession session,
        @RequestParam(name = "file1", required = false) MultipartFile file1,
        @RequestParam(name = "name", required = true) String name,
        @RequestParam(name = "chepai", required = true) String chepai,
        @RequestParam(name = "date", required = true) String date,
        @RequestParam(name = "tel", required = true) String tel,
        @RequestParam(name = "file2", required = false) MultipartFile file2,
        @RequestParam(name = "serverId", required = true) String serverId,
        @RequestParam(name = "time", required = true) int time) throws ParseException {
    Map<String, Object> ret = new HashMap<String, Object>();
    Date date1 = Date.valueOf(date);
    if (date1.before(Calendar.getInstance().getTime()) || date1.equals(Calendar.getInstance().getTime())) {
        ret.put("success", false);
        ret.put("reason", "????1-7");
        return ret;
    }
    if (wxService.getDayCounter().getCount(Calendar.getInstance().getTime(), date1) > 7) {
        ret.put("success", false);
        ret.put("reason", "?7");
        return ret;
    }
    if (wxService.getDayCounter().getCount(Calendar.getInstance().getTime(), date1) < 1) {
        ret.put("success", false);
        ret.put("reason", "???");
        return ret;
    }
    if (wxService.getDayCounter().isHoliday(date1)) {
        ret.put("success", false);
        ret.put("reason", "????");
        return ret;
    }
    WxMpUser wxMpUser = (WxMpUser) session.getAttribute("userOpenId");
    if (wxMpUser == null) {
        ret.put("success", false);
        ret.put("reason", "");
        return ret;
    }
    if (appointmentDao.findInOrderingAppointmentByOpenId(wxMpUser.getOpenId()).size() > 0) {
        ret.put("success", false);
        ret.put("reason", "??");
        return ret;
    }
    if (appointmentDao.isInBlackList(tel, wxMpUser.getOpenId())) {
        ret.put("success", false);
        ret.put("reason", "3????");
    }
    if (appointmentDao.findCountByOpenId(wxMpUser.getOpenId()) > 2) {
        ret.put("success", false);
        ret.put("reason", "???");
        return ret;
    }
    if (appointmentDao.findCountByTel(tel) > 2) {
        ret.put("success", false);
        ret.put("reason", "???");
        return ret;
    }

    if (appointmentDao.countForDay(date, time) >= 15 && time == 0) {
        ret.put("success", false);
        ret.put("reason", "??");
        return ret;
    }
    if (appointmentDao.countForDay(date, time) >= 10 && time == 1) {
        ret.put("success", false);
        ret.put("reason", "??");
        return ret;
    }

    Appointment appointment = new Appointment();
    appointment.setName(wxMpUser.getNickname());
    appointment.setOpenId(wxMpUser.getOpenId());
    appointment.setRealName(name);
    appointment.setChepai(chepai);
    appointment.setDate(date1);
    appointment.setDriverLicense("");
    appointment.setTel(tel);
    appointment.setServerId(serverId);
    appointment.setTime(time);
    appointmentDao.save(appointment);
    ret.put("success", true);
    return ret;
}