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(ReadableInstant start, ReadableInstant end) 

Source Link

Document

Creates a duration from the given interval endpoints.

Usage

From source file:me.vertretungsplan.parser.ParserUtils.java

License:Mozilla Public License

static LocalDate parseDate(String string) {
    if (string == null)
        return null;
    reinitIfNeeded();/*  w w w.j  av  a  2  s  .c o  m*/

    string = string.replace("Stand:", "").replace("Import:", "").replaceAll(", Woche [A-Z]", "").trim();
    int i = 0;
    for (DateTimeFormatter f : dateFormatters) {
        try {
            LocalDate d = f.parseLocalDate(string);
            if (dateFormats[i].contains("yyyy")) {
                return d;
            } else {
                Duration currentYearDifference = abs(new Duration(DateTime.now(), d.toDateTimeAtCurrentTime()));
                Duration lastYearDifference = abs(
                        new Duration(DateTime.now(), d.minusYears(1).toDateTimeAtCurrentTime()));
                Duration nextYearDifference = abs(
                        new Duration(DateTime.now(), d.plusYears(1).toDateTimeAtCurrentTime()));
                if (lastYearDifference.isShorterThan(currentYearDifference)) {
                    return DateTimeFormat.forPattern(dateFormats[i]).withLocale(Locale.GERMAN)
                            .withDefaultYear(f.getDefaultYear() - 1).parseLocalDate(string);
                } else if (nextYearDifference.isShorterThan(currentYearDifference)) {
                    return DateTimeFormat.forPattern(dateFormats[i]).withLocale(Locale.GERMAN)
                            .withDefaultYear(f.getDefaultYear() + 1).parseLocalDate(string);
                } else {
                    return d;
                }
            }
        } catch (IllegalArgumentException e) {
            // Does not match this format, try the next one
        }
        i++;
    }
    // Does not match any known format :(
    return null;
}

From source file:models.Milestone.java

License:Apache License

public String until() {
    Date now = DateUtils.truncate(new Date(), Calendar.DATE);
    Date dueDate = DateUtils.truncate(this.dueDate, Calendar.DATE);
    Duration duration = new Duration(new DateTime(now), new DateTime(dueDate));
    long days = duration.getStandardDays();
    if (days < 0) {
        return Messages.get("common.time.overday", -days);
    } else if (days == 0) {
        return Messages.get("common.time.today");
    } else {/* w w w . j  a va  2  s  .co m*/
        return Messages.get("common.time.leftday", days);
    }
}

From source file:models.Milestone.java

License:Apache License

public Boolean isOverDueDate() {
    Duration duration = new Duration(DateTime.now(), new DateTime(dueDate));
    long days = duration.getStandardDays();
    return (days < 0);
}

From source file:module.workflow.domain.WorkflowLog.java

License:Open Source License

private static Duration calculateDuration(final WorkflowLog previous, final WorkflowLog next) {
    return new Duration(previous.getWhenOperationWasRan(), next.getWhenOperationWasRan());
}

From source file:myAgents.AgentGUI.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

    String beginHour = jComboBox1.getSelectedItem().toString();
    if (beginHour.equals(null)) {

        throw new IllegalArgumentException("Evento no enviado");

    }//from   www .  j  ava 2 s  .  co m
    String endHour = jComboBox2.getSelectedItem().toString();
    if (endHour.equals(null)) {
        throw new IllegalArgumentException("Evento no enviado");
    }

    if (endHour.equals(beginHour)) {
        throw new IllegalArgumentException("Evento no enviado");
    }
    String name = jTextField1.getText();
    if (name.equals(null)) {
        throw new IllegalArgumentException("Evento no enviado");
    }

    String duration = jComboBox3.getSelectedItem().toString();
    if (duration.equals(null)) {
        throw new IllegalArgumentException("Evento no enviado");
    }

    DateTime hourEnd = stringToDateTime(endHour);
    DateTime hourBegin = stringToDateTime(beginHour);
    Duration durationTime = stringToDuration(duration);
    Duration hourDuration = new Duration(hourBegin, hourEnd);

    if (hourEnd.isBefore(hourBegin) || hourBegin.isAfter(hourEnd) || hourDuration.isShorterThan(durationTime)) {
        throw new IllegalArgumentException("Evento no enviado");
    }

    int[] selectedTableIndices = jTable2.getSelectedRows();

    if (selectedTableIndices.length == 0) {
        throw new IllegalArgumentException("Evento no enviado");
    }

    Map<String, Boolean> eventAgents = new HashMap<String, Boolean>();

    for (int i = 0; i < selectedTableIndices.length; i++) {
        //nao esta a ter em conta se os agentaes so mandatorios ou nao... ter em atenao!!
        //if(jTable2.getValueAt(selectedTableIndices[i], 1).equals("true"))
        if (jTable2.getValueAt(selectedTableIndices[i], 0).toString().equals("true"))
            eventAgents.put(jTable2.getValueAt(selectedTableIndices[i], 0).toString(), true);
        else
            eventAgents.put(jTable2.getValueAt(selectedTableIndices[i], 0).toString(), false);

    }

    //alterar
    //Event event =  new Event(hourBegin, hourEnd, hourDuration, eventAgents,name, this.localAgent.getLocalName());
    //this.localAgent.sendMsg(event);

    jDialog1.setVisible(false);

}

From source file:myAgents.AgentGUI.java

public Duration stringToDuration(String strDate) {

    int int0 = Character.getNumericValue(strDate.charAt(0));
    int int1 = Character.getNumericValue(strDate.charAt(1));
    int int2 = Character.getNumericValue(strDate.charAt(3));
    int int3 = Character.getNumericValue(strDate.charAt(4));

    DateTime startTime = new DateTime(1993, 10, 8, 0, 0);
    DateTime endTime = new DateTime(1993, 10, 8, (int0 * 10 + int1), (int2 * 10 + int3));
    Duration myDuration = new Duration(startTime, endTime);

    return myDuration;

}

From source file:name.martingeisse.miner.ingame.CubeWorldHandler.java

License:Open Source License

/**
 * //from  w  ww  .j a va2  s  .c  om
 */
public void step() {
    final boolean keysEnabled = IngameHandler.gameMenuHandlerWrapper.getWrappedHandler() == null;
    final boolean mouseMovementEnabled = IngameHandler.gameMenuHandlerWrapper.getWrappedHandler() == null;

    // first, handle the stuff that already works without the world being loaded "enough"
    frameDurationSensor.tick();
    if (keysEnabled && Keyboard.isKeyDown(Keyboard.KEY_I)) {
        if (!infoButtonPressed) {
            player.dump();
        }
        infoButtonPressed = true;
    } else {
        infoButtonPressed = false;
    }
    if (keysEnabled && Keyboard.isKeyDown(Keyboard.KEY_P)) {
        player.setObserverMode(false);
    }
    if (keysEnabled && Keyboard.isKeyDown(Keyboard.KEY_O)) {
        player.setObserverMode(true);
    }
    if (keysEnabled && Keyboard.isKeyDown(Keyboard.KEY_G)) {
        grid = true;
    }
    if (keysEnabled && Keyboard.isKeyDown(Keyboard.KEY_H)) {
        grid = false;
    }
    if (keysEnabled && Keyboard.isKeyDown(Keyboard.KEY_K)) {
        MouseUtil.ungrab();
    }
    if (keysEnabled && Keyboard.isKeyDown(Keyboard.KEY_L)) {
        MouseUtil.grab();
    }
    if (keysEnabled && Keyboard.isKeyDown(Keyboard.KEY_SLASH) && !minusPressed) {
        IngameHandler.flashMessageHandler.addMessage("foobar! " + flashMessageCounter);
        flashMessageCounter++;
    }
    minusPressed = keysEnabled && Keyboard.isKeyDown(Keyboard.KEY_SLASH);
    wireframe = keysEnabled && Keyboard.isKeyDown(Keyboard.KEY_F);
    player.setWantsToJump(keysEnabled && Keyboard.isKeyDown(Keyboard.KEY_SPACE));
    if (keysEnabled && Keyboard.isKeyDown(Keyboard.KEY_1)) {
        currentCubeType = 1;
    } else if (keysEnabled && Keyboard.isKeyDown(Keyboard.KEY_2)) {
        currentCubeType = 2;
    } else if (keysEnabled && Keyboard.isKeyDown(Keyboard.KEY_3)) {
        currentCubeType = 3;
    } else if (keysEnabled && Keyboard.isKeyDown(Keyboard.KEY_4)) {
        currentCubeType = 50;
    }
    if (mouseMovementEnabled) {
        player.getOrientation()
                .setHorizontalAngle(player.getOrientation().getHorizontalAngle() - Mouse.getDX() * 0.5);
        double newUpAngle = player.getOrientation().getVerticalAngle() + Mouse.getDY() * 0.5;
        newUpAngle = (newUpAngle > 90) ? 90 : (newUpAngle < -90) ? -90 : newUpAngle;
        player.getOrientation().setVerticalAngle(newUpAngle);
    }
    sectionLoadHandler.handleStep();

    // process keyboard events -- needed for flawless GUI toggling
    // TODO properly disable all keyboard / mouse handling in the CubeWorldHandler when the GUI is active
    if (keysEnabled) {
        while (Keyboard.next()) {
            if (Keyboard.getEventKey() == Keyboard.KEY_ESCAPE && Keyboard.getEventKeyState()) {
                IngameHandler.gameMenuHandlerWrapper.setWrappedHandler(IngameHandler.gameMenuHandler);
                MouseUtil.ungrab();
            }
        }
    }

    // check if the world is loaded "enough"
    workingSet.acceptLoadedSections();
    if (!workingSet.hasAllRenderModels(player.getSectionId(), 1)
            || !workingSet.hasAllColliders(player.getSectionId(), 1)) {
        final Instant now = new Instant();
        if (new Duration(previousConnectionProblemInstant, now).getMillis() >= 1000) {
            logger.warn("connection problems");
            ThreadUtil.dumpThreads(Level.INFO);
            previousConnectionProblemInstant = now;
        }
        return;
    }

    // ---------------------------------------------------------------------------------------------------
    // now, handle the stuff that only works with enough information from the world
    // ---------------------------------------------------------------------------------------------------

    // normal movement: If on the ground, we move the player step-up, then front/side, then step-down.
    // This way the player can climb stairs while walking. In the air, this boils down to front/side movement.
    // We also keep track if the player is walking (front/side) for a "walking" sound effect.
    double speed = keysEnabled && Keyboard.isKeyDown(Keyboard.KEY_TAB) ? 10.0
            : keysEnabled && Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) ? 3.0 : 1.5;
    speed *= frameDurationSensor.getMultiplier();
    walking = false;
    double forward = 0, right = 0;
    if (keysEnabled && Keyboard.isKeyDown(Keyboard.KEY_A)) {
        right = -speed;
        walking = true;
    }
    if (keysEnabled && Keyboard.isKeyDown(Keyboard.KEY_D)) {
        right = speed;
        walking = true;
    }
    if (keysEnabled && Keyboard.isKeyDown(Keyboard.KEY_W)) {
        forward = speed;
        walking = true;
    }
    if (keysEnabled && Keyboard.isKeyDown(Keyboard.KEY_S)) {
        forward = -speed;
        walking = true;
    }
    player.moveHorizontal(forward, right, player.isOnGround() ? MAX_STAIRS_HEIGHT : 0);

    // special movement
    if (keysEnabled && Keyboard.isKeyDown(Keyboard.KEY_C)) {
        player.moveUp(-speed);
    }
    if (keysEnabled && Keyboard.isKeyDown(Keyboard.KEY_E)) {
        player.moveUp(speed);
    }

    // cube placement
    captureRayActionSupport = false;
    final long now = System.currentTimeMillis();
    if (now >= cooldownFinishTime) {
        if (mouseMovementEnabled && Mouse.isButtonDown(0)) {
            captureRayActionSupport = true;
            rayActionSupport.execute(player.getPosition().getX(), player.getPosition().getY(),
                    player.getPosition().getZ(), new RayAction(false) {
                        @Override
                        public void handleImpact(final int x, final int y, final int z, final double distance) {
                            if (distance < 3.0) {
                                final byte effectiveCubeType;
                                if (currentCubeType == 50) {
                                    final int angle = ((int) player.getOrientation().getHorizontalAngle() % 360
                                            + 360) % 360;
                                    if (angle < 45) {
                                        effectiveCubeType = 52;
                                    } else if (angle < 45 + 90) {
                                        effectiveCubeType = 50;
                                    } else if (angle < 45 + 180) {
                                        effectiveCubeType = 53;
                                    } else if (angle < 45 + 270) {
                                        effectiveCubeType = 51;
                                    } else {
                                        effectiveCubeType = 52;
                                    }
                                } else {
                                    effectiveCubeType = currentCubeType;
                                }

                                /* TODO: The call to breakFree() will remove a stairs cube if the player is standing
                                 * on the lower step, because the player's bounding box intersects with the cube's
                                 * bounding box. Solution 1: Remove breakFree(), don't place a cube if the player then
                                 * collides. Solution 2: Make breakFree() more accurate.
                                 */
                                final CubeModificationPacketBuilder builder = new CubeModificationPacketBuilder();
                                builder.addModification(x, y, z, effectiveCubeType);
                                breakFree(builder);
                                IngameHandler.protocolClient.send(builder.getPacket());
                                // cooldownFinishTime = now + 1000;
                                cooldownFinishTime = now + 200;
                            }
                        }
                    });
        } else if (mouseMovementEnabled && Mouse.isButtonDown(1)) {
            captureRayActionSupport = true;
            rayActionSupport.execute(player.getPosition().getX(), player.getPosition().getY(),
                    player.getPosition().getZ(), new RayAction(true) {
                        @Override
                        public void handleImpact(final int x, final int y, final int z, final double distance) {
                            if (distance < 2.0) {
                                IngameHandler.protocolClient.sendDigNotification(x, y, z);
                                resources.getHitCube().playAsSoundEffect(1.0f, 1.0f, false);
                                // cooldownFinishTime = now + 1000;
                                cooldownFinishTime = now + 200;
                            }
                        }
                    });
        }
    }

    // special actions
    if (keysEnabled && Keyboard.isKeyDown(Keyboard.KEY_B)) {
        final CubeModificationPacketBuilder builder = new CubeModificationPacketBuilder();
        breakFree(builder);
        IngameHandler.protocolClient.send(builder.getPacket());
    }

    // handle player logic
    player.step(frameDurationSensor.getMultiplier());

    // handle sound effects
    if (player.isOnGround() && walking) {
        footstepSound.handleActiveTime();
    } else {
        footstepSound.reset();
    }
    if (player.isJustLanded()) {
        resources.getLandOnGround().playAsSoundEffect(1.0f, 1.0f, false);
    }

}

From source file:net.link.util.ws.security.x509.WSSecurityX509TokenHandler.java

License:Open Source License

private boolean handleInboundDocument(SOAPPart document, SOAPMessageContext soapMessageContext) {

    logger.dbg("In: WS-Security header validation");
    List<WSSecurityEngineResult> wsSecurityEngineResults;
    try {/*ww  w.  j  ava2 s . c o  m*/
        //noinspection unchecked
        wsSecurityEngineResults = new WSSecurityEngine().processSecurityHeader(document, null, null,
                new ServerCrypto());
    } catch (WSSecurityException e) {
        throw SOAPUtils.createSOAPFaultException("The signature or decryption was invalid", "FailedCheck", e);
    }
    logger.dbg("results: %s", wsSecurityEngineResults);
    if (null == wsSecurityEngineResults) {
        if (!getWSSecConfiguration().isInboundSignatureOptional())
            throw SOAPUtils.createSOAPFaultException("No WS-Security header was found but is required.",
                    "InvalidSecurity");

        logger.dbg("Allowing inbound message without signature: it's set to optional");
        return true;
    }

    Timestamp timestamp = null;
    List<WSDataRef> signedElements = null;
    for (WSSecurityEngineResult result : wsSecurityEngineResults) {

        @SuppressWarnings("unchecked")
        List<WSDataRef> resultSignedElements = (List<WSDataRef>) result
                .get(WSSecurityEngineResult.TAG_DATA_REF_URIS);
        //            Set<String> resultSignedElements = (Set<String>) result.get( WSSecurityEngineResult.TAG_SIGNED_ELEMENT_IDS );
        if (null != resultSignedElements)
            signedElements = resultSignedElements;

        X509Certificate[] certificateChain = (X509Certificate[]) result
                .get(WSSecurityEngineResult.TAG_X509_CERTIFICATES);
        X509Certificate certificate = (X509Certificate) result.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
        if (null != certificateChain)
            setCertificateChain(soapMessageContext, certificateChain);
        else if (null != certificate)
            setCertificateChain(soapMessageContext, certificate);

        Timestamp resultTimestamp = (Timestamp) result.get(WSSecurityEngineResult.TAG_TIMESTAMP);
        if (null != resultTimestamp)
            timestamp = resultTimestamp;
    }

    if (null == signedElements)
        throw SOAPUtils.createSOAPFaultException("No signed elements found.", "FailedCheck");
    logger.dbg("# signed elements: %d", signedElements.size());
    soapMessageContext.put(SIGNED_ELEMENTS_CONTEXT_KEY, signedElements);

    // Check whether the SOAP Body has been signed.
    try {
        String bodyId = document.getEnvelope().getBody().getAttributeNS(WSConstants.WSU_NS, "Id");

        if (null == bodyId || bodyId.isEmpty())
            throw SOAPUtils.createSOAPFaultException("SOAP Body should have a wsu:Id attribute", "FailedCheck");
        if (!isElementSigned(soapMessageContext, bodyId))
            throw SOAPUtils.createSOAPFaultException("SOAP Body was not signed", "FailedCheck");
    } catch (SOAPException e) {
        throw SOAPUtils.createSOAPFaultException("error retrieving SOAP Body", "FailedCheck", e);
    }

    /*
    * Validate certificate.
    */
    CertificateChain certificateChain = findCertificateChain(soapMessageContext);
    if (null == certificateChain)
        throw SOAPUtils.createSOAPFaultException("missing X509Certificate chain in WS-Security header",
                "InvalidSecurity");
    if (!getWSSecConfiguration().isCertificateChainTrusted(certificateChain))
        throw SOAPUtils.createSOAPFaultException("can't trust X509Certificate chain in WS-Security header",
                "InvalidSecurity");

    /*
     * Check timestamp.
     */
    if (null == timestamp)
        throw SOAPUtils.createSOAPFaultException("missing Timestamp in WS-Security header", "InvalidSecurity");
    String timestampId = timestamp.getID();
    if (!isElementSigned(soapMessageContext, timestampId))
        throw SOAPUtils.createSOAPFaultException("Timestamp not signed", "FailedCheck");
    Duration age = new Duration(timestamp.getCreated().getTime(), System.currentTimeMillis());
    Duration maximumAge = getWSSecConfiguration().getMaximumAge();
    if (age.isLongerThan(maximumAge)) {
        logger.dbg("Maximum age exceeded by %s (since %s)", maximumAge.minus(age),
                timestamp.getCreated().getTime());
        throw SOAPUtils.createSOAPFaultException("Message too old", "FailedCheck");
    }

    return true;
}

From source file:net.schweerelos.timeline.model.Timeline.java

License:Open Source License

public Duration getDuration() {
    return new Duration(start, end);
}

From source file:net.schweerelos.timeline.ui.TimelinePanel.java

License:Open Source License

public int convertDateToXCoord(DateTime date) {
    if (!tModel.isWithinRange(date)) {
        if (tModel.isBeforeStart(date)) {
            return 0;
        } else {/*  w  w  w .j av a2 s  .  c o m*/
            return getWidth();
        }
    }
    Duration visibleDuration = tModel.getDuration();
    Duration fromStart = new Duration(tModel.getStart(), date);
    float ratio = fromStart.getMillis() / (float) visibleDuration.getMillis();
    int xCoord = (int) Math.floor(ratio * getWidth());
    return xCoord;
}