text:
package gov.hhs.fha.nhinc.policyengine.adapter.pip;

import gov.hhs.fha.nhinc.common.nhinccommonadapter.FineGrainedPolicyCriteriaType;
import gov.hhs.fha.nhinc.common.nhinccommonadapter.FineGrainedPolicyCriterionType;
import gov.hhs.fha.nhinc.common.nhinccommonadapter.PatientPreferencesType;
import gov.hhs.fha.nhinc.common.nhinccommonadapter.UserIdFormatType;
import oasis.names.tc.xacml._2_0.policy.schema.os.PolicyType;

import org.apache.commons.logging.Log;
import org.jmock.Mockery;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import org.jmock.integration.junit4.JMock;
import org.jmock.integration.junit4.JUnit4Mockery;

import org.junit.Ignore;
import org.junit.runner.RunWith;

import static org.junit.Assert.*;

/**
 * Unit tests for XACMLExtractor
 *
 * @author Les Westberg
 */
@RunWith(JMock.class)
public class XACMLExtractorTest {
    Mockery context = new JUnit4Mockery();
    static PolicyType oXACMLPolicy1 = null;
    static PolicyType oXACMLPolicy2 = null;
    static String XACML_EXAMPLE_1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
            + "<Policy xmlns=\"urn:oasis:names:tc:xacml:2.0:policy:schema:os\""
            + "  PolicyId=\"12345678-1234-1234-1234-123456781234\" "
            + "  RuleCombiningAlgId=\"urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:first-applicable\">"
            + "  <Description>CONSUMER CONSENT POLICY</Description>"
            + ""
            + "<!-- The Target element at the Policy level identifies the subject to whom the Policy applies -->"
            + "  <Target>"
            + "    <Resources>"
            + "      <Resource>"
            + "      <!-- Consumer ID -->"
            + "        <ResourceMatch MatchId=\"http://www.hhs.gov/healthit/nhin/function#instance-identifier-equal\">"
            + "          <AttributeValue DataType=\"urn:hl7-org:v3#II\" xmlns:hl7=\"urn:hl7-org:v3\">"
            + "            <hl7:PatientId root=\"1.1\" extension=\"D123401\"/>"
            + "          </AttributeValue>"
            + "          <ResourceAttributeDesignator AttributeId=\"http://www.hhs.gov/healthit/nhin#subject-id\" "
            + "                                       DataType=\"urn:hl7-org:v3#II\"/>"
            + "        </ResourceMatch>"
            + "      </Resource>"
            + "    </Resources>"
            + "    <Actions>"
            + "      <!-- This policy applies to all document query and document retrieve transactions -->"
            + "      <Action>"
            + "        <ActionMatch MatchId=\"urn:oasis:names:tc:xacml:1.0:function:anyURI-equal\">"
            + "          <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#anyURI\">"
            + "            urn:ihe:iti:2007:CrossGatewayRetrieve"
            + "          </AttributeValue>"
            + "          <ActionAttributeDesignator AttributeId=\"urn:oasis:names:tc:xacml:2.0:action\" "
            + "                                     DataType=\"http://www.w3.org/2001/XMLSchema#anyURI\"/>"
            + "        </ActionMatch>"
            + "      </Action>"
            + "      <Action>"
            + "        <ActionMatch MatchId=\"urn:oasis:names:tc:xacml:1.0:function:anyURI-equal\">"
            + "          <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#anyURI\">"
            + "            urn:ihe:iti:2007:CrossGatewayQuery"
            + "          </AttributeValue>"
            + "          <ActionAttributeDesignator AttributeId=\"urn:oasis:names:tc:xacml:2.0:action\" "
            + "                                     DataType=\"http://www.w3.org/2001/XMLSchema#anyURI\"/>"
            + "        </ActionMatch>"
            + "      </Action>"
            + "    </Actions>"
            + "  </Target>"
            + "  <Rule RuleId=\"1\" Effect=\"Permit\">"
            + "    <Description>Rule specifying fine grained criteria.</Description>"
            + "    <Target>"
            + "      <Subjects>"
            + "        <Subject>"
            + "          <!-- User Role -->"
            + "          <SubjectMatch MatchId=\"urn:oasis:names:tc:xacml:1.0:function:string-equal\">"
            + "            <!-- coded value for physicians -->"
            + "            <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">112247003</AttributeValue>"
            + "            <SubjectAttributeDesignator AttributeId=\"urn:oasis:names:tc:xacml:2.0:subject:role\" "
            + "                                        DataType=\"http://www.w3.org/2001/XMLSchema#string\"/>"
            + "          </SubjectMatch>"
            + "        </Subject>"
            + "      </Subjects>"
            + "      <!-- since there is no Resource element, this rule applies to all resources -->"
            + "    </Target>"
            + "  </Rule>"
            + "  <Rule RuleId=\"2\" Effect=\"Permit\">"
            + "    <Description>Rule specifying fine grained criteria.</Description>"
            + "    <Target>"
            + "      <Subjects>"
            + "        <Subject>"
            + "          <!-- User Role -->"
            + "          <SubjectMatch MatchId=\"urn:oasis:names:tc:xacml:1.0:function:string-equal\">"
            + "            <!-- coded value for dentists -->"
            + "            <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">106289002</AttributeValue>"
            + "            <SubjectAttributeDesignator AttributeId=\"urn:oasis:names:tc:xacml:2.0:subject:role\" "
            + "                                        DataType=\"http://www.w3.org/2001/XMLSchema#string\"/>"
            + "          </SubjectMatch>"
            + "        </Subject>"
            + "        <Subject>"
            + "          <!-- Organization ID-->"
            + "          <SubjectMatch MatchId=\"urn:oasis:names:tc:xacml:1.0:function:anyURI-equal\">"
            + "            <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#anyURI\">http://www.happytoothdental.com</AttributeValue>"
            + "            <SubjectAttributeDesignator AttributeId=\"urn:oasis:names:tc:xspa:1.0:subject:organization-id\" "
            + "                                        DataType=\"http://www.w3.org/2001/XMLSchema#anyURI\"/>"
            + "          </SubjectMatch>"
            + "        </Subject>"
            + "      </Subjects>"
            + "      <Resources>"
            + "        <Resource>"
            + "          <!-- Confidentiality Code -->"
            + "          <ResourceMatch MatchId=\"urn:oasis:names:tc:xacml:1.0:function:string-equal\">"
            + "            <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">N</AttributeValue>"
            + "            <ResourceAttributeDesignator AttributeId=\"urn:oasis:names:tc:xspa:1.0:resource:patient:hl7:confidentiality-code\" "
            + "                                         DataType=\"http://www.w3.org/2001/XMLSchema#string\"/>"
            + "          </ResourceMatch>"
            + "        </Resource>"
            + "      </Resources>"
            + "      <Environments>"
            + "        <Environment>"
            + "          <!-- Rule Start Date -->"
            + "            <EnvironmentMatch MatchId=\"urn:oasis:names:tc:xacml:1.0:function:date-greather-than-or-equal\">"
            + "              <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#date\">2009-07-01</AttributeValue>"
            + "              <EnvironmentAttributeDesignator AttributeId=\"http://www.hhs.gov/healthit/nhin#rule-start-date\" "
            + "                                              DataType=\"http://www.w3.org/2001/XMLSchema#date\"/>"
            + "            </EnvironmentMatch>"
            + "        </Environment>"
            + "        <Environment>"
            + "          <!-- Rule End Date -->"
            + "          <EnvironmentMatch MatchId=\"urn:oasis:names:tc:xacml:1.0:function:date-less-than-or-equal\">"
            + "            <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#date\">2009-12-31</AttributeValue>"
            + "            <EnvironmentAttributeDesignator AttributeId=\"http://www.hhs.gov/healthit/nhin#rule-end-date\" "
            + "                                            DataType=\"http://www.w3.org/2001/XMLSchema#date\"/>"
            + "          </EnvironmentMatch>"
            + "        </Environment>"
            + "      </Environments>      "
            + "    </Target>"
            + "  </Rule>"
            + "  <Rule RuleId=\"3\" Effect=\"Permit\">"
            + "    <Description>Rule specifying fine grained criteria.</Description>"
            + "    <Target>"
            + "      <Subjects>"
            + "        <Subject>"
            + "          <!-- Home Community Id -->"
            + "          <SubjectMatch MatchId=\"urn:oasis:names:tc:xacml:1.0:function:anyURI-equal\">"
            + "            <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#anyURI\">1.1</AttributeValue>"
            + "            <SubjectAttributeDesignator AttributeId=\"http://www.hhs.gov/healthit/nhin#HomeCommunityId\" "
            + "                                        DataType=\"http://www.w3.org/2001/XMLSchema#anyURI\"/>"
            + "          </SubjectMatch>"
            + "        </Subject>"
            + "        <Subject>"
            + "          <!-- Subject ID as email -->"
            + "          <SubjectMatch MatchId=\"urn:oasis:names:tc:xacml:1.0:function:rfc822Name-match\">"
            + "            <AttributeValue DataType=\"urn:oasis:names:tc:xacml:1.0:data-type:rfc822Name\">john.doe@somewhere.com</AttributeValue>"
            + "            <SubjectAttributeDesignator AttributeId=\"urn:oasis:names:tc:xacml:1.0:subject:subject-id\" "
            + "                                        DataType=\"urn:oasis:names:tc:xacml:1.0:data-type:rfc822Name\"/>"
            + "          </SubjectMatch>"
            + "        </Subject>"
            + "      </Subjects>"
            + "      <Resources>"
            + "        <Resource>"
            + "          <!-- Document Type (Class) -->"
            + "          <ResourceMatch MatchId=\"urn:oasis:names:tc:xacml:1.0:function:string-equal\">"
            + "            <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">45666666</AttributeValue>"
            + "            <ResourceAttributeDesignator AttributeId=\"urn:oasis:names:tc:xspa:1.0:resource:hl7:type\" "
            + "                                         DataType=\"http://www.w3.org/2001/XMLSchema#string\"/>"
            + "          </ResourceMatch>"
            + "        </Resource>"
            + "      </Resources>"
            + "    </Target>"
            + "  </Rule>"
            + "  <Rule RuleId=\"4\" Effect=\"Permit\">"
            + "    <Description>Rule specifying fine grained criteria.</Description>"
            + "    <Target>"
            + "      <Subjects>"
            + "        <Subject>"
            + "          <!-- User ID - X500 -->"
            + "          <SubjectMatch MatchId=\"urn:oasis:names:tc:xacml:1.0:function:x509Name-match\">"
            + "            <AttributeValue DataType=\"urn:oasis:names:tc:xacml:1.0:data-type:x500Name\">cn=John Doe, ou=People, o=Somewhere, c=us</AttributeValue>"
            + "            <SubjectAttributeDesignator AttributeId=\"urn:oasis:names:tc:xacml:1.0:subject:subject-id\" "
            + "                                        DataType=\"urn:oasis:names:tc:xacml:1.0:data-type:x500Name\"/>"
            + "          </SubjectMatch>"
            + "        </Subject>"
            + "        <Subject>"
            + "          <!-- Purpose for use -->"
            + "          <SubjectMatch MatchId=\"urn:oasis:names:tc:xacml:1.0:function:string-equal\">"
            + "            <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">Treatment</AttributeValue>"
            + "            <SubjectAttributeDesignator AttributeId=\"urn:oasis:names:tc:xspa:1.0:subject:purposeofuse\" "
            + "                                        DataType=\"http://www.w3.org/2001/XMLSchema#string\"/>"
            + "          </SubjectMatch>"
            + "        </Subject>"
            + "      </Subjects>"
            + "      <Resources>"
            + "        <Resource>"
            + "          <!-- Document Id  -->"
            + "          <ResourceMatch MatchId=\"urn:oasis:names:tc:xacml:1.0:function:string-equal\">"
            + "            <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">1234567</AttributeValue>"
            + "            <ResourceAttributeDesignator AttributeId=\"urn:oasis:names:tc:xacml:1.0:resource:resource-id\" "
            + "                  								       DataType=\"http://www.w3.org/2001/XMLSchema#string\"/>"
            + "          </ResourceMatch>" + "        </Resource>" + "      </Resources>" + "    </Target>"
            + "  </Rule>" + "  <Rule RuleId=\"5\" Effect=\"Deny\">"
            + "    <Description>Rule specifying fine grained criteria.</Description>" + "    <Target/>" + "  </Rule>"
            + "</Policy>";

    static String XACML_EXAMPLE_2 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
            + "<Policy xmlns=\"urn:oasis:names:tc:xacml:2.0:policy:schema:os\""
            + "  PolicyId=\"12345678-1234-1234-1234-123456781234\" "
            + "  RuleCombiningAlgId=\"urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:first-applicable\">"
            + "  <Description>CONSUMER CONSENT POLICY</Description>" + ""
            + "<!-- The Target element at the Policy level identifies the subject to whom the Policy applies -->"
            + "  <Target>" + "    <Resources>" + "      <Resource>" + "      <!-- Consumer ID -->"
            + "        <ResourceMatch MatchId=\"http://www.hhs.gov/healthit/nhin/function#instance-identifier-equal\">"
            + "          <AttributeValue DataType=\"urn:hl7-org:v3#II\" xmlns:hl7=\"urn:hl7-org:v3\">"
            + "            <hl7:PatientId root=\"1.1\" extension=\"D123401\"/>" + "          </AttributeValue>"
            + "          <ResourceAttributeDesignator AttributeId=\"http://www.hhs.gov/healthit/nhin#subject-id\" "
            + "                                       DataType=\"urn:hl7-org:v3#II\"/>" + "        </ResourceMatch>"
            + "      </Resource>" + "    </Resources>" + "    <Actions>"
            + "      <!-- This policy applies to all document query and document retrieve transactions -->"
            + "      <Action>" + "        <ActionMatch MatchId=\"urn:oasis:names:tc:xacml:1.0:function:anyURI-equal\">"
            + "          <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#anyURI\">"
            + "            urn:ihe:iti:2007:CrossGatewayRetrieve" + "          </AttributeValue>"
            + "          <ActionAttributeDesignator AttributeId=\"urn:oasis:names:tc:xacml:2.0:action\" "
            + "                                     DataType=\"http://www.w3.org/2001/XMLSchema#anyURI\"/>"
            + "        </ActionMatch>" + "      </Action>" + "      <Action>"
            + "        <ActionMatch MatchId=\"urn:oasis:names:tc:xacml:1.0:function:anyURI-equal\">"
            + "          <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#anyURI\">"
            + "            urn:ihe:iti:2007:CrossGatewayQuery" + "          </AttributeValue>"
            + "          <ActionAttributeDesignator AttributeId=\"urn:oasis:names:tc:xacml:2.0:action\" "
            + "                                     DataType=\"http://www.w3.org/2001/XMLSchema#anyURI\"/>"
            + "        </ActionMatch>" + "      </Action>" + "    </Actions>" + "  </Target>"
            + "  <Rule RuleId=\"5\" Effect=\"Deny\">"
            + "    <Description>Rule specifying fine grained criteria.</Description>" + "    <Target/>" + "  </Rule>"
            + "</Policy>";

    public XACMLExtractorTest() {
    }

    @BeforeClass
    public static void setUpClass() throws Exception {
        XACMLSerializer oSerializer = new XACMLSerializer();
        oXACMLPolicy1 = oSerializer.deserializeConsentXACMLDoc(XACML_EXAMPLE_1);
        oXACMLPolicy2 = oSerializer.deserializeConsentXACMLDoc(XACML_EXAMPLE_2);

        // try
        // {
        // String sTest = oSerializer.serializeConsentXACMLDoc(oXACMLPolicy1);
        // String sStop = "";
        // }
        // catch (Exception e)
        // {
        // String sJunk = "text";
        // String sJunk2 = "text";
        // }

    }

    @AfterClass
    public static void tearDownClass() throws Exception {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    /**
     * This asserts the data in Fine Grained Policy Criterion 1 of the data.
     *
     * @param oCriterion The criterion to be validated.
     */
    public void assertValidExample1Criterion1(FineGrainedPolicyCriterionType oCriterion) {
        assertNotNull("Criterion 1", oCriterion);
        assertEquals("SequentialId", "1", oCriterion.getSequentialId());
        assertEquals("Permit", true, oCriterion.isPermit());
        assertNotNull("UserRole", oCriterion.getUserRole());
        assertEquals("UserRole.Code", "112247003", oCriterion.getUserRole().getCode());

        // That is all that should be in here. Everything else should be null - make sure that is true.
        // ----------------------------------------------------------------------------------------------
        assertNull("UserRole.DisplayName", oCriterion.getUserRole().getDisplayName());
        assertNull("UserRole.CodeSystem", oCriterion.getUserRole().getCodeSystem());
        assertNull("UserRole.CodeSystemName", oCriterion.getUserRole().getCodeSystemName());
        assertNull("PolicyOID", oCriterion.getPolicyOID());
        assertNull("DocumentTypeCode", oCriterion.getDocumentTypeCode());
        assertNull("PurposeOfUse", oCriterion.getPurposeOfUse());
        assertNull("ConfidentialityCode", oCriterion.getConfidentialityCode());
        assertNull("Action", oCriterion.getAction());
        assertNull("OrganizationId", oCriterion.getOrganizationId());
        assertNull("HomeCommunityId", oCriterion.getHomeCommunityId());
        assertNull("UniqueDocumentId", oCriterion.getUniqueDocumentId());
        assertNull("RuleStartDate", oCriterion.getRuleStartDate());
        assertNull("RuleEndDate", oCriterion.getRuleEndDate());
        assertNull("UserId", oCriterion.getUserId());
        assertNull("UserIdFormat", oCriterion.getUserIdFormat());
    }

    /**
     * This asserts the data in Fine Grained Policy Criterion 2 of the data.
     *
     * @param oCriterion The criterion to be validated.
     */
    public void assertValidExample1Criterion2(FineGrainedPolicyCriterionType oCriterion) {
        assertNotNull("Criterion 2", oCriterion);
        assertEquals("SequentialId", "2", oCriterion.getSequentialId());
        assertEquals("Permit", true, oCriterion.isPermit());
        assertNotNull("UserRole", oCriterion.getUserRole());
        assertEquals("UserRole.Code", "106289002", oCriterion.getUserRole().getCode());
        assertEquals("OrganizationId", "http://www.happytoothdental.com", oCriterion.getOrganizationId());
        assertNotNull("ConfidentialityCode", oCriterion.getConfidentialityCode());
        assertEquals("ConfidentialityCode.Code", "N", oCriterion.getConfidentialityCode().getCode());
        assertNotNull("RuleStartDate", oCriterion.getRuleStartDate());
        assertEquals("RuleStartDate", "20090701", oCriterion.getRuleStartDate());
        assertNotNull("RuleEndDate", oCriterion.getRuleEndDate());
        assertEquals("RuleEndDate", "20091231", oCriterion.getRuleEndDate());

        // That is all that should be in here. Everything else should be null - make sure that is true.
        // ----------------------------------------------------------------------------------------------
        assertNull("UserRole.DisplayName", oCriterion.getUserRole().getDisplayName());
        assertNull("UserRole.CodeSystem", oCriterion.getUserRole().getCodeSystem());
        assertNull("UserRole.CodeSystemName", oCriterion.getUserRole().getCodeSystemName());
        assertNull("ConfidentialityCode.DisplayName", oCriterion.getConfidentialityCode().getDisplayName());
        assertNull("ConfidentialityCode.CodeSystem", oCriterion.getConfidentialityCode().getCodeSystem());
        assertNull("ConfidentialityCode.CodeSystemName", oCriterion.getConfidentialityCode().getCodeSystemName());
        assertNull("PolicyOID", oCriterion.getPolicyOID());
        assertNull("DocumentTypeCode", oCriterion.getDocumentTypeCode());
        assertNull("PurposeOfUse", oCriterion.getPurposeOfUse());
        assertNull("Action", oCriterion.getAction());
        assertNull("HomeCommunityId", oCriterion.getHomeCommunityId());
        assertNull("UniqueDocumentId", oCriterion.getUniqueDocumentId());
        assertNull("UserId", oCriterion.getUserId());
        assertNull("UserIdFormat", oCriterion.getUserIdFormat());
    }

    /**
     * This asserts the data in Fine Grained Policy Criterion 3 of the data.
     *
     * @param oCriterion The criterion to be validated.
     */
    public void assertValidExample1Criterion3(FineGrainedPolicyCriterionType oCriterion) {
        assertNotNull("Criterion 3", oCriterion);
        assertEquals("SequentialId", "3", oCriterion.getSequentialId());
        assertEquals("Permit", true, oCriterion.isPermit());
        assertEquals("HomeCommunityId", "1.1", oCriterion.getHomeCommunityId());
        assertEquals("UserId", "john.doe@somewhere.com", oCriterion.getUserId());
        assertEquals("UserIdFormat", UserIdFormatType.EMAIL, oCriterion.getUserIdFormat());
        assertNotNull("DocumentTypeCode", oCriterion.getDocumentTypeCode());
        assertEquals("DocumentTypeCode.Code", "45666666", oCriterion.getDocumentTypeCode().getCode());

        // That is all that should be in here. Everything else should be null - make sure that is true.
        // ----------------------------------------------------------------------------------------------
        assertNull("DocumentTypeCode.DisplayName", oCriterion.getDocumentTypeCode().getDisplayName());
        assertNull("DocumentTypeCode.CodeSystem", oCriterion.getDocumentTypeCode().getCodeSystem());
        assertNull("DocumentTypeCode.CodeSystemName", oCriterion.getDocumentTypeCode().getCodeSystemName());
        assertNull("UserRole", oCriterion.getUserRole());
        assertNull("PolicyOID", oCriterion.getPolicyOID());
        assertNull("PurposeOfUse", oCriterion.getPurposeOfUse());
        assertNull("ConfidentialityCode", oCriterion.getConfidentialityCode());
        assertNull("Action", oCriterion.getAction());
        assertNull("OrganizationId", oCriterion.getOrganizationId());
        assertNull("UniqueDocumentId", oCriterion.getUniqueDocumentId());
        assertNull("RuleStartDate", oCriterion.getRuleStartDate());
        assertNull("RuleEndDate", oCriterion.getRuleEndDate());
    }

    /**
     * This asserts the data in Fine Grained Policy Criterion 4 of the data.
     *
     * @param oCriterion The criterion to be validated.
     */
    public void assertValidExample1Criterion4(FineGrainedPolicyCriterionType oCriterion) {
        assertNotNull("Criterion 4", oCriterion);
        assertEquals("SequentialId", "4", oCriterion.getSequentialId());
        assertEquals("Permit", true, oCriterion.isPermit());
        assertEquals("UserId", "cn=John Doe, ou=People, o=Somewhere, c=us", oCriterion.getUserId());
        assertEquals("UserIdFormat", UserIdFormatType.X_500, oCriterion.getUserIdFormat());
        assertNotNull("PurposeOfUse", oCriterion.getPurposeOfUse());
        assertEquals("PurposeOfUse.Code", "Treatment", oCriterion.getPurposeOfUse().getCode());
        assertEquals("UniqueDocumentId", "1234567", oCriterion.getUniqueDocumentId());

        // That is all that should be in here. Everything else should be null - make sure that is true.
        // ----------------------------------------------------------------------------------------------
        assertNull("PurposeOfUse.DisplayName", oCriterion.getPurposeOfUse().getDisplayName());
        assertNull("PurposeOfUse.CodeSystem", oCriterion.getPurposeOfUse().getCodeSystem());
        assertNull("PurposeOfUse.CodeSystemName", oCriterion.getPurposeOfUse().getCodeSystemName());
        assertNull("UserRole", oCriterion.getUserRole());
        assertNull("PolicyOID", oCriterion.getPolicyOID());
        assertNull("DocumentTypeCode", oCriterion.getDocumentTypeCode());
        assertNull("ConfidentialityCode", oCriterion.getConfidentialityCode());
        assertNull("Action", oCriterion.getAction());
        assertNull("OrganizationId", oCriterion.getOrganizationId());
        assertNull("HomeCommunityId", oCriterion.getHomeCommunityId());
        assertNull("RuleStartDate", oCriterion.getRuleStartDate());
        assertNull("RuleEndDate", oCriterion.getRuleEndDate());
    }

    /**
     * This asserts the data in Fine Grained Policy Criterion 5 of the data.
     *
     * @param oCriterion The criterion to be validated.
     */
    public void assertValidExample1Criterion5(FineGrainedPolicyCriterionType oCriterion) {
        assertNotNull("Criterion 5", oCriterion);
        assertEquals("SequentialId", "5", oCriterion.getSequentialId());
        assertEquals("Permit", false, oCriterion.isPermit());

        // That is all that should be in here. Everything else should be null - make sure that is true.
        // ----------------------------------------------------------------------------------------------
        assertNull("UserRole", oCriterion.getUserRole());
        assertNull("PolicyOID", oCriterion.getPolicyOID());
        assertNull("DocumentTypeCode", oCriterion.getDocumentTypeCode());
        assertNull("PurposeOfUse", oCriterion.getPurposeOfUse());
        assertNull("ConfidentialityCode", oCriterion.getConfidentialityCode());
        assertNull("Action", oCriterion.getAction());
        assertNull("OrganizationId", oCriterion.getOrganizationId());
        assertNull("HomeCommunityId", oCriterion.getHomeCommunityId());
        assertNull("UniqueDocumentId", oCriterion.getUniqueDocumentId());
        assertNull("RuleStartDate", oCriterion.getRuleStartDate());
        assertNull("RuleEndDate", oCriterion.getRuleEndDate());
        assertNull("UserId", oCriterion.getUserId());
        assertNull("UserIdFormat", oCriterion.getUserIdFormat());
    }

    /**
     * This validates that the information in the FineGrainedPolicyCriteria is what we expected it to be.
     *
     * @param oFineGrainedPolicyCriteria The policy to validate.
     */
    public void assertValidExample1FineGrainedPolicyCriteria(FineGrainedPolicyCriteriaType oFineGrainedPolicyCriteria) {
        assertNotNull("FineGrainedPolicyCriteria", oFineGrainedPolicyCriteria);
        assertEquals("Size of FineGrainedPolicyCriterion", 5, oFineGrainedPolicyCriteria
                .getFineGrainedPolicyCriterion().size());

        for (int i = 0; i < oFineGrainedPolicyCriteria.getFineGrainedPolicyCriterion().size(); i++) {
            FineGrainedPolicyCriterionType oCriterion = oFineGrainedPolicyCriteria.getFineGrainedPolicyCriterion().get(
                    i);

            switch (i + 1) // 0 Offset
            {
            case 1: {
                assertValidExample1Criterion1(oCriterion);
                break;
            }
            case 2: {
                assertValidExample1Criterion2(oCriterion);
                break;
            }
            case 3: {
                assertValidExample1Criterion3(oCriterion);
                break;
            }
            case 4: {
                assertValidExample1Criterion4(oCriterion);
                break;
            }
            case 5: {
                assertValidExample1Criterion5(oCriterion);
                break;
            }
            default: {
                fail("Unexpected rule was encountered.");
                break;
            }
            }
        }

    }

    /**
     * Test out the ExtractPatientPreferences method.
     *
     */
    @Ignore
    @Test
    public void testExtractPatientPreferences() {
        final Log mockLog = context.mock(Log.class);

        XACMLExtractor oExtractor = new XACMLExtractor() {
            @Override
            protected Log createLogger() {
                return mockLog;
            }
        };

        // Test Policy 1
        // --------------
        PatientPreferencesType oPtPref = null;
        try {
            oPtPref = oExtractor.extractPatientPreferences(oXACMLPolicy1);
        } catch (Exception e) {
            fail("Received unexpected exception when extracting patient preferences.  Error: " + e.getMessage());
        }

        assertNotNull("PatientPreferences", oPtPref);
        assertEquals("AssigningAuthority", "1.1", oPtPref.getAssigningAuthority());
        assertEquals("PatientId", "D123401", oPtPref.getPatientId());
        assertNotNull("FineGrainedPolicyMetadata", oPtPref.getFineGrainedPolicyMetadata());
        assertEquals("PolicyOIDXacml", "12345678-1234-1234-1234-123456781234", oPtPref.getFineGrainedPolicyMetadata()
                .getPolicyOID());
        assertValidExample1FineGrainedPolicyCriteria(oPtPref.getFineGrainedPolicyCriteria());

        // Test Policy 2
        // ---------------
        oPtPref = null;
        try {
            oPtPref = oExtractor.extractPatientPreferences(oXACMLPolicy2);
        } catch (Exception e) {
            fail("Received unexpected exception when extracting patient preferences.  Error: " + e.getMessage());
        }

        assertNotNull("PatientPreferences", oPtPref);
        assertEquals("AssigningAuthority", "1.1", oPtPref.getAssigningAuthority());
        assertEquals("PatientId", "D123401", oPtPref.getPatientId());
        assertNotNull("FineGrainedPolicyMetadata", oPtPref.getFineGrainedPolicyMetadata());
        assertEquals("PolicyOIDXacml", "12345678-1234-1234-1234-123456781234", oPtPref.getFineGrainedPolicyMetadata()
                .getPolicyOID());
        assertEquals("OptIn", false, oPtPref.isOptIn());
        assertNull("FineGranedPolicyCriteria", oPtPref.getFineGrainedPolicyCriteria());

    }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class QBhelper {

	function __construct() {

	}

	/*--------------------------------------------------------------------------------------------------------
	 *
	 *      Genernate new session token
	 *
	 *--------------------------------------------------------------------------------------------------------*/

	public function generateSession() {

		// Generate signature
		$nonce = rand();
		$timestamp = time(); // time() method must return current timestamp in UTC but seems like hi is return timestamp in current time zone
		$signature_string = "application_id=" . QB_APP_ID . "&auth_key=" . QB_AUTH_KEY . "&nonce=" . $nonce . "&timestamp=" . $timestamp;
		$signature = hash_hmac('sha1', $signature_string , QB_AUTH_SECRET);

		$post_body = http_build_query( array(
			'application_id' => QB_APP_ID,
			'auth_key' => QB_AUTH_KEY,
			'timestamp' => $timestamp,
			'nonce' => $nonce,
			'signature' => $signature
		));

		// Configure cURL
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, QB_API_ENDPOINT . '/' . QB_PATH_AUTH); // Full path is - https://api.quickblox.com/auth.json
		curl_setopt($curl, CURLOPT_POST, true); // Use POST
		curl_setopt($curl, CURLOPT_POSTFIELDS, $post_body); // Setup post body
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Receive server response
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

		// Execute request and read response
		$response = curl_exec($curl);

		$result = null;
		ob_start();
		try {
			$result = json_decode($response)->session->token;
		}
		catch (Exception $e) {
		}

		// Close connection
		curl_close($curl);
		ob_end_clean();
		return $result;
	}

	/*--------------------------------------------------------------------------------------------------------
	 *
	 *      Signup
	 *
	 *--------------------------------------------------------------------------------------------------------*/
	public function signupUser($fullname, $username, $email, $phone, $avatar, $path, $external_user_id) {
		$token = $this->generateSession();

		$request = json_encode(array(
			'user' => array(
				'full_name' => $fullname,
		 		'login' => $username,
		  		'email' => $email,
		  		'password' => QB_DEFAULT_PASSWORD,
		  		'phone' => $phone,
		  		'website' => $avatar,
		  		'custom_data' => $path,
		  		'external_user_id' => $external_user_id
		  	)
		));

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, QB_API_ENDPOINT . '/' . QB_PATH_USER); // Full path is - https://api.quickblox.com/auth.json
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
		  'Content-Type: application/json',
		  'QuickBlox-REST-API-Version: 0.1.0',
		  'QB-Token: ' . $token
		));
		$response = curl_exec($ch);

		$result = null;

		ob_start();
		try {
			$result = json_decode($response);
		}
		catch (Exception $e) {
			$result = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		}
		curl_close($ch);
		ob_end_clean();
		return $result;
	}

	/*--------------------------------------------------------------------------------------------------------
	 *
	 *      Update User
	 *
	 *--------------------------------------------------------------------------------------------------------*/
	public function updateUser($qb_token, $qb_id, $user) {

		$request = json_encode(array(
			'user' => $user
		));

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, QB_API_ENDPOINT . '/users/' . $qb_id.'.json'); // Full path is - https://api.quickblox.com/auth.json
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
		curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
		  'Content-Type: application/json',
		  'QuickBlox-REST-API-Version: 0.1.0',
		  'QB-Token: ' . $qb_token
		));
		$response = curl_exec($ch);

		$result = null;

		ob_start();
		try {
			$result = json_decode($response);
		}
		catch (Exception $e) {
			$result = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		}
		curl_close($ch);
		ob_end_clean();
		return $result;
	}

	/*--------------------------------------------------------------------------------------------------------
	 *
	 *      Delete User
	 *
	 *--------------------------------------------------------------------------------------------------------*/
	public function deleteUser($qb_token, $qb_id) {

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, QB_API_ENDPOINT . '/users/' . $qb_id.'.json'); // Full path is - https://api.quickblox.com/auth.json
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
		  'Content-Type: application/json',
		  'QuickBlox-REST-API-Version: 0.1.0',
		  'QB-Token: ' . $qb_token
		));
		$response = curl_exec($ch);

		$result = null;

		ob_start();
		try {
			$result = json_decode($response);
		}
		catch (Exception $e) {
			$result = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		}
		curl_close($ch);
		ob_end_clean();
		return $result;
	}

	/*--------------------------------------------------------------------------------------------------------
	 *
	 *      Signin
	 *
	 *--------------------------------------------------------------------------------------------------------*/

	public function signinUser($username = null) {

		$nonce = rand();
		$timestamp = time(); // time() method must return current timestamp in UTC but seems like hi is return timestamp in current time zone
		$signature_string = "application_id=" . QB_APP_ID . "&auth_key=" . QB_AUTH_KEY . "&nonce=" . $nonce . "&timestamp=" . $timestamp."&user[login]=".$username."&user[password]=".QB_DEFAULT_PASSWORD;
		$signature = hash_hmac('sha1', $signature_string , QB_AUTH_SECRET);

		$post_body = http_build_query( array(
			'application_id' => QB_APP_ID,
			'auth_key' => QB_AUTH_KEY,
			'timestamp' => $timestamp,
			'nonce' => $nonce,
			'signature' => $signature,
			'user' => array('login'=>$username, 'password'=>QB_DEFAULT_PASSWORD)
		));

		// Configure cURL
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, QB_API_ENDPOINT . '/' . QB_PATH_AUTH); // Full path is - https://api.quickblox.com/auth.json
		curl_setopt($curl, CURLOPT_POST, true); // Use POST
		curl_setopt($curl, CURLOPT_POSTFIELDS, $post_body); // Setup post body
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Receive server response
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

		// Execute request and read response
		$response = curl_exec($curl);
		$result = null;

		ob_start();
		try {
			$result = json_decode($response);
		}
		catch (Exception $e) {
		}
		curl_close($curl);
		ob_end_clean();
		return $result;
	}

	/*--------------------------------------------------------------------------------------------------------
	 *
	 *      Sign out
	 *
	 *--------------------------------------------------------------------------------------------------------*/
	public function signoutUser($email) {

	}

	/*--------------------------------------------------------------------------------------------------------
	 *
	 *      Create a new group
	 *
	 *--------------------------------------------------------------------------------------------------------*/
	public function createGroup($token, $type, $name, $ids) {

		$request = json_encode(array(
			'type' => $type,
	 		'name' => $name,
	  		'occupants_ids' => $ids
		));

		$ch = curl_init();

		curl_setopt($ch, CURLOPT_URL, QB_API_ENDPOINT . '/' . QB_PATH_DIALOG); // Full path is - https://api.quickblox.com/auth.json
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
		  'Content-Type: application/json',
		  'QuickBlox-REST-API-Version: 0.1.0',
		  'QB-Token: ' . $token
		));
		$response = curl_exec($ch);

		$result = null;

		ob_start();
		try {
			$result = json_decode($response);
			// $result = $response;
		}
		catch (Exception $e) {
			// $result = curl_getinfo($ch, CURLINFO_HTTP_CODE);
			$result = 'error';
		}
		curl_close($ch);
		ob_end_clean();
		return $result;
	}

	/*--------------------------------------------------------------------------------------------------------
	 *
	 *      Update group
	 *
	 *--------------------------------------------------------------------------------------------------------*/
	public function updateGroup($token, $group_id, $name, $ids) {

		$request = null;
		if (strlen($ids) > 0)
		{
			$request = json_encode(array(
		 		'name' => $name,
		  		'push_all' => array (
		  			'occupants_ids' => explode(',', $ids)
		  		)
			));
		}
		else
		{
			$request = json_encode(array(
		 		'name' => $name
			));
		}

		$ch = curl_init();

		curl_setopt($ch, CURLOPT_URL, QB_API_ENDPOINT . '/chat/Dialog/' . $group_id .'.json'); // Full path is - https://api.quickblox.com/auth.json
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
		curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
		  'Content-Type: application/json',
		  'QuickBlox-REST-API-Version: 0.1.0',
		  'QB-Token: ' . $token
		));
		$response = curl_exec($ch);

		$result = null;

		ob_start();
		try {
			$result = json_decode($response);
			// $result = $response;
		}
		catch (Exception $e) {
			// $result = curl_getinfo($ch, CURLINFO_HTTP_CODE);
			$result = 'error';
		}
		curl_close($ch);
		ob_end_clean();
		return $result;
	}

	/*--------------------------------------------------------------------------------------------------------
	 *
	 *      Update group (remove group members)
	 *
	 *--------------------------------------------------------------------------------------------------------*/
	public function removeGroupMember($token, $group_id, $ids) {

		$request = null;
		if (strlen($ids) > 0)
		{
			$request = json_encode(array(
		  		'pull_all' => array (
		  			'occupants_ids' => explode(',', $ids)
		  		)
			));
		}
		else
		{
			$request = json_encode(array(
		 		'name' => $name
			));
		}

		$ch = curl_init();

		curl_setopt($ch, CURLOPT_URL, QB_API_ENDPOINT . '/chat/Dialog/' . $group_id .'.json'); // Full path is - https://api.quickblox.com/auth.json
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
		curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
		  'Content-Type: application/json',
		  'QuickBlox-REST-API-Version: 0.1.0',
		  'QB-Token: ' . $token
		));
		$response = curl_exec($ch);

		$result = null;

		ob_start();
		try {
			$result = json_decode($response);
			// $result = $response;
		}
		catch (Exception $e) {
			// $result = curl_getinfo($ch, CURLINFO_HTTP_CODE);
			$result = 'error';
		}
		curl_close($ch);
		ob_end_clean();
		return $result;
	}

	/*--------------------------------------------------------------------------------------------------------
	 *
	 *      Get group
	 *
	 *--------------------------------------------------------------------------------------------------------*/
	public function getGroup($qb_token, $group_id) {

		$ch = curl_init();

		curl_setopt($ch, CURLOPT_URL, QB_API_ENDPOINT . '/' . QB_PATH_DIALOG . '?_id=' . $group_id); // Full path is - https://api.quickblox.com/auth.json
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
		  'Content-Type: application/json',
		  'QuickBlox-REST-API-Version: 0.1.0',
		  'QB-Token: ' . $qb_token
		));
		$response = curl_exec($ch);

		$result = null;

		ob_start();
		try {
			$result = json_decode($response);
			// $result = $response;
		}
		catch (Exception $e) {
			// $result = curl_getinfo($ch, CURLINFO_HTTP_CODE);
			$result = 'error';
		}
		curl_close($ch);
		ob_end_clean();
		return $result;
	}

	/*--------------------------------------------------------------------------------------------------------
	 *
	 *      Signup
	 *
	 *--------------------------------------------------------------------------------------------------------*/
	public function createCirculate($qb_token, $chat_dialog_id, $recipient_id, $message) {

		$request = json_encode(array(
			'chat_dialog_id' =>  $chat_dialog_id,
	 		'message' => $message,
	  		'recipient_id' => $recipient_id,
	  		'send_to_chat' => 1,
	  		'circulate' => 1,
		));

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, QB_API_ENDPOINT . '/' . QB_PATH_MESSAGE); // Full path is - https://api.quickblox.com/auth.json
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
		  'Content-Type: application/json',
		  'QuickBlox-REST-API-Version: 0.1.0',
		  'QB-Token: ' . $qb_token
		));
		$response = curl_exec($ch);

		$result = null;

		ob_start();
		try {
			$result = json_decode($response);
		}
		catch (Exception $e) {
			$result = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		}
		curl_close($ch);
		ob_end_clean();
		return $result;
	}

	/*--------------------------------------------------------------------------------------------------------
	 *
	 *      Send GCM
	 *
	 *--------------------------------------------------------------------------------------------------------*/
	public function sendGCM($id, $content) {
		// API access key from Google API's Console

		ob_start();

		$registrationIds = array( $id );
		// prep the bundle

		$fields = array
		(
			'registration_ids' 	=> $registrationIds,
			'data'			=> $content
		);

		$headers = array
		(
			'Authorization: key=' . GCM_API_KEY,
			'Content-Type: application/json'
		);

		$ch = curl_init();
		curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
		curl_setopt( $ch,CURLOPT_POST, true );
		curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
		curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
		curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
		curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
		$result = curl_exec($ch );

		echo $result;

		curl_close( $ch );

		ob_end_clean();

		return $result;
	}

	/*--------------------------------------------------------------------------------------------------------
	 *
	 *      Send APN
	 *
	 *--------------------------------------------------------------------------------------------------------*/
	public function sendAPN($deviceToken, $content, $pemFilename = "") {
		if ($pemFilename == "")
			$pemFilename = 'pushcert.pem';

		// set time limit to zero in order to avoid timeout
		set_time_limit(0);

		// charset header for output
		header('content-type: text/html; charset: utf-8');

		// this is the pass phrase you defined when creating the key
		$passphrase = 'qwert';
		// you can post a variable to this string or edit the message here
		// tr_to_utf function needed to fix the Turkish characters
		//$message = tr_to_utf("blah blah blah...");

		// load your device ids to an array
		$deviceIds = array(
			$deviceToken
		);
		// this is where you can customize your notification
		//$payload = '{"aps":{"alert":"' . $message . '","sound":"default", "type": "ipray_invitation", "sender":"' . $sender . '", "receiver":"' . $receiver . '"}}';
		$payload = '{"aps":' . $content . '}';
		//$payload = '{"aps":{"alert":"blah blah blah...","sound":"default", "type": "ipray_invitation"}}';

		$result = 'Start' . '
';
		ob_start();

		////////////////////////////////////////////////////////////////////////////////
		// start to create connection
		$ctx = stream_context_create();
		stream_context_set_option($ctx, 'ssl', 'local_cert', $pemFilename);
		stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

		echo count($deviceIds) . ' devices will receive notifications.
';

		$undelivered = 0;

		foreach ($deviceIds as $item) {
		    // wait for some time
		    sleep(1);

		    // Open a connection to the APNS server
		    $fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);

		    if (!$fp) {
		        exit("Failed to connect: $err $errstr" . '
');
		    } else {
		        echo 'Apple service is online. ' . '
';
		    }

		    // Build the binary notification
		    $msg = chr(0) . pack('n', 32) . pack('H*', $item) . pack('n', strlen($payload)) . $payload;

		    // Send it to the server
		    $result = fwrite($fp, $msg, strlen($msg));

		    if (!$result) {
		        //echo 'Undelivered message count: ' . $item . '
';
		        $undelivered++;
		    } else {
		        echo 'Delivered message count: ' . $item . '
';
		    }

		    if ($fp) {
		        fclose($fp);
		        echo 'The connection has been closed by the client' . '
';
		    }
		}

		echo count($deviceIds) . ' devices have received notifications.
';

		ob_end_clean();

		// set time limit back to a normal value
		set_time_limit(30);

		return $undelivered;
	}

	public function sendViaMailgun($from, $to, $subject, $html) {

		$ch = curl_init();

		curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
	    curl_setopt($ch, CURLOPT_USERPWD, 'api:key-7e055f5229a3cc5f47cdb456549baa9d');
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
	    curl_setopt($ch, CURLOPT_URL,
	          'https://api.mailgun.net/v3/email.eggchat.net/messages');
	    curl_setopt($ch, CURLOPT_POSTFIELDS,
	            array('from' => $from,
	                  'to' => $to,
	                  'subject' => $subject,
	                  'text' => $html));
	    $result = curl_exec($ch);

	    $result = curl_error($ch);
		curl_close($ch);
		return $result;
	}

}
?>

redpajama_set_name: RedPajamaGithub


text:
def escape(text):
    return text.replace('\\', '\\\\').replace('"', '\\"')

opposites = {
    'north': 'south',
    'east': 'west',
    'south': 'north',
    'west': 'east'
}

class Rel:
    def __init__(self, offset=0):
        self.offset = offset

    def __add__(self, other):
        return Rel(self.offset + other)

    def __sub__(self, other):
        return Rel(self.offset - other)

    def __str__(self):
        if self.offset == 0:
            return '~'
        return '~%d' % self.offset

class CommandPlacer:

    def __init__(self, origin):
        self.x, self.y, self.z = origin
        self.commands = []
        self.block_positions = []

    def place(self, line):
        orig_x, orig_z = self.x, self.z
        branch_len = 0
        for main, branch in line:
            setblock = self.create_setblock(main)
            self.commands.append(setblock)
            this_branch_len = 0
            for additional in branch:
                self.x += 1
                setblock = self.create_setblock(additional, True)
                self.commands.append(setblock)
                this_branch_len += 1
            self.x = orig_x
            branch_len = max(branch_len, this_branch_len)
            self.z += 1
        if branch_len > 0: branch_len += 1 # add space after branch
        self.x = orig_x + 1 + branch_len
        self.z = orig_z

    def output(self):
        return self.commands

    def cleanup(self):
        destroyblocks = []
        for pos in self.block_positions:
            destroyblocks.append('setblock %s %s %s air' % pos)
        return destroyblocks

    def create_setblock(self, block, rotate=False):
        block, command = block
        self.block_positions.append((self.x, self.y, self.z))

        if block.mode == 'CHAIN':
            block_type = 'chain_command_block'
        elif block.mode == 'REPEAT':
            block_type = 'repeating_command_block'
        else:
            block_type = 'command_block'

        state = {}
        if block.cond:
            state['conditional'] = 'true'
        direction = 'south'
        if rotate:
            direction = 'east'
        if block.opposite:
            direction = opposites[direction]
        state['facing'] = direction

        state_str = '[' + ','.join([k+'='+v for k,v in state.items()]) + ']'
        data = ('{TrackOutput:0b,auto:%db,Command:"%s",' \
               + 'UpdateLastExecution:%db}') % (
                   1 if block.auto else 0,
                   escape(command),
                   1 if block.single_use else 0)

        block = block_type + state_str + data

        return 'setblock %s %s %s %s replace' % (
            self.x, self.y, self.z, block)


text:
@protocol NSMutableCopying
- (id)mutableCopyWithZone:(struct _NSZone *)arg1;
@end


text:
<#
.SYNOPSIS

No summary available.

.DESCRIPTION

No description available.

.PARAMETER Class
No description available.
.PARAMETER Timestamp
No description available.
.PARAMETER Path
No description available.
.PARAMETER Size
No description available.
.OUTPUTS

DiskSpaceMonitorDescriptorDiskSpace<PSCustomObject>
#>

function Initialize-DiskSpaceMonitorDescriptorDiskSpace {
    [CmdletBinding()]
    Param (
        [Parameter(Position = 0, ValueFromPipelineByPropertyName = $true)]
        [String]
        ${Class},
        [Parameter(Position = 1, ValueFromPipelineByPropertyName = $true)]
        [System.Nullable[Int32]]
        ${Timestamp},
        [Parameter(Position = 2, ValueFromPipelineByPropertyName = $true)]
        [String]
        ${Path},
        [Parameter(Position = 3, ValueFromPipelineByPropertyName = $true)]
        [System.Nullable[Int32]]
        ${Size}
    )

    Process {
        'Creating PSCustomObject: PSOpenAPITools => DiskSpaceMonitorDescriptorDiskSpace' | Write-Debug
        $PSBoundParameters | Out-DebugParameter | Write-Debug

        $PSO = [PSCustomObject]@{
            "_class" = ${Class}
            "timestamp" = ${Timestamp}
            "path" = ${Path}
            "size" = ${Size}
        }

        return $PSO
    }
}

<#
.SYNOPSIS

Convert from JSON to DiskSpaceMonitorDescriptorDiskSpace<PSCustomObject>

.DESCRIPTION

Convert from JSON to DiskSpaceMonitorDescriptorDiskSpace<PSCustomObject>

.PARAMETER Json

Json object

.OUTPUTS

DiskSpaceMonitorDescriptorDiskSpace<PSCustomObject>
#>
function ConvertFrom-JsonToDiskSpaceMonitorDescriptorDiskSpace {
    Param(
        [AllowEmptyString()]
        [string]$Json
    )

    Process {
        'Converting JSON to PSCustomObject: PSOpenAPITools => DiskSpaceMonitorDescriptorDiskSpace' | Write-Debug
        $PSBoundParameters | Out-DebugParameter | Write-Debug

        $JsonParameters = ConvertFrom-Json -InputObject $Json

        # check if Json contains properties not defined in DiskSpaceMonitorDescriptorDiskSpace
        $AllProperties = ("_class", "timestamp", "path", "size")
        foreach ($name in $JsonParameters.PsObject.Properties.Name) {
            if (!($AllProperties.Contains($name))) {
                throw "Error! JSON key '$name' not found in the properties: $($AllProperties)"
            }
        }

        if (!([bool]($JsonParameters.PSobject.Properties.name -match "_class"))) { #optional property not found
            $Class = $null
        } else {
            $Class = $JsonParameters.PSobject.Properties["_class"].value
        }

        if (!([bool]($JsonParameters.PSobject.Properties.name -match "timestamp"))) { #optional property not found
            $Timestamp = $null
        } else {
            $Timestamp = $JsonParameters.PSobject.Properties["timestamp"].value
        }

        if (!([bool]($JsonParameters.PSobject.Properties.name -match "path"))) { #optional property not found
            $Path = $null
        } else {
            $Path = $JsonParameters.PSobject.Properties["path"].value
        }

        if (!([bool]($JsonParameters.PSobject.Properties.name -match "size"))) { #optional property not found
            $Size = $null
        } else {
            $Size = $JsonParameters.PSobject.Properties["size"].value
        }

        $PSO = [PSCustomObject]@{
            "_class" = ${Class}
            "timestamp" = ${Timestamp}
            "path" = ${Path}
            "size" = ${Size}
        }

        return $PSO
    }

}


text:
package net.medialabs.functions;

public interface Parser {
	public Route parse();
}


text:
<?php
// Get the PHP helper library from twilio.com/docs/php/install
require_once '/path/to/vendor/autoload.php'; // Loads the library
use Twilio\Rest\Client;

// Your Account Sid and Auth Token from twilio.com/console
$apiKeySid = "SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$apiKeySecret = "your_auth_apiKeySecret";
$client = new Client($apiKeySid, $apiKeySecret);

$room = $client->video->rooms->create([
    'uniqueName' => 'DailyStandup'
]);

echo $room->sid;


text:
/* Global Styles ////////////////////////////////////////////////////////////////////////////// */
html{
	font-size: 16px !important;
}

.slide.safe-area {
    padding-top: env(safe-area-inset-top) !important;
}

.caption {
	font-size: .75rem;
	line-height: 1.25rem;
	opacity: .5;
}
.main-header{
	box-shadow:0 2px 4px rgba(98, 98, 98, 0.3);
	padding: 1rem;
}
h5{
	font-size: 1rem !important;
    font-weight: bold;
}
.list-layout{
    padding: 1rem 0;
    padding-top: 0;
}

#listLayout2::after,
#listLayout2::before {
    border-top: none !important ;
}

.list-item{
	cursor: pointer;
}
.list-item:hover{
	background-color: rgba(150,150,150,.05);
}
.btn-icon,
.btn-icon.glyphicon{
	top: auto;
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 0;
	width: 2.5rem;
	height: 2.5rem;
	border-radius: 50%;
	border: 0;
	background-color: transparent;
	font-size: 1.125rem;
	cursor: pointer;
}
.btn-icon.glyphicon::before{
	position: relative;
	top: 1px;
	left: 1px;
}
.btn-icon:hover{
	background-color: rgba(150,150,150,.05);
}
.load-in{
	transform: scale(.1);
	opacity: 0;
	animation: load-in .2s ease-in .5s forwards;
}
@keyframes load-in {
	0%{
			transform: scale(.1);
	}
	100%{
			transform: scale(1);
			opacity: 1;
	}
}
.bottom.fixed-bottom.primaryBackgroundTheme{
	padding-bottom: env(safe-area-inset-bottom);
}

.word-break{
	word-break: break-word;
}
.item-main-header {
    box-shadow: 0 2px 4px rgb(98 98 98 / 30%);
}
/* End Global Styles ////////////////////////////////////////////////////////////////////////////// */

.audio-player {
    overflow: hidden!important;
    position: fixed;
    width: 100%;
    height: 100%;
}

.holder.now-playing .media-center-plugin {
    position: relative;
    height: 100%;
    padding-bottom: calc(20px + env(safe-area-inset-bottom));
    max-width: 660px;
    margin: 0 auto;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

.media-header-link {
    flex-shrink: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0;
}

.media-header-link .btn.btn-icon {
    margin-left: auto;
}

.btn.btn-icon {
    background-color: transparent;
    border: 0;
    width: 42px;
    height: 42px;
    display: flex;
    align-items: center;
    border-radius: 50%;
    flex-shrink: 0;
    font-size: 20px;
    padding: 0;
}

.holder.now-playing .media-holder, .more-info .media-holder {
    display: table;
    text-align: center;
    width: 220px;
    height: 220px;
    max-width: 220px;
    max-height: 220px;
    margin: 0 auto;
}

.layout3 .titleFlexBox {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.layout3 .titleFlexBox .li-actions-item .star {
  position: relative;
  line-height: 1;
  margin-right: 0;
}

.layout3 .titleFlexBox .li-actions-item .share {
  right: 10px;
  top: 1px;
}

.layout3.list-3 .titleFlexBox .li-actions-item i {
    margin-left: 10px;
}

.layout3.list-3 .titleFlexBox .action {
  margin-left: 15px;
}

.layout3.list-3 .titleFlexBox .li-actions-item {
  display: flex;
}

.layout3.list-3 .list-item-media{
    display: flex;
    align-items: center;
    overflow: hidden;
}
.layout3.list-3 .list-item-media .list-media-holder{
    flex-shrink: 0;
}
.layout3.list-3 .list-item-media .li-actions-item{
    position: relative;
}
.layout3.list-3 .list-item-media .list-media-holder .li-actions-item{
    position: absolute;
}
.layout3.list-3 .li-actions-item .star{
    margin-right: 0;
    padding: .25rem !important;
}
.layout3.list-3 .list-layout .list-item-media .list-media-holder{
    margin: .25rem;
    margin-right: 0;
}

@media (max-height: 600px) {
    .holder.now-playing .media-holder, .holder.now-playing .media-holder .media-inner img {
        max-height: 120px;
        max-width: 120px;
    }
}

.holder.now-playing .media-holder .media-inner, .more-info .media-holder .media-inner {
    max-width: 220px;
    max-height: 220px;
    display: table-cell;
    vertical-align: middle;
}

.holder.now-playing .media-holder .media-inner img {
    max-width: 100%;
    max-height: 100%;
    border-radius: 8px;
    width: 240px;
    height: 240px;
    object-fit: cover;
    box-shadow: 0 0 16px rgba(0,0,0,.5);
}

.btn.btn-icon, .holder.now-playing .media-player-info {
    padding: 24px 0 4px;
    justify-content: center;
}

.media-player-btns {
    padding: 24px 0;
    justify-content: space-between;
}

.holder.now-playing .media-player-info, .media-header-link, .media-player-btns, .slider {
    width: 100%;
    max-width: 600px;
    margin: 0 auto;
}

.holder.now-playing .media-player-info, .media-player-btns {
    flex-shrink: 0;
    display: flex;
    align-items: center;
}

.holder.now-playing .media-player-action-btns span, .holder.now-playing .media-player-btns span, .holder.now-playing .media-player-info span {
    font-size: 18px;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0;
    width: 48px;
    border-radius: 50%;
    height: 48px;
    cursor: pointer;
}

.btn.btn-icon {
    background-color: transparent;
    border: 0;
    width: 42px;
    height: 42px;
    display: flex;
    align-items: center;
    border-radius: 50%;
    flex-shrink: 0;
    font-size: 20px;
    padding: 0;
}

.holder.now-playing .media-player-info .media-title {
    margin: 0 12px;
}

.ellipsis {
    display: block;
}

.slider {
    padding: 0 4px;
}

@media (max-height: 600px) {
.holder.now-playing .media-player-btns .icon.icon-sm {
    top: -5px;
}
}

.holder.now-playing .media-player-btns .icon.icon-sm {
    font-size: 22px;
    position: relative;
    color: #999;
}

@media (max-height: 600px) {
.holder.now-playing .media-player-btns .icon {
    font-size: 32px;
}
}

.holder.now-playing .media-player-btns span {
    transition: none;
}

.holder.now-playing .media-player-btns .player-btns {
    display: flex;
    align-items: center;
}

.audio-plyer input[type=range] {
	-webkit-appearance: none;
	height: 32px;
    width: 100%;
    background: unset;
}

.audio-plyer input[type=range]:focus {
	outline: none;
}

.audio-plyer input[type=range]::-webkit-slider-runnable-track {
	width: 100%;
	height: 3px;
	cursor: pointer;
	animate: 0.2s;
	background: #ffffff;
}

.audio-plyer input[type=range]::-webkit-slider-thumb {
	height: 9px;
	width: 9px;
	background: #ffffff;
	cursor: pointer;
	-webkit-appearance: none;
	margin-top: -2.7px;
	border-radius: 4.5px;
}

.audio-plyer input[type=range]:focus::-webkit-slider-runnable-track {
	/*background: #367ebd;*/
}

.audio-plyer input[type=range]::-moz-range-track {
	width: 100%;
	height: 10px;
	cursor: pointer;
	animate: 0.2s;
	background: #ffffff;
}

.audio-plyer input[type=range]::-moz-range-thumb {
	height: 20px;
	width: 20px;
	background: #ffffff;
	cursor: pointer;
	-webkit-appearance: none;
	margin-top: -5px;
	border-radius: 10px;
}

.audio-plyer input[type=range]::-ms-track {
	width: 100%;
	height: 8.4px;
	cursor: pointer;
	animate: 0.2s;
	background: transparent;
	border-color: transparent;
	border-width: 16px 0;
	color: transparent;
}

.audio-plyer input[type=range]::-ms-fill-lower {
	background: #2a6495;
	border: 0.2px solid #010101;
	border-radius: 2.6px;
	box-shadow: 1px 1px 1px #000000, 0px 0px 1px #0d0d0d;
}

.audio-plyer input[type=range]::-ms-fill-upper {
	background: #3071a9;
	border: 0.2px solid #010101;
	border-radius: 2.6px;
	box-shadow: 1px 1px 1px #000000, 0px 0px 1px #0d0d0d;
}

.audio-plyer input[type=range]::-ms-thumb {
	box-shadow: 1px 1px 1px #000000, 0px 0px 1px #0d0d0d;
	border: 1px solid #000000;
	height: 36px;
	width: 16px;
	border-radius: 3px;
	background: #ffffff;
	cursor: pointer;
}

.audio-plyer input[type=range]:focus::-ms-fill-lower {
	background: #3071a9;
}

.audio-player input[type=range]:focus::-ms-fill-upper {
	background: #367ebd;
}
/* End of audio player style*/
.slider{
	width: 100%;
	max-width: 600px;
	margin: 0 auto;
	padding: 0 4px;
}
.slider .time-indicator span{
	font-size: 12px;
	color: #fff;
	opacity: .7;
	margin: 0 6px;
}

@media (max-height: 600px) {
    .holder.now-playing .media-player-btns .icon.icon-sm {
        top: -5px;
    }
}

.holder.now-playing .media-player-btns .player-btns .btn-primary {
    margin: 0 16px;
}

button.btn-icon.btn-lg {
    width: 64px;
    height: 64px;
    padding: 0;
    box-shadow: 0 4px 16px rgba(0,0,0,.5);
}

.holder.now-playing .media-player-action-btns {
    display: flex;
    justify-content: space-between;
    width: 100%;
    max-width: 600px;
    margin: 0 auto;
}

.holder.now-playing .media-player-action-btns span {
    opacity: .5;
}

.whiteTheme, .whiteTheme:hover, .whiteTheme:focus {
    color: #fff !important;
}

@media (max-height: 600px)
{
    .holder.now-playing .media-holder, .holder.now-playing .media-holder .media-inner img {
        max-height: 120px;
        max-width: 120px;
    }
}

#countdownOverlay {
    height: 0;
    width: 100%;
    position: fixed;
    z-index: 1;
    left: 0;
    bottom: 0;
    background-color: rgba(0,0,0, 0.8);
    overflow-x: hidden;
    transition: 0.2s;
    border-top-left-radius: 8% ;
    border-top-right-radius: 8%;
}

#countdownOverlay  .overlay-content {
    position: relative;
    top: 25%;
    width: 100%;
    text-align: center;
    margin-top: 10px;
    color: white;
}

#countdownOverlay .overlay-content h5,
#countdownOverlay  .overlay-content button  {
    font-size: 18px !important;
    color: white !important;
}

.overlay-content button {
    padding: 10px 15px;
}

#countdownOverlay.h30 {
    height: 30%;
}

#videogularElement .vid-play-pause-btn,
#videogularElement .next-item-btn,
#videogularElement .prev-item-btn,
#videogularElement .volume-btn,
#videogularElement .fullscreen-btn {
    width: 20px;
    padding: 0 0.32rem;
    display: table-cell;
    vertical-align: middle;
    text-align: center;
    cursor: pointer;
}

#videogularElement vg-mute-button {
    width: 32px !important;
}

#videogularElement .iconButton {
    border: none !important;
}

#videogularElement .next-item-btn .iconButton,
#videogularElement .prev-item-btn .iconButton {
    vertical-align: text-top;
}

#videogularElement .next-item-btn .iconButton i,
#videogularElement .prev-item-btn .iconButton i {
    color: white !important;
    top: -1px;
}

#videogularElement vg-volume-bar .verticalVolumeBar {
    position: fixed !important;
}

videogular .iconButton, [videogular] .iconButton,
#videogularElement .next-item-btn .iconButton {
    padding: 6px 4px !important;
}

#videogularElement .next-item-btn .iconButton {
    margin-right: 0.8rem;
}

#videogularElement .iconButton i {
    font-size: 13px;
    top: -1px;
}

#videogularElement > vg-controls > div > vg-scrub-bar {
    width: 100%;
}

#videogularElement .vid-time {
    font-size: 15px;
    width: 55px;
    padding-left: 1.2rem;
    padding-right: 0.3rem;
}

/* .layout2 .people-holder {
    display: flex;
}

.layout2 .people-media img {
    flex-shrink: 0;
    width: 35%;
    padding: .75rem;
}

.layout2 .people-info p {
    font-size: .875rem;
    text-align: left;
} */

.now-playing-backgroundImage {
    -o-filter: blur(10px) brightness(0.4);
    -moz-filter: blur(10px) brightness(0.4);
    -webkit-filter: blur(10px) brightness(0.4);
    filter: blur(10px) brightness(0.4);
    position: absolute;
    top: -5%;
    left: -5%;
    -o-background-size: cover;
    -moz-background-size: cover;
    -webkit-background-size: cover;
    background-size: cover !important;
    height: 110%;
    width: 110%;
    z-index: 0;
}

.glyphicon-option-horizontal {
    padding: 7px 10px !important;
}

.blured-image {
    filter: blur(5px);
    z-index: -1;
    width: 100% !important;
    position: absolute;
    top: 0;
    left: 0;
}

.plugin_blured_image span img {
    width: 100% !important;
}


text:
<?php

namespace Smartbox\Integration\FrameworkBundle\Tests\Unit\Core\Messages;

use Smartbox\CoreBundle\Type\SerializableArray;
use Smartbox\Integration\FrameworkBundle\Core\Exchange;
use Smartbox\Integration\FrameworkBundle\Core\Messages\Context;
use Smartbox\Integration\FrameworkBundle\Core\Messages\Message;
use Smartbox\Integration\FrameworkBundle\Core\Messages\MessageInterface;
use Smartbox\Integration\FrameworkBundle\Core\Messages\RetryExchangeEnvelope;

class RetryExchangeEnvelopeTest extends \PHPUnit\Framework\TestCase
{
    /** @var RetryExchangeEnvelope */
    private $retryExchangeEnvelope;

    protected function setUp()
    {
        /** @var Context|\PHPUnit_Framework_MockObject_MockObject $context */
        $context = $this->createMock(Context::class);

        /** @var MessageInterface|\PHPUnit_Framework_MockObject_MockObject $message */
        $message = $this->createMock(MessageInterface::class);
        $message
            ->expects($this->once())
            ->method('getContext')
            ->will($this->returnValue($context));

        $exchange = new Exchange($message);

        $this->retryExchangeEnvelope = new RetryExchangeEnvelope($exchange);
    }

    protected function tearDown()
    {
        $this->retryExchangeEnvelope = null;
    }

    public function testConstruct()
    {
        $context = new Context();
        $message = new Message(null, [], $context);
        $exchange = new Exchange($message);
        $processingContext = new SerializableArray(['a' => 'b']);

        $retryExchangeEnvelope = new RetryExchangeEnvelope($exchange, $processingContext, 5);

        $this->assertSame($exchange, $retryExchangeEnvelope->getExchange());
        $this->assertSame($processingContext, $retryExchangeEnvelope->getProcessingContext());
        $this->assertSame(5, $retryExchangeEnvelope->getRetries());
    }

    public function testSetAndGetRetries()
    {
        $this->retryExchangeEnvelope->setRetries(3);

        $this->assertSame(3, $this->retryExchangeEnvelope->getRetries());
    }

    public function invalidRetryValuesProvider()
    {
        return [
            'Retry is not an integer' => ['retries' => '-1'],
            'Retry is a negative integer' => ['retries' => -1],
        ];
    }

    /**
     * @dataProvider invalidRetryValuesProvider
     *
     * @param $retries
     */
    public function testSetRetriesWhenParamIsNotAnInteger($retries)
    {
        $this->expectException(\InvalidArgumentException::class);

        $this->retryExchangeEnvelope->setRetries($retries);
    }
}