Java Code Examples for java.sql.Timestamp

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project activejdbc, under directory /activejdbc/src/main/java/org/javalite/activejdbc/validation/.

Source file: TimestampConverter.java

  18 
vote

public void convert(Model m){
  Object val=m.get(attributeName);
  if (!Util.blank(val)) {
    try {
      long time=df.parse(val.toString()).getTime();
      Timestamp t=new Timestamp(time);
      m.set(attributeName,t);
    }
 catch (    Exception e) {
      m.addValidator(this,attributeName);
    }
  }
}
 

Example 2

From project Amoeba-for-Aladdin, under directory /src/java/com/meidusa/amoeba/sqljep/function/.

Source file: Microsecond.java

  18 
vote

public static Long microsecond(Comparable<?> param) throws ParseException {
  if (param == null) {
    return null;
  }
  if (param instanceof Timestamp) {
    Timestamp ts=(Timestamp)param;
    return new Long(ts.getTime());
  }
  throw new ParseException(WRONG_TYPE + " microsecond(" + param.getClass()+ ")");
}
 

Example 3

From project Arecibo, under directory /alert-data-support/src/test/java/com/ning/arecibo/alert/confdata/dao/.

Source file: TestConfDataDAO.java

  18 
vote

private void basicConfDataChecks(final ConfDataObject actual,final long id,final ConfDataObject expected){
  final Timestamp now=new Timestamp(System.currentTimeMillis());
  Assert.assertEquals(actual.getId(),(Long)id);
  Assert.assertEquals(actual.getLabel(),expected.getLabel());
  Assert.assertTrue(actual.getCreateTimestamp().before(now));
  Assert.assertTrue(actual.getUpdateTimestamp().before(now));
}
 

Example 4

From project BanHammer, under directory /src/main/java/name/richardson/james/bukkit/banhammer/persistence/.

Source file: BanRecord.java

  18 
vote

/** 
 * Gets the state.
 * @return the state
 */
public State getState(){
  if (this.expiresAt == null) {
    return this.state;
  }
  final Timestamp now=new Timestamp(System.currentTimeMillis());
  return (now.after(this.expiresAt)) ? State.EXPIRED : this.state;
}
 

Example 5

From project baseunits, under directory /src/main/java/jp/xet/baseunits/mirage/.

Source file: TimePointValueType.java

  18 
vote

@Override public TimePoint get(Class<? extends TimePoint> type,CallableStatement cs,int index) throws SQLException {
  Timestamp date=cs.getTimestamp(index,CALENDAR);
  if (date == null) {
    return null;
  }
  return TimePoint.from(date);
}
 

Example 6

From project codjo-control, under directory /codjo-control-common/src/test/java/net/codjo/control/common/.

Source file: ParameterTest.java

  18 
vote

public void test_initStatement_today() throws Exception {
  Timestamp ima=new Timestamp(System.currentTimeMillis());
  dico.setNow(ima);
  Parameter parameter=new Parameter(1,"now","");
  mockStatement.setTimestamp(1,ima);
  statementControl.replay();
  parameter.initStatement(mockStatement,dico);
  statementControl.verify();
}
 

Example 7

From project com.idega.content, under directory /src/java/com/idega/content/bean/.

Source file: ContentItemBean.java

  18 
vote

@SuppressWarnings("finally") public Timestamp getParsedDateFromFeed(String dateValue){
  Timestamp t=null;
  try {
    t=new Timestamp(DateParser.parseW3CDateTime(dateValue).getTime());
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
 finally {
    return t;
  }
}
 

Example 8

From project contribution_eevolution_costing_engine, under directory /patch/base/src/org/compiere/model/.

Source file: MMatchInv.java

  18 
vote

/** 
 * Before Save
 * @param newRecord new
 * @return true
 */
protected boolean beforeSave(boolean newRecord){
  if (getDateTrx() == null)   setDateTrx(new Timestamp(System.currentTimeMillis()));
  if (getDateAcct() == null) {
    Timestamp ts=getNewerDateAcct();
    if (ts == null)     ts=getDateTrx();
    setDateAcct(ts);
  }
  if (getM_AttributeSetInstance_ID() == 0 && getM_InOutLine_ID() != 0) {
    MInOutLine iol=new MInOutLine(getCtx(),getM_InOutLine_ID(),get_TrxName());
    setM_AttributeSetInstance_ID(iol.getM_AttributeSetInstance_ID());
  }
  return true;
}
 

Example 9

From project daleq, under directory /integration/src/test/java/de/brands4friends/daleq/integration/tests/.

Source file: TimestampTest.java

  18 
vote

@Test @Restrict(not=MYSQL,reason="Mysql does not support milliseconds precision in Timestamps") public void timestamp_should_haveProperMillis(){
  final DateTime dateTime=new DateTime(2012,10,5,16,0,0,560);
  final Timestamp ts=new Timestamp(dateTime.getMillis());
  final Table table=aTable(TimestampTypeTable.class).with(aRow(42).f(TimestampTypeTable.A_TIMESTAMP,ts));
  daleq.insertIntoDatabase(table);
  final Table expected=aTable(TimestampTypeTable.class).with(aRow(42).f(TimestampTypeTable.A_TIMESTAMP,dateTime));
  daleq.assertTableInDatabase(expected);
}
 

Example 10

From project Diver, under directory /ca.uvic.chisel.javasketch.data/src/ca/uvic/chisel/javasketch/data/model/imple/internal/.

Source file: TraceImpl.java

  18 
vote

public Date getDataTime(){
  if (disposed) {
    return new Date(0);
  }
  try {
    Timestamp stamp=getDate("data_time");
    if (stamp != null) {
      return new Date(stamp.getTime());
    }
  }
 catch (  IllegalStateException e) {
  }
  return null;
}
 

Example 11

From project dozer, under directory /core/src/test/java/org/dozer/converters/.

Source file: DateConverterTest.java

  18 
vote

@Test public void testTimestampConversion(){
  Timestamp timestamp=new java.sql.Timestamp(1L);
  timestamp.setNanos(12345);
  Timestamp result=(Timestamp)converter.convert(Timestamp.class,timestamp);
  assertEquals(timestamp,result);
}
 

Example 12

From project egov-data, under directory /easyCompany2/src/main/java/egovframework/rte/tex/com/service/.

Source file: EgovStringUtil.java

  18 
vote

/** 
 * ??????????????? ?????? ?????? ??? ???????17?????IMESTAMP??? ???? ???
 * @param
 * @return Timestamp ?
 * @exception MyException
 * @see
 */
public static String getTimeStamp(){
  String rtnStr=null;
  String pattern="yyyyMMddhhmmssSSS";
  try {
    SimpleDateFormat sdfCurrent=new SimpleDateFormat(pattern,Locale.KOREA);
    Timestamp ts=new Timestamp(System.currentTimeMillis());
    rtnStr=sdfCurrent.format(ts.getTime());
  }
 catch (  Exception e) {
    log.debug(e.getMessage());
  }
  return rtnStr;
}
 

Example 13

From project agileBase, under directory /gtpb_server/src/com/gtwm/pb/model/manageSchema/.

Source file: DatabaseDefn.java

  17 
vote

/** 
 * Update all the existing field values in the database with the default value for that field
 */
private void setFieldDefaultDbAction(Connection conn,BaseField field) throws SQLException, CantDoThatException, ObjectNotFoundException, CodingErrorException {
  if (field.hasDefault()) {
    String internalTableName=field.getTableContainingField().getInternalTableName();
    String internalFieldName=field.getInternalFieldName();
    String SQLCode="UPDATE " + internalTableName + " SET "+ internalFieldName+ "=?";
    PreparedStatement statement=conn.prepareStatement(SQLCode);
    if (field instanceof TextField) {
      String defaultValue=((TextField)field).getDefault();
      statement.setString(1,defaultValue);
    }
 else     if (field instanceof DecimalField) {
      Double defaultValue=((DecimalField)field).getDefault();
      statement.setDouble(1,defaultValue);
    }
 else     if (field instanceof IntegerField) {
      Integer defaultValue=((IntegerField)field).getDefault();
      statement.setInt(1,defaultValue);
    }
 else     if (field instanceof CheckboxField) {
      Boolean defaultValue=((CheckboxField)field).getDefault();
      statement.setBoolean(1,defaultValue);
    }
 else     if (field instanceof DateField) {
      Calendar defaultValueCalendar=((DateField)field).getDefault();
      Timestamp defaultValue=new Timestamp(defaultValueCalendar.getTimeInMillis());
      statement.setTimestamp(1,defaultValue);
    }
 else {
      throw new CantDoThatException("Unable to set default value for field type " + field.getFieldCategory());
    }
    statement.execute();
    statement.close();
  }
}
 

Example 14

From project Aion-Extreme, under directory /AE-go_GameServer/src/com/aionemu/gameserver/services/.

Source file: PlayerService.java

  17 
vote

/** 
 * This method is called when player leaves the game, which includes just two cases: either player goes back to char selection screen or it's leaving the game [closing client].<br><br> <b><font color='red'>NOTICE: </font> This method is called only from  {@link AionConnection} and {@link CM_QUIT} and must not be called from anywhere else</b>
 * @param player
 */
public void playerLoggedOut(Player player){
  player.onLoggedOut();
  player.getCommonData().setOnline(false);
  player.getCommonData().setLastOnline(new Timestamp(System.currentTimeMillis()));
  player.getController().delete();
  player.setClientConnection(null);
  DAOManager.getDAO(PlayerDAO.class).onlinePlayer(player,false);
  storePlayer(player);
}
 

Example 15

From project ardverk-dht, under directory /components/store/src/main/java/org/ardverk/dht/storage/sql/.

Source file: DefaultIndex.java

  17 
vote

@Override public boolean delete(Key key,KUID valueId) throws SQLException {
  long now=System.currentTimeMillis();
  Date tombstone=new Date(now);
  Timestamp modified=new Timestamp(now);
  KUID bucketId=key.getId();
  KUID keyId=KeyId.valueOf(key);
  boolean success=true;
  try {
    cm.beginTxn();
{
      success&=update(SET_TOMBSTONE,valueId,tombstone);
    }
{
      success&=update(KEY_MODIFIED,keyId,modified);
    }
{
      success&=update(BUCKET_MODIFIED,bucketId,modified);
    }
    cm.commit();
  }
  finally {
    cm.endTxn();
  }
  return success;
}
 

Example 16

From project aws-toolkit-for-eclipse, under directory /com.amazonaws.eclipse.datatools.enablement.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/internal/driver/.

Source file: JdbcResultSet.java

  17 
vote

public Timestamp getTimestamp(final int col) throws SQLException {
  try {
    String str=getString(col);
    if (str == null) {
      return null;
    }
    return new Timestamp(new SimpleDateFormat().parse(str).getTime());
  }
 catch (  Exception e) {
    throw new SQLException(e.getMessage());
  }
}
 

Example 17

From project cas, under directory /cas-server-core/src/main/java/org/jasig/cas/ticket/registry/support/.

Source file: JdbcLockingStrategy.java

  17 
vote

/** 
 * @see org.jasig.cas.ticket.registry.support.LockingStrategy#acquire()
 */
@Transactional public boolean acquire(){
  boolean lockAcquired=false;
  if (this.platform == DatabasePlatform.SqlServer) {
    this.jdbcTemplate.execute("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
  }
  try {
    final SqlRowSet rowSet=(SqlRowSet)this.jdbcTemplate.query(this.selectSql,new Object[]{this.applicationId},new SqlRowSetResultSetExtractor());
    final Timestamp expDate=getExpirationDate();
    if (!rowSet.next()) {
      this.jdbcTemplate.update(this.createSql,new Object[]{this.applicationId,this.uniqueId,expDate});
      return true;
    }
    lockAcquired=canAcquire(rowSet);
    if (lockAcquired) {
      this.jdbcTemplate.update(this.updateAcquireSql,new Object[]{this.uniqueId,expDate,this.applicationId});
    }
  }
  finally {
    if (this.platform == DatabasePlatform.SqlServer) {
      this.jdbcTemplate.execute("SET TRANSACTION ISOLATION LEVEL READ COMMITTED");
    }
  }
  return lockAcquired;
}
 

Example 18

From project chukwa, under directory /src/test/java/org/apache/hadoop/chukwa/database/.

Source file: TestDatabasePrepareStatement.java

  17 
vote

public void testPrepareStatement(){
  DatabaseWriter db=new DatabaseWriter(cluster);
  Date today=new Date();
  long current=today.getTime();
  Timestamp timestamp=new Timestamp(current);
  String hostname="chukwa.example.org";
  String query="insert into [system_metrics] set timestamp='" + timestamp.toString() + "', host='"+ hostname+ "', cpu_user_pcnt=100;";
  Macro mp=new Macro(current,current,query);
  query=mp.toString();
  try {
    db.execute(query);
    query="select timestamp,host,cpu_user_pcnt from [system_metrics] where timestamp=? and host=? and cpu_user_pcnt=?;";
    mp=new Macro(current,current,query);
    query=mp.toString();
    ArrayList<Object> parms=new ArrayList<Object>();
    parms.add(current);
    parms.add(hostname);
    parms.add(100);
    ResultSet rs=db.query(query,parms);
    while (rs.next()) {
      assertTrue(hostname.intern() == rs.getString(2).intern());
      assertTrue(100 == rs.getInt(3));
    }
    db.close();
  }
 catch (  SQLException ex) {
    fail("Fail to run SQL statement:" + ExceptionUtil.getStackTrace(ex));
  }
}
 

Example 19

From project cloudhopper-commons-util, under directory /src/main/java/com/cloudhopper/commons/util/.

Source file: DateTimeUtil.java

  17 
vote

/** 
 * Null-safe method of converting a DateTime to a Timestamp. <br> NOTE: The timestamp also should be in UTC.
 * @return A UTC DateTime
 */
public static Timestamp toTimestamp(DateTime dt){
  if (dt == null) {
    return null;
  }
 else {
    return new Timestamp(dt.getMillis());
  }
}
 

Example 20

From project codjo-data-process, under directory /codjo-data-process-server/src/main/java/net/codjo/dataprocess/server/dao/.

Source file: StatusDao.java

  17 
vote

public void createDefaultExecutionListStatus(Connection con,int executionListId) throws SQLException {
  PreparedStatement pstmt=con.prepareStatement("insert into PM_EXECUTION_LIST_STATUS (EXECUTION_LIST_ID, STATUS, EXECUTION_DATE)" + " values (?, ?, ?)");
  try {
    pstmt.setInt(1,executionListId);
    pstmt.setInt(2,TO_DO);
    pstmt.setTimestamp(3,new Timestamp(0));
    pstmt.executeUpdate();
  }
  finally {
    pstmt.close();
  }
}
 

Example 21

From project components-ness-jdbi, under directory /src/main/java/com/nesscomputing/jdbi/argument/.

Source file: DateTimeArgument.java

  17 
vote

@Override public void apply(final int position,final PreparedStatement statement,final StatementContext ctx) throws SQLException {
  if (dateTime == null) {
    statement.setNull(position,Types.TIMESTAMP);
  }
 else {
    final long millis=dateTime.getMillis();
    statement.setTimestamp(position,new Timestamp(millis));
  }
}
 

Example 22

From project ddd-cqrs-sample, under directory /src/main/java/pl/com/bottega/erp/sales/domain/.

Source file: Order.java

  17 
vote

/** 
 * Sample business method
 */
public void submit(){
  checkIfDraft();
  status=OrderStatus.SUBMITTED;
  submitDate=new Timestamp(System.currentTimeMillis());
  eventPublisher.publish(new OrderSubmittedEvent(getEntityId()));
}
 

Example 23

From project elasticsearch-river-jdbc, under directory /src/main/java/org/elasticsearch/river/jdbc/.

Source file: SQLService.java

  17 
vote

/** 
 * Prepare statement for processing a river sync table
 * @param connection the JDBC connection
 * @param riverName the name of the river
 * @param optype the operation type
 * @param interval the interval to cover, in milliseconds (back from currenttime)
 * @return a preapred river table statement
 * @throws SQLException
 */
public PreparedStatement prepareRiverTableStatement(Connection connection,String riverName,String optype,long interval) throws SQLException {
  PreparedStatement p=connection.prepareStatement("select * from " + riverName + " where source_operation = ? and target_operation = 'n/a' and source_timestamp between ? and ?",ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
  p.setString(1,optype);
  java.util.Date d=new java.util.Date();
  long now=d.getTime();
  p.setTimestamp(2,new Timestamp(now - interval));
  p.setTimestamp(3,new Timestamp(now));
  return p;
}
 

Example 24

From project empire-db, under directory /empire-db/src/main/java/org/apache/empire/db/.

Source file: DBDatabaseDriver.java

  17 
vote

/** 
 * Adds a statement parameter to a prepared statement
 * @param pstmt the prepared statement
 * @param sqlParams list of objects
 */
protected void addStatementParam(PreparedStatement pstmt,int paramIndex,Object value,Connection conn) throws SQLException {
  if (value instanceof DBBlobData) {
    DBBlobData blobData=(DBBlobData)value;
    pstmt.setBinaryStream(paramIndex,blobData.getInputStream(),blobData.getLength());
    if (log.isDebugEnabled())     log.debug("Statement param {} set to BLOB data",paramIndex);
  }
 else   if (value instanceof DBClobData) {
    DBClobData clobData=(DBClobData)value;
    pstmt.setCharacterStream(paramIndex,clobData.getReader(),clobData.getLength());
    if (log.isDebugEnabled())     log.debug("Statement param {} set to CLOB data",paramIndex);
  }
 else   if (value instanceof Date && !(value instanceof Timestamp)) {
    Timestamp ts=new Timestamp(((Date)value).getTime());
    pstmt.setObject(paramIndex,ts);
    if (log.isDebugEnabled())     log.debug("Statement param {} set to date '{}'",paramIndex,ts);
  }
 else   if ((value instanceof Character) || (value instanceof Enum<?>)) {
    String strval=value.toString();
    pstmt.setObject(paramIndex,strval);
    if (log.isDebugEnabled())     log.debug("Statement param {} set to '{}'",paramIndex,strval);
  }
 else {
    pstmt.setObject(paramIndex,value);
    if (log.isDebugEnabled())     log.debug("Statement param {} set to '{}'",paramIndex,value);
  }
}
 

Example 25

From project en, under directory /src/l1j/server/server/.

Source file: Account.java

  17 
vote

public static void updateLastActive(final Account account){
  Connection con=null;
  PreparedStatement pstm=null;
  Timestamp ts=new Timestamp(System.currentTimeMillis());
  try {
    con=L1DatabaseFactory.getInstance().getConnection();
    String sqlstr="UPDATE accounts SET lastactive=? WHERE login = ?";
    pstm=con.prepareStatement(sqlstr);
    pstm.setTimestamp(1,ts);
    pstm.setString(2,account.getName());
    pstm.execute();
    account._lastActive=ts;
    _log.fine("Update lastactive for: " + account.getName());
  }
 catch (  Exception e) {
    _log.log(Level.SEVERE,e.getLocalizedMessage(),e);
  }
 finally {
    SQLUtil.close(pstm);
    SQLUtil.close(con);
  }
}
 

Example 26

From project AdServing, under directory /modules/services/tracking/src/main/java/net/mad/ads/services/tracking/impl/local/h2/.

Source file: H2TrackingService.java

  16 
vote

@Override public void track(TrackEvent event) throws ServiceException {
  PreparedStatement statement=null;
  Connection connection=null;
  try {
    connection=getConnection();
    String query="INSERT INTO trackevent (id, type, site, campaign, user, bannerid, ip, created) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
    statement=connection.prepareStatement(query);
    statement.setString(1,event.getId());
    statement.setString(2,event.getType().getName());
    statement.setString(3,event.getSite());
    statement.setString(4,event.getCampaign());
    statement.setString(5,event.getUser());
    statement.setString(6,event.getBannerId());
    statement.setString(7,event.getIp());
    statement.setTimestamp(8,new Timestamp(event.getTime()));
    statement.execute();
  }
 catch (  Exception e) {
    throw new ServiceException(e.getMessage());
  }
 finally {
    closeBoth(connection,statement);
  }
}
 

Example 27

From project android_8, under directory /src/com/google/gson/.

Source file: DefaultTypeAdapters.java

  16 
vote

@Override public Date deserialize(JsonElement json,Type typeOfT,JsonDeserializationContext context) throws JsonParseException {
  if (!(json instanceof JsonPrimitive)) {
    throw new JsonParseException("The date should be a string value");
  }
  Date date=deserializeToDate(json);
  if (typeOfT == Date.class) {
    return date;
  }
 else   if (typeOfT == Timestamp.class) {
    return new Timestamp(date.getTime());
  }
 else   if (typeOfT == java.sql.Date.class) {
    return new java.sql.Date(date.getTime());
  }
 else {
    throw new IllegalArgumentException(getClass() + " cannot deserialize to " + typeOfT);
  }
}
 

Example 28

From project azure4j-blog-samples, under directory /Log4J/CustomLog4JAppender/src/com/persistent/azure/logger/.

Source file: AzureTableStorageAppender.java

  16 
vote

/** 
 * The method makes the entry of log message in Windows Azure Table.
 * @param cloudTableClient The table client
 * @param messageLevel The log message level
 * @param message The message to be logged
 */
private void makeEntryIntoAzureTableStorage(CloudTableClient cloudTableClient,String messageLevel,String message){
  try {
    String instanceDetail=getInstanceDetails();
    Date date=new Date();
    Long milliseconds=date.getTime();
    LogEntity logEntity=new LogEntity();
    logEntity.setPartitionKey(messageLevel);
    logEntity.setRowKey(instanceDetail + "$" + milliseconds.toString());
    logEntity.setTimestamp(new Timestamp(new Date().getTime()));
    logEntity.setLevel(messageLevel);
    logEntity.setMessage(message);
    cloudTableClient.execute(tableName,TableOperation.insert(logEntity));
  }
 catch (  StorageException storageException) {
    storageException.printStackTrace();
  }
}
 

Example 29

From project contribution_eevolution_smart_browser, under directory /client/src/org/compiere/apps/.

Source file: ASearch.java

  16 
vote

/** 
 * Parse String
 * @param field column
 * @param in value
 * @return data type corrected value
 */
private Object parseString(GridField field,String in){
  log.log(Level.FINE,"Parse: " + field + ":"+ in);
  if (in == null)   return null;
  int dt=field.getDisplayType();
  try {
    if (dt == DisplayType.Integer || (DisplayType.isID(dt) && field.getColumnName().endsWith("_ID"))) {
      int i=Integer.parseInt(in);
      return new Integer(i);
    }
 else     if (DisplayType.isNumeric(dt)) {
      return DisplayType.getNumberFormat(dt).parse(in);
    }
 else     if (DisplayType.isDate(dt)) {
      long time=0;
      try {
        time=DisplayType.getDateFormat_JDBC().parse(in).getTime();
        return new Timestamp(time);
      }
 catch (      Exception e) {
        log.log(Level.SEVERE,in + "(" + in.getClass()+ ")"+ e);
        time=DisplayType.getDateFormat(dt).parse(in).getTime();
      }
      return new Timestamp(time);
    }
 else     if (dt == DisplayType.YesNo)     return Boolean.valueOf(in);
 else     return in;
  }
 catch (  Exception ex) {
    log.log(Level.SEVERE,"Object=" + in,ex);
    return null;
  }
}
 

Example 30

From project CraftCommons, under directory /src/main/java/com/craftfire/commons/managers/.

Source file: DataManager.java

  16 
vote

private String updateFieldsString(HashMap<String,Object> data){
  String query=" SET", suffix=",";
  int i=1;
  Iterator<Entry<String,Object>> it=data.entrySet().iterator();
  while (it.hasNext()) {
    Map.Entry<String,Object> pairs=it.next();
    if (i == data.size()) {
      suffix="";
    }
    Object val=pairs.getValue();
    String valstr=null;
    if (val instanceof Date) {
      val=new Timestamp(((Date)val).getTime());
    }
    if (val == null) {
      valstr="NULL";
    }
 else {
      valstr="'" + val.toString().replaceAll("'","''") + "'";
    }
    query+=" `" + pairs.getKey() + "` =  "+ valstr+ suffix;
    i++;
  }
  return query;
}
 

Example 31

From project D2-Java-Persistence, under directory /src/main/java/org/d2/plugins/jdbc/.

Source file: AbstractJdbcStorageSystem.java

  16 
vote

public void saveDocument(String id,String str,Date now){
  try {
    String sql="select id from " + tableName + " where id=?";
    PreparedStatement pstmt=conn.prepareStatement(sql);
    pstmt.setString(1,id);
    ResultSet rs=pstmt.executeQuery();
    boolean found=rs.next();
    rs.close();
    if (found) {
      sql="update " + tableName + " set data=?,dttm=? where id=?";
    }
 else {
      sql="insert into " + tableName + " (data, dttm, id) values (?,?,?)";
    }
    pstmt=conn.prepareStatement(sql);
    pstmt.setString(1,id);
    pstmt.setString(2,str);
    pstmt.setTimestamp(3,new Timestamp(now.getTime()));
    int count=pstmt.executeUpdate();
    if (count != 1)     throw new RuntimeException("Count was " + count + " but should have been 1 for insert or update statement with id="+ id);
  }
 catch (  Exception e) {
    throw Util.wrap(e);
  }
}
 

Example 32

From project EasyBan, under directory /src/uk/org/whoami/easyban/datasource/.

Source file: SQLDataSource.java

  16 
vote

@Override public synchronized void banNick(String nick,String admin,String reason,Calendar until){
  PreparedStatement pst=null;
  try {
    createNick(nick);
    pst=con.prepareStatement("INSERT INTO player_ban (player_id,admin,reason,until) VALUES(" + "(SELECT player_id FROM player WHERE player= ? )," + "?,"+ "?,"+ "?"+ ");");
    pst.setString(1,nick);
    pst.setString(2,admin);
    if (reason != null) {
      pst.setString(3,reason);
    }
 else {
      pst.setNull(3,Types.VARCHAR);
    }
    if (until != null) {
      pst.setTimestamp(4,new Timestamp(until.getTimeInMillis()));
    }
 else {
      pst.setTimestamp(4,new Timestamp(100000));
    }
    pst.executeUpdate();
  }
 catch (  SQLException ex) {
    ConsoleLogger.info(ex.getMessage());
  }
 finally {
    if (pst != null) {
      try {
        pst.close();
      }
 catch (      SQLException ex) {
      }
    }
  }
}
 

Example 33

From project bonecp, under directory /bonecp/src/main/java/com/jolbox/bonecp/.

Source file: CallableStatementHandle.java

  15 
vote

/** 
 * {@inheritDoc}
 * @see java.sql.CallableStatement#getTimestamp(int)
 */
public Timestamp getTimestamp(int parameterIndex) throws SQLException {
  checkClosed();
  try {
    return this.internalCallableStatement.getTimestamp(parameterIndex);
  }
 catch (  SQLException e) {
    throw this.connectionHandle.markPossiblyBroken(e);
  }
}
 

Example 34

From project codjo-broadcast, under directory /codjo-broadcast-common/src/test/java/net/codjo/broadcast/common/columns/.

Source file: DateColumnGeneratorTest.java

  15 
vote

public void test_formatField() throws Exception {
  Object[][] matrix={{"COL_1","COL_2","TABLE_A_FIELD_B","TABLE_A_FIELD_C"},{Timestamp.valueOf("1966-10-10 12:00:00"),Timestamp.valueOf("1966-10-10 12:00:00"),null,"FININF"}};
  ResultSet rs=new FakeResultSet(matrix).getStub();
  rs.next();
  Padder padder=new Padder(" ",18,false);
  DateColumnGenerator dcg=new DateColumnGenerator(FIELD_INFO,"DEST_FIELD","dd/MM/yyyy",null);
  DateColumnGenerator dcgTwin=new DateColumnGenerator(FIELD_INFO,"DEST_FIELD","dd/MM/yyyy",padder);
  assertEquals(dcg.proceedField(rs),"10/10/1966");
  assertEquals(dcgTwin.proceedField(rs),"        10/10/1966");
}
 

Example 35

From project codjo-standalone-common, under directory /src/main/java/net/codjo/utils/.

Source file: SqlTypeConverter.java

  15 
vote

/** 
 * Retourne le type Java associe a un type SQL.
 * @param sqlType
 * @return Une String contenant le type Java (ex : "String")
 * @throws IllegalArgumentException TODO
 */
public static Class toJavaType(int sqlType){
switch (sqlType) {
case Types.CHAR:
case Types.VARCHAR:
case Types.LONGVARCHAR:
    return String.class;
case Types.SMALLINT:
case Types.INTEGER:
  return int.class;
case Types.FLOAT:
return float.class;
case Types.DOUBLE:
return double.class;
case Types.BIGINT:
return long.class;
case Types.NUMERIC:
return java.math.BigDecimal.class;
case Types.TIMESTAMP:
return Timestamp.class;
case Types.TIME:
return Time.class;
case Types.DATE:
return java.sql.Date.class;
case Types.BIT:
return boolean.class;
default :
throw new IllegalArgumentException("Type SQL" + " non supporte : " + sqlType);
}
}
 

Example 36

From project contribution_eevolution_warehouse_management, under directory /extension/eevolution/warehousemanagement/src/main/java/org/eevolution/process/.

Source file: GenerateInOutBound.java

  15 
vote

/** 
 * Get Parameters
 */
protected void prepare(){
  p_Record_ID=getRecord_ID();
  for (  ProcessInfoParameter para : getParameter()) {
    String name=para.getParameterName();
    if (para.getParameter() == null)     ;
 else     if (name.equals("ShipDate")) {
      p_ShipDate=(Timestamp)para.getParameter();
    }
 else     if (name.equals("PickDate")) {
      p_PickDate=(Timestamp)para.getParameter();
    }
 else     if (name.equals("POReference")) {
      p_POReference=(String)para.getParameter();
    }
 else     if (name.equals("M_Locator_ID")) {
      p_M_Locator_ID=para.getParameterAsInt();
    }
 else     if (name.equals("DeliveryRule")) {
      p_DeliveryRule=(String)para.getParameter();
    }
 else     if (name.equals("C_DocType_ID")) {
      p_C_DocType_ID=para.getParameterAsInt();
    }
 else     if (name.equals("DocAction")) {
      p_DocAction=(String)para.getParameter();
    }
 else     log.log(Level.SEVERE,"Unknown Parameter: " + name);
  }
}
 

Example 37

From project core_1, under directory /src/com/iCo6/util/org/apache/commons/dbutils/.

Source file: BeanProcessor.java

  15 
vote

/** 
 * Calls the setter method on the target object for the given property. If no setter method exists for the property, this method does nothing.
 * @param target The object to set the property on.
 * @param prop The property to set.
 * @param value The value to pass into the setter.
 * @throws SQLException if an error occurs setting the property.
 */
private void callSetter(Object target,PropertyDescriptor prop,Object value) throws SQLException {
  Method setter=prop.getWriteMethod();
  if (setter == null) {
    return;
  }
  Class<?>[] params=setter.getParameterTypes();
  try {
    if (value != null) {
      if (value instanceof java.util.Date) {
        if (params[0].getName().equals("java.sql.Date")) {
          value=new java.sql.Date(((java.util.Date)value).getTime());
        }
 else         if (params[0].getName().equals("java.sql.Time")) {
          value=new java.sql.Time(((java.util.Date)value).getTime());
        }
 else         if (params[0].getName().equals("java.sql.Timestamp")) {
          value=new java.sql.Timestamp(((java.util.Date)value).getTime());
        }
      }
    }
    if (this.isCompatibleType(value,params[0])) {
      setter.invoke(target,new Object[]{value});
    }
 else {
      throw new SQLException("Cannot set " + prop.getName() + ": incompatible types.");
    }
  }
 catch (  IllegalArgumentException e) {
    throw new SQLException("Cannot set " + prop.getName() + ": "+ e.getMessage());
  }
catch (  IllegalAccessException e) {
    throw new SQLException("Cannot set " + prop.getName() + ": "+ e.getMessage());
  }
catch (  InvocationTargetException e) {
    throw new SQLException("Cannot set " + prop.getName() + ": "+ e.getMessage());
  }
}
 

Example 38

From project Cours-3eme-ann-e, under directory /Java/FerryInpres/src/data_bean/.

Source file: CSVBean.java

  15 
vote

public CSVBean(String csv_dir) throws FileNotFoundException, IOException {
  File dir=new File(csv_dir);
  this._accompagnants=new LinkedList<Accompagnant>();
  for (  String[] l : loadCSV(new File(dir,"accompagnants.csv"))) {
    this._accompagnants.add(new Accompagnant(Integer.valueOf(l[0]),l[1],l[2],l[3],Integer.valueOf(l[4])));
  }
  this._navires=new LinkedList<Navire>();
  for (  String[] l : loadCSV(new File(dir,"navires.csv"))) {
    this._navires.add(new Navire(Integer.valueOf(l[0]),l[1],Integer.valueOf(l[2]),Integer.valueOf(l[3])));
  }
  this._ports=new LinkedList<Port>();
  for (  String[] l : loadCSV(new File(dir,"ports.csv"))) {
    this._ports.add(new Port(l[0],Integer.valueOf(l[1]),Integer.valueOf(l[2]),l[3]));
  }
  this._reservations=new LinkedList<Reservation>();
  for (  String[] l : loadCSV(new File(dir,"reservations.csv"))) {
    this._reservations.add(new Reservation(Integer.valueOf(l[0]),Boolean.valueOf(l[1]),Boolean.valueOf(l[2]),Integer.valueOf(l[3]),Integer.valueOf(l[4])));
  }
  this._traversees=new LinkedList<Traversee>();
  for (  String[] l : loadCSV(new File(dir,"traversees.csv"))) {
    this._traversees.add(new Traversee(Integer.valueOf(l[0]),Timestamp.valueOf(l[1]),Integer.valueOf(l[2]),l[3],l[4]));
  }
  this._voyageurs=new LinkedList<Voyageur>();
  for (  String[] l : loadCSV(new File(dir,"voyageurs.csv"))) {
    this._voyageurs.add(new Voyageur(Integer.valueOf(l[0]),l[1],l[2],l[3],l[4]));
  }
}
 

Example 39

From project elephant-twin, under directory /com.twitter.elephanttwin/src/main/java/com/twitter/elephanttwin/util/.

Source file: DateUtil.java

  15 
vote

/** 
 * Timezones in mysql are wacky, this takes a timestamp and returns a Calendar representation of it in UTC
 */
public static Calendar fromSqlTimestamp(Timestamp t){
  if (t == null) {
    return null;
  }
  Calendar cal=getCalendarInstance();
  cal.setTimeInMillis(t.getTime());
  return cal;
}