Example usage for java.util Date compareTo

List of usage examples for java.util Date compareTo

Introduction

In this page you can find the example usage for java.util Date compareTo.

Prototype

public int compareTo(Date anotherDate) 

Source Link

Document

Compares two Dates for ordering.

Usage

From source file:org.silverpeas.components.kmelia.service.DefaultKmeliaService.java

private Collection<PublicationDetail> filterPublicationsByBeginDate(Collection<PublicationDetail> publications,
        int nbDays) {
    List<PublicationDetail> pubOK = new ArrayList<>();
    if (publications != null) {
        Calendar rightNow = Calendar.getInstance();
        if (nbDays == 0) {
            nbDays = 1;/*from   www  . j  a v  a2s .  co m*/
        }
        rightNow.add(Calendar.DATE, 0 - nbDays);
        Date day = rightNow.getTime();
        Iterator<PublicationDetail> it = publications.iterator();
        PublicationDetail pub;
        Date dateToCompare;
        while (it.hasNext()) {
            pub = it.next();
            if (pub.getBeginDate() != null) {
                dateToCompare = pub.getBeginDate();
            } else {
                dateToCompare = pub.getCreationDate();
            }

            if (dateToCompare.compareTo(day) >= 0) {
                pubOK.add(pub);
            }
        }
    }
    return pubOK;
}

From source file:org.alfresco.solr.AlfrescoCoreAdminHandler.java

/**
 * @param cname// w  w  w  . j  a v  a2  s . com
 * @param detail
 * @param hist
 * @param values
 * @param srv
 * @param report
 * @throws IOException
 */
private void addCoreSummary(String cname, boolean detail, boolean hist, boolean values, InformationServer srv,
        NamedList<Object> report) throws IOException {
    NamedList<Object> coreSummary = new SimpleOrderedMap<Object>();
    coreSummary.addAll((SimpleOrderedMap<Object>) srv.getCoreStats());

    MetadataTracker metaTrkr = trackerRegistry.getTrackerForCore(cname, MetadataTracker.class);
    TrackerState metadataTrkrState = metaTrkr.getTrackerState();
    long lastIndexTxCommitTime = metadataTrkrState.getLastIndexedTxCommitTime();

    long lastIndexedTxId = metadataTrkrState.getLastIndexedTxId();
    long lastTxCommitTimeOnServer = metadataTrkrState.getLastTxCommitTimeOnServer();
    long lastTxIdOnServer = metadataTrkrState.getLastTxIdOnServer();
    Date lastIndexTxCommitDate = new Date(lastIndexTxCommitTime);
    Date lastTxOnServerDate = new Date(lastTxCommitTimeOnServer);
    long transactionsToDo = lastTxIdOnServer - lastIndexedTxId;
    if (transactionsToDo < 0) {
        transactionsToDo = 0;
    }

    AclTracker aclTrkr = trackerRegistry.getTrackerForCore(cname, AclTracker.class);
    TrackerState aclTrkrState = aclTrkr.getTrackerState();
    long lastIndexChangeSetCommitTime = aclTrkrState.getLastIndexedChangeSetCommitTime();
    long lastIndexedChangeSetId = aclTrkrState.getLastIndexedChangeSetId();
    long lastChangeSetCommitTimeOnServer = aclTrkrState.getLastChangeSetCommitTimeOnServer();
    long lastChangeSetIdOnServer = aclTrkrState.getLastChangeSetIdOnServer();
    Date lastIndexChangeSetCommitDate = new Date(lastIndexChangeSetCommitTime);
    Date lastChangeSetOnServerDate = new Date(lastChangeSetCommitTimeOnServer);
    long changeSetsToDo = lastChangeSetIdOnServer - lastIndexedChangeSetId;
    if (changeSetsToDo < 0) {
        changeSetsToDo = 0;
    }

    long nodesToDo = 0;
    long remainingTxTimeMillis = 0;
    if (transactionsToDo > 0) {
        // We now use the elapsed time as seen by the single thread farming out metadata indexing
        double meanDocsPerTx = srv.getTrackerStats().getMeanDocsPerTx();
        double meanNodeElaspedIndexTime = srv.getTrackerStats().getMeanNodeElapsedIndexTime();
        nodesToDo = (long) (transactionsToDo * meanDocsPerTx);
        remainingTxTimeMillis = (long) (nodesToDo * meanNodeElaspedIndexTime);
    }
    Date now = new Date();
    Date end = new Date(now.getTime() + remainingTxTimeMillis);
    Duration remainingTx = new Duration(now, end);

    long remainingChangeSetTimeMillis = 0;
    if (changeSetsToDo > 0) {
        // We now use the elapsed time as seen by the single thread farming out alc indexing
        double meanAclsPerChangeSet = srv.getTrackerStats().getMeanAclsPerChangeSet();
        double meanAclElapsedIndexTime = srv.getTrackerStats().getMeanAclElapsedIndexTime();
        remainingChangeSetTimeMillis = (long) (changeSetsToDo * meanAclsPerChangeSet * meanAclElapsedIndexTime);
    }
    now = new Date();
    end = new Date(now.getTime() + remainingChangeSetTimeMillis);
    Duration remainingChangeSet = new Duration(now, end);

    NamedList<Object> ftsSummary = new SimpleOrderedMap<Object>();
    long remainingContentTimeMillis = 0;
    srv.addFTSStatusCounts(ftsSummary);
    long cleanCount = ((Long) ftsSummary.get("Node count with FTSStatus Clean")).longValue();
    long dirtyCount = ((Long) ftsSummary.get("Node count with FTSStatus Dirty")).longValue();
    long newCount = ((Long) ftsSummary.get("Node count with FTSStatus New")).longValue();
    long nodesInIndex = ((Long) coreSummary.get("Alfresco Nodes in Index"));
    long contentYetToSee = nodesInIndex > 0 ? nodesToDo * (cleanCount + dirtyCount + newCount) / nodesInIndex
            : 0;
    ;
    if (dirtyCount + newCount + contentYetToSee > 0) {
        // We now use the elapsed time as seen by the single thread farming out alc indexing
        double meanContentElapsedIndexTime = srv.getTrackerStats().getMeanContentElapsedIndexTime();
        remainingContentTimeMillis = (long) ((dirtyCount + newCount + contentYetToSee)
                * meanContentElapsedIndexTime);
    }
    now = new Date();
    end = new Date(now.getTime() + remainingContentTimeMillis);
    Duration remainingContent = new Duration(now, end);
    coreSummary.add("FTS", ftsSummary);

    Duration txLag = new Duration(lastIndexTxCommitDate, lastTxOnServerDate);
    if (lastIndexTxCommitDate.compareTo(lastTxOnServerDate) > 0) {
        txLag = new Duration();
    }
    long txLagSeconds = (lastTxCommitTimeOnServer - lastIndexTxCommitTime) / 1000;
    if (txLagSeconds < 0) {
        txLagSeconds = 0;
    }

    Duration changeSetLag = new Duration(lastIndexChangeSetCommitDate, lastChangeSetOnServerDate);
    if (lastIndexChangeSetCommitDate.compareTo(lastChangeSetOnServerDate) > 0) {
        changeSetLag = new Duration();
    }
    long changeSetLagSeconds = (lastChangeSetCommitTimeOnServer - lastIndexChangeSetCommitTime) / 1000;
    if (txLagSeconds < 0) {
        txLagSeconds = 0;
    }

    ContentTracker contentTrkr = trackerRegistry.getTrackerForCore(cname, ContentTracker.class);
    TrackerState contentTrkrState = contentTrkr.getTrackerState();
    // Leave ModelTracker out of this check, because it is common
    boolean aTrackerIsRunning = aclTrkrState.isRunning() || metadataTrkrState.isRunning()
            || contentTrkrState.isRunning();
    coreSummary.add("Active", aTrackerIsRunning);

    ModelTracker modelTrkr = trackerRegistry.getModelTracker();
    TrackerState modelTrkrState = modelTrkr.getTrackerState();
    coreSummary.add("ModelTracker Active", modelTrkrState.isRunning());
    coreSummary.add("ContentTracker Active", contentTrkrState.isRunning());
    coreSummary.add("MetadataTracker Active", metadataTrkrState.isRunning());
    coreSummary.add("AclTracker Active", aclTrkrState.isRunning());

    // TX

    coreSummary.add("Last Index TX Commit Time", lastIndexTxCommitTime);
    coreSummary.add("Last Index TX Commit Date", lastIndexTxCommitDate);
    coreSummary.add("TX Lag", txLagSeconds + " s");
    coreSummary.add("TX Duration", txLag.toString());
    coreSummary.add("Timestamp for last TX on server", lastTxCommitTimeOnServer);
    coreSummary.add("Date for last TX on server", lastTxOnServerDate);
    coreSummary.add("Id for last TX on server", lastTxIdOnServer);
    coreSummary.add("Id for last TX in index", lastIndexedTxId);
    coreSummary.add("Approx transactions remaining", transactionsToDo);
    coreSummary.add("Approx transaction indexing time remaining",
            remainingTx.largestComponentformattedString());

    // Change set

    coreSummary.add("Last Index Change Set Commit Time", lastIndexChangeSetCommitTime);
    coreSummary.add("Last Index Change Set Commit Date", lastIndexChangeSetCommitDate);
    coreSummary.add("Change Set Lag", changeSetLagSeconds + " s");
    coreSummary.add("Change Set Duration", changeSetLag.toString());
    coreSummary.add("Timestamp for last Change Set on server", lastChangeSetCommitTimeOnServer);
    coreSummary.add("Date for last Change Set on server", lastChangeSetOnServerDate);
    coreSummary.add("Id for last Change Set on server", lastChangeSetIdOnServer);
    coreSummary.add("Id for last Change Set in index", lastIndexedChangeSetId);
    coreSummary.add("Approx change sets remaining", changeSetsToDo);
    coreSummary.add("Approx change set indexing time remaining",
            remainingChangeSet.largestComponentformattedString());

    coreSummary.add("Approx content indexing time remaining",
            remainingContent.largestComponentformattedString());

    // Stats

    coreSummary.add("Model sync times (ms)",
            srv.getTrackerStats().getModelTimes().getNamedList(detail, hist, values));
    coreSummary.add("Acl index time (ms)",
            srv.getTrackerStats().getAclTimes().getNamedList(detail, hist, values));
    coreSummary.add("Node index time (ms)",
            srv.getTrackerStats().getNodeTimes().getNamedList(detail, hist, values));
    coreSummary.add("Docs/Tx", srv.getTrackerStats().getTxDocs().getNamedList(detail, hist, values));
    coreSummary.add("Doc Transformation time (ms)",
            srv.getTrackerStats().getDocTransformationTimes().getNamedList(detail, hist, values));

    // Model

    Map<String, Set<String>> modelErrors = srv.getModelErrors();
    if (modelErrors.size() > 0) {
        NamedList<Object> errorList = new SimpleOrderedMap<Object>();
        for (Map.Entry<String, Set<String>> modelNameToErrors : modelErrors.entrySet()) {
            errorList.add(modelNameToErrors.getKey(), modelNameToErrors.getValue());
        }
        coreSummary.add(
                "Model changes are not compatible with the existing data model and have not been applied",
                errorList);
    }

    report.add(cname, coreSummary);
}

From source file:com.tasktop.c2c.server.tasks.tests.service.TaskServiceTest.java

License:asdf

@Test
public void createTask_withWorkLog() throws Exception {
    com.tasktop.c2c.server.tasks.domain.Task mockTask = getMockTask();
    WorkLog worklog = new WorkLog();
    worklog.setProfile(ProfileConverter.copy(currentUser));
    Date now = new Date();
    worklog.setDateWorked(now);/*from   ww  w.jav  a 2s.c  o m*/
    worklog.setHoursWorked(new BigDecimal(1.0));
    mockTask.getWorkLogs().add(worklog);
    com.tasktop.c2c.server.tasks.domain.Task createdTask = taskService.createTask(mockTask);

    assertEquals(1, createdTask.getWorkLogs().size());
    assertEquals(BigDecimal.ONE, createdTask.getWorkLogs().get(0).getHoursWorked());

    // the date that is stored is set by the client, not the server
    assertEquals(0, now.compareTo(createdTask.getWorkLogs().get(0).getDateWorked()));
}

From source file:com.stratelia.webactiv.kmelia.control.ejb.KmeliaBmEJB.java

private Collection<PublicationDetail> filterPublicationsByBeginDate(Collection<PublicationDetail> publications,
        int nbDays) {
    List<PublicationDetail> pubOK = new ArrayList<PublicationDetail>();
    if (publications != null) {
        Calendar rightNow = Calendar.getInstance();
        if (nbDays == 0) {
            nbDays = 1;//from  ww w  .  ja  v a 2s  .  com
        }
        rightNow.add(Calendar.DATE, 0 - nbDays);
        Date day = rightNow.getTime();
        Iterator<PublicationDetail> it = publications.iterator();
        PublicationDetail pub;
        Date dateToCompare;
        while (it.hasNext()) {
            pub = it.next();
            if (pub.getBeginDate() != null) {
                dateToCompare = pub.getBeginDate();
            } else {
                dateToCompare = pub.getCreationDate();
            }

            if (dateToCompare.compareTo(day) >= 0) {
                pubOK.add(pub);
            }
        }
    }
    return pubOK;
}

From source file:com.neusoft.mid.clwapi.service.pushRule.PushRuleServiceImpl.java

/**
 * ???//from  ww w  . ja v  a2s . c  om
 * 
 * @param token
 *            
 * @param eTag
 *            ?
 * @return ?
 */
@Override
public Object getRule(String token, String eTag) {
    // ??
    boolean checkEtag = true;
    // ?ID
    String usrId = context.getHttpHeaders().getHeaderString("usr_id");
    String enId = context.getHttpHeaders().getHeaderString("enterprise_id");
    String plaETag = context.getHttpHeaders().getHeaderString("rule_ETag");
    logger.info("???[" + usrId + "]?");
    logger.info("?ETag:" + eTag);
    logger.info("??ETag:" + plaETag);

    if (eTag == null) {
        logger.error("If-None-Match");
        throw new ApplicationException(ErrorConstant.ERROR10001, Response.Status.BAD_REQUEST);
    }

    // ?
    Date dateTer = null;
    // ??
    Date datePla = null;

    // 
    if (!eTag.equals("0")) {
        try {
            dateTer = BeanUtil.checkTimeForm(eTag, HttpConstant.TIME_FORMAT);
        } catch (ParseException e) {
            logger.error("??" + e.getMessage());
            throw new ApplicationException(ErrorConstant.ERROR10002, Response.Status.BAD_REQUEST);
        }
        // ??
        try {
            datePla = BeanUtil.checkTimeForm(plaETag, HttpConstant.TIME_FORMAT);
        } catch (ParseException e) {
            logger.error("???" + e.getMessage());
            throw new ApplicationException(ErrorConstant.ERROR90000, Response.Status.INTERNAL_SERVER_ERROR);
        }
    } else {
        // ???
        checkEtag = false;
    }

    logger.info("??");
    // ??
    List<PushRuleInfo> list = iPushRuleMapper.getPushRules(usrId, enId);
    logger.info("???");
    logger.debug("list = " + (list == null ? "NULL" : list.size()));

    // ?
    if (list == null || list.size() == 0) {

        logger.info("?????");
        // ??
        List<PushRuleInfo> enList = iPushRuleMapper
                .getEnterpriseRule(context.getHttpHeaders().getHeaderString("enterprise_id"));
        // ???
        if (enList == null || enList.size() == 0) {
            logger.error("??");
            throw new ApplicationException(ErrorConstant.ERROR10104, Response.Status.NOT_FOUND);
        }
        logger.info("??");

        // ?UUID
        String[] uuids = BeanUtil.getUUIDs(enList.size());

        // ????
        Iterator<PushRuleInfo> it = enList.iterator();
        logger.info("??");
        int i = 0;
        // 
        List<PushRuleInfo> temp = new ArrayList<PushRuleInfo>();
        while (it.hasNext()) {
            PushRuleInfo iPushRuleInfo = it.next();
            // ?
            iPushRuleInfo.setUsrId(usrId);
            iPushRuleInfo.setRuleId(uuids[i++]);
            temp.add(iPushRuleInfo);
        }

        logger.debug("???:");
        if (logger.isDebugEnabled()) {
            it = temp.iterator();
            while (it.hasNext()) {
                PushRuleInfo iPushRuleInfo = it.next();
                logger.debug(iPushRuleInfo.toString());
            }
        }

        // ???
        iPushRuleMapper.insertPersonalRule(temp);

        // ???
        list = iPushRuleMapper.getPushRules(usrId, enId);
        if (list == null || list.size() == 0) {
            logger.error("??");
            throw new ApplicationException(ErrorConstant.ERROR10010, Response.Status.NOT_FOUND);
        }
        logger.info("?");
        plaETag = list.get(0).getOperateTime();
        logger.debug("??" + plaETag);
        // ??
        upUserETag(token, usrId, plaETag);
        logger.info("???");
    } else {
        logger.debug("?");
        if (logger.isDebugEnabled()) {
            Iterator<PushRuleInfo> it = list.iterator();
            int i = 0;
            while (it.hasNext()) {
                PushRuleInfo iPushRuleInfo = it.next();
                logger.debug(++i + iPushRuleInfo.toString());
            }
        }
        // ??
        String e = list.get(0).getOperateTime();
        logger.info("????");
        logger.debug("???" + e);
        logger.debug("??" + plaETag);
        // ?
        if (!StringUtils.equals(e, plaETag)) {
            logger.info("?");
            // ??ETag
            upUserETag(token, usrId, e);
            plaETag = e;
        }
    }

    logger.info("???");

    // ?
    if ((list == null || list.size() == 0) && !plaETag.equals("0")) {
        logger.info("??");
        return Response.noContent().build();
    } else if (checkEtag && dateTer.compareTo(datePla) == 0) {
        // ??
        logger.info("???");
        return Response.notModified().build();
    } else if (checkEtag && dateTer.compareTo(datePla) > 0) {
        logger.error("???");
        throw new ApplicationException(ErrorConstant.ERROR10103, Response.Status.BAD_REQUEST);
    }

    // ?
    PushRuleResp iPushRuleResp = new PushRuleResp();
    iPushRuleResp.seteTag(plaETag);
    iPushRuleResp.setRuleContent(list);
    return JacksonUtils.toJsonRuntimeException(iPushRuleResp);
}

From source file:com.vkassin.mtrade.Common.java

public static void putOrder(final Context ctx, Quote quote) {

    final Instrument it = Common.selectedInstrument;// adapter.getItem(selectedRowId);

    final Dialog dialog = new Dialog(ctx);
    dialog.setContentView(R.layout.order_dialog);
    dialog.setTitle(R.string.OrderDialogTitle);

    datetxt = (EditText) dialog.findViewById(R.id.expdateedit);
    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
    Date dat1 = new Date();
    datetxt.setText(sdf.format(dat1));/*from ww  w  .  j  ava2s.  c o  m*/
    mYear = dat1.getYear() + 1900;
    mMonth = dat1.getMonth();
    mDay = dat1.getDate();
    final Date dat = new GregorianCalendar(mYear, mMonth, mDay).getTime();

    datetxt.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.i(TAG, "Show DatePickerDialog");
            DatePickerDialog dpd = new DatePickerDialog(ctx, mDateSetListener, mYear, mMonth, mDay);
            dpd.show();
        }
    });

    TextView itext = (TextView) dialog.findViewById(R.id.instrtext);
    itext.setText(it.symbol);

    final Spinner aspinner = (Spinner) dialog.findViewById(R.id.acc_spinner);
    List<String> list = new ArrayList<String>(Common.getAccountList());
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(Common.app_ctx,
            android.R.layout.simple_spinner_item, list);
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
    aspinner.setAdapter(dataAdapter);

    final EditText pricetxt = (EditText) dialog.findViewById(R.id.priceedit);
    final EditText quanttxt = (EditText) dialog.findViewById(R.id.quantedit);

    final Button buttonpm = (Button) dialog.findViewById(R.id.buttonPriceMinus);
    buttonpm.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            try {

                double price = Double.valueOf(pricetxt.getText().toString());
                price -= 0.01;
                if (price < 0)
                    price = 0;
                pricetxt.setText(twoDForm.format(price));

            } catch (Exception e) {

                Toast.makeText(ctx, R.string.CorrectPrice, Toast.LENGTH_SHORT).show();
            }
        }
    });

    final Button buttonpp = (Button) dialog.findViewById(R.id.buttonPricePlus);
    buttonpp.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            try {

                double price = Double.valueOf(pricetxt.getText().toString());
                price += 0.01;
                pricetxt.setText(twoDForm.format(price));

            } catch (Exception e) {

                Toast.makeText(ctx, R.string.CorrectPrice, Toast.LENGTH_SHORT).show();
            }
        }
    });

    final Button buttonqm = (Button) dialog.findViewById(R.id.buttonQtyMinus);
    buttonqm.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            try {

                long qty = Long.valueOf(quanttxt.getText().toString());
                qty -= 1;
                if (qty < 0)
                    qty = 0;
                quanttxt.setText(String.valueOf(qty));

            } catch (Exception e) {

                Toast.makeText(ctx, R.string.CorrectQty, Toast.LENGTH_SHORT).show();
            }
        }
    });

    final Button buttonqp = (Button) dialog.findViewById(R.id.buttonQtyPlus);
    buttonqp.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            try {

                long qty = Long.valueOf(quanttxt.getText().toString());
                qty += 1;
                quanttxt.setText(String.valueOf(qty));

            } catch (Exception e) {

                Toast.makeText(ctx, R.string.CorrectQty, Toast.LENGTH_SHORT).show();
            }
        }
    });

    final RadioButton bu0 = (RadioButton) dialog.findViewById(R.id.radio0);
    final RadioButton bu1 = (RadioButton) dialog.findViewById(R.id.radio1);

    if (quote != null) {

        // pricetxt.setText(quote.price.toString());
        pricetxt.setText(quote.getPriceS());
        if (quote.qtyBuy > 0) {

            quanttxt.setText(quote.qtyBuy.toString());
            bu1.setChecked(true);
            bu0.setChecked(false);

        } else {

            quanttxt.setText(quote.qtySell.toString());
            bu1.setChecked(false);
            bu0.setChecked(true);

        }
    }

    Button customDialog_Cancel = (Button) dialog.findViewById(R.id.cancelbutt);
    customDialog_Cancel.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View arg0) {

            dialog.dismiss();
        }

    });

    Button customDialog_Put = (Button) dialog.findViewById(R.id.putorder);
    customDialog_Put.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View arg0) {

            Double price = new Double(0);
            Long qval = new Long(0);

            try {

                price = Double.valueOf(pricetxt.getText().toString());
            } catch (Exception e) {

                Toast.makeText(ctx, R.string.CorrectPrice, Toast.LENGTH_SHORT).show();
                return;
            }
            try {

                qval = Long.valueOf(quanttxt.getText().toString());
            } catch (Exception e) {

                Toast.makeText(ctx, R.string.CorrectQty, Toast.LENGTH_SHORT).show();
                return;
            }

            if (dat.compareTo(new GregorianCalendar(mYear, mMonth, mDay).getTime()) > 0) {

                Toast.makeText(ctx, R.string.CorrectDate, Toast.LENGTH_SHORT).show();

                return;

            }

            JSONObject msg = new JSONObject();
            try {

                msg.put("objType", Common.CREATE_REMOVE_ORDER);
                msg.put("time", Calendar.getInstance().getTimeInMillis());
                msg.put("version", Common.PROTOCOL_VERSION);
                msg.put("device", "Android");
                msg.put("instrumId", Long.valueOf(it.id));
                msg.put("price", price);
                msg.put("qty", qval);
                msg.put("ordType", 1);
                msg.put("side", bu0.isChecked() ? 0 : 1);
                msg.put("code", String.valueOf(aspinner.getSelectedItem()));
                msg.put("orderNum", ++ordernum);
                msg.put("action", "CREATE");
                boolean b = (((mYear - 1900) == dat.getYear()) && (mMonth == dat.getMonth())
                        && (mDay == dat.getDate()));
                if (!b)
                    msg.put("expired", String.format("%02d.%02d.%04d", mDay, mMonth + 1, mYear));

                if (isSSL) {

                    //                ? ?:    newOrder-orderNum-instrumId-side-price-qty-code-ordType
                    //               :                  newOrder-16807-20594623-0-1150-13-1027700451-1
                    String forsign = "newOrder-" + ordernum + "-" + msg.getString("instrumId") + "-"
                            + msg.getString("side") + "-"
                            + JSONObject.numberToString(Double.valueOf(msg.getDouble("price"))) + "-"
                            + msg.getString("qty") + "-" + msg.getString("code") + "-"
                            + msg.getString("ordType");
                    byte[] signed = Common.signText(Common.signProfile, forsign.getBytes(), true);
                    String gsign = Base64.encodeToString(signed, Base64.DEFAULT);
                    msg.put("gostSign", gsign);
                }
                mainActivity.writeJSONMsg(msg);

            } catch (Exception e) {

                e.printStackTrace();
                Log.e(TAG, "Error! Cannot create JSON order object", e);
            }

            dialog.dismiss();
        }

    });

    dialog.show();

    WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
    lp.copyFrom(dialog.getWindow().getAttributes());
    lp.width = WindowManager.LayoutParams.FILL_PARENT;
    lp.height = WindowManager.LayoutParams.FILL_PARENT;
    dialog.getWindow().setAttributes(lp);

}

From source file:cn.apputest.ctria.sql.DBManager.java

public CarBasicInfoDataEntity queryTheCursorCarBasicInfo(String plateNumber, String plateNumber_gua) {
    // System.out.println("query database");
    DateFormat newdate = new DateFormat();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Date dateTime1 = null;
    try {//from  w  ww .  j  a v  a2s.co m
        dateTime1 = dateFormat.parse(newdate.getDate3());
    } catch (ParseException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    CarBasicInfoDataEntity carbasicinfo = new CarBasicInfoDataEntity();
    Cursor maxweight_c = db.rawQuery(
            "SELECT SUM_QUALITY FROM or_car where PLATE_NUMBER='" + plateNumber + "' COLLATE NOCASE", null);
    Cursor traction_quality_c = db.rawQuery(
            "SELECT TRACTION_QUALITY FROM or_car where PLATE_NUMBER='" + plateNumber + "' COLLATE NOCASE",
            null);
    Cursor check_quality_c = db.rawQuery(
            "SELECT CHECK_QUALITY FROM or_car where PLATE_NUMBER='" + plateNumber + "' COLLATE NOCASE", null);
    Cursor check_quality_tail_c = db.rawQuery(
            "SELECT CHECK_QUALITY FROM or_car where PLATE_NUMBER='" + plateNumber_gua + "' COLLATE NOCASE",
            null);
    Cursor maxweight_tail_c = db.rawQuery(
            "SELECT SUM_QUALITY FROM or_car where PLATE_NUMBER='" + plateNumber_gua + "' COLLATE NOCASE", null);
    Cursor reorgannize_quality_c = db.rawQuery(
            "SELECT REORGANIZE_QUALITY FROM or_car where PLATE_NUMBER='" + plateNumber + "' COLLATE NOCASE",
            null);
    Cursor permitcard_c = db.rawQuery("SELECT EXPIRE_DATE FROM or_permit_run_cert where PLATE_NUMBER='"
            + plateNumber + "' COLLATE NOCASE", null);
    Cursor transportCardHead_c = db.rawQuery(
            "SELECT EXPIRE_DATE FROM or_transport_cert where PLATE_NUMBER='" + plateNumber + "' COLLATE NOCASE",
            null);
    Cursor transportCardTail_c = db.rawQuery("SELECT EXPIRE_DATE FROM or_transport_cert where PLATE_NUMBER='"
            + plateNumber_gua + "' COLLATE NOCASE", null);
    Cursor insuranceHead_c = db.rawQuery(
            "SELECT INSURANCE_DATE FROM or_car_insurance where CAR_NUMBER='" + plateNumber + "' COLLATE NOCASE",
            null);
    Cursor insuranceTail_c = db.rawQuery("SELECT INSURANCE_DATE FROM or_car_insurance where CAR_NUMBER='"
            + plateNumber_gua + "' COLLATE NOCASE", null);
    Cursor insuranceCargo_c = db
            .rawQuery("SELECT INSURANCE_TIME FROM or_carrier_warranty where LICENSE_NUMBER='" + plateNumber_gua
                    + "' COLLATE NOCASE", null);
    Cursor specialequipusage_c = db
            .rawQuery("SELECT NEXT_CHECKOUT_DATE FROM or_special_equipment where CAR_NUMBER='" + plateNumber_gua
                    + "' COLLATE NOCASE", null);
    carbasicinfo.setMaxweight(0);
    carbasicinfo.setTraction_quality(0);
    carbasicinfo.setCheck_quality(0);
    carbasicinfo.setReorganize_quality(0);
    carbasicinfo.setCheck_quality_tail(0);
    carbasicinfo.setMaxweight_tail(0);
    carbasicinfo.setStatus4InsuranceCertCargo(-1);
    carbasicinfo.setStatus4InsuranceCertHead(-1);
    carbasicinfo.setStatus4InsuranceCertTail(-1);
    carbasicinfo.setStatus4PermitRunCert(-1);
    carbasicinfo.setStatus4SEquipCheck(-1);
    carbasicinfo.setStatus4TransportCertHead(-1);
    carbasicinfo.setStatus4TransportCertTail(-1);
    while (maxweight_c.moveToNext()) {
        double a = maxweight_c.getDouble(maxweight_c.getColumnIndex("SUM_QUALITY"));
        carbasicinfo.setMaxweight(a);
    }
    maxweight_c.close();

    while (maxweight_tail_c.moveToNext()) {
        double a = maxweight_tail_c.getDouble(maxweight_tail_c.getColumnIndex("SUM_QUALITY"));
        carbasicinfo.setMaxweight_tail(a);
    }
    maxweight_tail_c.close();

    while (check_quality_tail_c.moveToNext()) {
        double a = check_quality_tail_c.getDouble(check_quality_tail_c.getColumnIndex("CHECK_QUALITY"));
        carbasicinfo.setCheck_quality_tail(a);
    }
    check_quality_tail_c.close();

    while (traction_quality_c.moveToNext()) {
        double a = traction_quality_c.getDouble(traction_quality_c.getColumnIndex("TRACTION_QUALITY"));
        carbasicinfo.setTraction_quality(a);
    }
    traction_quality_c.close();
    while (check_quality_c.moveToNext()) {
        double a = check_quality_c.getDouble(check_quality_c.getColumnIndex("CHECK_QUALITY"));
        carbasicinfo.setCheck_quality(a);
    }
    check_quality_c.close();
    while (reorgannize_quality_c.moveToNext()) {
        double a = reorgannize_quality_c.getDouble(reorgannize_quality_c.getColumnIndex("REORGANIZE_QUALITY"));
        carbasicinfo.setReorganize_quality(a);
    }
    reorgannize_quality_c.close();

    while (permitcard_c.moveToNext()) {
        String endTime = permitcard_c.getString(permitcard_c.getColumnIndex("EXPIRE_DATE"));
        if (!StringUtils.isNotBlank(endTime)) {
            carbasicinfo.setStatus4PermitRunCert(-1);
        } else {
            Date dateTime2 = null;
            try {
                dateTime2 = dateFormat.parse(endTime);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            int i = dateTime1.compareTo(dateTime2);
            if (i > 0) {
                carbasicinfo.setStatus4PermitRunCert(1);
            } else {
                carbasicinfo.setStatus4PermitRunCert(0);
            }
        }

    }
    permitcard_c.close();
    while (transportCardHead_c.moveToNext()) {
        String endTime = transportCardHead_c.getString(transportCardHead_c.getColumnIndex("EXPIRE_DATE"));
        if (!StringUtils.isNotBlank(endTime)) {
            carbasicinfo.setStatus4TransportCertHead(-1);
        } else {
            Date dateTime2 = null;
            try {
                dateTime2 = dateFormat.parse(endTime);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            int i = dateTime1.compareTo(dateTime2);
            if (i > 0) {
                carbasicinfo.setStatus4TransportCertHead(1);
            } else {
                carbasicinfo.setStatus4TransportCertHead(0);
            }
        }
    }
    transportCardHead_c.close();
    while (transportCardTail_c.moveToNext()) {
        String endTime = transportCardTail_c.getString(transportCardTail_c.getColumnIndex("EXPIRE_DATE"));
        if (!StringUtils.isNotBlank(endTime)) {
            carbasicinfo.setStatus4TransportCertTail(-1);
        } else {
            Date dateTime2 = null;
            try {
                dateTime2 = dateFormat.parse(endTime);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            int i = dateTime1.compareTo(dateTime2);
            if (i > 0) {
                carbasicinfo.setStatus4TransportCertTail(1);
            } else {
                carbasicinfo.setStatus4TransportCertTail(0);
            }
        }
    }
    transportCardTail_c.close();
    while (insuranceHead_c.moveToNext()) {
        String endTime = insuranceHead_c.getString(insuranceHead_c.getColumnIndex("INSURANCE_DATE"));
        if (StringUtils.isNotBlank(endTime)) {
            String a[] = endTime.split(",");
            endTime = a[1];
        }
        if (!StringUtils.isNotBlank(endTime)) {
            carbasicinfo.setStatus4InsuranceCertHead(-1);
        } else {
            Date dateTime2 = null;
            try {
                dateTime2 = dateFormat.parse(endTime);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            int i = dateTime1.compareTo(dateTime2);
            if (i > 0) {
                carbasicinfo.setStatus4InsuranceCertHead(1);
            } else {
                carbasicinfo.setStatus4InsuranceCertHead(0);
            }
        }
    }
    insuranceHead_c.close();
    while (insuranceTail_c.moveToNext()) {
        String endTime = insuranceTail_c.getString(insuranceTail_c.getColumnIndex("INSURANCE_DATE"));
        if (StringUtils.isNotBlank(endTime)) {
            String a[] = endTime.split(",");
            endTime = a[1];
        }
        if (!StringUtils.isNotBlank(endTime)) {
            carbasicinfo.setStatus4InsuranceCertTail(-1);
        } else {
            Date dateTime2 = null;
            try {
                dateTime2 = dateFormat.parse(endTime);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            int i = dateTime1.compareTo(dateTime2);
            if (i > 0) {
                carbasicinfo.setStatus4InsuranceCertTail(1);
            } else {
                carbasicinfo.setStatus4InsuranceCertTail(0);
            }
        }
    }
    insuranceTail_c.close();
    while (insuranceCargo_c.moveToNext()) {
        String endTime = insuranceCargo_c.getString(insuranceCargo_c.getColumnIndex("INSURANCE_TIME"));

        if (StringUtils.isNotBlank(endTime)) {
            String a[] = endTime.split(",");
            endTime = a[1];
        }
        if (!StringUtils.isNotBlank(endTime)) {
            carbasicinfo.setStatus4InsuranceCertCargo(-1);
        } else {
            Date dateTime2 = null;
            try {
                dateTime2 = dateFormat.parse(endTime);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            int i = dateTime1.compareTo(dateTime2);
            if (i > 0) {
                carbasicinfo.setStatus4InsuranceCertCargo(1);
            } else {
                carbasicinfo.setStatus4InsuranceCertCargo(0);
            }
        }
    }
    insuranceCargo_c.close();
    while (specialequipusage_c.moveToNext()) {
        String endTime = specialequipusage_c
                .getString(specialequipusage_c.getColumnIndex("NEXT_CHECKOUT_DATE"));
        if (!StringUtils.isNotBlank(endTime)) {
            carbasicinfo.setStatus4SEquipCheck(-1);
        } else {
            Date dateTime2 = null;
            try {
                dateTime2 = dateFormat.parse(endTime);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            int i = dateTime1.compareTo(dateTime2);
            if (i > 0) {
                carbasicinfo.setStatus4SEquipCheck(1);
            } else {
                carbasicinfo.setStatus4SEquipCheck(0);
            }
        }
    }
    specialequipusage_c.close();

    return carbasicinfo;
}

From source file:com.openbravo.pos.sales.JRetailPanelTicket.java

public boolean deactivate() {
    int i = 0;/*from  w w  w .  j  a  va2 s . c o m*/
    if (m_oTicket != null) {
        try {
            String currentUpdated = m_dateformat.format(m_oTicket.getObjectUpdateDate()) + " "
                    + m_dateformattime.format(m_oTicket.getObjectUpdateDate());
            String dbUpdated = dlReceipts.getUpdatedTime(m_oTicket.getPlaceId(), m_oTicket.getSplitSharedId());
            Date currentUpdatedDate = DateFormats.StringToDateTime(currentUpdated);
            Date dbUpdatedDate = DateFormats.StringToDateTime(dbUpdated);
            if (dbUpdated.equals(null) || dbUpdated.equals("")) {
                showMessage(this, "This Bill is no longer exist");
                logger.info("This Bill is no longer exist");
            } else if (dbUpdatedDate.compareTo(currentUpdatedDate) > 0) {
                logger.info("The Table is being accessed by another User!Cannot update the bill");
                int iskds = dlReceipts.getKdsUpdateStatus(m_oTicket.getPlaceId(), m_oTicket.getSplitSharedId());
                if (iskds == 1) {
                    RetailTicketInfo ticket = dlReceipts.getRetailSharedTicketSplit(m_PlaceCurrent.getId(),
                            m_oTicket.getSplitSharedId());
                    if (ticket != null) {
                        ticket.setTicketOpen(false);
                        dlReceipts.updateSharedTicket(m_PlaceCurrent.getId(), ticket);
                    }
                }

                logger.info("The Table is being accessed by another User!Cannot update the bill");
                // showMessage(this, "The Table is being accessed by another User!Cannot update the bill");

            }
            System.out.println("within deactivate ");
            logger.info("within deactivate ");
            //if no kot done    
            if (m_oTicket.getOrderId() == 0) {
                try {
                    logger.info("Order No." + m_oTicket.getOrderId()
                            + "deleting 0 order no. Bill in deactivate method of " + m_oTicket.getTableName()
                            + " id is " + m_oTicket.getPlaceId());
                    dlReceipts.deleteSharedTicket(m_oTicket.getPlaceId());
                    m_ticketsbag.deleteTicket();
                } //if kot done but cancelled all lines
                catch (BasicException ex) {
                    Logger.getLogger(JRetailPanelTicket.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else if (m_oTicket.getOrderId() != 0 && m_oTicket.getLinesCount() == 0) {
                m_oTicket.setUser(m_App.getAppUserView().getUser().getUserInfo()); // El usuario que lo cobra
                m_oTicket.setActiveCash(m_App.getActiveCashIndex());
                m_oTicket.setActiveDay(m_App.getActiveDayIndex());
                m_oTicket.setDate(new Date()); //
                String ticketDocument;
                ticketDocument = m_App.getProperties().getStoreName() + "-" + m_App.getProperties().getPosNo()
                        + "-" + m_oTicket.getTicketId();
                String reason = "Splitted with zero lines/cancelled all kot lines";
                try {
                    dlSales.saveRetailCancelTicket(m_oTicket, m_App.getProperties().getStoreName(),
                            ticketDocument, "Y", m_App.getInventoryLocation(), reason, "",
                            m_App.getProperties().getPosNo(), "N");
                } catch (BasicException ex) {
                    logger.info("ORDER NO. " + m_oTicket.getOrderId()
                            + "exception in saveRetailCancelTicket in deactivate method" + ex.getMessage());
                    Logger.getLogger(JRetailPanelTicket.class.getName()).log(Level.SEVERE, null, ex);
                }
                if (m_oTicket.getSplitValue().equals("")) {
                    //     logger.info("Order No." + m_oTicket.getOrderId() + "deleting cancelled kot bill in deactivate method");
                    m_ticketsbag.deleteTicket();
                }
                //                else {
                //                    try {
                //                        logger.info("Order No." + m_oTicket.getOrderId() + "deleting cancelled kot splitted Bill in deactivate method");
                //                        dlReceipts.deleteSharedSplitTicket(m_oTicket.getPlaceId(), m_oTicket.getSplitSharedId());
                //                    } catch (BasicException ex) {
                //                        logger.info("ORDER NO. " + m_oTicket.getOrderId() + "exception in deleteSharedSplitTicket in deactivate method" + ex.getMessage());
                //                        Logger.getLogger(JRetailPanelTicket.class.getName()).log(Level.SEVERE, null, ex);
                //                    }
                //                }
            } //delete all non kot items
            else {
                //    if(IsSteward==0){
                while (i < m_oTicket.getLinesCount()) {
                    if (m_oTicket.getLine(i).getIsKot() == 0) {
                        removeTicketLine(i);
                        i = 0;
                    } else {
                        i++;
                    }
                }
                m_oTicket.refreshTxtFields(0);
                if (m_oTicket.getLinesCount() == 0) {
                    logger.info("Order No." + m_oTicket.getOrderId()
                            + "deleting zero lines Bill in deactivate method");
                    if (m_oTicket.getOrderId() != 0) {
                        m_oTicket.setUser(m_App.getAppUserView().getUser().getUserInfo()); // El usuario que lo cobra
                        m_oTicket.setActiveCash(m_App.getActiveCashIndex());
                        m_oTicket.setActiveDay(m_App.getActiveDayIndex());
                        m_oTicket.setDate(new Date()); //
                        String ticketDocument;
                        ticketDocument = m_App.getProperties().getStoreName() + "-"
                                + m_App.getProperties().getPosNo() + "-" + m_oTicket.getTicketId();
                        String reason = "cancelled all kot lines";
                        try {
                            dlSales.saveRetailCancelTicket(m_oTicket, m_App.getProperties().getStoreName(),
                                    ticketDocument, "Y", m_App.getInventoryLocation(), reason, "",
                                    m_App.getProperties().getPosNo(), "N");
                        } catch (BasicException ex) {
                            logger.info("newTicket saveRetailCancelTicket exception 2" + ex.getMessage() + ";");
                            Logger.getLogger(JRetailPanelTicket.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    m_ticketsbag.deleteTicket();
                }

            }
        } catch (BasicException ex) {
            Logger.getLogger(JRetailPanelTicket.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    RefreshTicketTimer.stop();
    return m_ticketsbag.deactivate();
}

From source file:com.openbravo.pos.sales.JRetailPanelTicket.java

private void m_jSettleBillActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jSettleBillActionPerformed

    logger.info("m_jSettleBillActionPerformed");
    logger.info(/*from  ww w  .  ja  v  a 2  s .co m*/
            "Start Settle Bill Button :" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").format(new Date()));
    //Below code is used for closing the day automatically if the application is not closed yesterday
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date sysDate = new Date();
    m_RootApp = (JRootApp) m_App;
    String closeTime = m_App.getProperties().getProperty("machine.closetime");
    String currentDate = format.format(sysDate).toString() + " " + closeTime;
    String closeDayDate = sdf.format(m_RootApp.getActiveDayDateStart());
    Date closeDate = null;
    Date activeDayDate = null;
    try {
        closeDate = sdf.parse(currentDate);
        activeDayDate = sdf.parse(closeDayDate);
    } catch (ParseException ex) {
        Logger.getLogger(JRetailPanelTicket.class.getName()).log(Level.SEVERE, null, ex);
    }
    //Comparing the actual close day date and current active close day date. if its greater than 0, then close the day automatically
    if (closeDate.compareTo(activeDayDate) > 0) {
        m_RootApp.closeDay();
        m_oTicket.setActiveCash(m_App.getActiveCashIndex());
        m_oTicket.setActiveDay(m_App.getActiveDayIndex());
        m_oTicket.setDate(new Date());
        String accDate = new SimpleDateFormat("yyyy-MM-dd").format(m_App.getActiveDayDateStart());
        Date dateValue = java.sql.Date.valueOf(accDate);
        m_oTicket.setAccountDate(dateValue);
    }
    if (m_oTicket.getLinesCount() == 0) {
        return;
    }
    boolean updated = checkTicketUpdation();
    if (!updated) {
        dbUpdatedDate = null;
        //Checking whether non kot items is there in the bill
        if (kotaction == 1) {
            try {
                kotDisplay();
            } catch (BasicException ex) {
                logger.info("Order NO." + m_oTicket.getOrderId()
                        + "exception on clicking settle bill kot action" + ex.getMessage());
                Logger.getLogger(JRetailPanelTicket.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        //Checking whether the bill is printed
        if (!m_oTicket.isPrinted()) {
            showMessage(this, "Settle bill is allowed after Bill is Printed");
            logger.info("Settle bill is allowed after Bill is Printed");
            return;
            //Checking whether bill is modified after the print
        } else if (m_oTicket.isPrinted() && m_oTicket.isListModified()) {
            showMessage(this, "Bill is Modified after previous print. So please print it again");
            logger.info("Bill is Modified after previous print. So please print it again");
            return;
        }
        JPaymentEditor.showMessage(JRetailPanelTicket.this, dlReceipts, m_oTicket, this, "Sales");
    }
}