Java Code Examples for java.util.Date

The following are top voted examples for showing how to use java.util.Date. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: apollo-custom   File: ReleaseHistoryService.java   View source code 8 votes vote down vote up
private ReleaseHistoryBO transformReleaseHistoryDTO2BO(ReleaseHistoryDTO dto, ReleaseDTO release){
  ReleaseHistoryBO bo = new ReleaseHistoryBO();
  bo.setId(dto.getId());
  bo.setAppId(dto.getAppId());
  bo.setClusterName(dto.getClusterName());
  bo.setNamespaceName(dto.getNamespaceName());
  bo.setBranchName(dto.getBranchName());
  bo.setReleaseId(dto.getReleaseId());
  bo.setPreviousReleaseId(dto.getPreviousReleaseId());
  bo.setOperator(dto.getDataChangeCreatedBy());
  bo.setOperation(dto.getOperation());
  Date releaseTime = dto.getDataChangeLastModifiedTime();
  bo.setReleaseTime(releaseTime);
  bo.setReleaseTimeFormatted(RelativeDateFormat.format(releaseTime));
  bo.setOperationContext(dto.getOperationContext());
  //set release info
  setReleaseInfoToReleaseHistoryBO(bo, release);

  return bo;
}
 
Example 2
Project: springbootWeb   File: WebLogAspect.java   View source code 6 votes vote down vote up
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(Object ret) {
    // 处理完请求,返回内容
    WebOosLog commLogger = commLoggerThreadLocal.get();
    commLogger.setActionResCode(ResponseStatus.SUCCESS);
    commLogger.setReqEndTime(new Date());
    commLogger.setReqDealTime((int) (commLogger.getReqEndTime().getTime() - commLogger.getReqStartTime().getTime()));
    commLogger.setResponseData(JSON.toJSONString(ret));
    commLogger.setIsUndefinedException(false);

    loggerRecordService.doRecord(commLogger);

    logger.debug("RESPONSE : " + JSON.toJSONString(ret));
    logger.debug("SPEND TIME : " + commLogger.getReqDealTime() + "ms");
    logger.debug("***************请求" + commLogger.getActionDesc() + "结束***************");
}
 
Example 3
Project: logistimo-web-service   File: UsersServiceImpl.java   View source code 6 votes vote down vote up
/**
 * update the lastmobileAccess time
 *
 * @param userId user id
 * @param aTime  accessed time
 */
@Override
public boolean updateLastMobileAccessTime(String userId, long aTime) {
  PersistenceManager pm = PMF.get().getPersistenceManager();
  IUserAccount userAccount;
  Date now = new Date(aTime);
  try {
    userAccount = JDOUtils.getObjectById(IUserAccount.class, userId, pm);
    if (userAccount.getLastMobileAccessed() == null
        || userAccount.getLastMobileAccessed().compareTo(now) < 0) {
      userAccount.setLastMobileAccessed(now);
    }
  } catch (Exception e) {
    xLogger
        .warn("{0} while updating last transacted time for the user, {1}", e.getMessage(), userId,
            e);
    return false;
  } finally {
    pm.close();
  }
  return true;
}
 
Example 4
Project: lazycat   File: AccessLogValve.java   View source code 6 votes vote down vote up
/**
 * Start this component and implement the requirements of
 * {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
 *
 * @exception LifecycleException
 *                if this component detects a fatal error that prevents this
 *                component from being used
 */
@Override
protected synchronized void startInternal() throws LifecycleException {

	// Initialize the Date formatters
	String format = getFileDateFormat();
	fileDateFormatter = new SimpleDateFormat(format, Locale.US);
	fileDateFormatter.setTimeZone(TimeZone.getDefault());
	dateStamp = fileDateFormatter.format(new Date(System.currentTimeMillis()));
	if (rotatable && renameOnRotate) {
		restore();
	}
	open();

	setState(LifecycleState.STARTING);
}
 
Example 5
Project: ext-lib-amazon-mws-fulfillment-inbound-shipment   File: FBAInboundServiceMWSMock.java   View source code 6 votes vote down vote up
/**
 * Create a new response object.
 * 
 * @param cls
 * 
 * @return The object.
 */
private <T extends MwsObject> T newResponse(
        Class<T> cls) {
    InputStream is = null;
    try {
        is = this.getClass().getResourceAsStream(cls.getSimpleName()+".xml");
        MwsXmlReader reader = new MwsXmlReader(is);
        T obj = cls.newInstance();
        obj.readFragmentFrom(reader);
        ResponseHeaderMetadata rhmd = new ResponseHeaderMetadata(
            "mockRequestId", Arrays.asList("A","B","C"), "mockTimestamp", 0d, 0d, new Date());
        cls.getMethod("setResponseHeaderMetadata", rhmd.getClass()).invoke(obj,  rhmd);
        return obj;
    } catch (Exception e) {
        throw MwsUtl.wrap(e);
    } finally {
        MwsUtl.close(is);
    }
}
 
Example 6
Project: theLXGweb   File: SavePlayerAndSendMailImpl.java   View source code 6 votes vote down vote up
public void savePlayer(@RequestBody player play){

        Random rand = new Random();
        int value = rand.nextInt(99);
        int value2 = rand.nextInt(99);

        String identityNumber = "TheLXG-Phy"+value+"1"+value2+"-"+play.getAlias();
        play.setPlayerId(identityNumber);
//        eMail.setMessageForPlayer(play);/*sets player Object mail is sent to and embeds details to message.*/
        Date date = new Date();
        play.setDate(date);
        playerService.addPlayer(play);

        if(sendMailNotification.sendEmail(play, eMail,"The LXG - Registration")){
            play.setMailStatus("mail sent");
        }else{
            play.setMailStatus("mail not sent");
        }

        playerService.updatePlayer(play);

    }
 
Example 7
Project: YiZhi   File: TimestampUtils.java   View source code 6 votes vote down vote up
public static String getDateTimeByGMT(int timeZone) {
    SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    switch (timeZone) {
        case 1:
            dff.setTimeZone(TimeZone.getTimeZone("GMT+1"));
            break;
        case 8:
            dff.setTimeZone(TimeZone.getTimeZone("GMT+8"));
            //LogUtils.i("采用东八区时区");
            break;
    }

    String time = dff.format(new Date());
    //LogUtils.i("东八区时区时间为--》》" + time);
    return time;
}
 
Example 8
Project: Ucount   File: AddItemActivity.java   View source code 6 votes vote down vote up
public void putItemInData(double money) {
    Sum sum = new Sum();
    IOItem ioItem = new IOItem();
    String tagName = (String) bannerText.getTag();
    int tagType = (int) bannerImage.getTag();

    if (tagType < 0) {
        ioItem.setType(ioItem.TYPE_COST);
    } else ioItem.setType(ioItem.TYPE_EARN);

    ioItem.setName(bannerText.getText().toString());
    ioItem.setSrcName(tagName);
    ioItem.setMoney(money);
    ioItem.setTimeStamp(formatItem.format(new Date()));         // 存储记账时间
    ioItem.setDescription(GlobalVariables.getmDescription());
    ioItem.save();

    // 存储完之后及时清空备注
    GlobalVariables.setmDescription("");

    int type = ioItem.getType();
    String sumDate = formatSum.format(new Date());
    // 计算总额
    sum.calculateMoneyIncludeNull(sum.SUM, "All", money, type, sumDate);
    calculateMonthlyMoney(type, ioItem);
}
 
Example 9
Project: oscm   File: TimerServiceBean.java   View source code 6 votes vote down vote up
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public List<VOTimerInfo> getCurrentTimerExpirationDates() {
    List<VOTimerInfo> result = new ArrayList<VOTimerInfo>();

    for (Timer timer : ParameterizedTypes.iterable(ctx.getTimerService()
            .getTimers(), Timer.class)) {
        Serializable info = timer.getInfo();
        if (info != null && info instanceof TimerType) {
            TimerType type = (TimerType) info;
            long expirationTime = timer.getTimeRemaining()
                    + System.currentTimeMillis();
            VOTimerInfo timerInfo = new VOTimerInfo();
            timerInfo.setTimerType(type.name());
            timerInfo.setExpirationDate(new Date(expirationTime));
            result.add(timerInfo);
        }
    }

    return result;
}
 
Example 10
Project: SVNAutoMerger   File: Notifier.java   View source code 6 votes vote down vote up
private static void sendEmail(String emailSubject, String emailBody) {
  logger.info("About to notify DEV and QA teams...");
  String body = String.format(EMAIL_TMPL_HEADER,
      new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z").format(new Date()))
      + emailBody;
  String emailTempFileContent = String.format(
      EMAIL_TMPL_CONTENT,
      PropertiesUtil.getString("email.sender"),
      emailSubject,
      body);
  try {
    String sendMailCommand = String.format(
        EMAIL_TMPL_CMD,
        emailTempFileContent,
        PropertiesUtil.getString("email.to.notify")
    );
    CommandExecutor.run( sendMailCommand, null);

  } catch (Exception e) {
    logger.error("Email notification has failed", e);
  }
}
 
Example 11
Project: BachelorPraktikum   File: VaultDao.java   View source code 6 votes vote down vote up
/**
 * This method is used to query {@link VaultEntry}s which are of a given type and lie in a specified period.
 * The types to be queried for are glucose types:
 * <ul>
 *     <li>{@link VaultEntryType#GLUCOSE_BG}</li>
 *     <li>{@link VaultEntryType#GLUCOSE_CGM}</li>
 *     <li>{@link VaultEntryType#GLUCOSE_CGM_ALERT}</li>
 * </ul>
 *
 * @param from The start of the period to query entries from.
 * @param to The end of the period to query entries from.
 * @return All {@link VaultEntry} which are of the required type and lie in the specified period.
 */
//TODO OTHER TYPES? Let's ask Jens @next meeting
public List<VaultEntry> queryGlucoseBetween(final Date from, final Date to) {
    List<VaultEntry> returnValues = null;
    try {
        PreparedQuery<VaultEntry> query
                = vaultDao.queryBuilder().orderBy("timestamp", true)
                .where()
                .eq(VaultEntry.TYPE_FIELD_NAME, VaultEntryType.GLUCOSE_BG)
                .or()
                .eq(VaultEntry.TYPE_FIELD_NAME, VaultEntryType.GLUCOSE_CGM)
                .or()
                .eq(VaultEntry.TYPE_FIELD_NAME, VaultEntryType.GLUCOSE_CGM_ALERT)
                .and()
                .between(VaultEntry.TIMESTAMP_FIELD_NAME, from, to)
                .prepare();
        returnValues = vaultDao.query(query);
    } catch (SQLException exception) {
        LOG.log(Level.SEVERE, "Error while db query", exception);
    }
    return returnValues;
}
 
Example 12
Project: GitHub   File: RealmResultsTests.java   View source code 6 votes vote down vote up
private void populateTestRealm(Realm testRealm, int objects) {
    testRealm.beginTransaction();
    testRealm.deleteAll();
    for (int i = 0; i < objects; i++) {
        AllTypes allTypes = testRealm.createObject(AllTypes.class);
        allTypes.setColumnBoolean((i % 3) == 0);
        allTypes.setColumnBinary(new byte[]{1, 2, 3});
        allTypes.setColumnDate(new Date(DECADE_MILLIS * (i - (objects / 2))));
        allTypes.setColumnDouble(Math.PI);
        allTypes.setColumnFloat(1.234567f + i);
        allTypes.setColumnString("test data " + i);
        allTypes.setColumnLong(i);
        NonLatinFieldNames nonLatinFieldNames = testRealm.createObject(NonLatinFieldNames.class);
        nonLatinFieldNames.set델타(i);
        nonLatinFieldNames.setΔέλτα(i);
        nonLatinFieldNames.set베타(1.234567f + i);
        nonLatinFieldNames.setΒήτα(1.234567f + i);
    }
    testRealm.commitTransaction();
}
 
Example 13
Project: LianXiZhihu   File: DateFormatter.java   View source code 5 votes vote down vote up
/**
 * 将long类date转换为String类型
 * @param date date
 * @return String date
 */
public String ZhihuDailyDateFormat(long date) {
    String sDate;
    Date d = new Date(date + 24*60*60*1000);
    SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
    sDate = format.format(d);

    return sDate;
}
 
Example 14
Project: LucaHome-AndroidApplication   File: MoneyMeterDataActivity.java   View source code 5 votes vote down vote up
private void createGraph() {
    _graphView.removeAllSeries();

    SerializableList<MoneyMeterData> moneyMeterDataList = MoneyMeterListService.getInstance().GetActiveMoneyMeter().GetMoneyMeterDataList();
    int moneyMeterDataListSize = moneyMeterDataList.getSize();
    DataPoint[] dataPoints = new DataPoint[moneyMeterDataListSize];

    Date firstDate = new Date();
    Date lastDate = new Date();

    for (int index = 0; index < moneyMeterDataListSize; index++) {
        SerializableDate saveDate = moneyMeterDataList.getValue(index).GetSaveDate();
        Date date = new Date(saveDate.Year(), saveDate.Month() - 1, saveDate.DayOfMonth());
        dataPoints[index] = new DataPoint(date, moneyMeterDataList.getValue(index).GetAmount());
        if (index == 0) {
            firstDate = date;
        } else if (index == moneyMeterDataListSize - 1) {
            lastDate = date;
        }
    }

    LineGraphSeries<DataPoint> series = new LineGraphSeries<>(dataPoints);
    _graphView.addSeries(series);

    _graphView.getGridLabelRenderer().setLabelFormatter(new DateAsXAxisLabelFormatter(this));
    _graphView.getGridLabelRenderer().setNumHorizontalLabels(3);

    _graphView.getViewport().setMinX(firstDate.getTime());
    _graphView.getViewport().setMaxX(lastDate.getTime());
    _graphView.getViewport().setXAxisBoundsManual(true);

    _graphView.getGridLabelRenderer().setHumanRounding(false);
}
 
Example 15
Project: parabuild-ci   File: ConverterForRSS093.java   View source code 5 votes vote down vote up
protected SyndEntry createSyndEntry(Item item) {
    SyndEntry syndEntry = super.createSyndEntry(item);
    Date pubDate = item.getPubDate();
    if (pubDate!=null) {
        syndEntry.setPublishedDate(pubDate);     //c
    }
    return syndEntry;
}
 
Example 16
Project: aws-sdk-java-v2   File: StandardModelFactoriesV2Test.java   View source code 5 votes vote down vote up
@Test
public void testDateSet() {
    assertEquals(Collections.singletonList("1970-01-01T00:00:00Z"),
                 convert("getDateSet", Collections.singleton(new Date(0)))
                         .ss());

    Calendar c = GregorianCalendar.getInstance();
    c.setTimeInMillis(0);

    assertEquals(Collections.singletonList("1970-01-01T00:00:00Z"),
                 convert("getCalendarSet", Collections.singleton(c))
                         .ss());
}
 
Example 17
Project: Aurora   File: VideoDaoEntity.java   View source code 5 votes vote down vote up
@Generated(hash = 1004013563)
public VideoDaoEntity(Long id, String body, Integer totalTime,
        Integer startTime, String shareInfo, Date date) {
    this.id = id;
    this.body = body;
    this.totalTime = totalTime;
    this.startTime = startTime;
    this.shareInfo = shareInfo;
    this.date = date;
}
 
Example 18
Project: ProyectoPacientes   File: StressRegressionTest.java   View source code 5 votes vote down vote up
/**
 * @param threadConn
 * @param threadStmt
 * @param threadNumber
 */
void contentiousWork(Connection threadConn, Statement threadStmt, int threadNumber) {
    Date now = new Date();

    try {
        for (int i = 0; i < 1000; i++) {
            ResultSet threadRs = threadStmt.executeQuery("SELECT 1, 2");

            while (threadRs.next()) {
                threadRs.getString(1);
                threadRs.getString(2);
            }

            threadRs.close();

            PreparedStatement pStmt = threadConn.prepareStatement("SELECT ?");
            pStmt.setTimestamp(1, new Timestamp(now.getTime()));

            threadRs = pStmt.executeQuery();

            while (threadRs.next()) {
                threadRs.getTimestamp(1);
            }

            threadRs.close();
            pStmt.close();
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex.toString());
    }
}
 
Example 19
Project: asura   File: DateIntervalTrigger.java   View source code 5 votes vote down vote up
/**
 * <p>
 * Returns the final time at which the <code>DateIntervalTrigger</code> will
 * fire, if there is no end time set, null will be returned.
 * </p>
 * 
 * <p>
 * Note that the return time may be in the past.
 * </p>
 */
public Date getFinalFireTime() {
    if (complete || getEndTime() == null) {
        return null;
    }

    // back up a second from end time
    Date fTime = new Date(getEndTime().getTime() - 1000L);
    // find the next fire time after that
    fTime = getFireTimeAfter(fTime, true);
    
    // the the trigger fires at the end time, that's it!
    if(fTime.equals(getEndTime()))
        return fTime;
    
    // otherwise we have to back up one interval from the fire time after the end time
    
    Calendar lTime = Calendar.getInstance();
    lTime.setTime(fTime);
    lTime.setLenient(true);
    
    if(getRepeatIntervalUnit().equals(IntervalUnit.SECOND)) {
        lTime.add(java.util.Calendar.SECOND, -1 * getRepeatInterval());
    }
    else if(getRepeatIntervalUnit().equals(IntervalUnit.MINUTE)) {
        lTime.add(java.util.Calendar.MINUTE, -1 * getRepeatInterval());
    }
    else if(getRepeatIntervalUnit().equals(IntervalUnit.HOUR)) {
        lTime.add(java.util.Calendar.HOUR_OF_DAY, -1 * getRepeatInterval());
    }
    else if(getRepeatIntervalUnit().equals(IntervalUnit.DAY)) {
        lTime.add(java.util.Calendar.DAY_OF_YEAR, -1 * getRepeatInterval());
    }
    else if(getRepeatIntervalUnit().equals(IntervalUnit.WEEK)) {
        lTime.add(java.util.Calendar.WEEK_OF_YEAR, -1 * getRepeatInterval());
    }
    else if(getRepeatIntervalUnit().equals(IntervalUnit.MONTH)) {
        lTime.add(java.util.Calendar.MONTH, -1 * getRepeatInterval());
    }
    else if(getRepeatIntervalUnit().equals(IntervalUnit.YEAR)) {
        lTime.add(java.util.Calendar.YEAR, -1 * getRepeatInterval());
    }

    return lTime.getTime();
}
 
Example 20
Project: parabuild-ci   File: VaultSourceControl.java   View source code 5 votes vote down vote up
private void reportCannotFindVersion(final Agent agent, final String path, final Date changeListDate) throws IOException, AgentFailureException {
  final VaultDateFormat format = new VaultDateFormat(agent.defaultLocale());
  final Error error = new Error();
  error.setBuildID(activeBuildID);
  error.setDescription("Could not find a version for Vault directory");
  error.setDetails("Vault repository: " + getSettingValue(SourceControlSetting.VAULT_REPOSITORY)
          + ", directory: " + path
          + (lastSyncDate != null ? ", last sync date: " + format.formatInput(lastSyncDate) : "")
          + (changeListDate != null ? ", change list date: " + format.formatInput(changeListDate) : ""));
  ErrorManagerFactory.getErrorManager().reportSystemError(error);
}
 
Example 21
Project: boohee_v5.6   File: QNApiImpl.java   View source code 5 votes vote down vote up
public void connectDevice(QNBleDevice bleDevice, String userId, int height, int gender, Date
        birthday, QNBleCallback callback) {
    if (isAppIdReady(callback)) {
        if (this.mBluetoothAdapter == null) {
            this.mBluetoothAdapter = ((BluetoothManager) this.mContext.getSystemService
                    ("bluetooth")).getAdapter();
        }
        if (this.mBluetoothAdapter == null) {
            callback.onCompete(4);
        } else if (!this.mContext.getPackageManager().hasSystemFeature("android.hardware" +
                ".bluetooth_le")) {
            callback.onCompete(6);
        } else if (this.mBluetoothAdapter.isEnabled()) {
            QNLog.log("成功进入到连接设备的方法:", bleDevice.deviceName, bleDevice.mac);
            QNUser user = synUser(userId, height, gender, birthday);
            synchronized (this.helperMap) {
                QNBleHelper bleHelper = (QNBleHelper) this.helperMap.get(bleDevice.mac);
                if (bleHelper == null) {
                    QNLog.log("没有连接过这个设备,重新创建蓝牙辅助类");
                    bleHelper = new QNBleHelper(bleDevice, user, this.mContext, callback, this);
                    this.helperMap.put(bleDevice.mac, bleHelper);
                } else {
                    QNLog.log("连接过这个设备,复用蓝牙辅助类");
                    bleHelper.update(user, callback);
                }
                callback.onConnectStart(bleDevice);
                bleHelper.doConnect();
            }
        } else {
            callback.onCompete(7);
        }
    }
}
 
Example 22
Project: Equella   File: FilterByActivationDateRangeSection.java   View source code 5 votes vote down vote up
private Date[] convertDates(TleDate[] dates)
{
	Date[] rng = new Date[2];
	TleDate from = dates[0];
	TleDate to = dates[1];
	if( from != null )
	{
		rng[0] = UtcDate.convertUtcMidnightToLocalMidnight(from, CurrentTimeZone.get()).toDate();
	}
	if( to != null )
	{
		rng[1] = UtcDate.convertUtcMidnightToLocalMidnight(to, CurrentTimeZone.get()).toDate();
	}
	return rng;
}
 
Example 23
Project: jaer   File: ImageCreator.java   View source code 5 votes vote down vote up
@Override
public void run() {
    BufferedImage img = new BufferedImage(display.getWidth(), display.getHeight(), BufferedImage.TYPE_INT_RGB);
    for (int y = 0; y < display.getHeight(); y++) {
        for (int x = 0; x < display.getWidth(); x++) {
            int idx = getIndex(x, y);
            int nIdx = 3 * idx;
            int r = ((int) (rgbValues[nIdx++] * 255)); // red component 0...255
            int g = ((int) (rgbValues[nIdx++] * 255)); // green component 0...255
            int b = ((int) (rgbValues[nIdx] * 255)); // blue component 0...255
            int col = (r << 16) | (g << 8) | b;
            img.setRGB(x, y, col);
        }
    }
    AffineTransform tx = AffineTransform.getScaleInstance(1, -1);  //alligns the image correctly
    tx.translate(0, -img.getHeight(null));
    AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
    img = op.filter(img, null);
    SimpleDateFormat sdfDate = new SimpleDateFormat("_yyyy_MM_dd_HH_mm_ss");//dd/MM/yyyy
    Date now = new Date();
    String strDate = sdfDate.format(now);
    try {
        ImageIO.write(img, "png", new File(String.format("%s/ImageCreator%s.png", path, strDate)));
    } catch (IOException ex) {
        log.warning("can not save Image, Error: " + ex.toString());
    }
}
 
Example 24
Project: blockvote   File: MainViewModel.java   View source code 5 votes vote down vote up
public Data(Date start, Date end, float[] s2x1d, float[] s2x7d, float[] s2x30d, float[] ec1d, float[] ec7d, float[] ec30d) {
	this.start = start;
	this.end = end;
	this.s2x1d = s2x1d;
	this.s2x7d = s2x7d;
	this.s2x30d = s2x30d;
	this.ec1d = ec1d;
	this.ec7d = ec7d;
	this.ec30d = ec30d;
}
 
Example 25
Project: Android-PickerDialog   File: BaseDatePickerDialog.java   View source code 5 votes vote down vote up
public void clickSubmit(View v) {
    if (mTimeSelectListener != null) {
        try {
            Date date = WheelTime.dateFormat.parse(mWheelTime.getTime());
            mTimeSelectListener.onTimeSelect(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    dismiss();
}
 
Example 26
Project: traccar-service   File: Statistics.java   View source code 5 votes vote down vote up
public void setCaptureTime(Date captureTime) {
    if (captureTime != null) {
        this.captureTime = new Date(captureTime.getTime());
    } else {
        this.captureTime = null;
    }
}
 
Example 27
Project: java-design-pattern   File: CloneTest.java   View source code 5 votes vote down vote up
@Test
public void testShallowCopy() throws CloneNotSupportedException {
    Date date = new Date(1241314415234L);
    ShallowCopy shallow = new ShallowCopy("bruce", date);
    ShallowCopy cloneShallow = (ShallowCopy) shallow.clone();
    date.setTime(2124124124L);
    assertEquals(shallow, cloneShallow);
}
 
Example 28
Project: oscm   File: BLValidatorTest.java   View source code 5 votes vote down vote up
@Test
public void isValidDateRange_valid() throws ValidationException {

    // given valid range
    Date fromDate = new Date(System.currentTimeMillis());
    Date toDate = new Date(System.currentTimeMillis() + 24 * 60 * 60);

    // when validated then no exception is thrown
    BLValidator.isValidDateRange(fromDate, toDate);
}
 
Example 29
Project: GitHub   File: DateParseTest6.java   View source code 5 votes vote down vote up
public void test_date() throws Exception {
    String text = "\"19790714\"";
    Date date = JSON.parseObject(text, Date.class);
    Calendar calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale);
    calendar.setTime(date);
    
    Assert.assertEquals(1979, calendar.get(Calendar.YEAR));
    Assert.assertEquals(6, calendar.get(Calendar.MONTH));
    Assert.assertEquals(14, calendar.get(Calendar.DAY_OF_MONTH));
    
    Assert.assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY));
    Assert.assertEquals(0, calendar.get(Calendar.MINUTE));
    Assert.assertEquals(0, calendar.get(Calendar.SECOND));
    Assert.assertEquals(0, calendar.get(Calendar.MILLISECOND));
}
 
Example 30
Project: unitimes   File: PdfLegacyReport.java   View source code 5 votes vote down vote up
public void printHeader() throws DocumentException {
    out(renderEnd(
            renderMiddle("UniTime "+Constants.getVersion(),iTitle),
            iTitle2));
    out(mpad(
            new SimpleDateFormat("EEE MMM dd, yyyy").format(new Date()),
            iSession,' ',iNrChars));
    outln('=');
    iLineNo=0;
    if (iCont!=null && iCont.length()>0)
        println("("+iCont+" Continued)");
    if (iHeader!=null) for (int i=0;i<iHeader.length;i++) println(iHeader[i]);
    headerPrinted();
}
 
Example 31
Project: openjdk-jdk10   File: Util.java   View source code 5 votes vote down vote up
/**
 *
 **/
public static void writeProlog (PrintWriter stream, String filename)
{
  // <d59355> Remove target directory
  String targetDir = ((Arguments)Compile.compiler.arguments).targetDir;
  if (targetDir != null)
    filename = filename.substring (targetDir.length ());
  stream.println ();
  stream.println ("/**");
  stream.println ("* " + filename.replace (File.separatorChar, '/') +
      " .");
  stream.println ("* " + Util.getMessage ("toJavaProlog1",
      Util.getMessage ("Version.product", Util.getMessage ("Version.number"))));
  // <d48911> Do not introduce invalid escape characters into comment! <daz>
  //stream.println ("* " + Util.getMessage ("toJavaProlog2", Compile.compiler.arguments.file));
  stream.println ("* " + Util.getMessage ("toJavaProlog2", Compile.compiler.arguments.file.replace (File.separatorChar, '/')));

  ///////////////
  // This SHOULD work, but there's a bug in the JDK.
  //    stream.println ("* " + DateFormat.getDateTimeInstance (DateFormat.FULL, DateFormat.FULL, Locale.getDefault ()).format (new Date ()));
  // This gets around the bug:

  DateFormat formatter = DateFormat.getDateTimeInstance (DateFormat.FULL, DateFormat.FULL, Locale.getDefault ());

  // Japanese-specific workaround.  JDK bug 4069784 being repaired by JavaSoft.
  // Keep this transient solution until bug fix is reported.cd .

  if (Locale.getDefault () == Locale.JAPAN)
    formatter.setTimeZone (java.util.TimeZone.getTimeZone ("JST"));
  else
    formatter.setTimeZone (java.util.TimeZone.getDefault ());

  stream.println ("* " + formatter.format (new Date ()));

  // <daz>
  ///////////////

  stream.println ("*/");
  stream.println ();
}
 
Example 32
Project: ServiceComb-Company-WorkShop   File: AuthenticationIntegrationTest.java   View source code 5 votes vote down vote up
@Test
public void returnsTokenOfAuthenticatedUser() throws Exception {
  ZonedDateTime loginTime = ZonedDateTime.now().truncatedTo(SECONDS);

  MvcResult result = mockMvc.perform(
      post("/rest/login")
          .contentType(APPLICATION_FORM_URLENCODED)
          .param(USERNAME, username)
          .param(PASSWORD, password))
      .andExpect(status().isOk()).andReturn();

  String tokenInHeader = result.getResponse().getHeader(AUTHORIZATION).replace(TOKEN_PREFIX, "");
  Claims token = Jwts.parser()
      .setSigningKey(secretKey)
      .parseClaimsJws(tokenInHeader)
      .getBody();

  assertThat(token.getSubject()).isEqualTo(username);
  assertThat(token.getExpiration())
      .isAfterOrEqualsTo(Date.from(loginTime.plusDays(1).toInstant()))
      .isBeforeOrEqualsTo(Date.from(ZonedDateTime.now().plusDays(1).toInstant()));

  mockMvc.perform(
      post("/rest/validate")
          .contentType(APPLICATION_JSON_UTF8_VALUE)
          .content(objectMapper.writeValueAsBytes(tokenInHeader)))
      .andExpect(status().isOk());
}
 
Example 33
Project: uflo   File: Variable.java   View source code 5 votes vote down vote up
public static Variable newVariable(Object value,Context context){
	Variable variable=null;
	if(value instanceof Date){
		variable=new DateVariable((Date)value);
	}else if(value instanceof String){
		String str=(String)value;
		if(str.length()>255){
			variable=new TextVariable(str,context);
		}else{
			variable=new StringVariable((String)value);				
		}
	}else if(value instanceof Double){
		variable=new DoubleVariable((Double)value);
	}else if(value instanceof Float){
		variable=new FloatVariable((Float)value);			
	}else if(value instanceof Long){
		variable=new LongVariable((Long)value);
	}else if(value instanceof Integer){
		variable=new IntegerVariable((Integer)value);
	}else if(value instanceof Boolean){
		variable=new BooleanVariable((Boolean)value);			
	}else if(value instanceof Short){
		variable=new ShortVariable((Short)value);			
	}else if(value instanceof Byte){
		variable=new ByteVariable((Byte)value);			
	}else if(value instanceof Character){
		variable=new CharacterVariable((Character)value);			
	}else{
		if(!(value instanceof java.io.Serializable)){
			throw new IllegalArgumentException("Variable value ["+value.getClass().getName()+"] must implement the java.io.Serializable interface");
		}
		variable=new BlobVariable(value,context);
	}
	return variable;
}
 
Example 34
Project: opencps-v2   File: DossierListennerUltils.java   View source code 5 votes vote down vote up
static void sendToApplicant(Applicant model, String notificationType, JSONObject messageKey) {

		try {
			long notificationQueueId = CounterLocalServiceUtil.increment(NotificationQueue.class.getName());
			NotificationQueue queue = null;
			Date now = new Date();
			Calendar cal = Calendar.getInstance();
			cal.set(Calendar.HOUR, cal.get(Calendar.HOUR) + 1);
			queue = NotificationQueueLocalServiceUtil.createNotificationQueue(notificationQueueId);
			queue.setCreateDate(now);
			queue.setModifiedDate(now);
			queue.setGroupId(model.getGroupId());
			queue.setCompanyId(model.getCompanyId());
			queue.setNotificationType(notificationType);
			queue.setClassName(Applicant.class.getName());

			queue.setClassPK(String.valueOf(model.getPrimaryKey()));
			queue.setToUsername(model.getApplicantName());
			queue.setToUserId(model.getUserId());
			queue.setToEmail(model.getContactEmail());
			queue.setToTelNo(model.getContactTelNo());

			messageKey.put("$USER_NAME$", model.getApplicantName());
			messageKey.put("toName", model.getApplicantName());
			messageKey.put("toAddress", model.getContactEmail());

			String payload = getPayload(notificationType, messageKey, model.getGroupId()).toString();

			queue.setPayload(payload);
			queue.setExpireDate(cal.getTime());

			NotificationQueueLocalServiceUtil.addNotificationQueue(queue);
		} catch (Exception e) {
			_log.error(e);
		}

	}
 
Example 35
Project: dbsync   File: BaseMainDbActivity.java   View source code 4 votes vote down vote up
@Override
public void run() {
    mTvCurrentTime.setText("CurrentTime: " +Utility.formatDateTimeNoTimeZone(new Date()));

    mMainHandler.postDelayed(this, 500);
}
 
Example 36
Project: opencps-v2   File: APIDateTimeUtils.java   View source code 4 votes vote down vote up
public static String convertDateToString(Date date, String pattern) {
	DateFormat dateFormat = DateFormatFactoryUtil.getSimpleDateFormat(
		pattern);

	if (Validator.isNull(date) || Validator.isNull(pattern)) {
		return StringPool.BLANK;
	}

	dateFormat.setTimeZone(TimeZoneUtil.getTimeZone("Asia/Ho_Chi_Minh"));

	Calendar calendar = Calendar.getInstance();

	calendar.setTime(date);

	return dateFormat.format(calendar.getTime());
}
 
Example 37
Project: xxpay-master   File: RefundOrderExample.java   View source code 4 votes vote down vote up
public Criteria andExpireTimeEqualTo(Date value) {
    addCriterion("ExpireTime =", value, "expireTime");
    return (Criteria) this;
}
 
Example 38
Project: TrackMeIfYouCanChat   File: Message.java   View source code 4 votes vote down vote up
public void set_d(Date d)
{
    this.d=d;
}
 
Example 39
Project: cf-mta-deploy-service   File: DeployedMtaModule.java   View source code 4 votes vote down vote up
public void setUpdatedOn(Date updatedOn) {
    this.updatedOn = updatedOn;
}
 
Example 40
Project: generator-thundr-gae-react   File: LocalDateDateTranslatorFactoryTest.java   View source code 4 votes vote down vote up
private LocalDate load(Date val) {
    return translator.load(val, null, null);
}