Example usage for org.joda.time DateTime getMillisOfSecond

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

Introduction

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

Prototype

public int getMillisOfSecond() 

Source Link

Document

Get the millis of second field value.

Usage

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.extensions.sql.zetasql.DateTimeUtils.java

License:Apache License

public static String formatTimestampWithTimeZone(DateTime dt) {
    String resultWithoutZone;//from  w ww. j a v  a  2  s  . c om
    if (dt.getMillisOfSecond() == 0) {
        resultWithoutZone = dt.toString(DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
    } else {
        resultWithoutZone = dt.toString(DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS"));
    }

    // ZetaSQL expects a 2-digit timezone offset (-05) if the minute part is zero, and it expects
    // a 4-digit timezone with a colon (-07:52) if the minute part is non-zero. None of the
    // variations on z,Z,ZZ,.. do this for us so we have to do it manually here.
    String zone = dt.toString(DateTimeFormat.forPattern("ZZ"));
    List<String> zoneParts = Lists.newArrayList(Splitter.on(':').limit(2).split(zone));
    if (zoneParts.size() == 2 && zoneParts.get(1).equals("00")) {
        zone = zoneParts.get(0);
    }

    return resultWithoutZone + zone;
}

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());
    }/*from   www.j  a  v  a 2  s .  co m*/

    return cal;
}

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/*from  www  . j a  v a 2s .  c  om*/
            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 {/*w  w  w .ja va  2  s  . c om*/
            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.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 2s . 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.classbooker.service.ReservationMgrServiceImpl.java

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

From source file:org.efaps.admin.datamodel.attributetype.DateTimeType.java

License:Apache License

/**
 * {@inheritDoc}//w  w w  .j a  v a2s  .c  o m
 * @throws EFapsException
 */
@Override
public Object readValue(final Attribute _attribute, final List<Object> _objectList) throws EFapsException {
    // reads the Value from "Admin_Common_DataBaseTimeZone"
    final String timezoneID = EFapsSystemConfiguration.get().getAttributeValue(KernelSettings.DBTIMEZONE);
    final ISOChronology chron;
    if (timezoneID != null) {
        final DateTimeZone timezone = DateTimeZone.forID(timezoneID);
        chron = ISOChronology.getInstance(timezone);
    } else {
        chron = ISOChronology.getInstanceUTC();
    }

    final List<DateTime> ret = new ArrayList<DateTime>();
    for (final Object object : _objectList) {
        if (object instanceof Timestamp || object instanceof Date) {
            // to avoid the automatic "correction" of the timezone first a local date must be made
            // and than a new Date with the correct timezone must be created
            final DateTime dateTime = new DateTime(object);
            final DateTime unlocalized = new DateTime(dateTime.getYear(), dateTime.getMonthOfYear(),
                    dateTime.getDayOfMonth(), dateTime.getHourOfDay(), dateTime.getMinuteOfHour(),
                    dateTime.getSecondOfMinute(), dateTime.getMillisOfSecond(), chron);
            ret.add(unlocalized);
        } else if (object != null) {
            ret.add(new DateTime());
        } else {
            ret.add(null);
        }
    }
    return _objectList.size() > 0 ? ret.size() > 1 ? ret : ret.get(0) : null;
}

From source file:org.efaps.admin.datamodel.attributetype.DateTimeType.java

License:Apache License

/**
 * The value that can be set is a Date, a DateTime or a String
 * yyyy-MM-dd'T'HH:mm:ss.SSSZZ. It will be normalized to ISO Calender with
 * TimeZone from SystemAttribute Admin_Common_DataBaseTimeZone. In case that
 * the SystemAttribute is missing UTC will be used.
 *
 * @param _value value to evaluate/*from w  w w  .  j a va2  s. c  o m*/
 * @return evaluated value
 * @throws EFapsException on error
 */
protected Timestamp eval(final Object[] _value) throws EFapsException {
    final Timestamp ret;
    if (_value == null || _value.length == 0 || _value[0] == null) {
        ret = null;
    } else {
        final DateTime dateTime = DateTimeUtil.translateFromUI(_value[0]);
        // until now we have a time that depends on the timezone of the application server
        // to convert it in a timestamp for the efaps database the timezone information (mainly the offset)
        // must be removed. This is done by creating a local date with the same, date and time.
        // this guarantees that the datetime inserted into the database depends on the setting
        // in the configuration and not on the timezone for the application server.
        final DateTime localized = new DateTime(dateTime.getYear(), dateTime.getMonthOfYear(),
                dateTime.getDayOfMonth(), dateTime.getHourOfDay(), dateTime.getMinuteOfHour(),
                dateTime.getSecondOfMinute(), dateTime.getMillisOfSecond());
        ret = localized != null ? new Timestamp(localized.getMillis()) : null;
    }
    return ret;
}