Java

such a brainfuck I know. None of the resources from this page are my words. I give full credits to author cited in the references.

Java IO Summary

Reference: http://tutorials.jenkov.com/java-io/overview.html

Byte Array

Reference: https://stackoverflow.com/questions/4019837/what-do-we-mean-by-byte-array

A byte is 8 bits (binary data).

A byte array is an array of bytes (tautology FTW!).

You could use a byte array to store a collection of binary data, for example, the contents of a file. The downside to this is that the entire file contents must be loaded into memory.

For large amounts of binary data, it would be better to use a streaming data type if your language supports it.

Java Reflection

Reference: https://stackoverflow.com/questions/37628/what-is-reflection-and-why-is-it-useful

Java Reflection makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.

In the code below you can see that, (Method) process is being called using getDeclaredMethod, and executed if found with invoke function.

import java.lang.reflect.InvocationTargetException;    
import java.lang.reflect.Method;  
  
public class ReflectMethodinvokeExample1  {  
  
    private static void process(String str) {  
        System.out.println("processing " + str);  
    }  
  
    public static void main(String... args) throws NoSuchMethodException,  
            InvocationTargetException, IllegalAccessException {  
        Method m = ReflectMethodinvokeExample1.class.getDeclaredMethod("process", String.class);  
        Object rv = m.invoke(null, "test");  
        System.out.println(rv);  
    }  
}  

Java Method invoke()

Reference:https://www.javatpoint.com/java-method-invoke-method

public Object invoke(Object obj, Object... args)  throws IllegalAccessException,  
               IllegalArgumentException,  
                InvocationTargetException 

Obtaining Constructor Objects

Class aClass = ...//obtain class object
final Constructor<?> constructor = aClass.getDeclaredConstructors()[0];
//Instantiate Objects using Constructor Object
MyObject myObject = constructor.newinstance("args")

Maps in Java [key : value pairs]

Map <Integer, Point2D.Double> hm = new HashMap<Integer, Point2D>();
hm.put(1, new Point2D.Double(50, 50));

Dynamic Proxies

Dynamic proxies allow one single class with one single method to service multiple method calls to arbitrary classes with an arbitrary number of methods. A dynamic proxy can be thought of as a kind of Façade, but one that can pretend to be an implementation of any interface. Under the cover, it routes all method invocations to a single handler – the invoke() method.

You create dynamic proxies using the Proxy.newProxyInstance() method. The newProxyInstance() methods takes 3 parameters:

  1. The ClassLoader that is to "load" the dynamic proxy class.

  2. An array of interfaces to implement.

  3. An InvocationHandler to forward all methods calls on the proxy to.

InvocationHandler handler = new MyInvocationHandler();
MyInterface proxy = (MyInterface) Proxy.newProxyInstance(
                            MyInterface.class.getClassLoader(),
                            new Class[] { MyInterface.class },
                            handler);

After running this code the proxy variable contains a dynamic implementation of the MyInterface interface. All calls to the proxy will be forwarded to the handler implementation of the general InvocationHandler interface.

InvocationHandler

public interface InvocationHandler{
  Object invoke(Object proxy, Method method, Object[] args)
         throws Throwable;
}

//example

public class MyInvocationHandler implements InvocationHandler{

  public Object invoke(Object proxy, Method method, Object[] args)
  throws Throwable {
    //do something "dynamic"
  }
}

The proxy parameter passed to the invoke() method is the dynamic proxy object implementing the interface. Most often you don't need this object.

The Method object passed into the invoke() method represents the method called on the interface the dynamic proxy implements. From the Method object you can obtain the method name, parameter types, return type, etc. See the text on Methods for more information.

The Object[] args array contains the parameter values passed to the proxy when the method in the interface implemented was called. Note: Primitives (int, long etc) in the implemented interface are wrapped in their object counterparts (Integer, Long etc.)

ChainedTransformer Class

Reference: https://klezvirus.github.io/Advanced-Web-Hacking/Serialisation/

A transformer, in JAVA, is a class which takes an object and returns a new object instance. A chained transformer, for instance, can chain multiple transformer together to transform an object multiple times, in sequence.

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import org.apache.commons.collections.Transformer;
import org.apache.commons.collections.functors.ChainedTransformer;
import org.apache.commons.collections.functors.ConstantTransformer;
import org.apache.commons.collections.functors.InvokerTransformer;

public class ExeCmdInvokerTransformer {
    
    public static void main(String args[]) {
        
        final String[] execArgs = new String[]{"cmd /c calc"};
        
        // Chain to transform object in -> ((Runtime)Runtime.class.getMethod("getRuntime").invoke(Object.class, null)).exec("cmd /c calc");
        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}, 
                execArgs
                 ),
            new ConstantTransformer(1)};
        
        Transformer transformerChain = new ChainedTransformer(transformers);
        
        // Testing the transformer
        Object object = new Object();
        transformerChain.transform(object);
    }
}

Key creation via LazyMap

Is a decorator (function that can be applied to an object, a Map in this case) that gets executed whenever a key is requested in a Map, invoking a transformer. The terms “lazy”, refers to the fact that a map decorated with a LazyMap decorator isn’t filled by (key, value) pairs from the start, but it gets populated once the first call to a map key forces the transformer to execute, fetching the correct value for the requested key.

import java.util.*;
import org.apache.commons.collections.Transformer;
import org.apache.commons.collections.map.LazyMap;

public class HowLazyMap {
    
    public static void main(String args[]) {
    // Create a Transformer to get random areas
        Transformer randomArea = new Transformer( ) {
            public Object transform( Object object ) {
                String name = (String) object;
                Random random = new Random();
                return random.nextDouble();
            }
        };

        // Create a LazyMap called desertAreasLazy, which uses the above Transformer
        Map deserts = new HashMap( );
        Map desertAreasLazy = LazyMap.decorate( deserts, randomArea );
        
        // Set name to fetch
        String desertName = "Gobi";
        
        System.out.println(String.format("Deserts contains %s? Result: %s", desertName, deserts.get(desertName)));  
        
        // Get name, print area
        String area = (String) String.valueOf(desertAreasLazy.get( desertName ));
        System.out.println( "Area: " + area );

        System.out.println(String.format("Deserts now contains %s? Result: %s", desertName, deserts.get(desertName)));
    }
}

Informally, a gadget chain could be built to create a LazyMap, set a Dynamic Proxy to hook a key creation, and execute a chained transformer on the hook. A more detailed example, using CommonsCollection, is provided further on.

Last updated