Example usage for org.joda.time DateTime getMinuteOfHour

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

Introduction

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

Prototype

public int getMinuteOfHour() 

Source Link

Document

Get the minute of hour field value.

Usage

From source file:org.apache.streams.util.DateUtil.java

License:Apache License

public static DateTime determineDateTime(String dateString, DateTimeZone theTimeZone) throws ParseException {
    DateTime beforeTimeZone = determineDateTime(dateString);
    return new DateTime(beforeTimeZone.getYear(), beforeTimeZone.getMonthOfYear(),
            beforeTimeZone.getDayOfMonth(), beforeTimeZone.getHourOfDay(), beforeTimeZone.getMinuteOfHour(),
            beforeTimeZone.getSecondOfMinute(), beforeTimeZone.getMillisOfSecond(), theTimeZone);
}

From source file:org.apereo.portal.events.aggr.AggregationInterval.java

License:Apache License

/**
 * Determine the starting DateTime (inclusive) of an interval based on an instant in time
 *
 * @param instant The instant in time to get the interval starting value for
 * @return The start of this interval in relation to the provided instant
 */// www  .ja v  a 2s  . com
public DateTime determineStart(DateTime instant) {
    if (this.dateTimeFieldType != null) {
        return instant.property(this.dateTimeFieldType).roundFloorCopy();
    }

    if (this == AggregationInterval.FIVE_MINUTE) {
        return instant.hourOfDay().roundFloorCopy().plusMinutes((instant.getMinuteOfHour() / 5) * 5);
    }

    throw new IllegalArgumentException("Cannot compute interval start time for " + this + " please use "
            + AggregationIntervalHelper.class);
}

From source file:org.apereo.portal.events.aggr.AggregationInterval.java

License:Apache License

/**
 * Determine the ending DateTime (exclusive) of an interval based on an instant in time
 *
 * @param instant The start of an instant
 * @return/*w  w  w.  j  ava 2  s.c o  m*/
 */
public DateTime determineEnd(DateTime instant) {
    if (this.dateTimeFieldType != null) {
        final DateTime start = instant.property(this.dateTimeFieldType).roundFloorCopy();
        return start.property(this.dateTimeFieldType).addToCopy(1);
    }

    if (this == AggregationInterval.FIVE_MINUTE) {
        final DateTime start = instant.hourOfDay().roundFloorCopy()
                .plusMinutes((instant.getMinuteOfHour() / 5) * 5);
        return start.plusMinutes(5);
    }

    throw new IllegalArgumentException(
            "Cannot compute interval end time for " + this + " please use " + AggregationIntervalHelper.class);
}

From source file:org.apereo.portal.portlets.statistics.BaseStatisticsReportController.java

License:Apache License

/** Build the aggregation {@link DataTable} */
protected final DataTable buildAggregationReport(F form) throws TypeMismatchException {
    //Pull data out of form for per-group fetching
    final AggregationInterval interval = form.getInterval();
    final DateMidnight start = form.getStart();
    final DateMidnight end = form.getEnd();

    final DateTime startDateTime = start.toDateTime();
    //Use a query end of the end date at 23:59:59
    final DateTime endDateTime = end.plusDays(1).toDateTime().minusSeconds(1);

    //Get the list of DateTimes used on the X axis in the report
    final List<DateTime> reportTimes = this.intervalHelper.getIntervalStartDateTimesBetween(interval,
            startDateTime, endDateTime, maxIntervals);

    final Map<D, SortedSet<T>> groupedAggregations = createColumnDiscriminatorMap(form);

    //Determine the ValueType of the date/time column. Use the most specific column type possible
    final ValueType dateTimeColumnType;
    if (interval.isHasTimePart()) {
        //If start/end are the same day just display the time
        if (startDateTime.toDateMidnight().equals(endDateTime.toDateMidnight())) {
            dateTimeColumnType = ValueType.TIMEOFDAY;
        }/*from w  w w  .j a v a 2 s.  c o  m*/
        //interval has time data and start/end are on different days, show full date time
        else {
            dateTimeColumnType = ValueType.DATETIME;
        }
    }
    //interval is date only
    else {
        dateTimeColumnType = ValueType.DATE;
    }

    //Setup the date/time column description
    final ColumnDescription dateTimeColumn;
    switch (dateTimeColumnType) {
    case TIMEOFDAY: {
        dateTimeColumn = new ColumnDescription("time", dateTimeColumnType, "Time");
        break;
    }
    default: {
        dateTimeColumn = new ColumnDescription("date", dateTimeColumnType, "Date");
    }
    }

    final DataTable table = new JsonDataTable();
    table.addColumn(dateTimeColumn);

    //Setup columns in the DataTable
    final Set<D> columnGroups = groupedAggregations.keySet();
    for (final D columnMapping : columnGroups) {
        final Collection<ColumnDescription> columnDescriptions = this.getColumnDescriptions(columnMapping,
                form);
        table.addColumns(columnDescriptions);
    }

    //Query for all aggregation data in the time range for all groups.  Only the
    //interval and discriminator data is used from the keys.
    final Set<K> keys = createAggregationsQueryKeyset(columnGroups, form);
    final BaseAggregationDao<T, K> baseAggregationDao = this.getBaseAggregationDao();
    final Collection<T> aggregations = baseAggregationDao.getAggregations(startDateTime, endDateTime, keys,
            extractGroupsArray(columnGroups));

    //Organize the results by group and sort them chronologically by adding them to the sorted set
    for (final T aggregation : aggregations) {
        final D discriminator = aggregation.getAggregationDiscriminator();
        final SortedSet<T> results = groupedAggregations.get(discriminator);
        results.add(aggregation);
    }

    //Build Map from discriminator column mapping to result iterator to allow putting results into
    //the correct column AND the correct time slot in the column
    Comparator<? super D> comparator = getDiscriminatorComparator();
    final Map<D, PeekingIterator<T>> groupedAggregationIterators = new TreeMap<D, PeekingIterator<T>>(
            (comparator));
    for (final Entry<D, SortedSet<T>> groupedAggregationEntry : groupedAggregations.entrySet()) {
        groupedAggregationIterators.put(groupedAggregationEntry.getKey(),
                Iterators.peekingIterator(groupedAggregationEntry.getValue().iterator()));
    }

    /*
     * populate the data, filling in blank spots. The full list of interval DateTimes is used to create every row in the
     * query range. Then the iterator
     */
    for (final DateTime rowTime : reportTimes) {
        // create the row
        final TableRow row = new TableRow();

        // add the date to the first cell
        final Value dateTimeValue;
        switch (dateTimeColumnType) {
        case DATE: {
            dateTimeValue = new DateValue(rowTime.getYear(), rowTime.getMonthOfYear() - 1,
                    rowTime.getDayOfMonth());
            break;
        }
        case TIMEOFDAY: {
            dateTimeValue = new TimeOfDayValue(rowTime.getHourOfDay(), rowTime.getMinuteOfHour(), 0);
            break;
        }
        default: {
            dateTimeValue = new DateTimeValue(rowTime.getYear(), rowTime.getMonthOfYear() - 1,
                    rowTime.getDayOfMonth(), rowTime.getHourOfDay(), rowTime.getMinuteOfHour(), 0, 0);
            break;
        }
        }
        row.addCell(new TableCell(dateTimeValue));

        for (final PeekingIterator<T> groupedAggregationIteratorEntry : groupedAggregationIterators.values()) {
            List<Value> values = null;

            if (groupedAggregationIteratorEntry.hasNext()) {
                final T aggr = groupedAggregationIteratorEntry.peek();
                if (rowTime.equals(aggr.getDateTime())) {
                    //Data is for the correct time slot, advance the iterator
                    groupedAggregationIteratorEntry.next();

                    values = createRowValues(aggr, form);
                }
            }

            //Gap in the data, fill it in using a null aggregation
            if (values == null) {
                values = createRowValues(null, form);
            }

            //Add the values to the row
            for (final Value value : values) {
                row.addCell(value);
            }
        }

        table.addRow(row);
    }

    return table;
}

From source file:org.aselect.server.request.handler.xsaml20.sp.Xsaml20_ISTS.java

License:Open Source License

@SuppressWarnings("unchecked")
public RequestState process(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ASelectException {
    String sMethod = "process";
    String sRid;/*from  w  w  w .  java2s.  c  o  m*/
    String sFederationUrl = null;
    PrintWriter pwOut = null;

    String sMyUrl = _sServerUrl; // extractAselectServerUrl(request);
    _systemLogger.log(Level.INFO, MODULE, sMethod,
            "MyUrl=" + sMyUrl + " MyId=" + getID() + " path=" + servletRequest.getPathInfo());

    try {
        pwOut = Utils.prepareForHtmlOutput(servletRequest, servletResponse);

        sRid = servletRequest.getParameter("rid");
        if (sRid == null) {
            _systemLogger.log(Level.WARNING, MODULE, sMethod, "Missing RID parameter");
            throw new ASelectCommunicationException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
        }

        // Find the associated session context
        _htSessionContext = _oSessionManager.getSessionContext(sRid);
        if (_htSessionContext == null) {
            _systemLogger.log(Level.WARNING, MODULE, sMethod, "No session found for RID: " + sRid);
            throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
        }
        // Session present
        Tools.resumeSensorData(_configManager, _systemLogger, _htSessionContext); //20111102, can change the session
        // 20091028, Bauke, let the user choose which IdP to use
        // 20110308, Bauke: changed, user chooses when "use_idp_select" is "true"
        //     otherwise this handler uses it's own resource group to get a resource and sets "federation_url"
        //     to the id of that resource
        sFederationUrl = servletRequest.getParameter("federation_url");

        //int cnt = MetaDataManagerSp.getHandle().getIdpCount();
        //if (cnt == 1) {
        //   sFederationUrl = MetaDataManagerSp.getHandle().getDefaultIdP(); // there can only be one
        //}
        if (bIdpSelectForm && (!Utils.hasValue(sFederationUrl))) {
            // No Federation URL choice made yet, allow the user to choose
            String sIdpSelectForm = Utils.loadTemplateFromFile(_systemLogger, _configManager.getWorkingdir(),
                    null/*subdir*/, "idpselect", _sUserLanguage, _configManager.getOrgFriendlyName(),
                    Version.getVersion());
            sIdpSelectForm = Utils.replaceString(sIdpSelectForm, "[rid]", sRid);
            // Not backward compatible! [aselect_url] used to be server_url/handler_id,
            // they're separated now to allow use of [aselect_url] in the traditional way too!
            sIdpSelectForm = Utils.replaceString(sIdpSelectForm, "[handler_url]", sMyUrl + "/" + getID());
            sIdpSelectForm = Utils.replaceString(sIdpSelectForm, "[aselect_url]", sMyUrl); // 20110310 + "/" + getID());
            sIdpSelectForm = Utils.replaceString(sIdpSelectForm, "[handler_id]", getID());
            sIdpSelectForm = Utils.replaceString(sIdpSelectForm, "[a-select-server]", _sServerId); // 20110310
            //sSelectForm = Utils.replaceString(sSelectForm, "[language]", sLanguage);
            sIdpSelectForm = _configManager.updateTemplate(sIdpSelectForm, _htSessionContext, servletRequest); // 20130822, Bauke: added to show requestor_friendly_name
            _systemLogger.log(Level.FINER, MODULE, sMethod,
                    "Template updated, [handler_url]=" + sMyUrl + "/" + getID());

            _htSessionContext.put("user_state", "state_idpselect");
            _oSessionManager.setUpdateSession(_htSessionContext, _systemLogger); // 20120403, Bauke: was updateSession
            Tools.pauseSensorData(_configManager, _systemLogger, _htSessionContext); //20111102 can update the session
            pwOut.println(sIdpSelectForm);
            return new RequestState(null);
        }
        // federation_url was set or bIdpSelectForm is false
        _systemLogger.log(Level.FINER, MODULE, sMethod, "federation_url=" + sFederationUrl);
        _htSessionContext.put("user_state", "state_toidp"); // at least remove state_select
        _oSessionManager.setUpdateSession(_htSessionContext, _systemLogger); // 20120403, Bauke: was updateSession

        // 20110308, Bauke: new mechanism to get to the IdP using the SAM agent (allows redundant resources)
        // User choice was made, or "federation_url" was set programmatically
        ASelectSAMAgent samAgent = ASelectSAMAgent.getHandle();
        SAMResource samResource = null;
        try {
            samResource = samAgent.getActiveResource(_sIdpResourceGroup);
        } catch (ASelectSAMException ex) { // no active resource
            // if a fallback is present: REDIRECT to the authsp
            if (Utils.hasValue(_sFallbackUrl)) {
                // Don't come back here:
                _htSessionContext.remove("forced_authsp");
                // 20110331, Bauke: We leave forced_uid in place!
                // If we do, control can easily be transferred to e.g. DigiD
                //htSessionContext.remove("forced_uid");
                _oSessionManager.setUpdateSession(_htSessionContext, _systemLogger); // 20120403, Bauke: added

                String sRedirectUrl = _sFallbackUrl;
                //sRedirectUrl = "[aselect_url]?request=direct_login1&rid=[rid]&authsp=Ldap&a-select-server=[a-select-server]";
                sRedirectUrl = Utils.replaceString(sRedirectUrl, "[aselect_url]", sMyUrl);
                sRedirectUrl = Utils.replaceString(sRedirectUrl, "[a-select-server]", _sServerId);
                sRedirectUrl = Utils.replaceString(sRedirectUrl, "[rid]", sRid);
                //sRedirectUrl = Utils.replaceString(sRedirectUrl, "[language]", sLanguage);
                _systemLogger.log(Level.FINER, MODULE, sMethod, "Fallback REDIRECT to: " + sRedirectUrl);

                Tools.pauseSensorData(_configManager, _systemLogger, _htSessionContext); //20111102 can change the session
                //_oSessionManager.updateSession(sRid, _htSessionContext);  // 20120403, Bauke: removed
                servletResponse.sendRedirect(sRedirectUrl);
                return new RequestState(null);
            } else {
                _systemLogger.log(Level.WARNING, MODULE, sMethod, "No active resource available");
                throw new ASelectSAMException(Errors.ERROR_ASELECT_SAM_UNAVALABLE);
            }
        }
        // The result is a single resource from our own resourcegroup
        sFederationUrl = samResource.getId();
        _systemLogger.log(Level.FINER, MODULE, sMethod, "IdP resource id=" + sFederationUrl);

        // 20090811, Bauke: save type of Authsp to store in the TGT later on
        // This is needed to prevent session sync when we're not saml20
        _htSessionContext.put("authsp_type", "saml20");
        _htSessionContext.put("federation_url", sFederationUrl);
        _oSessionManager.setUpdateSession(_htSessionContext, _systemLogger); // 20120403, Bauke: was updateSession

        _systemLogger.log(Level.FINER, MODULE, sMethod, "Get MetaData FederationUrl=" + sFederationUrl);
        MetaDataManagerSp metadataMgr = MetaDataManagerSp.getHandle();
        // RM_57_01
        // RM_57_02
        // We now support the Redirect and POST Binding
        String sDestination = null;
        if ("POST".equalsIgnoreCase(_sHttpMethod)) {
            sDestination = metadataMgr.getLocation(sFederationUrl,
                    SingleSignOnService.DEFAULT_ELEMENT_LOCAL_NAME, singleSignOnServiceBindingConstantHTTPPOST);
        } else {
            sDestination = metadataMgr.getLocation(sFederationUrl,
                    SingleSignOnService.DEFAULT_ELEMENT_LOCAL_NAME, singleSignOnServiceBindingConstantREDIRECT);
        }
        _systemLogger.log(Level.FINER, MODULE, sMethod, "Location retrieved=" + sDestination);
        if ("".equals(sDestination))
            throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);

        String sApplicationId = (String) _htSessionContext.get("app_id");
        String sApplicationLevel = getApplicationLevel(sApplicationId);
        String sAuthnContextClassRefURI = SecurityLevel.convertLevelToAuthnContextClassRefURI(sApplicationLevel,
                _systemLogger);
        // 20100428, Bauke: old: String sAuthnContextClassRefURI = levelMap.get(sApplicationLevel);
        if (sAuthnContextClassRefURI == null) {
            // this level was not configured. Log it and inform the user
            _systemLogger.log(Level.WARNING, MODULE, sMethod,
                    "Application Level " + sApplicationLevel + " is not configured");
            throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_APP_LEVEL);
        }

        // Send SAML request to the IDP
        XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();

        SAMLObjectBuilder<AuthnContextClassRef> authnContextClassRefBuilder = (SAMLObjectBuilder<AuthnContextClassRef>) builderFactory
                .getBuilder(AuthnContextClassRef.DEFAULT_ELEMENT_NAME);
        AuthnContextClassRef authnContextClassRef = authnContextClassRefBuilder.buildObject();

        authnContextClassRef.setAuthnContextClassRef(sAuthnContextClassRefURI);

        SAMLObjectBuilder<RequestedAuthnContext> requestedAuthnContextBuilder = (SAMLObjectBuilder<RequestedAuthnContext>) builderFactory
                .getBuilder(RequestedAuthnContext.DEFAULT_ELEMENT_NAME);
        RequestedAuthnContext requestedAuthnContext = requestedAuthnContextBuilder.buildObject();
        requestedAuthnContext.getAuthnContextClassRefs().add(authnContextClassRef);

        // 20100311, Bauke: added for eHerkenning
        PartnerData partnerData = MetaDataManagerSp.getHandle().getPartnerDataEntry(sFederationUrl);
        _systemLogger.log(Level.FINER, MODULE, sMethod, "Partnerdata: " + partnerData);
        String specialSettings = (partnerData == null) ? null : partnerData.getSpecialSettings();
        if (specialSettings != null && specialSettings.contains("minimum"))
            requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.MINIMUM);
        else
            requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);

        // 20120706, Bauke: save in session, must be transferred to TGT and used for Digid4 session_sync mechanism
        String sst = partnerData.getRedirectSyncTime();
        if (Utils.hasValue(sst)) {
            _htSessionContext.put("redirect_sync_time", sst);
            _htSessionContext.put("redirect_ists_url", sMyUrl + "/" + getID());
            _htSessionContext.put("redirect_post_form", partnerData.getRedirectPostForm());
            _oSessionManager.setUpdateSession(_htSessionContext, _systemLogger);
        }

        SAMLObjectBuilder<Issuer> issuerBuilder = (SAMLObjectBuilder<Issuer>) builderFactory
                .getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
        Issuer issuer = issuerBuilder.buildObject();
        // 20100311, Bauke: Alternate Issuer, added for eHerkenning
        if (partnerData != null && partnerData.getLocalIssuer() != null)
            issuer.setValue(partnerData.getLocalIssuer());
        else
            issuer.setValue(sMyUrl);

        // AuthnRequest
        SAMLObjectBuilder<AuthnRequest> authnRequestbuilder = (SAMLObjectBuilder<AuthnRequest>) builderFactory
                .getBuilder(AuthnRequest.DEFAULT_ELEMENT_NAME);
        AuthnRequest authnRequest = authnRequestbuilder.buildObject();

        // We should be able to set AssertionConsumerServiceIndex. This is according to saml specs mutually exclusive with
        // ProtocolBinding and AssertionConsumerServiceURL

        if (partnerData != null)
            _systemLogger.log(Level.FINER, MODULE, sMethod,
                    "acsi=" + partnerData.getAssertionConsumerServiceindex());

        if (partnerData != null && partnerData.getAssertionConsumerServiceindex() != null) {
            authnRequest.setAssertionConsumerServiceIndex(
                    Integer.parseInt(partnerData.getAssertionConsumerServiceindex()));
        } else { // mutually exclusive
            // 20100311, Bauke: added for eHerkenning
            // The assertion consumer url must be set to the value in the Metadata:
            // 20101112, RH, added support for POST binding
            if (specialSettings != null && specialSettings.toUpperCase().contains("POST"))
                authnRequest.setProtocolBinding(Saml20_Metadata.singleSignOnServiceBindingConstantPOST);
            else // backward compatibility, defaults to ARTIFACT
                authnRequest
                        .setProtocolBinding(Saml20_Metadata.assertionConsumerServiceBindingConstantARTIFACT);

            // We should be able to not set setAssertionConsumerServiceURL and let IDP get it from metadata
            // But not sure if all idp's will handle that well
            if (partnerData != null && partnerData.getDestination() != null) {
                if (!"".equals(partnerData.getDestination().trim())) { // if empty, let the idp look for the AssertionConsumerServiceURL in metadata 
                    authnRequest.setAssertionConsumerServiceURL(partnerData.getDestination());
                }
            } else { // backward compatibility, default to _sAssertionConsumerUrl
                authnRequest.setAssertionConsumerServiceURL(_sAssertionConsumerUrl);
            }
        }

        // RH, 20140505, sn
        String sForcedAttrConServInd = ApplicationManager.getHandle()
                .getForcedAttrConsServIndex(sApplicationId);
        if (sForcedAttrConServInd != null) {
            authnRequest.setAttributeConsumingServiceIndex(Integer.parseInt(sForcedAttrConServInd));
        } else {
            // RH, 20140505, en

            if (partnerData != null && partnerData.getAttributeConsumerServiceindex() != null) {
                authnRequest.setAttributeConsumingServiceIndex(
                        Integer.parseInt(partnerData.getAttributeConsumerServiceindex()));
            } else { // be backwards compatible
                authnRequest.setAttributeConsumingServiceIndex(2);
            }

        } // RH, 20140505, n

        authnRequest.setDestination(sDestination);
        DateTime tStamp = new DateTime();
        // Set interval conditions
        authnRequest = (AuthnRequest) SamlTools.setValidityInterval(authnRequest, tStamp, getMaxNotBefore(),
                getMaxNotOnOrAfter());

        // 20100531, Bauke, use Rid but add part of the timestamp to make the ID unique
        // The AssertionConsumer will strip it off to regain our Rid value
        String timePostFix = String.format("%02d%02d%02d%03d", tStamp.getHourOfDay(), tStamp.getMinuteOfHour(),
                tStamp.getSecondOfMinute(), tStamp.getMillisOfSecond());
        authnRequest.setID(sRid + timePostFix);

        authnRequest.setProviderName(_sServerId);
        authnRequest.setVersion(SAMLVersion.VERSION_20);
        authnRequest.setIssuer(issuer);
        authnRequest.setIssueInstant(new DateTime()); // 20100712
        authnRequest.setRequestedAuthnContext(requestedAuthnContext);

        // Check if we have to set the ForceAuthn attribute
        // 20090613, Bauke: use forced_authenticate (not forced_logon)!
        Boolean bForcedAuthn = (Boolean) _htSessionContext.get("forced_authenticate");
        if (bForcedAuthn == null)
            bForcedAuthn = false;
        // 20100311, Bauke: "force" special_setting added for eHerkenning
        if (bForcedAuthn || (specialSettings != null && specialSettings.contains("force"))) {
            _systemLogger.log(Level.INFO, MODULE, sMethod, "Setting the ForceAuthn attribute");
            authnRequest.setForceAuthn(true);
        }

        // 20140924, RH: "force_passive" special_setting (only for testing yet)
        // If needed in production must have its own element/attribuut in config
        Boolean bForcedPassive = (Boolean) _htSessionContext.get("forced_passive");
        if (bForcedPassive || (specialSettings != null && specialSettings.contains("passive"))) {
            _systemLogger.log(Level.INFO, MODULE, sMethod, "Setting the IsPassive attribute");
            authnRequest.setIsPassive(true);
        }

        // Handle testdata
        if (partnerData.getTestdata4partner() != null) {
            String timeOffset = partnerData.getTestdata4partner().getIssueInstant();
            if (timeOffset != null) {
                //               if (timeOffset.startsWith("-")) {
                //                  authnRequest.setIssueInstant(new DateTime().minus(1000*Long.parseLong(timeOffset)));
                //               } else {
                authnRequest.setIssueInstant(new DateTime().plus(1000 * Long.parseLong(timeOffset)));
                //               }
                // RM_57_03
            }
            if (partnerData.getTestdata4partner().getIssuer() != null) {
                authnRequest.getIssuer().setValue(partnerData.getTestdata4partner().getIssuer());
            }
            if (partnerData.getTestdata4partner().getAuthnContextClassRefURI() != null) {
                // There should be one so take first
                authnRequest.getRequestedAuthnContext().getAuthnContextClassRefs().get(0)
                        .setAuthnContextClassRef(
                                partnerData.getTestdata4partner().getAuthnContextClassRefURI());
            }
            if (partnerData.getTestdata4partner().getAuthnContextComparisonTypeEnumeration() != null) {
                if ("minimum".equalsIgnoreCase(
                        partnerData.getTestdata4partner().getAuthnContextComparisonTypeEnumeration()))
                    requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.MINIMUM);
                else if ("exact".equalsIgnoreCase(
                        partnerData.getTestdata4partner().getAuthnContextComparisonTypeEnumeration()))
                    requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
                else if ("better".equalsIgnoreCase(
                        partnerData.getTestdata4partner().getAuthnContextComparisonTypeEnumeration()))
                    requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.BETTER);
                else if ("maximum".equalsIgnoreCase(
                        partnerData.getTestdata4partner().getAuthnContextComparisonTypeEnumeration()))
                    requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.MAXIMUM);
            }
            if (partnerData.getTestdata4partner().getForceAuthn() != null) {
                authnRequest
                        .setForceAuthn(Boolean.parseBoolean(partnerData.getTestdata4partner().getForceAuthn()));
            }
            if (partnerData.getTestdata4partner().getProviderName() != null) {
                authnRequest.setProviderName(partnerData.getTestdata4partner().getProviderName());

            }
            if (partnerData.getTestdata4partner().getAssertionConsumerServiceIndex() != null) {
                // RM_57_04
                authnRequest.setAssertionConsumerServiceIndex(
                        Integer.parseInt(partnerData.getTestdata4partner().getAssertionConsumerServiceIndex()));
            }
            if (partnerData.getTestdata4partner().getAssertionConsumerServiceURL() != null) {
                authnRequest.setAssertionConsumerServiceURL(
                        partnerData.getTestdata4partner().getAssertionConsumerServiceURL());
            }
            if (partnerData.getTestdata4partner().getDestination() != null) {
                authnRequest.setDestination(partnerData.getTestdata4partner().getDestination());
            }

        }

        // 20100908, Bauke: Look for aselect_specials!
        // In app_url or in the caller's RelayState (if we're an IdP)
        String sSpecials = null;
        if (specialSettings != null && specialSettings.contains("relay_specials")) {
            sSpecials = Utils.getAselectSpecials(_htSessionContext, false/*leave base64*/, _systemLogger);
        }
        _systemLogger.log(Level.FINER, MODULE, sMethod,
                "<special_settings>=" + specialSettings + " aselect_specials=" + sSpecials);

        // Create the new RelayState
        String sRelayState = "idp=" + sFederationUrl;
        if (specialSettings != null && specialSettings.contains("relay_specials")) {
            if (Utils.hasValue(sSpecials))
                sRelayState += "&aselect_specials=" + sSpecials;
            sRelayState = Base64Codec.encode(sRelayState.getBytes());
            _systemLogger.log(Level.FINER, MODULE, sMethod, "RelayState=" + sRelayState);
        }

        //
        // We have the AuthnRequest, now get it to the other side
        //
        boolean useSha256 = (specialSettings != null && specialSettings.contains("sha256"));
        if (_sHttpMethod.equals("GET")) {
            // No use signing the AuthnRequest, it's even forbidden according to the Saml specs
            // Brent Putman quote: The Redirect-DEFLATE binding encoder strips off the protocol message's ds:Signature element (if even present)
            // before the marshalling and signing operations. Per the spec, it's not allowed to carry the signature that way.
            SAMLObjectBuilder<Endpoint> endpointBuilder = (SAMLObjectBuilder<Endpoint>) builderFactory
                    .getBuilder(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
            Endpoint samlEndpoint = endpointBuilder.buildObject();
            samlEndpoint.setLocation(sDestination);
            samlEndpoint.setResponseLocation(sMyUrl);
            _systemLogger.log(Level.FINER, MODULE, sMethod,
                    "GET EndPoint=" + samlEndpoint + " Destination=" + sDestination);

            //HttpServletResponseAdapter outTransport = SamlTools.createHttpServletResponseAdapter(response, sDestination);
            HttpServletResponseAdapter outTransport = new HttpServletResponseAdapter(servletResponse,
                    (sDestination == null) ? false : sDestination.toLowerCase().startsWith("https"));

            // RH, 20081113, set appropriate headers
            outTransport.setHeader("Pragma", "no-cache");
            outTransport.setHeader("Cache-Control", "no-cache, no-store");

            BasicSAMLMessageContext messageContext = new BasicSAMLMessageContext();
            messageContext.setOutboundMessageTransport(outTransport);
            messageContext.setOutboundSAMLMessage(authnRequest);
            messageContext.setPeerEntityEndpoint(samlEndpoint);

            BasicX509Credential credential = new BasicX509Credential();
            PrivateKey key = _configManager.getDefaultPrivateKey();
            credential.setPrivateKey(key);
            messageContext.setOutboundSAMLMessageSigningCredential(credential);

            // 20091028, Bauke: use RelayState to transport rid to my AssertionConsumer
            messageContext.setRelayState(sRelayState);

            MarshallerFactory marshallerFactory = Configuration.getMarshallerFactory();
            Marshaller marshaller = marshallerFactory.getMarshaller(messageContext.getOutboundSAMLMessage());
            Node nodeMessageContext = marshaller.marshall(messageContext.getOutboundSAMLMessage());
            _systemLogger.log(Level.FINER, MODULE, sMethod, "RelayState=" + sRelayState
                    + " OutboundSAMLMessage:\n" + XMLHelper.prettyPrintXML(nodeMessageContext));

            if (useSha256) {
                Saml20_RedirectEncoder encoder = new Saml20_RedirectEncoder(); // is a HTTPRedirectDeflateEncoder
                encoder.encode(messageContext); // does a sendRedirect()
            } else {
                // HTTPRedirectDeflateEncoder: SAML 2.0 HTTP Redirect encoder using the DEFLATE encoding method.
                // This encoder only supports DEFLATE compression and DSA-SHA1 and RSA-SHA1 signatures.
                HTTPRedirectDeflateEncoder encoder = new HTTPRedirectDeflateEncoder();
                encoder.encode(messageContext); // does a sendRedirect()
            }
            _systemLogger.log(Level.FINER, MODULE, sMethod, "Ready " + messageContext);
        } else { // POST
            // 20100331, Bauke: added support for HTTP POST
            _systemLogger.log(Level.FINER, MODULE, sMethod, "Sign the authnRequest >======" + authnRequest);
            authnRequest = (AuthnRequest) SamlTools.signSamlObject(authnRequest, useSha256 ? "sha256" : "sha1",
                    "true".equalsIgnoreCase(partnerData.getAddkeyname()),
                    "true".equalsIgnoreCase(partnerData.getAddcertificate()));
            _systemLogger.log(Level.FINER, MODULE, sMethod, "Signed the authnRequest ======<" + authnRequest);

            String sAssertion = XMLHelper.nodeToString(authnRequest.getDOM());
            _systemLogger.log(Level.FINER, MODULE, sMethod, "Assertion=" + sAssertion);
            try {
                byte[] bBase64Assertion = sAssertion.getBytes("UTF-8");
                BASE64Encoder b64enc = new BASE64Encoder();
                sAssertion = b64enc.encode(bBase64Assertion);
            } catch (UnsupportedEncodingException e) {
                _systemLogger.log(Level.WARNING, MODULE, sMethod, e.getMessage(), e);
                throw new ASelectException(Errors.ERROR_ASELECT_INTERNAL_ERROR);
            }

            // Let's POST the token
            String sInputs = buildHtmlInput("RelayState", sRelayState);
            //            sInputs += buildHtmlInput("SAMLResponse", sAssertion);  //Tools.htmlEncode(nodeMessageContext.getTextContent()));
            // RH, 20101104, this should be a SAMLRequest, we were just lucky the other side didn't bother   
            sInputs += buildHtmlInput("SAMLRequest", sAssertion); //Tools.htmlEncode(nodeMessageContext.getTextContent()));

            // 20100317, Bauke: pass language to IdP (does not work in the GET version)
            String sLang = (String) _htSessionContext.get("language");
            if (sLang != null)
                sInputs += buildHtmlInput("language", sLang);

            _systemLogger.log(Level.FINER, MODULE, sMethod, "Inputs=" + Utils.firstPartOf(sInputs, 200));
            handlePostForm(_sPostTemplate, sDestination, sInputs, servletRequest, servletResponse);
        }
        Tools.pauseSensorData(_configManager, _systemLogger, _htSessionContext); //20111102 can change the session
    } catch (ASelectException e) { // pass unchanged to the caller
        throw e;
    } catch (Exception e) {
        _systemLogger.log(Level.SEVERE, MODULE, sMethod, "Could not process", e);
        throw new ASelectException(Errors.ERROR_ASELECT_INTERNAL_ERROR, e);
    } finally {
        if (pwOut != null)
            pwOut.close();

        // 20130821, Bauke: save friendly name after session is gone
        if (_htSessionContext != null) {
            String sStatus = (String) _htSessionContext.get("status");
            String sAppId = (String) _htSessionContext.get("app_id");
            if ("del".equals(sStatus) && Utils.hasValue(sAppId)) {
                String sUF = ApplicationManager.getHandle().getFriendlyName(sAppId);
                HandlerTools.setEncryptedCookie(servletResponse, "requestor_friendly_name", sUF,
                        _configManager.getCookieDomain(), -1/*age*/, _systemLogger);
            }
        }
        _oSessionManager.finalSessionProcessing(_htSessionContext, true/*update session*/);
    }
    return new RequestState(null);
}

From source file:org.assertj.jodatime.api.DateTimeAssert.java

License:Apache License

/**
 * Returns true if both datetime are in the same year, month, day of month, hour and minute, false otherwise.
 * /*from   ww  w.ja v a  2s.  c o  m*/
 * @param actual the actual datetime. expected not be null
 * @param other the other datetime. expected not be null
 * @return true if both datetime are in the same year, month, day of month, hour and minute, false otherwise.
 */
private static boolean areEqualIgnoringSeconds(DateTime actual, DateTime other) {
    return areEqualIgnoringMinutes(actual, other) && actual.getMinuteOfHour() == other.getMinuteOfHour();
}

From source file:org.attribyte.wp.model.Site.java

License:Apache License

/**
 * Builds the permalink for a post from this site.
 * @param post The post.//ww  w  .  j  a v  a2s.  c o m
 * @return The permalink string.
 * @see <a href="https://codex.wordpress.org/Using_Permalinks">https://codex.wordpress.org/Using_Permalinks</a>
 */
public String buildPermalink(final Post post) {

    final String authorSlug = post.author != null ? Strings.nullToEmpty(post.author.slug) : "";
    final List<TaxonomyTerm> categories = post.categories();
    final Term categoryTerm = categories.size() > 0 ? categories.get(0).term : defaultCategory;
    final String category = categoryTerm != null ? categoryTerm.slug : "";
    final String post_id = Long.toString(post.id);
    final DateTime publishTime = new DateTime(post.publishTimestamp);
    final String year = Integer.toString(publishTime.getYear());
    final String monthnum = String.format("%02d", publishTime.getMonthOfYear());
    final String day = String.format("%02d", publishTime.getDayOfMonth());
    final String hour = String.format("%02d", publishTime.getHourOfDay());
    final String minute = String.format("%02d", publishTime.getMinuteOfHour());
    final String second = String.format("%02d", publishTime.getSecondOfMinute());
    final String path = permalinkStructure.replace("%year%", year).replace("%monthnum%", monthnum)
            .replace("%day%", day).replace("%hour%", hour).replace("%minute%", minute)
            .replace("%second%", second).replace("%post_id%", post_id).replace("%postname%", post.slug)
            .replace("%category%", category).replace("%author%", authorSlug);
    return baseURL + path;
}

From source file:org.bensteele.jirrigate.Irrigator.java

License:Open Source License

/**
 * Returns the time and date the next irrigation is due based on the watering_days and
 * watering_start_time. It does not take into account whether or not any of the {@link Controller}
 * are active./*from  w ww .j a v  a2  s  . c  o  m*/
 *
 * @return The time and date of the next irrigation for any controller under this irrigator's
 * control.
 */
protected DateTime nextIrrigationAt() {
    DateTime dt = new DateTime();
    for (int i = 0; i < 7; i++) {
        for (final int dayOfWeek : wateringDays) {
            if (dayOfWeek == (dt.getDayOfWeek())) {
                // If it's the first run then we may match the same day we are currently on, in this case
                // we need to check that we don't report a time in the past. Validate that the hour and
                // minute right now are not past the scheduled watering time. If it's not the first run
                // then it's ok to let through.
                if (i != 0 || (i == 0 && dt.toLocalTime().isBefore(wateringStartTime))) {

                    // Reset the hour to 0 and increment until we match the watering hour.
                    dt = dt.withHourOfDay(0);
                    while (dt.getHourOfDay() < wateringStartTime.getHourOfDay()) {
                        dt = dt.plusHours(1);
                    }

                    // Reset the minute to 0 and increment until we match the watering minute.
                    dt = dt.withMinuteOfHour(0);
                    while (dt.getMinuteOfHour() < wateringStartTime.getMinuteOfHour()) {
                        dt = dt.plusMinutes(1);
                    }
                    return dt;
                }
            }
        }
        dt = dt.plusDays(1);
    }
    return null;
}

From source file:org.classbooker.service.ReservationMgrServiceImpl.java

private boolean incorrectFormatDateTime(DateTime datetime) {
    return datetime.getMinuteOfHour() != 0 && datetime.getSecondOfMinute() != 0
            && datetime.getMillisOfSecond() != 0;
}

From source file:org.conqat.engine.bugzilla.lib.Bug.java

License:Apache License

/** Get milliseconds of an enumeration field that is holding a date. */
public long getMilliSeconds(EBugzillaField field) {
    // TODO (BH): Why variable here?
    long milliSeconds = 0;

    // TODO (BH): I would invert the condition and return/throw here to
    // reduce the nesting.
    if (fields.get(field) != null) {

        // TODO (BH): Why store value and overwrite in next line? You could
        // also move this outside of the if and use the variable in the if
        // expression.
        String bugzillaDate = StringUtils.EMPTY_STRING;
        bugzillaDate = fields.get(field);

        // TODO (BH): Make constants from these pattern
        Pattern todayPattern = Pattern.compile("[0-9]{2}:[0-9]{2}:[0-9]{2}");
        Pattern lastWeekPattern = Pattern.compile("[A-Z][a-z][a-z] [0-9]{2}:[0-9]{2}");
        Pattern anyDatePattern = Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2}");

        // TODO (BH): Variables only used once. Inline?
        Matcher todayMatcher = todayPattern.matcher(bugzillaDate);
        Matcher lastWeekMatcher = lastWeekPattern.matcher(bugzillaDate);
        Matcher anyDateMatcher = anyDatePattern.matcher(bugzillaDate);

        if (anyDateMatcher.matches()) {

            // TODO (BH): Make this a constant?
            DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");
            // TODO (BH): Directly return?
            milliSeconds = dateTimeFormatter.parseDateTime(bugzillaDate).getMillis();

        } else if (lastWeekMatcher.matches()) {

            DateTime lastWeekDate = new DateTime(Chronic.parse(bugzillaDate).getBeginCalendar().getTime());

            // Since jchronic parses the Bugzilla format exactly seven days
            // to late, we need to subtract those 7 days.
            // TODO (BH): Directly return?
            milliSeconds = lastWeekDate.minusDays(7).getMillis();

        } else if (todayMatcher.matches()) {

            DateTime todayDate = new DateTime();

            // TODO (BH): Make this a constant?
            DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("HH:mm:ss");
            DateTime fieldDate = dateTimeFormatter.parseDateTime(bugzillaDate);

            // TODO (BH): Directly return?
            milliSeconds = new DateTime(todayDate.getYear(), todayDate.getMonthOfYear(),
                    todayDate.getDayOfMonth(), fieldDate.getHourOfDay(), fieldDate.getMinuteOfHour(),
                    fieldDate.getSecondOfMinute()).getMillis();

        } else {/*from  www .  j av a  2 s . co  m*/
            // TODO (BH): I think this is not a good way of handling this
            // error as the argument might be valid, but the data is just
            // not good. Better use a checked exception, such as
            // ConQATException.
            throw new IllegalArgumentException("Field is not a Bugzilla date.");
        }

    } else {
        // TODO (BH): I think this is not a good way of handling this error
        // as the argument might be valid, but the data is just not present.
        // Better use a checked exception, such as ConQATException.
        throw new IllegalArgumentException("Argument is not a Bugzilla field.");
    }

    return milliSeconds;
}