List of usage examples for org.joda.time DateTime getHourOfDay
public int getHourOfDay()
From source file:org.agatom.springatom.web.validator.AppointmentValidator.java
License:Open Source License
private void validateDates(final NAppointment appointment, final ValidationContext context) { final MessageContext messageContext = context.getMessageContext(); final MessageBuilder messageBuilder = new MessageBuilder(); final DateTime begin = appointment.getBegin(); final DateTime end = appointment.getEnd(); final int beginHourOfDay = begin.getHourOfDay(); final int endHourOfDay = end.getHourOfDay(); if (beginHourOfDay < this.minTime) { messageContext.addMessage(messageBuilder.source("begin").error() .defaultText(String.format("Begin hour must not be lower than %d", this.minTime)).build()); }//from w w w. j a va 2s . c om if (endHourOfDay > this.maxTime) { messageContext.addMessage(messageBuilder.source("end").error() .defaultText(String.format("End hour must not be higher than %d", this.maxTime)).build()); } if (begin.isAfter(end)) { messageContext.addMessage( messageBuilder.source("begin").error().defaultText("Begin must be before End").build()); } else { final Duration duration = new Duration(end.minus(begin.getMillis()).getMillis()); if (duration.isShorterThan(new Duration(this.minDiffBetweenDates))) { messageContext .addMessage( messageBuilder.source("interval").warning() .defaultText(String.format("Time of appointment is shorter than %d minutes", TimeUnit.MILLISECONDS.toMinutes(this.minDiffBetweenDates))) .build()); } else if (duration.isLongerThan(new Duration(this.maxDiffBetweenDates))) { messageContext.addMessage(messageBuilder.source("interval").warning() .defaultText(String.format("Time of appointment is longer than %d days", TimeUnit.MILLISECONDS.toDays(this.maxDiffBetweenDates))) .build()); } } }
From source file:org.aludratest.cloud.web.report.ResourceReportUtil.java
License:Apache License
private static JavaScriptObject createTimeEntry(DateTime time, int activeResources) { JavaScriptObject result = new JavaScriptObject(); time = time.toDateTime(DateTimeZone.UTC); // convert time to JavaScript UTC time StringBuilder sbDateTime = new StringBuilder(); sbDateTime.append("Date.UTC("); sbDateTime.append(time.getYear()).append(", "); sbDateTime.append(time.getMonthOfYear() - 1).append(", "); sbDateTime.append(time.getDayOfMonth()).append(", "); sbDateTime.append(time.getHourOfDay()).append(", "); sbDateTime.append(time.getMinuteOfHour()).append(", "); sbDateTime.append(time.getSecondOfMinute()).append(", "); sbDateTime.append(time.getMillisOfSecond()).append(")"); result.set("x", new JavaScriptCodeFragment(sbDateTime.toString())); result.set("y", new JavaScriptCodeFragment("" + activeResources)); return result; }
From source file:org.apache.beam.sdk.io.jdbc.JdbcUtil.java
License:Apache License
private static Calendar getDateOrTimeOnly(DateTime dateTime, boolean wantDateOnly) { Calendar cal = Calendar.getInstance(); cal.setTimeZone(TimeZone.getTimeZone(dateTime.getZone().getID())); if (wantDateOnly) { // return date only cal.set(Calendar.YEAR, dateTime.getYear()); cal.set(Calendar.MONTH, dateTime.getMonthOfYear() - 1); cal.set(Calendar.DATE, dateTime.getDayOfMonth()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); } else { // return time only cal.set(Calendar.YEAR, 1970); cal.set(Calendar.MONTH, Calendar.JANUARY); cal.set(Calendar.DATE, 1); cal.set(Calendar.HOUR_OF_DAY, dateTime.getHourOfDay()); cal.set(Calendar.MINUTE, dateTime.getMinuteOfHour()); cal.set(Calendar.SECOND, dateTime.getSecondOfMinute()); cal.set(Calendar.MILLISECOND, dateTime.getMillisOfSecond()); }//w ww . j a v a 2s.c o m return cal; }
From source file:org.apache.isis.applib.value.Time.java
License:Apache License
/** * Create a Time object for storing a time with the time set to the * specified time of the Joda Time DateTime object. *///from ww w.ja v a 2s. c o m public Time(final DateTime dateTime) { this.time = newDateTime(dateTime.getHourOfDay(), dateTime.getMinuteOfHour(), dateTime.getSecondOfMinute()); }
From source file:org.apache.pig.pen.AugmentBaseDataVisitor.java
License:Apache License
Object GetSmallerValue(Object v) { byte type = DataType.findType(v); if (type == DataType.BAG || type == DataType.TUPLE || type == DataType.MAP) return null; switch (type) { case DataType.CHARARRAY: String str = (String) v; if (str.length() > 0) return str.substring(0, str.length() - 1); else// w ww . java 2 s.c o m return null; case DataType.BYTEARRAY: DataByteArray data = (DataByteArray) v; if (data.size() > 0) return new DataByteArray(data.get(), 0, data.size() - 1); else return null; case DataType.INTEGER: return Integer.valueOf((Integer) v - 1); case DataType.LONG: return Long.valueOf((Long) v - 1); case DataType.FLOAT: return Float.valueOf((Float) v - 1); case DataType.DOUBLE: return Double.valueOf((Double) v - 1); case DataType.BIGINTEGER: return ((BigInteger) v).subtract(BigInteger.ONE); case DataType.BIGDECIMAL: return ((BigDecimal) v).subtract(BigDecimal.ONE); case DataType.DATETIME: DateTime dt = (DateTime) v; if (dt.getMillisOfSecond() != 0) { return dt.minusMillis(1); } else if (dt.getSecondOfMinute() != 0) { return dt.minusSeconds(1); } else if (dt.getMinuteOfHour() != 0) { return dt.minusMinutes(1); } else if (dt.getHourOfDay() != 0) { return dt.minusHours(1); } else { return dt.minusDays(1); } default: return null; } }
From source file:org.apache.pig.pen.AugmentBaseDataVisitor.java
License:Apache License
Object GetLargerValue(Object v) { byte type = DataType.findType(v); if (type == DataType.BAG || type == DataType.TUPLE || type == DataType.MAP) return null; switch (type) { case DataType.CHARARRAY: return (String) v + "0"; case DataType.BYTEARRAY: String str = ((DataByteArray) v).toString(); str = str + "0"; return new DataByteArray(str); case DataType.INTEGER: return Integer.valueOf((Integer) v + 1); case DataType.LONG: return Long.valueOf((Long) v + 1); case DataType.FLOAT: return Float.valueOf((Float) v + 1); case DataType.DOUBLE: return Double.valueOf((Double) v + 1); case DataType.BIGINTEGER: return ((BigInteger) v).add(BigInteger.ONE); case DataType.BIGDECIMAL: return ((BigDecimal) v).add(BigDecimal.ONE); case DataType.DATETIME: DateTime dt = (DateTime) v; if (dt.getMillisOfSecond() != 0) { return dt.plusMillis(1); } else if (dt.getSecondOfMinute() != 0) { return dt.plusSeconds(1); } else if (dt.getMinuteOfHour() != 0) { return dt.plusMinutes(1); } else if (dt.getHourOfDay() != 0) { return dt.plusHours(1); } else {/*from ww w. java 2s.co m*/ return dt.plusDays(1); } default: return null; } }
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.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 ww w .j av a 2s .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 . j a v a 2 s .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 and hour, false otherwise. * // www.jav a2 s . c om * @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 and hour, false otherwise. */ private static boolean areEqualIgnoringMinutes(DateTime actual, DateTime other) { return haveSameYearMonthAndDayOfMonth(actual, other) && actual.getHourOfDay() == other.getHourOfDay(); }