Example usage for org.joda.time Duration Duration

List of usage examples for org.joda.time Duration Duration

Introduction

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

Prototype

public Duration(Object duration) 

Source Link

Document

Creates a duration from the specified object using the org.joda.time.convert.ConverterManager ConverterManager .

Usage

From source file:com.marand.thinkmed.medications.business.impl.TherapyDisplayProvider.java

License:Open Source License

String getTherapyDurationDisplay(final TherapyDto therapy, final Locale locale) {
    if (therapy.getStart() == null || therapy.getEnd() == null || (therapy.getDosingFrequency() != null
            && therapy.getDosingFrequency().getType() == DosingFrequencyTypeEnum.ONCE_THEN_EX)) {
        return "";
    }/* w ww  . ja v  a2  s.c om*/
    final StringBuilder therapyDisplay = new StringBuilder();

    therapyDisplay.append("<span class='TherapyDuration'>");
    therapyDisplay.append(addLineBreak());
    final String whiteSpace = " ";
    final Duration therapyDuration = new Duration(
            therapy.getEnd().getMillis() - therapy.getStart().getMillis());
    final PeriodFormatter therapyDurationFormatter = new PeriodFormatterBuilder().appendWeeks()
            .appendSuffix(whiteSpace + Dictionary.getEntry("week.lc", locale),
                    whiteSpace + Dictionary.getEntry("weeks", locale))
            .appendSeparator(", ").appendDays()
            .appendSuffix(whiteSpace + Dictionary.getEntry("day.lc", locale),
                    whiteSpace + Dictionary.getEntry("days", locale))
            .appendSeparator(", ").appendHours()
            .appendSuffix(whiteSpace + Dictionary.getEntry("hour.lc", locale),
                    whiteSpace + Dictionary.getEntry("hours.accusative", locale))
            .appendSeparator(", ").appendMinutes()
            .appendSuffix(whiteSpace + Dictionary.getEntry("minute.short.lc", locale)).appendSeparator(", ")
            .toFormatter();
    final String formattedTherapyDuration = therapyDurationFormatter
            .print(therapyDuration.toPeriod().normalizedStandard());
    therapyDisplay.append(createSpannedValue(Dictionary.getEntry("duration", locale),
            "DurationLabel TextLabel MedicationLabel", true));
    therapyDisplay.append(createSpannedValue(formattedTherapyDuration, "Duration TextData", true));
    therapyDisplay.append("</span>");

    return therapyDisplay.toString();
}

From source file:com.mastfrog.acteur.Application.java

License:Open Source License

HttpResponse _decorateResponse(Event<?> event, Page page, Acteur action, HttpResponse response) {
    Headers.write(Headers.SERVER, getName(), response);
    Headers.write(Headers.DATE, new DateTime(), response);
    if (debug) {//from  w  w w.  j ava 2s  . c om
        String pth = event instanceof HttpEvent ? ((HttpEvent) event).getPath().toString() : "";
        Headers.write(Headers.stringHeader("X-Req-Path"), pth, response);
        Headers.write(Headers.stringHeader("X-Acteur"), action.getClass().getName(), response);
        Headers.write(Headers.stringHeader("X-Page"), page.getClass().getName(), response);
    }
    if (corsEnabled && !response.headers().contains(HttpHeaders.Names.ACCESS_CONTROL_ALLOW_ORIGIN)) {
        Headers.write(Headers.ACCESS_CONTROL_ALLOW_ORIGIN, corsAllowOrigin, response);
        if (!response.headers().contains(HttpHeaders.Names.ACCESS_CONTROL_MAX_AGE)) {
            Headers.write(Headers.ACCESS_CONTROL_MAX_AGE, new Duration(corsMaxAgeMinutes), response);
        }
    }
    return decorateResponse(event, page, action, response);
}

From source file:com.mastfrog.acteur.headers.DurationHeader.java

License:Open Source License

@Override
public Duration toValue(String value) {
    try {/*from  w  w  w  .ja  v a  2s. c  o  m*/
        return new Duration(Long.parseLong(value));
    } catch (NumberFormatException nfe) {
        Logger.getLogger(DurationHeader.class.getName()).log(Level.INFO, "Bad duration header '" + value + "'",
                nfe);
        return null;
    }
}

From source file:com.mastfrog.acteur.util.RequestID.java

License:Open Source License

public Duration getDuration() {
    return new Duration(System.currentTimeMillis() - time);
}

From source file:com.metamx.druid.BaseQuery.java

License:Open Source License

@Override
public Duration getDuration() {
    if (duration == null) {
        Duration totalDuration = new Duration(0);
        for (Interval interval : querySegmentSpec.getIntervals()) {
            if (interval != null) {
                totalDuration = totalDuration.plus(interval.toDuration());
            }/*  w w w  . ja  v a 2s .  c om*/
        }
        duration = totalDuration;
    }

    return duration;
}

From source file:com.metamx.druid.db.DatabaseRuleManager.java

License:Open Source License

@LifecycleStart
public void start() {
    synchronized (lock) {
        if (started) {
            return;
        }//from  w w w  . j a va  2s .  co  m

        ScheduledExecutors.scheduleWithFixedDelay(exec, new Duration(0), config.getRulesPollDuration(),
                new Runnable() {
                    @Override
                    public void run() {
                        poll();
                    }
                });

        started = true;
    }
}

From source file:com.metamx.druid.db.DatabaseSegmentManager.java

License:Open Source License

@LifecycleStart
public void start() {
    synchronized (lock) {
        if (started) {
            return;
        }/* www . ja va 2  s .c om*/

        ScheduledExecutors.scheduleWithFixedDelay(exec, new Duration(0), config.getPollDuration(),
                new Runnable() {
                    @Override
                    public void run() {
                        poll();
                    }
                });

        started = true;
    }
}

From source file:com.metamx.druid.http.FileRequestLogger.java

License:Open Source License

@LifecycleStart
public void start() {
    try {/*from   ww w  .java2 s  . c om*/
        baseDir.mkdirs();

        MutableDateTime mutableDateTime = new DateTime().toMutableDateTime();
        mutableDateTime.setMillisOfDay(0);
        currentDay = mutableDateTime.toDateTime();

        fileWriter = new FileWriter(new File(baseDir, currentDay.toString("yyyy-MM-dd'.log'")), true);
        long nextDay = currentDay.plusDays(1).getMillis();
        Duration delay = new Duration(nextDay - new DateTime().getMillis());

        ScheduledExecutors.scheduleWithFixedDelay(exec, delay, Duration.standardDays(1),
                new Callable<ScheduledExecutors.Signal>() {
                    @Override
                    public ScheduledExecutors.Signal call() {
                        currentDay = currentDay.plusDays(1);

                        try {
                            synchronized (lock) {
                                Closeables.closeQuietly(fileWriter);
                                fileWriter = new FileWriter(new File(baseDir, currentDay.toString()), true);
                            }
                        } catch (Exception e) {
                            Throwables.propagate(e);
                        }

                        return ScheduledExecutors.Signal.REPEAT;
                    }
                });
    } catch (IOException e) {
        Throwables.propagate(e);
    }
}

From source file:com.metamx.druid.http.MasterMain.java

License:Open Source License

public static void main(String[] args) throws Exception {
    LogLevelAdjuster.register();//  ww  w  . j  av  a 2s . c  o  m

    final ObjectMapper jsonMapper = new DefaultObjectMapper();
    final Properties props = Initialization.loadProperties();
    final ConfigurationObjectFactory configFactory = Config.createFactory(props);
    final Lifecycle lifecycle = new Lifecycle();

    final HttpClientConfig.Builder httpClientConfigBuilder = HttpClientConfig.builder().withNumConnections(1);

    final String emitterTimeout = props.getProperty("druid.emitter.timeOut");
    if (emitterTimeout != null) {
        httpClientConfigBuilder.withReadTimeout(new Duration(emitterTimeout));
    }
    final HttpClient httpClient = HttpClientInit.createClient(httpClientConfigBuilder.build(), lifecycle);

    final ServiceEmitter emitter = new ServiceEmitter(PropUtils.getProperty(props, "druid.service"),
            PropUtils.getProperty(props, "druid.host"),
            Emitters.create(props, httpClient, jsonMapper, lifecycle));
    EmittingLogger.registerEmitter(emitter);

    final ScheduledExecutorFactory scheduledExecutorFactory = ScheduledExecutors.createFactory(lifecycle);

    final ServiceDiscoveryConfig serviceDiscoveryConfig = configFactory.build(ServiceDiscoveryConfig.class);
    CuratorFramework serviceDiscoveryCuratorFramework = Initialization
            .makeCuratorFramework(serviceDiscoveryConfig, lifecycle);
    final CuratorConfig curatorConfig = configFactory.build(CuratorConfig.class);
    CuratorFramework curatorFramework = Initialization.makeCuratorFramework(curatorConfig, lifecycle);

    final ZkPathsConfig zkPaths = configFactory.build(ZkPathsConfig.class);

    final ExecutorService exec = Executors.newFixedThreadPool(1,
            new ThreadFactoryBuilder().setDaemon(true).setNameFormat("ServerInventoryView-%s").build());

    final ServerInventoryViewConfig serverInventoryViewConfig = configFactory
            .build(ServerInventoryViewConfig.class);
    final String announcerType = serverInventoryViewConfig.getAnnouncerType();

    final ServerInventoryView serverInventoryView;
    if ("legacy".equalsIgnoreCase(announcerType)) {
        serverInventoryView = new SingleServerInventoryView(serverInventoryViewConfig, zkPaths,
                curatorFramework, exec, jsonMapper);
    } else if ("batch".equalsIgnoreCase(announcerType)) {
        serverInventoryView = new BatchServerInventoryView(serverInventoryViewConfig, zkPaths, curatorFramework,
                exec, jsonMapper);
    } else {
        throw new IAE("Unknown type %s", announcerType);
    }

    lifecycle.addManagedInstance(serverInventoryView);

    final DbConnectorConfig dbConnectorConfig = configFactory.build(DbConnectorConfig.class);
    final DatabaseRuleManagerConfig databaseRuleManagerConfig = configFactory
            .build(DatabaseRuleManagerConfig.class);
    final DBI dbi = new DbConnector(dbConnectorConfig).getDBI();
    DbConnector.createSegmentTable(dbi, PropUtils.getProperty(props, "druid.database.segmentTable"));
    DbConnector.createRuleTable(dbi, PropUtils.getProperty(props, "druid.database.ruleTable"));
    DatabaseRuleManager.createDefaultRule(dbi, databaseRuleManagerConfig.getRuleTable(),
            databaseRuleManagerConfig.getDefaultDatasource(), jsonMapper);

    final DatabaseSegmentManager databaseSegmentManager = new DatabaseSegmentManager(jsonMapper,
            scheduledExecutorFactory.create(1, "DatabaseSegmentManager-Exec--%d"),
            configFactory.build(DatabaseSegmentManagerConfig.class), dbi);
    final DatabaseRuleManager databaseRuleManager = new DatabaseRuleManager(jsonMapper,
            scheduledExecutorFactory.create(1, "DatabaseRuleManager-Exec--%d"), databaseRuleManagerConfig, dbi);

    final ScheduledExecutorService globalScheduledExec = scheduledExecutorFactory.create(1, "Global--%d");
    final List<Monitor> monitors = Lists.newArrayList();
    monitors.add(new JvmMonitor());
    if (Boolean.parseBoolean(props.getProperty("druid.monitoring.monitorSystem", "false"))) {
        monitors.add(new SysMonitor());
    }

    final MonitorScheduler healthMonitor = new MonitorScheduler(
            configFactory.build(MonitorSchedulerConfig.class), globalScheduledExec, emitter, monitors);
    lifecycle.addManagedInstance(healthMonitor);

    final DruidMasterConfig druidMasterConfig = configFactory.build(DruidMasterConfig.class);

    final ServiceDiscovery serviceDiscovery = Initialization
            .makeServiceDiscoveryClient(serviceDiscoveryCuratorFramework, serviceDiscoveryConfig, lifecycle);
    final ServiceAnnouncer serviceAnnouncer = Initialization.makeServiceAnnouncer(serviceDiscoveryConfig,
            serviceDiscovery);
    Initialization.announceDefaultService(serviceDiscoveryConfig, serviceAnnouncer, lifecycle);

    ServiceProvider serviceProvider = null;
    if (druidMasterConfig.getMergerServiceName() != null) {
        serviceProvider = Initialization.makeServiceProvider(druidMasterConfig.getMergerServiceName(),
                serviceDiscovery, lifecycle);
    }
    IndexingServiceClient indexingServiceClient = new IndexingServiceClient(httpClient, jsonMapper,
            serviceProvider);

    final ConfigManagerConfig configManagerConfig = configFactory.build(ConfigManagerConfig.class);
    DbConnector.createConfigTable(dbi, configManagerConfig.getConfigTable());
    JacksonConfigManager configManager = new JacksonConfigManager(new ConfigManager(dbi, configManagerConfig),
            jsonMapper);

    final LoadQueueTaskMaster taskMaster = new LoadQueueTaskMaster(curatorFramework, jsonMapper,
            scheduledExecutorFactory.create(1, "Master-PeonExec--%d"), druidMasterConfig);

    final DruidMaster master = new DruidMaster(druidMasterConfig, zkPaths, configManager,
            databaseSegmentManager, serverInventoryView, databaseRuleManager, curatorFramework, emitter,
            scheduledExecutorFactory, indexingServiceClient, taskMaster);
    lifecycle.addManagedInstance(master);

    try {
        lifecycle.start();
    } catch (Throwable t) {
        log.error(t, "Error when starting up.  Failing.");
        System.exit(1);
    }

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            log.info("Running shutdown hook");
            lifecycle.stop();
        }
    }));

    final Injector injector = Guice
            .createInjector(new MasterServletModule(serverInventoryView, databaseSegmentManager,
                    databaseRuleManager, master, jsonMapper, indexingServiceClient, configManager));

    final Server server = Initialization.makeJettyServer(configFactory.build(ServerConfig.class));

    final RedirectInfo redirectInfo = new RedirectInfo() {
        @Override
        public boolean doLocal() {
            return master.isClusterMaster();
        }

        @Override
        public URL getRedirectURL(String queryString, String requestURI) {
            try {
                final String currentMaster = master.getCurrentMaster();
                if (currentMaster == null) {
                    return null;
                }

                String location = String.format("http://%s%s", currentMaster, requestURI);

                if (queryString != null) {
                    location = String.format("%s?%s", location, queryString);
                }

                return new URL(location);
            } catch (Exception e) {
                throw Throwables.propagate(e);
            }
        }
    };

    final Context staticContext = new Context(server, "/static", Context.SESSIONS);
    staticContext.addServlet(new ServletHolder(new RedirectServlet(redirectInfo)), "/*");

    staticContext.setResourceBase(ComputeMain.class.getClassLoader().getResource("static").toExternalForm());

    final Context root = new Context(server, "/", Context.SESSIONS);
    root.addServlet(new ServletHolder(new StatusServlet()), "/status");
    root.addServlet(new ServletHolder(new DefaultServlet()), "/*");
    root.addEventListener(new GuiceServletConfig(injector));
    root.addFilter(GzipFilter.class, "/*", 0);
    root.addFilter(
            new FilterHolder(new RedirectFilter(new ToStringResponseHandler(Charsets.UTF_8), redirectInfo)),
            "/*", 0);
    root.addFilter(GuiceFilter.class, "/info/*", 0);
    root.addFilter(GuiceFilter.class, "/master/*", 0);

    server.start();
    server.join();
}

From source file:com.metamx.druid.indexing.common.RetryPolicy.java

License:Open Source License

public Duration getAndIncrementRetryDelay() {
    Duration retVal = new Duration(currRetryDelay);
    currRetryDelay = new Duration(Math.min(currRetryDelay.getMillis() * 2, MAX_RETRY_DURATION.getMillis()));
    retryCount++;// w w w .ja v a2s .  c  o m
    return retVal;
}