text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="br.edu.ufcspa.tc6m.controle.PreTesteActivity"
    tools:showIn="@layout/activity_pre_teste">

    <ScrollView
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="0dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <!--Texto inicial-->
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_margin="5dp"
            android:gravity="center"
            android:text="@string/selecione_os_sinais" />

        <!--Layout FC-->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:background="@drawable/round_edge"
            android:orientation="vertical"
            android:padding="5dp">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="left">

                <ImageView
                    android:layout_width="25dp"
                    android:layout_height="25dp"
                    android:layout_gravity="center"
                    android:padding="5dp"
                    android:src="@drawable/icon_fc_verde" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:text="@string/frequ_ncia_card_aca"
                    android:textColor="@color/corPrimaria"
                    android:textSize="18sp" />

            </LinearLayout>

            <TextView
                android:id="@+id/text_fc_obrigatorio"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="5dp"

                android:text="@string/alerta_fc"
                android:textColor="@color/colorAccent"
                android:textSize="12sp"
                android:visibility="gone" />

            <info.hoang8f.android.segmented.SegmentedGroup xmlns:segmentedgroup="http://schemas.android.com/apk/res-auto"
                android:layout_width="match_parent"
                android:layout_height="28dp"
                android:layout_marginBottom="10dp"
                android:orientation="horizontal"
                segmentedgroup:sc_border_width="2dp"
                segmentedgroup:sc_corner_radius="10dp"
                segmentedgroup:sc_tint_color="@color/corPrimaria">

                <CheckBox
                    android:id="@+id/bt_basal_fc"
                    style="@style/RadioButton"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:checked="true"
                    android:clickable="false"
                    android:text="@string/basal" />

                <CheckBox
                    android:id="@+id/bt_durante_fc"
                    style="@style/RadioButton"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="@string/durante" />

                <CheckBox
                    android:id="@+id/bt_final_fc"
                    style="@style/RadioButton"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:checked="true"
                    android:text="@string/depois" />

                <CheckBox
                    android:id="@+id/bt_repouso_fc"
                    style="@style/RadioButton"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:text="@string/recup" />

            </info.hoang8f.android.segmented.SegmentedGroup>

        </LinearLayout>

        <!--Layout Dispneia-->
        <LinearLayout
            android:id="@+id/layout_dispneia"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_marginTop="5dp"
            android:background="@drawable/round_edge"
            android:orientation="vertical"
            android:padding="5dp">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <ImageView
                    android:layout_width="25dp"
                    android:layout_height="25dp"
                    android:layout_gravity="center"
                    android:padding="3dp"
                    android:src="@drawable/icon_pulmao_verde" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:text="@string/dispneia"
                    android:textColor="@color/corPrimaria"
                    android:textSize="18sp" />

            </LinearLayout>

            <info.hoang8f.android.segmented.SegmentedGroup xmlns:segmentedgroup="http://schemas.android.com/apk/res-auto"
                android:layout_width="match_parent"
                android:layout_height="28dp"

                android:layout_marginBottom="10dp"
                android:orientation="horizontal"
                segmentedgroup:sc_border_width="2dp"
                segmentedgroup:sc_corner_radius="10dp"
                segmentedgroup:sc_tint_color="@color/corPrimaria">

                <CheckBox
                    android:id="@+id/bt_basal_dispneia"
                    style="@style/RadioButton"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="@string/basal" />

                <CheckBox
                    android:id="@+id/bt_durante_dispneia"
                    style="@style/RadioButton"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="@string/durante" />

                <CheckBox

                    android:id="@+id/bt_final_dispneia"
                    style="@style/RadioButton"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="@string/depois" />

                <CheckBox
                    android:id="@+id/bt_repouso_dispneia"
                    style="@style/RadioButton"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:text="@string/recup"
                    android:textSize="12sp" />

            </info.hoang8f.android.segmented.SegmentedGroup>

        </LinearLayout>

        <!--Layout Fad MMII-->
        <LinearLayout
            android:id="@+id/layout_fadiga"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_marginTop="5dp"
            android:background="@drawable/round_edge"
            android:orientation="vertical"
            android:padding="5dp">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <ImageView
                    android:layout_width="25dp"
                    android:layout_height="25dp"
                    android:layout_gravity="center"
                    android:padding="3dp"
                    android:src="@drawable/icon_mmii_verde" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:text="@string/fadiga_mmii"
                    android:textColor="@color/corPrimaria"
                    android:textSize="18sp" />

            </LinearLayout>

            <info.hoang8f.android.segmented.SegmentedGroup xmlns:segmentedgroup="http://schemas.android.com/apk/res-auto"
                android:layout_width="match_parent"
                android:layout_height="28dp"
                android:layout_marginBottom="10dp"
                android:orientation="horizontal"
                segmentedgroup:sc_border_width="2dp"
                segmentedgroup:sc_corner_radius="10dp"
                segmentedgroup:sc_tint_color="@color/corPrimaria">

                <CheckBox
                    android:id="@+id/bt_basal_fadiga"
                    style="@style/RadioButton"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"

                    android:text="@string/basal" />

                <CheckBox
                    android:id="@+id/bt_durante_fadiga"
                    style="@style/RadioButton"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="@string/durante" />

                <CheckBox
                    android:id="@+id/bt_final_fadiga"
                    style="@style/RadioButton"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="@string/depois" />

                <CheckBox
                    android:id="@+id/bt_repouso_fadiga"
                    style="@style/RadioButton"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:text="@string/recup"
                    android:textSize="12sp" />

            </info.hoang8f.android.segmented.SegmentedGroup>

        </LinearLayout>

        <!--Layout SPo2-->
        <LinearLayout
            android:id="@+id/layout_spo2"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_marginTop="5dp"
            android:background="@drawable/round_edge"
            android:orientation="vertical"
            android:padding="5dp">

            <LinearLayout

                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <ImageView
                    android:layout_width="25dp"
                    android:layout_height="25dp"
                    android:layout_gravity="center"
                    android:padding="3dp"
                    android:src="@drawable/icon_spo2_verde" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    android:layout_marginStart="5dp"
                    android:layout_marginBottom="5dp"
                    android:text="@string/saturacao_de_pulso_de_o"
                    android:textColor="@color/corPrimaria"
                    android:textSize="18sp"
                    android:layout_marginLeft="5dp" />
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    android:text="@string/_2"
                    android:textColor="@color/corPrimaria"
                    android:textSize="12sp" />

            </LinearLayout>

            <info.hoang8f.android.segmented.SegmentedGroup xmlns:segmentedgroup="http://schemas.android.com/apk/res-auto"
                android:layout_width="match_parent"
                android:layout_height="28dp"
                android:layout_marginBottom="10dp"
                android:orientation="horizontal"
                segmentedgroup:sc_border_width="2dp"
                segmentedgroup:sc_corner_radius="10dp"
                segmentedgroup:sc_tint_color="@color/corPrimaria">

                <CheckBox
                    android:id="@+id/bt_basal_spo2"
                    style="@style/RadioButton"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="@string/basal" />

                <CheckBox
                    android:id="@+id/bt_durante_spo2"
                    style="@style/RadioButton"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="@string/durante" />

                <CheckBox
                    android:id="@+id/bt_final_spo2"
                    style="@style/RadioButton"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="@string/depois" />

                <CheckBox
                    android:id="@+id/bt_repouso_spo2"
                    style="@style/RadioButton"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:text="@string/recup"
                    android:textSize="12sp" />

            </info.hoang8f.android.segmented.SegmentedGroup>

        </LinearLayout>

        <!--Layout PA-->
        <LinearLayout
            android:id="@+id/layout_pa"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_marginTop="5dp"
            android:background="@drawable/round_edge"
            android:orientation="vertical"
            android:padding="5dp">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <ImageView
                    android:layout_width="25dp"
                    android:layout_height="25dp"
                    android:layout_gravity="center"
                    android:padding="3dp"
                    android:src="@drawable/icon_pa_verde" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:text="@string/pressao_arterial"
                    android:textColor="@color/corPrimaria"
                    android:textSize="18sp" />

            </LinearLayout>

            <info.hoang8f.android.segmented.SegmentedGroup xmlns:segmentedgroup="http://schemas.android.com/apk/res-auto"
                android:layout_width="match_parent"
                android:layout_height="28dp"
                android:layout_marginBottom="10dp"
                android:orientation="horizontal"
                segmentedgroup:sc_border_width="2dp"
                segmentedgroup:sc_corner_radius="10dp"
                segmentedgroup:sc_tint_color="@color/corPrimaria">

                <CheckBox
                    android:id="@+id/bt_basal_pa"
                    style="@style/RadioButton"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="@string/basal" />

                <CheckBox
                    android:id="@+id/bt_final_pa"
                    style="@style/RadioButton"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="@string/depois" />

                <CheckBox
                    android:id="@+id/bt_repouso_pa"
                    style="@style/RadioButton"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:text="@string/recupera_o" />

            </info.hoang8f.android.segmented.SegmentedGroup>

        </LinearLayout>

        <!--Layout frr-->
        <LinearLayout
            android:visibility="gone"
            android:id="@+id/layout_fr"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_marginTop="5dp"
            android:background="@drawable/round_edge"
            android:orientation="vertical"
            android:padding="5dp">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <ImageView
                    android:layout_width="25dp"
                    android:layout_height="25dp"
                    android:layout_gravity="center"
                    android:padding="4dp"
                    android:src="@drawable/icon_pulmao_verde" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:text="@string/frequ_ncia_respirat_ria"
                    android:textColor="@color/corPrimaria"
                    android:textSize="18sp" />

            </LinearLayout>

            <info.hoang8f.android.segmented.SegmentedGroup xmlns:segmentedgroup="http://schemas.android.com/apk/res-auto"
                android:layout_width="match_parent"
                android:layout_height="28dp"
                android:layout_marginBottom="10dp"
                android:orientation="horizontal"
                segmentedgroup:sc_border_width="2dp"
                segmentedgroup:sc_corner_radius="10dp"
                segmentedgroup:sc_tint_color="@color/corPrimaria">

                <CheckBox
                    android:id="@+id/bt_basal_fr"
                    style="@style/RadioButton"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="@string/basal" />

                <CheckBox
                    android:id="@+id/bt_final_fr"
                    style="@style/RadioButton"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="@string/depois" />

                <CheckBox
                    android:id="@+id/bt_repouso_fr"
                    style="@style/RadioButton"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:text="@string/recupera_o" />

            </info.hoang8f.android.segmented.SegmentedGroup>

        </LinearLayout>

        <!--Layout GC-->
        <LinearLayout
            android:id="@+id/layout_gc"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_marginTop="5dp"
            android:background="@drawable/round_edge"
            android:orientation="vertical"
            android:padding="5dp">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <ImageView
                    android:layout_width="25dp"
                    android:layout_height="25dp"
                    android:layout_gravity="center"
                    android:padding="3dp"
                    android:src="@drawable/icon_sangue_verde" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:text="@string/glicemia_capilar"
                    android:textColor="@color/corPrimaria"
                    android:textSize="18sp" />

            </LinearLayout>

            <info.hoang8f.android.segmented.SegmentedGroup xmlns:segmentedgroup="http://schemas.android.com/apk/res-auto"
                android:layout_width="match_parent"
                android:layout_height="28dp"
                android:layout_marginBottom="10dp"
                android:orientation="horizontal"
                segmentedgroup:sc_border_width="2dp"
                segmentedgroup:sc_corner_radius="10dp"
                segmentedgroup:sc_tint_color="@color/corPrimaria">

                <CheckBox
                    android:id="@+id/bt_basal_gc"
                    style="@style/RadioButton"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="@string/basal" />

                <CheckBox
                    android:id="@+id/bt_final_gc"
                    style="@style/RadioButton"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="@string/depois" />

                <CheckBox
                    android:id="@+id/bt_repouso_gc"
                    style="@style/RadioButton"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:text="@string/recupera_o" />

            </info.hoang8f.android.segmented.SegmentedGroup>

        </LinearLayout>

        <!--Layout GC-->
        <LinearLayout
            android:id="@+id/layout_o2supl"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_marginTop="5dp"
            android:background="@drawable/round_edge"
            android:orientation="vertical"
            android:padding="5dp">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <ImageView
                    android:layout_width="25dp"
                    android:layout_height="25dp"
                    android:layout_gravity="center"
                    android:padding="3dp"
                    android:src="@drawable/icon_o2"
                    android:tint="@color/corPrimaria" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="5dp"
                    android:layout_marginStart="5dp"
                    android:layout_marginTop="5dp"
                    android:text="@string/o"
                    android:textColor="@color/corPrimaria"
                    android:textSize="18sp" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    android:text="@string/_2"
                    android:textColor="@color/corPrimaria"
                    android:textSize="12sp" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:text="@string/suplementar"
                    android:textColor="@color/corPrimaria"
                    android:textSize="18sp" />

            </LinearLayout>

            <info.hoang8f.android.segmented.SegmentedGroup xmlns:segmentedgroup="http://schemas.android.com/apk/res-auto"
                android:layout_width="match_parent"
                android:layout_height="28dp"
                android:layout_marginBottom="10dp"
                android:orientation="horizontal"
                segmentedgroup:sc_border_width="2dp"
                segmentedgroup:sc_corner_radius="10dp"
                segmentedgroup:sc_tint_color="@color/corPrimaria">

                <CheckBox
                    android:id="@+id/bt_basal_o2supl"
                    style="@style/RadioButton"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="@string/basal" />

                <CheckBox
                    android:id="@+id/bt_final_o2supl"
                    style="@style/RadioButton"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="@string/depois" />

            </info.hoang8f.android.segmented.SegmentedGroup>

        </LinearLayout>

    </LinearLayout>
    </ScrollView>

    <Button
        android:id="@+id/btOk"
        android:layout_width="180dp"
        android:layout_height="38dp"
        android:layout_gravity="center"
        android:layout_margin="10dp"
        android:background="@color/colorAccent"
        android:text="@string/continuar"
        android:textColor="#d7ffffff" />

</LinearLayout>


text:
package org.jaggeryjs.modules.sso.common.util;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.xerces.impl.Constants;
import org.apache.xerces.util.SecurityManager;
import org.apache.xml.security.exceptions.XMLSecurityException;
import org.apache.xml.security.signature.Reference;
import org.apache.xml.security.signature.XMLSignature;
import org.apache.xml.security.utils.IdResolver;
import org.jaggeryjs.modules.sso.common.constants.SSOConstants;
import org.joda.time.DateTime;
import org.opensaml.Configuration;
import org.opensaml.DefaultBootstrap;
import org.opensaml.common.SignableSAMLObject;
import org.opensaml.common.impl.SecureRandomIdentifierGenerator;
import org.opensaml.common.xml.SAMLConstants;
import org.opensaml.saml2.core.Assertion;
import org.opensaml.saml2.core.Audience;
import org.opensaml.saml2.core.AudienceRestriction;
import org.opensaml.saml2.core.Conditions;
import org.opensaml.saml2.core.NameID;
import org.opensaml.saml2.core.NameIDPolicy;
import org.opensaml.saml2.core.Response;
import org.opensaml.saml2.core.impl.NameIDBuilder;
import org.opensaml.saml2.core.impl.NameIDPolicyBuilder;
import org.opensaml.saml2.core.impl.StatusResponseTypeImpl;
import org.opensaml.security.SAMLSignatureProfileValidator;
import org.opensaml.xml.ConfigurationException;
import org.opensaml.xml.XMLObject;
import org.opensaml.xml.XMLObjectBuilder;
import org.opensaml.xml.io.Marshaller;
import org.opensaml.xml.io.MarshallerFactory;
import org.opensaml.xml.io.Unmarshaller;
import org.opensaml.xml.io.UnmarshallerFactory;
import org.opensaml.xml.signature.Signature;
import org.opensaml.xml.signature.SignatureValidator;
import org.opensaml.xml.signature.impl.SignatureImpl;
import org.opensaml.xml.util.Base64;
import org.opensaml.xml.util.DatatypeHelper;
import org.opensaml.xml.validation.ValidationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.core.util.KeyStoreManager;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import org.xml.sax.SAXException;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

public class Util {

    private static final int ENTITY_EXPANSION_LIMIT = 0;
    private static boolean bootStrapped = false;
    private static final String ISSUER = "issuer";
    private static final String IDENTITY_PROVIDER_ERROR = "urn:oasis:names:tc:SAML:2.0:status:Responder";
    private static final String NO_PASSIVE = "urn:oasis:names:tc:SAML:2.0:status:NoPassive";
    private static final String TIME_STAMP_SKEW = "timeStampSkew";
    private static final int DEAFAULT_TIME_STAMP_SKEW_IN_SECONDS = 300;

    private static Random random = new Random();

    private static final char[] charMapping = {
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
            'p'};

    private static Log log = LogFactory.getLog(Util.class);

    /**
     * This method is used to initialize the OpenSAML2 library. It calls the bootstrap method, if it
     * is not initialized yet.
     */
    public static void doBootstrap() {
        if (!bootStrapped) {
            try {
                DefaultBootstrap.bootstrap();
                bootStrapped = true;
            } catch (ConfigurationException e) {
                System.err.println("Error in bootstrapping the OpenSAML2 library");
                e.printStackTrace();
            }
        }
    }

    public static XMLObject buildXMLObject(QName objectQName)
            throws Exception {

        XMLObjectBuilder builder = org.opensaml.xml.Configuration.getBuilderFactory().getBuilder(objectQName);
        if (builder == null) {
            throw new Exception("Unable to retrieve builder for object QName "
                    + objectQName);
        }
        return builder.buildObject(objectQName.getNamespaceURI(), objectQName.getLocalPart(),
                objectQName.getPrefix());
    }

    /**
     * Generates a unique Id for Authentication Requests
     *
     * @return generated unique ID
     */
    public static String createID() {

        try {
            SecureRandomIdentifierGenerator generator = new SecureRandomIdentifierGenerator();
            return generator.generateIdentifier();
        } catch (NoSuchAlgorithmException e) {
            log.warn("Error while building Secure Random ID");
        }
        return null;
    }

    /**
     * Constructing the XMLObject Object from a String
     *
     * @param authReqStr
     * @return Corresponding XMLObject which is a SAML2 object
     * @throws Exception
     */
    public static XMLObject unmarshall(String authReqStr) throws Exception {
        XMLObject response;
        try {
            doBootstrap();
            DocumentBuilderFactory documentBuilderFactory = getSecuredDocumentBuilder();
            documentBuilderFactory.setIgnoringComments(true);
            Document document = getDocument(documentBuilderFactory, authReqStr);
            if (isSignedWithComments(document)) {
                documentBuilderFactory.setIgnoringComments(false);
                document = getDocument(documentBuilderFactory, authReqStr);
            }
            Element element = document.getDocumentElement();
            UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
            Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);
            response = unmarshaller.unmarshall(element);
            NodeList list = response.getDOM().getElementsByTagNameNS(SAMLConstants.SAML20P_NS, "Response");
            if (list.getLength() > 0) {
                log.error("Invalid schema for the SAML2 reponse. Multiple response objects found");
                throw new Exception("Error occured while processing saml2 response. Multiple response objects found");
            }
            NodeList assertionList = response.getDOM().getElementsByTagNameNS(SAMLConstants.SAML20_NS, "Assertion");
            if (response instanceof Assertion) {
                if (assertionList.getLength() > 0) {
                    log.error("Invalid schema for the SAML2 assertion. Multiple assertions detected");
                    throw new Exception("Error occurred while processing saml2 response. Multiple assertions detected");
                }
            } else {
                if (assertionList.getLength() > 1) {
                    log.error("Invalid schema for the SAML2 response. Multiple assertions detected");
                    throw new Exception("Error occurred while processing saml2 response. Multiple assertions detected");
                }
            }

            return response;
        } catch (Exception e) {
            throw new Exception("Error in constructing AuthRequest from " +
                    "the encoded String ", e);
        }
    }

    /**
     * Return whether SAML Assertion has the canonicalization method
     * set to 'http://www.w3.org/2001/10/xml-exc-c14n#WithComments'.
     *
     * @param document
     * @return true if canonicalization method equals to 'http://www.w3.org/2001/10/xml-exc-c14n#WithComments'
     */
    private static boolean isSignedWithComments(Document document) {

        XPath xPath = XPathFactory.newInstance().newXPath();
        try {
            String assertionId = (String) xPath.compile("//*[local-name()='Assertion']/@ID")
                    .evaluate(document, XPathConstants.STRING);

            if (StringUtils.isBlank(assertionId)) {
                return false;
            }

            NodeList nodeList = ((NodeList) xPath.compile(
                    "//*[local-name()='Assertion']" +
                            "/*[local-name()='Signature']" +
                            "/*[local-name()='SignedInfo']" +
                            "/*[local-name()='Reference'][@URI='#" + assertionId + "']" +
                            "/*[local-name()='Transforms']" +
                            "/*[local-name()='Transform']" +
                            "[@Algorithm='http://www.w3.org/2001/10/xml-exc-c14n#WithComments']")
                    .evaluate(document, XPathConstants.NODESET));
            return nodeList != null && nodeList.getLength() > 0;
        } catch (XPathExpressionException e) {
            String message = "Failed to find the canonicalization algorithm of the assertion. Defaulting to: " +
                    "http://www.w3.org/2001/10/xml-exc-c14n#";
            log.warn(message);
            if (log.isDebugEnabled()) {
                log.debug(message, e);
            }
            return false;
        }
    }

    private static Document getDocument(DocumentBuilderFactory documentBuilderFactory, String samlString)
            throws IOException, SAXException, ParserConfigurationException {

        DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
        ByteArrayInputStream inputStream = new ByteArrayInputStream(samlString.getBytes());
        return docBuilder.parse(inputStream);
    }

    /**
     * Serializing a SAML2 object into a String
     *
     * @param xmlObject object that needs to serialized.
     * @return serialized object
     * @throws Exception
     */
    public static String marshall(XMLObject xmlObject) throws Exception {
        try {
            doBootstrap();
            System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                    "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");

            MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration.getMarshallerFactory();
            Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject);
            Element element = marshaller.marshall(xmlObject);

            ByteArrayOutputStream byteArrayOutputStrm = new ByteArrayOutputStream();
            DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
            DOMImplementationLS impl =
                    (DOMImplementationLS) registry.getDOMImplementation("LS");
            LSSerializer writer = impl.createLSSerializer();
            LSOutput output = impl.createLSOutput();
            output.setByteStream(byteArrayOutputStrm);
            writer.write(element, output);
            return byteArrayOutputStrm.toString();
        } catch (Exception e) {
            throw new Exception("Error Serializing the SAML Response", e);
        }
    }

    /**
     * Encoding the response
     *
     * @param xmlString
     *            String to be encoded
     * @return encoded String
     */
    public static String encode(String xmlString) {
        // Encoding the message
        String encodedRequestMessage =
                Base64.encodeBytes(xmlString.getBytes(),
                        Base64.DONT_BREAK_LINES);
        return encodedRequestMessage.trim();
    }

/*    *//**
     * Compressing and Encoding the response
     *
     * @param xmlString String to be encoded
     * @return compressed and encoded String
     *//*
    public static String encode(String xmlString) throws Exception {
        Deflater deflater = new Deflater(Deflater.DEFLATED, true);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(
                byteArrayOutputStream, deflater);

        deflaterOutputStream.write(xmlString.getBytes());
        deflaterOutputStream.close();

        // Encoding the compressed message
        String encodedRequestMessage = Base64.encodeBytes(byteArrayOutputStream
                .toByteArray(), Base64.DONT_BREAK_LINES);
        return encodedRequestMessage.trim();
    }*/

    /**
     * Decoding and deflating the encoded AuthReq
     *
     * @param encodedStr encoded AuthReq
     * @return decoded AuthReq
     */

    public static String decode(String encodedStr) throws Exception {
        return new String(Base64.decode(encodedStr));
    }
    /*@Deprecated
    public static String decode(String encodedStr) throws Exception {
        try {
            org.apache.commons.codec.binary.Base64 base64Decoder = new org.apache.commons.codec.binary.Base64();
            byte[] xmlBytes = encodedStr.getBytes("UTF-8");
            byte[] base64DecodedByteArray = base64Decoder.decode(xmlBytes);

            try {
                Inflater inflater = new Inflater(true);
                inflater.setInput(base64DecodedByteArray);
                byte[] xmlMessageBytes = new byte[5000];
                int resultLength = inflater.inflate(xmlMessageBytes);

                if (!inflater.finished()) {
                    throw new RuntimeException("didn't allocate enough space to hold "
                            + "decompressed data");
                }

                inflater.end();
                return new String(xmlMessageBytes, 0, resultLength, "UTF-8");

            } catch (DataFormatException e) {
                ByteArrayInputStream bais = new ByteArrayInputStream(
                        base64DecodedByteArray);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                InflaterInputStream iis = new InflaterInputStream(bais);
                byte[] buf = new byte[1024];
                int count = iis.read(buf);
                while (count != -1) {
                    baos.write(buf, 0, count);
                    count = iis.read(buf);
                }
                iis.close();

                return new String(baos.toByteArray());
            }
        } catch (IOException e) {
            throw new Exception("Error when decoding the SAML Request.", e);
        }

    }*/

    /**
     * This method validates the signature of the SAML Response.
     *
     * @param resp SAML Response
     * @return true, if signature is valid.
     */
    public static boolean validateSignature(StatusResponseTypeImpl resp, String keyStoreName, String keyStorePassword,
            String alias, int tenantId, String tenantDomain) {
        if (resp.getSignature() == null) {
            log.error("SAML Response signing is enabled, but signature element not found in SAML Response element.");
            return false;
        }
        return validateSignature(resp.getSignature(), keyStoreName, keyStorePassword, alias, tenantId, tenantDomain);
    }

    public static boolean validateAssertionSignature(Response resp, String keyStoreName, String keyStorePassword,
            String alias, int tenantId, String tenantDomain) {
        Assertion assertion;
        assertion = retrieveAssertion(resp);
        if (assertion == null) {
            log.error("SAML Assertion not found in the Response");
            return false;
        }
        if (assertion.getSignature() == null) {
            log.error("SAMLAssertion signing is enabled, but signature element "
                    + "not found in SAML Assertion element.");
            return false;
        } else {
            return validateSignature(assertion.getSignature(), keyStoreName, keyStorePassword, alias, tenantId,
                    tenantDomain);
        }

    }

    private static boolean validateSignature(Signature signature, String keyStoreName, String keyStorePassword,
            String alias, int tenantId, String tenantDomain) {
        boolean isSigValid = false;
        try {
            KeyStore keyStore = null;
            java.security.cert.X509Certificate cert = null;
            if (tenantId != MultitenantConstants.SUPER_TENANT_ID) {
                // get an instance of the corresponding Key Store Manager instance
                KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(tenantId);
                keyStore = keyStoreManager.getKeyStore(generateKSNameFromDomainName(tenantDomain));
                cert = (java.security.cert.X509Certificate) keyStore.getCertificate(tenantDomain);
            } else {
                keyStore = KeyStore.getInstance("JKS");
                keyStore.load(new FileInputStream(new File(keyStoreName)), keyStorePassword.toCharArray());
                cert = (java.security.cert.X509Certificate) keyStore.getCertificate(alias);
            }
            try {
                SAMLSignatureProfileValidator signatureProfileValidator = new SAMLSignatureProfileValidator();
                signatureProfileValidator.validate(signature);

                // Following code segment is taken from org.opensaml.security.SAMLSignatureProfileValidator
                // of OpenSAML 2.6.4. This is done to get the latest XSW related fixes.

                SignatureImpl sigImpl = (SignatureImpl) signature;
                XMLSignature apacheSig = sigImpl.getXMLSignature();
                SignableSAMLObject signableObject = (SignableSAMLObject) sigImpl.getParent();

                Reference ref = null;
                try {
                    ref = apacheSig.getSignedInfo().item(0);
                } catch (XMLSecurityException e) {
                    // This exception should never occur, because it's already checked
                    // from the previous call to signatureProfileValidator#validate
                    log.error("Apache XML Security exception obtaining Reference", e);
                    throw new ValidationException("Could not obtain Reference from Signature/SignedInfo", e);
                }

                String uri = ref.getURI();

                validateReferenceURI(uri, signableObject);
                validateObjectChildren(apacheSig);

                // End of OpenSAML 2.6.4 logic
            } catch (ValidationException e) {
                String logMsg = "Signature do not confirm to SAML signature profile. Possible XML Signature Wrapping "
                        + "Attack!";
                log.warn(logMsg);
                if (log.isDebugEnabled()) {
                    log.debug(logMsg, e);
                }
                return isSigValid;
            }

            X509CredentialImpl credentialImpl = new X509CredentialImpl(cert);
            SignatureValidator signatureValidator = new SignatureValidator(credentialImpl);
            signatureValidator.validate(signature);
            isSigValid = true;
            return isSigValid;
        } catch (Exception e) {
            log.error("Error while validating signature", e);
            return isSigValid;
        }
    }

    /**
     * Validates the 'Not Before' and 'Not On Or After' conditions of the SAML Assertion
     *
     * @param resp  SAML Response
     */
    public static boolean validateAssertionValidityPeriod(Response resp, Properties prop) {
        Assertion assertion;
        assertion = retrieveAssertion(resp);
        if (assertion == null) {
            log.error("SAML Assertion not found in the Response");
            return false;
        }
        DateTime validFrom = assertion.getConditions().getNotBefore();
        DateTime validTill = assertion.getConditions().getNotOnOrAfter();
        int timeStampSkewInSeconds = getTimeStampSkewInSeconds(prop);

        if (validFrom != null && validFrom.minusSeconds(timeStampSkewInSeconds).isAfterNow()) {
            log.error("Failed to meet SAML Assertion Condition 'Not Before'");
            return false;
        }

        if (validTill != null && validTill.plusSeconds(timeStampSkewInSeconds).isBeforeNow()) {
            log.error("Failed to meet SAML Assertion Condition 'Not On Or After'");
            return false;
        }

        if (validFrom != null && validTill != null && validFrom.isAfter(validTill)) {
            log.error("SAML Assertion Condition 'Not Before' must be less than the " + "value of 'Not On Or After'");
            return false;
        }
        return true;
    }

    /**
     * Validate the AudienceRestriction of SAML2 Response
     *
     * @param resp SAML response
     * @return validity
     */
    public static boolean validateAudienceRestriction(Response resp, Properties properties) {
        Assertion assertion;
        assertion = retrieveAssertion(resp);

        if (assertion == null) {
            log.error("SAML Assertion not found in the Response");
            return false;
        } else {
            Conditions conditions = assertion.getConditions();
            if (conditions != null) {
                List<AudienceRestriction> audienceRestrictions = conditions.getAudienceRestrictions();
                if (audienceRestrictions != null && !audienceRestrictions.isEmpty()) {
                    for (AudienceRestriction audienceRestriction : audienceRestrictions) {
                        if (CollectionUtils.isNotEmpty(audienceRestriction.getAudiences())) {
                            boolean audienceFound = false;
                            for (Audience audience : audienceRestriction.getAudiences()) {
                                if (properties.get(ISSUER).equals(audience.getAudienceURI())) {
                                    audienceFound = true;
                                    break;
                                }
                            }
                            if (!audienceFound) {
                                log.error("SAML Assertion Audience Restriction validation failed");
                                return false;
                            }
                        } else {
                            log.error("SAML Response's AudienceRestriction doesn't contain Audiences");
                            return false;
                        }
                    }
                } else {
                    log.error("SAML Response doesn't contain AudienceRestrictions");
                    return false;
                }
            } else {
                log.error("SAML Response doesn't contain Conditions");
                return false;
            }
        }
        return true;
    }

    private static int getTimeStampSkewInSeconds(Properties prop) {
        int timeStampSkewInSeconds = DEAFAULT_TIME_STAMP_SKEW_IN_SECONDS;
        if (prop != null && prop.containsKey(TIME_STAMP_SKEW)) {
            String timeStampSkew = prop.get(TIME_STAMP_SKEW).toString();
            if (timeStampSkew != null && timeStampSkew.length() > 0) {
                timeStampSkewInSeconds = Integer.parseInt(timeStampSkew);
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("TimestampSkew is set to " + timeStampSkewInSeconds + " s.");
        }

        return timeStampSkewInSeconds;
    }

    private static Assertion retrieveAssertion(Response resp) {
        Assertion assertion = null;
        List<Assertion> assertions = resp.getAssertions();
        if (CollectionUtils.isNotEmpty(assertions)) {
            if (assertions.size() != 1) {
                log.error("SAML Response contains multiple assertions");
                return assertion;
            }
            assertion = assertions.get(0);
        }
        return assertion;
    }

    public static String getDomainName(XMLObject samlObject) {
        NodeList list = samlObject.getDOM().getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "NameID");
        String domainName = null;
        if (list.getLength() > 0) {
            String userName = list.item(0).getTextContent();
            domainName = MultitenantUtils.getTenantDomain(userName);
        }
        return domainName;
    }

    /**
     * Generate the key store name from the domain name
     *
     * @param tenantDomain tenant domain name
     * @return key store file name
     */
    private static String generateKSNameFromDomainName(String tenantDomain) {
        String ksName = tenantDomain.trim().replace(".", "-");
        return (ksName + ".jks");
    }

    /**
     * Create DocumentBuilderFactory with the XXE prevention measurements
     *
     * @return DocumentBuilderFactory instance
     */
    public static DocumentBuilderFactory getSecuredDocumentBuilder() {

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setXIncludeAware(false);
        dbf.setExpandEntityReferences(false);
        try {
            dbf.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE, false);
            dbf.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE, false);
            dbf.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE, false);
        } catch (ParserConfigurationException e) {
            log.error(
                    "Failed to load XML Processor Feature " + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE + " or " +
                            Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE + " or " + Constants.LOAD_EXTERNAL_DTD_FEATURE);
        }

        SecurityManager securityManager = new SecurityManager();
        securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT);
        dbf.setAttribute(Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY, securityManager);

        return dbf;
    }

    /** Build NameIDPolicy object given name ID policy format
    *
    * @param nameIdPolicy Name ID policy format
    * @return SAML NameIDPolicy object
    */
   public static NameIDPolicy buildNameIDPolicy(String nameIdPolicy) {
       NameIDPolicy nameIDPolicyObj = new NameIDPolicyBuilder().buildObject();
       if (!StringUtils.isEmpty(nameIdPolicy)) {
           nameIDPolicyObj.setFormat(nameIdPolicy);
       } else {
           nameIDPolicyObj.setFormat(SSOConstants.NAME_ID_POLICY_DEFAULT);
       }
       nameIDPolicyObj.setAllowCreate(true);
       return nameIDPolicyObj;
   }

    /** Build NameID object given name ID format
    *
    * @param nameIdFormat Name ID format
    * @param subject Subject
    * @return SAML NameID object
    */
   public static NameID buildNameID(String nameIdFormat, String subject) {
       NameID nameIdObj = new NameIDBuilder().buildObject();
       if (!StringUtils.isEmpty(nameIdFormat)) {
           nameIdObj.setFormat(nameIdFormat);
       } else {
           nameIdObj.setFormat(SSOConstants.NAME_ID_POLICY_DEFAULT);
       }
       nameIdObj.setValue(subject);
       return nameIdObj;
   }

   /**
    * Replaces the ${} in url with system properties and returns
    *
    * @param acsUrl assertion consumer service url
    * @return acsUrl with system properties replaced
    */
   public static String processAcsUrl(String acsUrl) {
       //matches shortest segments that are between '{' and '}'
       Pattern pattern = Pattern.compile("\\$\\{(.*?)\\}");
       Matcher matcher = pattern.matcher(acsUrl);
       while (matcher.find()) {
           String match = matcher.group(1);
           String property = System.getProperty(match);
           if (property != null) {
               acsUrl = acsUrl.replace("${" + match + "}", property);
           } else {
               log.warn("System Property " + match + " is not set");
           }
       }
       return acsUrl;
   }

    /**
     * Validate the Signature's Reference URI.
     *
     * First validate the Reference URI against the parent's ID itself.  Then validate that the
     * URI (if non-empty) resolves to the same Element node as is cached by the SignableSAMLObject.
     *
     *
     * @param uri the Signature Reference URI attribute value
     * @param signableObject the SignableSAMLObject whose signature is being validated
     * @throws ValidationException  if the URI is invalid or doesn't resolve to the expected DOM node
     */
    private static void validateReferenceURI(String uri, SignableSAMLObject signableObject) throws ValidationException {
        if (DatatypeHelper.isEmpty(uri)) {
            return;
        }

        String uriID = uri.substring(1);

        Element expected = signableObject.getDOM();
        if (expected == null) {
            log.error("SignableSAMLObject does not have a cached DOM Element.");
            throw new ValidationException("SignableSAMLObject does not have a cached DOM Element.");
        }
        Document doc = expected.getOwnerDocument();

        Element resolved = IdResolver.getElementById(doc, uriID);
        if (resolved == null) {
            log.error("Apache xmlsec IdResolver could not resolve the Element for id reference: " + uriID);
            throw new ValidationException(
                    "Apache xmlsec IdResolver could not resolve the Element for id reference: " + uriID);
        }

        if (!expected.isSameNode(resolved)) {
            log.error("Signature Reference URI " + uri + " did not resolve to the expected parent Element");
            throw new ValidationException("Signature Reference URI did not resolve to the expected parent Element");
        }
    }

    /**
     * Validate that the Signature instance does not contain any ds:Object children.
     *
     * @param apacheSig the Apache XML Signature instance
     * @throws ValidationException if the signature contains ds:Object children
     */
    private static void validateObjectChildren(XMLSignature apacheSig) throws ValidationException {
        if (apacheSig.getObjectLength() > 0) {
            log.error("Signature contained " + apacheSig.getObjectLength() + " ds:Object child element(s)");
            throw new ValidationException("Signature contained illegal ds:Object children");
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
## ------------------------------------------------------------------------
## Licensed to the Apache Software Foundation (ASF) under one or more
## contributor license agreements.  See the NOTICE file distributed with
## this work for additional information regarding copyright ownership.
## The ASF licenses this file to You under the Apache License, Version 2.0
## (the "License"); you may not use this file except in compliance with
## the License.  You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
## ------------------------------------------------------------------------
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <groupId>${groupId}</groupId>
  <artifactId>${artifactId}</artifactId>
  <packaging>jar</packaging>
  <version>${version}</version>

  <name>A Camel Spring Route</name>
  <url>http://www.myorganization.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  </properties>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-parent</artifactId>
        <version>${camel-version}</version>
        <scope>import</scope>
        <type>pom</type>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
    <dependency>
      <groupId>org.apache.camel</groupId>
      <artifactId>camel-core</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.camel</groupId>
      <artifactId>camel-spring</artifactId>
    </dependency>

    <!-- logging -->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-slf4j-impl</artifactId>
      <scope>runtime</scope>
    </dependency>

    <!-- testing -->
    <dependency>
      <groupId>org.apache.camel</groupId>
      <artifactId>camel-test-spring</artifactId>
      <scope>test</scope>
    </dependency>

  </dependencies>

  <build>
    <defaultGoal>install</defaultGoal>

    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>${maven-compiler-plugin-version}</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-resources-plugin</artifactId>
        <version>${maven-resources-plugin-version}</version>
        <configuration>
          <encoding>UTF-8</encoding>
        </configuration>
      </plugin>

      <!-- allows the route to be ran via 'mvn camel:run' -->
      <plugin>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-maven-plugin</artifactId>
        <version>${camel-version}</version>
      </plugin>
    </plugins>
  </build>

</project>


text:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:ignore="UnusedResources"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp" />


text:
<?php

/*
 * User Role Editor WordPress plugin
 * Author: Vladimir Garagulya
 * Email: support@role-editor.com
 * License: GPLv2 or later
 */

/**
 * Process AJAX requrest from User Role Editor
 *
 * @author vladimir
 */
class URE_Ajax_Processor {

    protected $lib = null;

    public function __construct($lib) {

        $this->lib = $lib;

    }
    // end of __construct()

    protected function ajax_check_permissions() {

        if (!wp_verify_nonce($_REQUEST['wp_nonce'], 'user-role-editor')) {
            echo json_encode(array('result'=>'error', 'message'=>'URE: Wrong or expired request'));
            die;
        }

        $key_capability = $this->lib->get_key_capability();
        if (!current_user_can($key_capability)) {
            echo json_encode(array('result'=>'error', 'message'=>'URE: Insufficient permissions'));
            die;
        }

    }
    // end of ajax_check_permissions()

    protected function get_users_without_role() {
        global $wp_roles;

        $new_role = filter_input(INPUT_POST, 'new_role', FILTER_SANITIZE_STRING);
        if (empty($new_role)) {
            $answer = array('result'=>'failure', 'message'=>'Provide new role');
            return $answer;
        }

        $assign_role = $this->lib->get_assign_role();
        if ($new_role==='no_rights') {
            $assign_role->create_no_rights_role();
        }

        if (!isset($wp_roles)) {
            $wp_roles = new WP_Roles();
        }
        if (!isset($wp_roles->roles[$new_role])) {
            $answer = array('result'=>'failure', 'message'=>'Selected new role does not exist');
            return $answer;
        }

        $users = $assign_role->get_users_without_role($new_role);

        $answer = array('result'=>'success', 'users'=>$users, 'new_role'=>$new_role, 'message'=>'success');

        return $answer;
    }
    // end of get_users_without_role()

    protected function _dispatch($action) {
        switch ($action) {
            case 'get_users_without_role':
                $answer = $this->get_users_without_role();
                break;
            default:
                $answer = array('result' => 'error', 'message' => 'unknown action "' . $action . '"');
        }

        return $answer;
    }
    // end of _dispatch()

    /**
     * AJAX requests dispatcher
     */
    public function dispatch() {

        $this->ajax_check_permissions();

        $action = filter_input(INPUT_POST, 'sub_action', FILTER_SANITIZE_STRING);
        if (empty($action)) {
            $action = filter_input(INPUT_GET, 'sub_action', FILTER_SANITIZE_STRING);
        }

        $answer = $this->_dispatch($action);

        $json_answer = json_encode($answer);
        echo $json_answer;
        die;
    }

}
// end of URE_Ajax_Processor


text:
# Nautilus (November 2017)

## Change Summary

 Title | Git Issue | Description
:------|:----------|:------------
Play minor version upgrade | [287](https://github.com/thomsonreuters/CM-Well/pull/287) | Play 3rd-party package upgraded to version 2.6.7
Integration test improvements | [275](https://github.com/thomsonreuters/CM-Well/pull/275) | Integration test improvements
**qstream** now supports **length** parameter | [285](https://github.com/thomsonreuters/CM-Well/pull/285) | The **qstream** streaming operator now supports the **length** parameter, which is the maximum number of infotons you want to receive.
Range filters now supported for **xg**/**yg**/**gqp** | [297](https://github.com/thomsonreuters/CM-Well/pull/297) | Range filters (<, <<, >, >>) for field values are now supported for **xg**/**yg**/**gqp** queries. See [Traversing Outbound and Inbound Links (*xg*, *yg* and *gqp*)](../../APIReference/Traversal/API.Traversal.Intro.md).
**Bug fix:** Removed unreliable missing data testing from **_sp** query | [296](https://github.com/thomsonreuters/CM-Well/pull/296) | The **_sp** API used to compare indexed infoton numbers with stored infoton numbers. In some cases of duplicate infotons, this would return erroneous "data missing" errors. This test has been disabled.
**Bug fix:** Hang in upgrade process | [279](https://github.com/thomsonreuters/CM-Well/pull/279) | A health test for Elastic Search would fail and the upgrade process would hang, due to a badly formed curl command (with no -X parameter).
**Bug fix**: Broken pagination links in Atom format | [222](https://github.com/thomsonreuters/CM-Well/pull/222) | Pagination links in Atom-formatted results were broken because of redundant question marks.

### Changes to API

* **qstream** now takes the **length** parameter.
* Range filters now supported for **xg**/**yg**/**gqp**.


text:
namespace Alpha.DAL.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class initial : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.Publishers",
                c => new
                    {
                        PublisherId = c.Int(nullable: false, identity: true),
                        Name = c.String(nullable: false, maxLength: 255),
                        Location = c.String(maxLength: 255),
                        IsDeleted = c.Boolean(nullable: false),
                        DateDeleted = c.DateTime(),
                    })
                .PrimaryKey(t => t.PublisherId);

        }

        public override void Down()
        {
            DropTable("dbo.Publishers");
        }
    }
}


text:
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;

namespace Spect.Net.VsPackage.VsxLibrary.ToolWindow
{
    /// <summary>
    /// This class provides access to Visual Studio's Error List tool window.
    /// </summary>
    public class ErrorListWindow
    {
        private readonly ErrorListProvider _errorListProvider;

        public ErrorListWindow()
        {
            _errorListProvider = new ErrorListProvider(SpectNetPackage.Default);
        }

        /// <summary>
        /// Clears the content of the Error List
        /// </summary>
        public void Clear()
        {
            _errorListProvider.Tasks.Clear();
        }

        /// <summary>
        /// Adds the specified error to the provider
        /// </summary>
        /// <param name="error">Error information entry</param>
        public void AddErrorTask(ErrorTask error)
        {
            _errorListProvider.Tasks.Add(error);
        }

        /// <summary>
        /// Navigates to the source code associated with the specified task
        /// </summary>
        /// <param name="task">Error task</param>
        public void Navigate(ErrorTask task)
        {
            _errorListProvider.Navigate(task, VSConstants.LOGVIEWID_Primary);
        }
    }
}


text:
/*
 * Base structure
 */

/* Move down content because we have a fixed navbar that is 50px tall */
body {
  padding-top: 4rem;
}

/*
 * Global add-ons
 */

.sub-header {
//  padding-bottom: 10px;
//  border-bottom: 1px solid #eee;
}

/*
 * Top navigation
 * Hide default border to remove 1px line.
 */
.navbar-fixed-top {
  border: 0;
}

.navbar-inverse {
  background-color: rgba(16,16,16, 0.8);
}

/*
 * Sidebar
 */

/* Hide for mobile, show later */
.sidebar {
  display: none;
}
@media (min-width: 768px) {
  .sidebar {
    position: fixed;
    top: 4rem;
    bottom: 0;
    left: 0;
    z-index: 1000;
    display: block;
    padding: 2rem 20px;
    overflow-x: hidden;
    overflow-y: auto; /* Scrollable contents if viewport is shorter than content. */
    background-color: rgba(245,245,245, 0.7);
//    border-right: 1px solid #eee;
  }
}

/* Sidebar navigation */
.nav-sidebar {
  margin-right: -21px; /* 20px padding + 1px border */
  margin-bottom: 2rem;
  margin-left: -20px;
  margin-top: 0;
}
.nav-sidebar > li > a {
  padding-right: 20px;
  padding-left: 20px;
}
.nav-sidebar > .active > a,
.nav-sidebar > .active > a:hover,
.nav-sidebar > .active > a:focus {
  color: #fff;
  background-color: #428bca;
}

/*
 * Main content
 */

.main {
  padding: 2rem 20px;
}
@media (min-width: 768px) {
  .main {
    padding-right: 40px;
    padding-left: 40px;
  }
}
.main .page-header {
  margin-top: 0;
}

/*
 * Placeholder dashboard ideas
 */

.placeholders {
  margin-bottom: 2rem;
  text-align: center;
}
.placeholders h4 {
  margin-bottom: 0;
}
.placeholder {
  margin-bottom: 2rem;
}
.placeholder img {
  display: inline-block;
  border-radius: 50%;
}

/*
 * Debug grid button.
 */

.toggle-grid {
  margin: 1rem;
  line-height: 2rem;
  padding: 0 6px;
}


text:
package net.seesharpsoft.intellij.plugins.csv.intention;

import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.util.IncorrectOperationException;
import net.seesharpsoft.intellij.plugins.csv.CsvHelper;
import net.seesharpsoft.intellij.plugins.csv.psi.CsvField;
import net.seesharpsoft.intellij.plugins.csv.psi.CsvTypes;
import net.seesharpsoft.intellij.psi.PsiHelper;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

@NonNls
public class CsvUnquoteValueIntentionAction extends CsvIntentionAction {

    public CsvUnquoteValueIntentionAction() {
        super("Unquote");
    }

    @Override
    public boolean isAvailable(@NotNull Project project, Editor editor, @Nullable final PsiElement psiElement) {
        if (!super.isAvailable(project, editor, psiElement)) {
            return false;
        }

        PsiElement element = psiElement == null ? null : CsvHelper.getParentFieldElement(psiElement);
        return element instanceof CsvField &&
                element.getFirstChild() != null &&
                (PsiHelper.getElementType(element.getFirstChild()) == CsvTypes.QUOTE ||
                        PsiHelper.getElementType(element.getLastChild()) == CsvTypes.QUOTE) &&
                CsvIntentionHelper.getChildren(element).stream().allMatch(childElement -> PsiHelper.getElementType(childElement) != CsvTypes.ESCAPED_TEXT);
    }

    @Override
    public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException {
        CsvIntentionHelper.unquoteValue(project, CsvHelper.getParentFieldElement(element));
    }

}


text:
function P = khatrirao(varargin)
%KHATRIRAO Khatri-Rao product of matrices.
%
%   KHATRIRAO(A,B) computes the Khatri-Rao product of matrices A and
%   B that have the same number of columns.  The result is the
%   column-wise Kronecker product
%   [KRON(A(:,1),B(:,1)) ... KRON(A(:,n),B(:,n))]
%
%   KHATRIRAO(A1,A2,...) computes the Khatri-Rao product of
%   multiple matrices that have the same number of columns.
%
%   KHATRIRAO(C) computes the Khatri-Rao product of
%   the matrices in cell array C.
%
%   KHATRIRAO(...,'r') computes the Khatri-Rao product in reverse
%   order.
%
%   Examples
%   A = rand(5,2); B = rand(3,2); C = rand(2,2);
%   khatrirao(A,B) %<-- Khatri-Rao of A and B
%   khatrirao(B,A,'r') %<-- same thing as above
%   khatrirao({C,B,A}) %<-- passing a cell array
%   khatrirao({A,B,C},'r') %<-- same as above
%
%   See also TENSOR, KTENSOR.
%
%MATLAB Tensor Toolbox.
%Copyright 2012, Sandia Corporation.

% This is the MATLAB Tensor Toolbox by T. Kolda, B. Bader, and others.
% http://www.sandia.gov/~tgkolda/TensorToolbox.
% Copyright (2012) Sandia Corporation. Under the terms of Contract
% DE-AC04-94AL85000, there is a non-exclusive license for use of this
% work by or on behalf of the U.S. Government. Export of this data may
% require a license from the United States Government.
% The full license terms can be found in the file LICENSE.txt

%% Error checking on input and set matrix order
% Note that this next if/else check forces A to be a cell array.
if ischar(varargin{end}) && varargin{end} == 'r'
    if nargin == 2 && iscell(varargin{1})
        % Input is a single cell array
        A = varargin{1};
    else
        % Input is a sequence of matrices
        A = {varargin{1:end-1}};
    end
    matorder = length(A):-1:1;
else
    if nargin == 1 && iscell(varargin{1})
        % Input is a single cell array
        A = varargin{1};
    else
        % Input is a sequence of matrices
        A = varargin;
    end
    matorder = 1:length(A);
end

%% Error check on matrices and compute number of rows in result

% N = number of columns (must be the same for every input)
N = size(A{1},2);

% After loop, M = number of rows in the result
M = 1;

for i = matorder
    if ndims(A) ~= 2
        error('Each argument must be a matrix');
    end
    if (N ~= size(A{i},2))
        error('All matrices must have the same number of columns.')
    end
    M = M * size(A{i},1);
end

%% Computation

% Preallocate
P = zeros(M,N);

% Loop through all the columns
for n = 1:N
    % Loop through all the matrices
    ab = A{matorder(1)}(:,n);
    for i = matorder(2:end)
       % Compute outer product of nth columns
       ab = A{i}(:,n) * ab(:).';
    end
    % Fill nth column of P with reshaped result
    P(:,n) = ab(:);
end


text:
#ifndef _MAGICKWAND_MAGICK_WAND_DEPRECATED_H
#define _MAGICKWAND_MAGICK_WAND_DEPRECATED_H

#include "wand/MagickWand.h"

#endif


text:
package com.sequenceiq.cloudbreak.orchestrator.salt.domain;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.collect.Streams;
import com.google.gson.annotations.SerializedName;

public class MinionIpAddressesResponse {

    @JsonProperty("return")
    @SerializedName("return")
    private List<Map<String, JsonNode>> result;

    @JsonIgnore
    public List<String> getAllIpAddresses() {
        return result.stream()
                .flatMap(result -> result.entrySet().stream())
                .filter(entry -> entry.getValue() != null)
                .filter(entry -> !"false".equals(entry.getValue().asText()))
                .flatMap(entry -> Streams.stream(entry.getValue().elements()))
                .map(JsonNode::asText)
                .collect(Collectors.toList());
    }

    @JsonIgnore
    public List<String> getUnreachableNodes() {
        return result.stream()
                .flatMap(result -> result.entrySet().stream())
                .filter(entry -> entry.getValue() == null || "false".equals(entry.getValue().asText()))
                .map(entry -> entry.getKey())
                .collect(Collectors.toList());
    }

    public List<Map<String, JsonNode>> getResult() {
        return result;
    }

    public void setResult(List<Map<String, JsonNode>> result) {
        this.result = result;
    }

    @Override
    public String toString() {
        return "MinionIpAddressesResponse{"
                + "result=" + result
                + '}';
    }
}


text:
using System;
using System.Diagnostics.Contracts;

namespace NDepend.Path {

   ///
   ///Represents a relative file path.
   ///
   ///<remarks>
   ///The extension method <see cref="PathHelpers.ToRelativeFilePath(string)"/> can be called to create a new IRelativeFilePath object from a string.
   ///</remarks>
   [ContractClass(typeof(IRelativeFilePathContract))]
   public interface IRelativeFilePath : IFilePath, IRelativePath {

      ///
      ///Returns a new relative file path refering to a file with name <paramref name="fileName"/>, located in the same directory as this file.
      ///
      ///<param name="fileName">The brother file name</param>
      new IRelativeFilePath GetBrotherFileWithName(string fileName);

      ///
      ///Returns a new relative directory path representing a directory with name <paramref name="directoryName"/>, located in the same directory as this file.
      ///
      ///<param name="directoryName">The brother directory name.</param>
      new IRelativeDirectoryPath GetBrotherDirectoryWithName(string directoryName);

      ///
      ///Returns a new relative file path representing this file with its file name extension updated to <paramref name="newExtension"/>.
      ///
      ///<param name="newExtension">The new file extension. It must begin with a dot followed by one or many characters.</param>
      new IRelativeFilePath UpdateExtension(string newExtension);

      ///
      ///Resolve this relative file from <paramref name="pivotDirectory"/>. If this file is "..\Dir2\File.txt" and <paramref name="pivotDirectory"/> is "C:\Dir1\Dir3", the returned absolute file is "C:\Dir1\Dir2\File.txt".
      ///
      ///<remarks>
      ///The returned file nor <paramref name="pivotDirectory"/> need to exist for this operation to complete properly.
      ///</remarks>
      ///<param name="pivotDirectory">The pivot directory from which the absolute path is computed.</param>
      ///<exception cref="ArgumentException">
      ///An absolute path cannot be resolved from <paramref name="pivotDirectory"/>.
      ///This can happen for example if <paramref name="pivotDirectory"/> is "C:\Dir1" and this relative file path is "..\..\Dir2\File.txt".
      ///</exception>
      ///<returns>A new absolute file path representing this relative file resolved from <paramref name="pivotDirectory"/>.</returns>
      new IAbsoluteFilePath GetAbsolutePathFrom(IAbsoluteDirectoryPath pivotDirectory);
   }

   [ContractClassFor(typeof(IRelativeFilePath))]
   abstract class IRelativeFilePathContract : IRelativeFilePath {
      public IRelativeFilePath GetBrotherFileWithName(string fileName) {
         Contract.Requires(fileName != null, "fileName must not be null");
         Contract.Requires(fileName.Length > 0, "fileName must not be empty");
         throw new NotImplementedException();
      }

      public IRelativeDirectoryPath GetBrotherDirectoryWithName(string directoryName) {
         Contract.Requires(directoryName != null, "directoryName must not be null");
         Contract.Requires(directoryName.Length > 0, "directoryName must not be empty");
         throw new NotImplementedException();
      }

      public IRelativeFilePath UpdateExtension(string newExtension) {
         Contract.Requires(newExtension != null, "newExtension must not be null");
         Contract.Requires(newExtension.Length >= 2, "newExtension must have at least two characters");
         Contract.Requires(newExtension[0] == '.', "newExtension first character must be a dot");
         throw new NotImplementedException();
      }

      public IAbsoluteFilePath GetAbsolutePathFrom(IAbsoluteDirectoryPath pivotDirectory) {
         Contract.Requires(pivotDirectory != null, "pivotDirectory must not be null");
         throw new NotImplementedException();
      }

      IAbsolutePath IRelativePath.GetAbsolutePathFrom(IAbsoluteDirectoryPath pivotDirectory) {
         throw new NotImplementedException();
      }

      IFilePath IFilePath.GetBrotherFileWithName(string fileName) { throw new NotImplementedException(); }
      IDirectoryPath IFilePath.GetBrotherDirectoryWithName(string directoryName) { throw new NotImplementedException(); }
      IFilePath IFilePath.UpdateExtension(string newExtension) { throw new NotImplementedException(); }

      public abstract bool CanGetAbsolutePathFrom(IAbsoluteDirectoryPath path);
      public abstract bool CanGetAbsolutePathFrom(IAbsoluteDirectoryPath path, out string failureReason);
      public abstract bool IsChildOf(IDirectoryPath parentDirectory);
      public abstract bool IsAbsolutePath { get; }
      public abstract bool IsRelativePath { get; }
      public abstract bool IsEnvVarPath { get; }
      public abstract bool IsVariablePath { get; }
      public abstract bool IsDirectoryPath { get; }
      public abstract bool IsFilePath { get; }
      public abstract PathMode PathMode { get; }
      IRelativeDirectoryPath IRelativePath.ParentDirectoryPath { get { throw new NotImplementedException(); } }
      public abstract IDirectoryPath ParentDirectoryPath { get; }
      public abstract bool HasParentDirectory { get; }
      public abstract bool NotEquals(object obj);
      public abstract string FileName { get; }
      public abstract string FileNameWithoutExtension { get; }
      public abstract string FileExtension { get; }
      public abstract bool HasExtension(string extension);

   }
}


text:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe XapitSync::Indexer do
  before(:each) do
    # we don't want to trigger the sync process with these
    XapitSync.override_syncing { }
  end

  it "should have path to pid file" do
    XapitSync::Indexer.pid_path.should == "#{Rails.root}/tmp/xapit_sync.pid"
  end

  it "should consider running when pid file exists" do
    stub(XapitSync::Indexer).pid_path { "/pid/path" }
    mock(File).exist?("/pid/path") { true }
    XapitSync::Indexer.should be_running
  end

  it "should consider running when pid file exists" do
    stub(XapitSync::Indexer).pid_path { "/pid/path" }
    mock(File).exist?("/pid/path") { true }
    XapitSync::Indexer.should be_running
  end

  it "should raise an exception when attempting to run when already running" do
    stub(XapitSync::Indexer).running? true
    lambda { XapitSync::Indexer.new.run(0) }.should raise_error
  end

  it "should create and delete pid file when run" do
    stub(XapitSync::Indexer).pid_path { "/path/to/pid" }
    indexer = XapitSync::Indexer.new
    mock(File).open("/path/to/pid", "w")
    mock(indexer).index_changes(123)
    mock(File).delete("/path/to/pid")
    indexer.run(123)
  end

  it "should loop through all changes and index each of them" do
    XapitChange.delete_all
    recipe = Recipe.create!(:name => "foo")
    mock(Recipe.xapit_index_blueprint).create_record(recipe.id)
    indexer = XapitSync::Indexer.new
    mock(indexer).sleep(5)
    mock(indexer).push_changes
    indexer.index_changes(5)
    XapitChange.count.should == 0
  end

  it "should push changes by flushing the database and reloading domains" do
    mock(Xapit::Config).writable_database.stub!.flush
    mock(Xapit::Config).close_database
    mock(XapitSync).reload_domains
    indexer = XapitSync::Indexer.new
    indexer.push_changes
  end
end


text:
using FluentAssertions;
using Mendham.Domain.Extensions;
using Mendham.Domain.Test.TestObjects.Other;
using Mendham.Domain.Test.TestObjects.ValueObjects.Struct;
using Mendham.Testing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;

namespace Mendham.Domain.Test
{
    public class ValueObjectExtensionTest
    {
        [Theory, MendhamData]
        public void IsEqualToValueObjectT_SameReference_True(StructValueObject valueObject)
        {
            bool result = valueObject.IsEqualToValueObject(valueObject);

            result.Should()
                .BeTrue("it is the same reference to the value object");
        }

        [Theory, MendhamData]
        public void IsEqualToValueObjectT_HasDifferentValues_False(StructValueObject valueObject1, StructValueObject valueObject2)
        {
            bool result = valueObject1.IsEqualToValueObject(valueObject2);

            result.Should()
                .BeFalse("the properties are not equal");
        }

        [Theory, MendhamData]
        public void IsEqualToValueObjectT_HasSameValues_True(string valueObjectStr, int valueObjectInt)
        {
            var valueObject1 = new StructValueObject(valueObjectStr, valueObjectInt);
            var valueObject2 = new StructValueObject(valueObjectStr, valueObjectInt);

            bool result = valueObject1.IsEqualToValueObject(valueObject2);

            result.Should()
                .BeTrue("the two value objects have the same properties");
        }

        [Theory, MendhamData]
        public void IsEqualToValueObjectT_HasOneDifferentValue_False(string valueObject1Str, string valueObject2Str, int commonInt)
        {
            var valueObject1 = new StructValueObject(valueObject1Str, commonInt);
            var valueObject2 = new StructValueObject(valueObject2Str, commonInt);

            bool result = valueObject1.IsEqualToValueObject(valueObject2);

            result.Should()
                .BeFalse("one of the properties of the two value objects does not match");
        }

        [Theory, MendhamData]
        public void IsEqualToValueObjectT_FirstHasNull_False(string valueObject2Str, int commonInt)
        {
            var valueObject1 = new StructValueObject(null, commonInt);
            var valueObject2 = new StructValueObject(valueObject2Str, commonInt);

            bool result = valueObject1.IsEqualToValueObject(valueObject2);

            result.Should()
                .BeFalse("one of the properties of the two value objects does not match");
        }

        [Theory, MendhamData]
        public void IsEqualToValueObjectT_SecondHasNull_False(string valueObject1Str, int commonInt)
        {
            var valueObject1 = new StructValueObject(valueObject1Str, commonInt);
            var valueObject2 = new StructValueObject(null, commonInt);

            bool result = valueObject1.IsEqualToValueObject(valueObject2);

            result.Should()
                .BeFalse("one of the properties of the two value objects does not match");
        }

        [Theory, MendhamData]
        public void IsEqualToValueObjectT_MatchingValuesWithNull_True(int commonInt)
        {
            var valueObject1 = new StructValueObject(null, commonInt);
            var valueObject2 = new StructValueObject(null, commonInt);

            bool result = valueObject1.IsEqualToValueObject(valueObject2);

            result.Should()
                .BeTrue("the properties of the two objects match");
        }

        [Theory, MendhamData]
        public void IsEqualToValueObjectT_SecondObjectIsDefault(StructValueObject valueObject1)
        {
            StructValueObject valueObject2 = default(StructValueObject);

            bool result = valueObject1.IsEqualToValueObject(valueObject2);

            result.Should()
                .BeFalse("the first value object has a value and the second is null");
        }
        [Theory, MendhamData]
        public void IsEqualToValueObjectAsObject_SameReference_True(StructValueObject valueObject)
        {
            bool result = valueObject.IsEqualToValueObject((object)valueObject);

            result.Should()
                .BeTrue("it is the same reference to the value object");
        }

        [Theory, MendhamData]
        public void IsEqualToValueObjectAsObject_HasDifferentValues_False(StructValueObject valueObject1, StructValueObject valueObject2)
        {
            bool result = valueObject1.IsEqualToValueObject((object)valueObject2);

            result.Should()
                .BeFalse("the properties are not equal");
        }

        [Theory, MendhamData]
        public void IsEqualToValueObjectAsObject_HasSameValues_True(string valueObjectStr, int valueObjectInt)
        {
            var valueObject1 = new StructValueObject(valueObjectStr, valueObjectInt);
            object valueObject2 = new StructValueObject(valueObjectStr, valueObjectInt);

            bool result = valueObject1.IsEqualToValueObject(valueObject2);

            result.Should()
                .BeTrue("the two value objects have the same properties");
        }

        [Theory, MendhamData]
        public void IsEqualToValueObjectAsObject_HasOneDifferentValue_False(string valueObject1Str, string valueObject2Str, int commonInt)
        {
            var valueObject1 = new StructValueObject(valueObject1Str, commonInt);
            object valueObject2 = new StructValueObject(valueObject2Str, commonInt);

            bool result = valueObject1.IsEqualToValueObject(valueObject2);

            result.Should()
                .BeFalse("one of the properties of the two value objects does not match");
        }

        [Theory, MendhamData]
        public void IsEqualToValueObjectAsObject_FirstHasNull_False(string valueObject2Str, int commonInt)
        {
            var valueObject1 = new StructValueObject(null, commonInt);
            object valueObject2 = new StructValueObject(valueObject2Str, commonInt);

            bool result = valueObject1.IsEqualToValueObject(valueObject2);

            result.Should()
                .BeFalse("one of the properties of the two value objects does not match");
        }

        [Theory, MendhamData]
        public void IsEqualToValueObjectAsObject_SecondHasNull_False(string valueObject1Str, int commonInt)
        {
            var valueObject1 = new StructValueObject(valueObject1Str, commonInt);
            object valueObject2 = new StructValueObject(null, commonInt);

            bool result = valueObject1.IsEqualToValueObject(valueObject2);

            result.Should()
                .BeFalse("one of the properties of the two value objects does not match");
        }

        [Theory, MendhamData]
        public void IsEqualToValueObjectAsObject_MatchingValuesWithNull_True(int commonInt)
        {
            var valueObject1 = new StructValueObject(null, commonInt);
            object valueObject2 = new StructValueObject(null, commonInt);

            bool result = valueObject1.IsEqualToValueObject(valueObject2);

            result.Should()
                .BeTrue("the properties of the two objects match");
        }

        [Theory, MendhamData]
        public void IsEqualToValueObjectAsObject_SecondObjectIsDefault(StructValueObject valueObject1)
        {
            object valueObject2 = default(StructValueObject);

            bool result = valueObject1.IsEqualToValueObject(valueObject2);

            result.Should()
                .BeFalse("the first value object has a value and the second is null");
        }

        [Theory, MendhamData]
        public void IsEqualToValueObjectAsObject_DifferentValueObject_False(string valueObjectStr, int valueObjectInt)
        {
            var valueObject1 = new StructValueObject(valueObjectStr, valueObjectInt);
            object valueObject2 = new AltStructValueObject(valueObjectStr, valueObjectInt);

            bool result = valueObject1.IsEqualToValueObject(valueObject2);

            result.Should()
                .BeFalse("the two objects are not the same type of value object");
        }

        [Theory, MendhamData]
        public void IsEqualToValueObjectAsObject_NonValueObject_False(string valueObjectStr, int valueObjectInt)
        {
            var valueObject1 = new StructValueObject(valueObjectStr, valueObjectInt);
            object valueObject2 = new PlainStructWithComponents(valueObjectStr, valueObjectInt);

            bool result = valueObject1.IsEqualToValueObject(valueObject2);

            result.Should()
                .BeFalse("the second object is not a value object");
        }

        [Theory, MendhamData]
        public void GetValueObjectHashCode_SameReference_Equal(StructValueObject valueObject)
        {
            var altRefForvalueObject = valueObject;

            int expected = valueObject.GetValueObjectHashCode();
            int result = valueObject.GetValueObjectHashCode();

            result.Should()
                .Be(expected, "they have the same reference");
        }

        [Theory, MendhamData]
        public void GetValueObjectHashCode_HasDifferentValues_NotEqual(StructValueObject valueObject1, StructValueObject valueObject2)
        {
            int expected = valueObject1.GetValueObjectHashCode();
            int result = valueObject2.GetValueObjectHashCode();

            result.Should()
                .NotBe(expected, "they have a different properties");
        }

        [Theory, MendhamData]
        public void GetValueObjectHashCode_HasSameValues_Equal(string valueObjectStr, int valueObjectInt)
        {
            var valueObject1 = new StructValueObject(valueObjectStr, valueObjectInt);
            var valueObject2 = new StructValueObject(valueObjectStr, valueObjectInt);

            int expected = valueObject1.GetValueObjectHashCode();
            int result = valueObject2.GetValueObjectHashCode();

            result.Should()
                .Be(expected, "they have the same properties");
        }

        [Theory, MendhamData]
        public void GetValueObjectHashCode_HasSameValuesWithNull_Equal(int valueObjectInt)
        {
            var valueObject1 = new StructValueObject(null, valueObjectInt);
            var valueObject2 = new StructValueObject(null, valueObjectInt);

            int expected = valueObject1.GetValueObjectHashCode();
            int result = valueObject2.GetValueObjectHashCode();

            result.Should()
                .Be(expected, "they have the same properties");
        }

        [Theory, MendhamData]
        public void GetValueObjectHashCode_HasSameValues_NotEqual(string valueObjectStr, int valueObjectInt)
        {
            var valueObject1 = new StructValueObject(valueObjectStr, valueObjectInt);
            var valueObject2 = new AltStructValueObject(valueObjectStr, valueObjectInt);

            int expected = valueObject1.GetValueObjectHashCode();
            int result = valueObject2.GetValueObjectHashCode();

            result.Should()
                .NotBe(expected, "they are not the same type of value object");
        }
    }
}


text:
require_relative '../../spec_helper'

describe Learndot::Records::Organization do

  before(:each) do
    @unicorn = Learndot::Unicorn.new :learndot_url => TEST_URL, :api_key => TEST_API_KEY
    @organization = @unicorn.organization
  end

  it 'should validate presence of app_name' do
    @organization.valid?.should be_true
    @organization.app_name = ''
    @organization.valid?.should be_false
  end

  it 'should validate presence of name' do
    @organization.valid?.should be_true
    @organization.name = ''
    @organization.valid?.should be_false
  end

  it 'should validate presence of host_url' do
    @organization.valid?.should be_true
    @organization.host_url = ''
    @organization.valid?.should be_false
  end

  it 'should destroy all its courses' do
    @organization.courses.each do |course|
     course.destroy!
    end
  end
end


text:
using System.Collections.Generic;
using System.Threading.Tasks;
using Demo.Core.Services;
using Octokit;

namespace Demo.App.Services.Offline
{
    public class OfflineRepositoryService : OfflineServiceBase, IRepositoryService
    {
        public Task<Repository> Get(string owner, string name)
        {
            return Deserialize<Repository>("caliburn-micro");
        }

        public Task<IReadOnlyList<Repository>> Search(string term)
        {
            return Deserialize<IReadOnlyList<Repository>>("search");
        }

        public Task<Readme> GetReadme(string owner, string name)
        {
            return Deserialize<Readme>("caliburn-micro-readme");
        }
    }
}