Example usage for org.joda.time DateTime minusSeconds

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

Introduction

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

Prototype

public DateTime minusSeconds(int seconds) 

Source Link

Document

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

Usage

From source file:com.lastpass.saml.SAMLClient.java

License:Apache License

private void validate(Response response) throws ValidationException {
    // response signature must match IdP's key, if present
    Signature sig = response.getSignature();
    if (sig != null)
        sigValidator.validate(sig);/*from ww w .  j  a v  a  2 s . c o m*/

    // response must be successful
    if (response.getStatus() == null || response.getStatus().getStatusCode() == null
            || !(StatusCode.SUCCESS_URI.equals(response.getStatus().getStatusCode().getValue()))) {
        throw new ValidationException("Response has an unsuccessful status code");
    }

    // response destination must match ACS
    if (!spConfig.getAcs().equals(response.getDestination()))
        throw new ValidationException("Response is destined for a different endpoint");

    DateTime now = DateTime.now();

    // issue instant must be within a day
    DateTime issueInstant = response.getIssueInstant();

    if (issueInstant != null) {
        if (issueInstant.isBefore(now.minusDays(1).minusSeconds(slack)))
            throw new ValidationException("Response IssueInstant is in the past");

        if (issueInstant.isAfter(now.plusDays(1).plusSeconds(slack)))
            throw new ValidationException("Response IssueInstant is in the future");
    }

    List<Assertion> assertions;
    try {
        assertions = parseAllAssertions(response);
    } catch (SAMLException ex) {
        throw new ValidationException("no assertions found.");
    }

    for (Assertion assertion : assertions) {
        // Assertion must be signed correctly
        if (!assertion.isSigned())
            throw new ValidationException("Assertion must be signed");

        sig = assertion.getSignature();
        sigValidator.validate(sig);

        // Assertion must contain an authnstatement
        // with an unexpired session
        if (assertion.getAuthnStatements().isEmpty()) {
            throw new ValidationException("Assertion should contain an AuthnStatement");
        }
        for (AuthnStatement as : assertion.getAuthnStatements()) {
            DateTime sessionTime = as.getSessionNotOnOrAfter();
            if (sessionTime != null) {
                DateTime exp = sessionTime.plusSeconds(slack);
                if (exp != null && (now.isEqual(exp) || now.isAfter(exp)))
                    throw new ValidationException("AuthnStatement has expired");
            }
        }

        if (assertion.getConditions() == null) {
            throw new ValidationException("Assertion should contain conditions");
        }

        // Assertion IssueInstant must be within a day
        DateTime instant = assertion.getIssueInstant();
        if (instant != null) {
            if (instant.isBefore(now.minusDays(1).minusSeconds(slack)))
                throw new ValidationException("Response IssueInstant is in the past");

            if (instant.isAfter(now.plusDays(1).plusSeconds(slack)))
                throw new ValidationException("Response IssueInstant is in the future");
        }

        // Conditions must be met by current time
        Conditions conditions = assertion.getConditions();
        DateTime notBefore = conditions.getNotBefore();
        DateTime notOnOrAfter = conditions.getNotOnOrAfter();

        if (notBefore == null || notOnOrAfter == null)
            throw new ValidationException("Assertion conditions must have limits");

        notBefore = notBefore.minusSeconds(slack);
        notOnOrAfter = notOnOrAfter.plusSeconds(slack);

        if (now.isBefore(notBefore))
            throw new ValidationException("Assertion conditions is in the future");

        if (now.isEqual(notOnOrAfter) || now.isAfter(notOnOrAfter))
            throw new ValidationException("Assertion conditions is in the past");

        // If subjectConfirmationData is included, it must
        // have a recipient that matches ACS, with a valid
        // NotOnOrAfter
        Subject subject = assertion.getSubject();
        if (subject != null && !subject.getSubjectConfirmations().isEmpty()) {
            boolean foundRecipient = false;
            for (SubjectConfirmation sc : subject.getSubjectConfirmations()) {
                if (sc.getSubjectConfirmationData() == null)
                    continue;

                SubjectConfirmationData scd = sc.getSubjectConfirmationData();
                if (scd.getNotOnOrAfter() != null) {
                    DateTime chkdate = scd.getNotOnOrAfter().plusSeconds(slack);
                    if (now.isEqual(chkdate) || now.isAfter(chkdate)) {
                        throw new ValidationException("SubjectConfirmationData is in the past");
                    }
                }

                if (spConfig.getAcs().equals(scd.getRecipient()))
                    foundRecipient = true;
            }

            if (!foundRecipient)
                throw new ValidationException("No SubjectConfirmationData found for ACS");
        }

        // audience must include intended SP issuer
        if (conditions.getAudienceRestrictions().isEmpty())
            throw new ValidationException("Assertion conditions must have audience restrictions");

        // only one audience restriction supported: we can only
        // check against the single SP.
        if (conditions.getAudienceRestrictions().size() > 1)
            throw new ValidationException("Assertion contains multiple audience restrictions");

        AudienceRestriction ar = conditions.getAudienceRestrictions().get(0);

        // at least one of the audiences must match our SP
        boolean foundSP = false;
        for (Audience a : ar.getAudiences()) {
            if (spConfig.getEntityId().equals(a.getAudienceURI()))
                foundSP = true;
        }
        if (!foundSP)
            throw new ValidationException("Assertion audience does not include issuer");
    }
}

From source file:com.pacoapp.paco.triggering.NotificationCreator.java

License:Open Source License

private void createAllNotificationsForLastMinute(long alarmTime) {
    DateTime alarmAsDateTime = new DateTime(alarmTime);
    Log.i(PacoConstants.TAG, "Creating All notifications for last minute from signaled alarmTime: "
            + alarmAsDateTime.toString());

    List<ExperimentDAO> experimentDAOs = Lists.newArrayList();
    for (Experiment experiment : experimentProviderUtil.getJoinedExperiments()) {
        experimentDAOs.add(experiment.getExperimentDAO());
    }// w  ww  .  j ava2 s  .c  o  m
    List<ActionSpecification> times = ActionScheduleGenerator.getAllAlarmsWithinOneMinuteofNow(
            alarmAsDateTime.minusSeconds(59), experimentDAOs, new AndroidEsmSignalStore(context),
            experimentProviderUtil);

    for (ActionSpecification timeExperiment : times) {
        if (timeExperiment.action == null) {
            continue; // not a notification action specification
        }
        // TODO might we be able to timeout all notifications for all experiments
        // instead of doing this for each experiment?
        final Long experimentId = timeExperiment.experiment.getId();
        ExperimentGroup experimentGroup = timeExperiment.experimentGroup;
        if (experimentGroup == null) {
            timeoutNotifications(experimentProviderUtil.getAllNotificationsFor(experimentId));
        } else {
            List<NotificationHolder> notificationsForGroup = experimentProviderUtil
                    .getNotificationsFor(experimentId, experimentGroup.getName());
            timeoutNotifications(notificationsForGroup);
        }
        createNewNotificationForExperiment(context, timeExperiment, false);
    }
}

From source file:com.reclabs.recomendar.common.helpers.types.DateHelper.java

License:Open Source License

/**
 * Subtract to the current date the amount of that precisionType represent.
 * @param date The date to subtract//from w  w  w  .  j  a  v  a2  s  .com
 * @param amount The amount to subtract
 * @param precisionType The field to subtract
 * @return The new date
 */
public static Date subtract(Date date, int amount, DatePrecisionType precisionType) {
    DateTime jodaDate1 = new DateTime(date.getTime());
    DateTime result;
    switch (precisionType) {
    case YEAR:
        result = jodaDate1.minusYears(amount);
        break;
    case MONTH:
        result = jodaDate1.minusMonths(amount);
        break;
    case DAY:
        result = jodaDate1.minusDays(amount);
        break;
    case HOUR:
        result = jodaDate1.minusHours(amount);
        break;
    case MINUTE:
        result = jodaDate1.minusMinutes(amount);
        break;
    case SECOND:
        result = jodaDate1.minusSeconds(amount);
        break;
    case MILLISECOND:
        result = jodaDate1.minusMillis(amount);
        break;
    default:
        LOGGER.warn("[Error subtract, precision value is invalid: {}]", precisionType);
        throw new RecIllegalArgumentException("The precision value is invalid " + precisionType);
    }
    return result.toDate();
}

From source file:com.sheepdog.mashmesh.Itinerary.java

License:Apache License

public static Itinerary fetch(String fromLocation, String toLocation, String viaLocation, DateTime arrivalTime)
        throws URISyntaxException, IOException {
    URIBuilder uriBuilder = new URIBuilder(DIRECTIONS_ENDPOINT_URL);
    uriBuilder.addParameter("origin", fromLocation);
    uriBuilder.addParameter("destination", toLocation);
    uriBuilder.addParameter("mode", "driving");
    uriBuilder.addParameter("language", "en_US"); // TODO: Configurable?
    uriBuilder.addParameter("region", "us");
    uriBuilder.addParameter("waypoints", viaLocation);
    uriBuilder.addParameter("sensor", "false");

    URL url = uriBuilder.build().toURL();
    BufferedReader responseReader = new BufferedReader(new InputStreamReader(url.openStream()));

    JsonParser parser = new JsonParser();
    JsonObject responseObject = parser.parse(responseReader).getAsJsonObject();
    JsonObject route = responseObject.getAsJsonArray("routes").get(0).getAsJsonObject();
    JsonArray legs = route.getAsJsonArray("legs");

    JsonObject startLeg = legs.get(0).getAsJsonObject();
    JsonObject endLeg = legs.get(legs.size() - 1).getAsJsonObject();

    DateTime departureTime = arrivalTime;
    List<Leg> directionLegs = new ArrayList<Leg>();

    Preconditions.checkState(legs.size() == 2, "Expected two direction legs in response");

    // Process the legs in reverse order so that we can compute departure and arrival
    //  times by working backwards from the desired arrival time.
    for (int i = legs.size() - 1; i >= 0; i--) {
        JsonObject leg = legs.get(i).getAsJsonObject();
        List<Step> directionSteps = new ArrayList<Step>();
        DateTime legArrivalTime = departureTime;

        for (JsonElement stepElement : leg.getAsJsonArray("steps")) {
            JsonObject stepObject = stepElement.getAsJsonObject();
            int duration = stepObject.getAsJsonObject("duration").get("value").getAsInt();
            String htmlInstructions = stepObject.get("html_instructions").getAsString();
            String distance = stepObject.getAsJsonObject("distance").get("text").getAsString();

            departureTime = departureTime.minusSeconds(duration);
            directionSteps.add(new Step(htmlInstructions, distance));
        }/*from   w  w  w. jav  a2  s.c  o  m*/

        Leg directionLeg = new Leg();
        directionLeg.departureTime = departureTime;
        directionLeg.startLatLng = getLatLng(leg.getAsJsonObject("start_location"));
        directionLeg.arrivalTime = legArrivalTime;
        directionLeg.endLatLng = getLatLng(leg.getAsJsonObject("end_location"));
        directionLeg.distanceMeters = leg.getAsJsonObject("distance").get("value").getAsInt();
        directionLeg.steps = Collections.unmodifiableList(directionSteps);
        directionLegs.add(directionLeg);
    }

    Collections.reverse(directionLegs);

    Itinerary itinerary = new Itinerary();
    itinerary.startAddress = startLeg.get("start_address").getAsString();
    itinerary.endAddress = endLeg.get("end_address").getAsString();
    itinerary.legs = Collections.unmodifiableList(directionLegs);
    itinerary.overviewPolyline = route.getAsJsonObject("overview_polyline").get("points").getAsString();

    return itinerary;
}

From source file:com.splicemachine.derby.utils.SpliceDateFunctions.java

License:Apache License

/**
 * Implements the trunc_date function//from   w w w . j a va 2 s  .c  o  m
 */
public static Timestamp TRUNC_DATE(Timestamp source, String field) throws SQLException {
    if (source == null || field == null)
        return null;
    DateTime dt = new DateTime(source);
    field = field.toLowerCase();
    String lowerCaseField = field.toLowerCase();
    if ("microseconds".equals(lowerCaseField)) {
        int nanos = source.getNanos();
        nanos = nanos - nanos % 1000;
        source.setNanos(nanos);
        return source;
    } else if ("milliseconds".equals(lowerCaseField)) {
        int nanos = source.getNanos();
        nanos = nanos - nanos % 1000000;
        source.setNanos(nanos);
        return source;
    } else if ("second".equals(lowerCaseField)) {
        source.setNanos(0);
        return source;

    } else if ("minute".equals(lowerCaseField)) {
        DateTime modified = dt.minusSeconds(dt.getSecondOfMinute());
        Timestamp ret = new Timestamp(modified.getMillis());
        ret.setNanos(0);
        return ret;
    } else if ("hour".equals(lowerCaseField)) {
        DateTime modified = dt.minusMinutes(dt.getMinuteOfHour()).minusSeconds(dt.getSecondOfMinute());
        Timestamp ret = new Timestamp(modified.getMillis());
        ret.setNanos(0);
        return ret;
    } else if ("day".equals(lowerCaseField)) {
        DateTime modified = dt.minusHours(dt.getHourOfDay()).minusMinutes(dt.getMinuteOfHour())
                .minusSeconds(dt.getSecondOfMinute());
        Timestamp ret = new Timestamp(modified.getMillis());
        ret.setNanos(0);
        return ret;
    } else if ("week".equals(lowerCaseField)) {
        DateTime modified = dt.minusDays(dt.getDayOfWeek()).minusHours(dt.getHourOfDay())
                .minusMinutes(dt.getMinuteOfHour()).minusSeconds(dt.getSecondOfMinute());
        Timestamp ret = new Timestamp(modified.getMillis());
        ret.setNanos(0);
        return ret;
    } else if ("month".equals(lowerCaseField)) {
        DateTime modified = dt.minusDays(dt.get(DateTimeFieldType.dayOfMonth()) - 1)
                .minusHours(dt.getHourOfDay()).minusMinutes(dt.getMinuteOfHour())
                .minusSeconds(dt.getSecondOfMinute());
        Timestamp ret = new Timestamp(modified.getMillis());
        ret.setNanos(0);
        return ret;
    } else if ("quarter".equals(lowerCaseField)) {
        int month = dt.getMonthOfYear();
        DateTime modified = dt;
        if ((month + 1) % 3 == 1) {
            modified = dt.minusMonths(2);
        } else if ((month + 1) % 3 == 0) {
            modified = dt.minusMonths(1);
        }
        DateTime fin = modified.minusDays(dt.get(DateTimeFieldType.dayOfMonth()) - 1)
                .minusHours(dt.getHourOfDay()).minusMinutes(dt.getMinuteOfHour())
                .minusSeconds(dt.getSecondOfMinute());
        Timestamp ret = new Timestamp(fin.getMillis());
        ret.setNanos(0);
        return ret;
    } else if ("year".equals(lowerCaseField)) {
        DateTime modified = dt.minusDays(dt.get(DateTimeFieldType.dayOfMonth()) - 1)
                .minusHours(dt.getHourOfDay()).minusMonths(dt.getMonthOfYear() - 1)
                .minusMinutes(dt.getMinuteOfHour()).minusSeconds(dt.getSecondOfMinute());
        Timestamp ret = new Timestamp(modified.getMillis());
        ret.setNanos(0);
        return ret;
    } else if ("decade".equals(lowerCaseField)) {
        DateTime modified = dt.minusDays(dt.get(DateTimeFieldType.dayOfMonth()) - 1)
                .minusYears(dt.getYear() % 10).minusHours(dt.getHourOfDay())
                .minusMonths(dt.getMonthOfYear() - 1).minusMinutes(dt.getMinuteOfHour())
                .minusSeconds(dt.getSecondOfMinute());
        Timestamp ret = new Timestamp(modified.getMillis());
        ret.setNanos(0);
        return ret;
    } else if ("century".equals(lowerCaseField)) {
        DateTime modified = dt.minusDays(dt.get(DateTimeFieldType.dayOfMonth()) - 1)
                .minusHours(dt.getHourOfDay()).minusYears(dt.getYear() % 100)
                .minusMonths(dt.getMonthOfYear() - 1).minusMinutes(dt.getMinuteOfHour())
                .minusSeconds(dt.getSecondOfMinute());
        Timestamp ret = new Timestamp(modified.getMillis());
        ret.setNanos(0);
        return ret;
    } else if ("millennium".equals(lowerCaseField)) {
        int newYear = dt.getYear() - dt.getYear() % 1000;
        //noinspection deprecation (converstion from joda to java.sql.Timestamp did not work for millennium < 2000)
        return new Timestamp(newYear - 1900, Calendar.JANUARY, 1, 0, 0, 0, 0);
    } else {
        throw new SQLException(String.format("invalid time unit '%s'", field));
    }
}

From source file:com.tango.BucketSyncer.MirrorOptions.java

License:Apache License

private long initMaxAge() {

    DateTime dateTime = new DateTime(nowTime);

    // all digits -- assume "days"
    if (ctime.matches("^[0-9]+$"))
        return dateTime.minusDays(Integer.parseInt(ctime)).getMillis();

    // ensure there is at least one digit, and exactly one character suffix, and the suffix is a legal option
    if (!ctime.matches("^[0-9]+[yMwdhms]$"))
        throw new IllegalArgumentException("Invalid option for ctime: " + ctime);

    if (ctime.endsWith("y"))
        return dateTime.minusYears(getCtimeNumber(ctime)).getMillis();
    if (ctime.endsWith("M"))
        return dateTime.minusMonths(getCtimeNumber(ctime)).getMillis();
    if (ctime.endsWith("w"))
        return dateTime.minusWeeks(getCtimeNumber(ctime)).getMillis();
    if (ctime.endsWith("d"))
        return dateTime.minusDays(getCtimeNumber(ctime)).getMillis();
    if (ctime.endsWith("h"))
        return dateTime.minusHours(getCtimeNumber(ctime)).getMillis();
    if (ctime.endsWith("m"))
        return dateTime.minusMinutes(getCtimeNumber(ctime)).getMillis();
    if (ctime.endsWith("s"))
        return dateTime.minusSeconds(getCtimeNumber(ctime)).getMillis();
    throw new IllegalArgumentException("Invalid option for ctime: " + ctime);
}

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));
    }/*  w w  w  .  j ava 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.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();/*from   w  w w. ja  v  a2s  .  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.tremolosecurity.proxy.SessionManagerImpl.java

License:Apache License

private HttpSession locateSession(UrlHolder holder, HttpServletRequest request, ServletContext ctx,
        String cookieName, HttpServletResponse resp) throws Exception {
    Cookie sessionCookie = null;//from   w ww.j  a v  a 2s  .  c  om

    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            if (cookie.getName().equalsIgnoreCase(cookieName)) {
                sessionCookie = cookie;
                break;
            }
        }
    }

    ConfigManager cfg = (ConfigManager) ctx.getAttribute(ProxyConstants.TREMOLO_CONFIG);

    ApplicationType app;

    if (holder != null) {
        app = holder.getApp();
    } else {
        app = null;

        String appName = null;
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                if (cookies[i].getName().equals("autoIdmAppName")) {
                    appName = URLDecoder.decode(cookies[i].getValue(), "UTF-8");
                    break;
                }
            }
        }

        if (appName == null) {
            // TODO create open session
            if (cookies != null) {
                for (int i = 0; i < cookies.length; i++) {
                    if (cookies[i].getName()
                            .equals(cfg.getCfg().getApplications().getOpenSessionCookieName())) {
                        String sessionID = cookies[i].getValue();
                        TremoloHttpSession tsession = this.sessions.get(sessionID);
                        // TODO add timeouts
                        if (tsession == null) {
                            return this.createOpenSession(request, resp, ctx);
                        } else {
                            return tsession;
                        }

                    }
                }
            }

            return createOpenSession(request, resp, ctx);
        } else {
            app = cfg.getApp(appName);

            if (app == null) {
                throw new Exception("No application named '" + appName + "' found");
            }

        }
    }

    SecretKey encKey = cfg.getSecretKey(app.getCookieConfig().getKeyAlias());

    // TremoloHttpSession tsession = (TremoloHttpSession)
    // request.getSession().getAttribute(app.getCookieConfig().getSessionCookieName());

    if (sessionCookie == null) {
        // if (tsession != null) tsession.invalidate();
        return createSession(app, request, resp, ctx, encKey);
    } else {

        HttpSession session = null;

        try {

            try {

                TremoloHttpSession tsession = findSessionFromCookie(sessionCookie, encKey, this);

                if (tsession == null) {
                    return createSession(app, request, resp, ctx, encKey);
                }

                String fromSessionID = (String) tsession.getAttribute(OpenUnisonConstants.TREMOLO_SESSION_ID);

                if (app.getCookieConfig().getTimeout() > 0) {
                    DateTime lastAccessed = (DateTime) tsession
                            .getAttribute(SessionManagerImpl.TREMOLO_SESSION_LAST_ACCESSED);
                    DateTime now = new DateTime();
                    if (now.minusSeconds(app.getCookieConfig().getTimeout()).isAfter(lastAccessed)) {
                        tsession.invalidate();
                        return createSession(app, request, resp, ctx, encKey);
                    } else {
                        tsession.setAttribute(SessionManagerImpl.TREMOLO_SESSION_LAST_ACCESSED, now);
                        session = tsession;
                    }
                } else {
                    session = tsession;
                }

            } catch (Exception e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Exception loading session", e);
                }
                return createSession(app, request, resp, ctx, encKey);

            }

            // this.sessions.put(session.getSessionID(), key);
            // }

        } catch (Exception e) {
            logger.error("Error generating session", e);
        }
        if (session == null) {
            // session.invalidate();
            return createSession(app, request, resp, ctx, encKey);
        }

        // session.resetAccess();

        return session;

    }
}

From source file:com.tremolosecurity.proxy.SessionManagerImpl.java

License:Apache License

@Override
public void run() {
    while (stillRun) {

        try {/*from  w ww .j  ava2 s  .c o  m*/

            ArrayList<String> toremove = new ArrayList<String>();

            Set<String> keys = new HashSet<String>();

            synchronized (this.sessionMgr.getSessions()) {
                keys.addAll(this.sessionMgr.getSessions().keySet());
            }

            for (String key : keys) {
                TremoloHttpSession session = this.sessionMgr.getSessions().get(key);

                if (session == null) {
                    continue;
                }

                ApplicationType app = cfg.getApp(session.getAppName());

                if (session.isOpen()) {
                    if (cfg.getCfg().getApplications().getOpenSessionTimeout() > 0) {
                        DateTime lastAccessed = (DateTime) session
                                .getAttribute(SessionManagerImpl.TREMOLO_SESSION_LAST_ACCESSED);

                        if (lastAccessed == null) {
                            lastAccessed = new DateTime(session.getCreationTime());
                        }

                        DateTime now = new DateTime();
                        if (now.minusSeconds(cfg.getCfg().getApplications().getOpenSessionTimeout())
                                .isAfter(lastAccessed)) {
                            session.invalidate();
                            toremove.add(key);
                        }
                    }
                } else {
                    if (app == null) {
                        StringBuffer b = new StringBuffer();
                        b.append("Session ").append(session.getId()).append(" application ")
                                .append(session.getAppName()).append(" does not exist, invalidating");
                        SessionManagerImpl.logger.warn(b.toString());
                        toremove.add(key);
                        session.invalidate();
                    } else {
                        if (app.getCookieConfig().getTimeout() > 0) {
                            DateTime lastAccessed = (DateTime) session
                                    .getAttribute(SessionManagerImpl.TREMOLO_SESSION_LAST_ACCESSED);

                            if (lastAccessed == null) {
                                lastAccessed = new DateTime(session.getCreationTime());
                            }

                            DateTime now = new DateTime();
                            if (now.minusSeconds(app.getCookieConfig().getTimeout()).isAfter(lastAccessed)) {
                                session.invalidate();
                                toremove.add(key);
                            }
                        }
                    }
                }

            }

            synchronized (this.sessionMgr.getSessions()) {
                StringBuffer b = new StringBuffer();
                b.append("Clearing ").append(toremove.size()).append(" sessions");
                SessionManagerImpl.logger.warn(b.toString());
                for (String key : toremove) {
                    this.sessionMgr.getSessions().remove(key);
                }
            }

            try {
                Thread.sleep(60000);
            } catch (InterruptedException e) {

            }
        } catch (Throwable t) {
            SessionManagerImpl.logger.warn("Exception while processing expired sessions", t);

            try {
                Thread.sleep(60000);
            } catch (InterruptedException e) {

            }
        }
    }

}