Example usage for org.joda.time DateTime plusSeconds

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

Introduction

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

Prototype

public DateTime plusSeconds(int seconds) 

Source Link

Document

Returns a copy of this datetime plus the specified number of seconds.

Usage

From source file:com.thinkbiganalytics.nifi.v2.init.InitializeFeed.java

License:Apache License

private void failed(ProcessContext context, ProcessSession session, String feedId, List<FlowFile> batch,
        DateTime failTime, boolean reinitializing) {
    String strategy = context.getProperty(FAILURE_STRATEGY).getValue();
    FlowFile inputFF = batch.stream().findFirst().get(); // batch size will always be > 0

    if (strategy.equals("RETRY")) {
        int delay = context.getProperty(RETRY_DELAY).evaluateAttributeExpressions(inputFF).asInteger();
        int max = context.getProperty(MAX_INIT_ATTEMPTS).evaluateAttributeExpressions(inputFF).asInteger();
        AtomicInteger count = getRetryCount(context, inputFF);

        if (count.getAndIncrement() >= max) {
            count.set(max);/*w w  w .ja  v a  2 s .c o  m*/
            session.transfer(inputFF, CommonProperties.REL_FAILURE);
        } else if (failTime.plusSeconds(delay).isBefore(DateTime.now(DateTimeZone.UTC))) {
            beginInitialization(context, session, feedId, batch, reinitializing);
            requeueFlowFiles(session, batch);
        } else {
            session.transfer(inputFF, CommonProperties.REL_FAILURE);
        }
    } else {
        session.transfer(inputFF, CommonProperties.REL_FAILURE);
    }
}

From source file:com.tomtom.speedtools.thread.WorkQueue.java

License:Apache License

/**
 * Start workload, or wait if there is too much workload in the queue.
 *
 * @param workLoad Workload to be started.
 * @param timeout  Timeout in millis. If there is no room left in the queue before this timeout expires, the
 *                 workload is discarded and not scheduled. Use 0 for wait 'forever'.
 *///from   w ww .  ja v a2 s. co m
@SuppressWarnings("CallToNotifyInsteadOfNotifyAll")
public void startOrWait(@Nonnull final Runnable workLoad, final long timeout) {
    assert timeout >= 0;
    assert !executor.isShutdown();
    assert Thread.currentThread().getId() == feederThread;

    final DateTime startTime = UTCTime.now();
    final long start = startTime.getMillis();
    DateTime nextDebugTime = startTime.plusSeconds(ISSUE_WAITING_LOG_LINE_AFTER_SECS);
    boolean scheduled = false;
    boolean again = false;
    int busyWait = BUSY_WAIT_MSECS_MIN;
    do {
        try {
            executor.execute(new RuntimeExceptionCatcher(workLoad));
            scheduled = true;
        } catch (final RejectedExecutionException ignored1) {
            assert !scheduled;
            try {
                //noinspection BusyWait
                Thread.sleep(busyWait);
                if (busyWait < BUSY_WAIT_MSECS_MAX) {
                    ++busyWait;
                }
                final DateTime now = UTCTime.now();
                final long timeWaiting = now.getMillis() - start;
                again = ((timeout == 0) || (timeWaiting < timeout));

                // Issue a log message only if timeout == 0 and task is rescheduled.
                if (again && (timeout == 0) && now.isAfter(nextDebugTime)) {
                    LOG.debug("startOrWait: workLoad not executed yet, already waiting {} secs...",
                            timeWaiting / 1000);
                    nextDebugTime = now.plusSeconds(ISSUE_WAITING_LOG_LINE_AFTER_SECS);
                }
            } catch (final InterruptedException ignored2) {
                assert !again;
            }
        }
    } while (!scheduled && again);
    if (!scheduled) {
        LOG.debug("startOrWait: workLoad was not scheduled, aborted after timeout={} msecs", timeout);
    }
}

From source file:com.tomtom.speedtools.thread.WorkQueue.java

License:Apache License

/**
 * Wait until the work pool finished executing all work load.
 *
 * @param timeout Max. wait time in msecs. Use 0 for 'forever'.
 * @return False if exceptions were caught during executing workload packages.
 *//*  www .jav  a2 s  .  c o m*/
public boolean waitUntilFinished(final long timeout) {
    assert timeout >= 0;
    assert !executor.isShutdown();
    assert Thread.currentThread().getId() == feederThread;

    LOG.debug("waitUntilFinished: shut down executor");
    executor.shutdown();

    final DateTime startTime = UTCTime.now();
    DateTime nextDebugTime = startTime.plusSeconds(ISSUE_WAITING_LOG_LINE_AFTER_SECS);
    boolean again = false;
    do {
        try {
            final DateTime now = UTCTime.now();
            if (now.isAfter(nextDebugTime)) {
                LOG.debug("waitUntilFinished: awaiting termination of executor for {} secs...",
                        (now.getMillis() - startTime.getMillis()) / 1000);
                nextDebugTime = now.plusSeconds(ISSUE_WAITING_LOG_LINE_AFTER_SECS);
            }
            again = !executor.awaitTermination((timeout == 0) ? ISSUE_WAITING_LOG_LINE_AFTER_SECS : timeout,
                    (timeout == 0) ? TimeUnit.SECONDS : TimeUnit.MILLISECONDS);
        } catch (final InterruptedException ignored) {
            // Ignored.
        }
    } while (again && (timeout == 0));
    LOG.debug("waitUntilFinished: executor terminated (creating new one)");

    /**
     *  Current pool is empty and done, get a new executor pool.
     *  Don't clear the exceptions list, as it is supposed to be the overall list for this
     *  WorkQueue instance (not fot the ThreadPoolExecutor instance).
     */
    executor = createNewExecutor();
    return exceptions.isEmpty();
}

From source file:com.tremolosecurity.provisioning.customTasks.CallRemoteWorkflow.java

License:Apache License

@Override
public boolean doTask(User user, Map<String, Object> request) throws ProvisioningException {

    HashMap<String, Object> newRequest = new HashMap<String, Object>();
    for (String name : this.fromRequest) {
        newRequest.put(name, request.get(name));
    }/*from  www.  ja  v a  2s .c o  m*/

    for (String key : this.staticRequest.keySet()) {
        newRequest.put(key, this.staticRequest.get(key));
    }

    WFCall wfCall = new WFCall();
    wfCall.setName(this.workflowName);
    wfCall.setRequestParams(newRequest);
    wfCall.setUser(new TremoloUser());
    wfCall.getUser().setUid(user.getUserID());
    wfCall.getUser().setUserPassword(user.getPassword());
    wfCall.getUser().setGroups(user.getGroups());
    wfCall.getUser().setAttributes(new ArrayList<Attribute>());
    wfCall.getUser().getAttributes().addAll(user.getAttribs().values());
    wfCall.setUidAttributeName(uidAttributeName);
    wfCall.setReason(task.getWorkflow().getUser().getRequestReason());
    if (task.getWorkflow().getRequester() != null) {
        wfCall.setRequestor(task.getWorkflow().getRequester().getUserID());
    } else {
        wfCall.setRequestor(this.lastMileUser);
    }

    DateTime notBefore = new DateTime();
    notBefore = notBefore.minusSeconds(timeSkew);
    DateTime notAfter = new DateTime();
    notAfter = notAfter.plusSeconds(timeSkew);

    com.tremolosecurity.lastmile.LastMile lastmile = null;

    try {
        lastmile = new com.tremolosecurity.lastmile.LastMile(this.uri, notBefore, notAfter, 0, "oauth2");

    } catch (URISyntaxException e) {
        throw new ProvisioningException("Could not generate lastmile", e);
    }

    Attribute attrib = new Attribute(this.lastMileUid, this.lastMileUser);
    lastmile.getAttributes().add(attrib);
    String encryptedXML = null;

    try {
        encryptedXML = lastmile
                .generateLastMileToken(this.task.getConfigManager().getSecretKey(this.lastmileKeyName));
    } catch (Exception e) {
        throw new ProvisioningException("Could not generate lastmile", e);
    }

    StringBuffer header = new StringBuffer();
    header.append("Bearer ").append(encryptedXML);

    BasicHttpClientConnectionManager bhcm = null;
    CloseableHttpClient http = null;

    try {
        bhcm = new BasicHttpClientConnectionManager(this.task.getConfigManager().getHttpClientSocketRegistry());

        RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).setRedirectsEnabled(false)
                .build();

        http = HttpClients.custom().setConnectionManager(bhcm).setDefaultRequestConfig(rc).build();

        HttpPost post = new HttpPost(this.url);
        post.addHeader(new BasicHeader("Authorization", header.toString()));

        Gson gson = new Gson();
        StringEntity str = new StringEntity(gson.toJson(wfCall), ContentType.APPLICATION_JSON);
        post.setEntity(str);

        HttpResponse resp = http.execute(post);
        if (resp.getStatusLine().getStatusCode() != 200) {
            throw new ProvisioningException("Call failed");
        }

    } catch (IOException e) {
        throw new ProvisioningException("Could not make call", e);
    } finally {
        if (http != null) {
            try {
                http.close();
            } catch (IOException e) {
                logger.warn(e);
            }
        }

        if (bhcm != null) {
            bhcm.close();
        }

    }

    return true;
}

From source file:com.tremolosecurity.provisioning.tasks.Approval.java

License:Apache License

public Approval(WorkflowTaskType taskConfig, ConfigManager cfg, Workflow wf) throws ProvisioningException {
    super(taskConfig, cfg, wf);

    this.approvers = new ArrayList<Approver>();
    this.azRules = new ArrayList<AzRule>();

    this.failed = false;

    ApprovalType att = (ApprovalType) taskConfig;

    for (AzRuleType azr : att.getApprovers().getRule()) {
        Approver approver = new Approver();

        if (azr.getScope().equalsIgnoreCase("filter")) {
            approver.type = ApproverType.Filter;
        } else if (azr.getScope().equalsIgnoreCase("group")) {
            approver.type = ApproverType.StaticGroup;
        } else if (azr.getScope().equalsIgnoreCase("dn")) {
            approver.type = ApproverType.DN;
        } else if (azr.getScope().equalsIgnoreCase("dynamicGroup")) {
            approver.type = ApproverType.DynamicGroup;
        } else if (azr.getScope().equalsIgnoreCase("custom")) {
            approver.type = ApproverType.Custom;

        }/* w  w w.ja  v  a  2  s  .c o  m*/

        approver.constraint = azr.getConstraint();

        setupCustomParameters(approver);

        this.approvers.add(approver);

        AzRule rule = new AzRule(azr.getScope(), azr.getConstraint(), azr.getClassName(), cfg, wf);

        this.azRules.add(rule);
        approver.customAz = rule.getCustomAuthorization();

    }

    this.label = att.getLabel();
    this.emailTemplate = att.getEmailTemplate();
    this.mailAttr = att.getMailAttr();
    this.failureEmailSubject = att.getFailureEmailSubject();
    this.failureEmailMsg = att.getFailureEmailMsg();

    this.escalationRules = new ArrayList<EscalationRule>();

    if (att.getEscalationPolicy() != null) {
        DateTime now = new DateTime();
        for (EscalationType ert : att.getEscalationPolicy().getEscalation()) {
            EscalationRule erule = new EsclationRuleImpl();

            DateTime when;

            if (ert.getExecuteAfterUnits().equalsIgnoreCase("sec")) {
                when = now.plusSeconds(ert.getExecuteAfterTime());
            } else if (ert.getExecuteAfterUnits().equals("min")) {
                when = now.plusMinutes(ert.getExecuteAfterTime());
            } else if (ert.getExecuteAfterUnits().equals("hr")) {
                when = now.plusHours(ert.getExecuteAfterTime());
            } else if (ert.getExecuteAfterUnits().equals("day")) {
                when = now.plusDays(ert.getExecuteAfterTime());
            } else if (ert.getExecuteAfterUnits().equals("wk")) {
                when = now.plusWeeks(ert.getExecuteAfterTime());
            } else {
                throw new ProvisioningException("Unknown time unit : " + ert.getExecuteAfterUnits());
            }

            erule.setCompleted(false);
            erule.setExecuteTS(when.getMillis());

            if (ert.getValidateEscalationClass() != null && !ert.getValidateEscalationClass().isEmpty()) {
                try {
                    erule.setVerify(
                            (VerifyEscalation) Class.forName(ert.getValidateEscalationClass()).newInstance());
                } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
                    throw new ProvisioningException("Could not initialize escalation rule", e);
                }
            } else {
                erule.setVerify(null);
            }

            erule.setAzRules(new ArrayList<AzRule>());
            for (AzRuleType azr : ert.getAzRules().getRule()) {
                Approver approver = new Approver();

                if (azr.getScope().equalsIgnoreCase("filter")) {
                    approver.type = ApproverType.Filter;
                } else if (azr.getScope().equalsIgnoreCase("group")) {
                    approver.type = ApproverType.StaticGroup;
                } else if (azr.getScope().equalsIgnoreCase("dn")) {
                    approver.type = ApproverType.DN;
                } else if (azr.getScope().equalsIgnoreCase("dynamicGroup")) {
                    approver.type = ApproverType.DynamicGroup;
                } else if (azr.getScope().equalsIgnoreCase("custom")) {
                    approver.type = ApproverType.Custom;
                }

                approver.constraint = azr.getConstraint();
                setupCustomParameters(approver);
                //this.approvers.add(approver);

                AzRule rule = new AzRule(azr.getScope(), azr.getConstraint(), azr.getClassName(), cfg, wf);

                erule.getAzRules().add(rule);
                approver.customAz = rule.getCustomAuthorization();

            }

            this.escalationRules.add(erule);
            now = when;
        }

        if (att.getEscalationPolicy().getEscalationFailure().getAction() != null) {
            switch (att.getEscalationPolicy().getEscalationFailure().getAction()) {
            case "leave":
                this.failureAzRules = null;
                this.failOnNoAZ = false;
                break;
            case "assign":
                this.failOnNoAZ = true;
                this.failureAzRules = new ArrayList<AzRule>();
                for (AzRuleType azr : att.getEscalationPolicy().getEscalationFailure().getAzRules().getRule()) {
                    Approver approver = new Approver();

                    if (azr.getScope().equalsIgnoreCase("filter")) {
                        approver.type = ApproverType.Filter;
                    } else if (azr.getScope().equalsIgnoreCase("group")) {
                        approver.type = ApproverType.StaticGroup;
                    } else if (azr.getScope().equalsIgnoreCase("dn")) {
                        approver.type = ApproverType.DN;
                    } else if (azr.getScope().equalsIgnoreCase("dynamicGroup")) {
                        approver.type = ApproverType.DynamicGroup;
                    } else if (azr.getScope().equalsIgnoreCase("custom")) {
                        approver.type = ApproverType.Custom;
                    }

                    approver.constraint = azr.getConstraint();
                    setupCustomParameters(approver);
                    //this.approvers.add(approver);

                    AzRule rule = new AzRule(azr.getScope(), azr.getConstraint(), azr.getClassName(), cfg, wf);

                    this.failureAzRules.add(rule);
                    approver.customAz = rule.getCustomAuthorization();

                }
                break;

            default:
                throw new ProvisioningException("Unknown escalation failure action : "
                        + att.getEscalationPolicy().getEscalationFailure().getAction());
            }

        }
    }

}

From source file:com.tremolosecurity.proxy.filters.CheckSession.java

License:Apache License

@Override
public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain)
        throws Exception {
    request.setAttribute("com.tremolosecurity.unison.proxy.noRedirectOnError",
            "com.tremolosecurity.unison.proxy.noRedirectOnError");
    ArrayList<Cookie> sessionCookies = request.getCookies(this.cookieName);
    if (sessionCookies == null || sessionCookies.isEmpty()) {
        response.sendError(401);/*from   w w  w.j  a  va2 s.  c om*/
    } else {
        for (Cookie cookie : sessionCookies) {
            TremoloHttpSession session = SessionManagerImpl.findSessionFromCookie(cookie, this.secretKey,
                    (SessionManagerImpl) GlobalEntries.getGlobalEntries()
                            .get(ProxyConstants.TREMOLO_SESSION_MANAGER));
            if (session == null) {
                response.sendError(401);
            } else {
                AuthInfo userData = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL))
                        .getAuthInfo();
                if (userData == null || !userData.isAuthComplete() || userData.getAuthLevel() == 0) {
                    response.sendError(401);
                } else {
                    SessionInfo si = new SessionInfo();
                    if (this.timeoutSeconds > 0) {
                        DateTime lastAccessed = (DateTime) session
                                .getAttribute(SessionManagerImpl.TREMOLO_SESSION_LAST_ACCESSED);
                        DateTime now = new DateTime();
                        DateTime expires = lastAccessed.plusSeconds(this.timeoutSeconds);

                        si.setMinsLeft((int) ((expires.getMillis() - System.currentTimeMillis()) / 1000 / 60));
                    } else {
                        si.setMinsLeft(-1);
                    }

                    String json = gson.toJson(si);
                    response.setContentType("application/json");
                    response.getWriter().println(json.trim());
                    response.sendError(200);
                }
            }
        }
    }
}

From source file:com.tremolosecurity.proxy.filters.LastMile.java

License:Apache License

@Override
public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain)
        throws Exception {

    DateTime notBefore = new DateTime();
    notBefore = notBefore.minusSeconds(timeScew);
    DateTime notAfter = new DateTime();
    notAfter = notAfter.plusSeconds(timeScew);

    AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL))
            .getAuthInfo();//w w w  .  java2 s  .  com

    com.tremolosecurity.lastmile.LastMile lastmile = new com.tremolosecurity.lastmile.LastMile(
            request.getRequestURI(), notBefore, notAfter, userData.getAuthLevel(), userData.getAuthChain());

    Iterator<String> it = this.headers.keySet().iterator();
    while (it.hasNext()) {
        String fromUser = it.next();
        String toApp = this.headers.get(fromUser);

        Attribute attrib = userData.getAttribs().get(fromUser);
        request.removeHeader(toApp);

        if (logger.isDebugEnabled()) {
            logger.debug("Header to add : " + fromUser);
        }

        if (attrib != null) {
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "Attribute " + fromUser + "='" + attrib.getValues() + "' for " + userData.getUserDN());
            }
            Attribute toAppAttrib = new Attribute(toApp);
            toAppAttrib.getValues().addAll(attrib.getValues());
            lastmile.getAttributes().add(toAppAttrib);
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("Attribute " + fromUser + " is not available for " + userData.getUserDN());
            }
        }
    }

    String encryptedXML = lastmile.generateLastMileToken(encKey);

    if (this.headerPrefix != null && !this.headerPrefix.isEmpty()) {
        StringBuffer b = new StringBuffer();
        b.append(this.headerPrefix).append(' ').append(encryptedXML);
        encryptedXML = b.toString();
    }

    request.addHeader(new Attribute(this.headerName, encryptedXML));

    //response.addHeader(this.headerName, requestKey.getEncrypted());

    chain.nextFilter(request, response, chain);

}

From source file:com.vaushell.shaarlijavaapi.Examples.java

License:Open Source License

/**
 * Show how we can get all tags.//  www  . ja v a 2 s . c om
 *
 * @throws IOException
 */
private static void tagsExample() throws IOException {
    try (final ShaarliClient client = new ShaarliClient(ENDPOINT)) {
        if (!client.login(LOGIN, PASSWORD)) {
            throw new IOException("Login error");
        }

        // Name tags
        final TreeSet<String> tags = new TreeSet<>();
        tags.add("java");
        tags.add("coding");

        // Create 10 links
        DateTime t = new DateTime();
        for (int i = 0; i < 10; ++i) {
            client.createOrUpdateLink(t, "http://fabien.vauchelles.com/" + i,
                    "Blog de Fabien Vauchelles n" + i, "Du coooodde rahhh::!!!!! #" + i, tags, false);

            t = t.plusSeconds(1);
        }

        // Get all tags
        for (final Entry<String, Integer> entryTag : client.getTags().entrySet()) {
            System.out.println("Tag: name=" + entryTag.getKey() + ", count=" + entryTag.getValue());
        }
    }
}

From source file:com.vaushell.shaarlijavaapi.Examples.java

License:Open Source License

/**
 * Show how we get all links./*  w ww  . jav  a  2  s.c o m*/
 *
 * @throws IOException
 */
private static void searchAllExample() throws IOException {
    try (final ShaarliClient client = new ShaarliClient(ENDPOINT)) {
        if (!client.login(LOGIN, PASSWORD)) {
            throw new IOException("Login error");
        }

        // Name tags
        final TreeSet<String> tags = new TreeSet<>();
        tags.add("java");
        tags.add("coding");

        // Create 10 links
        DateTime t = new DateTime();
        for (int i = 0; i < 10; ++i) {
            client.createOrUpdateLink(t, "http://fabien.vauchelles.com/" + i,
                    "Blog de Fabien Vauchelles n" + i, "Du coooodde rahhh::!!!!! #" + i, tags, false);

            t = t.plusSeconds(1);
        }

        // Iterate all links (without restriction)
        final Iterator<ShaarliLink> iterator = client.searchAllIterator();
        while (iterator.hasNext()) {
            final ShaarliLink link = iterator.next();

            System.out.println(link);
        }
    }
}

From source file:com.vaushell.shaarlijavaapi.Examples.java

License:Open Source License

/**
 * Show how we get all links on page 1./*  w  w  w  .  j  a va2s  .  c  o  m*/
 *
 * @throws IOException
 */
private static void searchAllPage1example() throws IOException {
    try (final ShaarliClient client = new ShaarliClient(ENDPOINT)) {
        if (!client.login(LOGIN, PASSWORD)) {
            throw new IOException("Login error");
        }

        // Name tags
        final TreeSet<String> tags = new TreeSet<>();
        tags.add("java");
        tags.add("coding");

        // Create 10 links
        DateTime t = new DateTime();
        for (int i = 0; i < 10; ++i) {
            client.createOrUpdateLink(t, "http://fabien.vauchelles.com/" + i,
                    "Blog de Fabien Vauchelles n" + i, "Du coooodde rahhh::!!!!! #" + i, tags, false);

            t = t.plusSeconds(1);
        }

        // Show only 2 links by page
        client.setLinksByPage(2);

        // Iterate all links (without restriction)
        for (final ShaarliLink link : client.searchAll(1)) {
            System.out.println(link);
        }
    }
}