Example usage for java.util Date after

List of usage examples for java.util Date after

Introduction

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

Prototype

public boolean after(Date when) 

Source Link

Document

Tests if this date is after the specified date.

Usage

From source file:hydrograph.ui.propertywindow.widgets.utility.SchemaRowValidation.java

private boolean validateSchemaRangeForDate(GenerateRecordSchemaGridRow generateRecordSchemaGridRow) {

    Date rangeFromDate = null, rangeToDate = null;

    SimpleDateFormat formatter = new SimpleDateFormat(generateRecordSchemaGridRow.getDateFormat());

    if (StringUtils.isNotBlank(generateRecordSchemaGridRow.getRangeFrom())) {
        try {/*from www . ja  va  2  s .  c  o  m*/
            rangeFromDate = formatter.parse(generateRecordSchemaGridRow.getRangeFrom());
        } catch (ParseException e) {
            return true;
        }
    }

    if (StringUtils.isNotBlank(generateRecordSchemaGridRow.getRangeTo())) {
        try {
            rangeToDate = formatter.parse(generateRecordSchemaGridRow.getRangeTo());
        } catch (ParseException e) {
            return true;
        }
    }

    if (rangeFromDate != null && rangeToDate != null && rangeFromDate.after(rangeToDate)) {
        return true;
    }

    return false;

}

From source file:com.dell.asm.asmcore.asmmanager.app.rest.DeviceInventoryService.java

/**
 * @see com.dell.asm.asmcore.asmmanager.client.deviceinventory.IDeviceInventoryService#updateDeviceFirmware(com.dell.asm.asmcore.asmmanager.client.deviceinventory.FirmwareUpdateRequest)
 *///  w  w w .  ja  v  a2 s .  com
@Override
public Response updateDeviceFirmware(FirmwareUpdateRequest request) {

    // Assert the default repository, if set, is not in error state
    failIfDefaultRepositoryInError();

    if ("schedule".equals(request.getScheduleType())) {
        Date now = new Date();
        Date scheduleDate = request.getScheduleDate();
        if (scheduleDate == null || now.after(scheduleDate)) {
            logger.info("Requested schedule date of " + scheduleDate + " is before current date of " + now);
            throw new LocalizedWebApplicationException(Response.Status.BAD_REQUEST,
                    AsmManagerMessages.scheduleDateIsPast());
        }
    }

    try {
        IJobManager jm = JobManager.getInstance();
        List<String> ids = request.getIdList();

        if (ids != null)
            for (String id : ids) {
                DeploymentEntity deployment = null;
                ServiceTemplate serviceTemplate = null;
                // Set all device states to PENDING so that scheduled firmware jobs are reflected in deployment status.
                if (UpdateType.SERVICE.equals(request.getUpdateType())) {
                    deployment = deploymentDAO.getDeployment(id, DeploymentDAO.FIRMWARE_REPOSITORY_ENTITY);
                    if (deployment.getMarshalledTemplateData() != null) {
                        serviceTemplate = MarshalUtil.unmarshal(ServiceTemplate.class,
                                deployment.getMarshalledTemplateData());
                        if (serviceTemplate.getComponents() != null) {
                            for (ServiceTemplateComponent component : serviceTemplate.getComponents()) {
                                if (ServiceTemplateComponent.ServiceTemplateComponentType.SERVER
                                        .equals(component.getType())) {
                                    String refId;
                                    // Is this check necessary?  If so, why is it not used in FirmwareUpdateJob::getJobDevices() ?
                                    if (component.getAsmGUID() != null) {
                                        refId = component.getAsmGUID();
                                    } else {
                                        refId = component.getId();
                                    }
                                    deviceInventoryDAO.setDeviceState(refId, DeviceState.PENDING, false);
                                }
                            }
                        }
                    }
                } else {
                    deviceInventoryDAO.setDeviceState(id, DeviceState.PENDING, false);
                }
                // If there is no cluster we create a separate Job for each device in the deployment/Service
                // so that the jobs can run in parallel.  Cluster jobs need to be run sequentially.
                if (deployment != null && serviceTemplate != null
                        && !serviceTemplate.hasClusterComponentType()) {
                    if (serviceTemplate != null && serviceTemplate.getComponents() != null) {
                        boolean nextReboot = "nextreboot".equals(request.getScheduleType());
                        String firmwareId = null;
                        if (deployment != null && deployment.getFirmwareRepositoryEntity() != null
                                && deployment.getFirmwareRepositoryEntity().getId() != null) {
                            firmwareId = deployment.getFirmwareRepositoryEntity().getId();
                        }
                        // Get all the servers in the service and run a firmware update job for each.
                        String groupName = "FirmwareUpdate:" + deployment.getId();
                        for (ServiceTemplateComponent component : serviceTemplate.getComponents()) {
                            if (ServiceTemplateComponent.ServiceTemplateComponentType.SERVER
                                    .equals(component.getType())) {
                                String refId;
                                if (component.getAsmGUID() != null) {
                                    refId = component.getAsmGUID();
                                } else {
                                    refId = component.getId();
                                }
                                JobDetail job = FirmwareUtil.getUpdateFirmwareJob(jm, refId,
                                        request.isExitMaintenanceMode(), nextReboot,
                                        FirmwareUpdateJob.UPDATE_TYPE_DEVICE, null, firmwareId, groupName);
                                job.getJobDataMap().put(FirmwareUpdateJob.DEPLOYMENT_STATE_KEY,
                                        deployment.getStatus().getValue());
                                createAndStartTrigger(jm, job, request);
                            }
                        }
                    }
                } else {
                    // Individual devices or service with cluster
                    String firmwareId = null;
                    if (deployment != null && deployment.getFirmwareRepositoryEntity() != null
                            && deployment.getFirmwareRepositoryEntity().getId() != null) {
                        firmwareId = deployment.getFirmwareRepositoryEntity().getId();
                    }
                    JobDetail job = FirmwareUtil.getUpdateFirmwareJob(jm, id, request.isExitMaintenanceMode(),
                            "nextreboot".equals(request.getScheduleType()),
                            UpdateType.SERVICE.equals(request.getUpdateType())
                                    ? FirmwareUpdateJob.UPDATE_TYPE_SERVICE
                                    : FirmwareUpdateJob.UPDATE_TYPE_DEVICE,
                            null, firmwareId);

                    if (deployment != null) {
                        job.getJobDataMap().put(FirmwareUpdateJob.DEPLOYMENT_STATE_KEY,
                                deployment.getStatus().getValue());
                    }
                    createAndStartTrigger(jm, job, request);
                }
            }
        return Response.status(Response.Status.NO_CONTENT).build();
    } catch (Exception e) {
        logger.error("Exception while updating inventory", e);
        throw new LocalizedWebApplicationException(Response.Status.INTERNAL_SERVER_ERROR,
                AsmManagerMessages.internalError());
    }
}

From source file:com.emc.vipr.sync.target.AtmosTarget.java

/**
 * If the target exists, we perform some checks and update only what
 * needs to be updated (metadata and/or content)
 *//*from   w  w  w.  j av  a  2 s.  co  m*/
private void checkUpdate(final SyncObject obj, final ObjectIdentifier destId, ObjectMetadata destMeta)
        throws IOException {
    SyncMetadata meta = obj.getMetadata();
    // Exists.  Check timestamps
    Date srcMtime = meta.getModificationTime();
    Date dstMtime = parseDate(destMeta.getMetadata().get("mtime"));
    Date srcCtime = getCTime(meta);
    if (srcCtime == null)
        srcCtime = srcMtime;
    Date dstCtime = parseDate(destMeta.getMetadata().get("ctime"));
    if ((srcMtime != null && dstMtime != null && srcMtime.after(dstMtime)) || force) {
        if (noUpdate) {
            LogMF.debug(l4j, "Skipping {0}, updates disabled.", obj.getSourceIdentifier(),
                    obj.getTargetIdentifier());
            return;
        }
        // Update the object
        InputStream in = null;
        try {
            in = obj.getInputStream();
            if (in == null) {
                // Metadata only
                final Map<String, Metadata> metaMap = AtmosUtil.getAtmosUserMetadata(obj.getMetadata());
                if (metaMap != null && metaMap.size() > 0) {
                    LogMF.debug(l4j, "Updating metadata on {0}", destId);
                    time(new Timeable<Void>() {
                        @Override
                        public Void call() {
                            atmos.setUserMetadata(destId,
                                    metaMap.values().toArray(new Metadata[metaMap.size()]));
                            return null;
                        }
                    }, OPERATION_SET_USER_META);
                }
                if (getAtmosAcl(obj.getMetadata()) != null) {
                    LogMF.debug(l4j, "Updating ACL on {0}", destId);
                    time(new Timeable<Void>() {
                        @Override
                        public Void call() {
                            atmos.setAcl(destId, getAtmosAcl(obj.getMetadata()));
                            return null;
                        }
                    }, OPERATION_SET_ACL);
                }
            } else {
                LogMF.debug(l4j, "Updating {0}", destId);
                if (checksum != null) {
                    try {
                        final RunningChecksum ck = new RunningChecksum(ChecksumAlgorithm.valueOf(checksum));
                        byte[] buffer = new byte[1024 * 1024];
                        long read = 0;
                        int c;
                        while ((c = in.read(buffer)) != -1) {
                            final BufferSegment bs = new BufferSegment(buffer, 0, c);
                            if (read == 0) {
                                // You cannot update a checksummed object.
                                // Delete and replace.
                                if (destId instanceof ObjectId) {
                                    throw new RuntimeException(
                                            "Cannot update checksummed " + "object by ObjectID, only "
                                                    + "namespace objects are " + "supported");
                                }
                                time(new Timeable<Void>() {
                                    @Override
                                    public Void call() {
                                        atmos.delete(destId);
                                        return null;
                                    }
                                }, OPERATION_DELETE_OBJECT);
                                ck.update(bs.getBuffer(), bs.getOffset(), bs.getSize());
                                final CreateObjectRequest request = new CreateObjectRequest();
                                request.identifier(destId).acl(getAtmosAcl(obj.getMetadata())).content(bs);
                                request.setUserMetadata(
                                        AtmosUtil.getAtmosUserMetadata(obj.getMetadata()).values());
                                request.contentType(obj.getMetadata().getContentType()).wsChecksum(ck);
                                time(new Timeable<Void>() {
                                    @Override
                                    public Void call() {
                                        atmos.createObject(request);
                                        return null;
                                    }
                                }, OPERATION_CREATE_OBJECT_FROM_SEGMENT_ON_PATH);
                            } else {
                                // Append
                                ck.update(bs.getBuffer(), bs.getOffset(), bs.getSize());
                                Range r = new Range(read, read + c - 1);
                                final UpdateObjectRequest request = new UpdateObjectRequest();
                                request.identifier(destId).content(bs).range(r).wsChecksum(ck);
                                request.contentType(obj.getMetadata().getContentType());
                                time(new Timeable<Void>() {
                                    @Override
                                    public Void call() {
                                        atmos.updateObject(request);
                                        return null;
                                    }
                                }, OPERATION_UPDATE_OBJECT_FROM_SEGMENT);
                            }
                            read += c;
                        }
                    } catch (NoSuchAlgorithmException e) {
                        throw new RuntimeException("Incorrect checksum method: " + checksum, e);
                    }
                } else {
                    final UpdateObjectRequest request = new UpdateObjectRequest();
                    request.identifier(destId).acl(getAtmosAcl(obj.getMetadata())).content(in);
                    request.setUserMetadata(AtmosUtil.getAtmosUserMetadata(obj.getMetadata()).values());
                    request.contentLength(obj.getMetadata().getSize())
                            .contentType(obj.getMetadata().getContentType());
                    time(new Timeable<Void>() {
                        @Override
                        public Void call() {
                            atmos.updateObject(request);
                            return null;
                        }
                    }, OPERATION_UPDATE_OBJECT_FROM_SEGMENT);
                }
            }

            // update retention/expiration in case policy changed
            updateRetentionExpiration(obj, destId);
        } finally {
            if (in != null) {
                in.close();
            }
        }

    } else if (srcCtime != null && dstCtime != null && srcCtime.after(dstCtime)) {
        if (noUpdate) {
            LogMF.debug(l4j, "Skipping {0}, updates disabled.", obj.getSourceIdentifier(),
                    obj.getTargetIdentifier());
            return;
        }
        // Metadata update required.
        final Map<String, Metadata> metaMap = AtmosUtil.getAtmosUserMetadata(obj.getMetadata());
        if (metaMap != null && metaMap.size() > 0) {
            LogMF.debug(l4j, "Updating metadata on {0}", destId);
            time(new Timeable<Void>() {
                @Override
                public Void call() {
                    atmos.setUserMetadata(destId, metaMap.values().toArray(new Metadata[metaMap.size()]));
                    return null;
                }
            }, OPERATION_SET_USER_META);
        }
        if (getAtmosAcl(obj.getMetadata()) != null) {
            LogMF.debug(l4j, "Updating ACL on {0}", destId);
            time(new Timeable<Void>() {
                @Override
                public Void call() {
                    atmos.setAcl(destId, getAtmosAcl(obj.getMetadata()));
                    return null;
                }
            }, OPERATION_SET_ACL);
        }

        // update retention/expiration in case policy changed
        updateRetentionExpiration(obj, destId);
    } else {
        // No updates
        LogMF.debug(l4j, "No changes from source {0} to dest {1}", obj.getSourceIdentifier(),
                obj.getTargetIdentifier());
    }
}

From source file:com.emc.ecs.sync.target.EcsS3Target.java

@Override
public void filter(SyncObject obj) {
    try {/*from w w  w .  j a  v  a2  s .com*/
        // skip the root of the bucket since it obviously exists
        if ("".equals(rootKey + obj.getRelativePath())) {
            log.debug("Target is bucket root; skipping");
            return;
        }

        // some sync objects lazy-load their metadata (i.e. AtmosSyncObject)
        // since this may be a timed operation, ensure it loads outside of other timed operations
        if (!(obj instanceof EcsS3ObjectVersion) || !((EcsS3ObjectVersion) obj).isDeleteMarker())
            obj.getMetadata();

        // Compute target key
        final String targetKey = getTargetKey(obj);
        obj.setTargetIdentifier(AwsS3Util.fullPath(bucketName, targetKey));

        if (includeVersions) {
            ListIterator<EcsS3ObjectVersion> sourceVersions = s3Source.versionIterator((EcsS3SyncObject) obj);
            ListIterator<EcsS3ObjectVersion> targetVersions = versionIterator(obj);

            boolean newVersions = false, replaceVersions = false;
            if (force) {
                replaceVersions = true;
            } else {

                // special workaround for bug where objects are listed, but they have no versions
                if (sourceVersions.hasNext()) {

                    // check count and etag/delete-marker to compare version chain
                    while (sourceVersions.hasNext()) {
                        EcsS3ObjectVersion sourceVersion = sourceVersions.next();

                        if (targetVersions.hasNext()) {
                            EcsS3ObjectVersion targetVersion = targetVersions.next();

                            if (sourceVersion.isDeleteMarker()) {

                                if (!targetVersion.isDeleteMarker())
                                    replaceVersions = true;
                            } else {

                                if (targetVersion.isDeleteMarker())
                                    replaceVersions = true;

                                else if (!sourceVersion.getETag().equals(targetVersion.getETag()))
                                    replaceVersions = true; // different checksum
                            }

                        } else if (!replaceVersions) { // source has new versions, but existing target versions are ok
                            newVersions = true;
                            sourceVersions.previous(); // back up one
                            putIntermediateVersions(sourceVersions, targetKey); // add any new intermediary versions (current is added below)
                        }
                    }

                    if (targetVersions.hasNext())
                        replaceVersions = true; // target has more versions

                    if (!newVersions && !replaceVersions) {
                        log.info("Source and target versions are the same.  Skipping {}",
                                obj.getRelativePath());
                        return;
                    }
                }
            }

            // something's off; must delete all versions of the object
            if (replaceVersions) {
                log.info(
                        "[{}]: version history differs between source and target; re-placing target version history with that from source.",
                        obj.getRelativePath());

                // collect versions in target
                final List<ObjectKey> deleteVersions = new ArrayList<>();
                while (targetVersions.hasNext())
                    targetVersions.next(); // move cursor to end
                while (targetVersions.hasPrevious()) { // go in reverse order
                    EcsS3ObjectVersion version = targetVersions.previous();
                    deleteVersions.add(new ObjectKey(targetKey, version.getVersionId()));
                }

                // batch delete all versions in target
                log.debug("[{}]: deleting all versions in target", obj.getRelativePath());
                time(new Function<Void>() {
                    @Override
                    public Void call() {
                        s3.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(deleteVersions));
                        return null;
                    }
                }, OPERATION_DELETE_VERSIONS);

                // replay version history in target
                while (sourceVersions.hasPrevious())
                    sourceVersions.previous(); // move cursor to beginning
                putIntermediateVersions(sourceVersions, targetKey);
            }

        } else { // normal sync (no versions)
            Date sourceLastModified = obj.getMetadata().getModificationTime();
            long sourceSize = obj.getMetadata().getContentLength();

            // Get target metadata.
            S3ObjectMetadata destMeta = null;
            try {
                destMeta = time(new Function<S3ObjectMetadata>() {
                    @Override
                    public S3ObjectMetadata call() {
                        return s3.getObjectMetadata(bucketName, targetKey);
                    }
                }, OPERATION_GET_METADATA);
            } catch (S3Exception e) {
                if (e.getHttpCode() != 404) {
                    throw new RuntimeException("Failed to check target key '" + targetKey + "' : " + e, e);
                }
            }

            if (!force && obj.getFailureCount() == 0 && destMeta != null) {

                // Check overwrite
                Date destLastModified = destMeta.getLastModified();
                long destSize = destMeta.getContentLength();

                if (destLastModified.equals(sourceLastModified) && sourceSize == destSize) {
                    log.info("Source and target the same.  Skipping {}", obj.getRelativePath());
                    return;
                }
                if (destLastModified.after(sourceLastModified)) {
                    log.info("Target newer than source.  Skipping {}", obj.getRelativePath());
                    return;
                }
            }
        }

        // at this point we know we are going to write the object
        // Put [current object version]
        if (obj instanceof S3ObjectVersion && ((S3ObjectVersion) obj).isDeleteMarker()) {

            // object has version history, but is currently deleted
            log.debug("[{}]: deleting object in target to replicate delete marker in source.",
                    obj.getRelativePath());
            time(new Function<Void>() {
                @Override
                public Void call() {
                    s3.deleteObject(bucketName, targetKey);
                    return null;
                }
            }, OPERATION_DELETE_OBJECT);
        } else {
            putObject(obj, targetKey);

            // if object has new metadata after the stream (i.e. encryption checksum), we must update S3 again
            if (obj.requiresPostStreamMetadataUpdate()) {
                log.debug("[{}]: updating metadata after sync as required", obj.getRelativePath());
                final CopyObjectRequest cReq = new CopyObjectRequest(bucketName, targetKey, bucketName,
                        targetKey);
                cReq.setObjectMetadata(EcsS3Util.s3MetaFromSyncMeta(obj.getMetadata()));
                time(new Function<Void>() {
                    @Override
                    public Void call() {
                        s3.copyObject(cReq);
                        return null;
                    }
                }, OPERATION_UPDATE_METADATA);
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("Failed to store object: " + e, e);
    }
}

From source file:org.openehealth.coala.beans.ConsentBean.java

/**
 * Method to validate input parameters (validFrom and validUntil) of consent
 * creation. This is needed to have proper error notification on missing
 * date input at consent creation view./*  www  . jav a 2s.co m*/
 * 
 * @param event
 */
public void validateCreateConsentParameters(ComponentSystemEvent event) {
    FacesContext fc = FacesContext.getCurrentInstance();
    String messages = fc.getApplication().getMessageBundle();
    Locale locale = new Locale(localeHandler.getLocale());
    ResourceBundle bundle = ResourceBundle.getBundle(messages, locale);

    UIComponent components = event.getComponent();

    UIInput validFromDateInput = (UIInput) components.findComponent("validFromInput");
    UIInput validUntilDateInput = (UIInput) components.findComponent("validUntilInput");

    boolean validFromDateEmpty = false;
    boolean validUntilDateEmpty = false;

    if (validFromDateInput.getLocalValue() == null
            || validFromDateInput.getLocalValue().toString().trim().isEmpty()) {
        validFromDateEmpty = true;
    }
    if (validUntilDateInput.getLocalValue() == null
            || validUntilDateInput.getLocalValue().toString().trim().isEmpty()) {
        validUntilDateEmpty = true;
    }

    if (validFromDateEmpty || validUntilDateEmpty) {
        validationSuccessful = false;
        FacesMessage msg = new FacesMessage(bundle.getString("errors.nonEmptyValidationDates"), "");
        msg.setSeverity(FacesMessage.SEVERITY_WARN);
        fc.addMessage(components.getClientId(), msg);
        // passed to the Render Response phase
        fc.renderResponse();
    }

    //validates if validFrom is after or equals validUntil
    Date from = (Date) validFromDateInput.getValue();
    Date until = (Date) validUntilDateInput.getValue();
    if (from == null || until == null) {
        validationSuccessful = false;
        FacesMessage msg = new FacesMessage("Please provide valid date input values for From AND Until.", "");
        msg.setSeverity(FacesMessage.SEVERITY_WARN);
        fc.addMessage(components.getClientId(), msg);
        // passed to the Render Response phase
        fc.renderResponse();
    } else if (from != null && until != null) {
        if (from.after(until) || from.equals(until)) {
            validationSuccessful = false;
            FacesMessage msg = new FacesMessage(bundle.getString("errors.fromBeforeUntil"), "");
            msg.setSeverity(FacesMessage.SEVERITY_WARN);
            fc.addMessage(components.getClientId(), msg);
            // passed to the Render Response phase
            fc.renderResponse();
        }
        // all checks passed now, set validationSuccessful to true, which causes the "Register" button to become active!
        else {
            LOG.info("Consent creation validation has passed now.");
            validationSuccessful = true;
        }
    } else {
        validationSuccessful = false;
        FacesMessage msg = new FacesMessage("Please provide valid date input values for From AND Until.", "");
        msg.setSeverity(FacesMessage.SEVERITY_WARN);
        fc.addMessage(components.getClientId(), msg);
        // passed to the Render Response phase
        fc.renderResponse();
    }
}

From source file:hydrograph.ui.propertywindow.widgets.listeners.grid.MouseHoverOnSchemaGridListener.java

private String setToolTipForDateSchemaRange(GenerateRecordSchemaGridRow generateRecordSchemaGridRow) {

    Date rangeFromDate = null, rangeToDate = null;
    SimpleDateFormat formatter = new SimpleDateFormat(generateRecordSchemaGridRow.getDateFormat());

    if (StringUtils.isNotBlank(generateRecordSchemaGridRow.getRangeFrom())) {
        try {//from w  w w.  j  ava 2  s. co m
            rangeFromDate = formatter.parse(generateRecordSchemaGridRow.getRangeFrom());
        } catch (ParseException e) {
            return Messages.RANGE_FROM_DATE_INCORRECT_PATTERN;
        }
    }

    if (StringUtils.isNotBlank(generateRecordSchemaGridRow.getRangeTo())) {
        try {
            rangeToDate = formatter.parse(generateRecordSchemaGridRow.getRangeTo());
        } catch (ParseException e) {
            return Messages.RANGE_TO_DATE_INCORRECT_PATTERN;
        }
    }

    if (rangeFromDate != null && rangeToDate != null && rangeFromDate.after(rangeToDate)) {
        return Messages.RANGE_FROM_GREATER_THAN_RANGE_TO;
    }

    return "";
}

From source file:com.ssbusy.controller.checkout.CheckoutController.java

private String saveSingleShip0(HttpServletRequest request, HttpServletResponse response, Model model,
        OrderInfoForm orderInfoForm, MyBillingInfoForm billingForm, MyShippingInfoForm shippingForm,
        BindingResult result, boolean ajax)
        throws PricingException, ServiceException, CheckoutException, ParseException {
    MyCustomer myCustomer = (MyCustomer) CustomerState.getCustomer();
    Region region = myCustomer.getRegion();
    Boolean w_flag = (Boolean) request.getSession().getAttribute("w_flag");
    if (region == null) {
        if (w_flag != null && w_flag) {
            return "redirect:/weixin/region";
        } else//from w w w . j a  v  a 2 s . c om
            return REDIRECT_REGION_SELECT;
    }

    MyAddress myAddress = processShippingForm(shippingForm, result);
    if (result.hasErrors()) {
        putFulfillmentOptionsAndEstimationOnModel(model);
        populateModelWithShippingReferenceData(request, model);
        model.addAttribute("states", stateService.findStates());
        model.addAttribute("countries", countryService.findCountries());
        model.addAttribute("expirationMonths", populateExpirationMonths());
        model.addAttribute("expirationYears", populateExpirationYears());
        model.addAttribute("validShipping", false);
        if (w_flag != null && w_flag) {
            return "weixin/cart/w_checkout";
        } else
            return checkoutAddress;
    }

    billingForm.setPaymentMethod(shippingForm.getPaymentMethod());
    billingForm.setBp_pay(shippingForm.getBp_pay());
    billingForm.setAlipay(shippingForm.getAlipay());
    if (shippingForm.getBp_pay() == null || shippingForm.getBp_pay().doubleValue() < 0)
        billingForm.setBp_pay(BigDecimal.ZERO);
    if (shippingForm.getAlipay() == null || shippingForm.getAlipay().doubleValue() < 0)
        billingForm.setAlipay(BigDecimal.ZERO);
    billingForm.setMyAddress(myAddress);
    prepopulateCheckoutForms(CartState.getCart(), orderInfoForm, null, billingForm);

    String assign = request.getParameter("assign");
    MyOrder cart = (MyOrder) CartState.getCart();

    Date dStart = null, dEnd = null;
    Date nowDay = Calendar.getInstance().getTime();
    if (nowDay.after(myDate1) && nowDay.before(myDate2)) {
        dStart = myDate1;
        dEnd = myDate2;
    } else if (nowDay.after(myDate2) && nowDay.before(myDate3)) {
        dStart = myDate2;
        dEnd = myDate3;
    } else if (nowDay.after(myDate3) && nowDay.before(myDate4)) {
        dStart = myDate3;
        dEnd = myDate4;
    }
    if (dStart != null) {
        List<Order> orders = myorderService.getAllSubmittedInTime(myCustomer.getId(), dStart, dEnd);
        boolean contain = ifCanAdd(orders);
        if (contain) {
            if (w_flag != null && w_flag) {
                return "redirect:/weixin/checkout";
            } else
                return "redirect:/checkout/checkout-step-2?error=%E4%B8%8D%E8%A6%81%E5%A4%AA%E8%B4%AA%E5%BF%83%EF%BC%8C%E5%8F%AA%E8%83%BD%E6%8A%A21%E6%AC%A1%E5%93%A6";
        }
    }

    String a1;
    Date a2;
    if ("2".equals(assign)) {
        String date = request.getParameter("date");
        String detaildate = request.getParameter("detaildate");
        int deta = 0;
        try {
            deta = Integer.parseInt(detaildate);
        } catch (Exception e) {
            // ignore
        }

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, deta);
        if ("1".equals(date)) {
            calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + 1);
        } else if ("2".equals(date)) {
            calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + 2);
        }
        SimpleDateFormat dateformat1 = new SimpleDateFormat("HH:mm");
        a2 = calendar.getTime();
        a1 = dateformat1.format(a2);
    } else {
        SimpleDateFormat dateformat1 = new SimpleDateFormat("HH:mm");
        a2 = new Date();
        a1 = dateformat1.format(a2);
    }
    cart.setDelieverDate(a2);

    FulfillmentGroup fulfillmentGroup = cart.getFulfillmentGroups().get(0);

    fulfillmentGroup.setAddress(shippingForm.getMyAddress());
    fulfillmentGroup.setPersonalMessage(shippingForm.getPersonalMessage());
    fulfillmentGroup.setDeliveryInstruction(shippingForm.getDeliveryMessage());

    cart = (MyOrder) orderService.save(cart, true);
    CartState.setCart(cart);
    CustomerAddress defaultAddress = customerAddressService
            .findDefaultCustomerAddress(CustomerState.getCustomer().getId());
    if (defaultAddress == null) {
        MyAddress address = (MyAddress) addressService.saveAddress(shippingForm.getMyAddress());
        CustomerAddress customerAddress = customerAddressService.create();
        customerAddress.setAddress(address);
        customerAddress.setCustomer(CustomerState.getCustomer());
        customerAddress = customerAddressService.saveCustomerAddress(customerAddress);
        customerAddressService.makeCustomerAddressDefault(customerAddress.getId(),
                customerAddress.getCustomer().getId());
    }

    // ????
    if (false) {// if("no".equals(request.getParameter("forcedSubmit"))){
        String[] times = region.getShipping_time().split(";");
        boolean isOutDeliveryDateRange = true;
        for (String time : times) {
            String[] shipping_time = time.split("-");
            if ((a1.compareTo(shipping_time[0]) > 0) && (a1.compareTo(shipping_time[1]) < 0))
                isOutDeliveryDateRange = false;
        }
        if (isOutDeliveryDateRange) {
            return "redirect:/checkout/checkout-step-2?flag=1";
        }
    }

    try {
        if ("alipay_pay".equals(billingForm.getPaymentMethod())) {
            String description = "";
            for (OrderItem ot : cart.getOrderItems()) {
                description = description + ot.getName() + "";
                if (description.length() > 50) {
                    description = description + "....";
                    break;
                }
            }
            // TODO ?location
            FulfillmentLocation loc = null;
            List<FulfillmentGroup> fgroups = cart.getFulfillmentGroups();
            if (fgroups == null || fgroups.size() == 0) {
                Customer customer = CustomerState.getCustomer();
                if (customer instanceof MyCustomer)
                    loc = ((MyCustomer) customer).getRegion().getFulfillmentLocations().get(0);
            } else {
                Address addr = fgroups.get(0).getAddress();
                if (addr instanceof MyAddress) {
                    loc = ((MyAddress) addr).getDormitory().getAreaAddress().getRegion()
                            .getFulfillmentLocations().get(0);
                }
            }
            // TODO path??alipay
            String path = "/alipay/direct_pay?tradeNo="
                    + (new SimpleDateFormat("yyyyMMddHHmm").format(SystemTime.asDate()) + cart.getId())
                    + "&subject= " + (loc == null ? "" : loc.getId())
                    + (new Date().getTime() % 1000000) + cart.getId() + " ??&description=" + description
                    + "&tradeUrl=http://www.onxiao.com/customer/orders";
            if (billingForm.getAlipay().compareTo(cart.getTotal().getAmount()) >= 0) {
                // ?
                path = path + "&totalFee=" + cart.getTotal();
                return "forward:" + path;

            } else {
                if (billingForm.getAlipay().doubleValue() == 0) {
                    return completeCodCheckout(request, response, model, billingForm, result);
                } else {
                    // ?
                    path = path + "&totalFee=" + billingForm.getAlipay();
                    return "forward:" + path;
                }
            }
        } else if ("balance_pay".equals(billingForm.getPaymentMethod())) {
            if (billingForm.getBp_pay().compareTo(cart.getTotal().getAmount()) >= 0) {
                return completeBpCheckout(request, response, model, billingForm, result);
            } else {
                if (billingForm.getAlipay().doubleValue() <= 0) {
                    return completeCodCheckout(request, response, model, billingForm, result);
                } else {
                    return complexCheckout(request, response, model, billingForm, result,
                            MyPaymentInfoType.Payment_Bp, cart.getId());
                }
            }

        } else if ("integral_pay".equals(billingForm.getPaymentMethod())) {
            return completeIntegrlCheckout(request, response, model, billingForm, result);
        } else {
            return completeCodCheckout(request, response, model, billingForm, result);
        }
    } catch (CheckoutException e) {
        if (ajax)
            throw e;
        if (e.getCause() instanceof InventoryUnavailableException) {
            try {
                if (w_flag != null && w_flag) {
                    return "redirect:/weixin/checkout";
                } else
                    return "redirect:/checkout/checkout-step-2?inventoryError=1&errorMessage=" + URLEncoder
                            .encode(((InventoryUnavailableException) e.getCause()).getMessage(), "utf-8");
            } catch (UnsupportedEncodingException e1) {
                if (w_flag != null && w_flag) {
                    return "redirect:/weixin/checkout";
                } else
                    return "redirect:/checkout/checkout-step-2?inventoryError=1&errorMessage="
                            + ((InventoryUnavailableException) e.getCause()).getMessage();
            }
        } else if (e.getCause() instanceof InsufficientFundsException) {
            if (w_flag != null && w_flag) {
                return "redirect:/weixin/checkout";
            } else
                return "redirect:/checkout/checkout-step-2?error=%E7%A7%AF%E5%88%86%E6%88%96%E8%80%85%E4%BD%99%E9%A2%9D%E4%B8%8D%E8%B6%B3";
        } else {
            throw e;
        }
    }
}

From source file:org.kuali.ole.service.impl.OleLicenseRequestServiceImpl.java

/**
 * This method will generate the request xml for the delete operation.
 * @param metadata//from   www.  ja  v a  2  s .co m
 * @return  rollBackXml
 */
//    private String buildDeleteAgreementRequestXml(OleAgreementDocumentMetadata metadata){
//        ResponseHandler responseHandler = new ResponseHandler();
//        RequestHandler requestHandler = new RequestHandler();
//        Request request = new Request();
//        request.setUser("khuntley");
//        request.setOperation("delete");
//        RequestDocument requestDocument = new RequestDocument();
//        requestDocument.setId("1");
//        requestDocument.setCategory(OLEConstants.WORK_CATEGORY);
//        requestDocument.setType("license");
//        requestDocument.setUuid(metadata.getAgreementUUID());
//        String agreementFormat = metadata.getAgreementFileName().substring(metadata.getAgreementFileName().indexOf(".")+1
//                ,metadata.getAgreementFileName().length());
//        if((agreementFormat.equals("pdf")) | (agreementFormat.equals("xslt"))) {
//            requestDocument.setFormat(agreementFormat);
//        }
//        else {
//            requestDocument.setFormat("doc");
//        }
//        //requestDocument.setFormat(agreementFormat);
//        List<RequestDocument> requestDocuments = new ArrayList<RequestDocument>();
//        requestDocuments.add(requestDocument);
//        request.setRequestDocuments(requestDocuments);
//        String rollBackXml = requestHandler.toXML(request);
//        return rollBackXml;
//    }
@Override
public boolean validateDate(Date documentDate, String fromDate, String toDate) throws Exception {
    boolean isValidDate = false;
    String dateToCompare = "";
    if (documentDate != null) {
        dateToCompare = dateFormat.format(documentDate);
    }
    try {
        if (((toDate == null || toDate.isEmpty()) && fromDate != null && !fromDate.isEmpty())
                && (dateToCompare.equals(fromDate)
                        || (documentDate != null && documentDate.after(dateFormat.parse(fromDate))))) {
            isValidDate = true;
        } else if (((fromDate == null || fromDate.isEmpty()) && toDate != null && !toDate.isEmpty())
                && (dateToCompare.equals(toDate)
                        || (documentDate != null && documentDate.before(dateFormat.parse(toDate))))) {
            isValidDate = true;
        } else if (((fromDate == null || fromDate.isEmpty()) && ((toDate == null) || toDate.isEmpty()))
                || ((fromDate != null && (dateToCompare.equals(fromDate)
                        || (documentDate != null && documentDate.after(dateFormat.parse(fromDate)))))
                        && (toDate != null && (dateToCompare.equals(toDate)
                                || (documentDate != null && documentDate.before(dateFormat.parse(toDate))))))) {
            isValidDate = true;
        }
    } catch (Exception e) {
        LOG.error("Error while comparing the date" + e.getMessage());
        throw new RuntimeException(e);
    }
    return isValidDate;

}

From source file:au.edu.uq.cmm.paul.servlet.WebUIController.java

@RequestMapping(value = "/facilities/{facilityName:.+}", params = {
        "setIntertidal" }, method = RequestMethod.POST)
public String setFacilityHWM(@PathVariable String facilityName, Model model, HttpServletRequest request,
        @RequestParam String lwmTimestamp, @RequestParam String hwmTimestamp) throws ConfigurationException {
    model.addAttribute("returnTo", inferReturnTo(request, "/facilities"));
    Facility facility = lookupFacilityByName(facilityName);
    FacilityStatus status = getFacilityStatusManager().getStatus(facility);
    if (status.getStatus() == FacilityStatusManager.Status.ON) {
        model.addAttribute("message", "Cannot change LWM and HWM while the Grabber is running.");
        return "failed";
    }//  ww  w  .  j a  va 2 s.  c  om
    Date oldLWM = status.getGrabberLWMTimestamp();
    Date oldHWM = status.getGrabberHWMTimestamp();
    Date lwm = parseDate(lwmTimestamp);
    Date hwm = parseDate(hwmTimestamp);
    Date now = new Date();
    if (lwm != null && hwm != null && !lwm.after(hwm) && hwm.before(now)) {
        getFacilityStatusManager().updateIntertidalTimestamp(facility, lwm, hwm);
        model.addAttribute("message", "Changed LWM / HWM for '" + facilityName + "' from " + oldLWM + " / "
                + oldHWM + " to " + lwm + " / " + hwm);
        return "ok";
    } else {
        if (lwm == null) {
            model.addAttribute("message", "Invalid LWM timestamp");
        } else if (hwm == null) {
            model.addAttribute("message", "Invalid HWM timestamp");
        } else if (lwm.after(hwm)) {
            model.addAttribute("message", "Inconsistent timestamps: LWM &gt; HWM");
        } else if (!hwm.before(now)) {
            model.addAttribute("message", "Inconsistent timestamps: HWM in the future");
        }
        return "failed";
    }
}

From source file:com.knowbout.epg.processor.ScheduleParser.java

private Date processSchedules(InputStream stream) throws IOException {
    log.debug("Processing raw text schedules for schedules");
    Date firstProgram = null;
    BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
    String line = reader.readLine();
    SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyyMMddHHmm");
    dateTimeFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    while (line != null) {
        String[] parts = line.split("\\|", -1);
        long stationId = Long.parseLong(parts[0]);
        String programId = parts[1];
        Date airTime = null;/*from ww  w .  j a v  a2  s  .c om*/
        try {
            airTime = dateTimeFormat.parse(parts[2] + parts[3]);
        } catch (ParseException e) {
            log.error("Error parsing airtime for :" + line);
        }
        if (airTime != null) {
            if (firstProgram == null || firstProgram.after(airTime)) {
                firstProgram = airTime;
            }
            StationLineup lineup = stationIdToLineup.get(stationId);
            if (lineup != null) {
                ChannelSchedule schedule = programSchedules.get(new Key(programId, lineup.getCallSign()));
                if (schedule == null) {
                    schedule = new ChannelSchedule(programId, lineup);
                    programSchedules.put(new Key(programId, lineup.getCallSign()), schedule);
                }
                if (schedule != null) {
                    String duration = parts[4];
                    int durationInMinutes = 0;
                    if (duration.length() == 4) {
                        int hours = Integer.parseInt(duration.substring(0, 2));
                        int minutes = Integer.parseInt(duration.substring(2, 4));
                        durationInMinutes = hours * 60 + minutes;
                    }
                    //End time is calculated, but we need it for searching
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
                    calendar.setTime(airTime);
                    calendar.add(Calendar.MINUTE, durationInMinutes);
                    ScheduleAiring airing = new ScheduleAiring(schedule, stationId, airTime, calendar.getTime(),
                            durationInMinutes, line);
                    schedule.addAiring(airing);
                }
            }

        }
        line = reader.readLine();
    }
    reader.close();
    log.debug("Finished processing raw text schedules for schedules");
    return firstProgram;
}