Java Code Examples for java.sql.Date

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 codjo-imports, under directory /codjo-imports-plugin/codjo-imports-plugin-filter/codjo-imports-plugin-filter-kernel/src/main/java/net/codjo/imports/plugin/filter/kernel/.

Source file: DefaultImportFunctionHolder.java

  23 
vote

public Date stringToDate(String value,String format,String locale) throws NoSuchFieldException, IllegalAccessException {
  SimpleDateFormat df=(SimpleDateFormat)SimpleDateFormat.getDateInstance(SimpleDateFormat.SHORT,getLocale(locale));
  if (format != null) {
    df.applyPattern(format);
  }
  Date result;
  try {
    result=new Date(df.parse(value).getTime());
  }
 catch (  ParseException e) {
    result=new Date(0);
  }
  return result;
}
 

Example 2

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

Source file: DateConverterTest.java

  22 
vote

@Test public void testXmlGregorianCalendar(){
  XMLGregorianCalendar xmlCalendar=mock(XMLGregorianCalendar.class);
  GregorianCalendar expected=new GregorianCalendar();
  when(xmlCalendar.toGregorianCalendar()).thenReturn(expected);
  Date date=new Date(expected.getTimeInMillis());
  assertEquals(date,converter.convert(Date.class,xmlCalendar));
}
 

Example 3

From project fastjson, under directory /src/test/java/com/alibaba/json/bvt/serializer/.

Source file: BugTest0.java

  22 
vote

public void test_2() throws Exception {
  Date t=new Date(System.currentTimeMillis());
  String text=JSON.toJSONString(t);
  Date t1=JSON.parseObject(text,Date.class);
  Assert.assertEquals(t,t1);
}
 

Example 4

From project Locast-Android, under directory /src/edu/mit/mobile/android/locast/widget/.

Source file: DiscussionBoard.java

  22 
vote

@Override public void setViewText(TextView v,String text){
switch (v.getId()) {
case R.id.date:
    final Date d=new Date(Long.parseLong(text));
  v.setText(d.toLocaleString());
break;
default :
super.setViewText(v,text);
}
}
 

Example 5

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

Source file: CustomValidatorTest.java

  21 
vote

@Test public void shouldRegisterCustomValidator(){
class FutureBirthValidator extends ValidatorAdapter {
    FutureBirthValidator(){
      setMessage("invalid.dob.message");
    }
    @Override public void validate(    Model m){
      Date dob=m.getDate("dob");
      Date now=new java.sql.Date(System.currentTimeMillis());
      if (dob.after(now)) {
        m.addValidator(this,"invalid.dob");
      }
    }
  }
  FutureBirthValidator validator=new FutureBirthValidator();
  Person.addValidator(validator);
  Person p=new Person();
  GregorianCalendar future=new GregorianCalendar();
  future.set(Calendar.YEAR,3000);
  p.set("dob",new Date(future.getTimeInMillis()));
  p.validate();
  a(p.errors().size()).shouldBeEqual(3);
  a(p.errors().get("invalid.dob")).shouldBeEqual("date of birth cannot be in future");
  Person.removeValidator(validator);
}
 

Example 6

From project AdminCmd, under directory /src/main/java/be/Balor/Player/.

Source file: Ban.java

  21 
vote

/** 
 * @param reason
 * @param date
 * @param player
 */
public Ban(final String reason,final String player){
  super();
  this.reason=reason;
  this.date=new Date(System.currentTimeMillis());
  this.player=player;
}
 

Example 7

From project android_packages_apps_Gallery2, under directory /src/com/android/gallery3d/photoeditor/.

Source file: SaveCopyTask.java

  21 
vote

public SaveCopyTask(Context context,Uri sourceUri,Callback callback){
  this.context=context;
  this.sourceUri=sourceUri;
  this.callback=callback;
  saveFileName=new SimpleDateFormat(TIME_STAMP_NAME).format(new Date(System.currentTimeMillis()));
}
 

Example 8

From project Anki-Android, under directory /src/com/ichi2/anki/.

Source file: Stats.java

  21 
vote

public static Stats globalStats(Deck deck){
  Log.i(AnkiDroidApp.TAG,"Getting global stats...");
  int type=STATS_LIFE;
  Date today=Utils.genToday(deck.getUtcOffset());
  Cursor cursor=null;
  Stats stats=null;
  try {
    cursor=AnkiDatabaseManager.getDatabase(deck.getDeckPath()).getDatabase().rawQuery("SELECT id " + "FROM stats WHERE type = " + String.valueOf(type),null);
    if (cursor.moveToFirst()) {
      stats=new Stats(deck);
      stats.fromDB(cursor.getLong(0));
      return stats;
    }
  }
  finally {
    if (cursor != null) {
      cursor.close();
    }
  }
  stats=new Stats(deck);
  stats.create(type,today);
  stats.mType=type;
  return stats;
}
 

Example 9

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

Source file: DefaultIndex.java

  21 
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 10

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

  21 
vote

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

Example 11

From project contribution_eevolution_costing_engine, under directory /extension/costengine/src/test/java/org/adempiere/.

Source file: AverageInvoiceCostTest.java

  21 
vote

public void assertCostDetail(CostResult costResult,String whereClause,ArrayList<Object> parameters){
  MCostDetail cd=getCostDetail(whereClause,parameters);
  System.out.println("Result" + costResult.toString());
  System.out.println("Cost Detail " + cd.toString());
  assertEquals("Cost Detail Amt ",costResult.cdAmt,cd.getAmt());
  assertEquals("Cost Detail Adjutment ",costResult.cdAdjutment,cd.getCostAdjustment());
  assertEquals("Cost Detail Qty",costResult.cdQty,cd.getQty());
  assertEquals("Cost Detail Current Price Cost ",costResult.cdCurrentCostPrice,cd.getCurrentCostPrice());
  assertEquals("Cost Detail Cumulate Qty ",costResult.cdCumulateQty,cd.getCumulatedQty());
  assertEquals("Cost Detail Cumulate Amt ",costResult.cdCumulateAmt,cd.getCumulatedAmt());
  assertEquals("Account Date",new Date(costResult.cdDateAcct.getTime()).toString(),new Date(cd.getDateAcct().getTime()).toString());
}
 

Example 12

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

Source file: TraceImpl.java

  21 
vote

private TraceImpl(String launchID,java.util.Date launchTime,WriteDataUtils utils) throws SQLException {
  this.dataUtils=utils;
  this.launchID=launchID;
  this.launchTime=new Date(launchTime.getTime());
  classes=new TreeMap<String,ITraceClass>();
  threads=new ArrayList<IThread>();
  modelCache=new TreeMap<String,ITraceModel>();
  load();
  dataUtils.addTriggerListener(this);
  classesDirty=true;
  threadsDirty=true;
  register(this);
}
 

Example 13

From project GTNA, under directory /src/gtna/io/.

Source file: Output.java

  21 
vote

public static void open(String filename){
  DELIMITER=Config.get("OUTPUT_DELIMITER");
  if (writeToFile) {
    fw=new Filewriter(filename);
  }
  timer=new Timer();
  Time time=new Time(System.currentTimeMillis());
  Date date=new Date(System.currentTimeMillis());
  writelnDelimiter();
  writeIndent();
  String start=Config.get("OUTPUT_START");
  start=start.replace("%DATE",date.toString());
  start=start.replace("%TIME",time.toString());
  writeln(start);
  writelnDelimiter();
}
 

Example 14

From project junit-rules, under directory /src/test/java/junit/rules/derby/.

Source file: DerbyDataSourceRuleTest.java

  21 
vote

/** 
 * @throws Exception should never happen
 */
@Test public void testDerbyDataSourceRule() throws Exception {
  final Connection conn=derby.getConnection();
  assertNotNull(conn);
  try {
    final Statement ps=conn.createStatement();
    try {
      final ResultSet rs=ps.executeQuery("VALUES CURRENT_DATE");
      rs.next();
      final Date today=rs.getDate(1);
      assertNotNull(today);
    }
  finally {
      ps.close();
    }
  }
  finally {
    conn.close();
  }
}
 

Example 15

From project logisima-play-neo4j, under directory /samples-and-tests/logisima-play-neo4j-test/test/play/module/neo4j/.

Source file: Neo4jUnit.java

  21 
vote

protected User createUser(String email,String firstname,String lastname,String login,Boolean save) throws Neo4jException {
  User user=new User();
  user.email=email;
  user.firstname=firstname;
  user.lastname=lastname;
  user.login=login;
  user.age=42;
  user.isActive=Boolean.TRUE;
  user.birthday=new Date(1983,2,26);
  if (save)   user.save();
  return user;
}
 

Example 16

From project Maimonides, under directory /src/com/codeko/apps/maimonides/usr/.

Source file: Usuario.java

  21 
vote

public final void cargarDesdeResultSet(ResultSet res) throws SQLException, Exception {
  setId(res.getInt("id"));
  setNombre(res.getString("nombre"));
  setClaveEncriptada(res.getString("clave"));
  setClaveAsignada(!Str.noNulo(getClaveEncriptada()).equals(""));
  Date dAlt=res.getDate("falta");
  Date dBaj=res.getDate("fbaja");
  if (dAlt != null) {
    setFechaAlta(Fechas.toGregorianCalendar(dAlt));
  }
  if (dBaj != null) {
    setFechaBaja(Fechas.toGregorianCalendar(dBaj));
  }
  setRoles(res.getInt("roles"));
  cargarProfesorAsociado();
  Cache.put(getClass(),getId(),this);
}
 

Example 17

From project medsavant, under directory /MedSavantServerEngine/src/org/ut/biolab/medsavant/serverapi/.

Source file: LogManager.java

  21 
vote

@Override public Date getDateOfLastServerLog(String sid) throws SQLException {
  TableSchema table=MedSavantDatabase.ServerlogTableSchema;
  SelectQuery query=new SelectQuery();
  query.addFromTable(table.getTable());
  query.addColumns(table.getDBColumn(ServerLogTableSchema.COLUMNNAME_OF_TIMESTAMP));
  query.addCondition(BinaryCondition.equalTo(table.getDBColumn(ServerLogTableSchema.COLUMNNAME_OF_USER),"server"));
  query.addOrdering(table.getDBColumn(ServerLogTableSchema.COLUMNNAME_OF_TIMESTAMP),Dir.DESCENDING);
  ResultSet rs=ConnectionController.executeQuery(sid,query.toString() + " LIMIT 1");
  if (rs.next()) {
    Date d=new Date(rs.getTimestamp(1).getTime());
    return d;
  }
 else {
    return null;
  }
}
 

Example 18

From project platform_packages_apps_Gallery2_1, under directory /src/com/android/gallery3d/photoeditor/.

Source file: SaveCopyTask.java

  21 
vote

public SaveCopyTask(Context context,Uri sourceUri,Callback callback){
  this.context=context;
  this.sourceUri=sourceUri;
  this.callback=callback;
  albumName=context.getString(R.string.edited_photo_bucket_name);
  saveFileName=new SimpleDateFormat(TIME_STAMP_NAME).format(new Date(System.currentTimeMillis()));
}
 

Example 19

From project querydsl, under directory /querydsl-core/src/test/java/com/mysema/query/.

Source file: DateConstantTest.java

  21 
vote

@Test public void test(){
  Calendar cal=Calendar.getInstance();
  cal.set(Calendar.DAY_OF_MONTH,1);
  cal.set(Calendar.MONTH,0);
  cal.set(Calendar.YEAR,2000);
  System.out.println(cal.getTime());
  DateExpression<Date> date=DateConstant.create(new Date(cal.getTimeInMillis()));
  assertEquals("1",date.dayOfMonth().toString());
  assertEquals("1",date.month().toString());
  assertEquals("2000",date.year().toString());
  assertEquals("7",date.dayOfWeek().toString());
  assertEquals("1",date.dayOfYear().toString());
}
 

Example 20

From project TextSecure, under directory /src/org/thoughtcrime/securesms/.

Source file: ConversationFragment.java

  21 
vote

private void handleDisplayDetails(MessageRecord message){
  String sender=message.getRecipients().getPrimaryRecipient().getNumber();
  String transport=message.isMms() ? "mms" : "sms";
  long date=message.getDate();
  SimpleDateFormat dateFormatter=new SimpleDateFormat("EEE MMM d, yyyy 'at' hh:mm:ss a zzz");
  AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
  builder.setTitle(R.string.ConversationFragment_message_details);
  builder.setIcon(android.R.drawable.ic_dialog_info);
  builder.setCancelable(false);
  builder.setMessage(String.format(getSherlockActivity().getString(R.string.ConversationFragment_sender_s_transport_s_sent_received_s),sender,transport.toUpperCase(),dateFormatter.format(new Date(date))));
  builder.setPositiveButton(android.R.string.ok,null);
  builder.show();
}
 

Example 21

From project twitstreet, under directory /src/com/twitstreet/market/.

Source file: StockMgrImpl.java

  21 
vote

@Override public void truncateStockHistory(){
  Connection connection=null;
  CallableStatement ps=null;
  try {
    connection=dbMgr.getConnection();
    ps=connection.prepareCall("{call refine_stock_history(?)}");
    Date twoDaysAgo=new Date((new java.util.Date()).getTime() - 2 * 24 * 60* 60* 1000);
    ps.setDate(1,twoDaysAgo);
    ps.execute();
  }
 catch (  SQLException ex) {
    logger.error(DBConstants.QUERY_EXECUTION_FAIL + ps.toString(),ex);
  }
 finally {
    dbMgr.closeResources(connection,ps,null);
  }
}
 

Example 22

From project verdandi, under directory /src/main/java/verdandi/.

Source file: Helper.java

  21 
vote

/** 
 * java.sql.Date is braindamage. It should only wrap around a date, but considers whole time for equals, so 2006-11-02 != 2006-11-02
 * @param d a day
 * @return a day with h,m,s,ms set to 0.
 */
public static Date normalize(Date d){
synchronized (cal) {
    cal.setTime(d);
    cal.set(Calendar.HOUR_OF_DAY,0);
    cal.set(Calendar.MINUTE,0);
    cal.set(Calendar.SECOND,0);
    cal.set(Calendar.MILLISECOND,0);
    return new Date(cal.getTimeInMillis());
  }
}
 

Example 23

From project zen-project, under directory /zen-jsweb/src/main/java/com/nominanuda/jsweb/host/.

Source file: JdbcDataSource.java

  21 
vote

protected Object convertToNative(ResultSet rs,String name) throws SQLException {
  Date ts=null;
  try {
    ts=rs.getDate(name);
  }
 catch (  Exception e) {
  }
  if (ts != null) {
    Time tm=null;
    try {
      tm=rs.getTime(name);
    }
 catch (    Exception e) {
    }
    if (tm != null) {
      DateTime dt=new DateTime(ts.getTime());
      dt=dt.plusMillis((int)tm.getTime());
      return dateTime.toISO8601UtcSecs(dt.getMillis());
    }
  }
  Object jdbcVal=rs.getObject(name);
  return convertToNative(jdbcVal);
}
 

Example 24

From project agraph-java-client, under directory /src/test/.

Source file: RepositoryConnectionTest.java

  20 
vote

@SuppressWarnings("deprecation") @Test @Category(TestSuites.Broken.class) public void testXmlCalendarZ() throws Exception {
  String NS="http://example.org/rdf/";
  int OFFSET=TimeZone.getDefault().getOffset(new Date(2007,Calendar.NOVEMBER,6).getTime()) / 1000 / 60;
  String SELECT_BY_DATE="SELECT ?s ?d WHERE { ?s <http://www.w3.org/1999/02/22-rdf-syntax-ns#value> ?d . FILTER (?d <= ?date) }";
  DatatypeFactory data=DatatypeFactory.newInstance();
  for (int i=1; i < 5; i++) {
    URI uri=vf.createURI(NS,"date" + i);
    XMLGregorianCalendar xcal=data.newXMLGregorianCalendar();
    xcal.setYear(2000);
    xcal.setMonth(11);
    xcal.setDay(i * 2);
    testCon.add(uri,RDF.VALUE,vf.createLiteral(xcal));
    URI uriz=vf.createURI(NS,"dateZ" + i);
    xcal=data.newXMLGregorianCalendar();
    xcal.setYear(2007);
    xcal.setMonth(11);
    xcal.setDay(i * 2);
    xcal.setTimezone(OFFSET);
    testCon.add(uriz,RDF.VALUE,vf.createLiteral(xcal));
  }
  XMLGregorianCalendar xcal=data.newXMLGregorianCalendar();
  xcal.setYear(2007);
  xcal.setMonth(11);
  xcal.setDay(6);
  xcal.setTimezone(OFFSET);
  TupleQuery query=testCon.prepareTupleQuery(QueryLanguage.SPARQL,SELECT_BY_DATE);
  query.setBinding("date",vf.createLiteral(xcal));
  TupleQueryResult result=query.evaluate();
  List<BindingSet> list=new ArrayList<BindingSet>();
  while (result.hasNext()) {
    list.add(result.next());
  }
  assertEquals(7,list.size());
}
 

Example 25

From project ChessCraft, under directory /src/main/java/me/desht/chesscraft/results/.

Source file: ResultEntry.java

  20 
vote

void save(Connection connection){
  try {
    PreparedStatement stmt=connection.prepareStatement("INSERT INTO results VALUES (?, ?, ?, ?, ?, ?, ?)");
    stmt.setString(1,playerWhite);
    stmt.setString(2,playerBlack);
    stmt.setString(3,gameName);
    stmt.setDate(4,new Date(startTime));
    stmt.setDate(5,new Date(endTime));
    stmt.setString(6,result.toString());
    stmt.setString(7,pgnResult);
    stmt.executeUpdate();
  }
 catch (  SQLException e) {
    LogUtils.warning("SQL insert failed: " + e.getMessage());
  }
}
 

Example 26

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

Source file: SQLService.java

  20 
vote

private void bind(PreparedStatement pstmt,int i,Object value) throws SQLException {
  if (value == null) {
    pstmt.setNull(i,Types.VARCHAR);
  }
 else   if (value instanceof String) {
    String s=(String)value;
    if ("$now".equals(s)) {
      pstmt.setDate(i,new Date(new java.util.Date().getTime()));
    }
 else {
      pstmt.setString(i,(String)value);
    }
  }
 else   if (value instanceof Integer) {
    pstmt.setInt(i,((Integer)value).intValue());
  }
 else   if (value instanceof Long) {
    pstmt.setLong(i,((Long)value).longValue());
  }
 else   if (value instanceof BigDecimal) {
    pstmt.setBigDecimal(i,(BigDecimal)value);
  }
 else   if (value instanceof Date) {
    pstmt.setDate(i,(Date)value);
  }
 else   if (value instanceof Timestamp) {
    pstmt.setTimestamp(i,(Timestamp)value);
  }
 else   if (value instanceof Float) {
    pstmt.setFloat(i,((Float)value).floatValue());
  }
 else   if (value instanceof Double) {
    pstmt.setDouble(i,((Double)value).doubleValue());
  }
 else {
    pstmt.setObject(i,value);
  }
}
 

Example 27

From project hs4j, under directory /src/main/java/com/google/code/hs4j/impl/.

Source file: ResultSetImpl.java

  20 
vote

private Date getDateFromString(String stringVal,Calendar cal) throws SQLException {
  if (stringVal == null) {
    this.lastWasNull=true;
    return null;
  }
  String val=stringVal.trim();
  if (val.length() == 0) {
    this.lastWasNull=true;
    return null;
  }
  if (val.equals("0") || val.equals("0000-00-00") || val.equals("0000-00-00 00:00:00")|| val.equals("00000000000000")|| val.equals("0")) {
    Calendar calendar=null;
    if (cal != null) {
      calendar=Calendar.getInstance(cal.getTimeZone());
    }
 else {
      calendar=Calendar.getInstance();
    }
    calendar.set(Calendar.YEAR,1);
    calendar.set(Calendar.MONTH,0);
    calendar.set(Calendar.DAY_OF_MONTH,1);
    return new Date(calendar.getTimeInMillis());
  }
  DateFormat dateFormat=DateFormat.getDateTimeInstance();
  if (cal != null) {
    TimeZone timeZone=cal.getTimeZone();
    dateFormat.setTimeZone(timeZone);
  }
  try {
    return new Date(dateFormat.parse(val).getTime());
  }
 catch (  ParseException e) {
    throw new SQLException("Parse date failure:" + val);
  }
}
 

Example 28

From project MensaUPB, under directory /src/de/najidev/mensaupb/helper/.

Source file: Context.java

  20 
vote

public Context(Configuration config){
  Calendar calendar=Calendar.getInstance();
{
switch (calendar.get(Calendar.DAY_OF_WEEK)) {
case Calendar.SATURDAY:
      calendar.add(Calendar.DAY_OF_MONTH,1);
case Calendar.SUNDAY:
    calendar.add(Calendar.DAY_OF_MONTH,1);
  break;
}
while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) calendar.add(Calendar.DAY_OF_WEEK,-1);
}
for (int i=0; i < availableDates.length; i++) {
availableDates[i]=new Date(calendar.getTimeInMillis());
calendar.add(Calendar.DATE,1);
}
}
 

Example 29

From project Newsreader, under directory /bundles/org.eclipse.ecf.protocol.nntp.store.derby/src/org/eclipse/ecf/protocol/nntp/store/derby/internal/.

Source file: NewsgroupDAO.java

  20 
vote

public void insertNewsgroup(INewsgroup newsgroup) throws StoreException {
  try {
    insertNewsgroup.setString(1,newsgroup.getServer().getURL());
    insertNewsgroup.setString(2,newsgroup.getNewsgroupName());
    insertNewsgroup.setString(3,newsgroup.isSubscribed() ? "1" : "0");
    insertNewsgroup.setString(4,newsgroup.getDescription());
    insertNewsgroup.setDate(5,new Date(Calendar.getInstance().getTimeInMillis()));
    insertNewsgroup.setInt(6,newsgroup.getLowWaterMark());
    insertNewsgroup.setInt(7,newsgroup.getHighWaterMark());
    insertNewsgroup.setInt(8,newsgroup.getArticleCount());
    insertNewsgroup.execute();
    ResultSet result=insertNewsgroup.getGeneratedKeys();
    if (result.next())     newsgroup.setProperty("DB_ID",result.getInt(1) + "");
  }
 catch (  SQLException e) {
    throw new StoreException(e.getMessage(),e);
  }
}
 

Example 30

From project Weave, under directory /JTDS_SqlServerDriver/src/main/net/sourceforge/jtds/jdbc/.

Source file: DateTime.java

  20 
vote

/** 
 * Retrieves the current datetime value as a Date.
 * @return the current datetime value as a <code>java.sql.Date</code>
 */
public Date toDate(){
  if (dateValue == null) {
    if (!unpacked) {
      unpackDateTime();
    }
    GregorianCalendar cal=(GregorianCalendar)calendar.get();
    cal.set(Calendar.YEAR,this.year);
    cal.set(Calendar.MONTH,this.month - 1);
    cal.set(Calendar.DAY_OF_MONTH,this.day);
    cal.set(Calendar.HOUR_OF_DAY,0);
    cal.set(Calendar.MINUTE,0);
    cal.set(Calendar.SECOND,0);
    cal.set(Calendar.MILLISECOND,0);
    dateValue=new Date(cal.getTime().getTime());
  }
  return dateValue;
}
 

Example 31

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

Source file: DayOfYear.java

  19 
vote

public static Integer dayOfYear(Comparable<?> param,Calendar cal) throws ParseException {
  if (param == null) {
    return null;
  }
  if (param instanceof Timestamp || param instanceof Date) {
    java.util.Date ts=(java.util.Date)param;
    cal.setTimeInMillis(ts.getTime());
    return new Integer(cal.get(DAY_OF_YEAR));
  }
  throw new ParseException(WRONG_TYPE + " weekofyear(" + param.getClass()+ ")");
}
 

Example 32

From project big-data-plugin, under directory /shims/common/src-mapred/org/pentaho/hadoop/mapreduce/converter/.

Source file: TypeConverterFactory.java

  19 
vote

/** 
 * Attempt to determine the Java  {@link Class} for the {@link ValueMetaInterface} provided
 * @param vmi Value Meta with type information to look up
 * @return the class that represents the type {@link ValueMetaInterface} represents; {@code null} if no type can be matched.
 */
public Class<?> getJavaClass(ValueMetaInterface vmi){
  Class<?> metaClass=null;
switch (vmi.getType()) {
case ValueMeta.TYPE_BIGNUMBER:
    metaClass=BigDecimal.class;
  break;
case ValueMeta.TYPE_BINARY:
metaClass=byte[].class;
break;
case ValueMeta.TYPE_BOOLEAN:
metaClass=Boolean.class;
break;
case ValueMeta.TYPE_DATE:
metaClass=Date.class;
break;
case ValueMeta.TYPE_INTEGER:
metaClass=Long.class;
break;
case ValueMeta.TYPE_NUMBER:
metaClass=Double.class;
break;
case ValueMeta.TYPE_STRING:
metaClass=String.class;
break;
case ValueMeta.TYPE_SERIALIZABLE:
metaClass=Object.class;
break;
}
return metaClass;
}
 

Example 33

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

Source file: CallableStatementHandle.java

  19 
vote

/** 
 * {@inheritDoc}
 * @see java.sql.CallableStatement#getDate(int)
 */
public Date getDate(int parameterIndex) throws SQLException {
  checkClosed();
  try {
    return this.internalCallableStatement.getDate(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: BooleanColumnGeneratorTest.java

  19 
vote

public void test_convertField_fieldNotFound() throws Exception {
  Object[][] matrix={{"FIELD_A","FIELD_B","FIELD_C"},{Date.valueOf("1966-10-10"),null,"FININF"}};
  ResultSet rs=new FakeResultSet(matrix).getStub();
  rs.next();
  BooleanColumnGenerator bcg=new BooleanColumnGenerator(fieldInfo,"DEST_FIELD",null);
  try {
    bcg.proceedField(rs);
    fail("Le test doit echouer ! le champ FIELD_Z n'existe pas");
  }
 catch (  SQLException e) {
    assertEquals("Unknown column name : COL_1",e.getMessage());
  }
}
 

Example 35

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

Source file: GenericTableModel.java

  19 
vote

/** 
 * Ajoute une ligne dans le model
 * @throws RuntimeException TODO
 * @throws IllegalArgumentException TODO
 */
void addNewLine(){
  if (readOnly) {
    throw new RuntimeException("Impossible d'ajouter une ligne si le composant est en mode lecture seule");
  }
  List newBlankLineList=new ArrayList();
  for (int i=0; i < columnDBNameList.size(); i++) {
    if (columnClass[i] == Boolean.class) {
      newBlankLineList.add(new Boolean(false));
    }
 else     if (columnClass[i] == Date.class) {
      newBlankLineList.add(null);
    }
 else     if (columnClass[i] == Integer.class) {
      newBlankLineList.add(null);
    }
 else     if (columnClass[i] == String.class) {
      newBlankLineList.add(null);
    }
 else     if (columnClass[i] == Number.class) {
      newBlankLineList.add(null);
    }
 else {
      throw new IllegalArgumentException();
    }
  }
  dataList.add(0,newBlankLineList);
  List newkeyValueLineList=new ArrayList();
  keyValueList.add(0,newkeyValueLineList);
  fireTableDataChanged();
}
 

Example 36

From project commons-mom, under directory /src/test/java/com/zauberlabs/commons/mom/test/.

Source file: Shipment.java

  19 
vote

/** 
 * constructor 
 */
public Shipment(final List<Order> orders,final String description,final Date createdOn,final Priority priority,final boolean canceled){
  this.orders=orders;
  this.description=description;
  this.createdOn=createdOn;
  this.priority=priority;
  this.canceled=canceled;
}
 

Example 37

From project jdbi, under directory /src/main/java/org/skife/jdbi/v2/.

Source file: OutParameters.java

  19 
vote

private Long getEpoch(String name){
  Object obj=map.get(name);
  if (obj == null) {
    throw new IllegalArgumentException(String.format("Parameter %s does not exist",name));
  }
  if (obj instanceof java.util.Date) {
    return ((java.util.Date)obj).getTime();
  }
 else {
    throw new IllegalArgumentException(String.format("Parameter %s is not Date but %s",name,obj.getClass()));
  }
}
 

Example 38

From project l2jserver2, under directory /l2jserver2-common/src/main/java/com/l2jserver/service/database/orientdb/.

Source file: AbstractOrientDatabaseService.java

  19 
vote

/** 
 * Returns the  {@link OType} representing the type represented by{@link Class}
 * @param cls the class
 * @return the {@link OType}. Never null.
 */
private OType getType(Class<?> cls){
  if (cls.isEnum()) {
    return OType.STRING;
  }
 else   if (ClassUtils.isSubclass(cls,Date.class)) {
    return OType.DATETIME;
  }
 else {
    return OType.getTypeByClass(cls);
  }
}
 

Example 39

From project logback, under directory /logback-core/src/test/java/ch/qos/logback/core/rolling/.

Source file: ScaffoldingForRollingTests.java

  19 
vote

protected void addExpectedFileName_ByDate(String outputDir,String testId,Date date,boolean gzExtension){
  String fn=outputDir + testId + "-"+ SDF.format(date);
  if (gzExtension) {
    fn+=".gz";
  }
  expectedFilenameList.add(fn);
}
 

Example 40

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

Source file: NamedParameterStatement.java

  19 
vote

/** 
 * Sets a parameter.
 * @param name  parameter name
 * @param value parameter value
 * @throws SQLException if an error occurred
 * @throws IllegalArgumentException if the parameter does not exist
 * @see PreparedStatement#setTimestamp(int,java.sql.Timestamp)
 */
public void setDate(String name,Date value) throws SQLException {
  int[] indexes=getIndexes(name);
  for (int i=0; i < indexes.length; i++) {
    statement.setDate(indexes[i],value);
  }
}
 

Example 41

From project objectos-comuns-jdbc, under directory /src/main/java/br/com/objectos/comuns/relational/jdbc/.

Source file: ResultSetWrapperPrefix.java

  19 
vote

@Override public Date getDate(String columnLabel){
  try {
    return rs.getDate(col(columnLabel));
  }
 catch (  SQLException e) {
    throw new SQLRuntimeException(e);
  }
}
 

Example 42

From project OpenSettlers, under directory /src/java/soc/server/database/.

Source file: SOCDBHelper.java

  19 
vote

/** 
 * DOCUMENT ME!
 * @param userName DOCUMENT ME!
 * @param host DOCUMENT ME!
 * @param password DOCUMENT ME!
 * @param email DOCUMENT ME!
 * @param time DOCUMENT ME!
 * @return true if the account was created
 * @throws SQLException DOCUMENT ME!
 */
public static boolean createAccount(String userName,String host,String password,String email,long time) throws SQLException {
  if (checkConnection()) {
    try {
      java.sql.Date sqlDate=new java.sql.Date(time);
      Calendar cal=Calendar.getInstance();
      createAccountCommand.setString(1,userName);
      createAccountCommand.setString(2,host);
      createAccountCommand.setString(3,password);
      createAccountCommand.setString(4,email);
      createAccountCommand.setDate(5,sqlDate,cal);
      createAccountCommand.setInt(6,0);
      createAccountCommand.setInt(7,0);
      createAccountCommand.setInt(8,1);
      createAccountCommand.setInt(9,0);
      createAccountCommand.executeUpdate();
      return true;
    }
 catch (    SQLException sqlE) {
      handleSQLException(sqlE);
    }
  }
  return false;
}
 

Example 43

From project rocoto, under directory /src/main/java/org/nnsoft/guice/rocoto/converters/.

Source file: SQLDateConverter.java

  19 
vote

/** 
 * {@inheritDoc}
 */
public Object convert(String value,TypeLiteral<?> toType){
  try {
    return Date.valueOf(value);
  }
 catch (  Throwable t) {
    throw new ProvisionException("String must be in JDBC format [yyyy-MM-dd] to create a java.sql.Date");
  }
}
 

Example 44

From project Shepherd-Project, under directory /src/main/java/org/ecocean/servlet/export/.

Source file: EncounterSearchExportShapefile.java

  19 
vote

/** 
 * Here is how you can use a SimpleFeatureType builder to create the schema for your shapefile dynamically. <p> This method is an improvement on the code used in the main method above (where we used DataUtilities.createFeatureType) because we can set a Coordinate Reference System for the FeatureType and a a maximum field length for the 'name' field dddd
 */
private static SimpleFeatureType createFeatureType(){
  SimpleFeatureTypeBuilder builder=new SimpleFeatureTypeBuilder();
  builder.setName(CommonConfiguration.getHTMLTitle());
  builder.setCRS(DefaultGeographicCRS.WGS84);
  builder.add("Location",Point.class);
  builder.add("Date",java.sql.Date.class);
  builder.add("Encounter",String.class);
  builder.add("Individual",String.class);
  builder.add("Sex",String.class);
  builder.add("Haplotype",String.class);
  builder.add("URL",String.class);
  final SimpleFeatureType LOCATION=builder.buildFeatureType();
  return LOCATION;
}
 

Example 45

From project spatial4j, under directory /src/main/java/com/spatial4j/core/io/geonames/.

Source file: Geoname.java

  19 
vote

public Geoname(String line){
  String[] vals=line.split("\t");
  id=Integer.parseInt(vals[0]);
  name=vals[1];
  nameASCII=vals[2];
  alternateNames=vals[3].split(",");
  latitude=Double.parseDouble(vals[4]);
  longitude=Double.parseDouble(vals[5]);
  featureClass=vals[6].length() > 0 ? vals[6].charAt(0) : 'S';
  featureCode=vals[7];
  countryCode=vals[8];
  countryCode2=vals[9].split(",");
  adminCode1=vals[10];
  adminCode2=vals[11];
  adminCode3=vals[12];
  adminCode4=vals[13];
  if (vals[14].length() > 0) {
    population=Long.decode(vals[14]);
  }
  if (vals[15].length() > 0) {
    elevation=Integer.decode(vals[15]);
  }
  if (vals[16].length() > 0) {
    gtopo30=Integer.decode(vals[16]);
  }
  timezone=vals[17];
  if (vals[18].length() > 0) {
    modified=Date.valueOf(vals[18]);
  }
}
 

Example 46

From project spring-insight-plugins, under directory /collection-plugins/jdbc/src/test/java/com/springsource/insight/plugin/jdbc/.

Source file: JdbcPreparedStatementOperationCollectionAspectTest.java

  19 
vote

@Test public void operationCollectionForPreparedStatement() throws SQLException {
  Connection c=dataSource.getConnection();
  String sql="select * from appointment where owner = ? and dateTime = ?";
  PreparedStatement ps=c.prepareStatement(sql);
  ps.setString(1,"Agim");
  ps.setDate(2,Date.valueOf("2009-06-01"));
  ps.execute();
  Operation operation=getLastEntered();
  assertEquals(sql,operation.get("sql"));
  @SuppressWarnings("unchecked") List<String> parameters=(List<String>)operation.asMap().get("params");
  assertEquals(2,parameters.size());
  assertArrayEquals(new Object[]{"Agim",Date.valueOf("2009-06-01").toString()},parameters.toArray());
}
 

Example 47

From project sqoop, under directory /src/java/org/apache/sqoop/lib/.

Source file: JdbcWritableBridge.java

  19 
vote

public static void writeDate(Date val,int paramIdx,int sqlType,PreparedStatement s) throws SQLException {
  if (null == val) {
    s.setNull(paramIdx,sqlType);
  }
 else {
    s.setDate(paramIdx,val);
  }
}
 

Example 48

From project tedis, under directory /tedis-replicator/src/main/java/com/taobao/common/tedis/replicator/mysql/.

Source file: MySQLPacket.java

  19 
vote

/** 
 * Reads a date from stream given its length and returns the corresponding {@link Date}
 * @param length size of the date data
 * @return jdbc Date decoded from stream
 */
public Date getDate(int length){
  int year=0;
  int month=0;
  int day=0;
  if (length >= 4) {
    year=getUnsignedShort();
    if (logger.isTraceEnabled())     logger.trace("year=" + year);
    month=getByte();
    if (logger.isTraceEnabled())     logger.trace("month=" + month);
    day=getByte();
    if (logger.isTraceEnabled())     logger.trace("day=" + day);
  }
  String date="" + year + "-"+ month+ "-"+ day;
  return Date.valueOf(date);
}
 

Example 49

From project WaarpCommon, under directory /src/main/java/org/waarp/common/xml/.

Source file: XmlValue.java

  19 
vote

/** 
 * Utility function to get a clone of a value
 * @param type
 * @param value
 * @return the clone Object
 * @throws InvalidObjectException
 */
public static Object getCloneValue(XmlType type,Object value) throws InvalidObjectException {
  if (value == null) {
    throw new InvalidObjectException("Can not convert value from null to type " + type.classType);
  }
switch (type) {
case BOOLEAN:
    return new Boolean((Boolean)value);
case INTEGER:
  return new Integer((Integer)value);
case FLOAT:
return new Float((Float)value);
case CHARACTER:
return new Character((Character)value);
case BYTE:
return new Byte((Byte)value);
case LONG:
return new Long((Long)value);
case DOUBLE:
return new Double((Double)value);
case SHORT:
return new Short((Short)value);
case SQLDATE:
return new java.sql.Date(((java.sql.Date)value).getTime());
case TIMESTAMP:
return new Timestamp(((Timestamp)value).getTime());
case STRING:
return new String((String)value);
case XVAL:
return new XmlValue((XmlValue)value);
case EMPTY:
default :
throw new InvalidObjectException("Can not convert value from " + value.getClass() + " to type "+ type.classType);
}
}