text:
package org.datanucleus.tests;

import java.util.Calendar;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaDelete;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.CriteriaUpdate;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Fetch;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.ParameterExpression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.metamodel.EntityType;
import javax.persistence.metamodel.Metamodel;

import org.datanucleus.samples.jpa.query.AbstractPerson;
import org.datanucleus.samples.jpa.query.Manager;
import org.datanucleus.samples.jpa.query.Manager_;
import org.datanucleus.samples.jpa.query.Person;
import org.datanucleus.samples.jpa.query.Player;
import org.datanucleus.samples.jpa.query.Player_;
import org.datanucleus.samples.jpa.query.Team;
import org.datanucleus.samples.jpa.query.Team_;
import org.datanucleus.tests.JPAPersistenceTestCase;

/**
 * Tests for the Criteria API in JPA using generated criteria classes.
 */
public class CriteriaMetaModelTest extends JPAPersistenceTestCase
{
    private static boolean initialised = false;

    public CriteriaMetaModelTest(String name)
    {
        super(name);
        if (!initialised)
        {
            addClassesToSchema(new Class[]
                {
                });
        }
    }

    /* (non-Javadoc)
     * @see org.datanucleus.tests.PersistenceTestCase#setUp()
     */
    @Override
    protected void setUp() throws Exception
    {
        super.setUp();

        EntityManager em = getEM();
        EntityTransaction tx = em.getTransaction();
        try
        {
            tx.begin();

            Team team1 = new Team(1, "Real Madrid");
            Manager mgr1 = new Manager(1, "Jose", "Mourinho", 8);
            mgr1.setTeam(team1);
            team1.setManager(mgr1);
            em.persist(team1);

            Team team2 = new Team(2, "Barcelona");
            Manager mgr2 = new Manager(2, "Pep", "Guardiola", 3);
            mgr2.setTeam(team2);
            team2.setManager(mgr2);
            em.persist(team2);

            Player pl1 = new Player(101, "David", "Beckham");
            Calendar cal = GregorianCalendar.getInstance();
            cal.set(Calendar.YEAR, 1989);
            cal.set(Calendar.MONTH, 8);
            cal.set(Calendar.DAY_OF_MONTH, 1);
            pl1.setStartDate(cal.getTime());
            em.persist(pl1);

            tx.commit();
        }
        finally
        {
            if (tx.isActive())
            {
                tx.rollback();
            }
            em.close();
        }
    }

    /* (non-Javadoc)
     * @see org.datanucleus.tests.PersistenceTestCase#tearDown()
     */
    @Override
    protected void tearDown() throws Exception
    {
        EntityManager em = getEM();
        EntityTransaction tx = em.getTransaction();
        try
        {
            tx.begin();

            Query q = em.createQuery("SELECT t FROM Team t");
            List<Team> teams = q.getResultList();
            Iterator<Team> teamIter = teams.iterator();
            while (teamIter.hasNext())
            {
                Team team = teamIter.next();
                Manager mgr = team.getManager();
                mgr.setTeam(null);
            }

            tx.commit();
        }
        finally
        {
            if (tx.isActive())
            {
                tx.rollback();
            }
            em.close();
        }
        clean(Player.class);
        clean(Team.class);
        clean(Manager.class);
        clean(Person.class);

        super.tearDown();
    }

    /**
     * Test some simple metamodel requests.
     */
    public void testMetamodel()
    {
        EntityManager em = getEM();
        EntityTransaction tx = em.getTransaction();
        try
        {
            tx.begin();

            Metamodel mm = em.getMetamodel();
            Set<EntityType<?>> ets = mm.getEntities();
            boolean personPresent = false;
            boolean abstractPersonPresent = false;
            for (EntityType<?> ent : ets)
            {
                if (ent.getJavaType().getName().equals(Person.class.getName()))
                {
                    personPresent = true;
                }
                if (ent.getJavaType().getName().equals(AbstractPerson.class.getName()))
                {
                    abstractPersonPresent = true;
                }
            }
            assertTrue(Person.class.getName() + " is not listed as Entity in MetaModel", personPresent);
            assertFalse(AbstractPerson.class.getName() + " is listed as Entity in MetaModel!", abstractPersonPresent);

            tx.rollback();
        }
        finally
        {
            if (tx.isActive())
            {
                tx.rollback();
            }
            em.close();
        }
    }

    /**
     * Test basic generation of query with candidate and alias.
     */
    public void testCandidate()
    {
        EntityManager em = getEM();
        EntityTransaction tx = em.getTransaction();
        try
        {
            tx.begin();

            CriteriaBuilder qb = emf.getCriteriaBuilder();
            CriteriaQuery<Team> crit = qb.createQuery(Team.class);
            Root<Team> candidate = crit.from(Team.class);
            candidate.alias("t");
            crit.select(candidate);

            // DN extension
            assertEquals("Generated JPQL query is incorrect",
                "SELECT t FROM org.datanucleus.samples.jpa.query.Team t", crit.toString());

            Query q = em.createQuery(crit);
            List<Team> teams = q.getResultList();

            assertNotNull("Null results returned!", teams);
            assertEquals("Number of results is incorrect", 2, teams.size());
            boolean realmadrid = false;
            boolean barcelona = false;
            Iterator<Team> teamIter = teams.iterator();
            while (teamIter.hasNext())
            {
                Team team = teamIter.next();
                if (team.getName().equals("Barcelona"))
                {
                    barcelona = true;
                }
                else if (team.getName().equals("Real Madrid"))
                {
                    realmadrid = true;
                }
            }
            assertTrue("Barcelona not returned", barcelona);
            assertTrue("Real Madrid not returned", realmadrid);

            tx.rollback();
        }
        finally
        {
            if (tx.isActive())
            {
                tx.rollback();
            }
            em.close();
        }
    }

    /**
     * Test basic querying for a candidate with a filter
     */
    public void testFilter()
    {
        EntityManager em = getEM();
        EntityTransaction tx = em.getTransaction();
        try
        {
            tx.begin();

            CriteriaBuilder qb = emf.getCriteriaBuilder();

            CriteriaQuery<Manager> crit = qb.createQuery(Manager.class);
            Root<Manager> candidate = crit.from(Manager.class);
            candidate.alias("m");
            crit.select(candidate);

            Predicate ageLessThan = qb.lessThan(candidate.get(Manager_.yearsExperience), 5);
            crit.where(ageLessThan);

            // DN extension
            assertEquals("Generated JPQL query is incorrect",
                "SELECT m FROM org.datanucleus.samples.jpa.query.Manager m WHERE (m.yearsExperience < 5)", crit.toString());

            Query q = em.createQuery(crit);
            List<Manager> results = q.getResultList();

            assertNotNull("Null results returned!", results);
            assertEquals("Number of results is incorrect", 1, results.size());
            Iterator<Manager> iter = results.iterator();
            boolean guardiola = false;
            while (iter.hasNext())
            {
                Manager mgr = iter.next();
                if (mgr.getFirstName().equals("Pep") && mgr.getLastName().equals("Guardiola"))
                {
                    guardiola = true;
                }
            }
            assertTrue("Guardiola was not returned!", guardiola);

            tx.rollback();
        }
        finally
        {
            if (tx.isActive())
            {
                tx.rollback();
            }
            em.close();
        }
    }

    /**
     * Test basic querying for a candidate with a filter
     */
    public void testFilterWithDate()
    {
        EntityManager em = getEM();
        EntityTransaction tx = em.getTransaction();
        try
        {
            tx.begin();

            CriteriaBuilder qb = emf.getCriteriaBuilder();

            CriteriaQuery<Player> crit = qb.createQuery(Player.class);
            Root<Player> candidate = crit.from(Player.class);
            candidate.alias("p");
            crit.select(candidate);

            Calendar cal = GregorianCalendar.getInstance();
            cal.set(Calendar.YEAR, 1987);
            cal.set(Calendar.MONTH, 1);
            cal.set(Calendar.DAY_OF_MONTH, 1);
            Predicate ageGreaterThan = qb.greaterThan(candidate.get(Player_.startDate), cal.getTime());
            crit.where(ageGreaterThan);

            // DN extension
//            assertEquals("Generated JPQL query is incorrect",
//                "SELECT p FROM org.datanucleus.samples.jpa.query.Player p WHERE (p.startDate > 'date')", crit.toString());

            Query q = em.createQuery(crit);
            List<Player> results = q.getResultList();

            assertNotNull("Null results returned!", results);
            assertEquals("Number of results is incorrect", 1, results.size());
            Iterator<Player> iter = results.iterator();
            boolean beckham = false;
            while (iter.hasNext())
            {
                Player plyr = iter.next();
                if (plyr.getFirstName().equals("David") && plyr.getLastName().equals("Beckham"))
                {
                    beckham = true;
                }
            }
            assertTrue("Beckham was not returned!", beckham);

            tx.rollback();
        }
        finally
        {
            if (tx.isActive())
            {
                tx.rollback();
            }
            em.close();
        }
    }

    /**
     * Test basic querying for a candidate with a filter with 2 clauses
     */
    public void testFilter2()
    {
        EntityManager em = getEM();
        EntityTransaction tx = em.getTransaction();
        try
        {
            tx.begin();

            CriteriaBuilder qb = emf.getCriteriaBuilder();

            CriteriaQuery<Manager> crit = qb.createQuery(Manager.class);
            Root<Manager> candidate = crit.from(Manager.class);
            candidate.alias("m");
            crit.select(candidate);

            Predicate yrsUpper = qb.lessThan(candidate.get(Manager_.yearsExperience), 5);
            Predicate yrsLower = qb.greaterThanOrEqualTo(candidate.get(Manager_.yearsExperience), 2);
            crit.where(yrsUpper, yrsLower);

            // DN extension
            assertEquals("Generated JPQL query is incorrect",
                "SELECT m FROM org.datanucleus.samples.jpa.query.Manager m WHERE (m.yearsExperience < 5) AND (m.yearsExperience >= 2)", crit.toString());

            Query q = em.createQuery(crit);
            List<Manager> results = q.getResultList();

            assertNotNull("Null results returned!", results);
            assertEquals("Number of results is incorrect", 1, results.size());
            Iterator<Manager> iter = results.iterator();
            boolean guardiola = false;
            while (iter.hasNext())
            {
                Manager mgr = iter.next();
                if (mgr.getFirstName().equals("Pep") && mgr.getLastName().equals("Guardiola"))
                {
                    guardiola = true;
                }
            }
            assertTrue("Guardiola was not returned!", guardiola);

            tx.rollback();
        }
        finally
        {
            if (tx.isActive())
            {
                tx.rollback();
            }
            em.close();
        }
    }

    /**
     * Test basic querying with a result.
     */
    public void testResult()
    {
        EntityManager em = getEM();
        EntityTransaction tx = em.getTransaction();
        try
        {
            tx.begin();

            CriteriaBuilder qb = emf.getCriteriaBuilder();

            CriteriaQuery<Manager> crit = qb.createQuery(Manager.class);
            Root<Manager> candidate = crit.from(Manager.class);
            Set<Join<Manager, ?>> joins = candidate.getJoins();
            assertNotNull(joins); // Make sure joins returns empty set
            assertEquals(0, joins.size());
            Set<Fetch<Manager, ?>> fetches = candidate.getFetches();
            assertNotNull(fetches); // Make sure fetches returns empty set
            assertEquals(0, fetches.size());

            candidate.alias("m");
            crit.multiselect(candidate.get(Manager_.firstName), candidate.get(Manager_.lastName));

            // DN extension
            assertEquals("Generated JPQL query is incorrect",
                "SELECT m.firstName,m.lastName FROM org.datanucleus.samples.jpa.query.Manager m", crit.toString());

            Query q = em.createQuery(crit);
            List<Object[]> results = q.getResultList();

            assertNotNull("Null results returned!", results);
            assertEquals("Number of results is incorrect", 2, results.size());
            boolean mourinho = false;
            boolean guardiola = false;
            Iterator<Object[]> resultIter = results.iterator();
            while (resultIter.hasNext())
            {
                Object[] result = resultIter.next();
                assertEquals(2, result.length);
                if (result[0].equals("Jose") && result[1].equals("Mourinho"))
                {
                    mourinho = true;
                }
                else if (result[0].equals("Pep") && result[1].equals("Guardiola"))
                {
                    guardiola = true;
                }
            }
            if (!mourinho)
            {
                fail("Jose Mourinho not returned");
            }
            if (!guardiola)
            {
                fail("Pep Guardiola not returned");
            }

            tx.rollback();
        }
        finally
        {
            if (tx.isActive())
            {
                tx.rollback();
            }
            em.close();
        }
    }

    /**
     * Test basic querying with a result with order.
     */
    public void testResultWithOrder()
    {
        EntityManager em = getEM();
        EntityTransaction tx = em.getTransaction();
        try
        {
            tx.begin();

            CriteriaBuilder qb = emf.getCriteriaBuilder();

            CriteriaQuery<Manager> crit = qb.createQuery(Manager.class);
            Root<Manager> candidate = crit.from(Manager.class);
            candidate.alias("m");
            crit.multiselect(candidate.get(Manager_.firstName), candidate.get(Manager_.lastName));

            crit.orderBy(qb.desc(candidate.get(Manager_.yearsExperience)));

            // DN extension
            assertEquals("Generated JPQL query is incorrect",
                "SELECT m.firstName,m.lastName FROM org.datanucleus.samples.jpa.query.Manager m ORDER BY m.yearsExperience DESC", crit.toString());

            Query q = em.createQuery(crit);
            List<Object[]> results = q.getResultList();

            assertNotNull("Null results returned!", results);
            assertEquals("Number of results is incorrect", 2, results.size());
            boolean mourinho = false;
            boolean guardiola = false;
            Iterator<Object[]> resultIter = results.iterator();
            while (resultIter.hasNext())
            {
                Object[] result = resultIter.next();
                assertEquals(2, result.length);
                if (result[0].equals("Jose") && result[1].equals("Mourinho"))
                {
                    mourinho = true;
                }
                else if (result[0].equals("Pep") && result[1].equals("Guardiola"))
                {
                    guardiola = true;
                }
            }
            if (!mourinho)
            {
                fail("Jose Mourinho not returned");
            }
            if (!guardiola)
            {
                fail("Pep Guardiola not returned");
            }

            tx.rollback();
        }
        finally
        {
            if (tx.isActive())
            {
                tx.rollback();
            }
            em.close();
        }
    }

    /**
     * Test basic querying for a candidate with an order.
     */
    public void testFilterWithOrder()
    {
        EntityManager em = getEM();
        EntityTransaction tx = em.getTransaction();
        try
        {
            tx.begin();

            CriteriaBuilder qb = emf.getCriteriaBuilder();

            CriteriaQuery<Manager> crit = qb.createQuery(Manager.class);
            Root<Manager> candidate = crit.from(Manager.class);
            candidate.alias("m");
            crit.select(candidate);

            Predicate ageLessThan = qb.greaterThan(candidate.get(Manager_.yearsExperience), 1);
            crit.where(ageLessThan);

            crit.orderBy(qb.asc(candidate.get(Manager_.yearsExperience)));

            // DN extension
            assertEquals("Generated JPQL query is incorrect",
                "SELECT m FROM org.datanucleus.samples.jpa.query.Manager m WHERE (m.yearsExperience > 1) ORDER BY m.yearsExperience ASC", crit.toString());

            Query q = em.createQuery(crit);
            List<Manager> managers = q.getResultList();

            assertNotNull("Managers is null!", managers);
            assertEquals("Number of managers is wrong", 2, managers.size());
            Manager mgr1 = managers.get(0);
            Manager mgr2 = managers.get(1);
            assertEquals("Pep", mgr1.getFirstName());
            assertEquals("Guardiola", mgr1.getLastName());
            assertEquals(3, mgr1.getYearsExperience());
            assertEquals("Jose", mgr2.getFirstName());
            assertEquals("Mourinho", mgr2.getLastName());
            assertEquals(8, mgr2.getYearsExperience());

            tx.rollback();
        }
        finally
        {
            if (tx.isActive())
            {
                tx.rollback();
            }
            em.close();
        }
    }

    /**
     * Test basic querying specifying null order clause
     */
    public void testFilterWithNullOrdering()
    {
        EntityManager em = getEM();
        EntityTransaction tx = em.getTransaction();
        try
        {
            tx.begin();

            CriteriaBuilder qb = emf.getCriteriaBuilder();

            CriteriaQuery<Manager> crit = qb.createQuery(Manager.class);
            Root<Manager> candidate = crit.from(Manager.class);
            candidate.alias("m");
            crit.select(candidate);

            Predicate ageLessThan = qb.greaterThan(candidate.get(Manager_.yearsExperience), 1);
            crit.where(ageLessThan);

            crit.orderBy(Collections.EMPTY_LIST);

            // DN extension
            assertEquals("Generated JPQL query is incorrect",
                "SELECT m FROM org.datanucleus.samples.jpa.query.Manager m WHERE (m.yearsExperience > 1)", crit.toString());

            Query q = em.createQuery(crit);
            List<Manager> managers = q.getResultList();

            assertNotNull("Managers is null!", managers);
            assertEquals("Number of managers is wrong", 2, managers.size());

            tx.rollback();
        }
        finally
        {
            if (tx.isActive())
            {
                tx.rollback();
            }
            em.close();
        }
    }

    /**
     * Test basic querying for a candidate with a filter.
     */
    public void testFilterWithMethodAndNamedParameter()
    {
        EntityManager em = getEM();
        EntityTransaction tx = em.getTransaction();
        try
        {
            tx.begin();

            CriteriaBuilder qb = emf.getCriteriaBuilder();

            CriteriaQuery<Manager> crit = qb.createQuery(Manager.class);
            Root<Manager> candidate = crit.from(Manager.class);
            candidate.alias("m");
            crit.select(candidate);

            ParameterExpression<String> param = qb.parameter(String.class, "myParam");
            Predicate ageLessThan = qb.like(candidate.get(Manager_.firstName), param);
            crit.where(ageLessThan);

            // DN extension
            assertEquals("Generated JPQL query is incorrect",
                "SELECT m FROM org.datanucleus.samples.jpa.query.Manager m WHERE m.firstName LIKE :myParam", crit.toString());

            Query q = em.createQuery(crit);
            q.setParameter("myParam", "Jo%");
            List<Manager> managers = q.getResultList();

            assertNotNull("Managers is null!", managers);
            assertEquals("Number of managers is wrong", 1, managers.size());
            Manager mgr1 = managers.get(0);
            assertEquals("Jose", mgr1.getFirstName());
            assertEquals("Mourinho", mgr1.getLastName());
            assertEquals(8, mgr1.getYearsExperience());

            tx.rollback();
        }
        finally
        {
            if (tx.isActive())
            {
                tx.rollback();
            }
            em.close();
        }
    }

    /**
     * Test basic querying for a candidate with a filter.
     */
    public void testFilterWithMethodAndUnnamedParameter()
    {
        EntityManager em = getEM();
        EntityTransaction tx = em.getTransaction();
        try
        {
            tx.begin();

            CriteriaBuilder qb = emf.getCriteriaBuilder();

            CriteriaQuery<Manager> crit = qb.createQuery(Manager.class);
            Root<Manager> candidate = crit.from(Manager.class);
            candidate.alias("m");
            crit.select(candidate);

            ParameterExpression<String> param = qb.parameter(String.class);
            Predicate ageLessThan = qb.like(candidate.get(Manager_.firstName), param);
            crit.where(ageLessThan);

            // DN extension
            assertEquals("Generated JPQL query is incorrect",
                "SELECT m FROM org.datanucleus.samples.jpa.query.Manager m WHERE m.firstName LIKE :DN_PARAM_0", crit.toString());

            Query q = em.createQuery(crit);
            q.setParameter(param, "Jo%");
            List<Manager> managers = q.getResultList();

            assertNotNull("Managers is null!", managers);
            assertEquals("Number of managers is wrong", 1, managers.size());
            Manager mgr1 = managers.get(0);
            assertEquals("Jose", mgr1.getFirstName());
            assertEquals("Mourinho", mgr1.getLastName());
            assertEquals(8, mgr1.getYearsExperience());

            tx.rollback();
        }
        finally
        {
            if (tx.isActive())
            {
                tx.rollback();
            }
            em.close();
        }
    }

    /**
     * Test generation of FROM with left outer join and ON clause.
     */
    public void testLeftOuterJoinOnQuery()
    {
        EntityManager em = getEM();
        EntityTransaction tx = em.getTransaction();
        try
        {
            tx.begin();

//          "SELECT Object(T) FROM " + Team.class.getName() + " T " +
//          "JOIN T.manager M ON M.lastName = 'Mourinho'").getResultList();

            CriteriaBuilder qb = emf.getCriteriaBuilder();
            CriteriaQuery<Team> crit = qb.createQuery(Team.class);
            Root<Team> candidate = crit.from(Team.class);
            candidate.alias("t");
            crit.select(candidate);
            Join<Team, Manager> mgrRoot = candidate.join(Team_.manager, JoinType.INNER);
            mgrRoot.alias("m");
            Predicate onCond = qb.equal(mgrRoot.get(Manager_.lastName), "Mourinho");
            mgrRoot.on(onCond);

            // DN extension
            assertEquals("Generated JPQL query is incorrect",
                "SELECT t FROM org.datanucleus.samples.jpa.query.Team t JOIN t.manager m ON (m.lastName = 'Mourinho')", crit.toString());

            Query q = em.createQuery(crit);
            List<Team> teams = q.getResultList();

            assertNotNull("Null results returned!", teams);
            assertEquals("Number of results is incorrect", 1, teams.size());
            boolean realmadrid = false;
            Iterator<Team> teamIter = teams.iterator();
            while (teamIter.hasNext())
            {
                Team team = teamIter.next();
                if (team.getName().equals("Real Madrid"))
                {
                    realmadrid = true;
                }
            }
            assertTrue("Real Madrid not returned", realmadrid);

            tx.rollback();
        }
        finally
        {
            if (tx.isActive())
            {
                tx.rollback();
            }
            em.close();
        }
    }

    /**
     * Test generation of a delete Criteria query
     */
    public void testDelete()
    {
        EntityManager em = getEM();
        EntityTransaction tx = em.getTransaction();
        try
        {
            tx.begin();

            CriteriaBuilder qb = emf.getCriteriaBuilder();
            CriteriaDelete<Team> crit = qb.createCriteriaDelete(Team.class);
            Root<Team> candidate = crit.from(Team.class);
            candidate.alias("t");
            Predicate teamName = qb.equal(candidate.get(Team_.name), "Barcelona");
            crit.where(teamName);

            // DN extension
            assertEquals("Generated JPQL delete query is incorrect",
                "DELETE FROM org.datanucleus.samples.jpa.query.Team t WHERE (t.name = 'Barcelona')", crit.toString());
            Query q = em.createQuery(crit);
            int num = q.executeUpdate();
            assertEquals("Number of objects deleted is wrong",  1, num);

            tx.rollback();
        }
        finally
        {
            if (tx.isActive())
            {
                tx.rollback();
            }
            em.close();
        }
    }

    /**
     * Test generation of an update Criteria query
     */
    public void testUpdate()
    {
        EntityManager em = getEM();
        EntityTransaction tx = em.getTransaction();
        try
        {
            tx.begin();

            CriteriaBuilder qb = emf.getCriteriaBuilder();
            CriteriaUpdate<Team> crit = qb.createCriteriaUpdate(Team.class);
            Root<Team> candidate = crit.from(Team.class);

            candidate.alias("t");
            crit.set(candidate.get(Team_.name), "Barcelona FC");

            Predicate teamName = qb.equal(candidate.get(Team_.id), 2);
            crit.where(teamName);

            // DN extension
            assertEquals("Generated JPQL update query is incorrect",
                "UPDATE org.datanucleus.samples.jpa.query.Team t SET t.name = 'Barcelona FC' WHERE (t.id = 2)", crit.toString());
            Query q = em.createQuery(crit);
            int num = q.executeUpdate();
            assertEquals("Number of objects updated is wrong",  1, num);

            tx.rollback();
        }
        finally
        {
            if (tx.isActive())
            {
                tx.rollback();
            }
            em.close();
        }
    }

    /**
     * Test criteria query with a function (SQL function).
     */
    public void testFunction()
    {
        EntityManager em = getEM();
        EntityTransaction tx = em.getTransaction();
        try
        {
            tx.begin();

            CriteriaBuilder qb = emf.getCriteriaBuilder();

            CriteriaQuery<Manager> crit = qb.createQuery(Manager.class);
            Root<Manager> candidate = crit.from(Manager.class);
            candidate.alias("m");
            crit.select(candidate);

            Expression<String> upperExpr = qb.function("UPPER", String.class, candidate.get(Manager_.firstName));
            Predicate firstNameUpperCaseEquals = qb.equal(upperExpr, "PEP");
            crit.where(firstNameUpperCaseEquals);

            // DN extension
            assertEquals("Generated JPQL query is incorrect",
                "SELECT m FROM org.datanucleus.samples.jpa.query.Manager m WHERE (FUNCTION('UPPER',m.firstName) = 'PEP')", crit.toString());

            Query q = em.createQuery(crit);
            List<Manager> managers = q.getResultList();

            assertNotNull("Managers is null!", managers);
            assertEquals("Number of managers is wrong", 1, managers.size());
            Manager mgr1 = managers.get(0);
            assertEquals("Pep", mgr1.getFirstName());
            assertEquals("Guardiola", mgr1.getLastName());

            tx.rollback();
        }
        catch (Exception e)
        {
            LOG.error("Exception during query", e);
            fail("Exception during test : " + e.getMessage());
        }
        finally
        {
            if (tx.isActive())
            {
                tx.rollback();
            }
            em.close();
        }
    }

    /**
     * Test serialisation of Criteria query.
     */
    /*public void testSerialise()
    {
        try
        {
            EntityManager em = getEM();
            EntityTransaction tx = em.getTransaction();
            try
            {
                tx.begin();

                CriteriaBuilder qb = emf.getCriteriaBuilder();
                CriteriaQuery<Team> crit = qb.createQuery(Team.class);
                Root<Team> candidate = crit.from(Team.class);
                candidate.alias("t");
                crit.select(candidate);

                // DN extension
                assertEquals("Generated JPQL query is incorrect",
                    "SELECT t FROM org.datanucleus.samples.jpa.query.Team t", crit.toString());

                try
                {
                    // Serialise the Expression
                    FileOutputStream fileStream = new FileOutputStream("criteria.ser");
                    ObjectOutputStream os = new ObjectOutputStream(fileStream);
                    os.writeObject(crit);
                    os.close();
                }
                catch (Exception e)
                {
                    NucleusLogger.GENERAL.error(">> Exception in serialise", e);
                    fail("Failed to serialise " + StringUtils.toJVMIDString(crit));
                }

                tx.rollback();
            }
            finally
            {
                if (tx.isActive())
                {
                    tx.rollback();
                }
                em.close();
            }

            em = getEM();
            tx = em.getTransaction();
            try
            {
                tx.begin();

                try
                {
                    // Deserialise the Expression
                    FileInputStream fileInputStream = new FileInputStream("criteria.ser");
                    ObjectInputStream oInputStream = new ObjectInputStream(fileInputStream);
                    Object obj = oInputStream.readObject();
                    if (obj instanceof CriteriaQuery)
                    {
                        CriteriaQuery crit1 = (CriteriaQuery)obj;

                        Query q = em.createQuery(crit1);
                        List<Team> teams = q.getResultList();

                        assertNotNull("Null results returned!", teams);
                        assertEquals("Number of results is incorrect", 2, teams.size());
                        boolean realmadrid = false;
                        boolean barcelona = false;
                        Iterator<Team> teamIter = teams.iterator();
                        while (teamIter.hasNext())
                        {
                            Team team = teamIter.next();
                            if (team.getName().equals("Barcelona"))
                            {
                                barcelona = true;
                            }
                            else if (team.getName().equals("Real Madrid"))
                            {
                                realmadrid = true;
                            }
                        }
                        assertTrue("Barcelona not returned", barcelona);
                        assertTrue("Real Madrid not returned", realmadrid);
                    }
                    else
                    {
                        fail("Deserialised object is " + obj.getClass().getName() + " not CriteriaQuery");
                    }
                    oInputStream.close();
                }
                catch (Exception e)
                {
                    NucleusLogger.GENERAL.error(">> Exception in deserialise", e);
                    fail("Failed to deserialise CriteriaQuery");
                }

                tx.rollback();
            }
            finally
            {
                if (tx.isActive())
                {
                    tx.rollback();
                }
                em.close();
            }
        }
        finally
        {

            // Delete the file
            File file = new File("criteria.ser");
            if (file.exists())
            {
                file.delete();
            }
        }
    }*/
}


text:
/* CARDS */
card .card {
  background-color: #FDFDFD;
  border: 1px solid #E4E4E4;
  border-radius: 4px;
  -moz-border-radius: 4px;
  -webkit-border-radius: 4px;
  -webkit-box-shadow: none;
  -moz-box-shadow: none;
  box-shadow: none;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  white-space: nowrap;
  height: 86px;
  width: 284px;
  margin: 20px 0 0 20px;
  padding: 20px;
  outline: 0 none;
  float: left;
}

card .card:hover {
  background-color: #E6EFF6;
  border: 1px solid #E6EFF6;
}

card .card.selected,
card .card.selected .cardDate {
  color: #FFF;
  background-color: #005DA6;
  border: 1px solid #005DA6;
}

card .cardMiddle {
  width: 100%;
  height: 100%;
}

card .cardMiddle .cardTypeIcon {
  height: 100%;
  width: 32px;
  float: right;
}

card .card.cardTrans .cardMiddle .cardTypeIcon {
  background: url("../../img/file_icons/Transformation.S_D.svg") no-repeat center center;
  background-size: 64px 64px;
}

card .card.cardJob .cardMiddle .cardTypeIcon {
  background: url("../../img/file_icons/Job.S_D.svg") no-repeat center center;
  background-size: 64px 64px;
}

card .card.selected .cardMiddle .cardTypeIcon {
  background-position: right center;
}

card .cardTitleAndDate {
  float: left;
  max-width: 200px;
  margin-top: -1px;
}

card .cardTitle {
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 20px;
}

card .cardDate {
  color: #999;
  line-height: 17px;
}

card .bottomSpacer {
  height: 20px;
  width: calc(100% + 20px);
  float: left;
}

redpajama_set_name: RedPajamaGithub


text:
from Message import *
from StpSwitch import *
import logging

logging.basicConfig

class STPView(object):

    def __init__(self, root=-1, distance=0, active_links=None, **kwargs):
        """
        Args
            switchid (): Switch Device ID
            distance ():
            origin ():
            destination ():
            active_links (): nodes required to proxy msg to root
        """
        self.root = root
        self.distance = distance
        self.pathThrough = kwargs.pop('pathThrough', 1)
        self.active_links = active_links or []
        self.logger = kwargs.pop('logger', logging.getLogger())

        log_level = kwargs.pop('log_level', logging.INFO)
        self.set_log_level(log_level)

    def set_log_level(self, lvl):
        self.logger.setLevel(lvl)

    def __repr__(self):
        classname = self.__class__.__name__
        reprstring = '%s(%s)' % (classname, str(self.root))
        return '<%s>' % reprstring

    def __str__(self):
        return self.__repr__()

class Switch(StpSwitch):

    def __init__(self, idNum, topolink, neighbors):
        # Invoke the super class constructor, which makes available to this object the following members:
        # -self.switchID                   (the ID number of this switch object)
        # -self.links                      (the list of swtich IDs connected to this switch object)
        super(Switch, self).__init__(idNum, topolink, neighbors)

        #TODO: Define a data structure to keep track of which links are part of / not part of the spanning tree.
        self.stp_view = STPView(idNum)

    def send_initial_messages(self):
        #TODO: This function needs to create and send the initial messages from this switch.
        #      Messages are sent via the superclass method send_message(Message msg) - see Message.py.
	#      Use self.send_message(msg) to send this.  DO NOT use self.topology.send_message(msg)
        claimedRoot = originID = self.switchID
        distanceToRoot = 0
        pathThrough = False
        for destinationID in self.links:
            print(claimedRoot, distanceToRoot, originID, destinationID, pathThrough)
            msg = Message(claimedRoot, distanceToRoot, originID, destinationID, pathThrough)
            self.send_message(msg)
        return

    def process_message(self, message):
        #TODO: This function needs to accept an incoming message and process it accordingly.
        #      This function is called every time the switch receives a new message.

        # check if pathThrough is True
        #print('%d] %s' % (self.switchID, 'processing msg from: %d' % message.origin))
        #print('%d] %s %s  %s' % (self.switchID, 'root', str(self.stp_view.root), str(message.root)))
        #print('%d] %s %s  %s' % (self.switchID, 'distance', str(self.stp_view.distance), str(message.distance)))
        #print('%d] %s %s  %s' % (self.switchID, 'activeLinks'))
        #print('%d] %s %s  %s' % (self.switchID, 'pathThrough', str(self.stp_view.pathThrough), str(message.pathThrough)))
        # check lowest root

        if message.root == self.stp_view.root and (message.distance != self.stp_view.distance):
            print('%d] %s' % (self.switchID, 'message from: %d' % message.origin))
            print('%d] %s' % (self.switchID, 'message.root: %d' % message.root))
            print('%d] %s' % (self.switchID, 'message.distance: %d' % message.distance))
            print('%d] %s' % (self.switchID, 'message.pathThrough: %s' % message.pathThrough))
            print('%d] %s' % (self.switchID, 'UPDATING STPVIEW (shared root, shorter distance)'))

        if message.root < self.stp_view.root:
            # new root requires an update to distance
            print('%d] %s' % (self.switchID, 'UPDATING STPVIEW (lower root discovered)'))
            claimedRoot = self.stp_view.root = message.root
            distanceToRoot = self.stp_view.distance = message.distance + 1
            self.stp_view.active_links.append(message.origin)
            pathThrough = self.stp_view.pathThrough = message.origin
            originID = self.switchID
            for destinationID in self.links:
                print(claimedRoot, distanceToRoot, originID, destinationID, pathThrough)
                msg = Message(claimedRoot, distanceToRoot, originID, destinationID, bool(pathThrough))
                self.send_message(msg)
            # Need to inform neighbors of change
        return

    def generate_logstring(self):
        #TODO: This function needs to return a logstring for this particular switch.  The
        #      string represents the active forwarding links for this switch and is invoked
        #      only after the simulaton is complete.  Output the links included in the
        #      spanning tree by increasing destination switch ID on a single line.
        #      Print links as '(source switch id) - (destination switch id)', separating links
        #      with a comma - ','.
        #
        #      For example, given a spanning tree (1 ----- 2 ----- 3), a correct output string
        #      for switch 2 would have the following text:
        #      2 - 1, 2 - 3
        #      A full example of a valid output file is included (sample_output.txt) with the project skeleton.
        return "switch logstring"


text:
package org.hisp.dhis.commons.collection;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * List implementation that provides a paged view.
 *
 * @author Lars Helge Overland
 */
public class PaginatedList<T>
    extends ArrayList<T>
{
    /**
     * Determines if a de-serialized file is compatible with this class.
     */
    private static final long serialVersionUID = 6296545460322554660L;

    public static final int DEFAULT_PAGE_SIZE = 10;

    private int pageSize;

    private int fromIndex = 0;

    public PaginatedList( Collection<T> collection )
    {
        super( collection );
        this.pageSize = DEFAULT_PAGE_SIZE;
    }

    /**
     * Sets page size.
     *
     * @param pageSize the page size.
     * @return this PaginatedList.
     */
    public PaginatedList<T> setPageSize( int pageSize )
    {
        this.pageSize = pageSize;

        return this;
    }

    /**
     * Sets the number of pages. The page size will be calculated and set in
     * order to provide the appropriate total number of pages. The resulting
     * number of pages can be lower than the given argument but not higher.
     *
     * @param pages the number of pages.
     * @return this PaginatedList
     */
    public PaginatedList<T> setNumberOfPages( int pages )
    {
        this.pageSize = (int) Math.ceil( (double) size() / pages );

        return this;
    }

    /**
     * Returns the next page in the list. The page size is defined by the
     * argument given in the constructor. If there is no more pages, null is
     * returned. The returned page is not guaranteed to have the same size as
     * the page size.
     *
     * @return the next page.
     */
    public List<T> nextPage()
    {
        int size = size();

        if ( fromIndex >= size )
        {
            return null;
        }

        int toIndex = Math.min( (fromIndex + pageSize), size );

        List<T> page = subList( fromIndex, toIndex );

        fromIndex = toIndex;

        return page;
    }

    /**
     * Sets the current page position to the first page.
     */
    public void reset()
    {
        fromIndex = 0;
    }

    /**
     * Returns the number of pages in the list.
     *
     * @return the number of pages.
     */
    public int pageCount()
    {
        int count = size();
        int pages = count / pageSize;
        int mod = count % pageSize;

        return mod == 0 ? pages : (pages + 1);
    }

    /**
     * Returns a list of all pages.
     *
     * @return a List of all pages.
     */
    public List<List<T>> getPages()
    {
        List<List<T>> pages = new ArrayList<>();

        List<T> page = null;

        while ( (page = nextPage()) != null )
        {
            pages.add( page );
        }

        return pages;
    }
}


text:
BOOST_PATH = /home/maik/boost/boost_1_55_0/

CC = g++
CFLAGS = -std=c++11 -Wall -O2
LDFLAGS = -static -lboost_program_options -L$(BOOST_PATH)stage/lib/
OUTPUT = mf

all: mf

mf: Argument.o brainfuck.o Call.o CallList.o compiler.o helper.o main.o Number.o String.o Variable.o ConvenienceFuck.o PrecomFuck.o BrainfuckNasmConverter.o
	$(CC) -o $@ $^ $(LDFLAGS)

main.o: main.cpp
	$(CC) -c $(CFLAGS) -isystem$(BOOST_PATH) $<

Argument.o: Argument.cpp Argument.h
	$(CC) -c $(CFLAGS) $<

brainfuck.o: brainfuck.cpp brainfuck.h
	$(CC) -c $(CFLAGS) $<

Call.o: Call.cpp Call.h
	$(CC) -c $(CFLAGS) $<

CallList.o: CallList.cpp CallList.h
	$(CC) -c $(CFLAGS) $<

compiler.o: compiler.cpp compiler.h
	$(CC) -c $(CFLAGS) $<

helper.o: helper.cpp helper.h
	$(CC) -c $(CFLAGS) $<

Number.o: Number.cpp Number.h
	$(CC) -c $(CFLAGS) $<

String.o: String.cpp String.h
	$(CC) -c $(CFLAGS) $<

Variable.o: Variable.cpp Variable.h
	$(CC) -c $(CFLAGS) $<

ConvenienceFuck.o: Interpreter/ConvenienceFuck.cpp Interpreter/ConvenienceFuck.h
	$(CC) -c $(CFLAGS) $<

PrecomFuck.o: Interpreter/PrecomFuck.cpp Interpreter/PrecomFuck.h
	$(CC) -c $(CFLAGS) $<

BrainfuckNasmConverter.o: NasmGenerator/BrainfuckNasmConverter.cpp NasmGenerator/BrainfuckNasmConverter.h
	$(CC) -c $(CFLAGS) $<

.PHONY: clean cleanest

clean:
	rm *.o

cleanest: clean
	rm mf


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class java.security.spec.EllipticCurve (Java Platform SE 7 )</title>
<meta name="date" content="2014-12-18">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 7

Prev

Next

Frames

No Frames

All Classes

Uses of Class
java.security.spec.EllipticCurve

Packages that use EllipticCurve

Package
Description

java.security.spec

Provides classes and interfaces for key specifications and algorithm
parameter specifications.

Uses of EllipticCurve in java.security.spec

Methods in java.security.spec that return EllipticCurve

Modifier and Type
Method and Description

EllipticCurve
ECParameterSpec.getCurve()

Returns the elliptic curve that this parameter defines.

Constructors in java.security.spec with parameters of type EllipticCurve

Constructor and Description

ECParameterSpec(EllipticCurve curve,
               ECPoint g,
               BigInteger n,
               int h)

Creates elliptic curve domain parameters based on the
 specified values.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 7

Prev

Next

Frames

No Frames

All Classes

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


text:
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.Network.Models
{
    public partial class VirtualNetworkPeering : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Name != null)
            {
                writer.WritePropertyName("name");
                writer.WriteStringValue(Name);
            }
            if (Etag != null)
            {
                writer.WritePropertyName("etag");
                writer.WriteStringValue(Etag);
            }
            if (Id != null)
            {
                writer.WritePropertyName("id");
                writer.WriteStringValue(Id);
            }
            writer.WritePropertyName("properties");
            writer.WriteStartObject();
            if (AllowVirtualNetworkAccess != null)
            {
                writer.WritePropertyName("allowVirtualNetworkAccess");
                writer.WriteBooleanValue(AllowVirtualNetworkAccess.Value);
            }
            if (AllowForwardedTraffic != null)
            {
                writer.WritePropertyName("allowForwardedTraffic");
                writer.WriteBooleanValue(AllowForwardedTraffic.Value);
            }
            if (AllowGatewayTransit != null)
            {
                writer.WritePropertyName("allowGatewayTransit");
                writer.WriteBooleanValue(AllowGatewayTransit.Value);
            }
            if (UseRemoteGateways != null)
            {
                writer.WritePropertyName("useRemoteGateways");
                writer.WriteBooleanValue(UseRemoteGateways.Value);
            }
            if (RemoteVirtualNetwork != null)
            {
                writer.WritePropertyName("remoteVirtualNetwork");
                writer.WriteObjectValue(RemoteVirtualNetwork);
            }
            if (RemoteAddressSpace != null)
            {
                writer.WritePropertyName("remoteAddressSpace");
                writer.WriteObjectValue(RemoteAddressSpace);
            }
            if (PeeringState != null)
            {
                writer.WritePropertyName("peeringState");
                writer.WriteStringValue(PeeringState.Value.ToString());
            }
            if (ProvisioningState != null)
            {
                writer.WritePropertyName("provisioningState");
                writer.WriteStringValue(ProvisioningState.Value.ToString());
            }
            writer.WriteEndObject();
            writer.WriteEndObject();
        }

        internal static VirtualNetworkPeering DeserializeVirtualNetworkPeering(JsonElement element)
        {
            string name = default;
            string etag = default;
            string id = default;
            bool? allowVirtualNetworkAccess = default;
            bool? allowForwardedTraffic = default;
            bool? allowGatewayTransit = default;
            bool? useRemoteGateways = default;
            SubResource remoteVirtualNetwork = default;
            AddressSpace remoteAddressSpace = default;
            VirtualNetworkPeeringState? peeringState = default;
            ProvisioningState? provisioningState = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("name"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("etag"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    etag = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("id"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    id = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("allowVirtualNetworkAccess"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                continue;
                            }
                            allowVirtualNetworkAccess = property0.Value.GetBoolean();
                            continue;
                        }
                        if (property0.NameEquals("allowForwardedTraffic"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                continue;
                            }
                            allowForwardedTraffic = property0.Value.GetBoolean();
                            continue;
                        }
                        if (property0.NameEquals("allowGatewayTransit"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                continue;
                            }
                            allowGatewayTransit = property0.Value.GetBoolean();
                            continue;
                        }
                        if (property0.NameEquals("useRemoteGateways"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                continue;
                            }
                            useRemoteGateways = property0.Value.GetBoolean();
                            continue;
                        }
                        if (property0.NameEquals("remoteVirtualNetwork"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                continue;
                            }
                            remoteVirtualNetwork = DeserializeSubResource(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("remoteAddressSpace"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                continue;
                            }
                            remoteAddressSpace = AddressSpace.DeserializeAddressSpace(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("peeringState"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                continue;
                            }
                            peeringState = new VirtualNetworkPeeringState(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("provisioningState"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                continue;
                            }
                            provisioningState = new ProvisioningState(property0.Value.GetString());
                            continue;
                        }
                    }
                    continue;
                }
            }
            return new VirtualNetworkPeering(id, name, etag, allowVirtualNetworkAccess, allowForwardedTraffic, allowGatewayTransit, useRemoteGateways, remoteVirtualNetwork, remoteAddressSpace, peeringState, provisioningState);
        }
    }
}


text:
<?php

namespace HB\BlogBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * User
 *
 * @ORM\Table()
 * @ORM\Entity
 */
class User
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="username", type="string", length=255)
     */
    private $username;

    /**
     * @var string
     *
     * @ORM\Column(name="login", type="string", length=255)
     */
    private $login;

    /**
     * @var string
     *
     * @ORM\Column(name="password", type="string", length=255)
     */
    private $password;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="datecre", type="datetime")
     */
    private $datecre;

    /**
     * @var boolean
     *
     * @ORM\Column(name="isadmin", type="boolean")
     */
    private $isadmin;

    /**
     * @var \stdClass
     *
     * @ORM\Column(name="picture", type="object", nullable=true)
     */
    private $picture;

    /**
     * @var Collection
     *
     * @ORM\OneToMany(targetEntity="HB\BlogBundle\Entity\Article", mappedBy="auteur", cascade={"detach"})
     */
    private $articles;
    //!! Doctrine crée une contrainte d'intégrité en DB
    // si un del user implique un  "auteur=null" sur article
    //il faut définir une 'cascade { 'detach' }' dans user sur article
    // qui se répercute par une contrainte "SET NULL" sur article.auteur lors d'un DEL
    //
    //!!! sur article.auteur_nom existe, il faut le mettre à jours à la main avant le user.delete

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->articles = new \Doctrine\Common\Collections\ArrayCollection();
        $this->datecre = new \DateTime();
        $this->isadmin = false;
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set username
     *
     * @param string $username
     * @return User
     */
    public function setUsername($username)
    {
        $this->username = $username;

        return $this;
    }

    /**
     * Get username
     *
     * @return string
     */
    public function getUsername()
    {
        return $this->username;
    }

    /**
     * Set login
     *
     * @param string $login
     * @return User
     */
    public function setLogin($login)
    {
        $this->login = $login;

        return $this;
    }

    /**
     * Get login
     *
     * @return string
     */
    public function getLogin()
    {
        return $this->login;
    }

    /**
     * Set password
     *
     * @param string $password
     * @return User
     */
    public function setPassword($password)
    {
        $this->password = $password;

        return $this;
    }

    /**
     * Get password
     *
     * @return string
     */
    public function getPassword()
    {
        return $this->password;
    }

    /**
     * Set datecre
     *
     * @param \DateTime $datecre
     * @return User
     */
    public function setDatecre($datecre)
    {
        $this->datecre = $datecre;

        return $this;
    }

    /**
     * Get datecre
     *
     * @return \DateTime
     */
    public function getDatecre()
    {
        return $this->datecre;
    }

    /**
     * Set isadmin
     *
     * @param boolean $isadmin
     * @return User
     */
    public function setIsadmin($isadmin)
    {
        $this->isadmin = $isadmin;

        return $this;
    }

    /**
     * Get isadmin
     *
     * @return boolean
     */
    public function getIsadmin()
    {
        return $this->isadmin;
    }

    /**
     * Set picture
     *
     * @param \stdClass $picture
     * @return User
     */
    public function setPicture($picture)
    {
        $this->picture = $picture;

        return $this;
    }

    /**
     * Get picture
     *
     * @return \stdClass
     */
    public function getPicture()
    {
        return $this->picture;
    }

    /**
     * Add articles
     *
     * @param \HB\BlogBundle\Entity\Article $article
     * @return User
     */
    public function addArticle(\HB\BlogBundle\Entity\Article $article)
    {

        //on aurait pu faire un $article->setAuteur($this)
        //il faut le faire d'un coté ou de l'autre, mais pas les deux
        $this->articles[] = $article;

        return $this;
    }

    /**
     * Remove articles
     *
     * @param \HB\BlogBundle\Entity\Article $articles
     */
    public function removeArticle(\HB\BlogBundle\Entity\Article $articles)
    {
        $this->articles->removeElement($articles);
    }

    /**
     * Get articles
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getArticles()
    {
        return $this->articles;
    }

    public function detachArticles()
    {
        foreach ($this->articles as $article)
        {
            $this->removeArticle($article);
            $article->setAuteur(null);
        }
    }
}


text:
package sql

import (
	"database/sql"
	"fmt"
	"reflect"
	"strconv"
	"strings"

	"github.com/marcuswestin/fun-go/errs"
)

type TxFunc func(shard *Shard) errs.Err

type Shard struct {
	DBName  string
	db      *sql.DB // Nil for transaction and autocommit shard structs
	sqlConn interface {
		Exec(query string, args ...interface{}) (sql.Result, error)
		Query(query string, args ...interface{}) (*sql.Rows, error)
	}
}

func (s *Shard) Transact(txFun TxFunc) errs.Err {
	conn, stdErr := s.db.Begin()
	if stdErr != nil {
		return errs.Wrap(stdErr, errs.Info{"Description": "Could not open transaction"})
	}
	defer func() {
		if panicErr := recover(); panicErr != nil {
			rbErr := conn.Rollback()
			panic(errs.New(errs.Info{
				"Description": "Panic during sql transcation",
				"PanicErr":    panicErr,
				"RollbackErr": rbErr,
			}))
		}
	}()

	err := txFun(&Shard{s.DBName, nil, conn})
	if err != nil {
		rbErr := conn.Rollback()
		if rbErr != nil {
			return errs.Wrap(rbErr, errs.Info{"Description": "Transact rollback error", "TransactionError": err})
		}

	} else {
		stdErr = conn.Commit()
		if stdErr != nil {
			return errs.Wrap(stdErr, errs.Info{"Description": "Could not commit transaction"})
		}
	}

	return nil
}

// Query with fixed args
func (s *Shard) Query(query string, args ...interface{}) (*sql.Rows, errs.Err) {
	fixArgs(args)
	rows, stdErr := s.sqlConn.Query(query, args...)
	if stdErr != nil {
		return nil, errs.Wrap(stdErr, errInfo("Query sqlConn.Query() error", query, args))
	}
	return rows, nil
}

// Execute with fixed args
func (s *Shard) Exec(query string, args ...interface{}) (sql.Result, errs.Err) {
	fixArgs(args)
	res, stdErr := s.sqlConn.Exec(query, args...)
	if stdErr != nil {
		return nil, errs.Wrap(stdErr, errInfo("Exec sqlConn.Exec() error", query, args))
	}
	return res, nil
}
func IsDuplicateExecError(err errs.Err) bool {
	str := err.StandardErrorMessage()
	return strings.HasPrefix(str, "Error 1060: Duplicate column name") ||
		strings.HasPrefix(str, "Error 1061: Duplicate key name") ||
		strings.HasPrefix(str, "Error 1050: Table") ||
		strings.HasPrefix(str, "Error 1022: Can't write; duplicate key in table")
}
func (s *Shard) ExecIgnoreDuplicateError(query string, args ...interface{}) (res sql.Result, err errs.Err) {
	res, err = s.Exec(query, args...)
	if err != nil && IsDuplicateExecError(err) {
		err = nil
	}
	return
}

/*
Fix args by converting them to values of their underlying kind.
This avoids problems in database/sql with e.g custom string types.
Without fixArgs, the following code:

	type Foo string
	...
	pool.Query("SELECT * WHERE Foo=?", Foo("bar"))

would give you the error:

	sql: converting Exec argument #1's type: unsupported type Foo, a string
*/
func fixArgs(args []interface{}) {
	for i, arg := range args {
		vArg := reflect.ValueOf(arg)
		switch vArg.Kind() {
		case reflect.String:
			args[i] = vArg.String()
			if args[i] == "" {
				args[i] = nil
			}
		}
	}
}

func (s *Shard) SelectInt(query string, args ...interface{}) (num int64, err errs.Err) {
	found, err := s.queryOne(query, args, &num)
	if err != nil {
		return
	}
	if !found {
		err = errs.New(errInfo("Query returned no rows", query, args))
		return
	}
	return
}

func (s *Shard) SelectString(query string, args ...interface{}) (str string, err errs.Err) {
	var nullStr sql.NullString
	found, err := s.queryOne(query, args, &nullStr)
	if err != nil {
		return
	}
	if found {
		str = nullStr.String
	} else {
		err = errs.New(errInfo("Query returned no rows", query, args))
		return
	}
	return
}

func (s *Shard) SelectUint(query string, args ...interface{}) (num uint, err errs.Err) {
	found, err := s.queryOne(query, args, &num)
	if err != nil {
		return
	}
	if !found {
		err = errs.New(errInfo("Query returned no rows", query, args))
		return
	}
	return
}

func (s *Shard) SelectIntForce(query string, args ...interface{}) (num int64, err errs.Err) {
	found, err := s.queryOne(query, args, &num)
	if err != nil {
		return
	}
	if !found {
		panic("Query returned no rows: " + query)
	}
	return
}

func (s *Shard) SelectStringForce(query string, args ...interface{}) (str string, err errs.Err) {
	found, err := s.queryOne(query, args, &str)
	if err != nil {
		return
	}
	if !found {
		panic("Query returned no rows: " + query)
	}
	return
}

func (s *Shard) SelectUintForce(query string, args ...interface{}) (num uint, err errs.Err) {
	found, err := s.queryOne(query, args, &num)
	if err != nil {
		return
	}
	if !found {
		panic("Query returned no rows: " + query)
	}
	return
}

func (s *Shard) SelectIntMaybe(query string, args ...interface{}) (num int64, found bool, err errs.Err) {
	found, err = s.queryOne(query, args, &num)
	return
}

func (s *Shard) SelectStringMaybe(query string, args ...interface{}) (str string, found bool, err errs.Err) {
	found, err = s.queryOne(query, args, &str)
	return
}

func (s *Shard) SelectUintMaybe(query string, args ...interface{}) (num uint, found bool, err errs.Err) {
	found, err = s.queryOne(query, args, &num)
	return
}

func (s *Shard) queryOne(query string, args []interface{}, out interface{}) (found bool, err errs.Err) {
	rows, err := s.Query(query, args...)
	if err != nil {
		return
	}
	defer rows.Close()

	if rows.Next() {
		stdErr := rows.Scan(out)
		if stdErr != nil {
			err = errs.Wrap(stdErr, errInfo("queryOne rows.Scan error", query, args))
			return
		}
		if rows.Next() {
			err = errs.New(errInfo("queryOne query returned too many rows", query, args))
			return
		}
		found = true
	}

	stdErr := rows.Err()
	if stdErr != nil {
		err = errs.Wrap(stdErr, errInfo("queryOne rows.Err", query, args))
		return
	}

	return
}

func (s *Shard) UpdateOne(query string, args ...interface{}) (err errs.Err) {
	return s.UpdateNum(1, query, args...)
}

func (s *Shard) UpdateNum(num int64, query string, args ...interface{}) (err errs.Err) {
	rowsAffected, err := s.Update(query, args...)
	if err != nil {
		return err
	}
	if rowsAffected != num {
		return errs.New(errInfo("UpdateNum affected unexpected number of rows", query, args,
			errs.Info{"ExpectedRows": num, "AffectedRows": rowsAffected}))
	}
	return
}

func (s *Shard) Update(query string, args ...interface{}) (rowsAffected int64, err errs.Err) {
	res, err := s.Exec(query, args...)
	if err != nil {
		return
	}

	rowsAffected, stdErr := res.RowsAffected()
	if stdErr != nil {
		err = errs.Wrap(stdErr, errInfo("Update RowsAffected error", query, args))
		return
	}
	return
}

func (s *Shard) InsertIgnoreId(query string, args ...interface{}) (err errs.Err) {
	_, err = s.Insert(query, args...)
	return
}

func IsDuplicateEntryError(err errs.Err) bool {
	str := err.StandardErrorMessage()
	return strings.Contains(str, "Duplicate entry")
}
func (s *Shard) InsertIgnoreDuplicates(query string, args ...interface{}) (err errs.Err) {
	_, err = s.Insert(query, args...)
	if err != nil && IsDuplicateEntryError(err) {
		err = nil
	}
	return
}

func (s *Shard) Insert(query string, args ...interface{}) (id int64, err errs.Err) {
	res, err := s.Exec(query, args...)
	if err != nil {
		return
	}
	id, stdErr := res.LastInsertId()
	if stdErr != nil {
		err = errs.Wrap(stdErr, errInfo("Insert LastInsertIderror", query, args))
		return
	}
	return
}

func (s *Shard) Select(output interface{}, query string, args ...interface{}) errs.Err {
	// Check types
	var outputPtr = reflect.ValueOf(output)
	if outputPtr.Kind() != reflect.Ptr {
		return errs.New(errInfo("Select expects a pointer to a slice of items", query, args))
	}
	var outputReflection = reflect.Indirect(outputPtr)
	if outputReflection.Kind() != reflect.Slice {
		return errs.New(errInfo("Select expects items to be a slice", query, args))
	}
	if outputReflection.Len() != 0 {
		return errs.New(errInfo("Select expects items to be empty", query, args))
	}
	outputReflection.Set(reflect.MakeSlice(outputReflection.Type(), 0, 0))

	// Query DB
	var rows, err = s.Query(query, args...)
	if err != nil {
		return err
	}
	defer rows.Close()
	columns, stdErr := rows.Columns()
	if stdErr != nil {
		return errs.Wrap(stdErr, errInfo("Select rows.Columns error", query, args))
	}

	valType := outputReflection.Type().Elem()
	isStruct := (valType.Kind() == reflect.Ptr && valType.Elem().Kind() == reflect.Struct)
	if isStruct {
		// Reflect onto structs
		for rows.Next() {
			structPtrVal := reflect.New(valType.Elem())
			outputItemStructVal := structPtrVal.Elem()
			err = structFromRow(outputItemStructVal, columns, rows, query, args)
			if err != nil {
				return err
			}
			outputReflection.Set(reflect.Append(outputReflection, structPtrVal))
		}
	} else {
		if len(columns) != 1 {
			return errs.New(errInfo("Select expected single column in select statement for slice of non-struct values", query, args))
		}
		for rows.Next() {
			rawBytes := &sql.RawBytes{}
			stdErr = rows.Scan(rawBytes)
			if stdErr != nil {
				return errs.Wrap(stdErr, errInfo("Select rows.Scan error", query, args))
			}
			outputValue := reflect.New(valType).Elem()
			err = scanColumnValue(columns[0], outputValue, rawBytes, query, args)
			if err != nil {
				return err
			}
			outputReflection.Set(reflect.Append(outputReflection, outputValue))
		}
	}

	stdErr = rows.Err()
	if err != nil {
		return errs.Wrap(stdErr, errInfo("Select rows.Err() error", query, args))
	}
	return nil
}

const scanOneTypeError = "fun/sql.SelectOne: expects a **struct, e.g var person *Person; c.SelectOne(&person, sql)"

func (s *Shard) SelectOne(output interface{}, query string, args ...interface{}) (err errs.Err) {
	found, err := s.scanOne(output, query, true, args...)
	if err != nil {
		return
	}
	if !found {
		err = errs.New(errInfo("scanOne got no rows", query, args))
		return
	}
	return
}
func (s *Shard) SelectMaybe(output interface{}, query string, args ...interface{}) (found bool, err errs.Err) {
	return s.scanOne(output, query, false, args...)
}
func (s *Shard) scanOne(output interface{}, query string, required bool, args ...interface{}) (found bool, err errs.Err) {
	// Check types
	var outputReflectionPtr = reflect.ValueOf(output)
	if !outputReflectionPtr.IsValid() {
		panic(scanOneTypeError)
	}
	if outputReflectionPtr.Kind() != reflect.Ptr {
		panic(scanOneTypeError)
	}
	var outputReflection = outputReflectionPtr.Elem()
	if outputReflection.Kind() != reflect.Ptr {
		panic(scanOneTypeError)
	}

	// Query DB
	rows, err := s.Query(query, args...)
	if err != nil {
		return
	}
	defer rows.Close()

	// Reflect onto struct
	columns, stdErr := rows.Columns()
	if stdErr != nil {
		err = errs.Wrap(stdErr, errInfo("rows.Columns() error", query, args))
		return
	}
	if !rows.Next() {
		return
	}

	var vStruct reflect.Value
	if outputReflection.IsNil() {
		structPtrVal := reflect.New(outputReflection.Type().Elem())
		outputReflection.Set(structPtrVal)
		vStruct = structPtrVal.Elem()
	} else {
		vStruct = outputReflection.Elem()
	}

	err = structFromRow(vStruct, columns, rows, query, args)
	if err != nil {
		return
	}

	if rows.Next() {
		err = errs.New(errInfo("scanOne got multiple rows", query, args))
		return
	}

	stdErr = rows.Err()
	if stdErr != nil {
		err = errs.Wrap(stdErr, errInfo("scanOne rows.Err() error", query, args))
		return
	}

	found = true
	return
}

type scanError struct {
	err   error
	query string
}

func (s *scanError) Error() string {
	return s.err.Error() + " [SQL: " + s.query + "]"
}

func structFromRow(outputItemStructVal reflect.Value, columns []string, rows *sql.Rows, query string, args []interface{}) errs.Err {
	vals := make([]interface{}, len(columns))
	for i, _ := range columns {
		vals[i] = &sql.RawBytes{}
	}
	stdErr := rows.Scan(vals...)
	if stdErr != nil {
		return errs.Wrap(stdErr, errInfo("structFromRow error", query, args))
	}

	for i, column := range columns {
		structFieldValue := outputItemStructVal.FieldByName(column)
		if !structFieldValue.IsValid() {
			fmt.Println("Warning: no corresponding struct field found for column: " + column)
			continue
		}
		err := scanColumnValue(column, structFieldValue, vals[i].(*sql.RawBytes), query, args)
		if err != nil {
			return err
		}
	}

	return nil
}

func scanColumnValue(column string, reflectVal reflect.Value, value *sql.RawBytes, query string, args []interface{}) errs.Err {
	bytes := []byte(*value)
	if bytes == nil {
		return nil // Leave struct field empty
	}
	switch reflectVal.Kind() {
	case reflect.String:
		reflectVal.SetString(string(bytes))
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		uintVal, stdErr := strconv.ParseUint(string(bytes), 10, 64)
		if stdErr != nil {
			return errs.Wrap(stdErr, errInfo("strconv.ParseUint error", query, args, errs.Info{"Bytes": bytes}))
		}
		reflectVal.SetUint(reflect.ValueOf(uintVal).Uint())
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		intVal, stdErr := strconv.ParseInt(string(bytes), 10, 64)
		if stdErr != nil {
			return errs.Wrap(stdErr, errInfo("strconv.ParseInt error", query, args, errs.Info{"Bytes": bytes}))
		}
		reflectVal.SetInt(reflect.ValueOf(intVal).Int())
	case reflect.Bool:
		boolVal, stdErr := strconv.ParseBool(string(bytes))
		if stdErr != nil {
			return errs.Wrap(stdErr, errInfo("strconv.ParseBool error", query, args, errs.Info{"Bytes": bytes}))
		}
		reflectVal.SetBool(reflect.ValueOf(boolVal).Bool())
	default:
		if reflectVal.Kind() == reflect.Slice { // && reflectVal. == reflect.Uint8 {
			// byte slice
			reflectVal.SetBytes(bytes)
		} else {
			return errs.New(errInfo("Bad row value for column "+column+": "+reflectVal.Kind().String(), query, args))
		}
	}
	return nil
}

func errInfo(description, query string, args []interface{}, infos ...errs.Info) errs.Info {
	info := errs.Info{"Description": description, "Query": query, "Args": args}
	for _, moreInfo := range infos {
		for key, val := range moreInfo {
			info[key] = val
		}
	}
	return info
}


text:
sudo docker cp spark-worker-1:/tmp/ /media/sf_VM_Dev/results/1
sudo docker cp spark-worker-2:/tmp/ /media/sf_VM_Dev/results/2
sudo docker cp spark-worker-3:/tmp/ /media/sf_VM_Dev/results/3
sudo docker cp spark-master:/tmp/ /media/sf_VM_Dev/results/m
sudo docker cp spark-master:/usr/local/spark/work /media/sf_VM_Dev/results/mW
sudo docker cp spark-worker-1::/usr/local/spark/work /media/sf_VM_Dev/results/1W
sudo docker cp spark-worker-2::/usr/local/spark/work /media/sf_VM_Dev/results/2W
sudo docker cp spark-worker-3::/usr/local/spark/work /media/sf_VM_Dev/results/3W


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Program.cs" company="Rare Crowds Inc">
// Copyright 2012-2013 Rare Crowds, Inc.
//
//   Licensed 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.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using ConsoleAppUtilities;
using SqlUtilities.Storage;
using Utilities.Runtime;
using Utilities.Storage;

namespace Utilities.DeploymentProps
{
    /// Contains the program entry point
    public static class Program
    {
        /// Separator between deployment and role instances
        private const char DeploymentInstanceSeparator = '-';

        /// Format for usage
        private const string UsageFormat =
@"Views and downloads entries from persistent dictionaries.
Usage: DProps.exe {{-c Command}} [-d DeploymentID] [-i RoleInstanceID] [additional optional arguments]
{0}";

        /// Format for verbose index
        private const string VerboseIndexFormat =
@"Deployments and role instances:
{0}

({1} total, {3} role instances and {2} deployments)";

        /// Format for verbose list
        private const string VerboseListFormat =
@"Properties:
{0}

({1} properties in {2} role instances and {3} deployments)";

        /// Format for verbose get
        private const string VerboseGetFormat =
@"Values:
{0}

({1} values in {2} role instances and {3} deployments)";

        /// Format for verbose remove
        private const string VerboseRemoveFormat = @"Removed '{0}' from {1} deployments and/or role instances.";

        /// Format for debug information
        private const string DebugInformationFormat = @"
Execution time: {0}ms
Connection string: {1}";

        /// Gets usage information
        private static string Usage
        {
            get
            {
                return UsageFormat
                    .FormatInvariant(CommandLineArguments.GetDescriptions<DeploymentPropsArgs>());
            }
        }

        /// Gets or sets the SQL connection string
        private static string ConnectionString
        {
            get { return ConfigurationManager.AppSettings["ConnectionString"]; }
            set { ConfigurationManager.AppSettings["ConnectionString"] = value; }
        }

        /// Program entry point
        /// <param name="args">Command-line arguments</param>
        /// <returns>The error code</returns>
        internal static int Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine(Usage);
                return 0;
            }

            try
            {
                // Parse command-line arguments
                var arguments = CommandLineArguments.Create<DeploymentPropsArgs>(args);
                if (!arguments.ArgumentsValid)
                {
                    Console.WriteLine(Usage);
                    return 1;
                }

                // Initialize persistent storage (used by Utilities.Runtime.DeploymentProperties)
                ConnectionString = arguments.ConnectionString ?? ConnectionString;
                ConfigurationManager.AppSettings["PersistentDictionary.DefaultType"] = "Sql";
                PersistentDictionaryFactory.Initialize(new[] { new SqlDictionaryFactory(ConnectionString) });

                // Get deployment ids matching argument filters
                var deploymentIds = GetDeploymentIds(
                    arguments.DeploymentId,
                    arguments.InstanceId,
                    arguments.PropertyName,
                    arguments.Recursive || arguments.Command == PropsCommand.Instances);

                // Run the specified command
                var commandStartTime = DateTime.UtcNow;
                switch (arguments.Command)
                {
                    case PropsCommand.Index:
                        // Display an index of the deployment ids
                        Index(deploymentIds, arguments.Verbose);
                        break;
                    case PropsCommand.Instances:
                        // Display an index of the filtered deployment ids
                        // Additionally filters for only instances
                        deploymentIds = deploymentIds
                            .Where(id => id.Contains(DeploymentInstanceSeparator))
                            .ToArray();
                        Index(deploymentIds, arguments.Verbose);
                        break;
                    case PropsCommand.List:
                        // List the names of all properties in the filtered deployments
                        List(deploymentIds, arguments.Verbose);
                        break;
                    case PropsCommand.Get:
                        // Get the specified property from the filtered deployments
                        Get(deploymentIds, arguments.PropertyName, arguments.PropertyValue, arguments.Verbose);
                        break;
                    case PropsCommand.Set:
                        // Set the specified property on the specified deployment/instance
                        Set(arguments.DeploymentId, arguments.InstanceId, arguments.PropertyName, arguments.PropertyValue);
                        break;
                    case PropsCommand.Remove:
                        // Remove the specified property from the filtered deployments
                        Remove(deploymentIds, arguments.PropertyName, arguments.Verbose);
                        break;
                }

                var commandExecuteTime = DateTime.UtcNow - commandStartTime;
                if (arguments.Verbose)
                {
                    DisplayDebugInformation(commandExecuteTime, ConnectionString);
                }

                return 0;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unhandled exception:");
                Console.WriteLine(ex.ToString());
                return 2;
            }
        }

        ///
        /// Gets deployment/role instance ids meeting the specified criteria
        ///
        /// <param name="deploymentIdFilter">Deployment ID/prefix (optional)</param>
        /// <param name="instanceIdFilter">Instance ID (optional)</param>
        /// <param name="propertyName">Property name (optional)</param>
        /// <param name="recursive">Whether role instances should be included</param>
        /// <returns>List of deployment/role instance ids</returns>
        private static string[] GetDeploymentIds(string deploymentIdFilter, string instanceIdFilter, string propertyName, bool recursive)
        {
            return DeploymentProperties.Dictionary.Keys
                .OrderBy(id => id)
                .Where(id => recursive == id.Contains(DeploymentInstanceSeparator))
                .Where(id => string.IsNullOrWhiteSpace(deploymentIdFilter) ? true : id.StartsWith(deploymentIdFilter, StringComparison.OrdinalIgnoreCase))
                .Where(id => string.IsNullOrWhiteSpace(instanceIdFilter) ? true : id.Contains(instanceIdFilter))
                .Where(id => string.IsNullOrWhiteSpace(propertyName) ? true : DeploymentProperties.Dictionary[id].ContainsKey(propertyName))
                .ToArray();
        }

        /// Displays debug information
        /// <param name="executionTime">How long the command took to execute</param>
        /// <param name="connectionString">The connection string used</param>
        private static void DisplayDebugInformation(TimeSpan executionTime, string connectionString)
        {
            Console.WriteLine(
                DebugInformationFormat.FormatInvariant(
                    executionTime.TotalMilliseconds,
                    connectionString));
        }

        ///
        /// Displays an index of deployment/role instance ids
        ///
        /// <param name="deploymentIds">Pre-filtered Deployment IDs</param>
        /// <param name="verbose">Whether to display verbose information</param>
        private static void Index(string[] deploymentIds, bool verbose)
        {
            Console.WriteLine(
                verbose ?
                VerboseIndexFormat.FormatInvariant(
                    string.Join("\n", deploymentIds),
                    deploymentIds.Length,
                    deploymentIds.Where(id => id.Contains(DeploymentInstanceSeparator)).Count(),
                    deploymentIds.Where(id => !id.Contains(DeploymentInstanceSeparator)).Count()) :
                string.Join("\n", deploymentIds));
        }

        ///
        /// Displays a list of properties in the deployments/role instances
        ///
        /// <param name="deploymentIds">Pre-filtered Deployment IDs</param>
        /// <param name="verbose">Whether to display verbose information</param>
        private static void List(string[] deploymentIds, bool verbose)
        {
            var propertyNames = DeploymentProperties.Dictionary
                .Where(deployment => deploymentIds.Contains(deployment.Key))
                .SelectMany(properties => properties.Value.Keys)
                .Distinct();

            Console.WriteLine(
                verbose ?
                VerboseListFormat.FormatInvariant(
                    string.Join("\n", propertyNames),
                    propertyNames.Count(),
                    deploymentIds.Where(id => id.Contains(DeploymentInstanceSeparator)).Count(),
                    deploymentIds.Where(id => !id.Contains(DeploymentInstanceSeparator)).Count()) :
                string.Join("\n", propertyNames));
        }

        ///
        /// Displays a get of properties in the deployments/role instances
        ///
        /// <param name="deploymentIds">Pre-filtered Deployment IDs</param>
        /// <param name="name">Property name</param>
        /// <param name="value">Property value</param>
        /// <param name="verbose">Whether to display verbose information</param>
        private static void Get(string[] deploymentIds, string name, string value, bool verbose)
        {
            var properties = DeploymentProperties.Dictionary
                .Where(deployment => deploymentIds.Contains(deployment.Key))
                .Where(deployment => string.IsNullOrWhiteSpace(name) ? true : deployment.Value.ContainsKey(name))
                .Where(deployment => string.IsNullOrWhiteSpace(value) ? true : deployment.Value[name] == value)
                .Select(deployment =>
                    "{0}[{1}]={2}".FormatInvariant(
                        deployment.Key,
                        name,
                        deployment.Value[name]));

            Console.WriteLine(
                verbose ?
                VerboseGetFormat.FormatInvariant(
                    string.Join("\n", properties),
                    properties.Count(),
                    deploymentIds.Where(id => id.Contains(DeploymentInstanceSeparator)).Count(),
                    deploymentIds.Where(id => !id.Contains(DeploymentInstanceSeparator)).Count()) :
                string.Join("\n", properties));
        }

        ///
        /// Sets a property on a deployment/role instance
        ///
        /// <param name="deploymentId">Deployment ID</param>
        /// <param name="instanceId">Role Instance ID</param>
        /// <param name="name">Property name</param>
        /// <param name="value">Property value</param>
        private static void Set(string deploymentId, string instanceId, string name, string value)
        {
            var id =
                string.IsNullOrWhiteSpace(instanceId) ?
                deploymentId :
                "{0}{1}{2}".FormatInvariant(
                    deploymentId,
                    DeploymentInstanceSeparator,
                    instanceId);

            if (!DeploymentProperties.Dictionary.ContainsKey(id))
            {
                try
                {
                    DeploymentProperties.Dictionary.Add(id, new Dictionary<string, string>());
                }
                catch (ArgumentException)
                {
                    // Key conflict means it was just added by something else
                }
            }

            if (!DeploymentProperties.Dictionary.TryUpdateValue(
                id,
                deployment => deployment[name] = value))
            {
                throw new InvalidOperationException("Unable to update value");
            }
        }

        ///
        /// Sets a property on a deployment/role instance
        ///
        /// <param name="deploymentIds">Pre-filtered Deployment IDs</param>
        /// <param name="name">Property name</param>
        /// <param name="verbose">Whether to display verbose information</param>
        private static void Remove(string[] deploymentIds, string name, bool verbose)
        {
            var removed = 0;

            foreach (var id in deploymentIds)
            {
                if (!DeploymentProperties.Dictionary.TryUpdateValue(
                    id,
                    deployment =>
                        {
                            if (deployment.Remove(name))
                            {
                                removed++;
                            }
                        }))
                {
                    throw new InvalidOperationException("Unable to update value");
                }
            }

            if (verbose)
            {
                Console.WriteLine(VerboseRemoveFormat.FormatInvariant(name, removed));
            }
        }
    }
}


text:
package com.shaunkawano;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public final class TypeUri {

  private final URI uri;
  private final List<String> pathSegments;
  private final Map<String, List<String>> queryMap;

  /**
   * Creates new {@code TypeUri} by parsing the given {@code uri} argument.
   *
   * @param uri {@code URI} to be parsed as {@code TypeUri}.
   * @return new {@code TypeUri} based on parsing the given {@code uri}.
   */
  public static TypeUri parse(URI uri) {
    return new TypeUri(uri);
  }

  /**
   * Creates new {@code TypeUri} by parsing the given {@code url} argument.
   *
   * @param url {@code String} url to be parsed as {@code TypeUri}.
   * @return new {@code TypeUri} based on parsing the given {@code url}.
   */
  public static TypeUri parse(String url) {
    return new TypeUri(URI.create(url));
  }

  private TypeUri(URI uri) {
    this.uri = uri;
    this.pathSegments = parsePathSegments(uri.getPath());

    try {
      this.queryMap = createQueryMap(uri.getQuery());
    } catch (UnsupportedEncodingException e) {
      throw new IllegalArgumentException(e);
    }
  }

  /**
   * Returns the raw {@code URI} that was parsed or created when this class is created.
   *
   * @return raw {@code uri} that was parsed or created when this class is created.
   */
  public URI URI() {
    return uri;
  }

  /**
   * Returns query map of this {@code TypeUri}.
   * This is null-safe; it returns an empty map if there is no associated query map.
   *
   * @return {@code queryMap} of this {@code TypeUri}.
   */
  public Map<String, List<String>> queryMap() {
    return queryMap;
  }

  /**
   * Returns path segments of this {@code TypeUri}.
   * This is null-safe; it returns an empty list if there is no associated path segments.
   *
   * @return {@code pathSegments} of this {@code TypeUri}.
   */
  public List<String> getPathSegments() {
    return pathSegments;
  }

  /**
   * Returns whether this {@code TypeUri} has no path segments.
   *
   * @return {@code true} if this {@code TypeUri} has empty path segments. {@code false} otherwise.
   */
  public boolean hasEmptyPath() {
    return pathSegments.isEmpty();
  }

  /**
   * Returns whether this {@code TypeUri} is network type.
   * Network type means if the host of this {@code TypeUri} is either "http" or "https".
   *
   * @return {@code true} if the host of this {@code TypeUri} is either "http" or "https".
   * {@code false} otherwise.
   */
  public boolean isNetwork() {
    String scheme = uri.getScheme();
    return "http".equals(scheme) || "https".equals(scheme);
  }

  /**
   * Returns whether the host of this {@code TypeUri} is "http".
   *
   * @return {@code true} if the host of this {@code TypeUri} is "http". {@code false} otherwise.
   */
  public boolean isHttp() {
    return "http".equals(uri.getScheme());
  }

  /**
   * Returns whether the host of this {@code TypeUri} is "https".
   *
   * @return {@code true} if the host of this {@code TypeUri} is "https". {@code false} otherwise.
   */
  public boolean isHttps() {
    return "https".equals(uri.getScheme());
  }

  /**
   * Returns whether the host of this {@code TypeUri} is the same as the given {@code host}.
   *
   * @return {@code true} if the host of this {@code TypeUri} is is the same as the given {@code
   * host}. {@code false} otherwise.
   */
  public boolean isHost(String host) {
    return host.equals(uri.getHost());
  }

  /**
   * Returns whether the scheme of this {@code TypeUri} is the same as the given {@code scheme}.
   *
   * @return {@code true} if the scheme of this {@code TypeUri} is is the same as the given {@code
   * scheme}. {@code false} otherwise.
   */
  public boolean isScheme(String scheme) {
    return scheme.equals(uri.getScheme());
  }

  /**
   * Returns whether this {@code TypeUri} has query.
   *
   * @return {@code true} if this {@code TypeUri} has query. {@code false} otherwise.
   */
  public boolean hasQuery() {
    return uri.getQuery() != null;
  }

  /**
   * Returns whether this {@code TypeUri} has the given {@code query}.
   *
   * @return {@code true} if this {@code TypeUri} has the given {@code query}. {@code false}
   * otherwise.
   */
  public boolean hasQuery(String query) {
    if (queryMap == null || queryMap.isEmpty()) {
      return false;
    }

    return queryMap.containsKey(query);
  }

  /**
   * Returns whether this {@code TypeUri} contains the given {@code queryMap}.
   *
   * @return {@code true} if this {@code TypeUri} contains the given {@code queryMap}. {@code false}
   * otherwise.
   */
  public boolean containsQueryMap(Map<String, String> queryMap) {
    if (queryMap == null || queryMap.isEmpty()) {
      return false;
    }

    for (Map.Entry<String, String> query : queryMap.entrySet()) {
      if (containsQueryMap(query.getKey(), query.getValue())) {
        return true;
      }
    }

    return false;
  }

  /**
   * Returns whether this {@code TypeUri} contains the given {@code queryKey} and {@code
   * queryValue} map.
   *
   * @return {@code true} if this {@code TypeUri} contains the given ontains the given {@code
   * queryKey} and {@code queryValue} map.
   */
  public boolean containsQueryMap(String queryKey, String queryValue) {
    List<String> queryValues = queryMap.get(queryKey);
    if (queryValues == null || queryValues.isEmpty()) {
      return false;
    }

    for (int i = 0, size = queryValues.size(); i < size; i++) {
      if (queryValue.equals(queryValues.get(i))) {
        return true;
      }
    }

    return false;
  }

  private Map<String, List<String>> createQueryMap(String query)
      throws UnsupportedEncodingException {
    if (query == null || query.isEmpty()) {
      return Collections.emptyMap();
    }

    String[] queryParameters = query.split("&");
    int length = queryParameters.length;
    Map<String, List<String>> queryMap = new LinkedHashMap<>(length);

    for (int i = 0; i < length; i++) {
      String parameter = queryParameters[i];
      int equalIndex = parameter.indexOf("=");

      String key;
      if (equalIndex > 0) {
        key = URLDecoder.decode(parameter.substring(0, equalIndex), "UTF-8");
      } else {
        key = parameter;
      }

      if (!queryMap.containsKey(key)) {
        queryMap.put(key, new LinkedList<String>());
      }

      String value;
      if (equalIndex > 0 && parameter.length() > equalIndex + 1) {
        value = URLDecoder.decode(parameter.substring(equalIndex + 1), "UTF-8");
      } else {
        value = "";
      }

      queryMap.get(key).add(value);
    }

    return queryMap;
  }

  private List<String> parsePathSegments(String pathString) {
    if (pathString == null || pathString.isEmpty()) {
      return Collections.emptyList();
    }

    String[] splitter = pathString.split("/");
    List<String> pathSegments = new ArrayList<>(splitter.length);
    for (int i = 0, length = splitter.length; i < length; i++) {
      String pathSegment = splitter[i];
      if (!pathSegment.isEmpty()) {
        pathSegments.add(pathSegment);
      }
    }

    if (pathSegments.isEmpty()) {
      return Collections.emptyList();
    } else {
      return pathSegments;
    }
  }

  @Override public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    TypeUri typeUri = (TypeUri) o;
    return uri != null ? uri.equals(typeUri.uri)
        : typeUri.uri == null && (queryMap != null ? queryMap.equals(typeUri.queryMap)
            : typeUri.queryMap == null && (pathSegments != null ? pathSegments.equals(
                typeUri.pathSegments) : typeUri.pathSegments == null));
  }

  @Override public int hashCode() {
    int result = uri != null ? uri.hashCode() : 0;
    result = 31 * result + (queryMap != null ? queryMap.hashCode() : 0);
    result = 31 * result + (pathSegments != null ? pathSegments.hashCode() : 0);
    return result;
  }

  @Override public String toString() {
    return String.format("TypeUri{uri=%s, queryMap=%s, pathSegments=%s}", uri, queryMap,
        pathSegments);
  }
}