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:org.cloudfoundry.identity.uaa.oauth.approval.JdbcApprovalStoreTests.java

private void addApproval(String userName, String clientId, String scope, long expiresIn,
        ApprovalStatus status) {//from  ww w .j a  v a  2 s  .c om
    Date expiresAt = new Timestamp(new Date().getTime() + expiresIn);
    Date lastUpdatedAt = new Date();
    Approval newApproval = new Approval(userName, clientId, scope, expiresAt, status, lastUpdatedAt);
    dao.addApproval(newApproval);
}

From source file:com.hs.mail.imap.dao.MySqlMessageDao.java

private long addPhysicalMessage(final MailMessage message) {
    final String sql = "INSERT INTO physmessage (size, internaldate, subject, sentdate, fromaddr) VALUES(?, ?, ?, ?, ?)";
    final MessageHeader header = message.getHeader();
    KeyHolder keyHolder = new GeneratedKeyHolder();
    getJdbcTemplate().update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
            PreparedStatement pstmt = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            pstmt.setLong(1, message.getSize()); // size
            pstmt.setTimestamp(2, new Timestamp(message.getInternalDate().getTime())); // internaldate
            pstmt.setString(3, header.getSubject()); // subject
            Date sent = header.getDate();
            pstmt.setTimestamp(4, (sent != null) ? new Timestamp(sent.getTime()) : null); // sentdate
            pstmt.setString(5, (header.getFrom() != null) ? header.getFrom().getDisplayString() : null); // fromaddr
            return pstmt;
        }// w  ww.  ja va  2  s .c o m
    }, keyHolder);
    long physmessageid = keyHolder.getKey().longValue();
    message.setPhysMessageID(physmessageid);
    addHeader(physmessageid, header);
    return physmessageid;
}

From source file:edgeserver.Publicador.java

@Override
public void run() {
    System.out.println("------------------------------------------------------------------");
    System.out.println("Inicializando Publicador.");
    System.out.print("Verificando contexo com o Servidor de Contexto: ");
    try {/*from ww w  .  j ava 2 s.  c  o  m*/
        this.testServer();
        System.out.println("OK");

        this.filaPublicacoes = this.obtemFila();

        if (!this.filaPublicacoes.isEmpty()) {
            System.out.println("Publicando fila de publicaes: ");
            this.filaPublicacoes = this.publicaFila();
        }

        synchronized (gatewaysCadastrados) {
            if (!gatewaysCadastrados.isEmpty()) {
                System.out.println("Efetuando novas publicaes: ");

                this.datapublicacao = new Date();
                gatewaysCadastrados.stream().forEach((gateway) -> {
                    gateway.getSensores().stream().forEach((sensor) -> {
                        try {
                            System.out.print("-> Publicando sensor " + sensor.getNome() + ": ");
                            publicaDado(sensor);
                            System.out.println("OK");
                        } catch (Exception ex) {
                            System.out.println("Fail");
                            System.out.print("Armazenando dado para publicao futura: ");
                            this.filaPublicacoes.add(new Publicacao(this.ServidorBordaID, sensor.getId(),
                                    new Timestamp(this.datapublicacao.getTime()), sensor.getDado()));
                            System.out.println("OK");
                        }
                    });
                });
            } else
                System.out.println("Nenhuma publicao a ser realizada.");
        }
    } catch (Exception ex) {
        System.out.println("Fail");
        synchronized (gatewaysCadastrados) {
            gatewaysCadastrados.stream().forEach((gateway) -> {
                gateway.getSensores().stream().forEach((sensor) -> {
                    System.out.print("Armazenando dados para publicaes futuras: ");
                    this.filaPublicacoes.add(new Publicacao(this.ServidorBordaID, sensor.getId(),
                            new Timestamp(this.datapublicacao.getTime()), sensor.getDado()));
                    System.out.println("OK");
                });
            });
        }
    }
    //this.writeObjectsToFile(filaPublicacoes);

    try {
        this.armazenaFila(filaPublicacoes);
    } catch (IOException ex) {
        Logger.getLogger(Publicador.class.getName()).log(Level.SEVERE, null, ex);
    }

    System.out.println("Finalizando Publicador.");
    System.out.println("------------------------------------------------------------------");
}

From source file:jp.co.acroquest.endosnipe.web.explorer.controller.JvnFileDownloadController.java

/**
 * JVN?/*from   ww  w.j  a  va2s  .c om*/
 * @param start 
 * @param end 
 * @param agentName ??
 * @param res ?
 * @return Jvn
 * @throws Exception ????
 */
@ResponseBody
@RequestMapping(value = "/search", method = RequestMethod.POST)
public List<JvnFileSearchResultDto> search(@RequestParam(value = "agentName") final String agentName,
        @RequestParam(value = "start", required = false) final String start,
        @RequestParam(value = "end", required = false) final String end, final HttpServletResponse res)
        throws Exception {
    SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);

    Timestamp startTime = null;
    Timestamp endTime = null;

    if (!StringUtils.isEmpty(start)) {
        startTime = new Timestamp(dateFormat.parse(start).getTime());
    }

    if (!StringUtils.isEmpty(end)) {
        endTime = new Timestamp(dateFormat.parse(end).getTime());
    }

    return this.jvnFileDownloadService_.getJavelinLog(startTime, endTime, agentName);
}

From source file:com.metaparadigm.jsonrpc.DateSerializer.java

public Object unmarshall(SerializerState state, Class clazz, Object o) throws UnmarshallException {
    JSONObject jso = (JSONObject) o;/* w w w . j ava 2 s.  c  o  m*/
    long time = 0;
    try {
        time = jso.getLong("time");
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    if (jso.has("javaClass")) {
        try {
            clazz = Class.forName(jso.getString("javaClass"));
        } catch (ClassNotFoundException cnfe) {
            throw new UnmarshallException(cnfe.getMessage());
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    if (Date.class.equals(clazz)) {
        return new Date(time);
    } else if (Timestamp.class.equals(clazz)) {
        return new Timestamp(time);
    } else if (java.sql.Date.class.equals(clazz)) {
        return new java.sql.Date(time);
    }
    throw new UnmarshallException("invalid class " + clazz);
}

From source file:org.runway.users.service.UserPasswordResetServiceImpl.java

public void createPasswordResetRequest(UserPasswordReset resetRequest) throws EmailNotRegisteredException {

    // first verify whether password can be reset.
    User user = null;/*from  ww w.  j av  a  2 s .com*/
    if (!TextUtils.isEmpty(resetRequest.getEmail())) {
        try {
            user = userManagerSvc.getUsersByEmail(resetRequest.getEmail());
            resetRequest.setUserId(user.getId());
        } catch (UserNotFoundException e) {
            e.printStackTrace();
            StringBuilder sb = new StringBuilder();
            sb.append(resetRequest.getEmail());
            sb.append(" not registered");
            throw new EmailNotRegisteredException(sb.toString(), e);
        }
    }

    // generate the password reset Id
    if (resetRequest.getId() == 0) {
        long id = passwordResetDao.generatePasswordResetId();
        resetRequest.setId((int) id);
    }

    if (resetRequest.getCreateTime() == null) {
        Timestamp createTime = new Timestamp(new Date().getTime());
        resetRequest.setCreateTime(createTime);
    }
    long oneday = 24 * 60 * 60 * 1000;
    Timestamp expireTime = new Timestamp(resetRequest.getCreateTime().getTime() + oneday);
    resetRequest.setExpireTime(expireTime);
    passwordResetDao.addPasswordReset(resetRequest);

    // send email.
    createAndSendEmail(user, resetRequest);
}

From source file:com.agiletec.plugins.jpcontentfeedback.aps.system.services.contentfeedback.comment.CommentDAO.java

@Override
public void addComment(IComment comment) {
    Connection conn = null;/*  w  w w  .  jav  a 2 s .  c  om*/
    PreparedStatement stat = null;
    try {
        conn = this.getConnection();
        conn.setAutoCommit(false);
        stat = conn.prepareStatement(ADD_COMMENT);
        stat.setInt(1, comment.getId());
        stat.setString(2, comment.getContentId());
        stat.setTimestamp(3, new Timestamp(new Date().getTime()));
        stat.setString(4, comment.getComment());
        stat.setInt(5, comment.getStatus());
        stat.setString(6, comment.getUsername());
        stat.executeUpdate();
        conn.commit();
    } catch (Throwable t) {
        this.executeRollback(conn);
        _logger.error("Error adding a comment", t);
        throw new RuntimeException("Error adding a comment", t);
    } finally {
        closeDaoResources(null, stat, conn);
    }

}

From source file:net.mindengine.oculus.frontend.service.project.JdbcProjectDAO.java

@Override
public Long createProject(Project project) throws Exception {

    PreparedStatement ps = getConnection().prepareStatement(
            "insert into projects (name, description, path, parent_id, icon, author_id, date) values (?,?,?,?,?,?,?)",
            Statement.RETURN_GENERATED_KEYS);

    ps.setString(1, project.getName());//from  w  w w  .  j a  v  a 2  s. c o m
    ps.setString(2, project.getDescription());
    ps.setString(3, project.getPath());
    ps.setLong(4, project.getParentId());
    ps.setString(5, project.getIcon());
    ps.setLong(6, project.getAuthorId());
    ps.setTimestamp(7, new Timestamp(project.getDate().getTime()));

    ps.executeUpdate();
    ResultSet rs = ps.getGeneratedKeys();
    Long projectId = null;
    if (rs.next()) {
        projectId = rs.getLong(1);
    }

    if (project.getParentId() > 0) {
        // Increasing the parents project subprojects_count var
        update("update projects set subprojects_count = subprojects_count+1 where id = :id", "id",
                project.getParentId());
    }

    return projectId;
}

From source file:de.tuttas.restful.AnwesenheitsManager.java

/**
 * Lschen eines Anwesenhietseintrages Adresse
 * /api/v1/anwesenheit/{ids}/{datum}/*from   w w  w.j  av  a  2  s. c  o  m*/
 *
 * @param ids ID des Schlers
 * @param dat Datum des Anwesenheit
 * @return Anwesenheit die gelscht wurde, oder null bei Fehler
 */
@DELETE
@Path("/{ids}/{datum}")
public Anwesenheit delAnwesenheit(@PathParam("ids") Integer ids, @PathParam("datum") Date dat) {
    Log.d("ids=" + ids + " Datum=" + dat);
    Anwesenheit a = em.find(Anwesenheit.class, new AnwesenheitId(ids, new Timestamp(dat.getTime())));
    if (a != null) {
        em.remove(a);
    } else {
        Log.d("Kann Anwesenheit nicht finden!");
    }
    return a;
}

From source file:com.iLabs.spice.handler.LoginHandler.java

public String loginAction() throws IOException, ClassNotFoundException, SQLException {
    String result = "failure";
    try {/*from   w  ww.j  a v  a  2  s.c  o m*/
        java.util.Date date = new java.util.Date();
        System.out.println("The Start Time (1): " + new Timestamp(date.getTime()));

        ProfileBean ownerProfile = (ProfileBean) getSessionScope().get("ownerProfile");
        ProfileBean currentProfile = (ProfileBean) getSessionScope().get("currentProfile");
        if (ownerProfile == null) {
            ownerProfile = new ProfileBean();
        }
        if (currentProfile == null) {
            currentProfile = new ProfileBean();
        }

        IPerson person = (IPerson) ServiceLocator.getService("PersonSvc");
        UserAuth authPerson = person.authenticateUser(currentProfile.getUserAuth().getUserName(),
                currentProfile.getUserAuth().getUserPassword());

        //This condition checks if the authPerson returned from authentication service is null or not.
        //If the user who enters the site is an authenticated user, the user's info and his friends info is stored in 
        //currentProfile as well as ownerProfile bean.
        if (authPerson != null && authPerson.getUserName() != null) {
            //Save the QoS Level of the user (Platinum, Gold or Silver)
            qoslevel = currentProfile.getUserAuth().getProfile().getProfileURL();

            ClientResource clientResource = new ClientResource("http://192.168.1.41:8180/sessions");

            Session session = new Session();

            ConnectionParty owner = new ConnectionParty();
            HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance()
                    .getExternalContext().getRequest();
            owner.setIp(request.getHeader("X-Forwarded-For"));
            owner.setPort(request.getRemotePort());
            System.out.println("Client address: " + request.getRemoteAddr());
            System.out.println("Client port: " + request.getRemotePort());
            if (qoslevel.equalsIgnoreCase("GOLD")) {
                owner.setSip_uri("sip:alice@openepc.test");
                session.setApplicationId("surveillance");
            } else {
                if (qoslevel.equalsIgnoreCase("Silver")) {
                    owner.setSip_uri("sip:bob@openepc.test");
                    session.setApplicationId("IMS");
                } else {
                    owner.setSip_uri("sip:charlie@openepc.test");
                    session.setApplicationId("YouTube");
                }
            }
            System.out.println("REQUEST  " + request.getRemoteAddr() + request.getRemoteHost()
                    + request.getLocalPort() + request.getRequestURI());
            System.out.println(request.getHeader("X-Forwarded-For"));
            ConnectionParty otherParty = new ConnectionParty();
            otherParty.setIp("192.168.1.41");
            otherParty.setPort(8080);
            otherParty.setSip_uri("");

            session.setSessionOwner(owner);
            session.setSessionOtherParty(otherParty);

            ServiceInfo serviceInfo = new ServiceInfo();
            //serviceInfo.setServiceId("Webcamstream");
            setBandwidthAndPriority(serviceInfo, qoslevel);
            serviceInfo.setMediaType(MediaType.DATA);
            serviceInfo.setLifeTime(6000);

            session.setServiceInfo(serviceInfo);

            Representation response = clientResource.post(session);
            String resp = response.getText();
            SI.setSessionID(resp.substring(70, 125));
            System.out.println("200 OK RESPONSE IS: " + resp);
            String s = SI.getSessionID();
            System.out.println("SESSION ID IS: " + s);

            UserFriends userFriends = person.getFriends(authPerson.getUserId());
            ownerProfile.setUserAuth(authPerson);
            ownerProfile.setUserFriends(userFriends);
            currentProfile.setUserAuth(authPerson);
            currentProfile.setUserFriends(userFriends);
            getSessionScope().put("ownerProfile", ownerProfile);
            getSessionScope().put("currentProfile", currentProfile);

            DatabaseConnector r = new DatabaseConnector();
            r.Write(s, authPerson.getUserId());
            //authPerson.getProfile().setProfileURL(s);
            System.out.println("User " + authPerson.getProfile().getFirstName() + " "
                    + authPerson.getProfile().getProfileURL());

            System.out.println("The Start Time (3): " + new Timestamp(date.getTime()));
            result = "success";
        } else { // if user is not an authenticate user, then error message is generated.
            FacesMessage message = new FacesMessage("Please Check Username and password");
            FacesContext.getCurrentInstance().addMessage("login:user_password", message);
        }

    } catch (SysException e) {
        e.printStackTrace();
    }
    return result;

}