text:
package org.ajabshahar.platform.resources;

import com.google.gson.Gson;
import com.ninja_squad.dbsetup.DbSetup;
import com.ninja_squad.dbsetup.Operations;
import com.ninja_squad.dbsetup.destination.DataSourceDestination;
import com.ninja_squad.dbsetup.operation.Operation;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import io.dropwizard.testing.junit.DropwizardAppRule;
import net.minidev.json.JSONObject;
import org.ajabshahar.DataSetup;
import org.ajabshahar.api.*;
import org.ajabshahar.platform.PlatformApplication;
import org.ajabshahar.platform.PlatformConfiguration;
import org.ajabshahar.platform.models.ReflectionTranscript;
import org.h2.jdbcx.JdbcDataSource;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;

import javax.ws.rs.core.NewCookie;
import java.util.*;

import static org.ajabshahar.DataSetup.INSERT_GATHERINGS;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;

public class ReflectionResourceIT {

    @ClassRule
    public static final DropwizardAppRule<PlatformConfiguration> RULE =
            new DropwizardAppRule<>(PlatformApplication.class, resourceFilePath("test-config.yaml"));

    private Client client;
    private JdbcDataSource dataSource;

    @Before
    public void setUp() {
        client = new Client();
        dataSource = new JdbcDataSource();
        dataSource.setUrl("jdbc:h2:./test");
        dataSource.setUser("sa");
        dataSource.setPassword("");
    }

    @Test
    public void shouldSaveReflection() {
        String songEnglishTransliteration = "Transliteration";
        Set<SongSummaryRepresentation> songs = new LinkedHashSet<>();
        PersonSummaryRepresentation personSummaryRepresentation = new PersonSummaryRepresentation(1, "name", "hindiName", "primaryOccupation", true);
        Set<PersonSummaryRepresentation> personSummaryRepresentations = new LinkedHashSet<PersonSummaryRepresentation>();
        personSummaryRepresentations.add(personSummaryRepresentation);
        songs.add(new SongSummaryRepresentation(1, songEnglishTransliteration, null, null, null, null, null, null,false,"video"));

        Operation operation = Operations.sequenceOf(DataSetup.DELETE_ALL, DataSetup.INSERT_CATEGORY, DataSetup.INSERT_PERSON, INSERT_GATHERINGS, DataSetup.INSERT_SONGS_AND_TITLE);

        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        JSONObject jsonReflection = new JSONObject();

        jsonReflection.put("title", "reflection");
        jsonReflection.put("verb", "by");
        jsonReflection.put("soundCloudId", "1234");
        jsonReflection.put("youtubeVideoId", "12345");
        jsonReflection.put("showOnMainFcPage", true);
        jsonReflection.put("publish", true);
        jsonReflection.put("speaker", null);
        jsonReflection.put("songs", songs);
        jsonReflection.put("people", personSummaryRepresentations);

        ClientResponse reflectionResponse = loginAndSave(jsonReflection);

        ReflectionRepresentation reflection = getEntity(reflectionResponse);

        assertThat(reflectionResponse.getStatus(), is(200));
        assertThat(reflection.getId(), is(not(0)));
        assertThat(reflection.getSongs().iterator().next().getId(), is(1L));
        assertThat(reflection.getPeople().iterator().next().getId(), is(1L));
    }

    @Test
    public void shouldSaveRelatedWords() {
        Operation operation = Operations.sequenceOf(DataSetup.DELETE_ALL, DataSetup.INSERT_CATEGORY, DataSetup.INSERT_PERSON, DataSetup.INSERT_REFLECTIONS, DataSetup.INSERT_WORDS);

        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        JSONObject jsonReflection = new JSONObject();

        jsonReflection.put("title", "reflection");
        jsonReflection.put("verb", "by");
        jsonReflection.put("soundCloudId", "1234");

        Set<WordSummaryRepresentation> words = new LinkedHashSet<>();

        WordSummaryRepresentation wordSummaryRepresentation = new WordSummaryRepresentation();
        wordSummaryRepresentation.setId(1);
        words.add(wordSummaryRepresentation);

        wordSummaryRepresentation = new WordSummaryRepresentation();
        wordSummaryRepresentation.setId(2);
        words.add(wordSummaryRepresentation);

        jsonReflection.put("words", words);

        ClientResponse reflectionResponse = loginAndSave(jsonReflection);
        ReflectionRepresentation reflection = getEntity(reflectionResponse);

        assertThat(reflectionResponse.getStatus(), is(200));
        assertThat(reflection.getId(), is(not(0)));

        reflectionResponse = getReflection(reflection.getId());
        ReflectionRepresentation reflectionRepresentation = getEntity(reflectionResponse);
        assertThat(reflectionRepresentation.getWords().size(), is(2));
    }

    @Test
    public void shouldEditReflection() {
        Operation operation = Operations.sequenceOf(DataSetup.DELETE_ALL);

        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        JSONObject jsonReflection = new JSONObject();

        jsonReflection.put("title", "reflection");
        jsonReflection.put("verb", "by");
        jsonReflection.put("soundCloudId", "1234");
        jsonReflection.put("youtubeVideoId", "12345");
        jsonReflection.put("showOnMainFcPage", true);
        jsonReflection.put("publish", true);

        ClientResponse reflectionResponse = loginAndSave(jsonReflection);

        ReflectionRepresentation reflection = getEntity(reflectionResponse);

        assertThat(reflectionResponse.getStatus(), is(200));
        assertThat(reflection.getId(), is(not(0)));
        assertThat(reflection.getSoundCloudId(), is("1234"));

        jsonReflection.put("soundCloudId", "6789");

        reflectionResponse = loginAndSave(jsonReflection);
        reflection = getEntity(reflectionResponse);

        assertThat(reflectionResponse.getStatus(), is(200));
        assertThat(reflection.getId(), is(not(0)));
        assertThat(reflection.getSoundCloudId(), is("6789"));
    }

    @Test
    public void shouldEditRelatedWords() {
        Operation operation = Operations.sequenceOf(DataSetup.DELETE_ALL,DataSetup.INSERT_CATEGORY,  DataSetup.INSERT_PERSON, DataSetup.INSERT_REFLECTIONS, DataSetup.INSERT_WORDS);

        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        JSONObject jsonReflection = new JSONObject();

        jsonReflection.put("title", "reflection");
        jsonReflection.put("verb", "by");
        jsonReflection.put("soundCloudId", "1234");

        Set<WordSummaryRepresentation> words = new LinkedHashSet<>();

        WordSummaryRepresentation wordSummaryRepresentation = new WordSummaryRepresentation();
        wordSummaryRepresentation.setId(1);
        words.add(wordSummaryRepresentation);

        wordSummaryRepresentation = new WordSummaryRepresentation();
        wordSummaryRepresentation.setId(2);
        words.add(wordSummaryRepresentation);

        jsonReflection.put("words", words);

        //save first
        ClientResponse reflectionResponse = loginAndSave(jsonReflection);
        ReflectionRepresentation reflection = getEntity(reflectionResponse);

        assertThat(reflectionResponse.getStatus(), is(200));
        assertThat(reflection.getId(), is(not(0)));

        reflectionResponse = getReflection(reflection.getId());
        ReflectionRepresentation reflectionRepresentation = getEntity(reflectionResponse);
        assertThat(reflectionRepresentation.getWords().size(), is(2));

        //edit
        words.remove(words.iterator().next());
        jsonReflection.put("words", words);

        reflectionResponse = loginAndSave(jsonReflection);
        reflection = getEntity(reflectionResponse);

        //check the db
        reflectionResponse = getReflection(reflection.getId());
        reflectionRepresentation = getEntity(reflectionResponse);
        assertThat(reflectionRepresentation.getWords().size(), is(1));
    }

    @Test
    public void shouldSaveTranscripts() {
        Operation operation = Operations.sequenceOf(DataSetup.DELETE_ALL);

        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        JSONObject jsonReflection = new JSONObject();

        jsonReflection.put("title", "reflection");
        jsonReflection.put("verb", "by");
        jsonReflection.put("soundCloudId", "1234");
        jsonReflection.put("youtubeVideoId", "12345");
        jsonReflection.put("showOnMainFcPage", true);
        jsonReflection.put("publish", true);

        Set<ReflectionTranscript> reflectionTranscripts = new LinkedHashSet<>();
        ReflectionTranscript reflectionTranscript = new ReflectionTranscript();
        reflectionTranscript.setEnglishTranscript("hey");
        reflectionTranscript.setHindiTranscript("hey hindi");
        reflectionTranscripts.add(reflectionTranscript);

        jsonReflection.put("reflectionTranscripts", reflectionTranscripts);

        ClientResponse reflectionResponse = loginAndSave(jsonReflection);

        assertThat(reflectionResponse.getStatus(), is(200));
        ReflectionRepresentation reflectionRepresentation = getEntity(reflectionResponse);

        reflectionResponse = getReflection(reflectionRepresentation.getId());

        reflectionRepresentation = getEntity(reflectionResponse);

        assertThat(reflectionRepresentation.getReflectionTranscripts().size(), is(1));
        assertThat(reflectionRepresentation.getReflectionTranscripts().iterator().next().getId(), not(0));
        assertThat(reflectionRepresentation.getReflectionTranscripts().iterator().next().getEnglishTranscript(), is("hey"));
        assertThat(reflectionRepresentation.getReflectionTranscripts().iterator().next().getHindiTranscript(), is("hey hindi"));
    }

    private ReflectionRepresentation getEntity(ClientResponse reflectionResponse) {
        return reflectionResponse.getEntity(ReflectionRepresentation.class);
    }

    @Test
    public void shouldEditAndRemoveTranscripts() {
        Operation operation = Operations.sequenceOf(DataSetup.DELETE_ALL);

        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        JSONObject jsonReflection = new JSONObject();

        jsonReflection.put("title", "reflection");
        jsonReflection.put("verb", "by");
        jsonReflection.put("soundCloudId", "1234");
        jsonReflection.put("youtubeVideoId", "12345");
        jsonReflection.put("showOnMainFcPage", true);
        jsonReflection.put("publish", true);
        jsonReflection.put("about", "old");

        Set<ReflectionTranscript> reflectionTranscripts = new LinkedHashSet<>();
        ReflectionTranscript reflectionTranscript = new ReflectionTranscript();
        reflectionTranscript.setEnglishTranscript("hey");
        reflectionTranscript.setHindiTranscript("hey hindi");
        reflectionTranscripts.add(reflectionTranscript);

        jsonReflection.put("reflectionTranscripts", reflectionTranscripts);

        ClientResponse reflectionResponse = loginAndSave(jsonReflection);

        reflectionResponse = getReflection(getEntity(reflectionResponse).getId());
        ReflectionRepresentation reflectionRepresentation = getEntity(reflectionResponse);

        assertThat(reflectionRepresentation.getReflectionTranscripts().size(), is(1));
        jsonReflection.put("id", reflectionRepresentation.getId());
        jsonReflection.put("about", "new");
        jsonReflection.put("reflectionTranscripts", Collections.EMPTY_LIST);

        reflectionResponse = loginAndSave(jsonReflection);

        reflectionResponse = getReflection(getEntity(reflectionResponse).getId());

        ReflectionRepresentation reflection2 = getEntity(reflectionResponse);
        Set<ReflectionTranscript> reflectionTranscripts1 = reflection2.getReflectionTranscripts();
        assertThat(reflectionTranscripts1.size(), is(0));
        assertThat(reflection2.getAbout(), is("new"));
    }

    @Test
    public void shouldEditAndUpdateTranscripts() {
        Operation operation = Operations.sequenceOf(DataSetup.DELETE_ALL);

        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        JSONObject jsonReflection = new JSONObject();

        jsonReflection.put("title", "reflection");
        jsonReflection.put("verb", "by");
        jsonReflection.put("soundCloudId", "1234");
        jsonReflection.put("youtubeVideoId", "12345");
        jsonReflection.put("showOnMainFcPage", true);
        jsonReflection.put("publish", true);
        jsonReflection.put("about", "old");

        Set<ReflectionTranscript> reflectionTranscripts = new LinkedHashSet<>();
        ReflectionTranscript reflectionTranscript = new ReflectionTranscript();
        reflectionTranscript.setEnglishTranscript("hey");
        reflectionTranscript.setHindiTranscript("hey hindi");
        reflectionTranscripts.add(reflectionTranscript);

        jsonReflection.put("reflectionTranscripts", reflectionTranscripts);

        ClientResponse reflectionResponse = loginAndSave(jsonReflection);

        reflectionResponse = getReflection(getEntity(reflectionResponse).getId());
        ReflectionRepresentation reflectionRepresentation = getEntity(reflectionResponse);

        Set<ReflectionTranscript> reflectionTranscriptsFromDb = reflectionRepresentation.getReflectionTranscripts();
        assertThat(reflectionTranscriptsFromDb.size(), is(1));
        jsonReflection.put("id", reflectionRepresentation.getId());
        jsonReflection.put("about", "new");
        ReflectionTranscript newReflectionTranscript = new ReflectionTranscript();
        newReflectionTranscript.setId(reflectionTranscriptsFromDb.iterator().next().getId());
        newReflectionTranscript.setEnglishTranscript("hey i changed!");

        jsonReflection.put("reflectionTranscripts", Arrays.asList(newReflectionTranscript));

        reflectionResponse = loginAndSave(jsonReflection);

        reflectionResponse = getReflection(getEntity(reflectionResponse).getId());

        ReflectionRepresentation reflection2 = getEntity(reflectionResponse);
        Set<ReflectionTranscript> reflectionTranscripts1 = reflection2.getReflectionTranscripts();
        assertThat(reflectionTranscripts1.size(), is(1));
        assertThat(reflectionTranscripts1.iterator().next().getEnglishTranscript(), is("hey i changed!"));
        assertThat(reflection2.getAbout(), is("new"));
    }

    @Test
    public void shouldSaveRelatedSpeaker() {

        Operation operation = Operations.sequenceOf(DataSetup.DELETE_ALL, DataSetup.INSERT_CATEGORY, DataSetup.INSERT_PERSON);

        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        JSONObject jsonReflection = new JSONObject();

        jsonReflection.put("title", "reflection");
        jsonReflection.put("verb", "by");
        jsonReflection.put("soundCloudId", "1234");
        jsonReflection.put("youtubeVideoId", "12345");
        jsonReflection.put("showOnMainFcPage", true);
        jsonReflection.put("publish", true);

        PersonSummaryRepresentation personSummaryRepresentation = new PersonSummaryRepresentation(1, "Ravi", "hindi name", "singer", true);
        jsonReflection.put("speaker", personSummaryRepresentation);

        ClientResponse reflectionResponse = loginAndSave(jsonReflection);

        assertThat(reflectionResponse.getStatus(), is(200));

        reflectionResponse = getReflection(getEntity(reflectionResponse).getId());

        assertThat(getEntity(reflectionResponse).getSpeaker().getId(), is(1L));
    }

    @Test
    public void shouldEditRelatedSpeaker() {
        Operation operation = Operations.sequenceOf(DataSetup.DELETE_ALL,DataSetup.INSERT_CATEGORY,  DataSetup.INSERT_PERSON);

        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        JSONObject jsonReflection = new JSONObject();

        jsonReflection.put("title", "reflection");
        jsonReflection.put("verb", "by");
        jsonReflection.put("soundCloudId", "1234");
        jsonReflection.put("youtubeVideoId", "12345");
        jsonReflection.put("showOnMainFcPage", true);
        jsonReflection.put("publish", true);

        PersonSummaryRepresentation personSummaryRepresentation = new PersonSummaryRepresentation(1, "Ravi", "hindi name", "singer", true);
        jsonReflection.put("speaker", personSummaryRepresentation);

        ClientResponse reflectionResponse = loginAndSave(jsonReflection);

        assertThat(reflectionResponse.getStatus(), is(200));

        reflectionResponse = getReflection(getEntity(reflectionResponse).getId());

        assertThat(getEntity(reflectionResponse).getSpeaker().getId(), is(1L));

        personSummaryRepresentation = new PersonSummaryRepresentation(2, "Shabnam", "Virmani", "singer", true);
        jsonReflection.put("speaker", personSummaryRepresentation);

        reflectionResponse = loginAndSave(jsonReflection);

        assertThat(reflectionResponse.getStatus(), is(200));

        reflectionResponse = getReflection(getEntity(reflectionResponse).getId());

        assertThat(getEntity(reflectionResponse).getSpeaker().getId(), is(2L));

    }

    @Test
    public void shouldSaveInfo() {

        Operation operation = Operations.sequenceOf(DataSetup.DELETE_ALL,DataSetup.INSERT_CATEGORY,  DataSetup.INSERT_PERSON);

        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        JSONObject jsonReflection = new JSONObject();

        jsonReflection.put("title", "reflection");
        jsonReflection.put("verb", "by");
        jsonReflection.put("soundCloudId", "1234");
        jsonReflection.put("youtubeVideoId", "12345");
        jsonReflection.put("showOnMainFcPage", true);
        jsonReflection.put("publish", true);
        jsonReflection.put("info", "some info");

        ClientResponse reflectionResponse = loginAndSave(jsonReflection);

        assertThat(reflectionResponse.getStatus(), is(200));

        assertThat(getEntity(reflectionResponse).getInfo(), is("some info"));
    }

    @Test
    public void shouldEditInfo() {
        Operation operation = Operations.sequenceOf(DataSetup.DELETE_ALL);

        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        JSONObject jsonReflection = new JSONObject();

        jsonReflection.put("title", "reflection");
        jsonReflection.put("verb", "by");
        jsonReflection.put("soundCloudId", "1234");
        jsonReflection.put("youtubeVideoId", "12345");
        jsonReflection.put("showOnMainFcPage", true);
        jsonReflection.put("publish", true);
        jsonReflection.put("info", "some info");

        ClientResponse reflectionResponse = loginAndSave(jsonReflection);

        ReflectionRepresentation reflection = getEntity(reflectionResponse);

        assertThat(reflectionResponse.getStatus(), is(200));

        assertThat(reflection.getInfo(), is("some info"));

        jsonReflection.put("info", "some other info");

        reflectionResponse = loginAndSave(jsonReflection);
        reflection = getEntity(reflectionResponse);

        assertThat(reflectionResponse.getStatus(), is(200));

        assertThat(reflection.getInfo(), is("some other info"));
    }

    @Test
    public void shouldSaveThumbnailUrl() {

        Operation operation = Operations.sequenceOf(DataSetup.DELETE_ALL,DataSetup.INSERT_CATEGORY,  DataSetup.INSERT_PERSON);

        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        JSONObject jsonReflection = new JSONObject();

        jsonReflection.put("title", "reflection");
        jsonReflection.put("verb", "by");
        jsonReflection.put("soundCloudId", "1234");
        jsonReflection.put("youtubeVideoId", "12345");
        jsonReflection.put("showOnMainFcPage", true);
        jsonReflection.put("publish", true);
        jsonReflection.put("thumbnailURL", "some url");

        ClientResponse reflectionResponse = loginAndSave(jsonReflection);

        assertThat(reflectionResponse.getStatus(), is(200));

        assertThat(getEntity(reflectionResponse).getThumbnailURL(), is("some url"));
    }

    @Test
    public void shouldEditThumbnailUrl() {
        Operation operation = Operations.sequenceOf(DataSetup.DELETE_ALL);

        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        JSONObject jsonReflection = new JSONObject();

        jsonReflection.put("title", "reflection");
        jsonReflection.put("verb", "by");
        jsonReflection.put("soundCloudId", "1234");
        jsonReflection.put("youtubeVideoId", "12345");
        jsonReflection.put("showOnMainFcPage", true);
        jsonReflection.put("publish", true);
        jsonReflection.put("thumbnailURL", "some url");

        ClientResponse reflectionResponse = loginAndSave(jsonReflection);

        ReflectionRepresentation reflection = getEntity(reflectionResponse);

        assertThat(reflectionResponse.getStatus(), is(200));

        assertThat(reflection.getThumbnailURL(), is("some url"));

        jsonReflection.put("thumbnailURL", "some other url");

        reflectionResponse = loginAndSave(jsonReflection);
        reflection = getEntity(reflectionResponse);

        assertThat(reflectionResponse.getStatus(), is(200));

        assertThat(reflection.getThumbnailURL(), is("some other url"));
    }

    @Test
    public void shouldSaveAbout() {

        Operation operation = Operations.sequenceOf(DataSetup.DELETE_ALL,DataSetup.INSERT_CATEGORY,  DataSetup.INSERT_PERSON);

        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        JSONObject jsonReflection = new JSONObject();

        jsonReflection.put("title", "reflection");
        jsonReflection.put("verb", "by");
        jsonReflection.put("soundCloudId", "1234");
        jsonReflection.put("youtubeVideoId", "12345");
        jsonReflection.put("showOnMainFcPage", true);
        jsonReflection.put("publish", true);
        jsonReflection.put("about", "some text");

        ClientResponse reflectionResponse = loginAndSave(jsonReflection);

        assertThat(reflectionResponse.getStatus(), is(200));

        assertThat(getEntity(reflectionResponse).getAbout(), is("some text"));
    }

    @Test
    public void shouldEditAbout() {
        Operation operation = Operations.sequenceOf(DataSetup.DELETE_ALL);

        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        JSONObject jsonReflection = new JSONObject();

        jsonReflection.put("title", "reflection");
        jsonReflection.put("verb", "by");
        jsonReflection.put("soundCloudId", "1234");
        jsonReflection.put("youtubeVideoId", "12345");
        jsonReflection.put("showOnMainFcPage", true);
        jsonReflection.put("publish", true);
        jsonReflection.put("about", "some text");

        ClientResponse reflectionResponse = loginAndSave(jsonReflection);

        ReflectionRepresentation reflection = getEntity(reflectionResponse);

        assertThat(reflectionResponse.getStatus(), is(200));

        assertThat(reflection.getAbout(), is("some text"));

        jsonReflection.put("about", "some other text");

        reflectionResponse = loginAndSave(jsonReflection);
        reflection = getEntity(reflectionResponse);

        assertThat(reflectionResponse.getStatus(), is(200));

        assertThat(reflection.getAbout(), is("some other text"));
    }

    @Test
    public void shouldSaveReflectionExcerpt() {

        Operation operation = Operations.sequenceOf(DataSetup.DELETE_ALL,DataSetup.INSERT_CATEGORY, DataSetup.INSERT_PERSON);

        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        JSONObject jsonReflection = new JSONObject();

        jsonReflection.put("title", "reflection");
        jsonReflection.put("verb", "by");
        jsonReflection.put("soundCloudId", "1234");
        jsonReflection.put("youtubeVideoId", "12345");
        jsonReflection.put("showOnMainFcPage", true);
        jsonReflection.put("publish", true);
        jsonReflection.put("reflectionExcerpt", "some text");

        ClientResponse reflectionResponse = loginAndSave(jsonReflection);

        assertThat(reflectionResponse.getStatus(), is(200));

        assertThat(getEntity(reflectionResponse).getReflectionExcerpt(), is("some text"));
    }

    @Test
    public void shouldEditReflectionExcerpt() {
        Operation operation = Operations.sequenceOf(DataSetup.DELETE_ALL);

        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        JSONObject jsonReflection = new JSONObject();

        jsonReflection.put("title", "reflection");
        jsonReflection.put("verb", "by");
        jsonReflection.put("soundCloudId", "1234");
        jsonReflection.put("youtubeVideoId", "12345");
        jsonReflection.put("showOnMainFcPage", true);
        jsonReflection.put("publish", true);
        jsonReflection.put("reflectionExcerpt", "some text");

        ClientResponse reflectionResponse = loginAndSave(jsonReflection);

        ReflectionRepresentation reflection = getEntity(reflectionResponse);

        assertThat(reflectionResponse.getStatus(), is(200));

        assertThat(reflection.getReflectionExcerpt(), is("some text"));

        jsonReflection.put("reflectionExcerpt", "some other text");

        reflectionResponse = loginAndSave(jsonReflection);
        reflection = getEntity(reflectionResponse);

        assertThat(reflectionResponse.getStatus(), is(200));

        assertThat(reflection.getReflectionExcerpt(), is("some other text"));
    }

    @Test
    public void shouldSaveDuration() {

        Operation operation = Operations.sequenceOf(DataSetup.DELETE_ALL, DataSetup.INSERT_CATEGORY, DataSetup.INSERT_PERSON);

        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        JSONObject jsonReflection = new JSONObject();

        jsonReflection.put("title", "reflection");
        jsonReflection.put("verb", "by");
        jsonReflection.put("soundCloudId", "1234");
        jsonReflection.put("youtubeVideoId", "12345");
        jsonReflection.put("showOnMainFcPage", true);
        jsonReflection.put("publish", true);
        jsonReflection.put("duration", "100");

        ClientResponse reflectionResponse = loginAndSave(jsonReflection);

        assertThat(reflectionResponse.getStatus(), is(200));

        assertThat(getEntity(reflectionResponse).getDuration(), is("100"));
    }

    @Test
    public void shouldEditDuration() {
        Operation operation = Operations.sequenceOf(DataSetup.DELETE_ALL);

        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        JSONObject jsonReflection = new JSONObject();

        jsonReflection.put("title", "reflection");
        jsonReflection.put("verb", "by");
        jsonReflection.put("soundCloudId", "1234");
        jsonReflection.put("youtubeVideoId", "12345");
        jsonReflection.put("showOnMainFcPage", true);
        jsonReflection.put("publish", true);
        jsonReflection.put("duration", "100");

        ClientResponse reflectionResponse = loginAndSave(jsonReflection);

        ReflectionRepresentation reflection = getEntity(reflectionResponse);

        assertThat(reflectionResponse.getStatus(), is(200));

        assertThat(reflection.getDuration(), is("100"));

        jsonReflection.put("duration", "200");

        reflectionResponse = loginAndSave(jsonReflection);
        reflection = getEntity(reflectionResponse);

        assertThat(reflectionResponse.getStatus(), is(200));

        assertThat(reflection.getDuration(), is("200"));
    }

    @Test
    public void shouldGetReflectionsByIds(){
        Operation operation = Operations.sequenceOf(DataSetup.DELETE_ALL, DataSetup.INSERT_COMPLETE_STARTER_SET);

        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        ClientResponse reflectionResponse = client.resource(
                String.format("http://localhost:%d/api/reflections/summaries?", RULE.getLocalPort(), 1, 2))
                .queryParam("ids", "1")
                .queryParam("ids","2")
                .header("Content-type", "application/json")
                .get(ClientResponse.class);

        Set<LinkedHashMap> reflectionSummaries = reflectionResponse.getEntity(Set.class);

        assertNotNull(reflectionSummaries);
        assertEquals(2, reflectionSummaries.size());
        Iterator<LinkedHashMap> summaryRepresentationIterator = reflectionSummaries.iterator();
        assertEquals("Oh that wonderful song!", summaryRepresentationIterator.next().get("title"));
        assertEquals("I hate that word!", summaryRepresentationIterator.next().get("title"));
    }

    @Test
    public void shouldGetReflectionsByIdsEvenWhenThereIsJustOneId(){
        Operation operation = Operations.sequenceOf(DataSetup.DELETE_ALL,DataSetup.INSERT_COMPLETE_STARTER_SET);

        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        ClientResponse reflectionResponse = client.resource(
                String.format("http://localhost:%d/api/reflections/summaries?", RULE.getLocalPort()))
                .queryParam("ids","1")
                .header("Content-type", "application/json")
                .get(ClientResponse.class);

        LinkedHashSet reflectionSummaries = reflectionResponse.getEntity(LinkedHashSet.class);

        assertNotNull(reflectionSummaries);
        assertEquals(1,reflectionSummaries.size());
        LinkedHashMap  summaryRepresentation = (LinkedHashMap) reflectionSummaries.iterator().next();
        assertEquals("Oh that wonderful song!", summaryRepresentation.get("title"));
    }

    @Test
    public void shouldGetReflectionAndRelatedContent(){
        Operation operation = Operations.sequenceOf(DataSetup.DELETE_ALL,DataSetup.INSERT_COMPLETE_STARTER_SET);

        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        ClientResponse reflectionResponse = client.resource(
                String.format("http://localhost:%d/api/reflections/edit", RULE.getLocalPort()))
                .queryParam("id","1")
                .header("Content-type", "application/json")
                .get(ClientResponse.class);

        ReflectionRepresentation reflectionRepresentation =  reflectionResponse.getEntity(ReflectionRepresentation.class);

        assertNotNull(reflectionRepresentation);
        assertThat(reflectionRepresentation.getWords().size(), greaterThan(0));
        assertThat(reflectionRepresentation.getSongs().size(), greaterThan(0));
        assertThat(reflectionRepresentation.getPeople().size(),greaterThan(0));
    }

    @Test
    public void shouldGetReflectionsByPerson() {
        Operation operation = Operations.sequenceOf(DataSetup.DELETE_ALL,DataSetup.INSERT_COMPLETE_STARTER_SET);

        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        ClientResponse reflectionResponse = client.resource(
                String.format("http://localhost:%d/api/reflections/summaries?personId=1", RULE.getLocalPort()))
                .get(ClientResponse.class);

        Set<ReflectionsSummaryRepresentation> reflectionsSummaryRepresentation = reflectionResponse.getEntity(Set.class);

        assertEquals(1,reflectionsSummaryRepresentation.size());

    }

    private static String resourceFilePath(String resource) {
        return ClassLoader.getSystemClassLoader().getResource(resource).getFile();
    }

    private ClientResponse loginAndSave(JSONObject jsonReflection) {
        String userCredentials = "{\"username\":\"admin\",\"password\":\"password\"}";

        ClientResponse clientResponse = client.resource(
                String.format("http://localhost:%d/api/login", RULE.getLocalPort())).header("Content-type", "application/json")
                .post(ClientResponse.class, userCredentials);

        NewCookie sessionCookie = geCookie(clientResponse);

        return client.resource(
                String.format("http://localhost:%d/api/reflections", RULE.getLocalPort()))
                .header("Content-type", "application/json")
                .cookie(sessionCookie)
                .post(ClientResponse.class, jsonReflection);
    }

    private ClientResponse getReflection(int id) {
        return client.resource(
                String.format("http://localhost:%d/api/reflections/edit?id=%d", RULE.getLocalPort(), id))
                .header("Content-type", "application/json")
                .get(ClientResponse.class);
    }

    private NewCookie geCookie(ClientResponse response) {
        return getCookie(response, "JSESSIONID");
    }

    private NewCookie getCookie(ClientResponse response, String name) {
        NewCookie sessionCookie = null;
        for (NewCookie cookie : response.getCookies()) {
            if (cookie.getName().equalsIgnoreCase(name)) {
                sessionCookie = cookie;
            }
        }
        return sessionCookie;
    }
}


text:
<?php

namespace Raindrop\LocaleBundle\Tests\LocaleGuesser;

use Raindrop\LocaleBundle\LocaleGuesser\BrowserLocaleGuesser;
use Raindrop\LocaleBundle\LocaleGuesser\LocaleGuesserInterface;
use Symfony\Component\HttpFoundation\Request;

class BrowserLocaleGuesserTest extends \PHPUnit_Framework_TestCase
{
    public function testGuesserExtendsInterface()
    {
        $metaValidator = $this->getMetaValidatorMock();
        $guesser = $this->getGuesser($metaValidator);
        $this->assertTrue($guesser instanceof LocaleGuesserInterface);
    }

    public function testNoPreferredLocale()
    {
        $metaValidator = $this->getMetaValidatorMock();
        $guesser = $this->getGuesser($metaValidator);
        $request = Request::create('/');
        $request->headers->set('Accept-language', '');
        $this->assertFalse($guesser->guessLocale($request));
        $this->assertFalse($guesser->getIdentifiedLocale());
    }

    public function testLocaleIsIdentifiedFromBrowser()
    {
        $metaValidator = $this->getMetaValidatorMock();
        $request = $this->getRequestWithBrowserPreferences();
        $guesser = $this->getGuesser($metaValidator);

        $metaValidator->expects($this->once())
                ->method('isAllowed')
                ->will($this->returnValue(true));

        $this->assertTrue($guesser->guessLocale($request));
        $this->assertEquals('fr_FR', $guesser->getIdentifiedLocale());
    }

    public function testLocaleIsIdentifiedFromBrowserTestFallbackForNoIntlExtension()
    {
        $metaValidator = $this->getMetaValidatorMock();
        $request = $this->getRequestWithBrowserPreferences();
        $guesser = $this->getGuesser($metaValidator);

        $reflectionClass = new \ReflectionClass($guesser);
        $property = $reflectionClass->getProperty('intlExtension');
        $property->setAccessible(true);
        $property->setValue($guesser, false);

        $metaValidator->expects($this->once())
                ->method('isAllowed')
                ->with('fr_FR')
                ->will($this->returnValue(true));

        $this->assertTrue($guesser->guessLocale($request));
        $this->assertEquals('fr_FR', $guesser->getIdentifiedLocale());
    }

    public function testLocaleIsNotIdentifiedIsNoMatchedLanguage()
    {
        $metaValidator = $this->getMetaValidatorMock();
        $request = $this->getRequestWithBrowserPreferences();
        $guesser = $this->getGuesser($metaValidator);

        $metaValidator->expects($this->any())
                ->method('isAllowed')
                ->will($this->returnValue(false));
        $this->assertFalse($guesser->guessLocale($request));
        $this->assertFalse($guesser->getIdentifiedLocale());
    }

    public function testLocaleIsNotIdentifiedIsNoMatchedLanguageTestFallbackForNoIntlExtension()
    {
        $metaValidator = $this->getMetaValidatorMock();
        $request = $this->getRequestWithBrowserPreferences();
        $guesser = $this->getGuesser($metaValidator);

        $reflectionClass = new \ReflectionClass($guesser);
        $property = $reflectionClass->getProperty('intlExtension');
        $property->setAccessible(true);
        $property->setValue($guesser, false);

        $metaValidator->expects($this->any())
                ->method('isAllowed')
                ->will($this->returnValue(false));

        $guesser->guessLocale($request);
        $this->assertFalse($guesser->getIdentifiedLocale());
    }

    public function correctLocales()
    {
        return array(
            'strict 1' => array(array('en', 'de', 'fr'), 'fr', true),
            'unstrict 1' => array(array('en', 'de', 'fr'), 'fr_CH', false),
            'strict 2' => array(array('de', 'en_GB', 'fr', 'fr_FR'), 'fr', true),
            'unstrict 2' => array(array('de', 'en_GB', 'fr', 'fr_FR'), 'fr_CH', false),
            'strict 3' => array(array('en', 'en_GB', 'fr', 'fr'), 'fr', true),
            'unstrict 3' => array(array('en', 'en_GB', 'fr', 'fr_CH'), 'fr_CH', false),
            'strict 4' => array(array('fr', 'en_GB'), 'fr', true),
            'unstrict 4' => array(array('fr', 'en_GB'), 'fr_CH', false),
            'strict 5' => array(array('fr_LI', 'en'), 'en', true),
            'unstrict 5' => array(array('fr_LI', 'en'), 'en_GB', false)
        );
    }

    /**
     * @dataProvider correctLocales
     *
     * @param array  $allowedLocales
     * @param string $result
     */
    public function testEnsureCorrectLocaleForAllowedLocales($allowedLocales, $result, $strict)
    {
        $metaValidator = $this->getMetaValidatorMock();
        $request = $this->getRequestWithBrowserPreferencesMultipleLangLocales();
        $guesser = $this->getGuesser($metaValidator, $allowedLocales);

        // Emulate a simple validator for strict mode
        $metaValidator->expects($this->atLeastOnce())
                ->method('isAllowed')
                ->will($this->returnCallback(function ($v) use ($allowedLocales, $strict) {
            if (in_array($v, $allowedLocales)) {
                return true;
            } elseif (!$strict) {
                $splittedLocale = explode('_', $v);
                $v = count($splittedLocale) > 1 ? $splittedLocale[0] : $v;

                return in_array($v, $allowedLocales);
            }

            return false;
        }));

        $this->assertTrue($guesser->guessLocale($request));
        $this->assertEquals($result, $guesser->getIdentifiedLocale());
    }

    private function getGuesser($metaValidator, $allowedLocales = array('en', 'fr', 'de'))
    {
        $guesser = new BrowserLocaleGuesser($metaValidator, $allowedLocales);

        return $guesser;
    }

    private function getRequestWithBrowserPreferences()
    {
        $request = Request::create('/');
        $request->headers->set('Accept-language', 'fr-FR,fr;q=0.1,en-US;q=0.6,en;q=0.4');

        return $request;
    }

    private function getRequestWithBrowserPreferencesMultipleLangLocales()
    {
        $request = Request::create('/');
        $request->headers->set('Accept-language', 'fr-CH,fr;q=0.8,fr-FR;q=0.7, en-GB;q=0.6,en;q=0.5');

        return $request;
    }

    private function getMetaValidatorMock()
    {
        $mock = $this->getMockBuilder('\Raindrop\LocaleBundle\Validator\MetaValidator')->disableOriginalConstructor()->getMock();

        return $mock;
    }
}

redpajama_set_name: RedPajamaGithub


text:
A lightweight state machine implementation for Android.

## Download

Via gradle. In main build.gradle :

```gradle
allprojects {
    repositories {
        ...
        maven {
            url "https://oss.sonatype.org/content/repositories/snapshots"
        }
    }
}
```

Add library:

```gradle
compile 'com.polidea:statemachine:1.0.0-SNAPSHOT'
```

or Maven. Add plugin repository:

```xml
<pluginRepository>
    <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
    <snapshots>
        <enabled>true</enabled>
    </snapshots>
</pluginRepository>
```

Add library:

```xml
<dependency>
  <groupId>com.polidea</groupId>
  <artifactId>statemachine</artifactId>
  <version>1.0.0-SNAPSHOT</version>
</dependency>
```

**It is a stable version of library**

## Usage

### Creating custom BaseStateableHandler

The easiest way to use StateMachine is to extend `BaseStateableHandler`. It have 4 main methods that we should override:

* `getStateProvider()` - used by State's to get data from our Fragment/Activity. Base StateProvider contains one method `provideContext()`
* `getActionInterface()` - used by State's to perform action's on Activity/Fragment, e.g. show Toast.
* `getInitialStateClass()` - initial state class for `StateMachine`. By default it returns `InitialState` class.
* `onStateMachineDescribe(StateMachine stateMachine)` - here we should describe transitions between states in our `StateMachine`. Each transition is a set of: from class, to class, event id. It means: when current state is 'from state' and it will propagate 'event id' then state machine should go to 'to state'.

Sample `BaseStateableHandler`:

```java
public class LoginStateableHandler extends BaseStateableHandler<LoginProvider, LoginActionInterface> implements LoginProvider, LoginActionInterface {
    @Override
    public LoginProvider getStateProvider() {
        return this;
    }

    @Override
    public LoginActionInterface getActionInterface() {
        return this;
    }

    @Override
    public int provideFragmentContainerId() {
        return R.id.fragment_container;
    }

    @Override
    public void onStateMachineDescribe(StateMachine<LoginProvider, LoginActionInterface> stateMachine) {
        stateMachine.addTransitionFromClass(LoginInitialState.class, LoginEvents.START_LOGIN, OnGoingLoginState.class);

        stateMachine.addTransitionFromClass(OnGoingLoginState.class, LoginEvents.CANCELLED, LoginInitialState.class);
        stateMachine.addTransitionFromClass(OnGoingLoginState.class, LoginEvents.SENDING_IN_PROGRESS, WaitingForLoginRequestState.class);

        stateMachine.addTransitionFromClass(WaitingForLoginRequestState.class, LoginEvents.FINISHED, InitialState.class);
    }

    @Override
    public Class<? extends State> getInitialStateClass() {
        return LoginInitialState.class;
    }

    ...
}
```

As you can see here, state machine contains 3 states: `LoginInitialState`, `OnGoingLoginState` and `WaitingForLoginRequestState`. Initial state is `LoginInitialState`. Looking at one of transition:

```java
stateMachine.addTransitionFromClass(LoginInitialState.class, LoginEvents.START_LOGIN, OnGoingLoginState.class);
```

means that, when state machine is in `LoginInitialState` and that state will fire `LoginEvents.START_LOGIN` event, then state machine should go to state `OnGoingLoginState`.

### Starting custom BaseStateableHandler

To make `LoginStateableHandler` work, you must remember to call it's `onCreate(Bundle savedInstanceState)`, `onResume()`, `onPause()`, `onSaveInstanceState(Bundle outState)` methods in appropriate Fragment/Activity lifecycle method's. Sample usage:

```java
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    handler = new LoginStateableHandler();
    handler.onCreate(savedInstanceState);
}

@Override
protected void onResume() {
    super.onResume();
    handler.onResume();
}

@Override
protected void onPause() {
    super.onPause();
    handler.onPause();
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    handler.onSaveInstanceState(outState);
}
```

Of course you can initialize handler from other places, not only Fragment/Activity. Here is an example of starting handler in singleton class like `Application`:

```java
public class MyApplication extends Application {

    LoginStateableHandler handler;

    @Override
    public void onCreate() {
        super.onCreate();

        handler = new LoginStateableHandler();
        handler.onCreate(null);
        handler.onResume();
    }
}
```

### Creating states

State machine consist of states. Each state should extends `State` that contains two methods:

* `onStateApplied()` - called when entering state
* `onStateLeft()` - called when leaving state

Each state should call `fireEvent(int eventId)` when it finish it's job. Sample `State`:

```java
public class OnGoingLoginState extends State<LoginProvider, LoginActionInterface>{

    @Inject
    Bus bus;

    @Inject
    NetworkManager networkManager;

    public OnGoingLoginState() {
        Application.getComponentInstance().inject(this);
    }

    @Override
    public void onStateApplied() {
        bus.register(this);
    }

    @Override
    public void onStateLeft() {
        bus.unregister(this);
    }

    @Subscribe
    public void onBusLoginEvent(BusLoginEvent loginEvent) {
        networkManager.loginUser(loginEvent.getEmail(), loginEvent.getPassword());
        fireEvent(LoginEvents.SENDING_IN_PROGRESS);
    }
}
```

It is nice to use some Bus implementation, like [EventBus](https://github.com/greenrobot/EventBus) or [Otto](https://github.com/square/otto), to receive applications events.<p/>
In that example we use [Otto](https://github.com/square/otto) for sending `BusLoginEvent` (it may be send by activity when 'Login' button tapped) and receiving that event in `OnGoingLoginState`.

## Used libraries

* **[otto]** https://github.com/square/otto
* **[dagger 2]** https://github.com/google/dagger
* **[spock]** https://code.google.com/p/spock/
* **[android support library v7]**

## LICENSE

[LICENSE](./LICENSE)


text:
layout: default
title: Confirmed Message Receipt
---

# Use Cases

A publisher wants to know that a message it has sent has been recieved.


text:
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:security="http://www.springframework.org/schema/security"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/security
       http://www.springframework.org/schema/security/spring-security.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd">

    <tx:annotation-driven />

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost/board"/>
        <property name="username" value="root"/>
        <property name="password" value="xander"/>
    </bean>

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <bean id="messageBoardService" class="org.xander.spring.springIdol.springSecurity.service.MessageBoardServiceImpl" >
        <property name="mutableAclService" ref="aclService" />
    </bean>
</beans>


text: gensrc-overlay


text:
package com.cloudbees.plugins.credentials;

import com.cloudbees.plugins.credentials.matchers.AllOfMatcher;
import com.cloudbees.plugins.credentials.matchers.AnyOfMatcher;
import com.cloudbees.plugins.credentials.matchers.ConstantMatcher;
import com.cloudbees.plugins.credentials.matchers.IdMatcher;
import com.cloudbees.plugins.credentials.matchers.InstanceOfMatcher;
import com.cloudbees.plugins.credentials.matchers.NotMatcher;
import com.cloudbees.plugins.credentials.matchers.ScopeMatcher;
import com.cloudbees.plugins.credentials.matchers.UsernameMatcher;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Some standard matchers and filtering utility methods.
 *
 * @since 1.5
 */
public class CredentialsMatchers {

    /**
     * Utility class.
     */
    private CredentialsMatchers() {
        throw new UnsupportedOperationException("Utility class");
    }

    /**
     * Creates a matcher that always matches.
     *
     * @return a matcher that always matches.
     */
    @NonNull
    public static CredentialsMatcher always() {
        return new ConstantMatcher(true);
    }

    /**
     * Creates a matcher that never matches.
     *
     * @return a matcher that never matches.
     */
    @NonNull
    public static CredentialsMatcher never() {
        return new ConstantMatcher(false);
    }

    /**
     * Creates a matcher that inverts the supplied matcher.
     *
     * @param matcher matcher to invert.
     * @return a matcher that is the opposite of the supplied matcher.
     */
    @NonNull
    public static CredentialsMatcher not(@NonNull CredentialsMatcher matcher) {
        return new NotMatcher(matcher);
    }

    /**
     * Creates a matcher that matches credentials of the specified type.
     *
     * @param clazz the type of credential to match.
     * @return a matcher that matches credentials of the specified type.
     */
    @NonNull
    public static CredentialsMatcher instanceOf(@NonNull Class clazz) {
        return new InstanceOfMatcher(clazz);
    }

    /**
     * Creates a matcher that matches {@link com.cloudbees.plugins.credentials.common.IdCredentials} with the
     * supplied {@link com.cloudbees.plugins.credentials.common.IdCredentials#getId()}
     *
     * @param id the {@link com.cloudbees.plugins.credentials.common.IdCredentials#getId()} to match.
     * @return a matcher that matches {@link com.cloudbees.plugins.credentials.common.IdCredentials} with the
     *         supplied {@link com.cloudbees.plugins.credentials.common.IdCredentials#getId()}
     */
    @NonNull
    public static CredentialsMatcher withId(@NonNull String id) {
        return new IdMatcher(id);
    }

    /**
     * Creates a matcher that matches {@link Credentials} with the supplied {@link CredentialsScope}.
     *
     * @param scope the {@link CredentialsScope} to match.
     * @return a matcher that matches {@link Credentials} with the supplied {@link CredentialsScope}.
     */
    @NonNull
    public static CredentialsMatcher withScope(@NonNull CredentialsScope scope) {
        return new ScopeMatcher(scope);
    }

    /**
     * Creates a matcher that matches {@link Credentials} with the supplied {@link CredentialsScope}.
     *
     * @param scopes the {@link CredentialsScope}s to match.
     * @return a matcher that matches {@link Credentials} with the supplied {@link CredentialsScope}s.
     */
    @NonNull
    public static CredentialsMatcher withScopes(@NonNull CredentialsScope... scopes) {
        return new ScopeMatcher(scopes);
    }

    /**
     * Creates a matcher that matches {@link Credentials} with the supplied {@link CredentialsScope}.
     *
     * @param scopes the {@link CredentialsScope}s to match.
     * @return a matcher that matches {@link Credentials} with the supplied {@link CredentialsScope}s.
     */
    @NonNull
    public static CredentialsMatcher withScopes(@NonNull Collection<CredentialsScope> scopes) {
        return new ScopeMatcher(scopes);
    }

    /**
     * Creates a matcher that matches {@link com.cloudbees.plugins.credentials.common.UsernameCredentials} with the
     * supplied {@link com.cloudbees.plugins.credentials.common.UsernameCredentials#getUsername()}
     *
     * @param username the {@link com.cloudbees.plugins.credentials.common.UsernameCredentials#getUsername()} to match.
     * @return a matcher that matches {@link com.cloudbees.plugins.credentials.common.UsernameCredentials} with the
     *         supplied {@link com.cloudbees.plugins.credentials.common.UsernameCredentials#getUsername()}
     */
    @NonNull
    public static CredentialsMatcher withUsername(@NonNull String username) {
        return new UsernameMatcher(username);
    }

    /**
     * Creates a matcher that matches when all of the supplied matchers match.
     *
     * @param matchers the matchers to match.
     * @return a matcher that matches when all of the supplied matchers match.
     */
    @NonNull
    public static CredentialsMatcher allOf(@NonNull CredentialsMatcher... matchers) {
        return new AllOfMatcher(Arrays.asList(matchers));
    }

    /**
     * Creates a matcher that matches when any of the supplied matchers match.
     *
     * @param matchers the matchers to match.
     * @return a matcher that matches when any of the supplied matchers match.
     */
    @NonNull
    public static CredentialsMatcher anyOf(@NonNull CredentialsMatcher... matchers) {
        return new AnyOfMatcher(Arrays.asList(matchers));
    }

    /**
     * Creates a matcher that matches when both of the supplied matchers match.
     *
     * @param matcher1 the first matcher to match.
     * @param matcher2 the second matcher to match.
     * @return a matcher that matches when both of the supplied matchers match.
     */
    @NonNull
    public static CredentialsMatcher both(@NonNull CredentialsMatcher matcher1, @NonNull CredentialsMatcher matcher2) {
        return new AllOfMatcher(Arrays.asList(matcher1, matcher2));
    }

    /**
     * Creates a matcher that matches when either of the supplied matchers match.
     *
     * @param matcher1 the first matcher to match.
     * @param matcher2 the second matcher to match.
     * @return a matcher that matches when either of the supplied matchers match.
     */
    @NonNull
    public static CredentialsMatcher either(@NonNull CredentialsMatcher matcher1,
                                            @NonNull CredentialsMatcher matcher2) {
        return new AnyOfMatcher(Arrays.asList(matcher1, matcher2));
    }

    /**
     * Creates a matcher that matches when none of the supplied matchers match.
     *
     * @param matchers the matchers to match.
     * @return a matcher that matches when none of the supplied matchers match.
     */
    @NonNull
    public static CredentialsMatcher noneOf(@NonNull CredentialsMatcher... matchers) {
        return not(anyOf(matchers));
    }

    /**
     * Filters credentials using the supplied matcher.
     *
     * @param credentials the credentials to filter.
     * @param matcher     the matcher to match on.
     * @param <C>         the type of credentials.
     * @return only those credentials that match the supplied matcher.
     */
    @NonNull
    public static <C extends Credentials> Collection<C> filter(@NonNull Collection<C> credentials,
                                                               @NonNull CredentialsMatcher matcher) {
        Collection<C> result = credentials instanceof Set ? new LinkedHashSet<C>() : new ArrayList<C>();
        for (C credential : credentials) {
            if (credential != null && matcher.matches(credential)) {
                result.add(credential);
            }
        }
        return result;
    }

    /**
     * Filters credentials using the supplied matcher.
     *
     * @param credentials the credentials to filter.
     * @param matcher     the matcher to match on.
     * @param <C>         the type of credentials.
     * @return only those credentials that match the supplied matcher.
     */
    @NonNull
    public static <C extends Credentials> Set<C> filter(@NonNull Set<C> credentials,
                                                        @NonNull CredentialsMatcher matcher) {
        Set<C> result = new LinkedHashSet<C>();
        for (C credential : credentials) {
            if (credential != null && matcher.matches(credential)) {
                result.add(credential);
            }
        }
        return result;
    }

    /**
     * Filters credentials using the supplied matcher.
     *
     * @param credentials the credentials to filter.
     * @param matcher     the matcher to match on.
     * @param <C>         the type of credentials.
     * @return only those credentials that match the supplied matcher.
     */
    @NonNull
    public static <C extends Credentials> List<C> filter(@NonNull List<C> credentials,
                                                         @NonNull CredentialsMatcher matcher) {
        List<C> result = new ArrayList<C>();
        for (C credential : credentials) {
            if (credential != null && matcher.matches(credential)) {
                result.add(credential);
            }
        }
        return result;
    }

    /**
     * Filters credentials using the supplied matcher.
     *
     * @param credentials the credentials to filter.
     * @param matcher     the matcher to match on.
     * @param <C>         the type of credentials.
     * @return only those credentials that match the supplied matcher.
     */
    @NonNull
    public static <C extends Credentials> Iterable<C> filter(@NonNull Iterable<C> credentials,
                                                             @NonNull CredentialsMatcher matcher) {
        List<C> result = new ArrayList<C>();
        for (C credential : credentials) {
            if (credential != null && matcher.matches(credential)) {
                result.add(credential);
            }
        }
        return result;
    }

    /**
     * Filters a map keyed by credentials using the supplied matcher.
     *
     * @param credentialMap the map keyed by credentials to filter.
     * @param matcher       the matcher to match on.
     * @param <C>           the type of credentials.
     * @param <V>           the type of the map values.
     * @return only those entries with keys that that match the supplied matcher.
     */
    @NonNull
    public static <C extends Credentials, V> Map<C, V> filterKeys(@NonNull Map<C, V> credentialMap,
                                                                  @NonNull CredentialsMatcher matcher) {
        Map<C, V> result = new LinkedHashMap<C, V>();
        for (Map.Entry<C, V> credential : credentialMap.entrySet()) {
            if (credential.getKey() != null && matcher.matches(credential.getKey())) {
                result.put(credential.getKey(), credential.getValue());
            }
        }
        return result;
    }

    /**
     * Filters a map based on credential values using the supplied matcher.
     *
     * @param credentialMap the map with credentials values to filter.
     * @param matcher       the matcher to match on.
     * @param <K>           the type of the map keys.
     * @param <C>           the type of credentials.
     * @return only those entries with keys that that match the supplied matcher.
     */
    @NonNull
    public static <C extends Credentials, K> Map<K, C> filterValues(@NonNull Map<K, C> credentialMap,
                                                                    @NonNull CredentialsMatcher matcher) {
        Map<K, C> result = new LinkedHashMap<K, C>();
        for (Map.Entry<K, C> credential : credentialMap.entrySet()) {
            if (credential.getValue() != null && matcher.matches(credential.getValue())) {
                result.put(credential.getKey(), credential.getValue());
            }
        }
        return result;
    }

    /**
     * Returns the first credential from a collection that matches the supplied matcher or if none match then the
     * specified default.
     *
     * @param credentials   the credentials to select from.
     * @param matcher       the matcher.
     * @param defaultIfNone the default value if no match found.
     * @param <C>           the type of credential.
     * @return a matching credential or the supplied default.
     */
    @CheckForNull
    public static <C extends Credentials> C firstOrDefault(@NonNull Iterable<C> credentials,
                                                           @NonNull CredentialsMatcher matcher,
                                                           @CheckForNull C defaultIfNone) {
        for (C c : credentials) {
            if (matcher.matches(c)) {
                return c;
            }
        }
        return defaultIfNone;
    }

    /**
     * Returns the first credential from a collection that matches the supplied matcher or {@code null} if none match.
     *
     * @param credentials   the credentials to select from.
     * @param matcher       the matcher.
     * @param <C>           the type of credential.
     * @return a matching credential or the supplied default.
     */
    @CheckForNull
    public static <C extends Credentials> C firstOrNull(@NonNull Iterable<C> credentials,
                                                           @NonNull CredentialsMatcher matcher) {
        return firstOrDefault(credentials, matcher, null);
    }
}


text:
ACCEPTED

#### According to
Interim Register of Marine and Nonmarine Genera

#### Published in
Acta Bot. Hung. 11: 208.

#### Original name
null

### Remarks
null


text:
package org.lorislab.armonitor.web.rs.mapper;

import java.util.Set;
import org.kohsuke.MetaInfServices;
import org.lorislab.armonitor.activity.wrapper.ActivityChangeLogWrapper;
import org.lorislab.armonitor.mapper.MapperService;
import org.lorislab.armonitor.store.model.StoreActivityLog;
import org.lorislab.armonitor.store.model.StoreBuild;
import org.lorislab.armonitor.web.rs.model.ActivityChangeLog;

/**
 *
 * @author Andrej Petras
 */
@MetaInfServices
public class ActivityChangeLogMapper implements MapperService<ActivityChangeLogWrapper, ActivityChangeLog> {

    @Override
    public ActivityChangeLog map(ActivityChangeLogWrapper data, Set<String> profiles) {
        ActivityChangeLog result = new ActivityChangeLog();
        result.link = data.getLink();

        // add the log
        StoreActivityLog log = data.getLog();
        result.id = log.getRevision();
        result.user = log.getUser();
        result.message = log.getMessage();
        result.date = log.getDate();

        // add the build
        StoreBuild build = log.getBuild();
        if (build != null) {
            result.build = build.getGuid();
            result.version = build.getMavenVersion();
            result.rc = build.getBuild();
        }
        return result;
    }

    @Override
    public ActivityChangeLogWrapper update(ActivityChangeLogWrapper entity, ActivityChangeLog data, Set<String> profiles) {
        return entity;
    }

    @Override
    public ActivityChangeLogWrapper create(ActivityChangeLog data, Set<String> profiles) {
        return null;
    }

    @Override
    public ActivityChangeLog create(Set<String> profiles) {
        return null;
    }

}


text:
@echo off
REM Extract the contents of every zip file in the current directory into
REM seperate directories

REM 7z.exe must be accessible from the "Path" environment variable

REM BUGS:
REM   *Unable to extract from archives with a filename that contains an
REM    exclamation point (!) or an ampersand (&)
setlocal EnableDelayedExpansion
if errorlevel 1 (
	echo Unable to enable Delayed variable expansion
	exit /B
)

set debug=no
set destination=%cd%
set single_dir=no

if -%1-==-- goto loopend

:argloop
if %1==--debug (
	set debug=yes
) else if %1==-d (
	set debug=yes
) else if %1==-p (
	set pass=%2
	shift
) else if %1==--password (
	set pass=%2
	shift
) else if %1==--single-directory (
	set single_dir=yes
) else if %1==-sd (
	set single_dir=yes
) else if %1==--output-directory (
	set destination=%~2
	shift
) else if %1==-od (
	set destination=%~2
	shift
) else if %1==here (
	set single_dir=yes
	set destination=.
) else if %1==-h (
	goto printHelp
) else if %1==--help (
	goto printHelp
)
shift
if not -%1-==-- goto argloop

:loopend
REM Add trailing slash if necessary
if not !destination:~-1!==\ (
	if not !destination:~-1!==/ (
		set destination=!destination!\
	)
)

REM "xzips.bat -sd"
REM In this situation a new directory should be created to hold the contents
REM of all the archives since extracting everything to the current directory
REM might clutter it up. All archives' contents can be extracted to the housing
REM directory with "xzips -sd -od ." or with the shorthand "xzips here"
if !single_dir!==yes (
	if "!destination!" == "%cd%\" (
		set destination=!destination!archives\
	)
)

for %%i in (*) do (
	set _procfile=no
	if %%~xi==.zip set _procfile=yes
	if %%~xi==.rar set _procfile=yes
	if %%~xi==.tar set _procfile=yes
	if %%~xi==.gz set _procfile=yes
	if %%~xi==.7z set _procfile=yes
	if %%~xi==.xz set _procfile=yes
	if %%~xi==.bz2 set _procfile=yes
	if %%~xi==.001 set _procfile=yes
	if !_procfile!==yes (
		if !single_dir!==no (
			set tmp_dst=!destination!%%~ni
			if !debug!==yes (
				echo 7z.exe x -r -o"!tmp_dst!" -p!pass! "%%i"
			) else (
				call 7z.exe x -r -o"!tmp_dst!" -p!pass! "%%i"
			)
		) else (
			if !debug!==yes (
				echo 7z.exe x -r -o"!destination!" -p!pass! "%%i"
			) else (
				call 7z.exe x -r -o"!destination!" -p!pass! "%%i"
			)
		)
	)
)
exit /B

:printHelp
echo Extracts the contents of every zip file in the current directory
echo.
echo xzips [options] [here]
echo.
echo   OPTIONS
echo   -d, --debug
echo       Don't extract any archives, print the command to the console instead
echo   -p, --password
echo       Extract archives using the provided password
echo   -sd, --single-directory
echo       Extract all archives to the same directory
echo   -od dir (--output-directory)
echo       Directory to output the archive contents to
echo   here
echo       Shorthand for "-sd -od .", effectively extracting every archive's
echo       contents to the current directory
echo   -h, --help
echo       Print this message
echo.
echo If no options are specified, the contents of each zip file will be stored
echo in their own new directory named after the archive.
echo The -sd option will consolidate the contents of all archives into just the
echo output directory (current directory if not specified). If -sd is the only
echo option specified a new directory will be created to hold the archives'
echo contents.
echo "xzips -sd -od ." or "xzips here" can be used to store all archive
echo contents in the current directory
echo.
echo PASSWORDS
echo When entering a password you must enclose it with qutation marks.
echo Also, if the password contains an exclamation mark or an ampersand you must
echo escape it when passing the string to the script.
echo.
echo     ex: D:\home\Desktop^> xzips -sd -p "12^^^!35"
echo.
echo Also bere in mind that the debugging flag won't work when specifying a password
echo that includes one of those characters.
exit /B


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

  <properties>
    <site.staging.base>${project.parent.parent.basedir}</site.staging.base>

    <aopalliance.bundle.version>1.0_5</aopalliance.bundle.version>
    <beanlib.bundle.version>5.0.2beta_1-SNAPSHOT</beanlib.bundle.version>
    <cglib.bundle.version>2.2_2</cglib.bundle.version>
    <commons-beanutils.bundle.version>1.8.2_2</commons-beanutils.bundle.version>
    <commons-configuration.bundle.version>1.4_3</commons-configuration.bundle.version>
    <commons-digester.bundle.version>1.8_3</commons-digester.bundle.version>
    <commons-httpclient.bundle.version>3.1_6</commons-httpclient.bundle.version>
    <commons-jxpath.bundle.version>1.2_5</commons-jxpath.bundle.version>
    <commons-validator.bundle.version>1.3.1_1-SNAPSHOT</commons-validator.bundle.version>
    <dom4j.bundle.version>1.6.1_4</dom4j.bundle.version>
    <ehcache.bundle.version>2.4.3_1</ehcache.bundle.version>
    <freemarker.bundle.version>2.3.18_1</freemarker.bundle.version>
    <javassist.bundle.version>3.12.1.ga_1</javassist.bundle.version>
    <javax-inject.bundle.version>1_1</javax-inject.bundle.version>
    <jcharset.version>1.0</jcharset.version>
    <jcip-annotations.bundle.version>1.0_1-SNAPSHOT</jcip-annotations.bundle.version>
    <jdom.bundle.version>1.1_4</jdom.bundle.version>
    <joda-time.bundle.version>1.5.2_4</joda-time.bundle.version>
    <jsoup.bundle.version>1.5.2_1</jsoup.bundle.version>
    <junit.bundle.version>4.9_1</junit.bundle.version>
    <lucene.bundle.version>3.0.3_2</lucene.bundle.version>
    <maven.archetype.version>2.1</maven.archetype.version>
    <maven-model-v3.version>2.0</maven-model-v3.version>
    <ognl.bundle.version>2.7.3_5</ognl.bundle.version>
    <oro.bundle.version>2.0.8_5</oro.bundle.version>
    <plexus-classworlds.version>2.4</plexus-classworlds.version>
    <plexus-component-annotations.version>1.5.5</plexus-component-annotations.version>
    <plexus-interpolation.version>1.14</plexus-interpolation.version>
    <plexus-velocity.version>1.1.8</plexus-velocity.version>
    <quartz.bundle.version>2.1.0_1-SNAPSHOT</quartz.bundle.version>
    <rome.bundle.version>1.0_2</rome.bundle.version>
    <servicemix.specs.version>1.9.0</servicemix.specs.version>
    <sisu-inject-bean.version>2.3.0</sisu-inject-bean.version>
    <guava.version>14.0.1</guava.version>
    <stax-utils.bundle.version>20040917_2</stax-utils.bundle.version>
    <testng.version>6.3.1</testng.version>
    <velocity.bundle.version>1.7_3</velocity.bundle.version>
    <velocity-tools.version>2.0-alpha1</velocity-tools.version>
    <xpp3.bundle.version>1.1.4c_5</xpp3.bundle.version>
    <xstream.bundle.version>1.4_1</xstream.bundle.version>
    <ws-commons-util.bundle.version>1.0.2_1-SNAPSHOT</ws-commons-util.bundle.version>
  </properties>

  <build>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <filtering>true</filtering>
        <includes>
          <include>**/*</include>
        </includes>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-resources-plugin</artifactId>
        <configuration>
          <useDefaultDelimiters>false</useDefaultDelimiters>
          <delimiters>
            <delimiter>${*}</delimiter>
          </delimiters>
        </configuration>
        <executions>
          <execution>
            <id>filter</id>
            <phase>generate-resources</phase>
            <goals>
              <goal>resources</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>build-helper-maven-plugin</artifactId>
        <executions>
          <execution>
            <id>attach-artifact</id>
            <phase>package</phase>
            <goals>
              <goal>attach-artifact</goal>
            </goals>
            <configuration>
              <artifacts>
                <artifact>
                  <file>target/classes/features.xml</file>
                  <type>xml</type>
                  <classifier>features</classifier>
                </artifact>
              </artifacts>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

  <profiles>
    <profile>
      <id>validate</id>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.karaf.tooling</groupId>
            <artifactId>features-maven-plugin</artifactId>
            <version>2.4.1</version>
            <configuration>
              <file>${project.build.directory}/classes/features.xml</file>
              <karafConfig>${project.build.directory}/classes/config.properties</karafConfig>
              <jreVersion>jre-1.6</jreVersion>
            </configuration>
            <executions>
              <execution>
                <id>validate</id>
                <phase>process-resources</phase>
                <goals>
                  <goal>validate</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>

</project>


text:
import logging = require('./logging');
import npm = require('./npm-package');
var log = new logging.Log();

export class Grunt {
    grunt;
    registeredTasks: string[] = [];

    public constructor(grunt) {
        this.grunt = grunt;
    }

    public registerExternalTask(name: string, dependencies : string[], callback) {
        new npm.Package().installIfFileNotExist(name, dependencies, () => {
            process.chdir(global.relativeDir);
            this.grunt.loadNpmTasks(name);
            process.chdir(global.basedir);
            callback();
        });
    }

    public registerTask(name: string, description: string, onTaskStart: () => void) {
        if (this.registeredTasks.some((_) => _ === name)) {
            return;
        }
        this.registeredTasks.push(name);
        this.grunt.registerTask(name, description, onTaskStart);
        log.verbose.writeln("Grunt", "Loaded task " + name);
    }

    public initConfig(config : any) {
        this.grunt.initConfig(config);
    }

    public run(task : string) {
        this.grunt.task.run(task);
    }
}


text:
process.env.NODE_ENV = 'test';
require('should');
var helpers = require(__dirname + '/../helpers');
var models  = require(__dirname + '/../../../server/models');

describe('Boards', function() {
    var userOwner;
    var users;

    beforeEach(function(done) {
        users = [];

        // Cleanup and create a bunch of testusers
        helpers.createTestDatabase()
            .then(function() { return models.User.make({ name: 'Testuser', password: 'password'}); })
            .then(function(user) {
                userOwner = user;
                return models.User.make({ name: 'OtherUser1', password: 'password'});
            })
            .then(function(user) { users.push(user); return models.User.make({ name: 'OtherUser2', password: 'password'}); })
            .then(function(user) { users.push(user); return models.User.make({ name: 'OtherUser3', password: 'password'}); })
            .then(function(user) { users.push(user); done(); })
            .catch(function(err) { done(err); });
    });

    describe('Creation', function() {
        it('should not accept board-creation without a user', function(done) {
            models.Board.make(null, { name: 'Testboard' })
                .then(function() { done(new Error('Board created even without valid user')); })
                .catch(function(err) {
                    err.message.should.match(/Invalid user/);
                    done();
                });
        });

        it('should not accept board-creation with a non-existing user', function(done) {
            var user = models.User.build({ name: 'Not saved user' });
            models.Board.make(user, { name: 'Testboard'})
                .then(function() { done(new Error('Board created with a not saved user-instance')); })
                .catch(function(err) {
                    err.message.should.match(/Invalid user/);
                    done();
                });
        });

        it('should not be able to add a board without a name', function(done) {
            models.Board.make(userOwner, {})
                .then(function() { done(new Error('Added board without a name')); })
                .catch(function() { done(); });
        });

        it('should not be able to add a board with an empty name', function(done) {
            models.Board.make(userOwner, {})
                .then(function() { done(new Error('Added board with an empty name')); })
                .catch(function() { done(); });
        });

        it('should create a board and make the user an admin', function(done) {
            models.Board.make(userOwner, { name: 'Testboard'})
                .then(function(board) {
                    models.Board.isBoard(board).should.equal(true);
                    board.name.should.equal('Testboard');
                    board.private.should.equal(true);
                    return board.getUsers();
                })
                .then(function(u) {
                    var user = u[0];
                    user.id.should.equal(userOwner.id);
                    user.name.should.equal(userOwner.name);
                    user.BoardUsers.admin.should.equal(true);
                    done();
                })
                .catch(function(err) { done(err); });
        });

        it('should create a non-private board', function(done) {
            models.Board.make(userOwner, { name: 'Testboard', private: false})
                .then(function(board) {
                    board.name.should.equal('Testboard');
                    board.private.should.equal(false);
                    done();
                }).catch(function(err) { done(err); });
        });
    });

    describe('Users', function() {
        var board;
        beforeEach(function(done) {
            models.Board.make(userOwner, { name: 'Testboard'}).then(function(b) {
                board = b;
                done();
            }).catch(function(err) { done(err); });
        });

        it('should be able to add users to a board', function(done) {
            board.addUser(users[0])
                .then(function() { return board.addUser(users[1], { admin: false }); })
                .then(function() { return board.addUser(users[2], { admin: true }); })
                .then(function() { return board.getUsers(); })
                .then(function(u) {
                    u.length.should.equal(4);
                    u[0].id.should.equal(userOwner.id);
                    u[0].BoardUsers.admin.should.equal(true);
                    u[1].id.should.equal(users[0].id);
                    u[1].BoardUsers.admin.should.equal(false);
                    u[2].id.should.equal(users[1].id);
                    u[2].BoardUsers.admin.should.equal(false);
                    u[3].id.should.equal(users[2].id);
                    u[3].BoardUsers.admin.should.equal(true);
                    done();
                })
                .catch(function(err) { done(err); });
        });

        it('should add a user only once', function(done) {
            board.addUser(users[0])
                .then(function() { return board.addUser(users[0]); })
                .then(function() { return board.getUsers(); })
                .then(function(u) {
                    u.length.should.equal(2);
                    u[1].id.should.equal(users[0].id);
                    done();
                })
                .catch(function(err) { done(err); });
        });

        it('should be able to verify that a user is participating in a board', function(done) {
            board.addUser(users[0])
                .then(function() { return board.hasUser(users[0]); })
                .then(function(isParticipating) {
                    isParticipating.should.equal(true);
                    done();
                })
                .catch(function(err) { done(err); });
        });

        it('should be able to verify that a user is no participant of a board', function(done) {
            board.addUser(users[0])
                .then(function() { return board.hasUser(users[1]); })
                .then(function(isParticipating) {
                    isParticipating.should.equal(false);
                    done();
                })
                .catch(function(err) { done(err); });
        });

        it('should remove a user from a board', function(done) {
            board.addUser(users[0])
                .then(function() { return board.removeUser(users[0]); })
                .then(function() { return board.hasUser(users[0]); })
                .then(function(isParticipating) {
                    isParticipating.should.equal(false);
                    done();
                })
                .catch(function(err) { done(err); });
        });

        it('should promote a user to admin', function(done) {
            board.addUser(users[0], { admin: false })
                .then(function() { return board.getUsers(); })
                .then(function(u) {
                    u[1].BoardUsers.admin.should.equal(false);
                    u[1].BoardUsers.admin = true;
                    return u[1].BoardUsers.save();
                })
                .then(function() { return board.getUsers(); })
                .then(function(u) {
                    u[1].BoardUsers.admin.should.equal(true);
                    done();
                })
                .catch(function(err) { done(err); });
        });

        it('should degrade an admin to user', function(done) {
            board.addUser(users[0], { admin: true })
                .then(function() { return board.getUsers(); })
                .then(function(u) {
                    u[1].BoardUsers.admin.should.equal(true);
                    u[1].BoardUsers.admin = false;
                    return u[1].BoardUsers.save();
                })
                .then(function() { return board.getUsers(); })
                .then(function(u) {
                    u[1].BoardUsers.admin.should.equal(false);
                    done();
                })
                .catch(function(err) { done(err); });
        });

        it('should verify if a user is a board admin', function(done) {
            board.addUser(users[0], { admin: true })
                .then(function() { return board.isAdmin(users[0]); })
                .then(function(isAdmin) {
                    isAdmin.should.equal(true);
                    done();
                })
                .catch(function(err) { done(err); });
        });

        it('should verify that a user is not a board admin', function(done) {
            board.isAdmin(users[0])
                .then(function(isAdmin) {
                    isAdmin.should.equal(false);
                    done();
                })
                .catch(function(err) { done(err); });
        });
    });
});


text:
<?php

function domain_mapping_gc_cache( $function, $directory ) {
	global $cache_path;

	if ( ! function_exists( 'domain_mapping_warning' ) ) {
		return false;
	}

	$siteurl = domain_mapping_siteurl( false );
	if ( ! $siteurl ) {
		return false;
	}

	$protocol = ( isset( $_SERVER['HTTPS'] ) && 'on' === strtolower( $_SERVER['HTTPS'] ) ) ? 'https://' : 'http://';
	$siteurl  = trailingslashit( str_replace( $protocol, '', $siteurl ) );

	if ( 'homepage' === $directory ) {
		$directory = '';
	}

	switch ( $function ) {
		case 'rebuild':
			@wp_cache_rebuild_or_delete( $cache_path . 'supercache/' . $siteurl . $directory . 'index.html' );
			@wp_cache_rebuild_or_delete( $cache_path . 'supercache/' . $siteurl . $directory . 'index.html.gz' );
			break;
		case 'prune':
			prune_super_cache( $cache_path . 'supercache/' . $siteurl . $directory . 'index.html', true, true );
			prune_super_cache( $cache_path . 'supercache/' . $siteurl . $directory . 'index.html.gz', true, true );
			break;
	}

	return $directory;
}

function domain_mapping_supercachedir( $dir ) {
	global $cache_path;
	if ( ! function_exists( 'domain_mapping_warning' ) ) {
		return $dir;
	}

	$siteurl = domain_mapping_siteurl( false );
	if ( ! $siteurl ) {
		return $dir;
	}

	$protocol = ( isset( $_SERVER['HTTPS'] ) && 'on' === strtolower( $_SERVER['HTTPS'] ) ) ? 'https://' : 'http://';
	$siteurl  = str_replace( $protocol, '', $siteurl );
	return trailingslashit( $cache_path . 'supercache/' . $siteurl );
}

function domain_mapping_actions() {
	global $cache_domain_mapping;
	if ( '1' === $cache_domain_mapping ) {
		add_filter( 'wp_super_cache_supercachedir', 'domain_mapping_supercachedir' );
		add_action( 'gc_cache', 'domain_mapping_gc_cache', 10, 2 );
	}
}
add_cacheaction( 'add_cacheaction', 'domain_mapping_actions' );

function wp_supercache_domain_mapping_admin() {
	global $cache_domain_mapping, $wp_cache_config_file, $valid_nonce;

	$cache_domain_mapping = '' === $cache_domain_mapping ? '0' : $cache_domain_mapping;

	if ( isset( $_POST['cache_domain_mapping'] ) && $valid_nonce ) {
		if ( $cache_domain_mapping === (int) $_POST['cache_domain_mapping'] ) {
			$changed = false;
		} else {
			$changed = true;
		}
		$cache_domain_mapping = (int) $_POST['cache_domain_mapping'];
		wp_cache_replace_line( '^ *\$cache_domain_mapping', "\$cache_domain_mapping = '$cache_domain_mapping';", $wp_cache_config_file );
	}
	$id = 'domain_mapping-section';
	?>
		<fieldset id="<?php echo $id; ?>" class="options">

<?php _e( 'Domain Mapping', 'wp-super-cache' ); ?>

		<form name="wp_manager" action="" method="post">
		<input type="radio" name="cache_domain_mapping" value="1" <?php if ( $cache_domain_mapping ) { echo 'checked="checked" '; } ?>/> <?php _e( 'Enabled', 'wp-super-cache' ); ?>
		<input type="radio" name="cache_domain_mapping" value="0" <?php if ( ! $cache_domain_mapping ) { echo 'checked="checked" '; } ?>/> <?php _e( 'Disabled', 'wp-super-cache' ); ?>

<?php _e( '', 'wp-super-cache' ); ?>

	<?php
	echo '
' . __( 'Provides support for Domain Mapping plugin to map multiple domains to a blog.', 'wp-super-cache' ) . '
';
	if ( isset( $changed ) && $changed ) {
		if ( $cache_domain_mapping ) {
			$status = __( 'enabled', 'wp-super-cache' );
		} else {
			$status = __( 'disabled', 'wp-super-cache' );
		}
		echo '
' . sprintf( __( 'Domain Mapping support is now %s', 'wp-super-cache' ), $status ) . '
';
	}
	echo '
<input class="button-primary" ' . SUBMITDISABLED . 'type="submit" value="' . __( 'Update', 'wp-super-cache' ) . '" />
';
	wp_nonce_field( 'wp-cache' );
	?>
	</form>
	</fieldset>
	<?php
}
add_cacheaction( 'cache_admin_page', 'wp_supercache_domain_mapping_admin' );

function wp_supercache_domain_mapping_notice() {
	global $cache_enabled;
	if ( $cache_enabled ) {
		echo '

' . __( 'Domain Mapping plugin detected! Please go to the Supercache plugins page and enable the domain mapping helper plugin.', 'wp-super-cache' ) . '

';
	}
}
function wp_supercache_domain_mapping_exists() {
	global $cache_domain_mapping;
	if ( '1' === $cache_domain_mapping ) {
		return false;
	}

	if ( is_admin() && function_exists( 'domain_mapping_warning' ) ) {
		add_action( 'admin_notices', 'wp_supercache_domain_mapping_notice' );
	}
}

if ( isset( $_GET['page'] ) && 'wpsupercache' === $_GET['page'] ) {
	add_cacheaction( 'add_cacheaction', 'wp_supercache_domain_mapping_exists' );
}

function wpsc_domain_mapping_list( $list ) {
	$list['domain_mapping'] = array(
		'key'   => 'domain_mapping',
		'url'   => 'https://wordpress.org/plugins/wordpress-mu-domain-mapping/',
		'title' => __( 'Domain Mapping', 'wp-super-cache' ),
		'desc'  => __( 'Provides support for Domain Mapping plugin to map multiple domains to a blog.', 'wp-super-cache' ),
	);
	return $list;
}
add_cacheaction( 'wpsc_filter_list', 'wpsc_domain_mapping_list' );


text:
from livestreamer.stream import HTTPStream

def get_streams(session):
    return dict(support=HTTPStream(session, "http://test.se/support"))


text:
/*global module */
/*global process */

var generators = require( 'yeoman-generator' );
var path = require( 'path' );
var _ = require( 'lodash' );
var util = require( '../../lib/util' );
var commonPrompts = require( '../../lib/common-prompts' );
var bowerDefaults = require('../../lib/bower-defaults.json' );

module.exports = generators.Base.extend( {

   constructor: function() {
      'use strict';
      generators.Base.apply( this, arguments );
      this.argument( 'name', {
         type: String,
         required: false,
         desc: 'Name of the artifact'
      } );
      this.option( 'activity', {
         type: Boolean,
         defaults: false,
         desc: 'Create an activity instead of a widget'
      } );
      this.option( 'directory', {
         type: String,
         defaults: '',
         desc: 'Base directory for widgets'
      } );
      this.option( 'banner', {
         type: String,
         defaults: '',
         desc: 'Path to a file with a banner'
      } );
   },

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   initializing: function() {
      'use strict';
      var laxarIntegrationTechnology = this.config.get( 'laxarIntegrationTechnology' ) || 'plain';
      var artifactType = this.options.activity ? 'activity' : 'widget';

      var widgetName = util.determineArtifactName( this );
      this.widgetDirname = util.determineArtifactDirName( this, path.join( 'includes', 'widgets' ) );

      this.placeholder = {
         name: widgetName,
         description: '',
         licenseLabel: 'license',
         licenses: this.config.get( 'licenses' ),
         homepage: this.config.get( 'homepage' ),
         author: this.config.get( 'author' ),
         laxarIntegrationTechnology: laxarIntegrationTechnology,
         cssClassName: '',
         banner:  util.getBanner( this ),
         artifactType: artifactType,
         path: widgetName
      };

      this.placeholder.dependencies = bowerDefaults.dependencies;
      this.placeholder.devDependencies = bowerDefaults.devDependencies;
   },

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   prompting: function() {
      'use strict';
      var done = this.async();

      commonPrompts.greetings( this, this.placeholder.artifactType );

      var prompts = commonPrompts.prompts( this.placeholder.artifactType, this.placeholder );
      if( this.options.activity ) {
         prompts.push( {
            type: 'list',
            name: 'laxarIntegrationTechnology',
            message: 'Integration technology:',
            choices: [ 'plain', 'angular' ],
            default: this.placeholder.laxarIntegrationTechnology
         } );
      }
      else {
         prompts.push( {
            type: 'list',
            name: 'laxarIntegrationTechnology',
            message: 'Integration technology:',
            choices: [ 'plain', 'angular', 'react' ],
            default: this.placeholder.laxarIntegrationTechnology
         } );
      }

      prompts.push( {
         type: 'confirm',
         name: 'infrastructure',
         message: 'Create project infrastructure (README.md, bower.json)?',
         default: false
      } );

      this.prompt( prompts, function( answers ) {

         for( var answerName in answers ) {
            if( answers.hasOwnProperty( answerName ) ) {
               this.placeholder[ answerName ] = answers[ answerName ];
            }
         }

         var licenseList = util.createLicenseText( answers.licenses );
         this.license = licenseList[ 1 ];
         for( var key in licenseList[ 0 ] ) {
            if( licenseList[ 0 ].hasOwnProperty( key ) ) {
               this.placeholder[ key ] = licenseList[ 0 ][ key ];
            }
         }

         this.placeholder.angularModuleName =
            _.camelCase( this.placeholder.name );
         this.placeholder.angularControllerName =
            _.capitalize( _.camelCase( this.placeholder.name ) ) + 'Controller';

         if( !this.options.activity ) {
            this.placeholder.cssClassName = _.kebabCase( this.placeholder.name );
         }

         this.placeholder.banner = util.createBanner( this );
         done();

      }.bind( this ) );
   },

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   configuring: function() {
      'use strict';
      this.config.set( {
         author: this.placeholder.author,
         homepage: this.placeholder.homepage,
         licenses: this.license,
         laxarIntegrationTechnology: this.placeholder.laxarIntegrationTechnology,
         banner: this.placeholder.banner
      } );
   },

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   writing: function() {
      'use strict';
      var filesToCopy = {
         'widget.json': 'widget.json',
         'gitignore': '.gitignore',
         'spec/spec_runner.html': 'spec/spec_runner.html',
         'spec/spec_runner.js': 'spec/spec_runner.js',
         'spec/widget.spec.js': 'spec/' + this.placeholder.name + '.spec.js'
      };
      var integrationTechnology = this.placeholder.laxarIntegrationTechnology;
      var widget = !this.options.activity;

      if( widget && integrationTechnology !== 'react' ) {
         filesToCopy[ 'default.theme/widget.html' ] = 'default.theme/' + this.placeholder.name + '.html';
      }
      if( widget ) {
         filesToCopy[ 'default.theme/css/widget.css' ] = 'default.theme/css/' + this.placeholder.name + '.css';
      }

      if( integrationTechnology === 'plain' ) {
         if( !widget ) {
            filesToCopy[ 'controller.plain.activity.js' ] = this.placeholder.name + '.js';
         }
         else {
            filesToCopy[ 'controller.plain.widget.js' ] = this.placeholder.name + '.js';
         }
      }
      else if( integrationTechnology === 'angular' ) {
         filesToCopy[ 'controller.angular.js' ] = this.placeholder.name + '.js';
      }
      else if( integrationTechnology === 'react' ) {
         filesToCopy[ 'controller.react.jsx' ] = this.placeholder.name + '.jsx';
      }

      if( this.placeholder.infrastructure ) {
         filesToCopy[ 'README.md' ] = 'README.md';
         if( widget && integrationTechnology !== 'react') {
            filesToCopy[ 'bower.widget.json' ] = 'bower.json';
         }
         else if ( widget && integrationTechnology === 'react' ) {
            filesToCopy[ 'bower.react.widget.json' ] = 'bower.json';
         }
         else {
            filesToCopy[ 'bower.activity.json' ] = 'bower.json';
         }
      }
      for( var file in filesToCopy ) {
         if( filesToCopy.hasOwnProperty( file ) ) {
            this.fs.copyTpl(
               this.templatePath( file ),
               this.destinationPath(
                  path.join( this.widgetDirname, this.placeholder.name, filesToCopy[ file ] )
               ),
               this.placeholder
            );
         }
      }
   },

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   end: function() {
      'use strict';
      if( this.placeholder.laxarIntegrationTechnology === 'react' ) {
         var link = 'https://laxarjs.org/docs/laxar-react-adapter-v0-latest/';
         this.log( '\nEnsure that your application is prepared for using the ' +
                   this.placeholder.laxarIntegrationTechnology + ' adapter or do the necessary steps which' +
                   ' are described in the documentation of the adapter:' );
         this.log( link );
         this.log( '\nThen you can start developing your ' + this.placeholder.artifactType + '!' );
      }
      else {
         this.log( '\nYou can now start developing your ' + this.placeholder.artifactType + '!' );
      }
      this.log( 'For more information about developing widgets with LaxarJS, please refer to the manuals:' );
      this.log( '\nhttps://laxarjs.org/docs/laxar-v1-latest/manuals/' );
   }
} );


text:
@(elements: views.html.helper.FieldElements)

@import play.api.i18n._
@import views.html.helper._

  	@elements.label
    @elements.input
    @if(elements.hasErrors){
      @elements.errors.mkString("", " , ", "")
    }

@{/*   FOR BOOTSTRAP 2

  @elements.label

    @elements.input
    @if(elements.hasErrors){
      @elements.errors.mkString("", " , ", "")
    }

*/}


text:
using System;
using System.Linq;
using Newtonsoft.Json;
using TraktSharp.Helpers;

namespace TraktSharp.Entities {

	/// Settings for a user's account
	[Serializable]
	public class TraktAccountSettings {

		/// The user's timezone represented in the form of an Olson timezone ID string
		[JsonProperty(PropertyName = "timezone")]
		public string OlsonTimeZoneId { get; set; }

		///
		///     The user's timezone represented in the form of a <see cref="TimeZoneInfo" /> instance (derived from
		///     <see cref="OlsonTimeZoneId" />)
		///
		[JsonIgnore]
		public TimeZoneInfo TimeZone => !string.IsNullOrEmpty(OlsonTimeZoneId) ? TraktTimeZoneHelper.FromOlsonTimeZoneId(OlsonTimeZoneId) : default;

		/// A cover image for the user's account
		[JsonProperty(PropertyName = "cover_image")]
		public string CoverImage { get; set; }

	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<metadata>
  <groupId>com.googlecode.forplay</groupId>
  <artifactId>forplay-hello-core-archetype</artifactId>
  <versioning>
    <versions>
      <version>1.0-SNAPSHOT</version>
    </versions>
    <lastUpdated>20110722062231</lastUpdated>
  </versioning>
</metadata>