Example usage for org.joda.time DateTime now

List of usage examples for org.joda.time DateTime now

Introduction

In this page you can find the example usage for org.joda.time DateTime now.

Prototype

public static DateTime now() 

Source Link

Document

Obtains a DateTime set to the current system millisecond time using ISOChronology in the default time zone.

Usage

From source file:access.deploy.Leaser.java

License:Apache License

/**
 * Creates a new lease for the Deployment.
 * // ww  w .  jav  a 2s. c o m
 * @param deployment
 *            Deployment to create a lease for
 * @param durationDays
 *            the Number of days to create the deployment for
 */
public Lease createDeploymentLease(Deployment deployment, Integer durationDays) {
    // Create the Lease
    String leaseId = uuidFactory.getUUID();
    Integer updatedDurationDays = ((durationDays != null) && (durationDays.intValue() > 0)) ? durationDays
            : DEFAULT_LEASE_PERIOD_DAYS;
    Lease lease = new Lease(leaseId, deployment.getDeploymentId(),
            DateTime.now().plusDays(updatedDurationDays.intValue()));

    // Commit the Lease to the Database
    accessor.insertLease(lease);

    // Return reference
    pzLogger.log(
            String.format("Creating Deployment Lease for Deployment %s on host %s for %s",
                    deployment.getDeploymentId(), deployment.getHost(), deployment.getDataId()),
            Severity.INFORMATIONAL, new AuditElement(ACCESS, "createDeploymentLease", leaseId));
    return lease;
}

From source file:access.deploy.Leaser.java

License:Apache License

/**
 * <p>//from   ww  w .j a  v  a  2  s  .  com
 * This method is scheduled to run periodically and look for leases that are expired. If a lease is found to be
 * expired, and GeoServer resources are limited, then the lease will be terminated.
 * </p>
 * 
 * <p>
 * Leases might not be terminated if they are expired, if GeoServer has more than adequate resources available. This
 * is configurable, but ultimately the goal is to create a friendly user experience while not bogging down GeoServer
 * with lots of old, unused deployments.
 * </p>
 * 
 * <p>
 * This will currently run every day at 3:00am.
 * </p>
 */
@Scheduled(cron = "0 0 3 * * ?")
public void reapExpiredLeases() {
    // Log the initiation of reaping.
    pzLogger.log("Running scheduled daily reaping of expired Deployment Leases.", Severity.INFORMATIONAL);

    // Determine if GeoServer is reaching capacity of its resources.
    // TODO: Not sure if this is needed just yet.
    pzLogger.log("GeoServer not at capacity. No reaping of resources required.", Severity.INFORMATIONAL);

    Iterable<Lease> leases = accessor.getExpiredLeases(DateTime.now());
    for (Lease expiredLease : leases) {
        // There are leases with expired deployments. Remove them.
        try {
            deployer.undeploy(expiredLease.getDeploymentId());
            // Log the removal
            pzLogger.log(String.format(
                    "Expired Lease with Id %s with expiration date %s for Deployment %s has been removed.",
                    expiredLease.getLeaseId(), expiredLease.getExpiresOn(), expiredLease.getDeploymentId()),
                    Severity.INFORMATIONAL,
                    new AuditElement(ACCESS, "reapExpiredLease", expiredLease.getDeploymentId()));
        } catch (Exception exception) {
            String error = String.format(
                    "Error reaping Expired Lease with Id %s: %s. This expired lease may still persist.",
                    expiredLease.getLeaseId(), exception.getMessage());
            LOGGER.error(error, exception);
            pzLogger.log(error, Severity.ERROR);
        }
    }
}

From source file:achmad.rifai.erp1.ui.pesan.Tulis.java

private void sActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sActionPerformed
    DateTime t = DateTime.now();
    new Thread(() -> {
        try {/*  www  . j  av  a2  s .  c o m*/
            jejakPengiriman(t);
        } catch (Exception ex) {
            achmad.rifai.erp1.util.Db.hindar(ex);
        }
    }).start();
    try {
        achmad.rifai.erp1.util.Db d = achmad.rifai.erp1.util.Work.loadDB();
        achmad.rifai.erp1.entity.Pesan p = new achmad.rifai.erp1.entity.Pesan();
        p.setDeleted(false);
        p.setKode(k.getId() + t);
        p.setPengirim(k.getId());
        p.setWaktu(t);
        p.setPesan(isi.getText());
        p.setKe(genPenerima());
        new achmad.rifai.erp1.entity.dao.DAOPesan(d).insert(p);
        d.close();
    } catch (Exception ex) {
        achmad.rifai.erp1.util.Db.hindar(ex);
    }
    this.setVisible(false);
}

From source file:act.apidoc.Endpoint.java

License:Apache License

private Object generateSampleData(BeanSpec spec, Set<Type> typeChain, List<String> nameChain) {
    Type type = spec.type();//from  www. j a va2s  . co  m
    if (typeChain.contains(type) && !isCollection(type)) {
        return S.concat(spec.name(), ":", type); // circular reference detected
    }
    typeChain.add(type);
    String name = spec.name();
    if (S.notBlank(name)) {
        nameChain.add(name);
    }
    if (null != fastJsonPropertyPreFilter) {
        String path = S.join(nameChain).by(".").get();
        if (!fastJsonPropertyPreFilter.matches(path)) {
            return null;
        }
    }
    Class<?> classType = spec.rawType();
    try {
        if (void.class == classType || Void.class == classType || Result.class.isAssignableFrom(classType)) {
            return null;
        }
        if (Object.class == classType) {
            return "<Any>";
        }
        try {
            if (classType.isEnum()) {
                Object[] ea = classType.getEnumConstants();
                int len = ea.length;
                return 0 < len ? ea[N.randInt(len)] : null;
            } else if (Locale.class == classType) {
                return (defLocale);
            } else if (String.class == classType) {
                String mockValue = S.random(5);
                if (spec.hasAnnotation(Sensitive.class)) {
                    return Act.crypto().encrypt(mockValue);
                }
                return S.random(5);
            } else if (classType.isArray()) {
                Object sample = Array.newInstance(classType.getComponentType(), 2);
                Array.set(sample, 0,
                        generateSampleData(BeanSpec.of(classType.getComponentType(), Act.injector()),
                                C.newSet(typeChain), C.newList(nameChain)));
                Array.set(sample, 1,
                        generateSampleData(BeanSpec.of(classType.getComponentType(), Act.injector()),
                                C.newSet(typeChain), C.newList(nameChain)));
                return sample;
            } else if ($.isSimpleType(classType)) {
                if (Enum.class == classType) {
                    return "<Any Enum>";
                }
                if (!classType.isPrimitive()) {
                    classType = $.primitiveTypeOf(classType);
                }
                return StringValueResolver.predefined().get(classType).resolve(null);
            } else if (LocalDateTime.class.isAssignableFrom(classType)) {
                return LocalDateTime.now();
            } else if (DateTime.class.isAssignableFrom(classType)) {
                return DateTime.now();
            } else if (LocalDate.class.isAssignableFrom(classType)) {
                return LocalDate.now();
            } else if (LocalTime.class.isAssignableFrom(classType)) {
                return LocalTime.now();
            } else if (Date.class.isAssignableFrom(classType)) {
                return new Date();
            } else if (classType.getName().contains(".ObjectId")) {
                return "<id>";
            } else if (BigDecimal.class == classType) {
                return BigDecimal.valueOf(1.1);
            } else if (BigInteger.class == classType) {
                return BigInteger.valueOf(1);
            } else if (ISObject.class.isAssignableFrom(classType)) {
                return null;
            } else if (Map.class.isAssignableFrom(classType)) {
                Map map = $.cast(Act.getInstance(classType));
                List<Type> typeParams = spec.typeParams();
                if (typeParams.isEmpty()) {
                    typeParams = Generics.typeParamImplementations(classType, Map.class);
                }
                if (typeParams.size() < 2) {
                    map.put(S.random(), S.random());
                    map.put(S.random(), S.random());
                } else {
                    Type keyType = typeParams.get(0);
                    Type valType = typeParams.get(1);
                    map.put(generateSampleData(BeanSpec.of(keyType, null, Act.injector()), C.newSet(typeChain),
                            C.newList(nameChain)),
                            generateSampleData(BeanSpec.of(valType, null, Act.injector()), C.newSet(typeChain),
                                    C.newList(nameChain)));
                    map.put(generateSampleData(BeanSpec.of(keyType, null, Act.injector()), C.newSet(typeChain),
                            C.newList(nameChain)),
                            generateSampleData(BeanSpec.of(valType, null, Act.injector()), C.newSet(typeChain),
                                    C.newList(nameChain)));
                }
            } else if (Iterable.class.isAssignableFrom(classType)) {
                Collection col = $.cast(Act.getInstance(classType));
                List<Type> typeParams = spec.typeParams();
                if (typeParams.isEmpty()) {
                    typeParams = Generics.typeParamImplementations(classType, Map.class);
                }
                if (typeParams.isEmpty()) {
                    col.add(S.random());
                } else {
                    Type componentType = typeParams.get(0);
                    col.add(generateSampleData(BeanSpec.of(componentType, null, Act.injector()),
                            C.newSet(typeChain), C.newList(nameChain)));
                    col.add(generateSampleData(BeanSpec.of(componentType, null, Act.injector()),
                            C.newSet(typeChain), C.newList(nameChain)));
                }
                return col;
            }

            if (null != stringValueResolver(classType)) {
                return S.random(5);
            }

            Object obj = Act.getInstance(classType);
            List<Field> fields = $.fieldsOf(classType);
            for (Field field : fields) {
                if (Modifier.isStatic(field.getModifiers())) {
                    continue;
                }
                if (ParamValueLoaderService.shouldWaive(field)) {
                    continue;
                }
                Class<?> fieldType = field.getType();
                Object val = null;
                try {
                    field.setAccessible(true);
                    val = generateSampleData(BeanSpec.of(field, Act.injector()), C.newSet(typeChain),
                            C.newList(nameChain));
                    Class<?> valType = null == val ? null : val.getClass();
                    if (null != valType && fieldType.isAssignableFrom(valType)) {
                        field.set(obj, val);
                    }
                } catch (Exception e) {
                    LOGGER.warn("Error setting value[%s] to field[%s.%s]", val, classType.getSimpleName(),
                            field.getName());
                }
            }
            return obj;
        } catch (Exception e) {
            LOGGER.warn("error generating sample data for type: %s", classType);
            return null;
        }
    } finally {
        //typeChain.remove(classType);
    }
}

From source file:act.i18n.LocaleResolver.java

License:Apache License

public void dissolve() {
    if (!shouldWriteLocaleCookie()) {
        return;/*from  ww w.  ja  v  a2s  .c o m*/
    }
    String cookieName = config.localeCookieName();
    Locale locale = context.locale();
    if (null == locale) {
        locale = this.locale;
    }
    String localeStr = locale.toString();
    H.Session session = context.session();
    if (null != session) {
        if (reset) {
            session.remove(KEY);
        } else {
            session.put(KEY, localeStr);
        }
    }
    H.Cookie cookie = new H.Cookie(cookieName, localeStr);
    cookie.domain(config.cookieDomain());
    cookie.path("/");
    // in case we have resolved locale from cookie and we shouldn't write cookie anymore, we need to clear it
    cookie.maxAge(reset ? -1 : COOKIE_TTL);
    if (reset) {
        cookie.expires(DateTime.now().minusDays(1).toDate());
    }
    context.resp().addCookie(cookie);
}

From source file:act.job.JobManager.java

License:Apache License

public void on(DateTime instant, Runnable runnable) {
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("schedule runnable[%s] on %s", runnable, instant);
    }//from  w w  w  .j  a v a 2 s.  c o m
    DateTime now = DateTime.now();
    E.illegalArgumentIf(instant.isBefore(now));
    Seconds seconds = Seconds.secondsBetween(now, instant);
    executor().schedule(wrap(runnable), seconds.getSeconds(), TimeUnit.SECONDS);
}

From source file:act.job.JobManager.java

License:Apache License

public <T> Future<T> on(DateTime instant, Callable<T> callable) {
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("schedule callable[%s] on %s", callable, instant);
    }//from w w w.  ja v a 2 s. c om
    DateTime now = DateTime.now();
    E.illegalArgumentIf(instant.isBefore(now));
    Seconds seconds = Seconds.secondsBetween(now, instant);
    return executor().schedule(callable, seconds.getSeconds(), TimeUnit.SECONDS);
}

From source file:act.session.RotationSecretProvider.java

License:Apache License

private String extension(int forwardStep) {
    long trait;/*from ww  w.j  a va 2  s. c  o  m*/
    if (periodInMinutes > 60) {
        int periodInHours = periodInMinutes / 60;
        int hoursOfDay = DateTime.now().hourOfDay().get();
        int period = hoursOfDay / periodInHours;
        trait = currentHourStart().getMillis() / 1000 / 60;
        if (0 < period) {
            trait += (period * 60);
        }
    } else {
        int minutesOfHour = DateTime.now().minuteOfHour().get();
        int period = minutesOfHour / periodInMinutes;
        trait = currentHourStart().getMillis() / 1000 / 60;
        if (0 < period) {
            trait += period;
        }
    }
    if (forwardStep > 0) {
        trait += forwardStep * periodInMinutes;
    }
    return S.string(trait);
}

From source file:act.session.RotationSecretProvider.java

License:Apache License

private static DateTime currentHourStart() {
    return DateTime.now().withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0);
}

From source file:actors.DeployManager.java

License:Apache License

private void deployStage(final FleetDeploymentCommands.DeployStage deployStageMessage) {
    Logger.info("DeployManager starting a fleet deployment");
    // TODO(barp): make sure the stage is locked [Artemis-?]
    // TODO(barp): try grabbing the deployment lock [Artemis-?]
    // TODO(barp): lookup any existing child actor deploying that stage [Artemis-?]
    final Manifest manifest = deployStageMessage.getDeployment();
    final Stage stage = deployStageMessage.getStage();

    try (final Transaction transaction = Ebean.beginTransaction()) {
        final ManifestHistory history = Stage.applyManifestToStage(stage, manifest);
        final Deployment deployment = new Deployment();
        deployment.setStart(DateTime.now());
        deployment.setInitiator(deployStageMessage.getInitiator());
        deployment.setState(DeploymentState.NOT_STARTED);
        deployment.setDeploymentOwner(InetAddress.getLocalHost().getCanonicalHostName());
        deployment.setHeartbeat(DateTime.now());
        deployment.save();/*  w w  w.  j a v  a2s  .co  m*/
        // Render the hosts into the deployment
        final List<HostDeployment> hostDeployments = Lists.newArrayList();
        stage.getHostclasses().forEach(hc -> {
            hc.getHosts().forEach(host -> {
                final HostDeployment hd = new HostDeployment();
                hd.setDeployment(deployment);
                hd.setHeartbeat(DateTime.now());
                hd.setHost(host);
                hd.setState(DeploymentState.NOT_STARTED);
                hd.save();
                hostDeployments.add(hd);
            });
        });
        deployment.setHostStates(hostDeployments);
        deployment.setManifestHistory(history);
        deployment.save();
        transaction.commit();
        startDeployment(deployment);
        sender().tell(deployment, self());
    } catch (final IOException e) {
        throw Throwables.propagate(e);
    }
}