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:io.druid.security.basic.authorization.db.cache.CoordinatorPollingBasicAuthorizerCacheManager.java

License:Apache License

@LifecycleStart
public void start() {
    if (!lifecycleLock.canStart()) {
        throw new ISE("can't start.");
    }/*from www  .  ja v a  2 s  .co m*/

    LOG.info("Starting CoordinatorPollingBasicAuthorizerCacheManager.");

    try {
        initUserMaps();

        ScheduledExecutors.scheduleWithFixedDelay(exec, new Duration(commonCacheConfig.getPollingPeriod()),
                new Duration(commonCacheConfig.getPollingPeriod()), () -> {
                    try {
                        long randomDelay = ThreadLocalRandom.current().nextLong(0,
                                commonCacheConfig.getMaxRandomDelay());
                        LOG.debug("Inserting random polling delay of [%s] ms", randomDelay);
                        Thread.sleep(randomDelay);

                        LOG.debug("Scheduled cache poll is running");
                        for (String authorizerPrefix : authorizerPrefixes) {
                            UserAndRoleMap userAndRoleMap = fetchUserAndRoleMapFromCoordinator(authorizerPrefix,
                                    false);
                            if (userAndRoleMap != null) {
                                cachedUserMaps.put(authorizerPrefix, userAndRoleMap.getUserMap());
                                cachedRoleMaps.put(authorizerPrefix, userAndRoleMap.getRoleMap());
                            }
                        }
                        LOG.debug("Scheduled cache poll is done");
                    } catch (Throwable t) {
                        LOG.makeAlert(t, "Error occured while polling for cachedUserMaps.").emit();
                    }
                });

        lifecycleLock.started();
        LOG.info("Started CoordinatorPollingBasicAuthorizerCacheManager.");
    } finally {
        lifecycleLock.exitStart();
    }
}

From source file:io.druid.security.basic.authorization.db.updater.CoordinatorBasicAuthorizerMetadataStorageUpdater.java

License:Apache License

@LifecycleStart
public void start() {
    if (!lifecycleLock.canStart()) {
        throw new ISE("can't start.");
    }// ww w .j  a v  a  2s  . c om

    if (authorizerMapper == null || authorizerMapper.getAuthorizerMap() == null) {
        return;
    }

    try {
        LOG.info("Starting CoordinatorBasicAuthorizerMetadataStorageUpdater");
        for (Map.Entry<String, Authorizer> entry : authorizerMapper.getAuthorizerMap().entrySet()) {
            Authorizer authorizer = entry.getValue();
            if (authorizer instanceof BasicRoleBasedAuthorizer) {
                String authorizerName = entry.getKey();
                authorizerNames.add(authorizerName);
                BasicRoleBasedAuthorizer basicRoleBasedAuthorizer = (BasicRoleBasedAuthorizer) authorizer;

                byte[] userMapBytes = getCurrentUserMapBytes(authorizerName);
                Map<String, BasicAuthorizerUser> userMap = BasicAuthUtils
                        .deserializeAuthorizerUserMap(objectMapper, userMapBytes);
                cachedUserMaps.put(authorizerName, new BasicAuthorizerUserMapBundle(userMap, userMapBytes));

                byte[] roleMapBytes = getCurrentRoleMapBytes(authorizerName);
                Map<String, BasicAuthorizerRole> roleMap = BasicAuthUtils
                        .deserializeAuthorizerRoleMap(objectMapper, roleMapBytes);
                cachedRoleMaps.put(authorizerName, new BasicAuthorizerRoleMapBundle(roleMap, roleMapBytes));

                initSuperusers(authorizerName, userMap, roleMap);
            }
        }

        ScheduledExecutors.scheduleWithFixedDelay(exec, new Duration(commonCacheConfig.getPollingPeriod()),
                new Duration(commonCacheConfig.getPollingPeriod()), new Callable<ScheduledExecutors.Signal>() {
                    @Override
                    public ScheduledExecutors.Signal call() throws Exception {
                        if (stopped) {
                            return ScheduledExecutors.Signal.STOP;
                        }
                        try {
                            LOG.debug("Scheduled db poll is running");
                            for (String authorizerName : authorizerNames) {

                                byte[] userMapBytes = getCurrentUserMapBytes(authorizerName);
                                Map<String, BasicAuthorizerUser> userMap = BasicAuthUtils
                                        .deserializeAuthorizerUserMap(objectMapper, userMapBytes);
                                if (userMapBytes != null) {
                                    synchronized (cachedUserMaps) {
                                        cachedUserMaps.put(authorizerName,
                                                new BasicAuthorizerUserMapBundle(userMap, userMapBytes));
                                    }
                                }

                                byte[] roleMapBytes = getCurrentRoleMapBytes(authorizerName);
                                Map<String, BasicAuthorizerRole> roleMap = BasicAuthUtils
                                        .deserializeAuthorizerRoleMap(objectMapper, roleMapBytes);
                                if (roleMapBytes != null) {
                                    synchronized (cachedUserMaps) {
                                        cachedRoleMaps.put(authorizerName,
                                                new BasicAuthorizerRoleMapBundle(roleMap, roleMapBytes));
                                    }
                                }
                            }
                            LOG.debug("Scheduled db poll is done");
                        } catch (Throwable t) {
                            LOG.makeAlert(t, "Error occured while polling for cachedUserMaps.").emit();
                        }
                        return ScheduledExecutors.Signal.REPEAT;
                    }
                });

        lifecycleLock.started();
    } finally {
        lifecycleLock.exitStart();
    }
}

From source file:io.druid.server.coordinator.DruidCoordinatorConfig.java

License:Apache License

@Config("druid.coordinator.load.timeout")
public Duration getLoadTimeoutDelay() {
    return new Duration(15 * 60 * 1000);
}

From source file:io.druid.server.coordinator.HttpLoadQueuePeon.java

License:Apache License

private void doSegmentManagement() {
    if (stopped || !mainLoopInProgress.compareAndSet(false, true)) {
        log.debug("[%s]Ignoring tick. Either in-progress already or stopped.", serverId);
        return;//  ww  w .  j a v  a2 s. c  o m
    }

    int batchSize = config.getHttpLoadQueuePeonBatchSize();

    List<DataSegmentChangeRequest> newRequests = new ArrayList<>(batchSize);

    synchronized (lock) {
        Iterator<Map.Entry<DataSegment, SegmentHolder>> iter = Iterators
                .concat(segmentsToDrop.entrySet().iterator(), segmentsToLoad.entrySet().iterator());

        while (batchSize > 0 && iter.hasNext()) {
            batchSize--;
            Map.Entry<DataSegment, SegmentHolder> entry = iter.next();
            if (entry.getValue().hasTimedOut()) {
                entry.getValue().requestFailed("timed out");
                iter.remove();
            } else {
                newRequests.add(entry.getValue().getChangeRequest());
            }
        }
    }

    if (newRequests.size() == 0) {
        log.debug("[%s]Found no load/drop requests. SegmentsToLoad[%d], SegmentsToDrop[%d], batchSize[%d].",
                serverId, segmentsToLoad.size(), segmentsToDrop.size(), config.getHttpLoadQueuePeonBatchSize());
        mainLoopInProgress.set(false);
        return;
    }

    try {
        log.debug("Sending [%d] load/drop requests to Server[%s].", newRequests.size(), serverId);
        BytesAccumulatingResponseHandler responseHandler = new BytesAccumulatingResponseHandler();
        ListenableFuture<InputStream> future = httpClient.go(
                new Request(HttpMethod.POST, changeRequestURL)
                        .addHeader(HttpHeaders.Names.ACCEPT, MediaType.APPLICATION_JSON)
                        .addHeader(HttpHeaders.Names.CONTENT_TYPE, MediaType.APPLICATION_JSON)
                        .setContent(requestBodyWriter.writeValueAsBytes(newRequests)),
                responseHandler, new Duration(config.getHttpLoadQueuePeonHostTimeout().getMillis() + 5000));

        Futures.addCallback(future, new FutureCallback<InputStream>() {
            @Override
            public void onSuccess(InputStream result) {
                boolean scheduleNextRunImmediately = true;
                try {
                    if (responseHandler.status == HttpServletResponse.SC_NO_CONTENT) {
                        log.debug("Received NO CONTENT reseponse from [%s]", serverId);
                    } else if (HttpServletResponse.SC_OK == responseHandler.status) {
                        try {
                            List<SegmentLoadDropHandler.DataSegmentChangeRequestAndStatus> statuses = jsonMapper
                                    .readValue(result, RESPONSE_ENTITY_TYPE_REF);
                            log.debug("Server[%s] returned status response [%s].", serverId, statuses);
                            synchronized (lock) {
                                if (stopped) {
                                    log.debug("Ignoring response from Server[%s]. We are already stopped.",
                                            serverId);
                                    scheduleNextRunImmediately = false;
                                    return;
                                }

                                for (SegmentLoadDropHandler.DataSegmentChangeRequestAndStatus e : statuses) {
                                    switch (e.getStatus().getState()) {
                                    case SUCCESS:
                                    case FAILED:
                                        handleResponseStatus(e.getRequest(), e.getStatus());
                                        break;
                                    case PENDING:
                                        log.info("Request[%s] is still pending on server[%s].", e.getRequest(),
                                                serverId);
                                        break;
                                    default:
                                        scheduleNextRunImmediately = false;
                                        log.error("WTF! Server[%s] returned unknown state in status[%s].",
                                                serverId, e.getStatus());
                                    }
                                }
                            }
                        } catch (Exception ex) {
                            scheduleNextRunImmediately = false;
                            logRequestFailure(ex);
                        }
                    } else {
                        scheduleNextRunImmediately = false;
                        logRequestFailure(new RE("Unexpected Response Status."));
                    }
                } finally {
                    mainLoopInProgress.set(false);

                    if (scheduleNextRunImmediately) {
                        processingExecutor.execute(HttpLoadQueuePeon.this::doSegmentManagement);
                    }
                }
            }

            @Override
            public void onFailure(Throwable t) {
                try {
                    logRequestFailure(t);
                } finally {
                    mainLoopInProgress.set(false);
                }
            }

            private void logRequestFailure(Throwable t) {
                log.error(t, "Request[%s] Failed with status[%s]. Reason[%s].", changeRequestURL,
                        responseHandler.status, responseHandler.description);
            }
        }, processingExecutor);
    } catch (Throwable th) {
        log.error(th, "Error sending load/drop request to [%s].", serverId);
        mainLoopInProgress.set(false);
    }
}

From source file:io.druid.server.coordinator.HttpLoadQueuePeon.java

License:Apache License

@Override
public void start() {
    synchronized (lock) {
        if (stopped) {
            throw new ISE("Can't start.");
        }//  ww w.  j a  v  a2  s. c  o  m

        ScheduledExecutors.scheduleAtFixedRate(processingExecutor,
                new Duration(config.getHttpLoadQueuePeonRepeatDelay()),
                new Callable<ScheduledExecutors.Signal>() {
                    @Override
                    public ScheduledExecutors.Signal call() {
                        if (!stopped) {
                            doSegmentManagement();
                        }

                        if (stopped) {
                            return ScheduledExecutors.Signal.STOP;
                        } else {
                            return ScheduledExecutors.Signal.REPEAT;
                        }
                    }
                });
    }
}

From source file:io.druid.server.log.FileRequestLogger.java

License:Apache License

@LifecycleStart
public void start() {
    try {/*from   w w w.j a v a 2s  .  c o  m*/
        baseDir.mkdirs();

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

        fileWriter = new OutputStreamWriter(
                new FileOutputStream(new File(baseDir, currentDay.toString("yyyy-MM-dd'.log'")), true),
                Charsets.UTF_8);
        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) {
                                CloseQuietly.close(fileWriter);
                                fileWriter = new OutputStreamWriter(
                                        new FileOutputStream(new File(baseDir, currentDay.toString()), true),
                                        Charsets.UTF_8);
                            }
                        } catch (Exception e) {
                            Throwables.propagate(e);
                        }

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

From source file:io.druid.server.master.DruidMasterConfig.java

License:Open Source License

@Config("druid.master.load.timeout")
public Duration getLoadTimeoutDelay() {
    return new Duration(15 * 60 * 1000);
}

From source file:io.druid.server.router.CoordinatorRuleManager.java

License:Apache License

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

        this.exec = Execs.scheduledSingleThreaded("CoordinatorRuleManager-Exec--%d");

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

        started = true;
    }
}

From source file:io.ehdev.android.drivingtime.view.dialog.InsertOrEditRecordDialog.java

License:Open Source License

private void setOKButton(AlertDialog.Builder builder) {
    builder.setPositiveButton(R.string.addRecord, new DialogInterface.OnClickListener() {
        @Override//from ww w  .jav a 2 s .c om
        public void onClick(DialogInterface dialog, int which) {
            Dialog thisDialog = InsertOrEditRecordDialog.this.getDialog();
            Task task = (Task) ((Spinner) thisDialog.findViewById(R.id.drivingTypeSpinner)).getSelectedItem();
            Long durationOfEntry = getDurationOfEntry(thisDialog);
            drivingRecord.setDrivingTask(task);
            drivingRecord.setStartTime(dateTimeForEntry);
            drivingRecord.setDurationOfDriving(new Duration(durationOfEntry));
            try {
                databaseHelper.getRecordDao().createOrUpdate(drivingRecord);
            } catch (Exception e) {
                Log.i(TAG, e.getMessage());
            }

            thisDialog.dismiss();
        }
    });
}

From source file:io.ehdev.android.drivingtime.view.dialog.InsertOrEditTaskDialog.java

License:Open Source License

private void setOKButton(AlertDialog.Builder builder) {
    builder.setPositiveButton(R.string.addRecord, new DialogInterface.OnClickListener() {
        @Override/*from   w  ww .  ja  va 2s.c om*/
        public void onClick(DialogInterface dialog, int which) {
            Dialog thisDialog = InsertOrEditTaskDialog.this.getDialog();
            String taskName = ((EditText) thisDialog.findViewById(R.id.taskName)).getText().toString();
            Long durationOfEntry = getDurationOfEntry(thisDialog);
            drivingTask.setTaskName(taskName);
            drivingTask.setRequiredHours(new Duration(durationOfEntry));
            try {
                databaseHelper.getTaskDao().createOrUpdate(drivingTask);
            } catch (Exception e) {
                Log.i(TAG, e.getMessage());
            }

            thisDialog.dismiss();
        }
    });
}