Example usage for org.joda.time DateTime getSecondOfMinute

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

Introduction

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

Prototype

public int getSecondOfMinute() 

Source Link

Document

Get the second of minute field value.

Usage

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 ww  w  .j a  va  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.jav  a2s. 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.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 va 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 and day of month, hour, minute and second, false
 * otherwise./* ww  w. j  ava  2s  .  co  m*/
 * 
 * @param actual the actual datetime. expected not be null
 * @param other the other datetime. expected not be null
 * @return true if both datetime are in the same year, month and day of month, hour, minute and second, false
 *         otherwise.
 */
private static boolean areEqualIgnoringMillis(DateTime actual, DateTime other) {
    return areEqualIgnoringSeconds(actual, other) && actual.getSecondOfMinute() == other.getSecondOfMinute();
}

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

License:Apache License

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

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

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

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

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

License:Apache License

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

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

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

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

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

        if (anyDateMatcher.matches()) {

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

        } else if (lastWeekMatcher.matches()) {

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

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

        } else if (todayMatcher.matches()) {

            DateTime todayDate = new DateTime();

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

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

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

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

    return milliSeconds;
}

From source file:org.dataconservancy.ui.services.CollectionActivityServiceImpl.java

License:Apache License

/**
 * returns creation activity for a collection
 * @param collection//from   ww w . j  av  a  2 s.  c om
 * @return activity
 */
private Activity retrieveCreationActivityForCollection(Collection collection) {
    DateTime depositDate = collection.getDepositDate();

    Activity activity = new Activity();
    Person actor = userService.get(collection.getDepositorId());
    activity.setActor(actor);
    activity.setDateTimeOfOccurrence(new DateTime(depositDate.getYear(), depositDate.getMonthOfYear(),
            depositDate.getDayOfMonth(), depositDate.getHourOfDay(), depositDate.getMinuteOfHour(),
            depositDate.getSecondOfMinute()));
    activity.setType(Activity.Type.COLLECTION_DEPOSIT);
    activity.setCount(1);

    return activity;
}

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

License:Apache License

/**
 * {@inheritDoc}//w w  w. j av  a2s .c om
 * @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;
}