text:
package it.com.googlecode.jsu.workflow.function;

import com.atlassian.jira.functest.framework.suite.Category;
import com.atlassian.jira.functest.framework.suite.WebTest;
import com.atlassian.jira.rest.api.issue.IssueFields;
import com.atlassian.jira.rest.api.issue.IssueUpdateRequest;
import com.atlassian.jira.rest.api.issue.ResourceRef;
import com.atlassian.jira.testkit.client.restclient.Issue;
import com.atlassian.jira.testkit.client.restclient.Response;
import org.apache.commons.lang.time.DateUtils;

import java.util.*;

@WebTest({ Category.FUNC_TEST, Category.REST })
public class ValidatorTest extends AbstractTestBase {
    private static final String ISSUE_V10_PASS = "TJP-12";
    private static final String ISSUE_V10_FAIL = "TJP-13";
    private static final String ISSUE_V11_PASS = "TJP-14";
    private static final String ISSUE_V11_FAIL = "TJP-15";
    private static final String ISSUE_V12_PASS = "TJP-16";
    private static final String ISSUE_V12_FAIL = "TJP-17";
    private static final String ISSUE_V13_PASS = "TJP-18";
    private static final String ISSUE_V13_FAIL = "TJP-19";
    private static final String ISSUE_V14_PASS = "TJP-20";
    private static final String ISSUE_V14_FAIL = "TJP-22";
    private static final String ISSUE_V15_PASS = "TJP-23";
    private static final String ISSUE_V15_FAIL = "TJP-21";
    private static final String ISSUE_V16_PASS = "TJP-33";
    private static final String ISSUE_V16_FAIL = "TJP-34";
    private static final String ISSUE_V17_PASS = "TJP-35";
    private static final String ISSUE_V17_FAIL = "TJP-36";
    private static final String ISSUE_V18_PASS = "TJP-37";
    private static final String ISSUE_V18_FAIL = "TJP-38";
    private static final String ISSUE_V19_PASS = "TJP-41";
    private static final String ISSUE_V19_FAIL = "TJP-42";
    private static final String ISSUE_V20_PASS = "TJP-43";
    private static final String ISSUE_V21_PASS = "STJP-1";
    private static final String ISSUE_V21_FAIL = "STJP-2";
    private static final String ISSUE_V22_FAIL = "TJP-44";
    private static final String ISSUE_V23_PASS = "STJP-3";
    private static final String ISSUE_V23_FAIL = "STJP-4";
    private static final String ISSUE_V24_PASS = "TJP-45";
    private static final String ISSUE_V24_FAIL = "TJP-46";
    private static final String ISSUE_V25_PASS = "TJP-47";
    private static final String ISSUE_V25_FAIL = "TJP-48";
    private static final String ISSUE_V26_PASS = "TJP-49";
    private static final String ISSUE_V26_FAIL = "TJP-50";
    private static final String ISSUE_V27_PASS = "TJP-51";
    private static final String ISSUE_V27_FAIL = "TJP-52";

    private static final String TRANSITION_V10 = "1251";
    private static final String TRANSITION_V11 = "1261";
    private static final String TRANSITION_V12 = "1271";
    private static final String TRANSITION_V13 = "1281";
    private static final String TRANSITION_V14 = "1291";
    private static final String TRANSITION_V15 = "1301";
    private static final String TRANSITION_V16 = "1341";
    private static final String TRANSITION_V17 = "1351";
    private static final String TRANSITION_V18 = "1361";
    private static final String TRANSITION_V19 = "1391";
    private static final String TRANSITION_V20 = "1401";
    private static final String TRANSITION_V21 = "1401";
    private static final String TRANSITION_V22 = "1411";
    private static final String TRANSITION_V23 = "1411";
    private static final String TRANSITION_V24 = "1421";
    private static final String TRANSITION_V25 = "1431";
    private static final String TRANSITION_V26 = "1441";
    private static final String TRANSITION_V27 = "1451";

    //Verifies that field DatePicker is less than value of now. Only date part.
    public void testV10Pass() throws Exception {
        Issue issue = issueClient.get(ISSUE_V10_PASS);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        IssueFields issueFields = new IssueFields();
        issueFields.customField(FIELD_DATE_PICKER_ID,DATE_FORMAT.format(DateUtils.addDays(new Date(), -2)));
        issueUpdateRequest.fields(issueFields);
        final Response updateReponse = issueClient.updateResponse(ISSUE_V10_PASS, issueUpdateRequest);
        assertEquals(204, updateReponse.statusCode);

        issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V10));
        final Response response = transitionsClient.postResponse(ISSUE_V10_PASS, issueUpdateRequest);
        assertEquals(204, response.statusCode);

        issue = issueClient.get(ISSUE_V10_PASS);
        assertEquals(STATUS_RESOLVED,issue.fields.status.name());
    }

    //Verifies that field DatePicker is less than value of now. Only date part.
    public void testV10Fail() throws Exception {
        Issue issue = issueClient.get(ISSUE_V10_FAIL);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        IssueFields issueFields = new IssueFields();
        issueFields.customField(FIELD_DATE_PICKER_ID,DATE_FORMAT.format(DateUtils.addDays(new Date(),+2)));
        issueUpdateRequest.fields(issueFields);
        final Response updateReponse = issueClient.updateResponse(ISSUE_V10_FAIL, issueUpdateRequest);
        assertEquals(204, updateReponse.statusCode);

        issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V10));
        final Response response = transitionsClient.postResponse(ISSUE_V10_FAIL, issueUpdateRequest);
        assertEquals(204, response.statusCode);

        issue = issueClient.get(ISSUE_V10_FAIL);
        assertEquals(STATUS_IN_PROGRESS,issue.fields.status.name());
    }

    //Verifies that field DateTime is greater than value of 5d. Including time part.
    public void testV11Pass() throws Exception {
        Issue issue = issueClient.get(ISSUE_V11_PASS);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        IssueFields issueFields = new IssueFields();
        issueFields.customField(FIELD_DATE_TIME_ID,DATE_TIME_FORMAT.format(DateUtils.addDays(new Date(),+6)));
        issueUpdateRequest.fields(issueFields);
        final Response updateReponse = issueClient.updateResponse(ISSUE_V11_PASS, issueUpdateRequest);
        assertEquals(204, updateReponse.statusCode);

        issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V11));
        final Response response = transitionsClient.postResponse(ISSUE_V11_PASS, issueUpdateRequest);
        assertEquals(204, response.statusCode);

        issue = issueClient.get(ISSUE_V11_PASS);
        assertEquals(STATUS_RESOLVED,issue.fields.status.name());
    }

    //Verifies that field DateTime is greater than value of 5d. Including time part.
    public void testV11Fail() throws Exception {
        Issue issue = issueClient.get(ISSUE_V11_FAIL);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        IssueFields issueFields = new IssueFields();
        issueFields.customField(FIELD_DATE_TIME_ID,DATE_TIME_FORMAT.format(DateUtils.addDays(new Date(),+4)));
        issueUpdateRequest.fields(issueFields);
        final Response updateReponse = issueClient.updateResponse(ISSUE_V11_FAIL, issueUpdateRequest);
        assertEquals(204, updateReponse.statusCode);

        issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V11));
        final Response response = transitionsClient.postResponse(ISSUE_V11_FAIL, issueUpdateRequest);
        assertEquals(204, response.statusCode);

        issue = issueClient.get(ISSUE_V11_FAIL);
        assertEquals(STATUS_IN_PROGRESS,issue.fields.status.name());
    }

    //Verifies that field DatePicker is less than value of -1m. Only date part.
    public void testV12Pass() throws Exception {
        Issue issue = issueClient.get(ISSUE_V12_PASS);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        IssueFields issueFields = new IssueFields();
        issueFields.customField(FIELD_DATE_PICKER_ID,DATE_FORMAT.format(DateUtils.addDays(new Date(),-40)));
        issueUpdateRequest.fields(issueFields);
        final Response updateReponse = issueClient.updateResponse(ISSUE_V12_PASS, issueUpdateRequest);
        assertEquals(204, updateReponse.statusCode);

        issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V12));
        final Response response = transitionsClient.postResponse(ISSUE_V12_PASS, issueUpdateRequest);
        assertEquals(204, response.statusCode);

        issue = issueClient.get(ISSUE_V12_PASS);
        assertEquals(STATUS_RESOLVED,issue.fields.status.name());
    }

    //Verifies that field DatePicker is less than value of -1m. Only date part.
    public void testV12Fail() throws Exception {
        Issue issue = issueClient.get(ISSUE_V12_FAIL);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        IssueFields issueFields = new IssueFields();
        issueFields.customField(FIELD_DATE_PICKER_ID,DATE_FORMAT.format(DateUtils.addDays(new Date(),-25)));
        issueUpdateRequest.fields(issueFields);
        final Response updateReponse = issueClient.updateResponse(ISSUE_V12_FAIL, issueUpdateRequest);
        assertEquals(204, updateReponse.statusCode);

        issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V12));
        final Response response = transitionsClient.postResponse(ISSUE_V12_FAIL, issueUpdateRequest);
        assertEquals(204, response.statusCode);

        issue = issueClient.get(ISSUE_V12_FAIL);
        assertEquals(STATUS_IN_PROGRESS,issue.fields.status.name());
    }

    //Verifies that field DatePicker is greater than or equal to value of 1w. Only date part.
    public void testV13Pass() throws Exception {
        Issue issue = issueClient.get(ISSUE_V13_PASS);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        IssueFields issueFields = new IssueFields();
        issueFields.customField(FIELD_DATE_PICKER_ID,DATE_FORMAT.format(DateUtils.addDays(new Date(),7)));
        issueUpdateRequest.fields(issueFields);
        final Response updateReponse = issueClient.updateResponse(ISSUE_V13_PASS, issueUpdateRequest);
        assertEquals(204, updateReponse.statusCode);

        issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V13));
        final Response response = transitionsClient.postResponse(ISSUE_V13_PASS, issueUpdateRequest);
        assertEquals(204, response.statusCode);

        issue = issueClient.get(ISSUE_V13_PASS);
        assertEquals(STATUS_RESOLVED,issue.fields.status.name());
    }

    //Verifies that field DatePicker is greater than or equal to value of 1w. Only date part.
    public void testV13Fail() throws Exception {
        Issue issue = issueClient.get(ISSUE_V13_FAIL);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        IssueFields issueFields = new IssueFields();
        issueFields.customField(FIELD_DATE_PICKER_ID,DATE_FORMAT.format(DateUtils.addDays(new Date(),6)));
        issueUpdateRequest.fields(issueFields);
        final Response updateReponse = issueClient.updateResponse(ISSUE_V13_FAIL, issueUpdateRequest);
        assertEquals(204, updateReponse.statusCode);

        issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V13));
        final Response response = transitionsClient.postResponse(ISSUE_V13_FAIL, issueUpdateRequest);
        assertEquals(204, response.statusCode);

        issue = issueClient.get(ISSUE_V13_FAIL);
        assertEquals(STATUS_IN_PROGRESS,issue.fields.status.name());
    }

    //Verifies that field DatePicker is not equal to value of now. Only date part.
    public void testV14Pass() throws Exception {
        Issue issue = issueClient.get(ISSUE_V14_PASS);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        IssueFields issueFields = new IssueFields();
        issueFields.customField(FIELD_DATE_PICKER_ID,DATE_FORMAT.format(DateUtils.addDays(new Date(),1)));
        issueUpdateRequest.fields(issueFields);
        final Response updateReponse = issueClient.updateResponse(ISSUE_V14_PASS, issueUpdateRequest);
        assertEquals(204, updateReponse.statusCode);

        issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V14));
        final Response response = transitionsClient.postResponse(ISSUE_V14_PASS, issueUpdateRequest);
        assertEquals(204, response.statusCode);

        issue = issueClient.get(ISSUE_V14_PASS);
        assertEquals(STATUS_RESOLVED,issue.fields.status.name());
    }

    //Verifies that field DatePicker is not equal to value of now. Only date part.
    public void testV14Fail() throws Exception {
        Issue issue = issueClient.get(ISSUE_V14_FAIL);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        IssueFields issueFields = new IssueFields();
        issueFields.customField(FIELD_DATE_PICKER_ID,DATE_FORMAT.format(new Date()));
        issueUpdateRequest.fields(issueFields);
        final Response updateReponse = issueClient.updateResponse(ISSUE_V14_FAIL, issueUpdateRequest);
        assertEquals(204, updateReponse.statusCode);

        issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V14));
        final Response response = transitionsClient.postResponse(ISSUE_V14_FAIL, issueUpdateRequest);
        assertEquals(204, response.statusCode);

        issue = issueClient.get(ISSUE_V14_FAIL);
        assertEquals(STATUS_IN_PROGRESS,issue.fields.status.name());
    }

    //Verifies that field DatePicker is greater than value of 1y. Only date part.
    public void testV15pass() throws Exception {
        Issue issue = issueClient.get(ISSUE_V15_PASS);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        IssueFields issueFields = new IssueFields();
        issueFields.customField(FIELD_DATE_PICKER_ID,DATE_FORMAT.format(DateUtils.addDays(new Date(),370)));
        issueUpdateRequest.fields(issueFields);
        final Response updateReponse = issueClient.updateResponse(ISSUE_V15_PASS, issueUpdateRequest);
        assertEquals(204, updateReponse.statusCode);

        issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V15));
        final Response response = transitionsClient.postResponse(ISSUE_V15_PASS, issueUpdateRequest);
        assertEquals(204, response.statusCode);

        issue = issueClient.get(ISSUE_V15_PASS);
        assertEquals(STATUS_RESOLVED,issue.fields.status.name());
    }

    //Verifies that field DatePicker is greater than value of 1y. Only date part.
    public void testV15Fail() throws Exception {
        Issue issue = issueClient.get(ISSUE_V15_FAIL);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        IssueFields issueFields = new IssueFields();
        issueFields.customField(FIELD_DATE_PICKER_ID,DATE_FORMAT.format(DateUtils.addDays(new Date(),350)));
        issueUpdateRequest.fields(issueFields);
        final Response updateReponse = issueClient.updateResponse(ISSUE_V15_FAIL, issueUpdateRequest);
        assertEquals(204, updateReponse.statusCode);

        issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V15));
        final Response response = transitionsClient.postResponse(ISSUE_V15_FAIL, issueUpdateRequest);
        assertEquals(204, response.statusCode);

        issue = issueClient.get(ISSUE_V15_FAIL);
        assertEquals(STATUS_IN_PROGRESS,issue.fields.status.name());
    }

    //The field TextField its contents must match against the regular expression ^[ABC][qwer]+[0-9]{3}
    public void testV16pass() throws Exception {
        Issue issue = issueClient.get(ISSUE_V16_PASS);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V16));

        final Response reponse = transitionsClient.postResponse(ISSUE_V16_PASS, issueUpdateRequest);
        assertEquals(204, reponse.statusCode);

        issue = issueClient.get(ISSUE_V16_PASS);
        assertEquals(STATUS_RESOLVED,issue.fields.status.name());
    }

    //The field TextField its contents must match against the regular expression ^[ABC][qwer]+[0-9]{3}
    public void testV16fail() throws Exception {
        Issue issue = issueClient.get(ISSUE_V16_FAIL);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V16));

        final Response reponse = transitionsClient.postResponse(ISSUE_V16_FAIL, issueUpdateRequest);
        assertEquals(204, reponse.statusCode);

        issue = issueClient.get(ISSUE_V16_FAIL);
        assertEquals(STATUS_IN_PROGRESS,issue.fields.status.name());
    }

    //The field NumberField its contents must match against the regular expression [0-4]{5}\.0
    public void testV17pass() throws Exception {
        Issue issue = issueClient.get(ISSUE_V17_PASS);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V17));

        final Response reponse = transitionsClient.postResponse(ISSUE_V17_PASS, issueUpdateRequest);
        assertEquals(204, reponse.statusCode);

        issue = issueClient.get(ISSUE_V17_PASS);
        assertEquals(STATUS_RESOLVED,issue.fields.status.name());
    }

    //The field NumberField its contents must match against the regular expression [0-4]{5}\.0
    public void testV17fail() throws Exception {
        Issue issue = issueClient.get(ISSUE_V17_FAIL);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V17));

        final Response reponse = transitionsClient.postResponse(ISSUE_V17_FAIL, issueUpdateRequest);
        assertEquals(204, reponse.statusCode);

        issue = issueClient.get(ISSUE_V17_FAIL);
        assertEquals(STATUS_IN_PROGRESS,issue.fields.status.name());
    }

    //The field URLField its contents must match against the regular expression http://[w]{3}\.[a-z]*\.ch
    public void testV18pass() throws Exception {
        Issue issue = issueClient.get(ISSUE_V18_PASS);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V18));

        final Response reponse = transitionsClient.postResponse(ISSUE_V18_PASS, issueUpdateRequest);
        assertEquals(204, reponse.statusCode);

        issue = issueClient.get(ISSUE_V18_PASS);
        assertEquals(STATUS_RESOLVED,issue.fields.status.name());
    }

    //The field URLField its contents must match against the regular expression http://[w]{3}\.[a-z]*\.ch
    public void testV18fail() throws Exception {
        Issue issue = issueClient.get(ISSUE_V18_FAIL);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V18));

        final Response reponse = transitionsClient.postResponse(ISSUE_V18_FAIL, issueUpdateRequest);
        assertEquals(204, reponse.statusCode);

        issue = issueClient.get(ISSUE_V18_FAIL);
        assertEquals(STATUS_IN_PROGRESS,issue.fields.status.name());
    }

    //Required fields: Σ Time Spent
    public void testV19pass() throws Exception {
        Issue issue = issueClient.get(ISSUE_V19_PASS);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V19));

        final Response reponse = transitionsClient.postResponse(ISSUE_V19_PASS, issueUpdateRequest);
        assertEquals(204, reponse.statusCode);

        issue = issueClient.get(ISSUE_V19_PASS);
        assertEquals(STATUS_RESOLVED,issue.fields.status.name());
    }

    //Required fields: Σ Time Spent
    public void testV19fail() throws Exception {
        Issue issue = issueClient.get(ISSUE_V19_FAIL);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V19));

        final Response reponse = transitionsClient.postResponse(ISSUE_V19_FAIL, issueUpdateRequest);
        assertEquals(204, reponse.statusCode);

        issue = issueClient.get(ISSUE_V19_FAIL);
        assertEquals(STATUS_IN_PROGRESS,issue.fields.status.name());
    }

    //Required fields: Textfield2
    public void testV20pass() throws Exception {
        Issue issue = issueClient.get(ISSUE_V20_PASS);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V20));

        final Response reponse = transitionsClient.postResponse(ISSUE_V20_PASS, issueUpdateRequest);
        assertEquals(204, reponse.statusCode);

        issue = issueClient.get(ISSUE_V20_PASS);
        assertEquals(STATUS_RESOLVED,issue.fields.status.name());
    }

    //Required fields: Textfield2
    public void testV21pass() throws Exception {
        Issue issue = issueClient.get(ISSUE_V21_PASS);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V21));

        final Response reponse = transitionsClient.postResponse(ISSUE_V21_PASS, issueUpdateRequest);
        assertEquals(204, reponse.statusCode);

        issue = issueClient.get(ISSUE_V21_PASS);
        assertEquals(STATUS_RESOLVED,issue.fields.status.name());
    }

    //Required fields: Textfield2
    public void testV21fail() throws Exception {
        Issue issue = issueClient.get(ISSUE_V21_FAIL);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V21));

        final Response reponse = transitionsClient.postResponse(ISSUE_V21_FAIL, issueUpdateRequest);
        assertEquals(204, reponse.statusCode);

        issue = issueClient.get(ISSUE_V21_FAIL);
        assertEquals(STATUS_IN_PROGRESS,issue.fields.status.name());
    }

    //Required fields (ignoring context): Textfield2
    public void testV22fail() throws Exception {
        Issue issue = issueClient.get(ISSUE_V22_FAIL);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V22));

        final Response reponse = transitionsClient.postResponse(ISSUE_V22_FAIL, issueUpdateRequest);
        assertEquals(204, reponse.statusCode);

        issue = issueClient.get(ISSUE_V22_FAIL);
        assertEquals(STATUS_IN_PROGRESS,issue.fields.status.name());
    }

    //Required fields (ignoring context): Textfield2
    public void testV23pass() throws Exception {
        Issue issue = issueClient.get(ISSUE_V23_PASS);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V23));

        final Response reponse = transitionsClient.postResponse(ISSUE_V23_PASS, issueUpdateRequest);
        assertEquals(204, reponse.statusCode);

        issue = issueClient.get(ISSUE_V23_PASS);
        assertEquals(STATUS_RESOLVED,issue.fields.status.name());
    }

    //Required fields (ignoring context): Textfield2
    public void testV23fail() throws Exception {
        Issue issue = issueClient.get(ISSUE_V23_FAIL);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V23));

        final Response reponse = transitionsClient.postResponse(ISSUE_V23_FAIL, issueUpdateRequest);
        assertEquals(204, reponse.statusCode);

        issue = issueClient.get(ISSUE_V23_FAIL);
        assertEquals(STATUS_IN_PROGRESS,issue.fields.status.name());
    }

    //The field SelectList its contents must match against the regular expression Option B
    public void testV24pass() throws Exception {
        Issue issue = issueClient.get(ISSUE_V24_PASS);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V24));

        final Response reponse = transitionsClient.postResponse(ISSUE_V24_PASS, issueUpdateRequest);
        assertEquals(204, reponse.statusCode);

        issue = issueClient.get(ISSUE_V24_PASS);
        assertEquals(STATUS_RESOLVED,issue.fields.status.name());
    }

    //The field SelectList its contents must match against the regular expression Option B
    public void testV24fail() throws Exception {
        Issue issue = issueClient.get(ISSUE_V24_FAIL);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V24));

        final Response reponse = transitionsClient.postResponse(ISSUE_V24_FAIL, issueUpdateRequest);
        assertEquals(204, reponse.statusCode);

        issue = issueClient.get(ISSUE_V24_FAIL);
        assertEquals(STATUS_IN_PROGRESS,issue.fields.status.name());
    }

    //The field RadioButtons its contents must match against the regular expression Option C
    public void testV25pass() throws Exception {
        Issue issue = issueClient.get(ISSUE_V25_PASS);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V25));

        final Response reponse = transitionsClient.postResponse(ISSUE_V25_PASS, issueUpdateRequest);
        assertEquals(204, reponse.statusCode);

        issue = issueClient.get(ISSUE_V25_PASS);
        assertEquals(STATUS_RESOLVED,issue.fields.status.name());
    }

    //The field RadioButtons its contents must match against the regular expression Option C
    public void testV25fail() throws Exception {
        Issue issue = issueClient.get(ISSUE_V25_FAIL);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V25));

        final Response reponse = transitionsClient.postResponse(ISSUE_V25_FAIL, issueUpdateRequest);
        assertEquals(204, reponse.statusCode);

        issue = issueClient.get(ISSUE_V25_FAIL);
        assertEquals(STATUS_IN_PROGRESS,issue.fields.status.name());
    }

    //The field MultiCheckboxes its contents must match against the regular expression Option [B,C]
    public void testV26pass() throws Exception {
        Issue issue = issueClient.get(ISSUE_V26_PASS);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V26));

        final Response reponse = transitionsClient.postResponse(ISSUE_V26_PASS, issueUpdateRequest);
        assertEquals(204, reponse.statusCode);

        issue = issueClient.get(ISSUE_V26_PASS);
        assertEquals(STATUS_RESOLVED,issue.fields.status.name());
    }

    //The field MultiCheckboxes its contents must match against the regular expression Option [B,C]
    public void testV26fail() throws Exception {
        Issue issue = issueClient.get(ISSUE_V26_FAIL);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V26));

        final Response reponse = transitionsClient.postResponse(ISSUE_V26_FAIL, issueUpdateRequest);
        assertEquals(204, reponse.statusCode);

        issue = issueClient.get(ISSUE_V26_FAIL);
        assertEquals(STATUS_IN_PROGRESS,issue.fields.status.name());
    }

    //The field MultiSelect its contents must match against the regular expression Option [A,B]
    public void testV27pass() throws Exception {
        Issue issue = issueClient.get(ISSUE_V27_PASS);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V27));

        final Response reponse = transitionsClient.postResponse(ISSUE_V27_PASS, issueUpdateRequest);
        assertEquals(204, reponse.statusCode);

        issue = issueClient.get(ISSUE_V27_PASS);
        assertEquals(STATUS_RESOLVED,issue.fields.status.name());
    }

    //The field MultiSelect its contents must match against the regular expression Option [A,B]
    public void testV27fail() throws Exception {
        Issue issue = issueClient.get(ISSUE_V27_FAIL);
        assertNotNull(issue);

        IssueUpdateRequest issueUpdateRequest = new IssueUpdateRequest();
        issueUpdateRequest.fields(new IssueFields());
        issueUpdateRequest.transition(ResourceRef.withId(TRANSITION_V27));

        final Response reponse = transitionsClient.postResponse(ISSUE_V27_FAIL, issueUpdateRequest);
        assertEquals(204, reponse.statusCode);

        issue = issueClient.get(ISSUE_V27_FAIL);
        assertEquals(STATUS_IN_PROGRESS,issue.fields.status.name());
    }
}


text:
using System;
using System.ComponentModel.Composition;
using System.Text.RegularExpressions;
using Microsoft.PythonTools.Analysis;
using Microsoft.PythonTools.BuildTasks;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Interpreter;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudioTools.Project;

namespace Microsoft.PythonTools.Project.Web {
    [Export(typeof(IPythonLauncherProvider))]
    class PythonWebLauncherProvider : IPythonLauncherProvider2 {
        private readonly PythonToolsService _pyService;
        private readonly IServiceProvider _serviceProvider;

        private static readonly Regex SubstitutionPattern = new Regex(@"\{([\w_]+)\}");

        [ImportingConstructor]
        public PythonWebLauncherProvider([Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider) {
            _serviceProvider = serviceProvider;
            _pyService = serviceProvider.GetPythonToolsService();
        }

        public IPythonLauncherOptions GetLauncherOptions(IPythonProject properties) {
            return new PythonWebLauncherOptions(properties);
        }

        public string Name => PythonConstants.WebLauncherName;
        public string LocalizedName => Strings.PythonWebLauncherName;
        public string Description => Strings.PythonWebLauncherDescription;
        public int SortPriority => 100;

        internal static string DoSubstitutions(LaunchConfiguration original, IPythonProject project, string str) {
            if (string.IsNullOrEmpty(str)) {
                return str;
            }

            return SubstitutionPattern.Replace(
                str,
                m => {
                    switch (m.Groups[1].Value.ToLowerInvariant()) {
                        case "startupfile":
                            return original.ScriptName;
                        case "startupmodule":
                            try {
                                return ModulePath.FromFullPath(original.ScriptName, project.ProjectHome).ModuleName;
                            } catch (ArgumentException) {
                            }
                            break;
                    }
                    return m.Value;
                }
            );
        }

        private static LaunchConfiguration GetMSBuildCommandConfig(
            LaunchConfiguration original,
            IPythonProject project,
            string targetProperty,
            string targetTypeProperty,
            string argumentsProperty,
            string environmentProperty
        ) {
            var target = DoSubstitutions(original, project, project.GetProperty(targetProperty));
            if (string.IsNullOrEmpty(target)) {
                target = original.ScriptName;
            }

            var targetType = project.GetProperty(targetTypeProperty);
            if (string.IsNullOrEmpty(targetType)) {
                targetType = PythonCommandTask.TargetTypeScript;
            }

            var config = original.Clone();
            if (PythonCommandTask.TargetTypeModule.Equals(targetType, StringComparison.OrdinalIgnoreCase)) {
                if (string.IsNullOrEmpty(config.InterpreterArguments)) {
                    config.InterpreterArguments = "-m " + target;
                } else {
                    config.InterpreterArguments = config.InterpreterArguments + " -m " + target;
                }
            } else if (PythonCommandTask.TargetTypeExecutable.Equals(targetType, StringComparison.OrdinalIgnoreCase)) {
                config.InterpreterPath = target;
            } else {
                config.ScriptName = target;
            }

            var args = DoSubstitutions(original, project, project.GetProperty(argumentsProperty));
            if (!string.IsNullOrEmpty(args)) {
                if (string.IsNullOrEmpty(config.ScriptArguments)) {
                    config.ScriptArguments = args;
                } else {
                    config.ScriptArguments = config.ScriptArguments + " " + args;
                }
            }

            var env = DoSubstitutions(original, project, project.GetProperty(environmentProperty));
            config.Environment = PathUtils.MergeEnvironments(config.Environment, PathUtils.ParseEnvironment(env));

            return config;
        }

        public IProjectLauncher CreateLauncher(IPythonProject project) {
            var defaultConfig = project.GetLaunchConfigurationOrThrow();

            var runConfig = GetMSBuildCommandConfig(
                defaultConfig,
                project,
                PythonWebLauncher.RunWebServerTargetProperty,
                PythonWebLauncher.RunWebServerTargetTypeProperty,
                PythonWebLauncher.RunWebServerArgumentsProperty,
                PythonWebLauncher.RunWebServerEnvironmentProperty
            );
            var debugConfig = GetMSBuildCommandConfig(
                defaultConfig,
                project,
                PythonWebLauncher.DebugWebServerTargetProperty,
                PythonWebLauncher.DebugWebServerTargetTypeProperty,
                PythonWebLauncher.DebugWebServerArgumentsProperty,
                PythonWebLauncher.DebugWebServerEnvironmentProperty
            );

            // Check project type GUID and enable the Django-specific features
            // of the debugger if required.
            var projectGuids = project.GetUnevaluatedProperty("ProjectTypeGuids") ?? "";
            // HACK: Literal GUID string to avoid introducing Django-specific public API
            // We don't want to expose a constant from PythonTools.dll.
            // TODO: Add generic breakpoint extension point
            // to avoid having to pass this property for Django and any future
            // extensions.
            if (projectGuids.IndexOf("5F0BE9CA-D677-4A4D-8806-6076C0FAAD37", StringComparison.OrdinalIgnoreCase) >= 0) {
                debugConfig.LaunchOptions["DjangoDebug"] = "true";
                defaultConfig.LaunchOptions["DjangoDebug"] = "true";
            }

            return new PythonWebLauncher(_serviceProvider, runConfig, debugConfig, defaultConfig);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
"""Pylint integration to Pylama."""
import logging
from argparse import ArgumentParser
from os import environ
from pathlib import Path
from typing import Dict

from pylint.interfaces import CONFIDENCE_LEVELS
from pylint.lint import Run
from pylint.reporters import BaseReporter

from pylama.context import RunContext
from pylama.lint import LinterV2 as BaseLinter

HOME_RCFILE = Path(environ.get("HOME", "")) / ".pylintrc"

logger = logging.getLogger("pylama")

class Linter(BaseLinter):
    """Check code with Pylint."""

    name = "pylint"

    @classmethod
    def add_args(cls, parser: ArgumentParser):
        """Add --max-complexity option."""
        parser.add_argument(
            "--pylint-confidence",
            choices=[cc.name for cc in CONFIDENCE_LEVELS],
            help="Only show warnings with the listed confidence levels.",
        )

    def run_check(self, ctx: RunContext):
        """Pylint code checking."""
        logger.debug("Start pylint")
        params = ctx.get_params("pylint")
        options = ctx.options
        if options:
            params.setdefault("max_line_length", options.max_line_length)
            params.setdefault("confidence", options.pylint_confidence)

        params.setdefault("enable", ctx.select | ctx.get_filter("pylint", "select"))
        params.setdefault("disable", ctx.ignore | ctx.get_filter("pylint", "ignore"))
        # if params.get("disable"):
        #     params["disable"].add("W0012")

        class Reporter(BaseReporter):
            """Handle messages."""

            def _display(self, _):
                pass

            def handle_message(self, msg):
                msg_id = msg.msg_id
                ctx.push(
                    filtrate=False,
                    col=msg.column + 1,
                    lnum=msg.line,
                    number=msg_id,
                    text=msg.msg,
                    type=msg_id[0],
                    source="pylint",
                )

        logger.debug(params)

        reporter = Reporter()
        args = _Params(params).to_attrs()
        Run([ctx.temp_filename] + args, reporter=reporter, exit=False)

class _Params:
    """Store pylint params."""

    def __init__(self, params: Dict):
        attrs = {
            name.replace("_", "-"): self.prepare_value(value)
            for name, value in params.items()
            if value
        }
        if HOME_RCFILE.exists():
            attrs["rcfile"] = HOME_RCFILE.as_posix()

        if attrs.get("disable"):
            attrs["disable"] += ",W0012"
        else:
            attrs["disable"] = "W0012"

        self.attrs = attrs

    @staticmethod
    def prepare_value(value):
        """Prepare value to pylint."""
        if isinstance(value, (list, tuple, set)):
            return ",".join(value)

        if isinstance(value, bool):
            return "y" if value else "n"

        return str(value)

    def to_attrs(self):
        """Convert to argument list."""
        return [f"--{key}={value}" for key, value in self.attrs.items()]  # noqa

    def __str__(self):
        return " ".join(self.to_attrs())

    def __repr__(self):
        return f"<Pylint {self}>"

# pylama:ignore=W0403


text:
package com.flowci.core.job.event;

import com.flowci.core.agent.domain.TtyCmd;
import lombok.Getter;
import org.springframework.context.ApplicationEvent;

@Getter
public class TtyStatusUpdateEvent extends ApplicationEvent {

    private final TtyCmd.Out out;

    public TtyStatusUpdateEvent(Object source, TtyCmd.Out out) {
        super(source);
        this.out = out;
    }
}


text:
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';

import { AppConfig } from '../app.config';
import { Radio } from '../models/index';

@Injectable()
export class RadioService {
    constructor(private http: Http, private config: AppConfig) { }

    // getAll() {
    //     return this.http.get(this.config.apiUrl + '/radios/getAllUsers', this.jwt()).map((response: Response) => response.json());
    // }

    // getById(_id: string) {
    //     return this.http.get(this.config.apiUrl + '/radios/' + _id, this.jwt()).map((response: Response) => response.json());
    // }

    create(radio: Radio) {
        return this.http.post(this.config.apiUrl + '/radios/addradio', radio);
    }

    // update(radio: Radio) {
    //     return this.http.put(this.config.apiUrl + '/radios/' + radio._id, radio, this.jwt());
    // }

    // delete(_id: string) {
    //     return this.http.delete(this.config.apiUrl + '/radios/' + _id, this.jwt());
    // }

    // private helper methods

    // private jwt() {
    //     // create authorization header with jwt token
    //     let currentUser = JSON.parse(localStorage.getItem('currentUser'));
    //     if (currentUser && currentUser.token) {
    //         let headers = new Headers({ 'Authorization': 'Bearer ' + currentUser.token });
    //         return new RequestOptions({ headers: headers });
    //     }
    // }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: root
 * Date: 7/20/16
 * Time: 3:47 PM
 */

namespace Masca\PersonnelBundle\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class StatusType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('etablisement', ChoiceType::class,[
                'label'=>'Etablissement',
                'placeholder'=>'Choisissez',
                'choices_as_values'=>true,
                'choices'=>["Université"=>"universite", "Lycée"=>"lycee"]
            ])
            ->add('typePoste', ChoiceType::class, [
                'label'=>'Type de poste',
                'placeholder'=>'Choisissez..',
                'choices_as_values'=>true,
                'choices'=>['Enseignant'=>'prof','Autre'=>'autre']
            ])
            ->add('typeSalaire', ChoiceType::class, [
                'label'=>'Mode de payement',
                'placeholder'=>'Choisissez..',
                'choices_as_values'=>true,
                'choices'=> ["Salaire fixe" => "fixe", "Volume horaire" => "heure"]
            ])
            ->add('dateEmbauche',DateType::class,[
                'label'=>'Embaucher le',
                'format'=>'dd MMMM yyyy',
                'years'=>range(date('Y')-50,date('Y')+2),
                'placeholder'=>array('year'=>'Année','day'=>'Jour','month'=>'Mois')
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
       $resolver->setDefaults([
           'data_class'=>'Masca\PersonnelBundle\Entity\Status',
           'trait_choices'=>null
       ]);
    }

}


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

    <import resource="classpath:CONNECT-interceptor-beans.xml" />
    <context:property-placeholder />
    <cxf:bus>
        <cxf:features>
            <p:policies />
        </cxf:features>
    </cxf:bus>

    <!-- Admin Distribution -->

    <jaxws:endpoint xmlns:tns="urn:gov:hhs:fha:nhinc:adapteradmindistribution" id="AdapterAdministrativeDistributionSecured"
        address="/AdapterAdministrativeDistributionSecured" serviceName="tns:Adapter_AdministrativeDistributionSecured"
        endpointName="tns:Adapter_AdministrativeDistributionSecured_PortType" implementor="gov.hhs.fha.nhinc.admindistribution.adapter.AdapterAdministrativeDistributionSecured"
        wsdlLocation="classpath:wsdl/AdapterAdminDistSecured.wsdl">
        <jaxws:properties>
            <entry key="ws-security.signature.properties" value="file:///${nhinc.properties.dir}/signature.properties" />
            <entry key="ws-security.encryption.properties" value="file:///${nhinc.properties.dir}/truststore.properties" />
            <entry key="mtom-enabled" value="true" />
            <entry key="ws-security.timestamp.validator">
                <bean class="gov.hhs.fha.nhinc.callback.cxf.largefile.TimestampValidator" />
            </entry>
            <entry key="ws-security.saml2.validator">
                <bean class="gov.hhs.fha.nhinc.callback.cxf.CONNECTSamlAssertionValidator" />
            </entry>
            <entry key="ws-security.enable.timestamp.cache" value="false" />
        </jaxws:properties>
        <jaxws:inInterceptors>
            <ref bean="timestampInInterceptor" />
        </jaxws:inInterceptors>
        <jaxws:outFaultInterceptors>
            <ref bean="attachmentFaultOutInterceptor" />
        </jaxws:outFaultInterceptors>
    </jaxws:endpoint>

    <jaxws:endpoint xmlns:tns="urn:gov:hhs:fha:nhinc:adapteradmindistribution" id="AdapterAdministrativeDistribution"
        address="/AdapterAdministrativeDistribution" serviceName="tns:Adapter_AdministrativeDistribution" endpointName="tns:Adapter_AdministrativeDistribution_PortType"
        implementor="gov.hhs.fha.nhinc.admindistribution.adapter.AdapterAdministrativeDistribution" wsdlLocation="classpath:wsdl/AdapterAdminDist.wsdl">
        <jaxws:properties>
            <entry key="mtom-enabled" value="true" />
        </jaxws:properties>
    </jaxws:endpoint>

</beans>


text:
This Pentaho SSO Extension is intended to provide Single Sign-On setup for Pentaho Platform using OAuth/OIDC "Authorization Code" grant flow with OS OAuth/OIDC certified server (this version was tested with MITREid 1.2.0 and WSO2 IS 5.1.0).
This project is mainly based on code and documentation, developed by **https://bitbucket.org/secureops/sops-pentaho**, so refer to it if you want more info/features (like **SAML/SSO**, classic **Openid**, classic **OAuth**) using social IdP provider (**google, facebook, linkedin, twitter**) - this features was removed by my custom implementation (not necessary for my company requirements).

SSO extension allows to configure any number of Identity Providers, defining the list of Pentaho Roles for each "users channel" separately. Pentaho's own Authentication functionality can be also kept active if needed.

The extension is tested with: **Pentaho BI Server 5.4.0 CE**, **MITREid 1.2.3** (https://github.com/mitreid-connect/OpenID-Connect-Java-Spring-Server), **WSO2 IS 5.1.0** (http://wso2.com).

The instruction below intends that you have Pentaho platform installed and configured, one OAuth/OIDC server (MITREid or WSO2 IS).

##Compilation

To make it simpler, needed external libraries are included into embedded lib directory. All other dependences are related to Pentaho and Spring, and are available in assembled Pentaho platform.

Compilation requires the following packages coming with Pentaho:

-   Pentaho Core, API and Extensions packages (3 jars: **pentaho-platform-extensions-TRUNK-SNAPSHOT.jar**, **pentaho-platform-api-TRUNK-SNAPSHOT.jar**, **pentaho-platform-core-TRUNK-SNAPSHOT.jar**)
-   Spring Core (**spring-2.5.6.jar**)
-   Spring Security Core (**spring-security-core-2.0.5.RELEASE.jar**)
-   SLF4J (**slf4j-api-1.7.3.jar**)
-   ServletAPI (**servlet-api.jar** - is the only jar which is not available in Pentaho lib, but it is always coming with any Java Container)

In case of compiling the package using Apache Ant, please correct the needed paths in the **build.xml** provided (see the comments in build.xml file).

##Deployment

Ant script releases **com.arena.sso-1.x.jar** file in the dist directory, together with needed libraries copied. To deploy the extension, all the jar files from **dist** directory should be simply copied into Pentaho lib directory.

***
##Configuration

**1.** Configure *AuthenticationProcessingFilter*, *AuthenticationProvider*, *Consumer* and *AuthenticationEntryPoint* (this one was not required for OpenId because of embedded support by Spring) beans for OAuth/OIDC in **applicationContext-spring-security.xml** like the following:
```xml
<bean id="oauthAuthenticationProcessingFilter" class="com.arena.sso.oidc.OAuthAuthenticationProcessingFilter">
	<property name="authenticationManager">
		<bean id="oauthAuthenticationManager" class="org.springframework.security.providers.ProviderManager">
			<property name="providers">
				<list>
					<ref local="oauthAuthenticationProvider" />
				</list>
			</property>
		</bean>
	</property>
	<property name="consumer" ref="oauthConsumer" />
	<property name="defaultTargetUrl" value="/Home" />
	<property name="authenticationFailureUrl" value="/Login?login_error=1" />
	<property name="targetUrlResolver">
		<ref local="targetUrlResolver" />
	</property>
</bean>
```

```xml
<bean id="oauthAuthenticationProvider" class="com.arena.sso.oidc.OAuthAuthenticationProvider">
	<property name="userDetailsService" ref="oauthUserDetailsService" />
</bean>
```

```xml
<bean id="oauthConsumer" class="com.arena.sso.oidc.consumer.OAuthConsumerImpl">
	<constructor-arg index="0" value="${oauth.redirectUrl}"/>
	<!-- custom property for MITRE-OPENID server -->
	<property name="mitreoidConsumerKey" value="${oauth.mitreoidConsumerKey}"/>
	<property name="mitreoidConsumerSecret" value="${oauth.mitreoidConsumerSecret}"/>
	<property name="mitreoidTokenRequestUri" value="${oauth.mitreoidTokenRequestUri}"/>
	<property name="mitreoidAccessTokenUri" value="${oauth.mitreoidAccessTokenUri}"/>
	<property name="mitreoidAuthenticationTokenUri" value="${oauth.mitreoidAuthenticationTokenUri}"/>
	<property name="mitreOpenIdClaim" value="${oauth.mitreOpenIdClaim}"/>
	<!-- end MITRE-OPENID server -->

	<!-- custom property for WSO2 IS-Oauth server -->
	<property name="wso2isConsumerKey" value="${oauth.wso2isConsumerKey}"/>
	<property name="wso2isConsumerSecret" value="${oauth.wso2isConsumerSecret}"/>
	<property name="wso2isTokenRequestUri" value="${oauth.wso2isTokenRequestUri}"/>
	<property name="wso2isAccessTokenUri" value="${oauth.wso2isAccessTokenUri}"/>
	<property name="wso2isAuthenticationTokenUri" value="${oauth.wso2isAuthenticationTokenUri}"/>
	<property name="wso2OpenIdClaim" value="${oauth.wso2OpenIdClaim}"/>
	<!-- end WSO2 IS-Oauth server -->
</bean>
```

```xml
<bean id="oauthAuthenticationEntryPoint" class="com.arena.sso.oidc.OAuthAuthenticationEntryPoint">
	<property name="consumer" ref="oauthConsumer" />
</bean>
```

- Default *filterProcessesUrl* of *OAuthAuthenticationProcessingFilter* is ***/oauth/authenticate***. It can be overridden adding *filterProcessesUrl* property in the *oauthAuthenticationProcessingFilter* bean above. Please note that this URL is the one, which should be passed to Social's as a redirection (callback) URL. It should be also configured in the **oauth.properties** (see next point).

- *oauthAuthenticationProcessingFilter* and *oauthAuthenticationEntryPoint* defined above should be queued in the *FilterChainProxy* (property *filterInvocationDefinitionSource*) after Spring's *authenticationProcessingFilter*.

- In case that *targetUrlResolver* is defined as a nested bean under Spring's *authenticationProcessingFilter*, it should be taken out to be in global scope to be referenced from all *AuthenticationProcessingFilters* configured.

Sample config for **applicationContext-spring-security.xml**
```xml
:
  <bean class="org.springframework.security.util.FilterChainProxy" id="filterChainProxy">
    <property name="filterInvocationDefinitionSource">
      <value>CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
			PATTERN_TYPE_APACHE_ANT
			/webservices/**=securityContextHolderAwareRequestFilterForWS,httpSessionPentahoSessionContextIntegrationFilter,httpSessionContextIntegrationFilter,basicProcessingFilter,anonymousProcessingFilter,exceptionTranslationFilterForWS,filterInvocationInterceptorForWS
			/api/**=securityContextHolderAwareRequestFilterForWS,httpSessionPentahoSessionContextIntegrationFilter,httpSessionContextIntegrationFilter,basicProcessingFilter,requestParameterProcessingFilter,anonymousProcessingFilter,exceptionTranslationFilterForWS,filterInvocationInterceptorForWS
			/plugin/**=securityContextHolderAwareRequestFilterForWS,httpSessionPentahoSessionContextIntegrationFilter,httpSessionContextIntegrationFilter,basicProcessingFilter,requestParameterProcessingFilter,anonymousProcessingFilter,exceptionTranslationFilterForWS,filterInvocationInterceptorForWS
			/**=securityContextHolderAwareRequestFilter,httpSessionPentahoSessionContextIntegrationFilter,httpSessionContextIntegrationFilter,httpSessionReuseDetectionFilter,enhancedHttpSessionReuseDetectionFilter,logoutFilter,closeFilter,authenticationProcessingFilter,oauthAuthenticationProcessingFilter,oauthAuthenticationEntryPoint,basicProcessingFilter,requestParameterProcessingFilter,anonymousProcessingFilter,exceptionTranslationFilter,filterInvocationInterceptor</value>
    </property>
  </bean>
  <bean class="org.springframework.security.ui.TargetUrlResolverImpl" id="targetUrlResolver">
    <property name="justUseSavedRequestOnGet" value="true"/>
  </bean>
    <!-- === OAuth/OIDC autentication == -->
  <bean class="com.arena.sso.oidc.OAuthAuthenticationProcessingFilter" id="oauthAuthenticationProcessingFilter">
    <property name="authenticationManager">
      <bean class="org.springframework.security.providers.ProviderManager" id="oauthAuthenticationManager">
        <property name="providers">
          <list>
            <ref local="oauthAuthenticationProvider"/>
          </list>
        </property>
      </bean>
    </property>
    <property name="consumer" ref="oauthConsumer"/>
    <property name="defaultTargetUrl" value="/Home"/>
    <property name="authenticationFailureUrl" value="/Login?sso_login_error=1"/>
    <property name="targetUrlResolver">
      <ref local="targetUrlResolver"/>
    </property>
  </bean>
  <bean class="com.arena.sso.oidc.OAuthAuthenticationProvider" id="oauthAuthenticationProvider">
    <property name="userDetailsService" ref="oauthUserDetailsService"/>
  </bean>
  <bean class="com.arena.sso.oidc.consumer.OAuthConsumerImpl" id="oauthConsumer">
    <constructor-arg index="0" value="${oauth.redirectUrl}"/>
    <!-- custom property for MITRE-OPENID server -->
    <property name="mitreoidConsumerKey" value="${oauth.mitreoidConsumerKey}"/>
    <property name="mitreoidConsumerSecret" value="${oauth.mitreoidConsumerSecret}"/>
    <property name="mitreoidTokenRequestUri" value="${oauth.mitreoidTokenRequestUri}"/>
    <property name="mitreoidAccessTokenUri" value="${oauth.mitreoidAccessTokenUri}"/>
    <property name="mitreoidAuthenticationTokenUri" value="${oauth.mitreoidAuthenticationTokenUri}"/>
    <property name="mitreOpenIdClaim" value="${oauth.mitreOpenIdClaim}"/>
    <!-- end MITRE-OPENID server -->
    <!-- custom property for WSO2 IS-Oauth server -->
    <property name="wso2isConsumerKey" value="${oauth.wso2isConsumerKey}"/>
    <property name="wso2isConsumerSecret" value="${oauth.wso2isConsumerSecret}"/>
    <property name="wso2isTokenRequestUri" value="${oauth.wso2isTokenRequestUri}"/>
    <property name="wso2isAccessTokenUri" value="${oauth.wso2isAccessTokenUri}"/>
    <property name="wso2isAuthenticationTokenUri" value="${oauth.wso2isAuthenticationTokenUri}"/>
    <property name="wso2OpenIdClaim" value="${oauth.wso2OpenIdClaim}"/>
    <!-- end WSO2 IS-Oauth server -->
  </bean>
  <bean class="com.arena.sso.oidc.OAuthAuthenticationEntryPoint" id="oauthAuthenticationEntryPoint">
    <property name="consumer" ref="oauthConsumer"/>
  </bean>
  <bean class="com.arena.sso.EnhancedHttpSessionReuseDetectionFilter" id="enhancedHttpSessionReuseDetectionFilter">
    <property name="filterProcessesUrl" value="/j_spring_security_check"/>
    <property name="sessionReuseDetectedUrl" value="/Login?sso_login_error=2"/>
    <property name="ssoFilterProcessesUrls">
      <list>
        <value>/j_spring_oauth_security_check</value>
      </list>
    </property>
  </bean>
  <!-- === END OAuth/OIDC autentication == <<<<<<<<< -->
:
```

**2.** Add and configure **oauth.properties** file to manage configurable values (used by *OAuthConsumerImpl*) related to OAuth/OIDC server you are using (file example is provided in the **resources** folder). The file should be added to **pentaho-solutions/system** directory.

Also add the following bean into **pentaho-spring-beans.xml** to make the property file data available for Spring IOC.

```xml
<bean class="org.pentaho.platform.config.SolutionPropertiesFileConfiguration">
	<constructor-arg value="oauth"/>
	<constructor-arg value="oauth.properties"/>
	<pen:publish as-type="INTERFACES"/>
</bean>
```

- The property *redirectUrl* in **oauth.properties** file should correspond to the one configures for Social Apps as redirect (callback) URL. It should also correspond to the URL processed by *oauthAuthenticationProcessingFilter*.
  Its structure is:**```
    http://<host>:<port>/<context>/<oauth\_authentication\_processing\_filter\_processes\_url>```**

**3.** Configure *EnhancedHttpSessionReuseDetectionFilter* in **applicationContext-spring-security.xml** like the following:

```xml
<bean id="enhancedHttpSessionReuseDetectionFilter" class="com.arena.sso.EnhancedHttpSessionReuseDetectionFilter">
	<property name="filterProcessesUrl" value="/j_spring_security_check" />
	<property name="sessionReuseDetectedUrl" value="/Login?login_error=2" />
	<property name ="ssoFilterProcessesUrls">
		<list>
			<value>/j_spring_oauth_security_check</value>
		</list>
	</property>
</bean>
```

- Please note that *ssoFilterProcessesUrls* property should contain all added SSO authentication URLs. So, if it was already added because some other IdP, just the value *j\_spring\_oauth\_security\_check* should be added into *ssoFilterProcessesUrls* list.

**4.** Configure *SsoUserDetailsService* as *oauthUserDetailsService* bean in **pentahoObjects.spring.xml** like the following (refered from *OAuthAuthenticationProvider* configured above):

```xml
<bean id="oauthUserDetailsService" class="com.arena.sso.SsoUserDetailsService">
	<constructor-arg>
		<ref local="cachingUserDetailsService"/>
	</constructor-arg>
	<property name="userRoleDao">
		<ref bean="userRoleDaoTxn" />
	</property>
	<property name="roles">
		<list>
			<value>Administrator</value>
			<value>Business Analyst</value>
		</list>
	</property>
</bean>
```

- The list of *roles* should contain Pentaho role names, which should be assigned to the user signing-up using OAuth Authentication.

- Also please note that *userRoleDaoTxn* is given as default configuration (defined in **repository.spring.xml**) as *ProxyFactoryBean* (*userRoleDao* property of *SsoUserDetailsService*).

> The issue is that *userRoleDaoProxy* bean, which is intended for production configuration, adds method level security using Spring AOP, which does not allow to *createUser* without administrative privilege. Alternatively, *userRoleDao* can be changed to *userRoleDaoProxy*, but *userRoleDaoMethodInterceptor* in **repository.spring.xml** should be adjusted to allow *createUser*, *setPassword* and *setUserDescription* methods invocation.

**5.** Add OAuth authentication entry point and authentication URLs into *objectDefinitionSource* property of *filterInvocationInterceptor* (*FilterSecurityInterceptor*) like the following line in the CDATA section (in **applicationContext-spring-security.xml**):

```
\A/j_spring_oauth_security_check.*\Z=Anonymous,Authenticated
\A/oauth/authenticate.*\Z=Anonymous,Authenticated
```

- Place the lines after *j\_spring\_security\_check*

***

##SSO FrontEnd Configuration

**OIDC Login Processing URL **

```
http://<host>:<port>/<context>/j_spring_oauth_security_check
```

- required parameter is "***issuer***". The value should be one of the following:
	- *"mitreoid"*
	- *"wso2is"*

For example:
```
http://pentaho.server:pentaho_port/pentaho_context_root/j_spring_oauth_security_check?issuer=mitreoid
```


text:
//
//  BaseViewController.m
//  WxxReadClient
//
//  Created by weng xiangxun on 2017/3/23.
//  Copyright © 2017年 wxx. All rights reserved.
//

#import "BaseViewController.h"
#import "BaseNetControll.h"
//@implementation UINavigationBar (CustomHeight)
//- (CGSize)sizeThatFits:(CGSize)size {
//    // Change navigation bar height. The height must be even, otherwise there will be a white line above the navigation bar.
//    CGSize newSize = CGSizeMake(self.frame.size.width, 74);
//    return newSize;
//}
//
//-(void)layoutSubviews {
//    [super layoutSubviews];
//
//    CGRect barFrame = self.frame;
//    barFrame.size.height = 74;
//    self.frame = barFrame;
//
//    // Make items on navigation bar vertically centered.
//    int i = 0;
//    for (UIView *view in self.subviews) {
//        if (i == 0)
//            continue;
//        float centerY = self.bounds.size.height / 2.0f;
//        CGPoint center = view.center;
//        center.y = centerY;
//        view.center = center;
//    }
//}
//@end
@interface BaseViewController ()
@property (nonatomic,strong)UIActivityIndicatorView *activityIndicator;
@property (nonatomic,strong)CAGradientLayer *topgradientLayer;
@property (nonatomic,strong)UIButton *reloadBtn;
@property (nonatomic,strong)UILabel *reloadLb;
@end

@implementation BaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1];
    //    self.edgesForExtendedLayout = UIRectEdgeNone;
    //    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:wxxColorTitleTextColor}];

    // Do any additional setup after loading the view.

}

-(void)initRealoadBtn{
    if (!self.reloadLb) {
        self.reloadLb  = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
        self.reloadLb.text = @"目前无法连接";
        self.reloadLb.textColor = [UIColor blackColor];
        [self.view addSubview:self.reloadLb];
        self.reloadLb.textAlignment = NSTextAlignmentCenter;
        self.reloadLb.font = [UIFont systemFontOfSize:25];
        self.reloadLb.translatesAutoresizingMaskIntoConstraints = NO;
        NSDictionary* lbviews = NSDictionaryOfVariableBindings(_reloadLb);
        //设置高度
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_reloadLb(50)]-orgy-|" options:0 metrics:@{@"orgy":@(self.view.frame.size.height/2)} views:lbviews]];

        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_reloadLb]|" options:0 metrics:nil views:lbviews]];
    }
    if (!self.reloadBtn) {
        self.reloadBtn = [[UIButton alloc]init];
        [self.view addSubview:self.reloadBtn];
        [self.view bringSubviewToFront:self.reloadBtn];
        [self.reloadBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        self.reloadBtn.layer.borderWidth = 1;
        self.reloadBtn.layer.cornerRadius = 3;
        self.reloadBtn.layer.borderColor = [UIColor blackColor].CGColor;
        [self.reloadBtn setTitle:@"重试" forState:UIControlStateNormal];
        self.reloadBtn.translatesAutoresizingMaskIntoConstraints = NO;
        [self.reloadBtn addTarget:self action:@selector(reloadBtnClick) forControlEvents:UIControlEventTouchUpInside];
        NSDictionary* views = NSDictionaryOfVariableBindings(_reloadBtn);
//        //设置高度
//        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_reloadBtn(45)]" options:0 metrics:nil views:views]];
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-orgy-[_reloadBtn(45)]" options:0 metrics:@{@"orgy":@(self.view.frame.size.height/2+8)} views:views]];
        //设置宽度
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"[_reloadBtn(120)]" options:0 metrics:nil views:views]];
//        //垂直居中
//        [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_reloadBtn attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]];
        //水平居中
        [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_reloadBtn attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]];
        //end
    }
}

-(void)hideReloadUI{
    self.reloadBtn.hidden = YES;
    self.reloadLb.hidden = YES;
}

-(void)reloadBtnClick{
    if (![self isNetLink]) {
        self.reloadBtn.hidden = NO;
        self.reloadLb.hidden = NO;
        [UIView animateWithDuration:0.3 animations:^{
            self.reloadLb.alpha = 0.2;
            self.reloadBtn.alpha = 0.2;
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:0.3 animations:^{
                self.reloadLb.alpha = 1;
                self.reloadBtn.alpha = 1;
            } completion:^(BOOL finished) {

            }];
        }];
    }else{
        self.reloadBtn.hidden = YES;
        self.reloadLb.hidden = YES;
    }
}

-(BOOL)isNetLink{
    if([BaseNetControll sharedInstance].isReachable){
        return YES;
    }else{
        [self initRealoadBtn];
        return NO;
    }
}

-(void)initTopGradientLayer{
    if (!_topgradientLayer) {
        _topgradientLayer = [CAGradientLayer layer];  // 设置渐变效果
        _topgradientLayer.frame = CGRectMake(0, -0.5, self.view.frame.size.width, 7);
        _topgradientLayer.colors = [NSArray arrayWithObjects:
                                    (id)[[UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.2] CGColor],
                                    (id)[[UIColor clearColor] CGColor],
                                    (id)[[UIColor clearColor] CGColor], nil];
        _topgradientLayer.startPoint = CGPointMake(0, 0);
        _topgradientLayer.endPoint = CGPointMake(0, 1.0);
        _topgradientLayer.hidden = YES;
        [self.view.layer addSublayer:_topgradientLayer];
    }
}

-(void)resetTopGradientLayerFrame:(CGRect )rect{

    _topgradientLayer.frame = rect;//CGRectMake(0, -0.5, self.view.frame.size.width, 7);
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y <= 0) {
        //        [UIView animateWithDuration:0.5 animations:^{
        _topgradientLayer.hidden = YES;
        //        }];

    }else{
        if (_topgradientLayer.hidden) {
            _topgradientLayer.hidden = NO;
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated{

    // Called when the view is about to made visible. Default does nothing
    [super viewWillAppear:animated];

    //    CGRect rect = self.navigationController.navigationBar.frame;
    //    self.navigationController.navigationBar.frame = CGRectMake(rect.origin.x,rect.origin.y,rect.size.width,64);

    //    NSLog(@"修改前");
    //    [self printViewHierarchy:self.navigationController.navigationBar];
    //
    //    //修改NavigaionBar的高度
    //    self.navigationController.navigationBar.frame = CGRectMake(0, 20, 320, 100);
    //
    //    NSLog(@"\n修改后");
    //    [self printViewHierarchy:self.navigationController.navigationBar];
    //    [self.navigationController.navigationBar sizeThatFits:CGSizeMake([UIScreen mainScreen].bounds.size.width, 64)];
    //去除导航栏下方的横线
    //    [self.navigationController.navigationBar setBackgroundImage:[self imageWithColor:wxxColorBackground]
    //                       forBarPosition:UIBarPositionAny
    //                           barMetrics:UIBarMetricsDefault];
    //    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    //    [self initTopGradientLayer];
}

- (void)printViewHierarchy:(UIView *)superView
{
    static uint level = 0;
    for(uint i = 0; i < level; i++){
        printf("\t");
    }

    const char *className = NSStringFromClass([superView class]).UTF8String;
    const char *frame = NSStringFromCGRect(superView.frame).UTF8String;
    printf("%s:%s\n", className, frame);

    ++level;
    for(UIView *view in superView.subviews){
        [self printViewHierarchy:view];
    }
    --level;
}

- (UIImage*) imageWithColor: (UIColor*) color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

-(void)showLoading{
    if (!_activityIndicator) {
        //加载旋转的风火轮
        _activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _activityIndicator.hidesWhenStopped = NO;
        _activityIndicator.color = [UIColor blackColor];
        //
        [self.view addSubview:_activityIndicator];
        [self.view bringSubviewToFront:_activityIndicator];

        self.activityIndicator.translatesAutoresizingMaskIntoConstraints = NO;

        NSDictionary* views = NSDictionaryOfVariableBindings(_activityIndicator);
        //设置高度
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_activityIndicator(60)]" options:0 metrics:nil views:views]];
        //设置宽度
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"[_activityIndicator(60)]" options:0 metrics:nil views:views]];
        //垂直居中
        [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_activityIndicator attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]];
        //水平居中
        [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_activityIndicator attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]];
        //end
    }
    _activityIndicator.alpha = 1;
    [_activityIndicator startAnimating];
}

-(void)hideLoading{

    [_activityIndicator stopAnimating];
    _activityIndicator.alpha = 0;
}

- (void)hidesTabBar:(BOOL)hidden{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5];

    for (UIView *view in self.tabBarController.view.subviews) {
        self.tabBarController.view.backgroundColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1];
        if ([view isKindOfClass:[UITabBar class]]) {
            if (hidden) {
                [view setFrame:CGRectMake(view.frame.origin.x, [UIScreen mainScreen].bounds.size.height, view.frame.size.width , view.frame.size.height)];

            }else{
                [view setFrame:CGRectMake(view.frame.origin.x, [UIScreen mainScreen].bounds.size.height - 49, view.frame.size.width, view.frame.size.height)];

            }
        }else{
            if([view isKindOfClass:NSClassFromString(@"UITransitionView")]){
                if (hidden) {
                    [view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, [UIScreen mainScreen].bounds.size.height)];

                }else{

                    [view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, [UIScreen mainScreen].bounds.size.height - 49 )];

                }
            }
        }
    }
    [UIView commitAnimations];
}
/*
 #pragma mark - Navigation

 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end


text:
<!DOCTYPE html>

		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<link rel="stylesheet" type="text/css" href="../js/simpleslides.css" />
		<link rel="stylesheet" type="text/css" href="../css/style.css" />
		<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Lato|Space+Mono|Inconsolata" />
		<title>Halton Day 01</title>

Setup

Login Information

User: KATI Guest

Pass: Welcome123

Google Classroom

URL: classroom.google.com

Classcode: eleilcr

Books

Big Book: Learning Visual Basic .NET, 978-0-596-00386-9

Little Book: VB.NET Language Pocket Reference, 978-0-596-00428-6

Timeline

Meeting 1: Chapters 2, 4, 5, Turtle Programming

Meeting 2: Chapters 6, 7, Stochastic Programming

Meeting 3: Chapters 3, 8, 9, 11, Object-Oriented Programming

Meeting 4: Chapters 12, 14, 15, Structure and Algorithm Design

Meeting 5: ?

Hello World

Open Visual Studio

File > New > Project > Templates > Visual Basic > Windows Classic Desktop > Console App

Give it a meaningful name at the bottom and click ok

Edit code (see below), and press ctrl+F5 to run

			<xmp>
Module Example
    Sub Main()
        Console.WriteLine("Hello, World!")
    End Sub
End Module
			</xmp>

Data

Dim and Const

Declare new variables (that can change value) with Dim, or new constants (that cannot change value) with Const.

			<xmp>
Dim myName As String = "Bryan Knowles"
Const myWallet As Integer = 0
			</xmp>

Types

Use Integer for whole numbers (1234)

Use Double for real numbers (1.234)

Use String for text

Use Boolean for true/false values (named after George Boole)

Use Date for dates

WriteLine

Use Console.WriteLine(...) to display text to the user.

			<xmp>
Console.WriteLine("Hello, World!")

Dim myExample As String = "Here is another string"
Console.WriteLine(myExample)

Dim someNumber As Integer = 17
Console.WriteLine(someNumber)
			</xmp>

You can also use this command to display several values at once in a sentence.

			<xmp>
Dim name As String = "J. Doe"
Dim quiz As Double = 0.97
Dim lab As Double = 0.83
Dim homework As Double = 0.92
Console.WriteLine("{0} made these grades: {1}, {2}, and {3}.", name, quiz, lab, homework)
			</xmp>

Dungeons and Dragons

Starting Code

			<xmp>
Module Example
    Sub Main()
        Randomize()
        Dim name As String = "Bob Ross, the Migthy"
        Dim strength As Integer = (6 * Rnd() + 1) + (6 * Rnd() + 1) + (6 * Rnd() + 1) + (6 * Rnd() + 1)

        Console.WriteLine("Character Sheet for {0}:", name)
        Console.WriteLine("Strength = {0}", strength)
    End Sub
End Module
			</xmp>

Goal

Complete the program so that it creates and displays all of the following:

Name

Strength (4d6)

Constitution (4d6)

Defense (4d6)

Dexterity (2d8)

Intelligence (2d8)

Charisma (2d8)

Wisdom (1d12 + 2d6)

Willpower (1d12 + 2d6)

Perception (1d12 + 2d6)

Luck (1d20)

Note the dice that need to be rolled for each stat.

Turtles

Install

Download the Turtle Basic.zip file from Google Classroom and extract

Start a new console project in VS

Project > Add Reference > Browse

Select the SmallBasicLibrary.dll file from the downloaded folder

Add this to the very top of your code: Imports Microsoft.SmallBasic.Library

Write this in your main and run it: Turtle.Move(100)

Commands

Turtle.Move(distance) will move the turtle the direction it is facing by distance pixels. Negative pixels make it walk backwards. It will draw a line as it moves.

Turtle.MoveTo(x, y) will move the turtle to the location on the window that is x pixels from the left and y pixels from the top. It will draw a line as it moves.

Turtle.X = x will instantly move the turtle to x pixels from the left of the window. It will NOT draw a line as it moves. We similarly have Turtle.Y = y.

Turtle.Turn(degrees) will rotate the turtle by degrees degrees with respect to the direction it is currently facing. Zero degrees is up, and ninety degrees is to the right.

Turtle.Angle = degrees will set the turtles angle to exactly degrees degrees with respect to the window.

Goal

Using only Move and Turn, draw a box with 200 pixel sides. Then modify the code to use a variable to control the size of the box.

Stretch Goals

Draw a triangle

Draw an octagon

Draw a house

Draw a five-point star

Draw a scene with a house, some stars, and a mailbox out front


text:
#ifndef __STREAM_SERVER_CHANNEL_H__
#define __STREAM_SERVER_CHANNEL_H__

#include <tiny_typedef.h>
#include <tiny_ret.h>
#include <tiny_api.h>
#include "channel/Channel.h"
#include "channel/ChannelInitializer.h"

TINY_BEGIN_DECLS

TINY_API
TINY_LOR
Channel * StreamServerChannel_New(int maxConnections, ChannelLoopHook loopHook, void *ctx);

TINY_API
TINY_LOR
void StreamServerChannel_Initialize(Channel *thiz, ChannelInitializer initializer, void *ctx);

TINY_END_DECLS

#endif /* __STREAM_SERVER_CHANNEL_H__ */


text:
require 'spec_helper'

# This spec was generated by rspec-rails when you ran the scaffold generator.
# It demonstrates how one might use RSpec to specify the controller code that
# was generated by the Rails when you ran the scaffold generator.

describe ReviewsController do

  def mock_review(stubs={})
    @mock_review ||= mock_model(Review, stubs).as_null_object
  end

  describe "GET index" do
    it "assigns all reviews as @reviews" do
      Review.stub(:all) { [mock_review] }
      get :index
      assigns(:reviews).should eq([mock_review])
    end
  end

  describe "GET show" do
    it "assigns the requested review as @review" do
      Review.stub(:find).with("37") { mock_review }
      get :show, :id => "37"
      assigns(:review).should be(mock_review)
    end
  end

  describe "GET new" do
    it "assigns a new review as @review" do
      Review.stub(:new) { mock_review }
      get :new
      assigns(:review).should be(mock_review)
    end
  end

  describe "GET edit" do
    it "assigns the requested review as @review" do
      Review.stub(:find).with("37") { mock_review }
      get :edit, :id => "37"
      assigns(:review).should be(mock_review)
    end
  end

  describe "POST create" do
    describe "with valid params" do
      it "assigns a newly created review as @review" do
        Review.stub(:new).with({'these' => 'params'}) { mock_review(:save => true) }
        post :create, :review => {'these' => 'params'}
        assigns(:review).should be(mock_review)
      end

      it "redirects to the created review" do
        Review.stub(:new) { mock_review(:save => true) }
        post :create, :review => {}
        response.should redirect_to(review_url(mock_review))
      end
    end

    describe "with invalid params" do
      it "assigns a newly created but unsaved review as @review" do
        Review.stub(:new).with({'these' => 'params'}) { mock_review(:save => false) }
        post :create, :review => {'these' => 'params'}
        assigns(:review).should be(mock_review)
      end

      it "re-renders the 'new' template" do
        Review.stub(:new) { mock_review(:save => false) }
        post :create, :review => {}
        response.should render_template("new")
      end
    end
  end

  describe "PUT update" do
    describe "with valid params" do
      it "updates the requested review" do
        Review.stub(:find).with("37") { mock_review }
        mock_review.should_receive(:update_attributes).with({'these' => 'params'})
        put :update, :id => "37", :review => {'these' => 'params'}
      end

      it "assigns the requested review as @review" do
        Review.stub(:find) { mock_review(:update_attributes => true) }
        put :update, :id => "1"
        assigns(:review).should be(mock_review)
      end

      it "redirects to the review" do
        Review.stub(:find) { mock_review(:update_attributes => true) }
        put :update, :id => "1"
        response.should redirect_to(review_url(mock_review))
      end
    end

    describe "with invalid params" do
      it "assigns the review as @review" do
        Review.stub(:find) { mock_review(:update_attributes => false) }
        put :update, :id => "1"
        assigns(:review).should be(mock_review)
      end

      it "re-renders the 'edit' template" do
        Review.stub(:find) { mock_review(:update_attributes => false) }
        put :update, :id => "1"
        response.should render_template("edit")
      end
    end
  end

  describe "DELETE destroy" do
    it "destroys the requested review" do
      Review.stub(:find).with("37") { mock_review }
      mock_review.should_receive(:destroy)
      delete :destroy, :id => "37"
    end

    it "redirects to the reviews list" do
      Review.stub(:find) { mock_review }
      delete :destroy, :id => "1"
      response.should redirect_to(reviews_url)
    end
  end

end


text:
require 'sequoyah'
require 'sequel'

RSpec.configure do |config|
  config.run_all_when_everything_filtered = true
  config.order = 'random'
end


text:
from __future__ import absolute_import, division, print_function
from __future__ import unicode_literals

import logging

from tldp.utils import which
from tldp.utils import arg_isexecutable, isexecutable
from tldp.doctypes.common import depends
from tldp.doctypes.docbook4xml import Docbook4XML

logger = logging.getLogger(__name__)

class Asciidoc(Docbook4XML):
    formatname = 'AsciiDoc'
    extensions = ['.txt']
    signatures = []

    required = {'asciidoc_asciidoc': isexecutable,
                'asciidoc_xmllint': isexecutable,
                }
    required.update(Docbook4XML.required)

    def make_docbook45(self, **kwargs):
        s = '''"{config.asciidoc_asciidoc}" \\
                 --backend docbook45 \\
                 --out-file {output.validsource} \\
                 "{source.filename}"'''
        return self.shellscript(s, **kwargs)

    @depends(make_docbook45)
    def make_validated_source(self, **kwargs):
        s = '"{config.asciidoc_xmllint}" --noout --valid "{output.validsource}"'
        return self.shellscript(s, **kwargs)

    @classmethod
    def argparse(cls, p):
        descrip = 'executables and data files for %s' % (cls.formatname,)
        g = p.add_argument_group(title=cls.__name__, description=descrip)
        g.add_argument('--asciidoc-asciidoc', type=arg_isexecutable,
                       default=which('asciidoc'),
                       help='full path to asciidoc [%(default)s]')
        g.add_argument('--asciidoc-xmllint', type=arg_isexecutable,
                       default=which('xmllint'),
                       help='full path to xmllint [%(default)s]')

#
# -- end of file


text:
@class RolesModel;

@interface DataCenter : NSObject

//设备device token
@property(nonatomic,strong) NSString* deviceToken;

//应用token
@property(nonatomic,strong) NSString* appToken;

//应用的plist
@property(nonatomic,strong) NSString* plist;

//应用token 过期时间
@property(nonatomic,strong) NSDate* appTokeExpired;

//登陆帐号
@property(nonatomic,strong) NSString* username;

//登陆密码
@property(nonatomic,strong) NSString* password;

//记住密码
@property(nonatomic,assign) BOOL isRemember;

//登陆token
@property(nonatomic,strong) NSString* accountToken;

//帐号权限
@property(nonatomic,strong) RolesModel* roles;

//本地模块映射
@property(nonatomic,strong) NSMutableArray* localModules;

//已下载模块
@property(nonatomic,strong) NSMutableArray* installMoudules;

//服务器模块
@property(nonatomic,strong) NSArray* serviceModules;

+(DataCenter*)defaultCenter;

@end


text:
package com.chenpan.commoner.widget.loadview;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.widget.EditText;

/**
 * Created by Administrator on 2016/3/30.
 */
public class GraduallyTextView extends EditText {

    private CharSequence text;
    private int startY = 0;
    private float progress;
    private boolean isLoading;
    private Paint mPaint;
    private int textLength;
    private boolean isStop = true;
    private float scaleX;
    private int duration = 2000;
    private float sigleDuration;

    private ValueAnimator valueAnimator;

    public GraduallyTextView(Context context) {
        super(context);
        init();
    }

    public GraduallyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public GraduallyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public void init() {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setStyle(Paint.Style.FILL);
        setBackground(null);
        setCursorVisible(false);
        setFocusable(false);
        setEnabled(false);
        setFocusableInTouchMode(false);

        valueAnimator = ValueAnimator.ofFloat(0, 100).setDuration(duration);
        valueAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
        valueAnimator.setRepeatCount(Animation.INFINITE);
        valueAnimator.setRepeatMode(ValueAnimator.RESTART);
        valueAnimator.addUpdateListener(
                new ValueAnimator.AnimatorUpdateListener() {
                    @Override
                    public void onAnimationUpdate(ValueAnimator animation) {
                        progress = (Float) animation.getAnimatedValue();
                        GraduallyTextView.this.invalidate();
                    }
                });
    }

    public void startLoading() {
        if (!isStop) {
            return;
        }
        textLength = getText().length();
        if (TextUtils.isEmpty(getText().toString())) {
            return;
        }
        isLoading = true;
        isStop = false;
        text = getText();

        scaleX = getTextScaleX() * 10;
        startY = 88;
        mPaint.setColor(getCurrentTextColor());
        mPaint.setTextSize(getTextSize());
        setMinWidth(getWidth());
        setText("");
        setHint("");
        valueAnimator.start();
        sigleDuration = 100f / textLength;
    }

    public void stopLoading() {
        isLoading = false;
        valueAnimator.end();
        valueAnimator.cancel();
        isStop = true;
        setText(text);
    }

    public void setDuration(int duration) {
        this.duration = duration;
    }

    @Override
    protected void onVisibilityChanged(View changedView, int visibility) {
        super.onVisibilityChanged(changedView, visibility);
        if (!isLoading) {
            return;
        }
        if (visibility == View.VISIBLE) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                valueAnimator.resume();
            }

        }
        else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                valueAnimator.pause();
            }
        }
    }

    @Override protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (!isStop) {
            mPaint.setAlpha(255);
            if (progress / sigleDuration >= 1) {
                canvas.drawText(String.valueOf(text), 0,
                        (int) (progress / sigleDuration), scaleX, startY,
                        mPaint);
            }
            mPaint.setAlpha(
                    (int) (255 * ((progress % sigleDuration) / sigleDuration)));
            int lastOne = (int) (progress / sigleDuration);
            if (lastOne < textLength) {
                canvas.drawText(String.valueOf(text.charAt(lastOne)), 0, 1,
                        scaleX + getPaint().measureText(
                                text.subSequence(0, lastOne).toString()),
                        startY, mPaint);
            }
        }
    }
}


text:
<?php
/**
 * Default view for User's Private Message Inbox and Outbox
 */

//TODO: ability to view 1 full msg (there also see previous conversation with that person)
//TODO: mark seen msg as "READ"
//TODO: ability to mark seen msg as "UNREAD" again
//TODO: ability to mark a message as "DELETED". really useful? will require 2 copies of each msg, or else if user 1 deletes the msg, user2 also wont see it

namespace cd;

$session->requireLoggedIn();

if (!$this->owner)
    $this->owner = 'default';

switch ($this->owner) {
case 'inbox':

    echo '
Message inbox
';
    $list = Message::getInbox($session->id);
    //d($list);
    echo ahref('u/messages/outbox', 'Show outbox').'
';
    echo '
';

    foreach ($list as $msg)
    {
//        $from = User::get($msg->from);

        echo 'From '.UserLink::render($msg->from).', '.ago($msg->time_sent).'
';
//        echo 'Read: '.ago($msg->time_read).'
';  // XXX FIXME mark msgs as read!!!
        switch ($msg->type) {
        case PRIV_MSG:
            echo nl2br($msg->body).'
';
            break;
        case RECORDING_MSG:
            echo embed_flv($msg->body).'
';
            break;
        default:
            throw new \Exception ('eh');
        }
        echo ahref('videomsg/send/'.$msg->from, 'Reply with video').'
';
        echo ahref('u/messages/send/'.$msg->from, 'Reply with text').'
';
        echo '
';
    }

    break;

case 'outbox':
    echo '
Message outbox
';
    $list = Message::getOutbox($session->id);
    //d($list);
    echo ahref('u/messages/inbox', 'Show inbox').'
';
    echo '
';

    foreach ($list as $msg)
    {
        echo 'To '.UserLink::render($msg->to).', '.ago($msg->time_sent).'
';
        switch ($msg->type) {
        case PRIV_MSG:
            echo nl2br($msg->body).'
';
            break;
        case RECORDING_MSG:
            echo 'VIDEO MSG!!!
';
            echo embed_flv($msg->body).'
';
            break;
        default:
            throw new \Exception ('eh');
        }
        echo '
';
    }
    break;

case 'send':
    // child = send to user id
    if (Bookmark::exists(BOOKMARK_USERBLOCK, $session->id, $this->child)) {
        echo 'User has blocked you from access';
        return;
    }

    function msgSubmit($p)
    {
        Message::send($p['to'], $p['msg']);
        js_redirect('u/messages/inbox');
    }

    $user = User::get($this->child);

    echo '
Send a message to '.$user->name.'
';

    $form = new XhtmlForm();
    $form->addTextarea('msg', 'Msg');
    $form->addHidden('to', $this->child);
    $form->addSubmit('Send');
    $form->setHandler('msgSubmit');
    $form->setFocus('msg');
    echo $form->render();

    break;

default:
    echo 'No handler for view '.$this->owner;
}

?>