Example usage for java.sql Timestamp Timestamp

List of usage examples for java.sql Timestamp Timestamp

Introduction

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

Prototype

public Timestamp(long time) 

Source Link

Document

Constructs a Timestamp object using a milliseconds time value.

Usage

From source file:isl.FIMS.servlet.imports.ImportVocabulary.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    this.initVars(request);
    String username = getUsername(request);

    Config conf = new Config("AdminVoc");

    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    StringBuilder xml = new StringBuilder(
            this.xmlStart(this.topmenu, username, this.pageTitle, this.lang, "", request));
    String file = request.getParameter("file");

    if (ServletFileUpload.isMultipartContent(request)) {
        // configures some settings
        String filePath = this.export_import_Folder;
        java.util.Date date = new java.util.Date();
        Timestamp t = new Timestamp(date.getTime());
        String currentDir = filePath + t.toString().replaceAll(":", "");
        File saveDir = new File(currentDir);
        if (!saveDir.exists()) {
            saveDir.mkdir();// www.jav  a2  s  .  c  om
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
        factory.setRepository(saveDir);

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(REQUEST_SIZE);
        // constructs the directory path to store upload file
        String uploadPath = currentDir;

        try {
            // parses the request's content to extract file data
            List formItems = upload.parseRequest(request);
            Iterator iter = formItems.iterator();
            // iterates over form's fields
            File storeFile = null;
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    filePath = uploadPath + File.separator + fileName;
                    storeFile = new File(filePath);
                    // saves the file on disk
                    item.write(storeFile);
                }
            }
            ArrayList<String> content = Utils.readFile(storeFile);
            DMSConfig vocConf = new DMSConfig(this.DBURI, this.systemDbCollection + "Vocabulary/", this.DBuser,
                    this.DBpassword);
            Vocabulary voc = new Vocabulary(file, this.lang, vocConf);
            String[] terms = voc.termValues();

            for (int i = 0; i < content.size(); i++) {
                String addTerm = content.get(i);
                if (!Arrays.asList(terms).contains(addTerm)) {
                    voc.addTerm(addTerm);
                }

            }
            Utils.deleteDir(currentDir);
            response.sendRedirect("AdminVoc?action=list&file=" + file + "&menuId=AdminVoc");
        } catch (Exception ex) {
        }

    }

    xml.append("<FileName>").append(file).append("</FileName>\n");
    xml.append("<EntityType>").append("AdminVoc").append("</EntityType>\n");

    xml.append(this.xmlEnd());
    String xsl = conf.IMPORT_Vocabulary;
    try {
        XMLTransform xmlTrans = new XMLTransform(xml.toString());
        xmlTrans.transform(out, xsl);
    } catch (DMSException e) {
        e.printStackTrace();
    }
    out.close();
}

From source file:dk.nsi.sdm4.ydelse.dao.impl.SSRDAOImpl.java

@SuppressWarnings("unchecked")
private long insertBaseData(final SSR ssr) {
    return basedataInserter.executeAndReturnKey(new HashMap() {
        {//from   www . j  a va 2 s. c o m
            put("patientCpr", ssr.getPatientCpr().getHashedCpr());
            put("doctorOrganisationIdentifier", ssr.getDoctorOrganisationIdentifier().toString());
            put("admittedStart", new Timestamp(ssr.getTreatmentInterval().getStartMillis()));
            put("admittedEnd", new Timestamp(ssr.getTreatmentInterval().getEndMillis()));
            put("externalReference", ssr.getExternalReference());
        }
    }).longValue();
}

From source file:ejemplo.bean.TaskBean.java

public String login() throws IOException {

    Task t = new Task();
    String fichero;//from  ww w  .  j  a  v a  2 s .co m
    Task editTarea = null;

    RequestContext context = RequestContext.getCurrentInstance();
    FacesMessage message;
    boolean loggedIn = true;

    Timestamp insertarTiempo;
    insertarTiempo = new Timestamp(tiempo.getTime());

    t.setNombre_tarea(titulo);
    t.setDescription(descripcion);
    t.setEstado_tarea(estadoSeleccionado);
    t.setTiempo_estimado(insertarTiempo.toString());
    Calendar cal = Calendar.getInstance();
    t.setFecha_ini(cal.getTime().toString());
    t.setId_tarea(String.valueOf(System.currentTimeMillis()));
    t.setNombre_usuario(loginBean.user.getNombre());
    if (!file.getFileName().equals("")) {

        byte[] bytes = IOUtils.toByteArray(file.getInputstream());
        String realPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/");
        t.setFichero("/resources/files/" + file.getFileName());
        t.setNombre_fichero(file.getFileName());
        FileOutputStream os = new FileOutputStream(realPath + "resources/files/" + file.getFileName());
        os.write(bytes);
        os.close();
    }
    Projects selectedProject = loginBean.getSelectedProject();

    List<Task> tareas = selectedProject.getTareas();

    if (tareas == null) {
        List<Task> tareasInsertar = new ArrayList<>();
        tareasInsertar.add(t);
        selectedProject.setTareas(tareasInsertar);
    } else {
        selectedProject.getTareas().add(t);
    }

    dashboardView.RefreshDash();

    projectsService.editProjects(selectedProject);
    loginBean.setSelectedProject(selectedProject);
    message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Tarea", "La tarea se ha creado correctamente");
    FacesContext.getCurrentInstance().addMessage(null, message);
    context.addCallbackParam("loggedIn", loggedIn);

    return "";

}

From source file:com.taobao.itest.util.DateConverter.java

protected Object convertToDate(@SuppressWarnings("rawtypes") Class type, Object value) {
    if (value instanceof String) {
        try {//from w  ww . j a v a 2 s.  c o  m
            if (StringUtils.isEmpty(value.toString())) {
                return null;
            }
            String pattern = getDatePattern();
            if (value.toString().contains(":")) {
                pattern = getDateTimePattern();
            }
            DateFormat df = new SimpleDateFormat(pattern);
            Date date = df.parse((String) value);
            if (type.equals(Timestamp.class)) {
                return new Timestamp(date.getTime());
            }
            return date;
        } catch (Exception pe) {
            pe.printStackTrace();
            throw new ConversionException("Error converting String to Date");
        }
    } else if (value instanceof Date) {
        return value;
    } else if (value instanceof Long) {
        return getGmtDate((Long) value);
    }

    throw new ConversionException("Could not convert " + value.getClass().getName() + " to " + type.getName());
}

From source file:fr.paris.lutece.plugins.extend.modules.comment.service.CommentService.java

/**
 * {@inheritDoc}//from w w w.  ja  v  a  2s  .c o m
 */
@Override
@Transactional(CommentPlugin.TRANSACTION_MANAGER)
public void update(Comment comment) {
    Comment oldComment = findByPrimaryKey(comment.getIdComment());
    comment.setDateLastModif(new Timestamp(new Date().getTime()));
    _commentDAO.store(comment, CommentPlugin.getPlugin());
    if (oldComment.isPublished() ^ comment.isPublished()) {
        CommentListenerService.publishComment(comment.getExtendableResourceType(),
                comment.getIdExtendableResource(), comment.isPublished());
    }
    //        if ( ( oldComment.isPublished( ) && !comment.isPublished( ) ) || !oldComment.isPublished( ) && comment.isPublished( ) ) )
}

From source file:com.springmvc.controller.TimeLogController.java

@RequestMapping(value = "/search", method = RequestMethod.GET)
public String search(@RequestParam(value = "fromDate") String fromDate, String toDate, Model model)
        throws IOException, ParseException {
    List<TimeLog> timeLogs = timeLogService.getTimeLogs();
    List<TimeLog> foundTimeLogs = new ArrayList<TimeLog>();

    model.addAttribute("fromDate", fromDate);
    model.addAttribute("toDate", toDate);

    String message = "";

    if (fromDate.isEmpty() || toDate.isEmpty()) {
        model.addAttribute("pageTitle", "TimeLogs");
        model.addAttribute("pageDescription",
                "List of all login sessions and durations <br>You can sort and delete time logs as well");
        model.addAttribute("type", "danger");
        message = "Please choose a starting date with an ending date.";
        model.addAttribute("message", message);
        model.addAttribute("timelogs", timeLogService.getTimeLogs());
        return "timelog_list";
    }//from   ww w .ja v  a 2s .  c o m

    Timestamp beginDate = new Timestamp(new SimpleDateFormat("MM/dd/yyyy").parse(fromDate).getTime());
    Timestamp endDate = new Timestamp(new SimpleDateFormat("MM/dd/yyyy").parse(toDate).getTime());

    if (beginDate.after(endDate)) {
        model.addAttribute("pageTitle", "TimeLogs");
        model.addAttribute("pageDescription",
                "List of all login sessions and durations <br>You can sort and delete time logs as well");
        model.addAttribute("type", "danger");
        message = "Starting date cannot be after the ending date.";
        model.addAttribute("message", message);
        model.addAttribute("timelogs", timeLogService.getTimeLogs());
        return "timelog_list";
    }

    for (TimeLog t : timeLogs) {
        if ((t.getLogin().after(beginDate)) && (t.getLogin().before(endDate))) {
            foundTimeLogs.add(t);
        }
    }

    model.addAttribute("timelogs", foundTimeLogs);

    if (foundTimeLogs.isEmpty()) {
        message = "No logs between \"" + fromDate + " and " + toDate + "\" were found";
        model.addAttribute("type", "danger");
    } else {
        String extraS = "";
        String plural = "was";
        if (foundTimeLogs.size() != 1) {
            extraS = "s";
            plural = "were";
        }
        message = foundTimeLogs.size() + " log" + extraS + " between \"" + fromDate + " and " + toDate + "\" "
                + plural + " found.";
        model.addAttribute("type", "success");

    }
    model.addAttribute("pageTitle", "TimeLogs");
    model.addAttribute("pageDescription", "All the logs that matched your search criteria.");
    model.addAttribute("message", message);

    return "timelog_list";
}

From source file:com.luna.common.repository.UserRepository2ImplForDefaultSearchIT.java

@Test
public void testLtAndGtForDate() throws ParseException {
    int count = 15;
    String dateStr = "2012-01-15 16:59:00";
    String dateStrFrom = "2012-01-15 16:58:00";
    String dateStrEnd = "2012-01-15 16:59:01";
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    for (int i = 0; i < count; i++) {
        User user = createUser();// w w  w.  java 2s .  c om
        user.getBaseInfo().setBirthday(new Timestamp(df.parse(dateStr).getTime()));
        userRepository2.save(user);
    }
    Map<String, Object> searchParams = new HashMap<String, Object>();
    searchParams.put("baseInfo.birthday_gt", dateStrFrom);
    searchParams.put("baseInfo.birthday_lt", dateStrEnd);
    Searchable search = Searchable.newSearchable(searchParams);
    assertEquals(count, userRepository2.countAllByDefault(search));
}

From source file:com.bitranger.parknshop.buyer.controller.Payment.java

@RequestMapping(value = "/submitPayment", method = RequestMethod.POST)
public String beginPayment(HttpServletRequest req, Integer psOrderId, String bankCardId) {
    PsCustomer currentCustomer = (PsCustomer) req.getSession().getAttribute("currentCustomer");
    if (currentCustomer == null) {
        return Utility.error("User haven't logged in but tried to pay.");
    }/*  w ww  . ja  va 2 s .c  o m*/
    if (psOrderId == null) {
        return Utility.error("Payment: Order Id unspecified. ");
    }
    PsOrder psOrder = psOrderDao.findByOrderId(psOrderId);
    if (psOrder == null) {
        return Utility.error("Payment: Order doesn't exist. ");
    }
    if (!psOrder.getPsCustomer().getId().equals(currentCustomer.getId())) {
        return Utility.error("The user attempted to pay an order which does not belong to him");
    }
    PsAdministrator psAdministrator = psAdministratorDao.findById(1);
    psAdministrator.setBalance(psAdministrator.getBalance() + psOrder.getPriceTotal());
    psAdministratorDao.update(psAdministrator);

    psOrder.setStatus(OrderStatus.PAID);
    psOrder.setTimePaid(new Timestamp(System.currentTimeMillis()));
    log.info("Current balance " + psAdministrator.getBalance().toString());
    psOrderDao.update(psOrder);

    PsNoticeSeller n = new PsNoticeSeller(psOrder.getPsShop().getPsSeller(),
            new Timestamp(System.currentTimeMillis()), (short) 1);
    n.setSource(((PsCustomer) req.getSession().getAttribute("currentCustomer")).getName());
    n.setSource("order paied");
    psNoticeSellerDAO.save(n);

    return "success_payment";
}

From source file:org.wso2.uima.collectionProccesingEngine.consumers.HttpCasConsumer.java

/**
 * Send the parameter info as a http/https message to CEP.
 *
 * @param tweetText      the exact tweet received.
 * @param locationString the list of locations annotated from the tweet.
 * @param trafficLevel   the traffic level found as indicated by the tweet.
 *///  w w w.  j av a  2s . c  o  m

public void publish(String tweetText, String locationString, String trafficLevel) {

    Date date = new Date();
    String time = new Timestamp(date.getTime()).toString();

    try {
        HttpPost method = new HttpPost(httpEndPoint);

        if (httpClient != null) {
            String[] xmlElements = new String[] { "<events>" + "<event>" + "<metaData>" + "<Timestamp>" + time
                    + "</Timestamp>" + "</metaData>" +

                    "<payloadData>" +

                    "<Traffic_Location>" + locationString + "</Traffic_Location>" + "<Traffic_Level>"
                    + trafficLevel + "</Traffic_Level>" + "<Twitter_Text>" + tweetText + "</Twitter_Text>" +

                    "</payloadData>" +

                    "</event>" + "</events>" };

            try {
                for (String xmlElement : xmlElements) {
                    StringEntity entity = new StringEntity(xmlElement);
                    method.setEntity(entity);
                    if (httpEndPoint.startsWith("https")) {
                        processAuthentication(method, username, password);
                    }
                    httpClient.execute(method).getEntity().getContent().close();
                    logger.info("Event Published Successfully to " + httpEndPoint + "\n");
                }
            } catch (Exception e) {
                logger.error("Error While Sending Events to HTTP Endpoint : Connection Refused");
            }

            Thread.sleep(500); // We need to wait some time for the message to be sent

        }
    } catch (Throwable t) {
        logger.error("Unable to Connect to HTTP endpoint");
    }
}

From source file:org.cloudfoundry.identity.uaa.integration.codestore.ExpiringCodeStoreMockMvcTests.java

@Test
public void testGenerateCode() throws Exception {
    Timestamp ts = new Timestamp(System.currentTimeMillis() + 60000);
    ExpiringCode code = new ExpiringCode(null, ts, "{}");

    String requestBody = new ObjectMapper().writeValueAsString(code);
    MockHttpServletRequestBuilder post = post("/Codes").header("Authorization", "Bearer " + loginToken)
            .contentType(APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).content(requestBody);

    mockMvc.perform(post).andExpect(status().isCreated()).andExpect(jsonPath("$.code").exists())
            .andExpect(jsonPath("$.expiresAt").value(ts.getTime())).andExpect(jsonPath("$.data").value("{}"));

}