public int getWeek(Tuple input) {
    Timestamp ts = (Timestamp) input.getValueByField("eventTime");
    Calendar cal = Calendar.getInstance();
    try {
      cal.setTime(new Date(ts.getTime()));
    } catch (Exception e) {
      e.printStackTrace();
    }

    return cal.get(Calendar.WEEK_OF_YEAR);
  }
Example #2
1
 public ReturnTuple<Integer> newCustomer(int id, Timestamp timestamp)
     throws RemoteException, TransactionAbortedException, InvalidTransactionException {
   if (!isMaster) {
     System.out.println("Slave retransmitting newCustomer to master");
     return this.getMaster().newCustomer(id, timestamp);
   } else {
     timestamp.stamp();
     int rid =
         Integer.parseInt(
             String.valueOf(id)
                 + String.valueOf(Calendar.getInstance().get(Calendar.MILLISECOND))
                 + String.valueOf(Math.round(Math.random() * 100 + 1)));
     NewCustomerWithIdRMICommand nc =
         new NewCustomerWithIdRMICommand(carGroup, flightGroup, roomGroup, id, rid);
     nc.setTimestampObject(timestamp);
     ReturnTuple<Integer> result = null;
     try {
       overseer.validTransaction(id);
       lm.Lock(id, Customer.getKey(rid), nc.getRequiredLock());
       nc.execute();
       result = new ReturnTuple<Integer>(rid, nc.success.timestamp);
       overseer.addCommandToTransaction(id, nc);
     } catch (DeadlockException d) {
       timestamp.stamp();
       overseer.abort(id);
       timestamp.stamp();
       throw new TransactionAbortedException(timestamp);
     } catch (TransactionAbortedException tae) {
       tae.t = timestamp;
       throw tae;
     } catch (InvalidTransactionException ite) {
       ite.t = timestamp;
       throw ite;
     }
     result.timestamp.stamp();
     return result;
   }
 }
Example #3
0
 // Delete rooms from a location
 public ReturnTuple<Boolean> deleteRooms(int id, String location, Timestamp timestamp)
     throws RemoteException, TransactionAbortedException, InvalidTransactionException {
   if (!isMaster) {
     System.out.println("Slave retransmitting deleteRooms to master");
     return this.getMaster().deleteRooms(id, location, timestamp);
   } else {
     timestamp.stamp();
     DeleteRoomsRMICommand dr = new DeleteRoomsRMICommand(roomGroup, id, location);
     dr.setTimestampObject(timestamp);
     ReturnTuple<Boolean> result = null;
     try {
       overseer.validTransaction(id);
       lm.Lock(id, Hotel.getKey(location), dr.getRequiredLock());
       dr.execute();
       result = dr.success;
       if (result.result) overseer.addCommandToTransaction(id, dr);
     } catch (DeadlockException d) {
       timestamp.stamp();
       overseer.abort(id);
       timestamp.stamp();
       throw new TransactionAbortedException(timestamp);
     } catch (TransactionAbortedException tae) {
       tae.t = timestamp;
       throw tae;
     } catch (InvalidTransactionException ite) {
       ite.t = timestamp;
       throw ite;
     }
     result.timestamp.stamp();
     return result;
   }
 }
Example #4
0
 // Create a new car location or add cars to an existing location
 //  NOTE: if price <= 0 and the location already exists, it maintains its current price
 public ReturnTuple<Boolean> addCars(
     int id, String location, int count, int price, Timestamp timestamp)
     throws RemoteException, TransactionAbortedException, InvalidTransactionException {
   if (!isMaster) {
     System.out.println("Slave retransmitting addCars to master");
     return this.getMaster().addCars(id, location, count, price, timestamp);
   } else {
     timestamp.stamp();
     AddCarsRMICommand ac = new AddCarsRMICommand(carGroup, id, location, count, price);
     ac.setTimestampObject(timestamp);
     ReturnTuple<Boolean> result = null;
     try {
       overseer.validTransaction(id);
       lm.Lock(id, Car.getKey(location), ac.getRequiredLock());
       ac.execute();
       result = ac.success;
       if (result.result) overseer.addCommandToTransaction(id, ac);
     } catch (DeadlockException d) {
       timestamp.stamp();
       overseer.abort(id);
       timestamp.stamp();
       throw new TransactionAbortedException(timestamp);
     } catch (TransactionAbortedException tae) {
       tae.t = timestamp;
       throw tae;
     } catch (InvalidTransactionException ite) {
       ite.t = timestamp;
       throw ite;
     }
     result.timestamp.stamp();
     return result;
   }
 }
Example #5
0
 // Returns price of cars at this location
 public ReturnTuple<Integer> queryCarsPrice(int id, String location, Timestamp timestamp)
     throws RemoteException, TransactionAbortedException, InvalidTransactionException {
   if (!isMaster) {
     System.out.println("Slave retransmitting queryCarsPrice to master");
     return this.getMaster().queryCarsPrice(id, location, timestamp);
   } else {
     QueryCarsPriceRMICommand qcp = new QueryCarsPriceRMICommand(roomGroup, id, location);
     qcp.setTimestampObject(timestamp);
     ReturnTuple<Integer> result = null;
     try {
       overseer.validTransaction(id);
       lm.Lock(id, Car.getKey(location), qcp.getRequiredLock());
       qcp.execute();
       result = qcp.price;
     } catch (DeadlockException d) {
       timestamp.stamp();
       overseer.abort(id);
       timestamp.stamp();
       throw new TransactionAbortedException(timestamp);
     } catch (TransactionAbortedException tae) {
       tae.t = timestamp;
       throw tae;
     } catch (InvalidTransactionException ite) {
       ite.t = timestamp;
       throw ite;
     }
     result.timestamp.stamp();
     return result;
   }
 }
Example #6
0
 // Deletes customer from the database.
 public ReturnTuple<Boolean> deleteCustomer(int id, int customerID, Timestamp timestamp)
     throws RemoteException, TransactionAbortedException, InvalidTransactionException {
   if (!isMaster) {
     System.out.println("Slave retransmitting deleteCustomer to master");
     return this.getMaster().deleteCustomer(id, customerID, timestamp);
   } else {
     timestamp.stamp();
     DeleteCustomerRMICommand dc =
         new DeleteCustomerRMICommand(carGroup, flightGroup, roomGroup, id, customerID);
     dc.setTimestampObject(timestamp);
     ReturnTuple<Boolean> result = null;
     try {
       overseer.validTransaction(id);
       lm.Lock(id, Customer.getKey(customerID), dc.getRequiredLock());
       dc.execute();
       result = dc.success;
       if (result.result) overseer.addCommandToTransaction(id, dc);
     } catch (DeadlockException d) {
       timestamp.stamp();
       overseer.abort(id);
       timestamp.stamp();
       throw new TransactionAbortedException(timestamp);
     } catch (TransactionAbortedException tae) {
       tae.t = timestamp;
       throw tae;
     } catch (InvalidTransactionException ite) {
       ite.t = timestamp;
       throw ite;
     }
     result.timestamp.stamp();
     return result;
   }
 }
Example #7
0
 // Create a new flight, or add seats to existing flight
 //  NOTE: if flightPrice <= 0 and the flight already exists, it maintains its current price
 public ReturnTuple<Boolean> addFlight(
     int id, int flightNum, int flightSeats, int flightPrice, Timestamp timestamp)
     throws RemoteException, TransactionAbortedException, InvalidTransactionException {
   if (!isMaster) {
     System.out.println("Slave retransmitting addFlight to master");
     return this.getMaster().addFlight(id, flightNum, flightSeats, flightPrice, timestamp);
   } else {
     timestamp.stamp();
     AddFlightRMICommand af =
         new AddFlightRMICommand(flightGroup, id, flightNum, flightSeats, flightPrice);
     af.setTimestampObject(timestamp);
     ReturnTuple<Boolean> result = null;
     try {
       overseer.validTransaction(id);
       lm.Lock(id, Flight.getKey(flightNum), af.getRequiredLock());
       af.execute();
       result = af.success;
       if (result.result) overseer.addCommandToTransaction(id, af);
     } catch (DeadlockException d) {
       timestamp.stamp();
       overseer.abort(id);
       timestamp.stamp();
       throw new TransactionAbortedException(timestamp);
     } catch (TransactionAbortedException tae) {
       tae.t = timestamp;
       throw tae;
     } catch (InvalidTransactionException ite) {
       ite.t = timestamp;
       throw ite;
     }
     result.timestamp.stamp();
     return result;
   }
 }
Example #8
0
 // Returns the number of empty seats on this flight
 public ReturnTuple<Integer> queryFlight(int id, int flightNum, Timestamp timestamp)
     throws RemoteException, TransactionAbortedException, InvalidTransactionException {
   if (!isMaster) {
     System.out.println("Slave retransmitting queryFlight to master");
     return this.getMaster().queryFlight(id, flightNum, timestamp);
   } else {
     timestamp.stamp();
     QueryFlightRMICommand qf = new QueryFlightRMICommand(flightGroup, id, flightNum);
     qf.setTimestampObject(timestamp);
     ReturnTuple<Integer> result = null;
     try {
       overseer.validTransaction(id);
       lm.Lock(id, Flight.getKey(flightNum), qf.getRequiredLock());
       qf.execute();
       result = qf.numSeats;
     } catch (DeadlockException d) {
       timestamp.stamp();
       overseer.abort(id);
       timestamp.stamp();
       throw new TransactionAbortedException(timestamp);
     } catch (TransactionAbortedException tae) {
       tae.t = timestamp;
       throw tae;
     } catch (InvalidTransactionException ite) {
       ite.t = timestamp;
       throw ite;
     }
     result.timestamp.stamp();
     return result;
   }
 }
Example #9
0
 /**
  * Date In Period
  *
  * @param date date
  * @return true if in period
  */
 public boolean isInPeriod(Timestamp date) {
   if (date == null) return false;
   Timestamp dateOnly = TimeUtil.getDay(date);
   Timestamp from = TimeUtil.getDay(getStartDate());
   if (dateOnly.before(from)) return false;
   Timestamp to = TimeUtil.getDay(getEndDate());
   if (dateOnly.after(to)) return false;
   return true;
 } //	isInPeriod
  public void execute(Tuple input) {

    LOG.info("Entered prediction bolt execute...");
    String eventType = input.getStringByField("eventType");

    double prediction;

    if (eventType.equals("Normal")) {
      double[] predictionParams = enrichEvent(input);
      prediction = model.predict(Vectors.dense(predictionParams));

      LOG.info("Prediction is: " + prediction);

      String driverName = input.getStringByField("driverName");
      String routeName = input.getStringByField("routeName");
      int truckId = input.getIntegerByField("truckId");
      Timestamp eventTime = (Timestamp) input.getValueByField("eventTime");
      double longitude = input.getDoubleByField("longitude");
      double latitude = input.getDoubleByField("latitude");
      double driverId = input.getIntegerByField("driverId");
      SimpleDateFormat sdf = new SimpleDateFormat();

      collector.emit(
          input,
          new Values(
              prediction == 0.0 ? "normal" : "violation",
              driverName,
              routeName,
              driverId,
              truckId,
              sdf.format(new Date(eventTime.getTime())),
              longitude,
              latitude,
              predictionParams[0] == 1 ? "Y" : "N", // driver certification status
              predictionParams[1] == 1 ? "miles" : "hourly", // driver wage plan
              predictionParams[2] * 100, // hours feature was scaled down by 100
              predictionParams[3] * 1000, // miles feature was scaled down by 1000
              predictionParams[4] == 1 ? "Y" : "N", // foggy weather
              predictionParams[5] == 1 ? "Y" : "N", // rainy weather
              predictionParams[6] == 1 ? "Y" : "N" // windy weather
              ));

      if (prediction == 1.0) {

        try {
          writePredictionToHDFS(input, predictionParams, prediction);
        } catch (Exception e) {
          e.printStackTrace();
          throw new RuntimeException("Couldn't write prediction to hdfs" + e);
        }
      }
    }

    // acknowledge even if there is an error
    collector.ack(input);
  }
Example #11
0
 public ReturnTuple<Object> abort(int id, Timestamp timestamp)
     throws RemoteException, TransactionAbortedException, InvalidTransactionException {
   if (!isMaster) {
     System.out.println("Slave retransmitting abort to master");
     return this.getMaster().abort(id, timestamp);
   } else {
     timestamp.stamp();
     overseer.abort(id);
     timestamp.stamp();
     return new ReturnTuple<Object>(null, timestamp);
   }
 }
Example #12
0
 public ReturnTuple<Boolean> commit(int id, Timestamp timestamp)
     throws RemoteException, TransactionAbortedException, InvalidTransactionException {
   if (!isMaster) {
     System.out.println("Slave retransmitting commit to master");
     return this.getMaster().commit(id, timestamp);
   } else {
     timestamp.stamp();
     boolean result = overseer.commit(id);
     timestamp.stamp();
     return new ReturnTuple<Boolean>(result, timestamp);
   }
 }
Example #13
0
 public ReturnTuple<Integer> start(Timestamp timestamp) throws RemoteException {
   if (!isMaster) {
     System.out.println("Slave retransmitting start to master");
     return this.getMaster().start(timestamp);
   } else {
     timestamp.stamp();
     int tId;
     tId = overseer.createTransaction(lm);
     timestamp.stamp();
     return new ReturnTuple<Integer>(tId, timestamp);
   }
 }
Example #14
0
 /* reserve an itinerary */
 public ReturnTuple<Boolean> itinerary(
     int id,
     int customer,
     Vector flightNumbers,
     String location,
     boolean Car,
     boolean Room,
     Timestamp timestamp)
     throws RemoteException, TransactionAbortedException, InvalidTransactionException {
   if (!isMaster) {
     System.out.println("Slave retransmitting itinerary to master");
     return this.getMaster()
         .itinerary(id, customer, flightNumbers, location, Car, Room, timestamp);
   } else {
     timestamp.stamp();
     ItineraryRMICommand i =
         new ItineraryRMICommand(
             carGroup, flightGroup, roomGroup, id, customer, flightNumbers, location, Car, Room);
     i.setTimestampObject(timestamp);
     ReturnTuple<Boolean> result = null;
     try {
       overseer.validTransaction(id);
       lm.Lock(id, Customer.getKey(customer), i.getRequiredLock());
       lm.Lock(id, ResImpl.Car.getKey(location), i.getRequiredLock());
       lm.Lock(id, Hotel.getKey(location), i.getRequiredLock());
       for (Object flightNo : flightNumbers) {
         int flightNum = Integer.parseInt((String) flightNo);
         lm.Lock(id, Flight.getKey(flightNum), i.getRequiredLock());
       }
       i.execute();
       result = i.success;
       if (result.result && !i.error()) overseer.addCommandToTransaction(id, i);
     } catch (DeadlockException d) {
       timestamp.stamp();
       overseer.abort(id);
       timestamp.stamp();
       throw new TransactionAbortedException(timestamp);
     } catch (TransactionAbortedException tae) {
       tae.t = timestamp;
       throw tae;
     } catch (InvalidTransactionException ite) {
       ite.t = timestamp;
       throw ite;
     }
     result.timestamp.stamp();
     return result;
   }
 }
Example #15
0
  private Timestamp initTimestamp(Object o) {
    try {
      if (o == null) {
        // most frequent
        return new Timestamp();
      } else if (o instanceof String) {
        // second most frequent
        return new Timestamp((String) o);
      } else if (o instanceof JrubyTimestampExtLibrary.RubyTimestamp) {
        return new Timestamp(((JrubyTimestampExtLibrary.RubyTimestamp) o).getTimestamp());
      } else if (o instanceof Timestamp) {
        return new Timestamp((Timestamp) o);
      } else if (o instanceof DateTime) {
        return new Timestamp((DateTime) o);
      } else if (o instanceof Date) {
        return new Timestamp((Date) o);
      } else if (o instanceof RubySymbol) {
        return new Timestamp(((RubySymbol) o).asJavaString());
      } else {
        Event.logger.warn("Unrecognized " + TIMESTAMP + " value type=" + o.getClass().toString());
      }
    } catch (IllegalArgumentException e) {
      Event.logger.warn("Error parsing " + TIMESTAMP + " string value=" + o.toString());
    }

    tag(TIMESTAMP_FAILURE_TAG);
    this.data.put(TIMESTAMP_FAILURE_FIELD, o);

    return Timestamp.now();
  }
Example #16
0
 // return a bill
 public ReturnTuple<String> queryCustomerInfo(int id, int customerID, Timestamp timestamp)
     throws RemoteException, TransactionAbortedException, InvalidTransactionException {
   if (!isMaster) {
     System.out.println("Slave retransmitting queryCustomerInfo to master");
     return this.getMaster().queryCustomerInfo(id, customerID, timestamp);
   } else {
     timestamp.stamp();
     QueryCustomerInfoRMICommand qci =
         new QueryCustomerInfoRMICommand(carGroup, flightGroup, roomGroup, id, customerID);
     qci.setTimestampObject(timestamp);
     ReturnTuple<String> result = null;
     try {
       Vector<Integer> flightNos;
       Vector<String> locations;
       overseer.validTransaction(id);
       lm.Lock(id, Customer.getKey(customerID), qci.getRequiredLock());
       qci.execute();
       flightNos = qci.getCustomerFlightReservations();
       for (int flightNo : flightNos) {
         lm.Lock(id, Flight.getKey(flightNo), qci.getRequiredLock());
       }
       locations = qci.getCustomerRoomReservations();
       for (String location : locations) {
         lm.Lock(id, Hotel.getKey(location), qci.getRequiredLock());
       }
       locations = qci.getCustomerCarReservations();
       for (String location : locations) {
         lm.Lock(id, Car.getKey(location), qci.getRequiredLock());
       }
       qci.execute();
       result = qci.customerInfo;
     } catch (DeadlockException d) {
       timestamp.stamp();
       overseer.abort(id);
       timestamp.stamp();
       throw new TransactionAbortedException(timestamp);
     } catch (TransactionAbortedException tae) {
       tae.t = timestamp;
       throw tae;
     } catch (InvalidTransactionException ite) {
       ite.t = timestamp;
       throw ite;
     }
     result.timestamp.stamp();
     return result;
   }
 }
Example #17
0
 private static Timestamp shift(Timestamp v) {
   if (v == null) {
     return null;
   }
   long time = v.getTime();
   int offset = TimeZone.getDefault().getOffset(time);
   return new Timestamp(time + offset);
 }
Example #18
0
  public static String setSQLString(Timestamp columnValue) {

    String strColumnValue = "";
    if (columnValue != null) strColumnValue = "'" + columnValue.toString() + "'::timestamp";
    else strColumnValue = "null::timestamp";

    return strColumnValue;
  }
Example #19
0
  /**
   * Set Environment key to value
   *
   * @param key variable name ('#' will be converted to '_')
   * @param stringValue try to convert to Object
   */
  public void setEnvironment(String key, String stringValue) {
    if (key == null || key.length() == 0) return;
    //	log.fine( "Scriptlet.setEnvironment " + key, stringValue);
    if (stringValue == null) {
      m_ctx.remove(key);
      return;
    }

    //  Boolean
    if (stringValue.equals("Y")) {
      m_ctx.put(convertKey(key), Boolean.valueOf(true));
      return;
    }
    if (stringValue.equals("N")) {
      m_ctx.put(convertKey(key), Boolean.valueOf(false));
      return;
    }

    //  Timestamp
    Timestamp timeValue = null;
    try {
      timeValue = Timestamp.valueOf(stringValue);
      m_ctx.put(convertKey(key), timeValue);
      return;
    } catch (Exception e) {
    }

    //  Numeric
    Integer intValue = null;
    try {
      intValue = Integer.valueOf(stringValue);
    } catch (NumberFormatException e) {
    }
    Double doubleValue = null;
    try {
      doubleValue = Double.valueOf(stringValue);
    } catch (NumberFormatException e) {
    }
    if (doubleValue != null) {
      if (intValue != null) {
        double di = Double.parseDouble(intValue.toString());
        //  the numbers are the same -> integer
        if (Double.compare(di, doubleValue.doubleValue()) == 0) {
          m_ctx.put(convertKey(key), intValue);
          return;
        }
      }
      m_ctx.put(convertKey(key), doubleValue);
      return;
    }
    if (intValue != null) {
      m_ctx.put(convertKey(key), intValue);
      return;
    }
    m_ctx.put(convertKey(key), stringValue);
  } //  SetEnvironment
Example #20
0
 @Override
 public boolean equals(Object obj) {
   if ((obj != null) && (obj instanceof BindablePojo)) {
     BindablePojo other = (BindablePojo) obj;
     /*System.out.println(data1 + " == " + other.data1);
     System.out.println(data2 + " == " + other.data2);
     System.out.println(data3 + " == " + other.data3);*/
     boolean res =
         data1.equals(other.data1) && data2.equals(other.data2) && data3.equals(other.data3);
     return res;
   } else return false;
 }
Example #21
0
  public void testGetTimestamp() throws Exception {
    con.createStatement()
        .executeUpdate(
            "INSERT INTO testtimezone(tstz,ts,t,tz,d) VALUES('2005-01-01 15:00:00 +0300', '2005-01-01 15:00:00', '15:00:00', '15:00:00 +0300', '2005-01-01')");

    for (int i = 0; i < PREPARE_THRESHOLD; i++) {
      PreparedStatement ps = con.prepareStatement("SELECT tstz,ts,t,tz,d from testtimezone");
      ResultSet rs = ps.executeQuery();

      assertTrue(rs.next());
      checkDatabaseContents(
          "SELECT tstz::text,ts::text,t::text,tz::text,d::text from testtimezone",
          new String[] {
            "2005-01-01 12:00:00+00", "2005-01-01 15:00:00", "15:00:00", "15:00:00+03", "2005-01-01"
          });

      Timestamp ts;

      // timestamptz: 2005-01-01 15:00:00+03
      ts = rs.getTimestamp(1); // Represents an instant in time, timezone is irrelevant.
      assertEquals(1104580800000L, ts.getTime()); // 2005-01-01 12:00:00 UTC
      ts = rs.getTimestamp(1, cUTC); // Represents an instant in time, timezone is irrelevant.
      assertEquals(1104580800000L, ts.getTime()); // 2005-01-01 12:00:00 UTC
      ts = rs.getTimestamp(1, cGMT03); // Represents an instant in time, timezone is irrelevant.
      assertEquals(1104580800000L, ts.getTime()); // 2005-01-01 12:00:00 UTC
      ts = rs.getTimestamp(1, cGMT05); // Represents an instant in time, timezone is irrelevant.
      assertEquals(1104580800000L, ts.getTime()); // 2005-01-01 12:00:00 UTC
      ts = rs.getTimestamp(1, cGMT13); // Represents an instant in time, timezone is irrelevant.
      assertEquals(1104580800000L, ts.getTime()); // 2005-01-01 12:00:00 UTC

      // timestamp: 2005-01-01 15:00:00
      ts = rs.getTimestamp(2); // Convert timestamp to +0100
      assertEquals(1104588000000L, ts.getTime()); // 2005-01-01 15:00:00 +0100
      ts = rs.getTimestamp(2, cUTC); // Convert timestamp to UTC
      assertEquals(1104591600000L, ts.getTime()); // 2005-01-01 15:00:00 +0000
      ts = rs.getTimestamp(2, cGMT03); // Convert timestamp to +0300
      assertEquals(1104580800000L, ts.getTime()); // 2005-01-01 15:00:00 +0300
      ts = rs.getTimestamp(2, cGMT05); // Convert timestamp to -0500
      assertEquals(1104609600000L, ts.getTime()); // 2005-01-01 15:00:00 -0500
      ts = rs.getTimestamp(2, cGMT13); // Convert timestamp to +1300
      assertEquals(1104544800000L, ts.getTime()); // 2005-01-01 15:00:00 +1300

      // time: 15:00:00
      ts = rs.getTimestamp(3);
      assertEquals(50400000L, ts.getTime()); // 1970-01-01 15:00:00 +0100
      ts = rs.getTimestamp(3, cUTC);
      assertEquals(54000000L, ts.getTime()); // 1970-01-01 15:00:00 +0000
      ts = rs.getTimestamp(3, cGMT03);
      assertEquals(43200000L, ts.getTime()); // 1970-01-01 15:00:00 +0300
      ts = rs.getTimestamp(3, cGMT05);
      assertEquals(72000000L, ts.getTime()); // 1970-01-01 15:00:00 -0500
      ts = rs.getTimestamp(3, cGMT13);
      assertEquals(7200000L, ts.getTime()); // 1970-01-01 15:00:00 +1300

      // timetz: 15:00:00+03
      ts = rs.getTimestamp(4);
      assertEquals(
          43200000L, ts.getTime()); // 1970-01-01 15:00:00 +0300 -> 1970-01-01 13:00:00 +0100
      ts = rs.getTimestamp(4, cUTC);
      assertEquals(
          43200000L, ts.getTime()); // 1970-01-01 15:00:00 +0300 -> 1970-01-01 12:00:00 +0000
      ts = rs.getTimestamp(4, cGMT03);
      assertEquals(
          43200000L, ts.getTime()); // 1970-01-01 15:00:00 +0300 -> 1970-01-01 15:00:00 +0300
      ts = rs.getTimestamp(4, cGMT05);
      assertEquals(
          43200000L, ts.getTime()); // 1970-01-01 15:00:00 +0300 -> 1970-01-01 07:00:00 -0500
      ts = rs.getTimestamp(4, cGMT13);
      assertEquals(
          -43200000L,
          ts.getTime()); // 1970-01-01 15:00:00 +0300 -> 1970-01-02 01:00:00 +1300 (CHECK ME)

      // date: 2005-01-01
      ts = rs.getTimestamp(5);
      assertEquals(1104534000000L, ts.getTime()); // 2005-01-01 00:00:00 +0100
      ts = rs.getTimestamp(5, cUTC);
      assertEquals(1104537600000L, ts.getTime()); // 2005-01-01 00:00:00 +0000
      ts = rs.getTimestamp(5, cGMT03);
      assertEquals(1104526800000L, ts.getTime()); // 2005-01-01 00:00:00 +0300
      ts = rs.getTimestamp(5, cGMT05);
      assertEquals(1104555600000L, ts.getTime()); // 2005-01-01 00:00:00 -0500
      ts = rs.getTimestamp(5, cGMT13);
      assertEquals(1104490800000L, ts.getTime()); // 2005-01-01 00:00:00 +1300

      assertTrue(!rs.next());
      ps.close();
    }
  }
Example #22
0
  public void testSetTimestamp() throws Exception {
    for (int i = 0; i < PREPARE_THRESHOLD; i++) {
      con.createStatement().execute("delete from testtimezone");
      PreparedStatement insertTimestamp =
          con.prepareStatement("INSERT INTO testtimezone(seq,tstz,ts,tz,d) VALUES (?,?,?,?,?)");
      int seq = 1;

      Timestamp instant = new Timestamp(1104580800000L); // 2005-01-01 12:00:00 UTC
      Timestamp instantTime = new Timestamp(instant.getTime() % DAY);
      Timestamp instantDateJVM =
          new Timestamp(
              instant.getTime() - (instant.getTime() % DAY) - TimeZone.getDefault().getRawOffset());
      Timestamp instantDateUTC =
          new Timestamp(
              instant.getTime() - (instant.getTime() % DAY) - cUTC.getTimeZone().getRawOffset());
      Timestamp instantDateGMT03 =
          new Timestamp(
              instant.getTime() - (instant.getTime() % DAY) - cGMT03.getTimeZone().getRawOffset());
      Timestamp instantDateGMT05 =
          new Timestamp(
              instant.getTime() - (instant.getTime() % DAY) - cGMT05.getTimeZone().getRawOffset());
      Timestamp instantDateGMT13 =
          new Timestamp(
              instant.getTime()
                  - (instant.getTime() % DAY)
                  - cGMT13.getTimeZone().getRawOffset()
                  + DAY);

      // +0100 (JVM default)
      insertTimestamp.setInt(1, seq++);
      insertTimestamp.setTimestamp(2, instant); // 2005-01-01 13:00:00 +0100
      insertTimestamp.setTimestamp(3, instant); // 2005-01-01 13:00:00
      insertTimestamp.setTimestamp(4, instant); // 13:00:00 +0100
      insertTimestamp.setTimestamp(5, instant); // 2005-01-01
      insertTimestamp.executeUpdate();

      // UTC
      insertTimestamp.setInt(1, seq++);
      insertTimestamp.setTimestamp(2, instant, cUTC); // 2005-01-01 12:00:00 +0000
      insertTimestamp.setTimestamp(3, instant, cUTC); // 2005-01-01 12:00:00
      insertTimestamp.setTimestamp(4, instant, cUTC); // 12:00:00 +0000
      insertTimestamp.setTimestamp(5, instant, cUTC); // 2005-01-01
      insertTimestamp.executeUpdate();

      // +0300
      insertTimestamp.setInt(1, seq++);
      insertTimestamp.setTimestamp(2, instant, cGMT03); // 2005-01-01 15:00:00 +0300
      insertTimestamp.setTimestamp(3, instant, cGMT03); // 2005-01-01 15:00:00
      insertTimestamp.setTimestamp(4, instant, cGMT03); // 15:00:00 +0300
      insertTimestamp.setTimestamp(5, instant, cGMT03); // 2005-01-01
      insertTimestamp.executeUpdate();

      // -0500
      insertTimestamp.setInt(1, seq++);
      insertTimestamp.setTimestamp(2, instant, cGMT05); // 2005-01-01 07:00:00 -0500
      insertTimestamp.setTimestamp(3, instant, cGMT05); // 2005-01-01 07:00:00
      insertTimestamp.setTimestamp(4, instant, cGMT05); // 07:00:00 -0500
      insertTimestamp.setTimestamp(5, instant, cGMT05); // 2005-01-01
      insertTimestamp.executeUpdate();

      if (min73) {
        // +1300
        insertTimestamp.setInt(1, seq++);
        insertTimestamp.setTimestamp(2, instant, cGMT13); // 2005-01-02 01:00:00 +1300
        insertTimestamp.setTimestamp(3, instant, cGMT13); // 2005-01-02 01:00:00
        insertTimestamp.setTimestamp(4, instant, cGMT13); // 01:00:00 +1300
        insertTimestamp.setTimestamp(5, instant, cGMT13); // 2005-01-02
        insertTimestamp.executeUpdate();
      }

      insertTimestamp.close();

      // check that insert went correctly by parsing the raw contents in UTC
      checkDatabaseContents(
          "SELECT seq::text,tstz::text,ts::text,tz::text,d::text from testtimezone ORDER BY seq",
          new String[][] {
            new String[] {
              "1", "2005-01-01 12:00:00+00", "2005-01-01 13:00:00", "13:00:00+01", "2005-01-01"
            },
            new String[] {
              "2", "2005-01-01 12:00:00+00", "2005-01-01 12:00:00", "12:00:00+00", "2005-01-01"
            },
            new String[] {
              "3", "2005-01-01 12:00:00+00", "2005-01-01 15:00:00", "15:00:00+03", "2005-01-01"
            },
            new String[] {
              "4", "2005-01-01 12:00:00+00", "2005-01-01 07:00:00", "07:00:00-05", "2005-01-01"
            },
            new String[] {
              "5", "2005-01-01 12:00:00+00", "2005-01-02 01:00:00", "01:00:00+13", "2005-01-02"
            }
          });

      //
      // check results
      //

      seq = 1;
      PreparedStatement ps =
          con.prepareStatement("SELECT seq,tstz,ts,tz,d FROM testtimezone ORDER BY seq");
      ResultSet rs = ps.executeQuery();

      assertTrue(rs.next());
      assertEquals(seq++, rs.getInt(1));
      assertEquals(instant, rs.getTimestamp(2));
      assertEquals(instant, rs.getTimestamp(3));
      assertEquals(instantTime, rs.getTimestamp(4));
      assertEquals(instantDateJVM, rs.getTimestamp(5));

      assertTrue(rs.next());
      assertEquals(seq++, rs.getInt(1));
      assertEquals(instant, rs.getTimestamp(2, cUTC));
      assertEquals(instant, rs.getTimestamp(3, cUTC));
      assertEquals(instantTime, rs.getTimestamp(4, cUTC));
      assertEquals(instantDateUTC, rs.getTimestamp(5, cUTC));

      assertTrue(rs.next());
      assertEquals(seq++, rs.getInt(1));
      assertEquals(instant, rs.getTimestamp(2, cGMT03));
      assertEquals(instant, rs.getTimestamp(3, cGMT03));
      assertEquals(instantTime, rs.getTimestamp(4, cGMT03));
      assertEquals(instantDateGMT03, rs.getTimestamp(5, cGMT03));

      assertTrue(rs.next());
      assertEquals(seq++, rs.getInt(1));
      assertEquals(instant, rs.getTimestamp(2, cGMT05));
      assertEquals(instant, rs.getTimestamp(3, cGMT05));
      assertEquals(instantTime, rs.getTimestamp(4, cGMT05));
      assertEquals(instantDateGMT05, rs.getTimestamp(5, cGMT05));

      if (min73) {
        assertTrue(rs.next());
        assertEquals(seq++, rs.getInt(1));
        assertEquals(instant, rs.getTimestamp(2, cGMT13));
        assertEquals(instant, rs.getTimestamp(3, cGMT13));
        assertEquals(normalizeTimeOfDayPart(instantTime, cGMT13), rs.getTimestamp(4, cGMT13));
        assertEquals(instantDateGMT13, rs.getTimestamp(5, cGMT13));
      }

      assertTrue(!rs.next());
      ps.close();
    }
  }
Example #23
0
  /**
   * Before Save. Truncate Dates
   *
   * @param newRecord new
   * @return true
   */
  @Override
  protected boolean beforeSave(boolean newRecord) {
    Timestamp startdate = getStartDate();
    Timestamp enddate = getEndDate();

    if (enddate != null && startdate.after(enddate)) {

      s_log.saveError("Error", Msg.getMsg(getCtx(), "CalPeriodInvalidDate"));
      return false;
    }
    //	Truncate Dates
    startdate = TimeUtil.getDay(startdate);
    setStartDate(startdate);

    if (enddate != null) enddate = TimeUtil.getDay(enddate);
    else enddate = TimeUtil.getMonthLastDay(getStartDate());

    //		Adding the time component of 23:59:59 to the end date
    enddate = new Timestamp(enddate.getTime() + 86399000);
    setEndDate(enddate);

    MPeriod[] periods = getAllPeriodsInYear(getC_Year_ID(), "S", getCtx(), get_Trx());
    MPeriod[] allperiods = getAllPeriodsInCalendar(getC_Calendar_ID(), "S", getCtx(), get_Trx());
    //		Check for non-negative period number
    if (getPeriodNo() < 0) {
      s_log.saveError("Error", Msg.getMsg(getCtx(), "CalNegPeriodNo"));
      return false;
    }

    //		Check for standard period
    if (isStandardPeriod() == true) {
      // Check Period number is in ascending order

      Timestamp nextPeriodStartDate = null;
      Timestamp prevPeriodStartDate = null;

      // Get the next standard period number Start Date in this year
      String sql =
          "SELECT StartDate FROM C_Period WHERE "
              + "C_Period.IsActive='Y' AND PeriodType='S' "
              + "AND C_Period.C_Year_ID =? "
              + "AND C_Period.C_Period_ID <> ?"
              + "AND  C_Period.PeriodNo "
              + " >  ?  ORDER BY  C_Period.PeriodNo ASC";
      Object[][] result = null;
      result =
          QueryUtil.executeQuery(get_Trx(), sql, getC_Year_ID(), getC_Period_ID(), getPeriodNo());

      if (result.length != 0) nextPeriodStartDate = (Timestamp) result[0][0];

      // Get the previous standard period number Start Date in this year
      sql =
          "SELECT StartDate FROM C_Period WHERE "
              + "C_Period.IsActive='Y' AND PeriodType='S'  "
              + "AND C_Period.C_Year_ID =? "
              + "AND C_Period.C_Period_ID <> ?"
              + "AND C_Period.PeriodNo "
              + "< ?  ORDER BY  C_Period.PeriodNo DESC";

      result =
          QueryUtil.executeQuery(get_Trx(), sql, getC_Year_ID(), getC_Period_ID(), getPeriodNo());
      if (result.length != 0) prevPeriodStartDate = (Timestamp) result[0][0];

      if ((prevPeriodStartDate != null
          && TimeUtil.max(prevPeriodStartDate, startdate) == prevPeriodStartDate)) {
        s_log.saveError("Error", Msg.getMsg(getCtx(), "CalPeriodAsc"));
        return false;
      }

      if ((nextPeriodStartDate != null
          && TimeUtil.max(nextPeriodStartDate, startdate) == startdate)) {
        s_log.saveError("Error", Msg.getMsg(getCtx(), "CalPeriodAsc"));
        return false;
      }

      //  Check if the Standard Period is overlapping other periods.

      for (MPeriod period : allperiods) {
        if ((TimeUtil.isValid(period.getStartDate(), period.getEndDate(), startdate) == true
                || TimeUtil.isValid(period.getStartDate(), period.getEndDate(), enddate) == true)
            && period.getC_Period_ID() != getC_Period_ID()) {
          s_log.saveError("Error", Msg.getMsg(getCtx(), "CalPeriodOverlap"));
          return false;
        }
      }

    }
    //		Check for adjusting period
    else {
      boolean startflag = false;
      boolean endflag = false;
      for (MPeriod period : periods) {
        if (TimeUtil.isValid(period.getStartDate(), period.getEndDate(), startdate) == true)
          startflag = true;
        if (TimeUtil.isValid(period.getStartDate(), period.getEndDate(), enddate) == true)
          endflag = true;
        if (startflag == true && endflag == true) break;
      }
      if (startflag == false || endflag == false) {
        s_log.saveError("Error", Msg.getMsg(getCtx(), "CalAdjPeriod"));
        return false;
      }
    }
    return true;
  } //	beforeSave
Example #24
0
 /**
  * Converts the given time
  *
  * @param t The time of day. Must be within -24 and + 24 hours of epoc.
  * @param tz The timezone to normalize to.
  * @return the Time nomralized to 0 to 24 hours of epoc adjusted with given timezone.
  */
 private Timestamp normalizeTimeOfDayPart(Timestamp t, Calendar tz) {
   return new Timestamp(normalizeTimeOfDayPart(t.getTime(), tz.getTimeZone()));
 }
Example #25
0
 public static void main(String[] args) throws Exception {
   Timestamp ts = getTimestamp("2011-12-01T00:00:00.000+01:00");
   System.out.println(ts.toString());
 }
Example #26
0
  /**
   * This test is broken off from testSetTimestamp because it does not work for pre-7.4 servers and
   * putting tons of conditionals in that test makes it largely unreadable. The time data type does
   * not accept timestamp with time zone style input on these servers.
   */
  public void testSetTimestampOnTime() throws Exception {
    // Pre-7.4 servers cannot convert timestamps with timezones to times.
    if (!min74) return;

    for (int i = 0; i < PREPARE_THRESHOLD; i++) {
      con.createStatement().execute("delete from testtimezone");
      PreparedStatement insertTimestamp =
          con.prepareStatement("INSERT INTO testtimezone(seq,t) VALUES (?,?)");
      int seq = 1;

      Timestamp instant = new Timestamp(1104580800000L); // 2005-01-01 12:00:00 UTC
      Timestamp instantTime = new Timestamp(instant.getTime() % DAY);

      // +0100 (JVM default)
      insertTimestamp.setInt(1, seq++);
      insertTimestamp.setTimestamp(2, instant); // 13:00:00
      insertTimestamp.executeUpdate();

      // UTC
      insertTimestamp.setInt(1, seq++);
      insertTimestamp.setTimestamp(2, instant, cUTC); // 12:00:00
      insertTimestamp.executeUpdate();

      // +0300
      insertTimestamp.setInt(1, seq++);
      insertTimestamp.setTimestamp(2, instant, cGMT03); // 15:00:00
      insertTimestamp.executeUpdate();

      // -0500
      insertTimestamp.setInt(1, seq++);
      insertTimestamp.setTimestamp(2, instant, cGMT05); // 07:00:00
      insertTimestamp.executeUpdate();

      if (min73) {
        // +1300
        insertTimestamp.setInt(1, seq++);
        insertTimestamp.setTimestamp(2, instant, cGMT13); // 01:00:00
        insertTimestamp.executeUpdate();
      }

      insertTimestamp.close();

      checkDatabaseContents(
          "SELECT seq::text,t::text from testtimezone ORDER BY seq",
          new String[][] {
            new String[] {"1", "13:00:00"},
            new String[] {"2", "12:00:00"},
            new String[] {"3", "15:00:00"},
            new String[] {"4", "07:00:00"},
            new String[] {"5", "01:00:00"}
          });

      seq = 1;
      PreparedStatement ps = con.prepareStatement("SELECT seq,t FROM testtimezone ORDER BY seq");
      ResultSet rs = ps.executeQuery();

      assertTrue(rs.next());
      assertEquals(seq++, rs.getInt(1));
      assertEquals(instantTime, rs.getTimestamp(2));

      assertTrue(rs.next());
      assertEquals(seq++, rs.getInt(1));
      assertEquals(instantTime, rs.getTimestamp(2, cUTC));

      assertTrue(rs.next());
      assertEquals(seq++, rs.getInt(1));
      assertEquals(instantTime, rs.getTimestamp(2, cGMT03));

      assertTrue(rs.next());
      assertEquals(seq++, rs.getInt(1));
      assertEquals(instantTime, rs.getTimestamp(2, cGMT05));

      assertTrue(rs.next());
      assertEquals(seq++, rs.getInt(1));
      assertEquals(normalizeTimeOfDayPart(instantTime, cGMT13), rs.getTimestamp(2, cGMT13));

      assertTrue(!rs.next());
      ps.close();
    }
  }