Example usage for java.sql Timestamp getTime

List of usage examples for java.sql Timestamp getTime

Introduction

In this page you can find the example usage for java.sql Timestamp getTime.

Prototype

public long getTime() 

Source Link

Document

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Timestamp object.

Usage

From source file:database.DataLoader.java

private void moveOrders() throws SQLException, ClassNotFoundException, Exception {
    //    //from w w  w  . j  av  a2s  .  co m
    final String tableName = ORDER;
    final ResultSet orderSet = getFromOldBase(getSelectAll(tableName, "id"));
    while (orderSet.next()) {
        // ?  
        TransactionTemplate temp = new TransactionTemplate(transactionManager);
        temp.execute(new TransactionCallbackWithoutResult() {

            @Override
            protected void doInTransactionWithoutResult(TransactionStatus ts) {
                Long oldId = 0L;
                try {
                    oldId = orderSet.getLong("id");
                    String subject = orderSet.getString("theme");
                    if (subject.length() > 250) {
                        subject = subject.substring(0, 250);
                    }
                    Long oldBranchId = orderSet.getLong("branch_id");
                    Long oldOrderTypeId = orderSet.getLong("type_id");
                    String city = orderSet.getString("university");
                    Double price = orderSet.getDouble("price");
                    Double authorSalary = orderSet.getDouble("reward");
                    Date redline = orderSet.getDate("redline");
                    Date deadline = orderSet.getDate("deadline");
                    Long oldAuthorId = orderSet.getLong("author_id");
                    Long clientId = orderSet.getLong("client_id");
                    String rewardComment = orderSet.getString("reward_comment");
                    Boolean flag_0 = orderSet.getBoolean("flag_0");
                    Boolean flag_1 = orderSet.getBoolean("flag_1");
                    Timestamp timestamp = orderSet.getTimestamp("ready_date");
                    String readyComment = orderSet.getString("ready_comment");
                    String comment = orderSet.getString("description");
                    Date readyDate = null;
                    if (timestamp != null) {
                        readyDate = new Date(timestamp.getTime());
                    }

                    Long newBranchId = getNewId(oldBranchId, BRANCH);
                    Branch branch = branchDao.find(newBranchId);

                    Long newAuthorId = getNewId(oldAuthorId, USERS);
                    Author author = authorDao.find(newAuthorId);

                    Long newOrderTypeId = getNewId(oldOrderTypeId, TYPE);
                    OrderType orderType = orderTypeDao.find(newOrderTypeId);

                    Integer statusInt = orderSet.getInt("status");
                    OrderStatus status = getStatus(statusInt);
                    if (status == null) {
                        status = OrderStatus.NEW;
                    }

                    Date orderDate = getDateOrToday(orderSet, "created");

                    Order order = new Order();
                    order.setStatus(status);
                    order.setOrderDate(orderDate);
                    order.setAuthor(author);
                    order.setBranch(branch);
                    order.setOrderType(orderType);
                    order.setSubject(subject);
                    order.setCity(city);
                    order.setCost(price);
                    order.setAuthor_salary(authorSalary);
                    //  ? ? , ? 
                    order.setRealDate(deadline);
                    order.setDeadlineDate(redline);
                    order.setAuthorComment(readyComment);
                    order.setComment(comment);

                    order.setReadyDate(readyDate);
                    order.setFirstFlag(flag_0);
                    order.setSecondFlag(flag_1);
                    order.setCommentToAuthorSalary(rewardComment);
                    order.setOldId(StringAdapter.getString(oldId));

                    ResultSet clientSet = getFromOldBase("select * from " + CLIENT + " where id = " + clientId);
                    String clientEmail = null;
                    String clientFio = null;
                    String clientPhone = null;
                    while (clientSet.next()) {
                        clientEmail = trim(clientSet.getString("email"));
                        clientFio = clientSet.getString("firstname") + " " + clientSet.getString("fathername")
                                + " " + clientSet.getString("lastname");
                        clientPhone = clientSet.getString("phone");
                    }
                    if (ValidatorUtils.isEmail(clientEmail)) {
                        order.setClientEmail(clientEmail);
                    }
                    order.setClientFio(clientFio);
                    order.setClientPhone(clientPhone);

                    saveObjectAndLink(order, oldId, tableName);
                } catch (Throwable e) {
                    ts.setRollbackOnly();
                    addErrorMessage("order: " + oldId + " " + StringAdapter.getStackExeption(e));
                    log.warn("order: " + oldId + " " + StringAdapter.getStackExeption(e));
                }
            }
        });

    }

}

From source file:com.htm.test.TaskParentInterfaceTest.java

/**
 * Test the creation of a task instance.</br>
 * In the corresponding task model all properties are set (priority, skipable etc.).
 * For assigning people to the task instance only logical people groups are used.
 *
 * @throws HumanTaskManagerException/*w  w  w.  j a  v  a2 s . c o m*/
 */
@Test
public void createTaskInstance() throws HumanTaskManagerException {

    try {
        dataAccessRepository.beginTx();

        /* Set the the user name and password in the security context of spring */
        initSecurityContext(TASK_INITIATOR_USER_ID, TASK_INITIATOR_PASSWORD);

        /* Time before creation required for assertions */
        long timeBeforeTiCreation = Calendar.getInstance().getTimeInMillis();

        Timestamp expirationTime = new Timestamp(Calendar.getInstance().getTimeInMillis() + 5000);
        TaskParentInterface partenInterface = this.taskParentInterface;
        /* Create task instance */
        String tiid = partenInterface.createTaskInstance(TaskParentConnectorDummy.TASK_PARENT_ID,
                getCorrelationPropertyDummies(), TASK_MODEL_DUMMY_NAME_1, TASK_INSTANCE_DUMMY_NAME1,
                getInputDataDummy(), getAttachmentDummies(), expirationTime);
        /* Time after creation required for assertions */
        long timeAfterTiCreation = Calendar.getInstance().getTimeInMillis();

        ITaskModel taskModel = dataAccessRepository.getHumanTaskModel(TASK_MODEL_DUMMY_NAME_1);
        ITaskInstance resultTaskInstance = dataAccessRepository.getTaskInstance(tiid);

        /*
        * Assertions
        */
        assertEquals(TASK_INSTANCE_DUMMY_NAME1, resultTaskInstance.getName());
        assertEquals(ETaskInstanceState.READY, resultTaskInstance.getStatus());
        /*
        * Since we don't know exact time when the task instance was
        * transitioned to the READY state (i.e. activated) we have can only
        * specify an interval (it's the same with createdOn).
        */
        long activationTime = resultTaskInstance.getActivationTime().getTime();

        assertTrue(timeBeforeTiCreation <= activationTime && activationTime <= timeAfterTiCreation);
        long createdOnTime = resultTaskInstance.getCreatedOn().getTime();
        assertTrue(timeBeforeTiCreation <= createdOnTime && createdOnTime <= timeAfterTiCreation);
        assertEquals(expirationTime.getTime(), resultTaskInstance.getExpirationTime().getTime());

        assertEquals(TaskParentConnectorDummy.TASK_PARENT_ID, resultTaskInstance.getTaskParentId());

        /*
        * Priority, startBy, completeBy and skipable is determined while
        * task instance creation using xpath expressions. xpath expressions
        * are defined in the methods getPriorityQuery, getSkipableQuery
        * etc. in the class TaskInstanceDummyProvider. The evaluation
        * context is defined in the class TaskParentContextDummy
        */
        assertEquals("Compare priority.", Integer.valueOf(TaskParentContextDummy.PRIORITY).intValue(),
                resultTaskInstance.getPriority());
        try {
            assertEquals(XPathUtils.getTimestampFromString(TaskParentContextDummy.STARTBY),
                    resultTaskInstance.getStartBy());
        } catch (Exception e) {
            fail(e.getMessage());
        }
        try {
            assertEquals(XPathUtils.getTimestampFromString(TaskParentContextDummy.COMPLETEBY),
                    resultTaskInstance.getCompleteBy());
        } catch (Exception e) {
            fail(e.getMessage());
        }
        assertEquals(new Boolean(TaskParentContextDummy.SKIPABLE), resultTaskInstance.isSkipable());

        assertTrue(resultTaskInstance.getInput() instanceof Map<?, ?>);
        assertInputDummies(getInputDataDummy(), (Map<?, ?>) resultTaskInstance.getInput());

        /* The values for the presentation data that were set in the task model should be set here */
        assertEquals(taskModel.getPresentationModel().getTitle(), resultTaskInstance.getPresentationName());
        assertEquals(taskModel.getPresentationModel().getSubject(),
                resultTaskInstance.getPresentationSubject());
        assertEquals(taskModel.getPresentationModel().getDescription(),
                resultTaskInstance.getPresentationDescription());
        /*
        * The users are determined while task instance creation using xpath
        * expressions. The expressions are defined in the methods
        * getBusinessAdminQuery, getExcludedOwnerQuery etc. of this class.
        * The evaluation context is defined in getInputDataDummy
        */
        assertEquals(TASK_INITIATOR_USER_ID, resultTaskInstance.getTaskInitiator());
        assertUsers(getExpectedBusinessAdministrators(), resultTaskInstance.getBusinessAdministrators());
        assertUsers(getExpectedTaskStakeholders(), resultTaskInstance.getTaskStakeholders());
        /* potential owners are employees without interns */
        assertUsers(getExpectedPotentialOwners(), resultTaskInstance.getPotentialOwners());

        assertAttachments(TASK_INITIATOR_USER_ID, getAttachmentDummies(), resultTaskInstance.getAttachments());
        assertCorrelationProperties(getCorrelationPropertyDummies(),
                resultTaskInstance.getCorrelationProperties());

        assertEquals(ETaskInstanceState.READY, resultTaskInstance.getStatus());

        dataAccessRepository.commitTx();
    } catch (HumanTaskManagerException e) {
        dataAccessRepository.rollbackTx();
        throw e;
    } finally {
        dataAccessRepository.close();
    }
}

From source file:org.dcache.chimera.FsSqlDriver.java

/**
 *
 * creates an entry in t_level_x table//from  www . java 2  s.  c  om
 *
 * @param inode
 * @param uid
 * @param gid
 * @param mode
 * @param level
 * @return
 */
FsInode createLevel(FsInode inode, int uid, int gid, int mode, int level) {
    Timestamp now = new Timestamp(System.currentTimeMillis());
    _jdbc.update("INSERT INTO t_level_" + level
            + "(inumber,imode,inlink,iuid,igid,isize,ictime,iatime,imtime,ifiledata) VALUES(?,?,1,?,?,0,?,?,?, NULL)",
            ps -> {
                ps.setLong(1, inode.ino());
                ps.setInt(2, mode);
                ps.setInt(3, uid);
                ps.setInt(4, gid);
                ps.setTimestamp(5, now);
                ps.setTimestamp(6, now);
                ps.setTimestamp(7, now);
            });
    Stat stat = new Stat();
    stat.setCrTime(now.getTime());
    stat.setGeneration(0);
    stat.setSize(0);
    stat.setATime(now.getTime());
    stat.setCTime(now.getTime());
    stat.setMTime(now.getTime());
    stat.setUid(uid);
    stat.setGid(gid);
    stat.setMode(mode | UnixPermission.S_IFREG);
    stat.setNlink(1);
    stat.setIno(inode.ino());
    stat.setDev(17);
    stat.setRdev(13);
    return new FsInode(inode.getFs(), inode.ino(), FsInodeType.INODE, level, stat);
}

From source file:org.kuali.rice.kew.server.DTOConverterTest.java

@Test
public void testConvertActionItem() throws Exception {
    // get test data
    String testWorkgroupName = "TestWorkgroup";
    Group testWorkgroup = KimApiServiceLocator.getGroupService()
            .getGroupByNamespaceCodeAndName(KimConstants.KIM_GROUP_WORKFLOW_NAMESPACE_CODE, testWorkgroupName);
    String testWorkgroupId = testWorkgroup.getId();
    assertTrue("Test workgroup '" + testWorkgroupName + "' should have at least one user", KimApiServiceLocator
            .getGroupService().getDirectMemberPrincipalIds(testWorkgroup.getId()).size() > 0);
    String workflowId = KimApiServiceLocator.getGroupService()
            .getDirectMemberPrincipalIds(testWorkgroup.getId()).get(0);
    assertNotNull("User from workgroup should not be null", workflowId);
    String actionRequestCd = KewApiConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ;
    String actionRequestId = "4";
    String docName = "dummy";
    String roleName = "fakeRole";
    String documentId = "23";
    Timestamp dateAssigned = new Timestamp(new Date().getTime());
    String docHandlerUrl = "http://this.is.not.us";
    String docTypeLabel = "Label Me";
    String docTitle = "Title me";
    String responsibilityId = "35";
    DelegationType delegationType = DelegationType.PRIMARY;

    // create fake action item
    ActionItem actionItem = new ActionItem();
    actionItem.setActionRequestCd(actionRequestCd);
    actionItem.setActionRequestId(actionRequestId);
    actionItem.setDocName(docName);//from ww  w  . j a  va  2 s. c om
    actionItem.setRoleName(roleName);
    actionItem.setPrincipalId(workflowId);
    actionItem.setDocumentId(documentId);
    actionItem.setDateAssigned(dateAssigned);
    actionItem.setDocHandlerURL(docHandlerUrl);
    actionItem.setDocLabel(docTypeLabel);
    actionItem.setDocTitle(docTitle);
    actionItem.setGroupId(testWorkgroupId);
    actionItem.setResponsibilityId(responsibilityId);
    actionItem.setDelegationType(delegationType);
    actionItem.setDelegatorPrincipalId(workflowId);
    actionItem.setDelegatorGroupId(testWorkgroupId);

    // convert to action item vo object and verify
    org.kuali.rice.kew.api.action.ActionItem actionItemVO = ActionItem.to(actionItem);
    assertEquals("Action Item VO object has incorrect value", actionRequestCd,
            actionItemVO.getActionRequestCd());
    assertEquals("Action Item VO object has incorrect value", actionRequestId,
            actionItemVO.getActionRequestId());
    assertEquals("Action Item VO object has incorrect value", docName, actionItemVO.getDocName());
    assertEquals("Action Item VO object has incorrect value", roleName, actionItemVO.getRoleName());
    assertEquals("Action Item VO object has incorrect value", workflowId, actionItemVO.getPrincipalId());
    assertEquals("Action Item VO object has incorrect value", documentId, actionItemVO.getDocumentId());
    assertEquals("Action Item VO object has incorrect value", new DateTime(dateAssigned.getTime()),
            actionItemVO.getDateTimeAssigned());
    assertEquals("Action Item VO object has incorrect value", docHandlerUrl, actionItemVO.getDocHandlerURL());
    assertEquals("Action Item VO object has incorrect value", docTypeLabel, actionItemVO.getDocLabel());
    assertEquals("Action Item VO object has incorrect value", docTitle, actionItemVO.getDocTitle());
    assertEquals("Action Item VO object has incorrect value", "" + testWorkgroupId, actionItemVO.getGroupId());
    assertEquals("Action Item VO object has incorrect value", responsibilityId,
            actionItemVO.getResponsibilityId());
    assertEquals("Action Item VO object has incorrect value", delegationType, actionItemVO.getDelegationType());
    assertEquals("Action Item VO object has incorrect value", workflowId,
            actionItemVO.getDelegatorPrincipalId());
    assertEquals("Action Item VO object has incorrect value", testWorkgroupId,
            actionItemVO.getDelegatorGroupId());
}

From source file:org.kuali.rice.kew.server.BeanConverterTester.java

@Test
public void testConvertActionItem() throws Exception {
    // get test data
    String testWorkgroupName = "TestWorkgroup";
    Group testWorkgroup = KimApiServiceLocator.getGroupService()
            .getGroupByNamespaceCodeAndName(KimConstants.KIM_GROUP_WORKFLOW_NAMESPACE_CODE, testWorkgroupName);
    String testWorkgroupId = testWorkgroup.getId();
    assertTrue("Test workgroup '" + testWorkgroupName + "' should have at least one user", KimApiServiceLocator
            .getGroupService().getDirectMemberPrincipalIds(testWorkgroup.getId()).size() > 0);
    String workflowId = KimApiServiceLocator.getGroupService()
            .getDirectMemberPrincipalIds(testWorkgroup.getId()).get(0);
    assertNotNull("User from workgroup should not be null", workflowId);
    String actionRequestCd = KewApiConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ;
    String actionRequestId = "4";
    String docName = "dummy";
    String roleName = "fakeRole";
    String documentId = "abc23";
    Timestamp dateAssigned = new Timestamp(new Date().getTime());
    String docHandlerUrl = "http://this.is.not.us";
    String docTypeLabel = "Label Me";
    String docTitle = "Title me";
    String responsibilityId = "35";
    DelegationType delegationType = DelegationType.PRIMARY;

    // create fake action item
    ActionItem actionItem = new ActionItem();
    actionItem.setActionRequestCd(actionRequestCd);
    actionItem.setActionRequestId(actionRequestId);
    actionItem.setDocName(docName);/*from   www. j a va2 s . co  m*/
    actionItem.setRoleName(roleName);
    actionItem.setPrincipalId(workflowId);
    actionItem.setDocumentId(documentId);
    actionItem.setDateAssigned(dateAssigned);
    actionItem.setDocHandlerURL(docHandlerUrl);
    actionItem.setDocLabel(docTypeLabel);
    actionItem.setDocTitle(docTitle);
    actionItem.setGroupId(testWorkgroupId);
    actionItem.setResponsibilityId(responsibilityId);
    actionItem.setDelegationType(delegationType);
    actionItem.setDelegatorPrincipalId(workflowId);
    actionItem.setDelegatorGroupId(testWorkgroupId);

    // convert to action item vo object and verify
    org.kuali.rice.kew.api.action.ActionItem actionItemVO = ActionItem.to(actionItem);
    assertEquals("Action Item VO object has incorrect value", actionRequestCd,
            actionItemVO.getActionRequestCd());
    assertEquals("Action Item VO object has incorrect value", actionRequestId,
            actionItemVO.getActionRequestId());
    assertEquals("Action Item VO object has incorrect value", docName, actionItemVO.getDocName());
    assertEquals("Action Item VO object has incorrect value", roleName, actionItemVO.getRoleName());
    assertEquals("Action Item VO object has incorrect value", workflowId, actionItemVO.getPrincipalId());
    assertEquals("Action Item VO object has incorrect value", documentId, actionItemVO.getDocumentId());
    assertEquals("Action Item VO object has incorrect value", new DateTime(dateAssigned.getTime()),
            actionItemVO.getDateTimeAssigned());
    assertEquals("Action Item VO object has incorrect value", docHandlerUrl, actionItemVO.getDocHandlerURL());
    assertEquals("Action Item VO object has incorrect value", docTypeLabel, actionItemVO.getDocLabel());
    assertEquals("Action Item VO object has incorrect value", docTitle, actionItemVO.getDocTitle());
    assertEquals("Action Item VO object has incorrect value", "" + testWorkgroupId, actionItemVO.getGroupId());
    assertEquals("Action Item VO object has incorrect value", responsibilityId,
            actionItemVO.getResponsibilityId());
    assertEquals("Action Item VO object has incorrect value", delegationType, actionItemVO.getDelegationType());
    assertEquals("Action Item VO object has incorrect value", workflowId,
            actionItemVO.getDelegatorPrincipalId());
    assertEquals("Action Item VO object has incorrect value", testWorkgroupId,
            actionItemVO.getDelegatorGroupId());
}

From source file:jp.co.ntts.vhut.logic.PrivateCloudLogic.java

/**
 * @param startDate/*from ww w  .  j  av  a2  s  .  c  o  m*/
 * @param endDate
 * @param operations
 * @param statuses
 * @param where
 */
private void addCommandSearchConditions(Timestamp startDate, Timestamp endDate,
        Collection<CommandOperation> operations, Collection<CommandStatus> statuses, ComplexWhere where) {
    //??
    if (startDate != null && endDate != null) {
        if (startDate.getTime() > endDate.getTime()) {
            throw new InputRuntimeException("startDate, endDate", "startTime should be before endTime");
        }
        where.and(new SimpleWhere().ge(command().endTime(), TimestampUtil.floorAsDate(startDate))
                .le(command().startTime(), TimestampUtil.floorAsDate(endDate)));
    }
    //???AND?
    if (operations != null) {
        where.and(in(command().operation(), operations));
    }
    //??AND?
    if (statuses != null) {
        where.and(in(command().status(), statuses));
    }
}

From source file:org.kuali.kfs.module.ar.service.impl.ContractsGrantsInvoiceCreateDocumentServiceImpl.java

/**
 * This method would make sure the amounts of the current period are not included. So it calculates the cumulative and
 * subtracts the current period values. This would be done for Billing Frequencies - Monthly, Quarterly, Semi-Annual and Annual.
 *
 * @param glBalance/*from w w  w .j a  v  a 2 s .  co  m*/
 * @return balanceAmount
 */
protected KualiDecimal calculateBalanceAmountWithoutLastBilledPeriod(java.sql.Date lastBilledDate,
        Balance glBalance) {
    Timestamp ts = new Timestamp(new java.util.Date().getTime());
    java.sql.Date today = new java.sql.Date(ts.getTime());
    AccountingPeriod currPeriod = accountingPeriodService.getByDate(today);
    String currentPeriodCode = currPeriod.getUniversityFiscalPeriodCode();

    KualiDecimal currentBalanceAmount = KualiDecimal.ZERO;
    switch (currentPeriodCode) {
    case KFSConstants.MONTH13:
        currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth12Amount()));
        // notice - no break!!!! we want to fall through to pick up all the prior months amounts
    case KFSConstants.MONTH12:
        currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth11Amount()));
    case KFSConstants.MONTH11:
        currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth10Amount()));
    case KFSConstants.MONTH10:
        currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth9Amount()));
    case KFSConstants.MONTH9:
        currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth8Amount()));
    case KFSConstants.MONTH8:
        currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth7Amount()));
    case KFSConstants.MONTH7:
        currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth6Amount()));
    case KFSConstants.MONTH6:
        currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth5Amount()));
    case KFSConstants.MONTH5:
        currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth4Amount()));
    case KFSConstants.MONTH4:
        currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth3Amount()));
    case KFSConstants.MONTH3:
        currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth2Amount()));
    case KFSConstants.MONTH2:
        currentBalanceAmount = currentBalanceAmount.add(cleanAmount(glBalance.getMonth1Amount()));
    }

    return glBalance.getContractsGrantsBeginningBalanceAmount().add(currentBalanceAmount);
}

From source file:eu.cloudscale.showcase.generate.GenerateHibernate.java

@Override
public void populateOrdersAndCC_XACTSTable() {
    GregorianCalendar cal;/*from w  ww.  j a v a2 s .co m*/
    String[] credit_cards = { "VISA", "MASTERCARD", "DISCOVER", "AMEX", "DINERS" };
    int num_card_types = 5;
    String[] ship_types = { "AIR", "UPS", "FEDEX", "SHIP", "COURIER", "MAIL" };
    int num_ship_types = 6;

    String[] status_types = { "PROCESSING", "SHIPPED", "PENDING", "DENIED" };
    int num_status_types = 4;

    // Order variables
    int O_C_ID;
    java.sql.Timestamp O_DATE;
    double O_SUB_TOTAL;
    double O_TAX;
    double O_TOTAL;
    String O_SHIP_TYPE;
    java.sql.Timestamp O_SHIP_DATE;
    int O_BILL_ADDR_ID, O_SHIP_ADDR_ID;
    String O_STATUS;

    String CX_TYPE;
    int CX_NUM;
    String CX_NAME;
    java.sql.Date CX_EXPIRY;
    String CX_AUTH_ID;
    int CX_CO_ID;

    System.out.println("Populating ORDERS, ORDER_LINES, CC_XACTS with " + NUM_ORDERS + " orders");

    System.out.print("Complete (in 10,000's): ");

    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();

    for (int i = 1; i <= NUM_ORDERS; i++) {
        if (i % 1000 == 0) {
            session.flush();
            session.clear();

            System.out.print(i / 1000 + " ");
        }

        if (i % 10000 == 0) {
            System.out.println();
        }

        int num_items = getRandomInt(1, 5);

        cal = new GregorianCalendar();
        cal.add(Calendar.DAY_OF_YEAR, -1 * getRandomInt(1, 60));
        O_DATE = new java.sql.Timestamp(cal.getTime().getTime());
        O_SUB_TOTAL = (double) getRandomInt(1000, 999999) / 100;
        O_TAX = O_SUB_TOTAL * 0.0825;
        O_TOTAL = O_SUB_TOTAL + O_TAX + 3.00 + num_items;
        O_SHIP_TYPE = ship_types[getRandomInt(0, num_ship_types - 1)];
        cal.add(Calendar.DAY_OF_YEAR, getRandomInt(0, 7));
        O_SHIP_DATE = new java.sql.Timestamp(cal.getTime().getTime());

        O_STATUS = status_types[getRandomInt(0, num_status_types - 1)];

        Orders order = new Orders();

        ICustomer customer = this.customers.get(getRandomInt(1, this.customers.size() - 1));
        IAddress billAddress = this.addresses.get(getRandomInt(1, this.addresses.size() - 1));
        IAddress shipAddress = this.addresses.get(getRandomInt(1, this.addresses.size() - 1));

        //         int OL_I_ID = getRandomInt( 1, NUM_ITEMS );
        //         IItem item = itemDao.findById( OL_I_ID );

        // Set parameter
        order.setCustomer(customer);
        order.setODate(new Date(O_DATE.getTime()));
        order.setOSubTotal(O_SUB_TOTAL);
        order.setOTax(O_TAX);
        order.setOTotal(O_TOTAL);
        order.setOShipType(O_SHIP_TYPE);
        order.setOShipDate(O_SHIP_DATE);
        order.setAddressByOBillAddrId(billAddress);
        order.setAddressByOShipAddrId(shipAddress);
        order.setOStatus(O_STATUS);
        order.setCcXactses(new HashSet<ICcXacts>());
        order.setOrderLines(new HashSet<IOrderLine>());

        session.save(order);

        for (int j = 1; j <= num_items; j++) {
            int OL_ID = j;
            int OL_O_ID = i;

            int OL_QTY = getRandomInt(1, 300);
            double OL_DISCOUNT = (double) getRandomInt(0, 30) / 100;
            String OL_COMMENTS = getRandomAString(20, 100);

            OrderLine orderLine = new OrderLine();
            orderLine.setItem(this.items.get(getRandomInt(1, this.items.size() - 1)));
            orderLine.setOlQty(OL_QTY);
            orderLine.setOlDiscount(OL_DISCOUNT);
            orderLine.setOlComment(OL_COMMENTS);
            orderLine.setOrders(order);

            session.save(orderLine);
            order.getOrderLines().add(orderLine);

        }

        CX_TYPE = credit_cards[getRandomInt(0, num_card_types - 1)];
        CX_NUM = getRandomNString(16);
        CX_NAME = getRandomAString(14, 30);
        cal = new GregorianCalendar();
        cal.add(Calendar.DAY_OF_YEAR, getRandomInt(10, 730));
        CX_EXPIRY = new java.sql.Date(cal.getTime().getTime());
        CX_AUTH_ID = getRandomAString(15);

        CcXacts ccXacts = new CcXacts();

        ccXacts.setCountry(this.countries.get(getRandomInt(1, this.countries.size() - 1)));
        ccXacts.setOrders(order);
        ccXacts.setCxType(CX_TYPE);
        ccXacts.setCxNum(CX_NUM);
        ccXacts.setCxName(CX_NAME);
        ccXacts.setCxExpiry(CX_EXPIRY);
        ccXacts.setCxAuthId(CX_AUTH_ID);
        ccXacts.setCxXactAmt(O_TOTAL);
        ccXacts.setCxXactDate(O_SHIP_DATE);

        //         ccXacts.setOrders( order );

        order.getCcXactses().add(ccXacts);

        session.save(ccXacts);

    }

    tx.commit();
    session.close();

    System.out.println("");
}

From source file:uk.ac.soton.itinnovation.sad.service.services.SchedulingService.java

/**
 * Converts SADJob (database representation of a SAD job) into JSON
 *
 * @param theJob - database representation of the job
 * @return job as JSON// ww w . jav  a  2  s .  co  m
 */
public JSONObject jobAsJson(SADJob theJob) {
    JSONObject jobAsJson = new JSONObject();
    Timestamp tempTimestamp;
    ArrayList<SADJobExecution> executionsForJob;
    String jobId;
    String basePath = configurationService.getConfiguration().getBasepath();

    jobId = theJob.getIdAsString();
    jobAsJson.put("ID", jobId);
    jobAsJson.put("PluginName", theJob.getPluginName());
    jobAsJson.put("Name", theJob.getName());
    jobAsJson.put("Description", theJob.getDescription());
    jobAsJson.put("Arguments", JSONArray.fromObject(theJob.getArguments()));
    jobAsJson.put("Inputs", JSONArray.fromObject(theJob.getInputs()));
    jobAsJson.put("Outputs", JSONArray.fromObject(theJob.getOutputs()));
    jobAsJson.put("Schedule", JSONObject.fromObject(theJob.getSchedule()));
    jobAsJson.put("Status", theJob.getStatus());

    tempTimestamp = theJob.getWhenCreated();
    if (tempTimestamp == null) {
        jobAsJson.put("WhenCreated_as_string", "");
        jobAsJson.put("WhenCreated_in_msec", "");
    } else {
        jobAsJson.put("WhenCreated_as_string", Util.timestampToString(tempTimestamp));
        jobAsJson.put("WhenCreated_in_msec", tempTimestamp.getTime());
    }

    tempTimestamp = theJob.getWhenLastrun();
    if (tempTimestamp == null) {
        jobAsJson.put("WhenLastrun_as_string", "");
        jobAsJson.put("WhenLastrun_in_msec", "");
    } else {
        jobAsJson.put("WhenLastrun_as_string", Util.timestampToString(tempTimestamp));
        jobAsJson.put("WhenLastrun_in_msec", tempTimestamp.getTime());
    }

    executionsForJob = getExecutionsForJob(jobId);
    if (executionsForJob.isEmpty()) {
        jobAsJson.put("Executions_num", 0);
    } else {
        jobAsJson.put("Executions_num", executionsForJob.size());

    }

    jobAsJson.put("data_num", getDataNumForJob(theJob));
    jobAsJson.put("url_details", (basePath != null ? basePath : "") + "/jobs?jobId=" + jobId);
    jobAsJson.put("url_pause", (basePath != null ? basePath : "") + "/jobs?jobId=" + jobId + "&action=pause");
    jobAsJson.put("url_cancel", (basePath != null ? basePath : "") + "/jobs?jobId=" + jobId + "&action=cancel");
    jobAsJson.put("url_resume", (basePath != null ? basePath : "") + "/jobs?jobId=" + jobId + "&action=resume");
    jobAsJson.put("url_delete", (basePath != null ? basePath : "") + "/jobs?jobId=" + jobId + "&action=delete");

    jobAsJson.put("url_data", (basePath != null ? basePath : "") + "/jobs/" + jobId + "/data");
    jobAsJson.put("url_vis", (basePath != null ? basePath : "") + "/visualise/" + theJob.getPluginName()
            + "/data.html?jobid=" + jobId + "&num_results=20");

    return jobAsJson;
}

From source file:jp.co.ntts.vhut.logic.PrivateCloudLogic.java

@Override
public void updatePublicIpResources() {
    int count = Ipv4ConversionUtil.getHostAddressCount(cloudConfig.exIpStartAddress,
            cloudConfig.exIpEndAddress);
    count -= cloudConfig.getExIpExcludeList().size();
    List<PublicIpResource> toBeInsertList = new ArrayList<PublicIpResource>();
    List<PublicIpResource> toBeUpdateList = new ArrayList<PublicIpResource>();
    Timestamp currentDate = TimestampUtil.getCurrentDateAsTimestamp();
    Timestamp minDate = TimestampUtil.subtract(currentDate, 1, TimestampUtil.Unit.DAY);
    Timestamp maxDate = TimestampUtil.add(cloudConfig.getReservationEndTimeMax(), 1, TimestampUtil.Unit.DAY);
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
    Map<String, PublicIpResource> resourceMap = new HashMap<String, PublicIpResource>();
    //?/*  w  ww.j a  va 2  s .  c om*/
    List<PublicIpResource> oldResourceList = jdbcManager.from(PublicIpResource.class)
            .where(new SimpleWhere().eq(publicIpResource().cloudId(), cloudId)
                    .ge(publicIpResource().time(), minDate).le(publicIpResource().time(), maxDate))
            .getResultList();
    for (PublicIpResource oldResource : oldResourceList) {
        String key = dateFormat.format(oldResource.time);
        resourceMap.put(key, oldResource);
    }
    //??
    Timestamp targetDate = currentDate;
    while (targetDate.before(maxDate)) {
        String key = dateFormat.format(targetDate);
        PublicIpResource oldResource = resourceMap.get(key);
        if (oldResource == null) {
            //
            PublicIpResource newResource = new PublicIpResource();
            newResource.id = targetDate.getTime();
            newResource.publicIpMax = count;
            newResource.publicIpTerminablyUsed = 0;
            newResource.cloudId = cloudId;
            newResource.time = targetDate;
            toBeInsertList.add(newResource);
        } else {
            //
            oldResource.publicIpMax = count;
            toBeUpdateList.add(oldResource);
        }
        targetDate = TimestampUtil.add(targetDate, 1, TimestampUtil.Unit.DAY);
    }
    //??
    if (toBeInsertList.size() > 0) {
        jdbcManager.insertBatch(toBeInsertList).execute();
    }
    //??
    if (toBeUpdateList.size() > 0) {
        jdbcManager.updateBatch(toBeUpdateList).execute();
    }
}