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.vaushell.shaarlijavaapi.Examples.java

License:Open Source License

/**
 * Show how we use a term filter./*from ww w.j a v a  2  s. c  o  m*/
 *
 * @throws IOException
 */
private static void searchTermExample() throws IOException {
    try (final ShaarliClient client = new ShaarliClient(ENDPOINT)) {
        if (!client.login(LOGIN, PASSWORD)) {
            throw new IOException("Login error");
        }

        // Create 10 links
        DateTime t = new DateTime();
        for (int i = 0; i < 10; ++i) {
            final TreeSet<String> tags = new TreeSet<>();
            tags.add("java" + i);
            tags.add("coding");

            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 (with tags filter)
        final Iterator<ShaarliLink> iterator = client.searchTermIterator("Blog");
        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 use a term filter and get page 1.
 *
 * @throws IOException//from   w  w w .j  a v  a 2s  .c  o m
 */
private static void searchTermPage1example() throws IOException {
    try (final ShaarliClient client = new ShaarliClient(ENDPOINT)) {
        if (!client.login(LOGIN, PASSWORD)) {
            throw new IOException("Login error");
        }

        // Create 10 links
        DateTime t = new DateTime();
        for (int i = 0; i < 10; ++i) {
            final TreeSet<String> tags = new TreeSet<>();
            tags.add("java" + i);
            tags.add("coding");

            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.searchTerm(1, "Blog")) {
            System.out.println(link);
        }
    }
}

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

License:Open Source License

/**
 * Show how we use a tags filter./*from w w w.  ja va2  s . c om*/
 *
 * @throws IOException
 */
private static void searchTagsExample() throws IOException {
    try (final ShaarliClient client = new ShaarliClient(ENDPOINT)) {
        if (!client.login(LOGIN, PASSWORD)) {
            throw new IOException("Login error");
        }

        // Create 10 links
        DateTime t = new DateTime();
        for (int i = 0; i < 10; ++i) {
            final TreeSet<String> tags = new TreeSet<>();
            tags.add("java" + i);
            tags.add("coding");

            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 (with tags filter)
        final Iterator<ShaarliLink> iterator = client.searchTagsIterator("coding", "java2");
        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 use a tags filter and get page 1.
 *
 * @throws IOException//from   w ww.j a va  2 s. c  o m
 */
private static void searchTagsPage1Example() throws IOException {
    try (final ShaarliClient client = new ShaarliClient(ENDPOINT)) {
        if (!client.login(LOGIN, PASSWORD)) {
            throw new IOException("Login error");
        }

        // Create 10 links
        DateTime t = new DateTime();
        for (int i = 0; i < 10; ++i) {
            final TreeSet<String> tags = new TreeSet<>();
            tags.add("java" + i);
            tags.add("coding");

            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.searchTags(1, "coding", "java2")) {
            System.out.println(link);
        }
    }
}

From source file:com.vmware.demo.SamlGenerator.java

License:Open Source License

/**
 * Generate a Saml assertion for the given audienct, recipient and destination.
 * The attributes and remote user will be present in the assertion.
 *
 * @param samlAttributes to include in the Saml assertion
 * @param remoteUser is the username as passed in assertion, cannot be null
 *///ww  w.j a va 2  s  .com
public String generateSaml(String remoteUser, List<SamlAttribute> samlAttributes, String responseId,
        String audienceUri, String recipient, String destination, boolean signResponse, boolean signAssertion,
        boolean issuerInAssertion) throws SamlException {

    DateTime now = new DateTime();

    Assertion assertion = assertionBuilder.buildObject();
    assertion.setVersion(SAMLVersion.VERSION_20);

    if (null == remoteUser) {
        throw new SamlException("Remote user cannot be null when generating assertion.");
    }

    // Generate a new random id
    assertion.setID(idGenerator.generateIdentifier());
    assertion.setIssueInstant(now);

    // Set issuer
    Issuer issuer = issuerBuilder.buildObject();
    issuer.setValue(issuerName);

    // Issuer can be forced into assertion, or is automatically included if not signing response
    if (!signResponse || issuerInAssertion) {
        assertion.setIssuer(issuer);
    }

    AuthnStatement authnStmt = authnStatementBuilder.buildObject();
    authnStmt.setAuthnInstant(now);
    authnStmt.setSessionIndex(idGenerator.generateIdentifier());
    AuthnContext authnContext = (AuthnContext) buildXMLObject(AuthnContext.DEFAULT_ELEMENT_NAME);
    AuthnContextClassRef classRef = (AuthnContextClassRef) buildXMLObject(
            AuthnContextClassRef.DEFAULT_ELEMENT_NAME);
    classRef.setAuthnContextClassRef(AuthnContext.PPT_AUTHN_CTX);
    authnContext.setAuthnContextClassRef(classRef);
    authnStmt.setAuthnContext(authnContext);
    assertion.getAuthnStatements().add(authnStmt);
    NameID nameID = nameIDBuilder.buildObject();
    nameID.setNameQualifier(idpMetaDataURL);
    nameID.setValue(remoteUser);
    nameID.setFormat(SAML_NAMEID_FORMAT);
    Subject subject = (Subject) buildXMLObject(Subject.DEFAULT_ELEMENT_NAME);
    subject.setNameID(nameID);
    assertion.setSubject(subject);

    AttributeStatement attributeStatement = (AttributeStatement) buildXMLObject(
            AttributeStatement.DEFAULT_ELEMENT_NAME);
    for (SamlAttribute samlAttribute : samlAttributes) {
        Attribute attribute = (Attribute) buildXMLObject(Attribute.DEFAULT_ELEMENT_NAME);
        attribute.setName(samlAttribute.getName());
        attribute.setNameFormat(Attribute.BASIC);
        for (String value : samlAttribute.getValues()) {
            XSString xss = (XSString) stringBuilder.buildObject(AttributeValue.DEFAULT_ELEMENT_NAME,
                    XSString.TYPE_NAME);
            xss.setValue(value);
            attribute.getAttributeValues().add(xss);
        }
        attributeStatement.getAttributes().add(attribute);
    }
    assertion.getAttributeStatements().add(attributeStatement);

    Audience audience = (Audience) buildXMLObject(Audience.DEFAULT_ELEMENT_NAME);
    audience.setAudienceURI(audienceUri);

    AudienceRestriction ar = (AudienceRestriction) buildXMLObject(AudienceRestriction.DEFAULT_ELEMENT_NAME);
    ar.getAudiences().add(audience);

    Conditions conditions = (Conditions) buildXMLObject(Conditions.DEFAULT_ELEMENT_NAME);
    conditions.getAudienceRestrictions().add(ar);
    conditions.setNotBefore(now.minusSeconds(SAML_DRIFT));
    conditions.setNotOnOrAfter(now.plusSeconds(SAML_VALIDITY));

    assertion.setConditions(conditions);
    SubjectConfirmation subjConf = subjConfBuilder.buildObject();
    subjConf.setMethod(SUBJCONF_METHOD);
    QName qname = new QName(SAMLConstants.SAML20_NS, SubjectConfirmationData.DEFAULT_ELEMENT_LOCAL_NAME,
            SAMLConstants.SAML20_PREFIX);
    SubjectConfirmationData subjectCD = (SubjectConfirmationData) buildXMLObject(qname);
    subjectCD.setRecipient(recipient);
    subjectCD.setNotOnOrAfter(now.plusSeconds(SAML_VALIDITY));
    //see if this saml is in response to an authnrequest
    if (responseId != null) {
        subjectCD.setInResponseTo(responseId);
    }
    subjConf.setSubjectConfirmationData(subjectCD);
    assertion.getSubject().getSubjectConfirmations().add(subjConf);

    Response response = (Response) buildXMLObject(Response.DEFAULT_ELEMENT_NAME);
    Status status = (Status) buildXMLObject(Status.DEFAULT_ELEMENT_NAME);
    StatusCode statusCode = (StatusCode) buildXMLObject(StatusCode.DEFAULT_ELEMENT_NAME);
    statusCode.setValue(StatusCode.SUCCESS_URI);
    status.setStatusCode(statusCode);
    response.setStatus(status);
    response.setID(idGenerator.generateIdentifier());
    response.setIssueInstant(now);
    if (responseId != null) {
        response.setInResponseTo(responseId);
    }

    if (null != destination) {
        response.setDestination(destination);
    }

    Marshaller marshaller = null;
    if (signAssertion) {
        Signature signature = signatureBuilder.buildObject();
        signature.setSigningCredential(basicCredential);
        signature.setCanonicalizationAlgorithm(CANON_ALGORITHM);
        signature.setSignatureAlgorithm(SIGNATURE_METHOD);

        assertion.setSignature(signature);

        marshaller = marshallerFactory.getMarshaller(assertion);
        try {
            marshaller.marshall(assertion);
        } catch (MarshallingException e) {
            throw new SamlException("Failed to marshall assertion.", e);
        }

        try {
            Signer.signObject(signature);
        } catch (SignatureException e) {
            throw new SamlException("Failed to sign assertion.", e);
        }

        response.getAssertions().add(assertion);
    }

    if (signResponse) {
        Signature signature = signatureBuilder.buildObject();
        signature.setSigningCredential(basicCredential);
        signature.setCanonicalizationAlgorithm(CANON_ALGORITHM);
        signature.setSignatureAlgorithm(SIGNATURE_METHOD);

        // Allow issuer to be in the response, if forced
        // (e.g. don't put the issuer in the response, per the SAML spec, if the override says put it in the assertion)
        if (!issuerInAssertion) {
            response.setIssuer(issuer);
        }

        response.getAssertions().add(assertion);
        response.setSignature(signature);

        marshaller = marshallerFactory.getMarshaller(response);
        try {
            marshaller.marshall(response);
        } catch (MarshallingException e) {
            throw new SamlException("Failed to marshall response.", e);
        }

        try {
            Signer.signObject(signature);
        } catch (SignatureException e) {
            throw new SamlException("Failed to sign response.", e);
        }
    }

    marshaller = marshallerFactory.getMarshaller(response);
    Element messageDOM = null;
    try {
        messageDOM = marshaller.marshall(response);
    } catch (MarshallingException e) {
        throw new SamlException("Failed to re-marshall response.", e);
    }
    StringWriter writer = new StringWriter();
    XMLHelper.writeNode(messageDOM, writer);

    return Base64.encodeBytes(writer.toString().getBytes(SamlGenerator.CHARSET_UTF8), Base64.DONT_BREAK_LINES);
}

From source file:controllers.lib.Watchdog.java

License:Open Source License

private static boolean executeWatchdog() throws Exception {
    List<models.Websocket> websockets = models.Websocket.find.all();
    Iterator<models.Websocket> websocketsiterator = websockets.iterator();
    ActorRef akkaActor;//  w w  w . ja v a2  s.c o m

    while (websocketsiterator.hasNext()) {
        models.Websocket websocket = websocketsiterator.next();

        // Define actorRef -> empty ref -> teminated
        akkaActor = Akka.system().actorFor(websocket.path);

        // First check is if websocket avaible in akka --- GarbageCollection :)

        if (akkaActor.isTerminated()) {
            websocket.delete();
            continue;
        }

        // Date with duration and offset 15 sec
        try {
            DateTime slideTime = websocket.updateTime;
            slideTime = slideTime.plusSeconds(websocket.slide.duration).plusSeconds(10);
            DateTime nowTime = new DateTime();
            if (slideTime.isBefore(nowTime)) {
                ++websocket.warnings;
                websocket.update();
            }
        } catch (NullPointerException exception) {
            // Case updateTime oder slide is NULL
            ++websocket.warnings;
            websocket.update();
        }

        //System.out.println("Websocket  : " + websocket.websocket_id);
        //System.out.println("Slide      : " + websocket.slide.name);
        //System.out.println("NowTime    : " + nowTime);
        //System.out.println("SlideTime  : " + slideTime);
        //System.out.println("Problem    : " + (slideTime.before(nowTime)));
        //System.out.println("--------------------------------------");

        // Increment ErrorCount from websocket
        if (websocket.warnings > 0) {
            // What todo
            switch (websocket.warnings) {
            case 1:
                // Send Mail 
                break;

            case 2:
            case 3:
                // Reload Client
                ObjectNode message = Json.newObject();
                message.put("event", 2);
                message.put("data", "");
                // Send Reload Event
                akkaActor.tell(message.toString(), null);
                break;

            case 4:
            case 5:
                // Kill Connection and establish new connection
                akkaActor.tell(PoisonPill.getInstance(), null);
                break;

            default:
                // Send Mail
            }
        }
    }
    return true;
}

From source file:ddf.catalog.source.solr.provider.SolrProviderTestBase.java

License:Open Source License

Date dateAfterNow(DateTime now) {
    return now.plusSeconds(A_LITTLE_WHILE).toDate();
}

From source file:ddf.catalog.source.solr.provider.SolrProviderTestUtil.java

License:Open Source License

public static Date dateAfterNow(DateTime now) {
    return now.plusSeconds(A_LITTLE_WHILE).toDate();
}

From source file:ddf.catalog.source.solr.SolrProviderTestCase.java

License:Open Source License

protected Date dateAfterNow(DateTime now) {
    return now.plusSeconds(A_LITTLE_WHILE).toDate();
}

From source file:de.azapps.mirakel.sync.taskwarrior.model.TaskWarriorTaskSerializer.java

License:Open Source License

@Override
public JsonElement serialize(final Task src, final Type typeOfSrc, final JsonSerializationContext context) {
    final JsonObject json = new JsonObject();
    final Map<String, String> additionals = src.getAdditionalEntries();
    boolean isMaster = false;
    if (src.getRecurrence().isPresent()) {
        if (new MirakelQueryBuilder(mContext).and(Recurring.CHILD, Operation.EQ, src)
                .count(MirakelInternalContentProvider.RECURRING_TW_URI) == 0) {
            isMaster = true;/*from   w  w w. j av  a2s .  c  o m*/
        }
    }
    final Pair<String, String> statusEnd = getStatus(src, isMaster);
    final String status = statusEnd.second;
    final String end = statusEnd.first;
    String priority = null;
    switch (src.getPriority()) {
    case -2:
    case -1:
        priority = "L";
        break;
    case 1:
        priority = "M";
        break;
    case 2:
        priority = "H";
        break;
    default:
        break;
    }
    String uuid = src.getUUID();
    if (uuid.trim().isEmpty()) {
        uuid = java.util.UUID.randomUUID().toString();
        src.setUUID(uuid);
        src.save(false);
    }
    json.addProperty("uuid", uuid);
    json.addProperty("status", status);
    json.addProperty("entry", formatCal(src.getCreatedAt()));
    json.addProperty("description", src.getName());
    if (src.getDue().isPresent()) {
        json.addProperty("due", formatCal(src.getDue().get()));
    }
    if (!src.containsAdditional(Task.NO_PROJECT)) {
        json.addProperty("project", src.getList().getName());
    }
    if (priority != null) {
        json.addProperty("priority", priority);
        if ("L".equals(priority) && (src.getPriority() != -2)) {
            json.addProperty("priorityNumber", src.getPriority());
        }
    }
    json.addProperty("modified", formatCal(src.getUpdatedAt()));
    if (src.getReminder().isPresent()) {
        json.addProperty("reminder", formatCal(src.getReminder().get()));
    }
    if (end != null) {
        json.addProperty("end", end);
    }
    if (src.getProgress() != 0) {
        json.addProperty("progress", src.getProgress());
    }
    // Tags
    if (!src.getTags().isEmpty()) {
        final JsonArray tags = new JsonArray();
        for (final Tag t : src.getTags()) {
            // taskwarrior does not like whitespaces
            tags.add(new JsonPrimitive(t.getName().trim().replace(" ", "_")));
        }
        json.add("tags", tags);
    }
    // End Tags
    // Annotations
    if (!src.getContent().isEmpty()) {
        final JsonArray annotations = new JsonArray();
        /*
         * An annotation in taskd is a line of content in Mirakel!
         */
        final String annotationsList[] = src.getContent().split("\n");
        DateTime updatedAt = src.getUpdatedAt();
        for (final String a : annotationsList) {
            final JsonObject line = new JsonObject();
            line.addProperty("entry", formatCal(updatedAt));
            line.addProperty("description", a.replace("\n", ""));
            annotations.add(line);
            updatedAt = updatedAt.plusSeconds(1);
        }
        json.add("annotations", annotations);
    }
    // Anotations end
    // TW.depends==Mirakel.subtasks!
    // Dependencies
    if (src.countSubtasks() > 0L) {
        boolean first1 = true;
        final List<Task> subTasks = src.getSubtasks();
        final StringBuilder depends = new StringBuilder(subTasks.size() * 10);
        for (final Task subtask : subTasks) {
            if (first1) {
                first1 = false;
            } else {
                depends.append(',');
            }
            depends.append(subtask.getUUID());
        }
        json.addProperty("depends", depends.toString());
    }
    // recurring tasks must have a due
    if (src.getRecurrence().isPresent() && src.getDue().isPresent()) {
        handleRecurrence(json, src.getRecurrence().get());
        if (isMaster) {
            final Cursor cursor = mContext.getContentResolver().query(
                    MirakelInternalContentProvider.RECURRING_TW_URI, new String[] { "child", "offsetCount" },
                    "parent=?", new String[] { String.valueOf(src.getId()) }, "offsetCount ASC");
            final StringBuilder mask = new StringBuilder(cursor.getCount());
            cursor.moveToFirst();
            if (cursor.getCount() > 0) {
                int oldOffset = -1;
                do {
                    final int currentOffset = cursor.getInt(1);
                    if (currentOffset <= oldOffset) {
                        final long childId = cursor.getLong(0);
                        // This should not happen  it means that one offset is twice in the DB
                        final Optional<Task> child = Task.get(childId, true);
                        if (child.isPresent()) {
                            child.get().destroy(true);
                        } else {
                            // Whoa there is some garbage which we should destroy!
                            Task.destroyRecurrenceGarbageForTask(childId);
                        }
                        continue;
                    }
                    while (++oldOffset < currentOffset) {
                        mask.append('X');
                    }
                    final Optional<Task> child = Task.get(cursor.getLong(0));
                    if (!child.isPresent()) {
                        Log.wtf(TAG, "childtask is null");
                        mask.append('X');
                    } else {
                        mask.append(getRecurrenceStatus(getStatus(child.get(), false).second));
                    }
                } while (cursor.moveToNext());
            }
            cursor.close();
            json.addProperty("mask", mask.toString());
        } else {
            final Cursor cursor = mContext.getContentResolver().query(
                    MirakelInternalContentProvider.RECURRING_TW_URI, new String[] { "parent", "offsetCount" },
                    "child=?", new String[] { String.valueOf(src.getId()) }, null);
            cursor.moveToFirst();
            if (cursor.getCount() > 0) {
                final Optional<Task> master = Task.get(cursor.getLong(0));
                if (!master.isPresent()) {
                    // The parent is gone. This should not happen and we
                    // should delete the child then
                    src.destroy();
                } else {
                    json.addProperty("parent", master.get().getUUID());
                    json.addProperty("imask", cursor.getInt(1));
                }
            } else {
                Log.wtf(TAG, "no master found, but there must be a master");
            }
            cursor.close();
        }
    }
    // end Dependencies
    // Additional Strings
    for (final Map.Entry<String, String> entry : additionals.entrySet()) {
        if (!entry.getKey().equals(Task.NO_PROJECT) && !"status".equals(entry.getKey())) {
            json.addProperty(entry.getKey(), cleanQuotes(entry.getValue()));
        }
    }
    // end Additional Strings
    return json;
}