text:
package org.apache.camel.component.mllp.internal;

import java.io.ByteArrayOutputStream;

import org.apache.camel.component.mllp.MllpProtocolConstants;

import org.apache.camel.processor.mllp.Hl7AcknowledgementGenerationException;
import org.apache.camel.test.stub.camel.MllpEndpointStub;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;

public class Hl7UtilTest {
    // @formatter:off
    static final String TEST_MESSAGE =
        "MSH|^~\\&|ADT|EPIC|JCAPS|CC|20161206193919|RISTECH|ADT^A08|00001|D|2.3^^|||||||" + '\r'
            + "EVN|A08|20150107161440||REG_UPDATE_SEND_VISIT_MESSAGES_ON_PATIENT_CHANGES|RISTECH^RADIOLOGY^TECHNOLOGIST^^^^^^UCLA^^^^^RRMC||" + '\r'
            + "PID|1|2100355^^^MRN^MRN|2100355^^^MRN^MRN||MDCLS9^MC9||19700109|F||U|111 HOVER STREET^^LOS ANGELES^CA^90032^USA^P^^LOS ANGELE|"
            + "LOS ANGELE|(310)725-6952^P^PH^^^310^7256952||ENGLISH|U||60000013647|565-33-2222|||U||||||||N||" + '\r'
            + "PD1|||UCLA HEALTH SYSTEM^^10|10002116^ADAMS^JOHN^D^^^^^EPIC^^^^PROVID||||||||||||||" + '\r'
            + "NK1|1|DOE^MC9^^|OTH|^^^^^USA|(310)888-9999^^^^^310^8889999|(310)999-2222^^^^^310^9992222|Emergency Contact 1|||||||||||||||||||||||||||" + '\r'
            + "PV1|1|OUTPATIENT|RR CT^^^1000^^^^^^^DEPID|EL|||017511^TOBIAS^JONATHAN^^^^^^EPIC^^^^PROVID|017511^TOBIAS^JONATHAN^^^^^^EPIC^^^^PROVID||||||"
            + "CLR|||||60000013647|SELF|||||||||||||||||||||HOV_CONF|^^^1000^^^^^^^||20150107161438||||||||||" + '\r'
            + "PV2||||||||20150107161438||||CT BRAIN W WO CONTRAST||||||||||N|||||||||||||||||||||||||||" + '\r'
            + "ZPV||||||||||||20150107161438|||||||||" + '\r'
            + "AL1|1||33361^NO KNOWN ALLERGIES^^NOTCOMPUTRITION^NO KNOWN ALLERGIES^EXTELG||||||" + '\r'
            + "DG1|1|DX|784.0^Headache^DX|Headache||VISIT" + '\r'
            + "GT1|1|1000235129|MDCLS9^MC9^^||111 HOVER STREET^^LOS ANGELES^CA^90032^USA^^^LOS ANGELE|(310)725-6952^^^^^310^7256952||19700109|F|P/F|SLF|"
            + "565-33-2222|||||^^^^^USA|||UNKNOWN|||||||||||||||||||||||||||||" + '\r'
            + "UB2||||||||" + '\r';

    static final String EXPTECTED_ACKNOWLEDGEMENT_PAYLOAD =
        MllpProtocolConstants.START_OF_BLOCK
            + "MSH|^~\\&|JCAPS|CC|ADT|EPIC|20161206193919|RISTECH|ACK^A08|00001|D|2.3^^|||||||\r"
            + "MSA|AA|00001\r"
            + MllpProtocolConstants.END_OF_BLOCK + MllpProtocolConstants.END_OF_DATA;

    static final String EXPECTED_MESSAGE =
        "MSH|^~\\&|ADT|EPIC|JCAPS|CC|20161206193919|RISTECH|ADT^A08|00001|D|2.3^^|||||||" + "<0x0D CR>"
            + "EVN|A08|20150107161440||REG_UPDATE_SEND_VISIT_MESSAGES_ON_PATIENT_CHANGES|RISTECH^RADIOLOGY^TECHNOLOGIST^^^^^^UCLA^^^^^RRMC||" + "<0x0D CR>"
            + "PID|1|2100355^^^MRN^MRN|2100355^^^MRN^MRN||MDCLS9^MC9||19700109|F||U|111 HOVER STREET^^LOS ANGELES^CA^90032^USA^P^^LOS ANGELE|LOS ANGELE|(310)725-6952^P^PH^^^310^7256952"
            +     "||ENGLISH|U||60000013647|565-33-2222|||U||||||||N||" + "<0x0D CR>"
            + "PD1|||UCLA HEALTH SYSTEM^^10|10002116^ADAMS^JOHN^D^^^^^EPIC^^^^PROVID||||||||||||||" + "<0x0D CR>"
            + "NK1|1|DOE^MC9^^|OTH|^^^^^USA|(310)888-9999^^^^^310^8889999|(310)999-2222^^^^^310^9992222|Emergency Contact 1|||||||||||||||||||||||||||" + "<0x0D CR>"
            + "PV1|1|OUTPATIENT|RR CT^^^1000^^^^^^^DEPID|EL|||017511^TOBIAS^JONATHAN^^^^^^EPIC^^^^PROVID|017511^TOBIAS^JONATHAN^^^^^^EPIC^^^^PROVID||||||CLR|||||60000013647|SELF"
            +     "|||||||||||||||||||||HOV_CONF|^^^1000^^^^^^^||20150107161438||||||||||" + "<0x0D CR>"
            + "PV2||||||||20150107161438||||CT BRAIN W WO CONTRAST||||||||||N|||||||||||||||||||||||||||" + "<0x0D CR>"
            + "ZPV||||||||||||20150107161438|||||||||" + "<0x0D CR>"
            + "AL1|1||33361^NO KNOWN ALLERGIES^^NOTCOMPUTRITION^NO KNOWN ALLERGIES^EXTELG||||||" + "<0x0D CR>"
            + "DG1|1|DX|784.0^Headache^DX|Headache||VISIT" + "<0x0D CR>"
            + "GT1|1|1000235129|MDCLS9^MC9^^||111 HOVER STREET^^LOS ANGELES^CA^90032^USA^^^LOS ANGELE|(310)725-6952^^^^^310^7256952||19700109|F|P/F|SLF|565-33-2222|||||^^^^^USA|||UNKNOWN"
            +     "|||||||||||||||||||||||||||||" + "<0x0D CR>"
            + "UB2||||||||" + "<0x0D CR>";
    // @formatter:on

    static final String MSH_SEGMENT = "MSH|^~\\&|0|90100053675|JCAPS|CC|20131125122938|RISMD|ORM|28785|D|2.3";

    // @formatter:off
    static final String REMAINING_SEGMENTS =
        "PID|1||4507626^^^MRN^MRN||RAD VALIDATE^ROBERT||19650916|M||U|1818 UNIVERSITY AVE^^MADISON^WI^53703^USA^^^||(608)251-9999|||M|||579-85-3510||| " + '\r'
            + "PV1||OUTPATIENT|NMPCT^^^WWNMD^^^^^^^DEPID||||011463^ZARAGOZA^EDWARD^J.^^^^^EPIC^^^^PROVID|011463^ZARAGOZA^EDWARD^J.^^^^^EPIC^^^^PROVID"
            +     "|||||||||||90100053686|SELF||||||||||||||||||||||||201311251218|||||||V" + '\r'
            + "ORC|RE|9007395^EPC|9007395^EPC||Final||^^^201311251221^201311251222^R||201311251229|RISMD^RADIOLOGY^RADIOLOGIST^^|||SMO PET^^^7044^^^^^SMO PET CT||||||||||||||||I" + '\r'
            + "OBR|1|9007395^EPC|9007395^EPC|IMG7118^PET CT LIMITED CHEST W CONTRAST^IMGPROC^^PET CT CHEST||20131125|||||Ancillary Pe|||||||NMPCT|MP2 NM INJ01^MP2 NM INJECTION ROOM 01^PROVID"
            +     "|||201311251229||NM|Final||^^^201311251221^201311251222^R||||^test|E200003^RADIOLOGY^RESIDENT^^^^^^EPIC^^^^PROVID"
            +     "|812644^RADIOLOGY^GENERIC^ATTENDING 1^^^^^EPIC^^^^PROVID~000043^RADIOLOGY^RADIOLOGISTTWO^^^^^^EPIC^^^^PROVID|U0058489^SWAIN^CYNTHIA^LEE^||201311251245" + '\r'
            + "OBX|1|ST|&GDT|1|[11/25/2013 12:28:14 PM - PHYS, FIFTYFOUR]50||||||Final||||" + '\r';
    // @formatter:on

    static final byte[] TEST_MESSAGE_BYTES = TEST_MESSAGE.getBytes();
    @Test
    public void testGenerateInvalidPayloadExceptionMessage() throws Exception {
        String message = Hl7Util.generateInvalidPayloadExceptionMessage(TEST_MESSAGE.getBytes());

        assertNull("Valid payload should result in a null message", message);
    }

    @Test
    public void testGenerateInvalidPayloadExceptionMessageWithLengthLargerThanArraySize() throws Exception {
        byte[] payload = TEST_MESSAGE.getBytes();
        String message = Hl7Util.generateInvalidPayloadExceptionMessage(payload, payload.length * 2);

        assertNull("Valid payload should result in a null message", message);
    }

    @Test
    public void testGenerateInvalidPayloadExceptionMessageWithLengthSmallerThanArraySize() throws Exception {
        byte[] payload = TEST_MESSAGE.getBytes();
        String message = Hl7Util.generateInvalidPayloadExceptionMessage(payload, 10);

        assertEquals("The HL7 payload terminating byte [0x7c] is incorrect - expected [0xd]  {ASCII [<CR>]}", message);
    }

    @Test
    public void testGenerateInvalidPayloadExceptionMessageWithNullPayload() throws Exception {
        assertEquals("HL7 payload is null", Hl7Util.generateInvalidPayloadExceptionMessage(null));

        assertEquals("HL7 payload is null", Hl7Util.generateInvalidPayloadExceptionMessage(null, 1234));
    }

    @Test
    public void testGenerateInvalidPayloadExceptionMessageWithInvalidStartingSegment() throws Exception {
        byte[] invalidStartingSegment = "MSA|AA|00001|\r".getBytes();
        byte[] basePayload = TEST_MESSAGE.getBytes();

        ByteArrayOutputStream payloadStream = new ByteArrayOutputStream(invalidStartingSegment.length + basePayload.length);
        payloadStream.write(invalidStartingSegment);
        payloadStream.write(basePayload.length);

        assertEquals("The first segment of the HL7 payload {MSA} is not an MSH segment", Hl7Util.generateInvalidPayloadExceptionMessage(payloadStream.toByteArray()));
    }

    @Test
    public void testGenerateInvalidPayloadExceptionMessageWithEmptyPayload() throws Exception {
        byte[] payload = new byte[0];

        assertEquals("HL7 payload is empty", Hl7Util.generateInvalidPayloadExceptionMessage(payload));
        assertEquals("HL7 payload is empty", Hl7Util.generateInvalidPayloadExceptionMessage(payload, payload.length));
    }

    @Test
    public void testGenerateInvalidPayloadExceptionMessageWithEmbeddedStartOfBlock() throws Exception {
        byte[] basePayload = TEST_MESSAGE.getBytes();

        ByteArrayOutputStream payloadStream = new ByteArrayOutputStream(basePayload.length + 1);

        int embeddedStartOfBlockIndex = basePayload.length / 2;
        payloadStream.write(basePayload, 0, embeddedStartOfBlockIndex);
        payloadStream.write(MllpProtocolConstants.START_OF_BLOCK);
        payloadStream.write(basePayload, embeddedStartOfBlockIndex, basePayload.length - embeddedStartOfBlockIndex);

        String expected = "HL7 payload contains an embedded START_OF_BLOCK {0xb, ASCII <VT>} at index " + embeddedStartOfBlockIndex;

        assertEquals(expected, Hl7Util.generateInvalidPayloadExceptionMessage(payloadStream.toByteArray()));
    }

    @Test
    public void testGenerateInvalidPayloadExceptionMessageWithEmbeddedEndOfBlock() throws Exception {
        byte[] basePayload = TEST_MESSAGE.getBytes();

        ByteArrayOutputStream payloadStream = new ByteArrayOutputStream(basePayload.length + 1);

        int embeddedEndOfBlockIndex = basePayload.length / 2;
        payloadStream.write(basePayload, 0, embeddedEndOfBlockIndex);
        payloadStream.write(MllpProtocolConstants.END_OF_BLOCK);
        payloadStream.write(basePayload, embeddedEndOfBlockIndex, basePayload.length - embeddedEndOfBlockIndex);

        String expected = "HL7 payload contains an embedded END_OF_BLOCK {0x1c, ASCII <FS>} at index " + embeddedEndOfBlockIndex;

        assertEquals(expected, Hl7Util.generateInvalidPayloadExceptionMessage(payloadStream.toByteArray()));
    }

    /**
     * Description of test.
     *
     * @throws Exception in the event of a test error.
     */
    @Test
    public void testGenerateAcknowledgementPayload() throws Exception {
        MllpSocketBuffer mllpSocketBuffer = new MllpSocketBuffer(new MllpEndpointStub());
        Hl7Util.generateAcknowledgementPayload(mllpSocketBuffer, TEST_MESSAGE.getBytes(), "AA");

        assertEquals(EXPTECTED_ACKNOWLEDGEMENT_PAYLOAD, mllpSocketBuffer.toString());
    }

    /**
     * Description of test.
     *
     * @throws Exception in the event of a test error.
     */
    @Test(expected = Hl7AcknowledgementGenerationException.class)
    public void testGenerateAcknowledgementPayloadFromNullMessage() throws Exception {
        MllpSocketBuffer mllpSocketBuffer = new MllpSocketBuffer(new MllpEndpointStub());
        Hl7Util.generateAcknowledgementPayload(mllpSocketBuffer, null, "AA");

        assertEquals(EXPTECTED_ACKNOWLEDGEMENT_PAYLOAD, mllpSocketBuffer.toString());
    }

    /**
     * Description of test.
     *
     * @throws Exception in the event of a test error.
     */
    @Test(expected = Hl7AcknowledgementGenerationException.class)
    public void testGenerateAcknowledgementPayloadFromEmptyMessage() throws Exception {
        MllpSocketBuffer mllpSocketBuffer = new MllpSocketBuffer(new MllpEndpointStub());
        Hl7Util.generateAcknowledgementPayload(mllpSocketBuffer, new byte[0], "AA");

        assertEquals(EXPTECTED_ACKNOWLEDGEMENT_PAYLOAD, mllpSocketBuffer.toString());
    }

    /**
     * Description of test.
     *
     * @throws Exception in the event of a test error.
     */
    @Test
    public void testGenerateAcknowledgementPayloadWithoutEnoughFields() throws Exception {
        MllpSocketBuffer mllpSocketBuffer = new MllpSocketBuffer(new MllpEndpointStub());
        Hl7Util.generateAcknowledgementPayload(mllpSocketBuffer, TEST_MESSAGE.replaceFirst("|RISTECH|ADT^A08|00001|D|2.3^^|||||||", "").getBytes(), "AA");

        assertEquals(EXPTECTED_ACKNOWLEDGEMENT_PAYLOAD, mllpSocketBuffer.toString());
    }

    /**
     * If the MSH isn't terminated correctly, we'll get Junk for the acknowledgement.
     *
     * @throws Exception in the event of a test error.
     */
    @Test
    public void testGenerateAcknowledgementPayloadWithoutEndOfSegment() throws Exception {
        String junkMessage = "MSH|^~\\&|ADT|EPIC|JCAPS|CC|20161206193919|RISTECH|ADT^A08|00001|D|2.3^^|||||||"
            + "EVN|A08|20150107161440||REG_UPDATE_SEND_VISIT_MESSAGES_ON_PATIENT_CHANGES|RISTECH^RADIOLOGY^TECHNOLOGIST^^^^^^UCLA^^^^^RRMC||";

        String junkAcknowledgement =
            MllpProtocolConstants.START_OF_BLOCK
                + "MSH|^~\\&|JCAPS|CC|ADT|EPIC|20161206193919|RISTECH|ACK^A08|00001|D|2.3^^|||||||"
                + "EVN|A08|20150107161440||REG_UPDATE_SEND_VISIT_MESSAGES_ON_PATIENT_CHANGES|RISTECH^RADIOLOGY^TECHNOLOGIST^^^^^^UCLA^^^^^RRMC|\r"
                + "MSA|AA|00001\r"
                + MllpProtocolConstants.END_OF_BLOCK + MllpProtocolConstants.END_OF_DATA;

        MllpSocketBuffer mllpSocketBuffer = new MllpSocketBuffer(new MllpEndpointStub());
        Hl7Util.generateAcknowledgementPayload(mllpSocketBuffer, junkMessage.getBytes(), "AA");

        assertEquals(junkAcknowledgement, mllpSocketBuffer.toString());
    }

    /**
     * Description of test.
     *
     * @throws Exception in the event of a test error.
     */
    @Test
    public void testConvertStringToPrintFriendlyString() throws Exception {
        assertEquals(Hl7Util.NULL_REPLACEMENT_VALUE, Hl7Util.convertToPrintFriendlyString((String) null));
        assertEquals(Hl7Util.EMPTY_REPLACEMENT_VALUE, Hl7Util.convertToPrintFriendlyString(""));
        assertEquals(EXPECTED_MESSAGE, Hl7Util.convertToPrintFriendlyString(TEST_MESSAGE));
    }

    /**
     * Description of test.
     *
     * @throws Exception in the event of a test error.
     */
    @Test
    public void testConvertBytesToPrintFriendlyString() throws Exception {
        assertEquals(Hl7Util.NULL_REPLACEMENT_VALUE, Hl7Util.convertToPrintFriendlyString((byte[]) null));
        assertEquals(Hl7Util.EMPTY_REPLACEMENT_VALUE, Hl7Util.convertToPrintFriendlyString(new byte[0]));
        assertEquals(EXPECTED_MESSAGE, Hl7Util.convertToPrintFriendlyString(TEST_MESSAGE_BYTES));
    }

    /**
     * Description of test.
     *
     * @throws Exception in the event of a test error.
     */
    @Test
    public void testConvertBytesToPrintFriendlyStringWithStartAndEndPositions() throws Exception {
        assertEquals(Hl7Util.NULL_REPLACEMENT_VALUE, Hl7Util.convertToPrintFriendlyString((byte[]) null, 0, 1000));
        assertEquals(Hl7Util.NULL_REPLACEMENT_VALUE, Hl7Util.convertToPrintFriendlyString((byte[]) null, 200, 1000));
        assertEquals(Hl7Util.NULL_REPLACEMENT_VALUE, Hl7Util.convertToPrintFriendlyString((byte[]) null, -200, 1000));

        assertEquals(Hl7Util.NULL_REPLACEMENT_VALUE, Hl7Util.convertToPrintFriendlyString((byte[]) null, 0, 0));
        assertEquals(Hl7Util.NULL_REPLACEMENT_VALUE, Hl7Util.convertToPrintFriendlyString((byte[]) null, 200, 0));
        assertEquals(Hl7Util.NULL_REPLACEMENT_VALUE, Hl7Util.convertToPrintFriendlyString((byte[]) null, -200, 0));

        assertEquals(Hl7Util.NULL_REPLACEMENT_VALUE, Hl7Util.convertToPrintFriendlyString((byte[]) null, 0, -1000));
        assertEquals(Hl7Util.NULL_REPLACEMENT_VALUE, Hl7Util.convertToPrintFriendlyString((byte[]) null, 200, -1000));
        assertEquals(Hl7Util.NULL_REPLACEMENT_VALUE, Hl7Util.convertToPrintFriendlyString((byte[]) null, -200, -1000));

        assertEquals(Hl7Util.EMPTY_REPLACEMENT_VALUE, Hl7Util.convertToPrintFriendlyString(new byte[0], 0, 1000));
        assertEquals(Hl7Util.EMPTY_REPLACEMENT_VALUE, Hl7Util.convertToPrintFriendlyString(new byte[0], 200, 1000));
        assertEquals(Hl7Util.EMPTY_REPLACEMENT_VALUE, Hl7Util.convertToPrintFriendlyString(new byte[0], -200, 1000));

        assertEquals(Hl7Util.EMPTY_REPLACEMENT_VALUE, Hl7Util.convertToPrintFriendlyString(new byte[0], 0, 0));
        assertEquals(Hl7Util.EMPTY_REPLACEMENT_VALUE, Hl7Util.convertToPrintFriendlyString(new byte[0], 200, 0));
        assertEquals(Hl7Util.EMPTY_REPLACEMENT_VALUE, Hl7Util.convertToPrintFriendlyString(new byte[0], -200, 0));

        assertEquals(Hl7Util.EMPTY_REPLACEMENT_VALUE, Hl7Util.convertToPrintFriendlyString(new byte[0], 0, -1000));
        assertEquals(Hl7Util.EMPTY_REPLACEMENT_VALUE, Hl7Util.convertToPrintFriendlyString(new byte[0], 200, -1000));
        assertEquals(Hl7Util.EMPTY_REPLACEMENT_VALUE, Hl7Util.convertToPrintFriendlyString(new byte[0], -200, -1000));

        assertEquals(EXPECTED_MESSAGE, Hl7Util.convertToPrintFriendlyString(TEST_MESSAGE_BYTES, 0, TEST_MESSAGE_BYTES.length));
        assertEquals("", Hl7Util.convertToPrintFriendlyString(TEST_MESSAGE_BYTES, 0, 0));

        assertEquals(EXPECTED_MESSAGE, Hl7Util.convertToPrintFriendlyString(TEST_MESSAGE_BYTES, -14, TEST_MESSAGE_BYTES.length));

        assertEquals("", Hl7Util.convertToPrintFriendlyString(TEST_MESSAGE_BYTES, -14, 0));
        assertEquals("", Hl7Util.convertToPrintFriendlyString(TEST_MESSAGE_BYTES, -14, -14));
        assertEquals(EXPECTED_MESSAGE, Hl7Util.convertToPrintFriendlyString(TEST_MESSAGE_BYTES, -14, 1000000));

        assertEquals("", Hl7Util.convertToPrintFriendlyString(TEST_MESSAGE_BYTES, 0, -14));
        assertEquals(EXPECTED_MESSAGE, Hl7Util.convertToPrintFriendlyString(TEST_MESSAGE_BYTES, 0, 1000000));

        assertEquals("", Hl7Util.convertToPrintFriendlyString(TEST_MESSAGE_BYTES, 1000000, TEST_MESSAGE_BYTES.length));
        assertEquals("", Hl7Util.convertToPrintFriendlyString(TEST_MESSAGE_BYTES, 1000000, 0));
        assertEquals("", Hl7Util.convertToPrintFriendlyString(TEST_MESSAGE_BYTES, 1000000, -14));
        assertEquals("", Hl7Util.convertToPrintFriendlyString(TEST_MESSAGE_BYTES, 1000000, 1000000));

        assertEquals("", Hl7Util.convertToPrintFriendlyString(TEST_MESSAGE_BYTES, 50, 50));
    }

    /**
     * Description of test.
     *
     * @throws Exception in the event of a test error.
     */
    @Test
    public void testBytesToPrintFriendlyStringBuilder() throws Exception {
        assertEquals(Hl7Util.NULL_REPLACEMENT_VALUE, Hl7Util.bytesToPrintFriendlyStringBuilder((byte[]) null).toString());
        assertEquals(Hl7Util.EMPTY_REPLACEMENT_VALUE, Hl7Util.bytesToPrintFriendlyStringBuilder(new byte[0]).toString());
        assertEquals(EXPECTED_MESSAGE, Hl7Util.bytesToPrintFriendlyStringBuilder(TEST_MESSAGE_BYTES).toString());
    }

    /**
     * Description of test.
     *
     * @throws Exception in the event of a test error.
     */
    @Test
    public void testBytesToPrintFriendlyStringBuilderWithStartAndEndPositions() throws Exception {
        assertEquals(Hl7Util.NULL_REPLACEMENT_VALUE, Hl7Util.bytesToPrintFriendlyStringBuilder((byte[]) null, 0, 1000).toString());
        assertEquals(Hl7Util.NULL_REPLACEMENT_VALUE, Hl7Util.bytesToPrintFriendlyStringBuilder((byte[]) null, 200, 1000).toString());
        assertEquals(Hl7Util.NULL_REPLACEMENT_VALUE, Hl7Util.bytesToPrintFriendlyStringBuilder((byte[]) null, -200, 1000).toString());

        assertEquals(Hl7Util.NULL_REPLACEMENT_VALUE, Hl7Util.bytesToPrintFriendlyStringBuilder((byte[]) null, 0, 0).toString());
        assertEquals(Hl7Util.NULL_REPLACEMENT_VALUE, Hl7Util.bytesToPrintFriendlyStringBuilder((byte[]) null, 200, 0).toString());
        assertEquals(Hl7Util.NULL_REPLACEMENT_VALUE, Hl7Util.bytesToPrintFriendlyStringBuilder((byte[]) null, -200, 0).toString());

        assertEquals(Hl7Util.NULL_REPLACEMENT_VALUE, Hl7Util.bytesToPrintFriendlyStringBuilder((byte[]) null, 0, -1000).toString());
        assertEquals(Hl7Util.NULL_REPLACEMENT_VALUE, Hl7Util.bytesToPrintFriendlyStringBuilder((byte[]) null, 200, -1000).toString());
        assertEquals(Hl7Util.NULL_REPLACEMENT_VALUE, Hl7Util.bytesToPrintFriendlyStringBuilder((byte[]) null, -200, -1000).toString());

        assertEquals(Hl7Util.EMPTY_REPLACEMENT_VALUE, Hl7Util.bytesToPrintFriendlyStringBuilder(new byte[0], 0, 1000).toString());
        assertEquals(Hl7Util.EMPTY_REPLACEMENT_VALUE, Hl7Util.bytesToPrintFriendlyStringBuilder(new byte[0], 200, 1000).toString());
        assertEquals(Hl7Util.EMPTY_REPLACEMENT_VALUE, Hl7Util.bytesToPrintFriendlyStringBuilder(new byte[0], -200, 1000).toString());

        assertEquals(Hl7Util.EMPTY_REPLACEMENT_VALUE, Hl7Util.bytesToPrintFriendlyStringBuilder(new byte[0], 0, 0).toString());
        assertEquals(Hl7Util.EMPTY_REPLACEMENT_VALUE, Hl7Util.bytesToPrintFriendlyStringBuilder(new byte[0], 200, 0).toString());
        assertEquals(Hl7Util.EMPTY_REPLACEMENT_VALUE, Hl7Util.bytesToPrintFriendlyStringBuilder(new byte[0], -200, 0).toString());

        assertEquals(Hl7Util.EMPTY_REPLACEMENT_VALUE, Hl7Util.bytesToPrintFriendlyStringBuilder(new byte[0], 0, -1000).toString());
        assertEquals(Hl7Util.EMPTY_REPLACEMENT_VALUE, Hl7Util.bytesToPrintFriendlyStringBuilder(new byte[0], 200, -1000).toString());
        assertEquals(Hl7Util.EMPTY_REPLACEMENT_VALUE, Hl7Util.bytesToPrintFriendlyStringBuilder(new byte[0], -200, -1000).toString());

        assertEquals(EXPECTED_MESSAGE, Hl7Util.bytesToPrintFriendlyStringBuilder(TEST_MESSAGE_BYTES, 0, TEST_MESSAGE_BYTES.length).toString());
        assertEquals("", Hl7Util.bytesToPrintFriendlyStringBuilder(TEST_MESSAGE_BYTES, 0, 0).toString());

        assertEquals(EXPECTED_MESSAGE, Hl7Util.bytesToPrintFriendlyStringBuilder(TEST_MESSAGE_BYTES, -14, TEST_MESSAGE_BYTES.length).toString());

        assertEquals("", Hl7Util.bytesToPrintFriendlyStringBuilder(TEST_MESSAGE_BYTES, -14, 0).toString());
        assertEquals("", Hl7Util.bytesToPrintFriendlyStringBuilder(TEST_MESSAGE_BYTES, -14, -14).toString());
        assertEquals(EXPECTED_MESSAGE, Hl7Util.bytesToPrintFriendlyStringBuilder(TEST_MESSAGE_BYTES, -14, 1000000).toString());

        assertEquals("", Hl7Util.bytesToPrintFriendlyStringBuilder(TEST_MESSAGE_BYTES, 0, -14).toString());
        assertEquals(EXPECTED_MESSAGE, Hl7Util.bytesToPrintFriendlyStringBuilder(TEST_MESSAGE_BYTES, 0, 1000000).toString());

        assertEquals("", Hl7Util.bytesToPrintFriendlyStringBuilder(TEST_MESSAGE_BYTES, 1000000, TEST_MESSAGE_BYTES.length).toString());
        assertEquals("", Hl7Util.bytesToPrintFriendlyStringBuilder(TEST_MESSAGE_BYTES, 1000000, 0).toString());
        assertEquals("", Hl7Util.bytesToPrintFriendlyStringBuilder(TEST_MESSAGE_BYTES, 1000000, -14).toString());
        assertEquals("", Hl7Util.bytesToPrintFriendlyStringBuilder(TEST_MESSAGE_BYTES, 1000000, 1000000).toString());

        assertEquals("ADT^A08|00001|D|2.3^^|||||||<0x0D CR>EVN|A08|2015010716144", Hl7Util.bytesToPrintFriendlyStringBuilder(TEST_MESSAGE_BYTES, 50, 100).toString());
    }

    /**
     * Description of test.
     *
     * @throws Exception in the event of a test error.
     */
    @Test
    public void testAppendBytesAsPrintFriendlyString() throws Exception {
        StringBuilder builder = null;

        try {
            Hl7Util.appendBytesAsPrintFriendlyString(builder, null);
            fail("Exception should be raised with null StringBuilder argument");
        } catch (IllegalArgumentException ignoredEx) {
            // Eat this
        }

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, (byte[]) null);
        assertEquals(Hl7Util.NULL_REPLACEMENT_VALUE, builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, new byte[0]);
        assertEquals(Hl7Util.EMPTY_REPLACEMENT_VALUE, builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, TEST_MESSAGE_BYTES);
        assertEquals(EXPECTED_MESSAGE, builder.toString());
    }

    /**
     * Description of test.
     *
     * @throws Exception in the event of a test error.
     */
    @Test
    public void testAppendBytesAsPrintFriendlyStringWithStartAndEndPositions() throws Exception {
        StringBuilder builder = null;

        try {
            Hl7Util.appendBytesAsPrintFriendlyString(builder, null);
            fail("Exception should be raised with null StringBuilder argument");
        } catch (IllegalArgumentException ignoredEx) {
            // Eat this
        }

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, null, 0, 1000);
        assertEquals(Hl7Util.NULL_REPLACEMENT_VALUE, builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, null, 200, 1000);
        assertEquals(Hl7Util.NULL_REPLACEMENT_VALUE, builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, null, -200, 1000);
        assertEquals(Hl7Util.NULL_REPLACEMENT_VALUE, builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, null, 0, 0);
        assertEquals(Hl7Util.NULL_REPLACEMENT_VALUE, builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, null, 200, 0);
        assertEquals(Hl7Util.NULL_REPLACEMENT_VALUE, builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, null, -200, 0);
        assertEquals(Hl7Util.NULL_REPLACEMENT_VALUE, builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, null, 0, -1000);
        assertEquals(Hl7Util.NULL_REPLACEMENT_VALUE, builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, null, 200, -1000);
        assertEquals(Hl7Util.NULL_REPLACEMENT_VALUE, builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, null, -200, -1000);
        assertEquals(Hl7Util.NULL_REPLACEMENT_VALUE, builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, new byte[0], 0, 1000);
        assertEquals(Hl7Util.EMPTY_REPLACEMENT_VALUE, builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, new byte[0], 200, 1000);
        assertEquals(Hl7Util.EMPTY_REPLACEMENT_VALUE, builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, new byte[0], -200, 1000);
        assertEquals(Hl7Util.EMPTY_REPLACEMENT_VALUE, builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, new byte[0], 0, 0);
        assertEquals(Hl7Util.EMPTY_REPLACEMENT_VALUE, builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, new byte[0], 200, 0);
        assertEquals(Hl7Util.EMPTY_REPLACEMENT_VALUE, builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, new byte[0], -200, 0);
        assertEquals(Hl7Util.EMPTY_REPLACEMENT_VALUE, builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, new byte[0], 0, -1000);
        assertEquals(Hl7Util.EMPTY_REPLACEMENT_VALUE, builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, new byte[0], 200, -1000);
        assertEquals(Hl7Util.EMPTY_REPLACEMENT_VALUE, builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, new byte[0], -200, -1000);
        assertEquals(Hl7Util.EMPTY_REPLACEMENT_VALUE, builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, TEST_MESSAGE_BYTES, 0, TEST_MESSAGE_BYTES.length);
        assertEquals(EXPECTED_MESSAGE, builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, TEST_MESSAGE_BYTES, 0, 0);
        assertEquals("", builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, TEST_MESSAGE_BYTES, -14, TEST_MESSAGE_BYTES.length);
        assertEquals(EXPECTED_MESSAGE, builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, TEST_MESSAGE_BYTES, -14, 0);
        assertEquals("", builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, TEST_MESSAGE_BYTES, -14, -14);
        assertEquals("", builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, TEST_MESSAGE_BYTES, -14, 1000000);
        assertEquals(EXPECTED_MESSAGE, builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, TEST_MESSAGE_BYTES, 0, -14);
        assertEquals("", builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, TEST_MESSAGE_BYTES, 0, 1000000);
        assertEquals(EXPECTED_MESSAGE, builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, TEST_MESSAGE_BYTES, 1000000, TEST_MESSAGE_BYTES.length);
        assertEquals("", builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, TEST_MESSAGE_BYTES, 1000000, 0);
        assertEquals("", builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, TEST_MESSAGE_BYTES, 1000000, -14);
        assertEquals("", builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, TEST_MESSAGE_BYTES, 1000000, 1000000);
        assertEquals("", builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendBytesAsPrintFriendlyString(builder, TEST_MESSAGE_BYTES, 50, 100);
        assertEquals("ADT^A08|00001|D|2.3^^|||||||<0x0D CR>EVN|A08|2015010716144", builder.toString());
    }

    /**
     * Description of test.
     *
     * @throws Exception in the event of a test error.
     */
    @Test
    public void testAppendCharacterAsPrintFriendlyString() throws Exception {
        StringBuilder builder = null;

        try {
            Hl7Util.appendCharacterAsPrintFriendlyString(builder, 'a');
            fail("Exception should be raised with null StringBuilder argument");
        } catch (NullPointerException ignoredEx) {
            // Eat this
        }

        builder = new StringBuilder();
        Hl7Util.appendCharacterAsPrintFriendlyString(builder, MllpProtocolConstants.START_OF_BLOCK);
        assertEquals("<0x0B VT>", builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendCharacterAsPrintFriendlyString(builder, MllpProtocolConstants.END_OF_BLOCK);
        assertEquals("<0x1C FS>", builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendCharacterAsPrintFriendlyString(builder, MllpProtocolConstants.SEGMENT_DELIMITER);
        assertEquals("<0x0D CR>", builder.toString());

        builder = new StringBuilder();
        Hl7Util.appendCharacterAsPrintFriendlyString(builder, MllpProtocolConstants.MESSAGE_TERMINATOR);
        assertEquals("<0x0A LF>", builder.toString());
    }

    @Test
    public void testGetCharacterAsPrintFriendlyString() throws Exception {
        assertEquals("<0x0B VT>", Hl7Util.getCharacterAsPrintFriendlyString(MllpProtocolConstants.START_OF_BLOCK));
        assertEquals("<0x1C FS>", Hl7Util.getCharacterAsPrintFriendlyString(MllpProtocolConstants.END_OF_BLOCK));
        assertEquals("<0x0D CR>", Hl7Util.getCharacterAsPrintFriendlyString(MllpProtocolConstants.SEGMENT_DELIMITER));
        assertEquals("<0x0A LF>", Hl7Util.getCharacterAsPrintFriendlyString(MllpProtocolConstants.MESSAGE_TERMINATOR));
        assertEquals("<0x09 TAB>", Hl7Util.getCharacterAsPrintFriendlyString('\t'));
    }

    /**
     * Description of test.
     *
     * @throws Exception in the event of a test error.
     */
    @Test
    public void testFindMsh18WhenExistsWithoutTrailingPipe() throws Exception {
        final String testMessage = MSH_SEGMENT + "||||||8859/1" + '\r' + REMAINING_SEGMENTS;

        assertEquals("8859/1", Hl7Util.findMsh18(testMessage.getBytes()));
    }

    /**
     * Description of test.
     *
     * @throws Exception in the event of a test error.
     */
    @Test
    public void testFindMsh18WhenExistsWithTrailingPipe() throws Exception {
        final String testMessage = MSH_SEGMENT + "||||||8859/1|" + '\r' + REMAINING_SEGMENTS;

        assertEquals("8859/1", Hl7Util.findMsh18(testMessage.getBytes()));
    }

    /**
     * Description of test.
     *
     * @throws Exception in the event of a test error.
     */
    @Test
    public void testFindMsh18WhenMissingWithoutTrailingPipe() throws Exception {
        final String testMessage = MSH_SEGMENT + "||||||" + '\r' + REMAINING_SEGMENTS;

        assertEquals("", Hl7Util.findMsh18(testMessage.getBytes()));
    }

    /**
     * Description of test.
     *
     * @throws Exception in the event of a test error.
     */
    @Test
    public void testFindMsh18WhenMissingWithTrailingPipe() throws Exception {
        final String testMessage = MSH_SEGMENT + "|||||||" + '\r' + REMAINING_SEGMENTS;

        assertEquals("", Hl7Util.findMsh18(testMessage.getBytes()));
    }
}


text:
class java::util::zip::Checksum : public ::java::lang::Object
{

public:
  virtual jlong getValue() = 0;
  virtual void reset() = 0;
  virtual void update(jint) = 0;
  virtual void update(JArray< jbyte > *, jint, jint) = 0;
  static ::java::lang::Class class$;
} __attribute__ ((java_interface));

#endif // __java_util_zip_Checksum__

redpajama_set_name: RedPajamaGithub


text:
package org.wso2.carbon.device.mgt.oauth.extensions.validators;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.oauth.extensions.internal.OAuthExtensionsDataHolder;
import org.wso2.carbon.identity.application.common.model.User;
import org.wso2.carbon.identity.core.util.IdentityTenantUtil;
import org.wso2.carbon.identity.oauth.cache.CacheEntry;
import org.wso2.carbon.identity.oauth.cache.OAuthCache;
import org.wso2.carbon.identity.oauth.cache.OAuthCacheKey;
import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception;
import org.wso2.carbon.identity.oauth2.dao.OAuthScopeDAOImpl;
import org.wso2.carbon.identity.oauth2.dao.TokenManagementDAOImpl;
import org.wso2.carbon.identity.oauth2.model.AccessTokenDO;
import org.wso2.carbon.identity.oauth2.model.ResourceScopeCacheEntry;
import org.wso2.carbon.identity.oauth2.validators.OAuth2ScopeValidator;
import org.wso2.carbon.user.api.AuthorizationManager;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

@SuppressWarnings("unused")
public class ExtendedJDBCScopeValidator extends OAuth2ScopeValidator {

    private static final Log log = LogFactory.getLog(ExtendedJDBCScopeValidator.class);
    private static final String UI_EXECUTE = "ui.execute";

    @Override
    public boolean validateScope(AccessTokenDO accessTokenDO, String resource) throws IdentityOAuth2Exception {
        //Get the list of scopes associated with the access token
        String[] scopes = accessTokenDO.getScope();

        //If no scopes are associated with the token
        if (scopes == null || scopes.length == 0) {
            return true;
        }

        String resourceScope = null;
        OAuthScopeDAOImpl scopeDAO = new OAuthScopeDAOImpl();
        TokenManagementDAOImpl tokenManagementDAO = new TokenManagementDAOImpl();
        boolean cacheHit = false;

        // Check the cache, if caching is enabled.
        if (OAuthCache.getInstance().isEnabled()) {
            OAuthCache oauthCache = OAuthCache.getInstance();
            OAuthCacheKey cacheKey = new OAuthCacheKey(resource);
            CacheEntry result = oauthCache.getValueFromCache(cacheKey);

            //Cache hit
            if (result instanceof ResourceScopeCacheEntry) {
                resourceScope = ((ResourceScopeCacheEntry) result).getScope();
                cacheHit = true;
            }
        }

        if (!cacheHit) {
            resourceScope = tokenManagementDAO.findTenantAndScopeOfResource(resource).getKey();

            if (OAuthCache.getInstance().isEnabled()) {
                OAuthCache oauthCache = OAuthCache.getInstance();
                OAuthCacheKey cacheKey = new OAuthCacheKey(resource);
                ResourceScopeCacheEntry cacheEntry = new ResourceScopeCacheEntry(resourceScope);
                //Store resourceScope in cache even if it is null (to avoid database calls when accessing resources for
                //which scopes haven't been defined).
                oauthCache.addToCache(cacheKey, cacheEntry);
            }
        }

        //Return TRUE if - There does not exist a scope definition for the resource
        if (resourceScope == null) {
            if (log.isDebugEnabled()) {
                log.debug("Resource '" + resource + "' is not protected with a scope");
            }
            return true;
        }

        List<String> scopeList = new ArrayList<>(Arrays.asList(scopes));

        //If the access token does not bear the scope required for accessing the Resource.
        if (!scopeList.contains(resourceScope)) {
            if (log.isDebugEnabled()) {
                log.debug("Access token '" + accessTokenDO.getAccessToken() + "' does not bear the scope '" +
                                  resourceScope + "'");
            }
            return false;
        }

        try {
            User authorizedUser = accessTokenDO.getAuthzUser();
            RealmService realmService = OAuthExtensionsDataHolder.getInstance().getRealmService();
            int tenantId = realmService.getTenantManager().getTenantId(authorizedUser.getTenantDomain());

            //Get the permissions associated with the scope, if any
            Set<String> permissionsOfScope = scopeDAO.getBindingsOfScopeByScopeName(resourceScope, tenantId);

            //If the scope doesn't have any permissions associated with it.
            if (permissionsOfScope == null || permissionsOfScope.isEmpty()) {
                if (log.isDebugEnabled()) {
                    log.debug("Did not find any roles associated to the scope " + resourceScope);
                }
                return true;
            }

            if (log.isDebugEnabled()) {
                StringBuilder logMessage = new StringBuilder("Found permissions of scope '" + resourceScope + "' ");
                for (String permission : permissionsOfScope) {
                    logMessage.append(permission);
                    logMessage.append(", ");
                }
                log.debug(logMessage.toString());
            }

            if (tenantId == 0 || tenantId == -1) {
                tenantId = IdentityTenantUtil.getTenantIdOfUser(authorizedUser.getUserName());
            }

            AuthorizationManager authorizationManager;
            String[] userRoles;
            boolean tenantFlowStarted = false;

            try {
                //If this is a tenant user
                if (tenantId != MultitenantConstants.SUPER_TENANT_ID) {
                    PrivilegedCarbonContext.startTenantFlow();
                    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
                            realmService.getTenantManager().getDomain(tenantId), true);
                    tenantFlowStarted = true;
                }

                authorizationManager = realmService.getTenantUserRealm(tenantId).getAuthorizationManager();

            } finally {
                if (tenantFlowStarted) {
                    PrivilegedCarbonContext.endTenantFlow();
                }
            }
            boolean status = false;
            String username = MultitenantUtils.getTenantAwareUsername(authorizedUser.getUserName());
            for (String permission : permissionsOfScope) {
                if (authorizationManager != null) {
                    String userStore = authorizedUser.getUserStoreDomain();

                    if (userStore != null) {
                        status = authorizationManager
                                .isUserAuthorized(userStore + "/" + username, permission, UI_EXECUTE);
                    } else {
                        status = authorizationManager.isUserAuthorized(username, permission, UI_EXECUTE);
                    }
                    if (status) {
                        break;
                    }
                }
            }

            if (status) {
                if (log.isDebugEnabled()) {
                    log.debug("User '" + authorizedUser.getUserName() + "' is authorized");
                }
                return true;
            }

            if (log.isDebugEnabled()) {
                log.debug("No permissions associated for the user " + authorizedUser.getUserName());
            }
            return false;

        } catch (UserStoreException e) {
            //Log and return since we do not want to stop issuing the token in case of scope validation failures.
            log.error("Error when getting the tenant's UserStoreManager or when getting roles of user ", e);
            return false;
        }
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="500"
    android:interpolator="@android:interpolator/fast_out_linear_in"
    android:propertyName="trimPathEnd"
    android:startOffset="2020"
    android:valueFrom="0"
    android:valueTo="1" />


text:
<?php

namespace Elcodi\Bundle\ConfigurationBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\Definition\ConfigurationInterface;

use Elcodi\Bundle\CoreBundle\DependencyInjection\Abstracts\AbstractConfiguration;
use Elcodi\Component\Configuration\ElcodiConfigurationTypes;

/**
 * This is the class that validates and merges configuration from your app/config files
 */
class Configuration extends AbstractConfiguration implements ConfigurationInterface
{
    /**
     * Configure the root node
     *
     * @param ArrayNodeDefinition $rootNode
     */
    protected function setupTree(ArrayNodeDefinition $rootNode)
    {
        $rootNode
            ->children()
                ->arrayNode('mapping')
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->append($this->addMappingNode(
                            'configuration',
                            'Elcodi\Component\Configuration\Entity\Configuration',
                            '@ElcodiConfigurationBundle/Resources/config/doctrine/Configuration.orm.yml',
                            'default',
                            true
                        ))
                    ->end()
                ->end()
                ->arrayNode('elements')
                    ->useAttributeAsKey('')
                    ->prototype('array')
                        ->children()
                            ->scalarNode('key')
                                ->isRequired()
                            ->end()
                            ->scalarNode('name')
                                ->isRequired()
                            ->end()
                            ->scalarNode('namespace')
                                ->defaultValue('')
                            ->end()
                            ->enumNode('type')
                                ->values([
                                    ElcodiConfigurationTypes::TYPE_BOOLEAN,
                                    ElcodiConfigurationTypes::TYPE_STRING,
                                    ElcodiConfigurationTypes::TYPE_TEXT,
                                    ElcodiConfigurationTypes::TYPE_ARRAY,
                                ])
                            ->end()
                            ->scalarNode('reference')
                                ->defaultNull()
                            ->end()
                            ->variableNode('default_value')
                                ->defaultNull()
                            ->end()
                            ->scalarNode('can_be_empty')
                                ->defaultTrue()
                            ->end()
                            ->scalarNode('empty_message')
                                ->defaultValue('')
                            ->end()
                            ->booleanNode('read_only')
                                ->defaultFalse()
                            ->end()
                        ->end()
                    ->end()
                    ->beforeNormalization()
                        ->always(function ($elements) {

                            $newElements = [];
                            if (is_array($elements)) {
                                foreach ($elements as $element) {
                                    $completeParameterName = isset($element['namespace'])
                                        ? $element['namespace'] . '.' . $element['key']
                                        : $element['key'];

                                    $newElements[$completeParameterName] = $element;
                                }
                            }

                            return $newElements;
                        })
                    ->end()
                ->end()
            ->end();
    }
}


text:
package org.duomn.naive.common.thread;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 参照dwzmvc的工具类
 * @author Hu Qiang
 *
 */
public class ThreadPool implements ThreadPoolDiagnoes {
	/** Application allow mutiple thread pool, the log doesn't use static decorate */
	private Logger log = LoggerFactory.getLogger(ThreadPool.class);

	private int threadMaxSize;
	private String threadPrefix;
	private boolean running;

	private ThreadPoolExecutor threadPool = null;
	private BlockingQueue<Runnable> workQueue = new SynchronousQueue<Runnable>();

	/** 用于对诊断信息的读写锁 */
	private ReadWriteLock lock = new ReentrantReadWriteLock(false);
	/** 保存诊断信息的map */
	private Map<Runnable, ThreadDiagnose> diagnoseMap = new HashMap<Runnable, ThreadDiagnose>();

	public ThreadPool() {

	}

	public ThreadPool(int threadMaxSize, String threadPrefix) {
		if (threadMaxSize < 0) throw new IllegalArgumentException("maxsize < 0");
		this.threadMaxSize = threadMaxSize;
		this.threadPrefix = threadPrefix;
		log.debug("New ThreadPool given: coresize=" + threadMaxSize
				+ ", maxsize=" + threadMaxSize + ", thread_prefix="
				+ threadPrefix);
	}

	public synchronized void start() {
		if (!running) {
			log.debug("ThreadPool.start() starting");

			long waitTime = 30 * 60 * 1000L; // 30min
			threadPool = new ThreadPoolExecutor(threadMaxSize, threadMaxSize,
					waitTime, TimeUnit.MILLISECONDS, workQueue);
			threadPool.setThreadFactory(new ThreadFactory() {
				public Thread newThread(Runnable r) {
					Thread t = new Thread(r);
					t.setName(threadPrefix + "_" + next());
					t.setDaemon(true);
					if (t.getPriority() != Thread.NORM_PRIORITY) {
						t.setPriority(Thread.NORM_PRIORITY);
					}
					return t;
				}
			});
			running = true;
		} else {
			log.debug("ThreadPool.start() is already running");
		}
	}

	public synchronized void stop() {
		if (running) {
			log.debug("ThreadPool.stop() stopping");

			threadPool.shutdownNow();
			threadPool = null;
			running = false;
			try {
				lock.writeLock().lock();
				diagnoseMap.clear();
			} finally {
				lock.writeLock().unlock();
			}
		} else {
			log.debug("ThreadPool.stop() is already stop");
		}
	}

	public void execute(final Runnable torun) {
		if (running && torun != null) {
			Runnable wapper = new Runnable() {
				public void run() {
					ThreadDiagnose diagnose = new ThreadDiagnose();
					diagnose.className = torun.getClass().getName();
					diagnose.startTime = System.currentTimeMillis();
					diagnose.torun = torun;
					try {
						lock.writeLock().lock();
						diagnoseMap.put(this, diagnose);
					} finally {
						lock.writeLock().unlock();
					}
					try {
						torun.run();
					} finally {
						try {
							lock.writeLock().lock();
							diagnoseMap.remove(this);
						} finally {
							lock.writeLock().unlock();
						}
						log.debug("ThreadPool.execute:torun="
								+ diagnose.className
								+ ", Elapsed Time="
								+ (System.currentTimeMillis() - diagnose.startTime)
								+ "(ms)");
					}
				}
			};
			threadPool.execute(wapper);
		} else {
			log.debug("ThreadPool.execute() error:" + running+"="+running+", Runable="+torun);
			throw new IllegalThreadStateException("not running");
		}
	}

	@Override
	public boolean isRunning() {
		return running;
	}

	@Override
	public int maxSize() {
		return threadMaxSize;
	}

	@Override
	public int size() {
		if (threadPool != null) {
			return threadPool.getPoolSize();
		}
		return 0;
	}

	@Override
	public ThreadDiagnose[] getDiagnose() {
		List<ThreadDiagnose> list = new ArrayList<ThreadDiagnose>();
		try {
			lock.readLock().lock();
			for (ThreadDiagnose diagnose : diagnoseMap.values()) {
				list.add(diagnose.copyOne());
			}
		} finally {
			lock.readLock().unlock();
		}

		return list.toArray(new ThreadDiagnose[list.size()]);
	}

	private static AtomicInteger num = new AtomicInteger(0);
	/** 供线程命名时使用 */
	private static int next() {
		return num.getAndAdd(1);
	}

	/** 线程诊断信息 */
	public static class ThreadDiagnose {
		/** 正在运行的任务的类名 */
		private String className;
		/** 开始时间 */
		private long startTime;
		/** 要执行的任务 */
		private Runnable torun;

		private ThreadDiagnose copyOne() {
			ThreadDiagnose diagnose = new ThreadDiagnose();
			diagnose.className = className;
			diagnose.startTime = startTime;
			diagnose.torun = torun;
			return diagnose;
		}
	}
}


text:
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import withStyles from '../styles/withStyles';

export const styles = theme => ({
  root: {
    listStyle: 'none',
    margin: 0,
    padding: 0,
    position: 'relative',
  },
  padding: {
    paddingTop: theme.spacing.unit,
    paddingBottom: theme.spacing.unit,
  },
  dense: {
    paddingTop: theme.spacing.unit / 2,
    paddingBottom: theme.spacing.unit / 2,
  },
  subheader: {
    paddingTop: 0,
  },
});

class List extends React.Component {
  getChildContext() {
    return {
      dense: this.props.dense,
    };
  }

  render() {
    const {
      children,
      classes,
      className: classNameProp,
      component: Component,
      dense,
      disablePadding,
      subheader,
      ...other
    } = this.props;
    const className = classNames(
      classes.root,
      {
        [classes.dense]: dense && !disablePadding,
        [classes.padding]: !disablePadding,
        [classes.subheader]: subheader,
      },
      classNameProp,
    );

    return (
      <Component className={className} {...other}>
        {subheader}
        {children}
      </Component>
    );
  }
}

List.propTypes = {
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Useful to extend the style applied to components.
   */
  classes: PropTypes.object.isRequired,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The component used for the root node.
   * Either a string to use a DOM element or a component.
   */
  component: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
  /**
   * If `true`, compact vertical padding designed for keyboard and mouse input will be used for
   * the list and list items. The property is available to descendant components as the
   * `dense` context.
   */
  dense: PropTypes.bool,
  /**
   * If `true`, vertical padding will be removed from the list.
   */
  disablePadding: PropTypes.bool,
  /**
   * The content of the subheader, normally `ListSubheader`.
   */
  subheader: PropTypes.node,
};

List.defaultProps = {
  component: 'ul',
  dense: false,
  disablePadding: false,
};

List.childContextTypes = {
  dense: PropTypes.bool,
};

export default withStyles(styles, { name: 'MuiList' })(List);


text:
<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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>info.benjaminhill</groupId>
  <artifactId>image-sorter</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>Image Sorter</name>
  <description>Sorts your images</description>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.3</version>
        <configuration>
          <source />
          <target />
          <showDeprecation>true</showDeprecation>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>19.0-rc1</version>
    </dependency>
    <dependency>
      <groupId>com.drewnoakes</groupId>
      <artifactId>metadata-extractor</artifactId>
      <version>2.8.1</version>
    </dependency>

  </dependencies>
  <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>
</project>


text:
package org.papoose.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;

import org.papoose.core.spi.StartLevelStore;

/**
 *
 */
public class DefaultStartLevelStore implements StartLevelStore
{
    private final static String CLASS_NAME = DefaultStartLevelStore.class.getName();
    private final static Logger LOGGER = Logger.getLogger(CLASS_NAME);
    private final static String INITIAL_START_LEVEL = "initial";
    private final static String BUNDLE_START_LEVEL = "bundle";
    private final Properties properties = new Properties();
    private volatile File file;

    public void start(Papoose framework)
    {
        BundleContext bundleContext = framework.getSystemBundleContext();
        file = bundleContext.getDataFile("start-level.properties");

        if (file.exists())
        {
            load();
        }
        else
        {
            properties.put(INITIAL_START_LEVEL, "1");
            save();
        }
    }

    public void stop()
    {
        file = null;
    }

    public int getBundleStartLevel(Bundle bundle)
    {
        try
        {
            return Integer.valueOf(properties.getProperty(BUNDLE_START_LEVEL + "." + bundle.getBundleId()));
        }
        catch (NumberFormatException e)
        {
            return Integer.valueOf(properties.getProperty(INITIAL_START_LEVEL));
        }
    }

    public void setBundleStartLevel(Bundle bundle, int bundleStartLevel)
    {
        properties.put(BUNDLE_START_LEVEL + "." + bundle.getBundleId(), Integer.toString(bundleStartLevel));
        save();
    }

    public void clearBundleStartLevel(Bundle bundle)
    {
        properties.remove(BUNDLE_START_LEVEL + "." + bundle.getBundleId());
        save();
    }

    public int getInitialBundleStartLevel()
    {
        return Integer.valueOf(properties.getProperty(INITIAL_START_LEVEL));
    }

    public void setInitialBundleStartLevel(int initialBundleStartLevel)
    {
        properties.put(INITIAL_START_LEVEL, Integer.toString(initialBundleStartLevel));
        save();
    }

    private void load()
    {
        InputStream in = null;
        try
        {
            in = new FileInputStream(file);
            properties.load(in);
        }
        catch (IOException ioe)
        {
            LOGGER.log(Level.SEVERE, "Error loading " + file, ioe);
            throw new FatalError("Error loading " + file, ioe);
        }
        finally
        {
            if (in != null)
            {
                try
                {
                    in.close();
                }
                catch (IOException ioe)
                {
                    LOGGER.log(Level.WARNING, "Error loading " + file, ioe);
                }
            }
        }
    }

    private void save()
    {
        OutputStream out = null;
        try
        {
            out = new FileOutputStream(file);
            properties.store(out, "Start level properties saved at " + new Date());
        }
        catch (IOException ioe)
        {
            LOGGER.log(Level.SEVERE, "Error saving " + file, ioe);
            throw new FatalError("Error saving " + file, ioe);
        }
        finally
        {
            if (out != null)
            {
                try
                {
                    out.close();
                }
                catch (IOException ioe)
                {
                    LOGGER.log(Level.WARNING, "Error saving " + file, ioe);
                }
            }
        }
    }
}


text:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { LyFieldModule } from '@alyle/ui/field';
import { LySelectModule } from '@alyle/ui/select';
import { LyTypographyModule } from '@alyle/ui/typography';

import { BasicSelectComponent } from './basic-select.component';

@NgModule({
  declarations: [BasicSelectComponent],
  imports: [
    CommonModule,
    LyFieldModule,
    LySelectModule,
    LyTypographyModule
  ],
  exports: [BasicSelectComponent]
})
export class BasicSelectModule { }


text:
<?php

declare(strict_types=1);

namespace FunTimeCoding\PhpUtility\Test\Unit\LanguageExample\Pattern\Proxy;

use FunTimeCoding\PhpUtility\LanguageExample\Pattern\Proxy\ProxyFile;
use FunTimeCoding\PhpUtility\LanguageExample\Pattern\Proxy\RealFile;
use PHPUnit\Framework\TestCase;

class ProxyFileTest extends TestCase
{
    public function testNotYetLoaded(): void
    {
        $image = new ProxyFile('MyFilename');

        $this::assertEquals(new RealFile(''), $image->getFile());
    }

    public function testAfterLoading(): void
    {
        $image = new ProxyFile('MyFilename');

        $image->getContent();

        $this::assertEquals(new RealFile('MyFilename'), $image->getFile());
    }
}


text:
<?php
/**
 * Class does Authorization against facebook.
 *
 * Class can connect to facebook, do authorization and get current user object.
 * It implements ExternalAuth
 *
 * @author Aram Gevorgyan
 */
class FacebookAuth extends DbAccessor implements ExternalAuth
{
	private $config;

	private $redirectUrl = null;

	/**
	 * @var NAME of current social site
	 */
	const NAME = 'facebook';

	/**
	 * @var TBL_EXT_AUTH of facebook maping with own users
	 */
	const TBL_EXT_AUTH = 'extauth_map_facebook';

	/**
	 *
	 * @var TBL_FB_USER_INFO name of information table of facebook user
	 */
	const TBL_FB_USER_INFO = 'facebook_users_info';

	/**
	 * Constructor for FacebookAuth class,
	 * @param Config $config
	 */
	public function __construct(Config $config, $dbInstanceKey = null){
		parent::__construct($dbInstanceKey);
		$this->config = $config;
	}

	/**
	 * Function rewrite default redirect url and set new redirect url
	 * @param string $redirectUrl
	 */
	public function setRedirectUrl($redirectUrl) {
		$this->redirectUrl = $redirectUrl;
	}

	/**
	 * Help function
	 * If after redirect from Facebook there is no "code" parameter,
	 * function again does redirect to facebook's oAuth system
	 */
	private function redirectToDialog(){
		if($this->redirectUrl !== null) {
			$rediectUrl = $this->redirectUrl;
		} else {
			$rediectUrl = $this->config->redirectUrl;
		}
		$dialogUrl = "https://www.facebook.com/dialog/oauth?client_id="
            . $this->config->appId . "&redirect_uri=" . urlencode($rediectUrl);
        echo("<script> top.location.href='" . $dialogUrl . "'</script>");
	}

	/**
	 * Help function
	 * Function connects to facebook's "oAuth" protocol and gets access token
	 * @param string $code is code from facebook
	 * @return string
	 */
	private function getAccessToken($code) {
		if($this->redirectUrl !== null) {
			$rediectUrl = $this->redirectUrl;
		} else {
			$rediectUrl = $this->config->redirectUrl;
		}
		$tokenUrl = "https://graph.facebook.com/oauth/access_token?client_id="
        		.  $this->config->appId
        		. "&redirect_uri="  . urlencode($rediectUrl)
        		. "&client_secret=" . $this->config->appSecret
        		. "&code=" . $code;
        try{
    		return file_get_contents($tokenUrl);
        }
        catch(ErrorException $e){
        	return false;
        }
	}

	/**
	 * Help function
	 * Function gets facebook's User object with access token from "Facebook Graph"
	 * @param string $accessToken it's access token
	 * @return FacebookObject
	 */
	private function getFBUserFromGraph($accessToken){

		$graphUrl = "https://graph.facebook.com/me?" . $accessToken;
		try{
    		$fbUser = json_decode(file_get_contents($graphUrl));
	 	}
        catch(ErrorException $e){
        	return false;
        }
    	return $fbUser;
	}

	/**
	 * Help Function
	 * Function Set BirthDate with  Default date format and return it
	 * @param  $fbBirthDate birdthdate field from Facebook user object
	 * @return string
	 */
	private function setBirthDate($fbBirthDate){

		$utime = strtotime($fbBirthDate);
		$birthdate = date(DEFAULT_DATE_FORMAT, $utime);
		return $birthdate;
	}

	/**
	 * Help Function
	 * Fill Others fields from facebook user object to External user object field(otherFields)
	 * @param Facebook User object $fbUser
	 * @return ArrayObject
	 */
	private function fillOtherFieldsFromFBUser($fbUser){
		$othersArray = array();
		if(is_array($fbUser)){
			foreach ($fbUser as $key => $field) {
				if($field != null) {
					$othersArray[$key] = $field;
				}
			}
		}
		return 	$othersArray;
	}

	/**
	 * Help function
	 * Function Creates new ExternalUser object,
	 * from facebook's user object fills all members and returns ExtraUser object
	 * @param "stdClass object" $fbUser It's Facebook's User object
	 * @return ExternalUser
	 */
	private function createExternalUser($fbUser){
		$extUser = new ExternalUser();
		if(!empty($fbUser->first_name)) {
			$extUser->firstName = addslashes($fbUser->first_name);
			$fbUser->first_name = null;
		}
		if(!empty($fbUser->last_name)){
			$extUser->lastName = addslashes($fbUser->last_name);
			$fbUser->last_name = null;
		}
		if(!empty($fbUser->email)){
			$extUser->email = addslashes($fbUser->email);
			$fbUser->email = null;
		}
		if(!empty($fbUser->birthday)){
			$extUser->birthdate = $this->setBirthDate($fbUser->birthday);
			$fbUser->birthday = null;
		}
		if(!empty($fbUser->id)){
			$extUser->id = $fbUser->id;
			$fbUser->id = null;
		}
		if(!empty($fbUser->gender)){
			switch ($fbUser->gender) {
				case 'male' : $extUser->sex = ExternalUser::SEX_MALE; break;
				case 'female': $extUser->sex = ExternalUser::SEX_FEMALE; break;
			}
			$fbUser->gender = null;
		}
		$extUser->otherFields = $fbUser;
		return $extUser;
	}

	/**
	 * @see ExternalAuth::getName()
	 */
	public function getName(){
		return static::NAME;
	}

	/**
	 * @see ExternalAuth::getExtUser()
	 */
	public function getExtUser(){
		$code = null;
		if(isset($_GET["code"])){
			$code = $_GET["code"];
		}
		if(empty($code)) {
     		$this->redirectToDialog();
    	}
    	$accessToken = $this->getAccessToken($code);
    	$fbUser = $this->getFBUserFromGraph($accessToken);
    	$extUser = $this->createExternalUser($fbUser);
		return $extUser;
	}

	/**
	 * @see ExternalAuth::setExtMap()
	 */
	public function addToExtMap($userId,ExternalUser $extUser){
		if(!is_numeric($userId)) {
			throw new InvalidArgumentException("User Id Is not numeric");
		}
		if(!is_numeric($extUser->id)) {
			throw new InvalidArgumentException("External Id Is not numeric");
		}
		$extUserId = $extUser->id;
		$this->query->exec("INSERT INTO `".Tbl::get('TBL_EXT_AUTH')."`
									(`user_id`,`ext_user_id`) VALUES
									('$userId','$extUserId')");
		return true;
	}

	/**
	 * @see ExternalAuth::getLocalUserIDFromMap()
	 */
	public function getLocalUserIDFromMap(ExternalUser $extUser){
		if(!is_numeric($extUser->id)) {
			throw new Exception("id is not numeric");
		}
		$extUserId = $extUser->id;
		$this->query->exec("SELECT `user_id`
							FROM `".Tbl::get('TBL_EXT_AUTH')."`
							WHERE `ext_user_id`='$extUserId'
							LIMIT 1");

		return $this->query->fetchField('user_id');
	}

	/**
	 * @see ExternalAuth::getExternalUserId()
	 */
	public function getExternalUserId($userId){
		if(!is_numeric($userId)) {
			throw new Exception("User Id is not numeric");
		}
		$this->query->exec("SELECT `ext_user_id`
							FROM `".Tbl::get('TBL_EXT_AUTH')."`
							WHERE `user_id`='$userId'
							LIMIT 1");

		return $this->query->fetchField('ext_user_id');
	}

	/**
	 * @see ExternalAuth::deleteLocalUserFromMap()
	 */
	public function deleteUserIDFromMap($userId){
		if(!is_numeric($userId)) {
			throw new Exception("id is not numeric");
		}
		$this->query->exec("DELETE FROM `".Tbl::get('TBL_EXT_AUTH')."`
							WHERE `user_id`='$userId'
							LIMIT 1");
	}

	/**
	 * Function connects to Facebook and gets photo albums
	 * @param string $accessToken is access token, by default It`s null
	 * @return ArrayObject
	 */
	public function getAlbums($accessToken = null) {
		$code = $_GET["code"];
		if(empty($code)) {
     		$this->redirectToDialog();
    	}
    	$albumsArray = array();
    	if($accessToken === null) {
    		$accessToken = $this->getAccessToken($code);
    	}
    	$extAlbumUrl = "https://graph.facebook.com/me/albums?$accessToken&limit=100&offset=0";
    	try{
 			$extAlbum = json_decode(file_get_contents($extAlbumUrl));
	 	}
        catch(ErrorException $e){
        	return false;
        }

 		foreach($extAlbum->data as $fbAlbum) {
 			$albumObj = new FacebookPhotoAlbum();
 			$albumObj->id = $fbAlbum->id;
 			$albumObj->name = $fbAlbum->name;
 			$albumObj->photo = "https://graph.facebook.com/".$fbAlbum->id."/picture?$accessToken";
 			$albumObj->type = $fbAlbum->type;
 			$albumsArray[] = $albumObj;
 		}
 		return $albumsArray;
	}

	/**
	 * Function Connects to Facebook and get Profile pictures
	 * @return ArrayObject
	 */
	public function getProfilePhotos(){
		$code = $_GET["code"];
		if(empty($code)) {
     		$this->redirectToDialog();
    	}
    	$accessToken = $this->getAccessToken($code);
 		$extAlbum = $this->getAlbums($accessToken);
    	$filesArray = array ();
    	if(is_array($extAlbum) and count($extAlbum)){
	 		foreach ($extAlbum as $albumObj) {
	 			if($albumObj->type == 'profile') {
	 				$extPhotosUrl = "https://graph.facebook.com/".$albumObj->id."/photos?$accessToken";
	 				try{
	 					$extPhotosObject = json_decode(file_get_contents($extPhotosUrl));
			 		}
			        catch(ErrorException $e){
			        	return false;
			        }
	 				foreach ($extPhotosObject->data as $excObj) {
	 					if($excObj->source !== null) {
	 						$photoObj = new FacebookPhoto();
	 						$photoObj->id = $excObj->id;
	 						$photoObj->picture = $excObj->picture;
	 						$photoObj->source = $excObj->source;
	 						$photoObj->width = $excObj->width;
	 						$photoObj->height = $excObj->height;
	 						$filesArray[] = $photoObj;
	 					}
	 				}
	 			}
	 		}
    	}
 		return $filesArray;
	}

	/**
	 * Check if photo meets requirements for minimal size.
	 *
	 * @param FacebookPhoto $photoObj
	 * @param integer $largeSideMinSize
	 * @param integer $smallSideMinSize
	 * @return boolean
	 */
	public function isSizeMeetRequirements(FacebookPhoto $photoObj, $largeSideMinSize, $smallSideMinSize){
		$width = $photoObj->width;
		$height = $photoObj->height;
		if($width >= $height){
			if($width >= $largeSideMinSize and $height >= $smallSideMinSize){
				return true;
			}
		}
		else{
			if($height >= $largeSideMinSize and $width >= $smallSideMinSize){
				return true;
			}
		}
		return false;
	}

	/**
	 * Get External User information from info table.
	 * @param integer $userId user ID
	 * @throws InvalidArgumentException
	 * @return ArrayObject
	 */
	public function getExtUserInfo($userId){
		if(!is_numeric($userId)) {
			throw new InvalidArgumentException("User Id Is not numeric");
		}
		$this->query->exec("SELECT * FROM `".Tbl::get('TBL_FB_USER_INFO')."`
							WHERE `user_id`='$userId'
							LIMIT 1");
		return $this->query->fetchRecord();
	}

	/**
	 * Add to facebook info table External user information.
	 * @param integer $userId
	 * @param ExternalUser $extUser
	 * @throws InvalidArgumentException
	 */
	public function addExtUserInfo($userId, ExternalUser $extUser){
		if(!is_numeric($userId)) {
			throw new InvalidArgumentException("User Id Is not numeric");
		}
		if(!is_numeric($extUser->id)) {
			throw new InvalidArgumentException("External Id Is not numeric");
		}
		$this->query->exec("INSERT INTO `".Tbl::get('TBL_FB_USER_INFO')."`
									(`user_id`,`ext_user_id`, `name`) VALUES
									('$userId', '$extUser->id', '".(isset($extUser->otherFields->name) ? addslashes($extUser->otherFields->name) : "")."')");
	}

	/**
	 * delete all information from info table for current user
	 * @param integer $userId
	 * @throws InvalidArgumentException
	 */
	public function deleteExtUserInfo($userId) {
		if(!is_numeric($userId)) {
			throw new InvalidArgumentException("User Id Is not numeric");
		}
		$this->query->exec("DELETE FROM `".Tbl::get('TBL_FB_USER_INFO')."`
							WHERE `user_id`='$userId'
							LIMIT 1");
	}

	/**
	 * Function Updates local User Id from map table and user info table
	 * @param integer $userId current user Id
	 * @param ExternalUser $extUser External user object
	 * @throws InvalidArgumentException
	 */
	public function updateLocalUserId($userId, ExternalUser $extUser){
		if(!is_numeric($userId)) {
			throw new InvalidArgumentException("User Id Is not numeric");
		}
		if(!is_numeric($extUser->id)) {
			throw new InvalidArgumentException("External Id Is not numeric");
		}
		$this->query->exec(
							"UPDATE `".Tbl::get('TBL_EXT_AUTH')."`
							 SET `user_id` = '{$userId}'
							 WHERE `ext_user_id` = {$extUser->id}");
		$this->query->exec(
							"UPDATE `".Tbl::get('TBL_FB_USER_INFO')."`
							 SET `user_id` = '{$userId}'
							 WHERE `ext_user_id` = {$extUser->id}");
	}
}


text:
import shade
shade.simple_logging(debug=True)

cloud = shade.openstack_cloud(cloud='my-citycloud', region_name='Buf1')
try:
    server = cloud.create_server(
        'my-server', image='Ubuntu 16.04 Xenial Xerus',
        flavor=dict(id='0dab10b5-42a2-438e-be7b-505741a7ffcc'),
        wait=True, auto_ip=True)

    print("\n\nFull Server\n\n")
    cloud.pprint(server)

    print("\n\nTurn Detailed Off\n\n")
    cloud.pprint(cloud.get_server('my-server', detailed=False))

    print("\n\nBare Server\n\n")
    cloud.pprint(cloud.get_server('my-server', bare=True))

finally:
    # Delete it - this is a demo
    cloud.delete_server(server, wait=True, delete_ips=True)


text:
<html>
<head>
    <!--DXMETADATA start type="MetaCharset" -->
    <meta http-equiv="Content-Type" content="text/html; charset=UTF8"><!--DXMETADATA end-->
    <link rel="stylesheet" type="text/css" href="stylesheets/helpstudio.css">
    <style type="text/css">
        blockquote {
                margin-top: 0px;
                margin-bottom: 0px;
                margin-left: 16px;
        }
    </style>

	<meta content="Innovasys HelpStudio (www.innovasys.com)" name="GENERATOR">
</head>

<body style="margin-top:5;margin-left:5" topmargin="5" leftmargin="5">
    <!--DXMETADATA start type="IndexContent" Scrap="_INDEXCONTENT_ENTRY_WEB_BODY"-->Index Entries<!--DXMETADATA end-->
</body>
</html>


text:
var createThis:GameObject[];  // list of possible prefabs

private var rndNr:float; // this is for just a random number holder when we need it

var thisManyTimes:int=3;
var overThisTime:float=1.0;

var xWidth:float;  // define the square where prefabs will be generated
var yWidth:float;
var zWidth:float;

var xRotMax:float;  // define maximum rotation of each prefab
var yRotMax:float=180;
var zRotMax:float;

var allUseSameRotation:boolean=false;
private var allRotationDecided:boolean=false;

var detachToWorld:boolean=true;

private var x_cur:float;  // these are used in the random palcement process
private var y_cur:float;
private var z_cur:float;

private var xRotCur:float;  // these are used in the random protation process
private var yRotCur:float;
private var zRotCur:float;

private var timeCounter:float;  // counts the time :p
private var effectCounter:int;  // you will guess ti

private var trigger:float;  // trigger: at which interwals should we generate a particle

function Start () {

trigger=overThisTime/thisManyTimes;  //define the intervals of time of the prefab generation.

}

function Update () {

timeCounter+=Time.deltaTime;

	if(timeCounter>trigger&&effectCounter<=thisManyTimes)
		{
		rndNr=Mathf.Floor(Random.value*createThis.length);  //decide which prefab to create

		x_cur=transform.position.x+(Random.value*xWidth)-(xWidth*0.5);  // decide an actual place
		y_cur=transform.position.y+(Random.value*yWidth)-(yWidth*0.5);
		z_cur=transform.position.z+(Random.value*zWidth)-(zWidth*0.5);

		if(allUseSameRotation==false||allRotationDecided==false)  // basically this plays only once if allRotationDecided=true, otherwise it plays all the time
		{
		xRotCur=transform.rotation.x+(Random.value*xRotMax*2)-(xRotMax);  // decide rotation
		yRotCur=transform.rotation.y+(Random.value*yRotMax*2)-(yRotMax);
		zRotCur=transform.rotation.z+(Random.value*zRotMax*2)-(zRotMax);
		allRotationDecided=true;
		}

		//var justCreated:GameObject=Instantiate(createThis[rndNr], Vector3(x_cur, y_cur, z_cur), Vector3(xRotCur, yRotCur, zRotCur));  //create the prefab
		var justCreated:GameObject=Instantiate(createThis[rndNr], Vector3(x_cur, y_cur, z_cur), transform.rotation);  //create the prefab
		justCreated.transform.Rotate(xRotCur, yRotCur, zRotCur);

			if(detachToWorld==false)  // if needed we attach the freshly generated prefab to the object that is holding this script
			{
			justCreated.transform.parent=transform;
			}

		timeCounter-=trigger;  //administration :p
		effectCounter+=1;
		}

}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
    <title>Points to CSV</title>

    <link rel="stylesheet" href="https://js.arcgis.com/4.15/esri/themes/light/main.css" />


text:
<?php namespace Semaphore;

use Adapter\AdapterInterface;
use Semaphore\Adapter\SharedMemory;
use LogicException;

/**
 * Semaphore wrapper
 * @class
 */
class Semaphore
{
	/**
	 * List of active keys (created in scope of current object) due to unlock everything for the rescue
	 * @var array
	 */
	protected $keys = array();

	/**
	 * Automaticall unlock all semaphores locked by the given semaphore object
	 * @var bool
	 */
	protected $autoUnlock = true;

	/**
	 * Create semaphore instance with given adapter
	 * If adapter is not given - use default one
	 * @param AdapterInterface $adapter
	 */
	public function __construct(AdapterInterface $adapter = null) {
		$this->adapter = $adapter ?: $this->getDefaultAdapter();
	}

	/**
	 * Set autounlock flag
	 * @param bool
	 */
	public function setAutoUnlock($autoUnlock) {
		$this->autoUnlock = $this->autoUnlock;
	}

	/**
	 * Unlock all previously locked semaphores
	 */
	public function __destruct() {
		if ($this->autoUnlock) {
			$this->unlockAll();
		}
	}

	/**
	 * Unlock all previously locked semaphores
	 */
	public function unlockAll() {
		foreach ($this->keys as $key) {
			$this->unlock($key);
		}
	}

	/**
	 * Attempt to lock semaphore with given key
	 * @param string $key
	 * @return true if successfully locked semaphore, otherwise false
	 */
	public function lock($key) {
		$locked = $this->adapter->lock($key);

		if ($locked) {
			$this->storeKey($key);
		}

		return $locked;
	}

	/**
	 * Unlock semaphore with given key
	 * @param string $key
	 * @return bool true if successfully unlocked, otherwise false
	 */
	public function unlock($key) {
		$unlocked = $this->adapter->unlock($key);

		if ($unlocked) {
			$this->destroyKey($key);
		}

		return $unlocked;
	}

	/**
	 * Check if semaphore with given key is locked
	 * @param string $key
	 * @return bool
	 */
	public function locked($key) {
		return $this->adapter->locked($key);
	}

	/**
	 * Get semaphore adapter
	 * @return Adapter\AdapterInterface
	 */
	public function getAdapter() {
		return $this->adapter;
	}

	/**
	 * Store key to active keys list
	 * @param string $key
	 */
	protected function storeKey($key) {
		if (empty($this->keys)) {
			$this->keys[$key] = true;
		}
	}

	/**
	 * Remove key from active key list
	 * @param string $key
	 */
	protected function destroyKey($key) {
		if (!empty($this->keys[$key])) {
			unset($this->keys[$key]);
		}
	}

	protected function getDefaultAdapter() {
		return new SharedMemory();
	}
}


text:
<?xml version="1.0" ?>
<!--
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.
-->
<Root>
  <TestCase name="testAppendOptions[0: is-bounded=true]">
    <Resource name="sql">
      <![CDATA[select * from t1/*+ OPTIONS(k5='v5', 'a.b.c'='fakeVal') */]]>
    </Resource>
    <Resource name="planBefore">
      <![CDATA[
LogicalProject(a=[$0], b=[$1], c=[+($0, 1)])
+- LogicalTableScan(table=[[default_catalog, default_database, t1, source: [OptionsTableSource(props={k1=v1, k2=v2, a.b.c=fakeVal, k5=v5})], dynamic options: {a.b.c=fakeVal, k5=v5}]])
]]>
    </Resource>
    <Resource name="planAfter">
      <![CDATA[
Calc(select=[a, b, +(a, 1) AS c])
+- LegacyTableSourceScan(table=[[default_catalog, default_database, t1, source: [OptionsTableSource(props={k1=v1, k2=v2, a.b.c=fakeVal, k5=v5})], dynamic options: {a.b.c=fakeVal, k5=v5}]], fields=[a, b])
]]>
    </Resource>
  </TestCase>
  <TestCase name="testAppendOptions[1: is-bounded=false]">
    <Resource name="sql">
      <![CDATA[select * from t1/*+ OPTIONS(k5='v5', 'a.b.c'='fakeVal') */]]>
    </Resource>
    <Resource name="planBefore">
      <![CDATA[
LogicalProject(a=[$0], b=[$1], c=[+($0, 1)])
+- LogicalTableScan(table=[[default_catalog, default_database, t1, source: [OptionsTableSource(props={k1=v1, k2=v2, a.b.c=fakeVal, k5=v5})], dynamic options: {a.b.c=fakeVal, k5=v5}]])
]]>
    </Resource>
    <Resource name="planAfter">
      <![CDATA[
Calc(select=[a, b, +(a, 1) AS c])
+- LegacyTableSourceScan(table=[[default_catalog, default_database, t1, source: [OptionsTableSource(props={k1=v1, k2=v2, a.b.c=fakeVal, k5=v5})], dynamic options: {a.b.c=fakeVal, k5=v5}]], fields=[a, b])
]]>
    </Resource>
  </TestCase>
  <TestCase name="testOptionsHintOnTableApiView[0: is-bounded=true]">
    <Resource name="sql">
      <![CDATA[select * from view1/*+ OPTIONS(k1='#v1', k2='#v2', k3='#v3', k4='#v4') */]]>
    </Resource>
    <Resource name="planBefore">
      <![CDATA[
LogicalProject(a=[$0], b=[$1], c=[$2], d=[$3], e=[$4], f=[$5])
+- LogicalJoin(condition=[=($0, $3)], joinType=[inner])
   :- LogicalProject(a=[$0], b=[$1], c=[+($0, 1)])
   :  +- LogicalTableScan(table=[[default_catalog, default_database, t1, source: [OptionsTableSource(props={k1=v1, k2=v2})]]])
   +- LogicalTableScan(table=[[default_catalog, default_database, t2, source: [OptionsTableSource(props={k3=v3, k4=v4})]]])
]]>
    </Resource>
    <Resource name="planAfter">
      <![CDATA[
MultipleInput(readOrder=[0,1], members=[\nHashJoin(joinType=[InnerJoin], where=[=(a, d)], select=[a, b, c, d, e, f], build=[right])\n:- Calc(select=[a, b, +(a, 1) AS c])\n:  +- [#2] Exchange(distribution=[hash[a]])\n+- [#1] Exchange(distribution=[hash[d]])\n])
:- Exchange(distribution=[hash[d]])
:  +- LegacyTableSourceScan(table=[[default_catalog, default_database, t2, source: [OptionsTableSource(props={k3=v3, k4=v4})]]], fields=[d, e, f])
+- Exchange(distribution=[hash[a]])
   +- LegacyTableSourceScan(table=[[default_catalog, default_database, t1, source: [OptionsTableSource(props={k1=v1, k2=v2})]]], fields=[a, b])
]]>
    </Resource>
  </TestCase>
  <TestCase name="testJoinWithAppendedOptions[0: is-bounded=true]">
    <Resource name="sql">
      <![CDATA[
select * from
t1 /*+ OPTIONS(k5='v5', 'a.b.c'='fakeVal') */
join
t2 /*+ OPTIONS(k6='v6', 'd.e.f'='fakeVal') */
on t1.a = t2.d
]]>
    </Resource>
    <Resource name="planBefore">
      <![CDATA[
LogicalProject(a=[$0], b=[$1], c=[$2], d=[$3], e=[$4], f=[$5])
+- LogicalJoin(condition=[=($0, $3)], joinType=[inner])
   :- LogicalProject(a=[$0], b=[$1], c=[+($0, 1)])
   :  +- LogicalTableScan(table=[[default_catalog, default_database, t1, source: [OptionsTableSource(props={k1=v1, k2=v2, a.b.c=fakeVal, k5=v5})], dynamic options: {a.b.c=fakeVal, k5=v5}]])
   +- LogicalTableScan(table=[[default_catalog, default_database, t2, source: [OptionsTableSource(props={d.e.f=fakeVal, k3=v3, k4=v4, k6=v6})], dynamic options: {d.e.f=fakeVal, k6=v6}]])
]]>
    </Resource>
    <Resource name="planAfter">
      <![CDATA[
MultipleInput(readOrder=[0,1], members=[\nHashJoin(joinType=[InnerJoin], where=[=(a, d)], select=[a, b, c, d, e, f], build=[right])\n:- Calc(select=[a, b, +(a, 1) AS c])\n:  +- [#2] Exchange(distribution=[hash[a]])\n+- [#1] Exchange(distribution=[hash[d]])\n])
:- Exchange(distribution=[hash[d]])
:  +- LegacyTableSourceScan(table=[[default_catalog, default_database, t2, source: [OptionsTableSource(props={d.e.f=fakeVal, k3=v3, k4=v4, k6=v6})], dynamic options: {d.e.f=fakeVal, k6=v6}]], fields=[d, e, f])
+- Exchange(distribution=[hash[a]])
   +- LegacyTableSourceScan(table=[[default_catalog, default_database, t1, source: [OptionsTableSource(props={k1=v1, k2=v2, a.b.c=fakeVal, k5=v5})], dynamic options: {a.b.c=fakeVal, k5=v5}]], fields=[a, b])
]]>
    </Resource>
  </TestCase>
  <TestCase name="testJoinWithAppendedOptions[1: is-bounded=false]">
    <Resource name="sql">
      <![CDATA[
select * from
t1 /*+ OPTIONS(k5='v5', 'a.b.c'='fakeVal') */
join
t2 /*+ OPTIONS(k6='v6', 'd.e.f'='fakeVal') */
on t1.a = t2.d
]]>
    </Resource>
    <Resource name="planBefore">
      <![CDATA[
LogicalProject(a=[$0], b=[$1], c=[$2], d=[$3], e=[$4], f=[$5])
+- LogicalJoin(condition=[=($0, $3)], joinType=[inner])
   :- LogicalProject(a=[$0], b=[$1], c=[+($0, 1)])
   :  +- LogicalTableScan(table=[[default_catalog, default_database, t1, source: [OptionsTableSource(props={k1=v1, k2=v2, a.b.c=fakeVal, k5=v5})], dynamic options: {a.b.c=fakeVal, k5=v5}]])
   +- LogicalTableScan(table=[[default_catalog, default_database, t2, source: [OptionsTableSource(props={d.e.f=fakeVal, k3=v3, k4=v4, k6=v6})], dynamic options: {d.e.f=fakeVal, k6=v6}]])
]]>
    </Resource>
    <Resource name="planAfter">
      <![CDATA[
Join(joinType=[InnerJoin], where=[=(a, d)], select=[a, b, c, d, e, f], leftInputSpec=[NoUniqueKey], rightInputSpec=[NoUniqueKey])
:- Exchange(distribution=[hash[a]])
:  +- Calc(select=[a, b, +(a, 1) AS c])
:     +- LegacyTableSourceScan(table=[[default_catalog, default_database, t1, source: [OptionsTableSource(props={k1=v1, k2=v2, a.b.c=fakeVal, k5=v5})], dynamic options: {a.b.c=fakeVal, k5=v5}]], fields=[a, b])
+- Exchange(distribution=[hash[d]])
   +- LegacyTableSourceScan(table=[[default_catalog, default_database, t2, source: [OptionsTableSource(props={d.e.f=fakeVal, k3=v3, k4=v4, k6=v6})], dynamic options: {d.e.f=fakeVal, k6=v6}]], fields=[d, e, f])
]]>
    </Resource>
  </TestCase>
  <TestCase name="testJoinWithOverriddenOptions[0: is-bounded=true]">
    <Resource name="sql">
      <![CDATA[
select * from
t1 /*+ OPTIONS(k1='#v1', k2='#v2') */
join
t2 /*+ OPTIONS(k3='#v3', k4='#v4') */
on t1.a = t2.d
]]>
    </Resource>
    <Resource name="planBefore">
      <![CDATA[
LogicalProject(a=[$0], b=[$1], c=[$2], d=[$3], e=[$4], f=[$5])
+- LogicalJoin(condition=[=($0, $3)], joinType=[inner])
   :- LogicalProject(a=[$0], b=[$1], c=[+($0, 1)])
   :  +- LogicalTableScan(table=[[default_catalog, default_database, t1, source: [OptionsTableSource(props={k1=#v1, k2=#v2})], dynamic options: {k1=#v1, k2=#v2}]])
   +- LogicalTableScan(table=[[default_catalog, default_database, t2, source: [OptionsTableSource(props={k3=#v3, k4=#v4})], dynamic options: {k3=#v3, k4=#v4}]])
]]>
    </Resource>
    <Resource name="planAfter">
      <![CDATA[
MultipleInput(readOrder=[0,1], members=[\nHashJoin(joinType=[InnerJoin], where=[=(a, d)], select=[a, b, c, d, e, f], build=[right])\n:- Calc(select=[a, b, +(a, 1) AS c])\n:  +- [#2] Exchange(distribution=[hash[a]])\n+- [#1] Exchange(distribution=[hash[d]])\n])
:- Exchange(distribution=[hash[d]])
:  +- LegacyTableSourceScan(table=[[default_catalog, default_database, t2, source: [OptionsTableSource(props={k3=#v3, k4=#v4})], dynamic options: {k3=#v3, k4=#v4}]], fields=[d, e, f])
+- Exchange(distribution=[hash[a]])
   +- LegacyTableSourceScan(table=[[default_catalog, default_database, t1, source: [OptionsTableSource(props={k1=#v1, k2=#v2})], dynamic options: {k1=#v1, k2=#v2}]], fields=[a, b])
]]>
    </Resource>
  </TestCase>
  <TestCase name="testJoinWithOverriddenOptions[1: is-bounded=false]">
    <Resource name="sql">
      <![CDATA[
select * from
t1 /*+ OPTIONS(k1='#v1', k2='#v2') */
join
t2 /*+ OPTIONS(k3='#v3', k4='#v4') */
on t1.a = t2.d
]]>
    </Resource>
    <Resource name="planBefore">
      <![CDATA[
LogicalProject(a=[$0], b=[$1], c=[$2], d=[$3], e=[$4], f=[$5])
+- LogicalJoin(condition=[=($0, $3)], joinType=[inner])
   :- LogicalProject(a=[$0], b=[$1], c=[+($0, 1)])
   :  +- LogicalTableScan(table=[[default_catalog, default_database, t1, source: [OptionsTableSource(props={k1=#v1, k2=#v2})], dynamic options: {k1=#v1, k2=#v2}]])
   +- LogicalTableScan(table=[[default_catalog, default_database, t2, source: [OptionsTableSource(props={k3=#v3, k4=#v4})], dynamic options: {k3=#v3, k4=#v4}]])
]]>
    </Resource>
    <Resource name="planAfter">
      <![CDATA[
Join(joinType=[InnerJoin], where=[=(a, d)], select=[a, b, c, d, e, f], leftInputSpec=[NoUniqueKey], rightInputSpec=[NoUniqueKey])
:- Exchange(distribution=[hash[a]])
:  +- Calc(select=[a, b, +(a, 1) AS c])
:     +- LegacyTableSourceScan(table=[[default_catalog, default_database, t1, source: [OptionsTableSource(props={k1=#v1, k2=#v2})], dynamic options: {k1=#v1, k2=#v2}]], fields=[a, b])
+- Exchange(distribution=[hash[d]])
   +- LegacyTableSourceScan(table=[[default_catalog, default_database, t2, source: [OptionsTableSource(props={k3=#v3, k4=#v4})], dynamic options: {k3=#v3, k4=#v4}]], fields=[d, e, f])
]]>
    </Resource>
  </TestCase>
  <TestCase name="testOptionsHintOnSQLView[1: is-bounded=false]">
    <Resource name="sql">
      <![CDATA[select * from view1/*+ OPTIONS(k1='#v1', k2='#v2', k3='#v3', k4='#v4') */]]>
    </Resource>
    <Resource name="planBefore">
      <![CDATA[
LogicalProject(a=[$0], b=[$1], c=[$2], d=[$3], e=[$4], f=[$5])
+- LogicalJoin(condition=[=($0, $3)], joinType=[inner])
   :- LogicalProject(a=[$0], b=[$1], c=[+($0, 1)])
   :  +- LogicalTableScan(table=[[default_catalog, default_database, t1, source: [OptionsTableSource(props={k1=v1, k2=v2})]]])
   +- LogicalTableScan(table=[[default_catalog, default_database, t2, source: [OptionsTableSource(props={k3=v3, k4=v4})]]])
]]>
    </Resource>
    <Resource name="planAfter">
      <![CDATA[
Join(joinType=[InnerJoin], where=[=(a, d)], select=[a, b, c, d, e, f], leftInputSpec=[NoUniqueKey], rightInputSpec=[NoUniqueKey])
:- Exchange(distribution=[hash[a]])
:  +- Calc(select=[a, b, +(a, 1) AS c])
:     +- LegacyTableSourceScan(table=[[default_catalog, default_database, t1, source: [OptionsTableSource(props={k1=v1, k2=v2})]]], fields=[a, b])
+- Exchange(distribution=[hash[d]])
   +- LegacyTableSourceScan(table=[[default_catalog, default_database, t2, source: [OptionsTableSource(props={k3=v3, k4=v4})]]], fields=[d, e, f])
]]>
    </Resource>
  </TestCase>
  <TestCase name="testOverrideOptions[0: is-bounded=true]">
    <Resource name="sql">
      <![CDATA[select * from t1/*+ OPTIONS(k1='#v1', k2='#v2') */]]>
    </Resource>
    <Resource name="planBefore">
      <![CDATA[
LogicalProject(a=[$0], b=[$1], c=[+($0, 1)])
+- LogicalTableScan(table=[[default_catalog, default_database, t1, source: [OptionsTableSource(props={k1=#v1, k2=#v2})], dynamic options: {k1=#v1, k2=#v2}]])
]]>
    </Resource>
    <Resource name="planAfter">
      <![CDATA[
Calc(select=[a, b, +(a, 1) AS c])
+- LegacyTableSourceScan(table=[[default_catalog, default_database, t1, source: [OptionsTableSource(props={k1=#v1, k2=#v2})], dynamic options: {k1=#v1, k2=#v2}]], fields=[a, b])
]]>
    </Resource>
  </TestCase>
  <TestCase name="testOptionsHintOnSQLView[0: is-bounded=true]">
    <Resource name="sql">
      <![CDATA[select * from view1/*+ OPTIONS(k1='#v1', k2='#v2', k3='#v3', k4='#v4') */]]>
    </Resource>
    <Resource name="planBefore">
      <![CDATA[
LogicalProject(a=[$0], b=[$1], c=[$2], d=[$3], e=[$4], f=[$5])
+- LogicalJoin(condition=[=($0, $3)], joinType=[inner])
   :- LogicalProject(a=[$0], b=[$1], c=[+($0, 1)])
   :  +- LogicalTableScan(table=[[default_catalog, default_database, t1, source: [OptionsTableSource(props={k1=v1, k2=v2})]]])
   +- LogicalTableScan(table=[[default_catalog, default_database, t2, source: [OptionsTableSource(props={k3=v3, k4=v4})]]])
]]>
    </Resource>
    <Resource name="planAfter">
      <![CDATA[
MultipleInput(readOrder=[0,1], members=[\nHashJoin(joinType=[InnerJoin], where=[=(a, d)], select=[a, b, c, d, e, f], build=[right])\n:- Calc(select=[a, b, +(a, 1) AS c])\n:  +- [#2] Exchange(distribution=[hash[a]])\n+- [#1] Exchange(distribution=[hash[d]])\n])
:- Exchange(distribution=[hash[d]])
:  +- LegacyTableSourceScan(table=[[default_catalog, default_database, t2, source: [OptionsTableSource(props={k3=v3, k4=v4})]]], fields=[d, e, f])
+- Exchange(distribution=[hash[a]])
   +- LegacyTableSourceScan(table=[[default_catalog, default_database, t1, source: [OptionsTableSource(props={k1=v1, k2=v2})]]], fields=[a, b])
]]>
    </Resource>
  </TestCase>
  <TestCase name="testOptionsHintOnTableApiView[1: is-bounded=false]">
    <Resource name="sql">
      <![CDATA[select * from view1/*+ OPTIONS(k1='#v1', k2='#v2', k3='#v3', k4='#v4') */]]>
    </Resource>
    <Resource name="planBefore">
      <![CDATA[
LogicalProject(a=[$0], b=[$1], c=[$2], d=[$3], e=[$4], f=[$5])
+- LogicalJoin(condition=[=($0, $3)], joinType=[inner])
   :- LogicalProject(a=[$0], b=[$1], c=[+($0, 1)])
   :  +- LogicalTableScan(table=[[default_catalog, default_database, t1, source: [OptionsTableSource(props={k1=v1, k2=v2})]]])
   +- LogicalTableScan(table=[[default_catalog, default_database, t2, source: [OptionsTableSource(props={k3=v3, k4=v4})]]])
]]>
    </Resource>
    <Resource name="planAfter">
      <![CDATA[
Join(joinType=[InnerJoin], where=[=(a, d)], select=[a, b, c, d, e, f], leftInputSpec=[NoUniqueKey], rightInputSpec=[NoUniqueKey])
:- Exchange(distribution=[hash[a]])
:  +- Calc(select=[a, b, +(a, 1) AS c])
:     +- LegacyTableSourceScan(table=[[default_catalog, default_database, t1, source: [OptionsTableSource(props={k1=v1, k2=v2})]]], fields=[a, b])
+- Exchange(distribution=[hash[d]])
   +- LegacyTableSourceScan(table=[[default_catalog, default_database, t2, source: [OptionsTableSource(props={k3=v3, k4=v4})]]], fields=[d, e, f])
]]>
    </Resource>
  </TestCase>
  <TestCase name="testOverrideOptions[1: is-bounded=false]">
    <Resource name="sql">
      <![CDATA[select * from t1/*+ OPTIONS(k1='#v1', k2='#v2') */]]>
    </Resource>
    <Resource name="planBefore">
      <![CDATA[
LogicalProject(a=[$0], b=[$1], c=[+($0, 1)])
+- LogicalTableScan(table=[[default_catalog, default_database, t1, source: [OptionsTableSource(props={k1=#v1, k2=#v2})], dynamic options: {k1=#v1, k2=#v2}]])
]]>
    </Resource>
    <Resource name="planAfter">
      <![CDATA[
Calc(select=[a, b, +(a, 1) AS c])
+- LegacyTableSourceScan(table=[[default_catalog, default_database, t1, source: [OptionsTableSource(props={k1=#v1, k2=#v2})], dynamic options: {k1=#v1, k2=#v2}]], fields=[a, b])
]]>
    </Resource>
  </TestCase>
</Root>


text:
package xmpptrace.model;

import java.io.InputStream;
import java.util.Iterator;
import java.util.TreeMap;
import java.util.TreeSet;

import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

/**
 * Class to implement the NameSpaceContext interface for XMPP related XPath
 * queries.  This is used throughout the application when instantiating
 * new XPath objects.  It provides a mapping between standard XMPP namespaces
 * and prefixes which can be used in XPath queries.  This mapping is displayed
 * in editable tablular form in the user interface. It is preloaded with
 * namespaces from:
 *
 * http://xmpp.org/registrar/namespaces.xml
 *
 * @author adb
 */
public class XmppNamespaceContext
		implements NamespaceContext
{
	TreeMap<String, String> mPrefix2NsMap;
	TreeMap<String, TreeSet<String>> mNs2PrefixMap;

	private class XmlErrorHandler
			implements ErrorHandler
	{
		public void error(SAXParseException arg0) throws SAXException {}
		public void fatalError(SAXParseException arg0) throws SAXException {}
		public void warning(SAXParseException arg0) throws SAXException {}
	}

	// this class is a singleton
	static XmppNamespaceContext sInstance;
	static
	{
		sInstance = new XmppNamespaceContext();
	}

	/**
	 * Get reference to singleton instance.
	 * @return Reference to singleton instance.
	 */
	static public XmppNamespaceContext getInstance()
	{
		return sInstance;
	}

	/**
	 * Ctor is private, only one instance exists and is returned
	 * by getInstance() method.
	 */
	private XmppNamespaceContext()
	{
		mPrefix2NsMap = new TreeMap<String, String>();
		mNs2PrefixMap = new TreeMap<String, TreeSet<String>>();

		// we add these explicitly, as they are needed by the xmpp augur
		addPrefixNsPair("jc", "jabber:client");
		addPrefixNsPair("jia", "jabber:iq:auth");
		addPrefixNsPair("xmpp-sasl", "urn:ietf:params:xml:ns:xmpp-sasl");
		addPrefixNsPair("xmpp-bind", "urn:ietf:params:xml:ns:xmpp-bind");
		addPrefixNsPair("bosh", "http://jabber.org/protocol/httpbind");
		addPrefixNsPair("xdata", "jabber:x:data");

		// load namespaces.xml downloaded from xmpp.org
		try
		{
			DocumentBuilderFactory factory =
					DocumentBuilderFactory.newInstance();
			factory.setNamespaceAware(true);
			DocumentBuilder builder = factory.newDocumentBuilder();
			builder.setErrorHandler(new XmlErrorHandler());
			InputStream is = getClass().getResourceAsStream("namespaces.xml");
			if (is == null)
			{
			    System.out.println("namespace.xml file not found.");
			    return;
			}
			Document doc = builder.parse(is);

			NodeList namespaces =
					doc.getChildNodes().item(0).getChildNodes();
			int numNamespaces = namespaces.getLength();
			for (int i = 0; i < numNamespaces; ++i)
			{
				Node ns = namespaces.item(i);
				if (!ns.getNodeName().equals("ns")) continue;
				NodeList nsc = ns.getChildNodes();
				for (int j = 0; j < nsc.getLength(); ++j)
				{
					Node name = nsc.item(j);
					if (name.getNodeName().equals("name"))
					{
						addPrefixNsPair("ns" + String.valueOf(i),
								name.getTextContent());
						break;
					}
				}
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

	}

	/**
	 * Inserts a prefix-to-namespace mapping to the context.
	 * @param prefix Prefix string.
	 * @param ns Matching namespace string.
	 */
	public void addPrefixNsPair(String prefix, String ns)
	{
		// update prefix-to-namespace mapping
		String prevNs = mPrefix2NsMap.get(prefix);
		if (prevNs != null)
		{
			mNs2PrefixMap.get(prevNs).remove(prefix);
		}
		mPrefix2NsMap.put(prefix, ns);

		// update namespace-to-prefix mapping
		TreeSet<String> prefixes = mNs2PrefixMap.get(ns);
		if (prefixes == null)
		{
			prefixes = new TreeSet<String>();
			mNs2PrefixMap.put(ns, prefixes);
		}
		prefixes.add(prefix);
	}

	/**
	 * Returns a namespace-to-prefix map.
	 * @return Map of namespaces to prefixes.
	 */
	public TreeMap<String, TreeSet<String>> getPrefixMap()
	{
		return mNs2PrefixMap;
	}

	/**
	 * Returns the namespace corresponding to the given prefix.
	 * @param prefix Prefix for which a namespace is requested.
	 * @return The namespace for the given prefix.
	 */
	@Override
    public String getNamespaceURI(String prefix)
    {
    	String ns = mPrefix2NsMap.get(prefix);
    	if (ns == null)
    	{
    		ns = XMLConstants.NULL_NS_URI;
    	}
    	return ns;
    }

    /**
	 * Returns a prefix corresponding to the given namespace.
	 * @param namespaceURI Namespace for which a prefix is requested.
	 * @return The prefix for the given namespace.
	 */
	@Override
    public String getPrefix(String namespaceURI)
    {
		TreeSet<String> prefixes = mNs2PrefixMap.get(namespaceURI);
		if (prefixes != null)
		{
			return prefixes.first();
		}
		return null;
    }

	/**
	 * Returns an iterator over a set of prefixes which match
	 * the given namespace.
	 * @param namespaceURI Namespace for which prefixes are requested.
	 */
	@Override
    public Iterator<String> getPrefixes(String namespaceURI)
    {
		return mNs2PrefixMap.get(namespaceURI).iterator();
    }
}