List of usage examples for java.util GregorianCalendar getTimeInMillis
public long getTimeInMillis()
From source file:com.qut.middleware.esoe.sso.impl.SSOProcessorImpl.java
private result validateSession(SSOProcessorData data) { String remoteAddr = data.getRemoteAddress(); try {/*from w w w. java2 s . c o m*/ AuthnRequest authnRequest = data.getAuthnRequest(); // Make sure the handler isn't dodgy. if (authnRequest == null) { this.logger.error( "[SSO for {}] Calling SSO handler did not set AuthnRequest in the bean. Unable to continue processing.", remoteAddr); return SSOProcessor.result.SSOGenerationFailed; } // Check these so we can assume they're non-null if (authnRequest.getNameIDPolicy() == null || authnRequest.getNameIDPolicy().isAllowCreate() == null || authnRequest.getIssuer() == null || authnRequest.getIssuer().getValue() == null) { this.logger.error( "[SSO for {}] AuthnRequest was not complete - some required information was omitted. Unable to process."); return SSOProcessor.result.SSOGenerationFailed; } // Go to grab the session ID (and anything else we need) from the cookies. this.processCookies(data); String sessionID = data.getSessionID(); data.setIssuerID(authnRequest.getIssuer().getValue()); // If the user did not present a session cookie... if (sessionID == null || sessionID.length() <= 0) { if (authnRequest.getNameIDPolicy().isAllowCreate().booleanValue()) { this.logger.info( "[SSO for {}] Session not established, forcing authentication operation on principal", remoteAddr); return SSOProcessor.result.ForceAuthn; } this.logger.warn( "[SSO for {}] Session is not established and SPEP has prevented establishment from being allowed non passively, creating failure response", remoteAddr); createStatusAuthnResponse(data, StatusCodeConstants.requester, StatusCodeConstants.requestDenied, "Session could not be resolved from previous session establishment data and SPEP will not allow session establishment", true); return SSOProcessor.result.ForcePassiveAuthn; } this.logger.debug("[SSO for {}] Querying sessions processor for session ID {}", new Object[] { remoteAddr, sessionID }); Principal principal = this.sessionsProcessor.getQuery().queryAuthnSession(sessionID); // If the user's session cookie does not point to a valid session. if (principal == null) { // This is the same logic as when they do not have a session cookie, just that the log statements are different. if (authnRequest.getNameIDPolicy().isAllowCreate().booleanValue()) { this.logger.warn( "[SSO for {}] Could not locate a current session in the session cache. Forcing authentication operation on principal", remoteAddr); return SSOProcessor.result.ForceAuthn; } this.logger.warn( "[SSO for {}] Could not locate a current session in the session cache, and SPEP has prevented establishment from being allowed non passively, creating failure response", remoteAddr); createStatusAuthnResponse(data, StatusCodeConstants.responder, StatusCodeConstants.authnFailed, "Could not locate principal in local session for supposedly active session identifier", true); return SSOProcessor.result.ForcePassiveAuthn; } // Store principal in the bean for future use. data.setPrincipal(principal); this.logger.debug( "[SSO for {}] Retrieved principal for session ID {} - principal authn identifier is {}", new Object[] { remoteAddr, sessionID, principal.getPrincipalAuthnIdentifier() }); if (authnRequest.isForceAuthn() != null && authnRequest.isForceAuthn().booleanValue()) { TimeZone utc = new SimpleTimeZone(0, ConfigurationConstants.timeZone); GregorianCalendar cal = new GregorianCalendar(utc); long thisTime = cal.getTimeInMillis(); /* * The SP has indicated it wishes to force authn. If our principal authenticated more then allowed time skew * in the past then we have to auth them again, the invisible else case is that the principal has * authenticated within the allowed time skew window thus they can continue on their way */ if ((thisTime - principal.getAuthnTimestamp() > this.allowedTimeSkew)) { /* * The SP indicated it expects the interaction to be passive and it wishes to ensure the principal * undertakes authn, we can't grant this so return error */ if (authnRequest.isIsPassive() != null && authnRequest.isIsPassive().booleanValue()) { this.logger.debug( "[SSO for {}] SPEP has requested forced authn as part of this SSO operation and has also requested only passive session establishment which is not supported", remoteAddr); createStatusAuthnResponse(data, StatusCodeConstants.responder, StatusCodeConstants.noPassive, "ESOE does not support passive only session establishment", true); return SSOProcessor.result.ForcePassiveAuthn; } this.logger.info( "[SSO for {}] SPEP has requested forced authn as part of this SSO operation, forcing authentication", remoteAddr); return SSOProcessor.result.ForceAuthn; } } /* Determine if we have an identifier for this principal to use when communicating with remote SPEP's */ if (principal.getSAMLAuthnIdentifier() == null || principal.getSAMLAuthnIdentifier().length() <= 0) { createStatusAuthnResponse(data, StatusCodeConstants.responder, StatusCodeConstants.authnFailed, "The SAMLID identifying this principal to SPEP's is corrupted or invalid", true); this.sessionsProcessor.getTerminate().terminateSession(sessionID); return SSOProcessor.result.SSOGenerationFailed; } /* Generate SAML session index */ String sessionIndex = this.identifierGenerator.generateSAMLSessionID(); this.sessionsProcessor.getUpdate().addEntitySessionIndex(principal, data.getIssuerID(), sessionIndex); this.authnLogger.info( "[SSO for {}] Session established for SAML ID {} at SPEP {} and endpoint {} Principal authn identifier is {} New session index is {}", new Object[] { remoteAddr, principal.getSAMLAuthnIdentifier(), data.getIssuerID(), data.getResponseEndpoint(), principal.getPrincipalAuthnIdentifier(), sessionIndex }); data.setSessionIndex(sessionIndex); // Return null to indicate that there is no user agent interaction required. return null; } catch (SessionCacheUpdateException e) { this.logger.error("[SSO for {}] Failed to update session cache. Error was: {}", new Object[] { remoteAddr, e.getMessage() }); this.logger.debug(MessageFormatter .format("[SSO for {}] Failed to update session cache. Exception follows.", remoteAddr), e); return SSOProcessor.result.SSOGenerationFailed; } catch (SSOException e) { this.logger.error("[SSO for {}] Failed to perform SSO operation. Error was: {}", new Object[] { remoteAddr, e.getMessage() }); this.logger.debug(MessageFormatter .format("[SSO for {}] Failed to perform SSO operation. Exception follows.", remoteAddr), e); return SSOProcessor.result.SSOGenerationFailed; } }
From source file:org.sakaiproject.calendar.impl.RecurrenceRuleBase.java
/** * Return a List of all RecurrenceInstance objects generated by this rule within the given time range, based on the * prototype first range, in time order./* www .j a v a2 s . c om*/ * @param prototype The prototype first TimeRange. * @param range A time range to limit the generated ranges. * @param timeZone The time zone to use for displaying times. * %%% Note: this is currently not implemented, and always uses the "local" zone. * @return a List of RecurrenceInstance generated by this rule in this range. */ public List generateInstances(TimeRange prototype, TimeRange range, TimeZone timeZone) { // these calendars are used if local time zone and the time zone where the first event was created (timeZone) are different GregorianCalendar firstEventCalendarDate = null; GregorianCalendar nextFirstEventCalendarDate = null; // %%% Note: base the breakdonw on the "timeZone" parameter to support multiple timeZone displays -ggolden TimeBreakdown startBreakdown = prototype.firstTime().breakdownLocal(); GregorianCalendar startCalendarDate = TimeService.getCalendar(TimeService.getLocalTimeZone(), 0, 0, 0, 0, 0, 0, 0); startCalendarDate.set(startBreakdown.getYear(), startBreakdown.getMonth() - 1, startBreakdown.getDay(), startBreakdown.getHour(), startBreakdown.getMin(), startBreakdown.getSec()); // if local time zone and first event time zone are different // a new calendar is generated to calculate the re-occurring events // if not, the local time zone calendar is used boolean differentTimeZone = false; if (TimeService.getLocalTimeZone().getID().equals(timeZone.getID())) { differentTimeZone = false; } else { differentTimeZone = true; } if (differentTimeZone) { firstEventCalendarDate = TimeService.getCalendar(timeZone, 0, 0, 0, 0, 0, 0, 0); firstEventCalendarDate.setTimeInMillis(startCalendarDate.getTimeInMillis()); nextFirstEventCalendarDate = (GregorianCalendar) firstEventCalendarDate.clone(); } List rv = new Vector(); GregorianCalendar nextCalendarDate = (GregorianCalendar) startCalendarDate.clone(); int currentCount = 1; do { if (differentTimeZone) { // next time is calculated according to the first event time zone, not the local one nextCalendarDate.setTimeInMillis(nextFirstEventCalendarDate.getTimeInMillis()); } Time nextTime = TimeService.newTime(nextCalendarDate); // is this past count? if ((getCount() > 0) && (currentCount > getCount())) break; // is this past until? if ((getUntil() != null) && isAfter(nextTime, getUntil())) break; TimeRange nextTimeRange = TimeService.newTimeRange(nextTime.getTime(), prototype.duration()); // // Is this out of the range? // if (isOverlap(range, nextTimeRange)) { TimeRange eventTimeRange = null; // Single time cases require special handling. if (prototype.isSingleTime()) { eventTimeRange = TimeService.newTimeRange(nextTimeRange.firstTime()); } else { eventTimeRange = TimeService.newTimeRange(nextTimeRange.firstTime(), nextTimeRange.lastTime(), true, false); } // use this one rv.add(new RecurrenceInstance(eventTimeRange, currentCount)); } // if next starts after the range, stop generating else if (isAfter(nextTime, range.lastTime())) break; // advance interval years. if (differentTimeZone) { nextFirstEventCalendarDate = (GregorianCalendar) firstEventCalendarDate.clone(); nextFirstEventCalendarDate.add(getRecurrenceType(), getInterval() * currentCount); } else { nextCalendarDate = (GregorianCalendar) startCalendarDate.clone(); nextCalendarDate.add(getRecurrenceType(), getInterval() * currentCount); } currentCount++; } while (true); return rv; }
From source file:org.opensingular.internal.lib.commons.xml.TestMElement.java
License:asdf
/** * Verifica se os mtodos de set e get para java.util.Date e GregorianCalendar funcionam. *//*from ww w . ja va 2 s . c o m*/ @Test public void testSetGetDatas() { GregorianCalendar agoraGc = new GregorianCalendar(2001, 2, 31, 23, 59, 49); agoraGc.set(GregorianCalendar.MILLISECOND, 123); Date agoraDate = new Date(agoraGc.getTimeInMillis()); MElement xml; //Teste ler e escrever Calendar xml = MElement.newInstance("T"); xml.addElement("V2", agoraGc); assertEquals("string calendar errada", xml.getValor("V2"), "2001-03-31T23:59:49.123"); assertEquals("Calendar gravado lido", xml.getCalendar("V2"), agoraGc); //Teste ler e escrever java.util.Date xml = MElement.newInstance("T"); xml.addElement("V", agoraDate); assertEquals("string util.date errada", xml.getValor("V"), "2001-03-31T23:59:49.123"); assertEquals("util.date gravado lido", xml.getDate("V"), agoraDate); //Testa adicionar data como string xml.addDate("V3", "08/01/2003"); assertEquals("data errada", xml.getValor("V3"), "2003-01-08"); //Testa formatao assertEquals("formatao errada", xml.formatDate("V3"), "08/01/2003"); assertEquals("formatao errada", xml.formatDate("V3", "short"), "08/01/03"); assertEquals("formatao errada", xml.formatDate("V3", "medium"), "08/01/2003"); }
From source file:com.qut.middleware.esoe.sso.impl.SSOProcessorImpl.java
private Response createSuccessfulAuthnResponseObject(SSOProcessorData data, String sessionIndex, String charset, boolean signed) throws SSOException { Principal principal = data.getPrincipal(); if (principal == null) { throw new SSOException("SSO response being generated for null principal. Unable to continue."); }/* w w w . j ava 2 s.co m*/ String remoteAddress = data.getRemoteAddress(); this.logger.debug("[SSO for {}] Creating successful Authn response.", remoteAddress); AuthnStatement authnStatement = new AuthnStatement(); SubjectLocality subjectLocality = new SubjectLocality(); AuthnContext authnContext = new AuthnContext(); Subject subject = new Subject(); NameIDType issuer = new NameIDType(); NameIDType nameID = new NameIDType(); Signature signature = new Signature(); Conditions conditions = new Conditions(); Assertion assertion = new Assertion(); Status status = new Status(); StatusCode statusCode = new StatusCode(); Response response = new Response(); /* Generate subject locality */ subjectLocality.setDNSName(data.getHttpRequest().getServerName()); /* * Generate AuthnContext, SAML spec requires previous session to be set if user not directly authenticated * during this transaction */ TimeZone utc = new SimpleTimeZone(0, ConfigurationConstants.timeZone); GregorianCalendar cal = new GregorianCalendar(utc); long thisTime = cal.getTimeInMillis(); if (thisTime - principal.getAuthnTimestamp() > this.allowedTimeSkew) authnContext.setAuthnContextClassRef(AuthenticationContextConstants.previousSession); else authnContext.setAuthnContextClassRef(principal.getAuthenticationContextClass()); /* Generate successful authentication response for consumption by SPEP */ authnStatement.setAuthnInstant(CalendarUtils.generateXMLCalendar(0)); authnStatement.setSessionIndex(sessionIndex); /* Add our allowed time skew to the current time */ // TODO check that this is still accurate authnStatement .setSessionNotOnOrAfter(CalendarUtils.generateXMLCalendar(principal.getSessionNotOnOrAfter())); authnStatement.setSubjectLocality(subjectLocality); authnStatement.setAuthnContext(authnContext); /* Generate Issuer to attach to assertion and response */ issuer.setValue(this.esoeIdentifier); issuer.setFormat(NameIDFormatConstants.entity); /* populate subject to attach to assertion */ boolean setNameID = false; /** * If we're dealing with google insert mail identifier specially now and in special format until they correct * their problems */ if (data.getAuthnRequest().getIssuer().getValue().contains("google")) { /* Figure out what value we should try and get from the principals attributes - google wants email */ String attribName = this.identifierAttributeMapping.get(NameIDFormatConstants.emailAddress); if (attribName != null) { IdentityAttribute identityAttribute = principal.getAttributes().get(attribName); if (identityAttribute != null) { List<Object> attribValues = identityAttribute.getValues(); if (attribValues != null && attribValues.size() > 0) { String completeEmailAddress = (String) attribValues.get(0); int indAt = completeEmailAddress.indexOf('@'); nameID.setValue(completeEmailAddress.substring(0, indAt)); nameID.setFormat(NameIDFormatConstants.emailAddress); setNameID = true; } } } } else { if (data.getValidIdentifiers() != null) { this.logger.debug( "Got valid identifiers from Metadata or request, attempting to find appropriate value"); for (String identifier : data.getValidIdentifiers()) { if (NameIDFormatConstants.trans.equals(identifier)) { this.logger.info("Sending AuthnStatement with transient identifier"); nameID.setValue(principal.getSAMLAuthnIdentifier()); nameID.setFormat(NameIDFormatConstants.trans); setNameID = true; break; } /* Figure out what value we should try and get from the principals attributes */ String attribName = this.identifierAttributeMapping.get(identifier); if (attribName != null) { IdentityAttribute identityAttribute = principal.getAttributes().get(attribName); if (identityAttribute != null) { List<Object> attribValues = identityAttribute.getValues(); if (attribValues != null && attribValues.size() > 0) { this.logger.info("Sending AuthnStatement with identifier of type " + identifier); /* Use the first value if there are multiples */ nameID.setValue((String) attribValues.get(0)); nameID.setFormat(identifier); setNameID = true; break; } } } } } } /* We couldn't figure out an identifier to response with, so send transient identifier */ if (!setNameID) { nameID.setValue(principal.getSAMLAuthnIdentifier()); nameID.setFormat(NameIDFormatConstants.trans); } subject.setNameID(nameID); /* subject MUST contain a SubjectConfirmation */ SubjectConfirmation confirmation = new SubjectConfirmation(); confirmation.setMethod(ConfirmationMethodConstants.bearer); SubjectConfirmationDataType confirmationData = new SubjectConfirmationDataType(); confirmationData.setRecipient(data.getResponseEndpoint()); confirmationData.setInResponseTo(data.getAuthnRequest().getID()); confirmationData.setNotOnOrAfter(CalendarUtils.generateXMLCalendar(principal.getSessionNotOnOrAfter())); confirmation.setSubjectConfirmationData(confirmationData); subject.getSubjectConfirmationNonID().add(confirmation); /* Set conditions on the response. Restrict audience to the SPEP recieving this Response. */ conditions.setNotOnOrAfter(CalendarUtils.generateXMLCalendar(this.allowedTimeSkew)); List<ConditionAbstractType> audienceRestrictions = conditions .getConditionsAndOneTimeUsesAndAudienceRestrictions(); AudienceRestriction restrict = new AudienceRestriction(); restrict.getAudiences().add(data.getIssuerID()); audienceRestrictions.add(restrict); /* set assertion values */ assertion.setConditions(conditions); assertion.setVersion(VersionConstants.saml20); assertion.setID(this.identifierGenerator.generateSAMLID()); assertion.setIssueInstant(CalendarUtils.generateXMLCalendar(0)); assertion.setIssuer(issuer); assertion.setSignature(signature); assertion.setSubject(subject); assertion.getAuthnStatementsAndAuthzDecisionStatementsAndAttributeStatements().add(authnStatement); /* Generate successful status, only top level code supplied */ statusCode.setValue(StatusCodeConstants.success); status.setStatusCode(statusCode); /* Generate our response */ response.setID(this.identifierGenerator.generateSAMLID()); response.setInResponseTo(data.getAuthnRequest().getID()); response.setVersion(VersionConstants.saml20); response.setIssueInstant(CalendarUtils.generateXMLCalendar(0)); response.setDestination(data.getResponseEndpoint()); response.setConsent(ConsentIdentifierConstants.prior); response.setIssuer(issuer); response.setSignature(new Signature()); response.setStatus(status); response.getEncryptedAssertionsAndAssertions().add(assertion); return response; }
From source file:de.fischer.thotti.core.runner.NDRunner.java
private NDTestResult forkNDTestRunnerInSlaveMode(NonDistributedTestType test, TestInstanceType instance) throws IOException { NDTestResult result = new NDTestResult(); GregorianCalendar startTime; long startTimeMS; long endTimeMS; int exitCode = -9999; result.setTestId(test.getId());// ww w .j av a2 s. co m result.setJVMArgs(instance.getJvmArguments()); result.setJVMArgsID(instance.getJvmArgsID()); result.setParamGrpID(instance.getName()); CommandLine cmdLine = new CommandLine("java"); if (false == StringUtils.isEmpty(instance.getJvmArguments())) { cmdLine.addArguments(instance.getJvmArguments()); } cmdLine.addArgument("-cp").addArgument(System.getProperty("java.class.path")) .addArgument(NDRunner.class.getName()).addArgument("--slave").addArgument("--executionid") .addArgument(instance.getExecutionID().toString()); System.gc(); DefaultExecutor executor = new DefaultExecutor(); startTime = (GregorianCalendar) Calendar.getInstance(); startTimeMS = startTime.getTimeInMillis(); try { exitCode = executor.execute(cmdLine); result.setSuccessfulTermination(true); result.setExitCode(exitCode); } catch (ExecuteException e) { result.setSuccessfulTermination(false); result.setExitCode(e.getExitValue()); } finally { endTimeMS = System.currentTimeMillis(); } result.setExecutionTime(endTimeMS - startTimeMS); result.setStartTime(startTime); System.out.println(result); return result; }
From source file:org.oscarehr.web.Cds4ReportUIBean.java
private List<CdsHospitalisationDays> getHopitalisationDays2YearsBeforeAdmission(CdsClientForm form) { Admission admission = admissionMap.get(form.getAdmissionId()); GregorianCalendar startBound = (GregorianCalendar) admission.getAdmissionCalendar().clone(); startBound.add(GregorianCalendar.YEAR, -2); // 2 years prior to admission // materialise results startBound.getTimeInMillis(); return (getHopitalisationDaysDuringPeriod(form, startBound, admission.getAdmissionCalendar())); }
From source file:org.oscarehr.common.model.Demographic.java
public GregorianCalendar getBirthDay() { GregorianCalendar cal = null; if (dateOfBirth != null && monthOfBirth != null && yearOfBirth != null) { cal = new GregorianCalendar(); cal.setTimeInMillis(0);/*from ww w . ja v a 2 s . c o m*/ cal.set(Integer.parseInt(yearOfBirth), Integer.parseInt(monthOfBirth) - 1, Integer.parseInt(dateOfBirth)); // force materialisation of data cal.getTimeInMillis(); } return (cal); }
From source file:org.oscarehr.web.Cds4ReportUIBean.java
private int getCdsHospitalisationDaysCount2YearsBeforeProgramAdmission(Collection<CdsClientForm> forms) { int numberOfDaysInHospital = 0; if (forms != null) { for (CdsClientForm form : forms) { List<CdsHospitalisationDays> hospitalisationDays = getHopitalisationDays2YearsBeforeAdmission(form); Admission admission = admissionMap.get(form.getAdmissionId()); GregorianCalendar startBound = (GregorianCalendar) admission.getAdmissionCalendar().clone(); startBound.add(GregorianCalendar.YEAR, -2); // 2 years prior to admission // materialise results startBound.getTimeInMillis(); numberOfDaysInHospital = numberOfDaysInHospital + getTotalDayCount(hospitalisationDays, startBound, admission.getAdmissionCalendar()); }//from w w w.j a v a 2 s. co m } return (numberOfDaysInHospital); }
From source file:org.opencms.workplace.CmsLogin.java
/** * Sets the cookie in the response.<p> * /* www. j a v a 2s . c om*/ * @param cookie the cookie to set * @param delete flag to determine if the cookir should be deleted */ protected void setCookie(Cookie cookie, boolean delete) { if (getRequest().getAttribute(PARAM_PREDEF_OUFQN) != null) { // prevent the use of cookies if using a direct ou login url return; } int maxAge = 0; if (!delete) { // set the expiration date of the cookie to six months from today GregorianCalendar cal = new GregorianCalendar(); cal.add(Calendar.MONTH, 6); maxAge = (int) ((cal.getTimeInMillis() - System.currentTimeMillis()) / 1000); } cookie.setMaxAge(maxAge); // set the path cookie.setPath(link("/system/login")); // set the cookie getResponse().addCookie(cookie); }
From source file:org.openhab.binding.powermax.internal.message.PowerMaxCommDriver.java
/** * Send a message to set the alarm time and date using the system time and date * * @return true if the message was sent or false if not *//* ww w . j a va 2 s. c o m*/ public boolean sendSetTime() { logger.debug("sendSetTime()"); boolean done = false; GregorianCalendar cal = new GregorianCalendar(); if (cal.get(Calendar.YEAR) >= 2000) { logger.debug(String.format("sendSetTime(): sync time %02d/%02d/%04d %02d:%02d:%02d", cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR), cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND))); byte[] dynPart = new byte[6]; dynPart[0] = (byte) cal.get(Calendar.SECOND); dynPart[1] = (byte) cal.get(Calendar.MINUTE); dynPart[2] = (byte) cal.get(Calendar.HOUR_OF_DAY); dynPart[3] = (byte) cal.get(Calendar.DAY_OF_MONTH); dynPart[4] = (byte) (cal.get(Calendar.MONTH) + 1); dynPart[5] = (byte) (cal.get(Calendar.YEAR) - 2000); done = sendMessage(new PowerMaxBaseMessage(PowerMaxSendType.SETTIME, dynPart), false, 0); cal.set(Calendar.MILLISECOND, 0); syncTimeCheck = cal.getTimeInMillis(); } else { logger.warn( "PowerMax alarm binding: time not synchronized; please correct the date/time of your openHAB server"); syncTimeCheck = null; } return done; }