{{error}}
{{(quickSearchResults.length>10)?'10+':(quickSearchResults.length)}} {{(quickSearchResults.length==1)?'result':'results'}}
{{result.title}} {{result.timeStamp | mysql2ymd }}
I am sorry, no such article was written yet.
Simple file-on-disk JSON db
1 files attached: Heap.java
Heap.java
package eu.sorescu.db;

import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.UUID;

import groovy.json.JsonOutput;
import groovy.json.internal.JsonParserCharArray;


public class Heap {
    private static final long serialVersionUID = -5685880176240431312L;
    final File folder;
    private String joinedPath = "";

    public Heap(String... path) throws IOException {
        if (path.length == 1)
            if (path[0].length() == 0)
                path = new String[0];
        for (String aPath : path) this.joinedPath += "\\" + URLEncoder.encode(aPath, "UTF-8");
        folder = new File("heap" + this.joinedPath + "\\");
    }

    private File file(String arg0) {
        try {
            String encodedName = encode(arg0);
            return new File(folder, encodedName);
        } catch (IOException e) {
            throw new IllegalAccessError("heap://" + joinedPath + "/" + arg0);
        }
    }

    public Object[] list() {
        File[] files = folder.listFiles();
        ArrayList<String> result = new ArrayList<>();
        try {
            if (files != null)
                for (File file : files)
                    if (file.isFile())
                        result.add(decode(file.getName()));
        } catch (IOException e) {
            throw new NullPointerException(e.toString());
        }
        Object[] vector = result.toArray(new String[result.size()]);
        return vector;
    }

    public String[] listHeaps() throws IOException {
        File[] files = folder.listFiles();
        ArrayList<String> result = new ArrayList<>();
        if (files != null)
            for (File file : files)
                if (file.isDirectory())
                    result.add(decode(file.getName()));
        return result.toArray(new String[result.size()]);
    }

    // @Override
    public Object get(final Object arg0) {
        if (arg0 == null)
            throw new NullPointerException("d1012150913 Heap " + folder
                    + ": argument null");
        if (!(arg0 instanceof String))
            throw new NullPointerException("d1012150914 Heap " + folder + ": "
                    + arg0.getClass().getName() + " only String");
        return get((String) arg0);
    }

    public Object get(final String arg0, Object defaultValue) {
        Object result = get(arg0);
        if (result == null)
            result = defaultValue;
        return result;
    }

    private Object get(final String arg0) {
        try {
            File f = file(arg0);
            byte[] data = Files.readAllBytes(f.toPath());
            return new JsonParserCharArray().parse(data);
        } catch (Throwable ignored) {
        }
        return null;
    }

    public long getSize(String arg0) {
        try {
            return file(arg0).length();
        } catch (Throwable t) {
            return 0;
        }
    }

    public boolean has(String arg0) {
        if (arg0 == null)
            return false;
        File file = file(arg0);
        return file != null && file(arg0).exists();
    }

    public String put(Object value) {
        return put(null, value);
    }

    private static SimpleDateFormat TIME_STAMP = new SimpleDateFormat(
            "yyMMddhhmmssSSS");

    public String put(String key, Object value) {
        if ((key == null) || (key.length() == 0))
            key = UUID.randomUUID().toString() + "_"
                    + TIME_STAMP.format(new Date());
        write(file(key), value);
        return key;
    }

    public void delete(String arg0) {
        file(arg0).delete();
    }

    private static void write(File file, Object value)
             {
        String ser = JsonOutput.prettyPrint(JsonOutput.toJson(value));
        try {
            file.getParentFile().mkdirs();
            file.createNewFile();
            Files.write(file.toPath(), ser.getBytes(), StandardOpenOption.CREATE);
        } catch (Throwable t) {
            t.printStackTrace();
            throw new RuntimeException(t);
        }
    }

    private static String encode(String k) throws UnsupportedEncodingException {
        return URLEncoder.encode(k, "UTF-8");
    }

    private static String decode(String k) throws UnsupportedEncodingException {
        return URLDecoder.decode(k, "UTF-8");
    }
}
How I am looking for classes that extend a base class
1 files attached: Classes.java
Classes.java
public static Class[] classes(Class scope) throws IOException, URISyntaxException {
        Path root = new File(JUnitExecutor.class.getResource("/").toURI()).toPath();
        return Files.walk(root, FileVisitOption.FOLLOW_LINKS).map(path -> root.relativize(path))
                .filter(path -> path.toString().endsWith(".class"))
                .map(path -> path.toString())
                .map(path -> path.toString().substring(0, path.length() - 6).replace('\\', '.'))
                .map(path -> getClass(path))
                .filter(clazz -> scope.isAssignableFrom(clazz))
                .filter(clazz -> clazz != scope)
                .toArray(c -> new Class[c]);
    }

    private static Class getClass(String className) {
        try {
            return Class.forName(className);
        } catch (ClassNotFoundException e) {
            throw new ClassFormatError(className);
        }
    }
Simple stream copy function
Simple function to copy a stream to another.
1 files attached: CopyStream.java
CopyStream.java
public static void copyStream(InputStream is, OutputStream os) throws IOException {
        try (
                ReadableByteChannel input = Channels.newChannel(is);
                WritableByteChannel output = Channels.newChannel(os)
        ) {
            final ByteBuffer buffer = ByteBuffer.allocateDirect(65536);
            while (input.read(buffer) != -1) {
                buffer.flip();
                output.write(buffer);
                buffer.compact();
            }
            buffer.flip();
            while (buffer.hasRemaining())
                output.write(buffer);
        }
    }
My SSH URL Handler for Java
How I implemented my own SSH protocol handler in Java, to write code like in attached sample.
3 files attached: Sample.java Handler.java SSHURLConnection.java
Sample.java
new java.net.URL("ssh://user:password@host/?ls ~/desktop/").openConnection().getInputStream();
Handler.java SSHURLConnection.java
How much do you know about .NET?
1 files attached: Program.cs
Program.cs
namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            float nan = float.NaN;
            Console.WriteLine(Object.Equals(nan, nan));//true
            Console.WriteLine(Object.ReferenceEquals(nan, nan));//false
            Console.WriteLine(nan == nan);//false
            Console.WriteLine(nan.GetType());//System.single
            
            Object nano = float.NaN;
            Console.WriteLine(Object.Equals(nano, nano));//true
            Console.WriteLine(Object.ReferenceEquals(nano, nano));//true
            Console.WriteLine(nano == nano);//true
            Console.WriteLine(nano.GetType());//System.single
            Console.ReadKey();
        }
    }
}
Ranorex C# automation for MFC Windows GUI
The following code supposes you have Ranorex linked to your C# solution.
3 files attached: Main.script Repository.properties Program.cs
Main.script
rem call main
kill
start
type @login.password schilling
click @login.ok
click title=Schilling;text=Firmavalg
click title=Schilling;innertext=SPS.UK$,href=4$
doubleClick title=Schilling;text=Main.menu
doubleClick title=Schilling;text=Publisher
doubleClick title=Schilling;text=Product.management
REM Step 1
click title=Schilling;*=Product.management.project

rem ocr_click Project 3 0.5
type /form[@title~'^Product\smanagement\s-\sedit']/?/?/container[@caption~'^Product\smanagement\s-\sedit']/element/element[6]/text[@class='Edit'] 21321131231

REM Step 3
click *=Product.management;text=Create.project$
REM Step 4
click *=Product.management;*=Create.project;*=Other.projects..F7.
REM 5
click *=Product.management;text=Get.serial.number
REM 6
click *=Product.management;text=Accept$
rem ocr_click @Name: 0.5 0.5
REM 10
rem type *=Product.management;*=Save.project.as CrashCourseCardiology\t\t\t\t\t\t\t\tCrash
type @pm.edit.saveas.new-project-number {ts}
type @pm.edit.saveas.name "Crash Course Cardiology"
type @pm.edit.saveas.title "Crash Course Cardiology"
rem click on title
type @pm.edit.saveas.main-group 07
type @pm.edit.saveas.sub-group 021
type @pm.edit.saveas.dimension-1 002

click @pm.edit.saveas.new-project-number
click @pm.edit.saveas.name
click @pm.edit.saveas.new-project-number
click @pm.edit.saveas.name


click "*=Product.management;text=Create project$"
rem click "/form[@title='Error']/button[@text='OK']"
rem click "*=Product.management;text=Create project$"	
click "/form[@title='Question']/button[@text='&Yes']"

click @pm.edit.details.tab

wait 1000
clickAt @pm.edit.details.stackholders 100 20
clickAt @pm.edit.details.stackholders 10 20
clickAt @pm.edit.details.stackholders 100 20
wait 1000
type "/form[@title~'^Product\ management\ -\ edit']/?/?/container[@caption~'^Product\ management\ -\ edit']/?/?/container[@caption='Details']/?/?/container[@caption='Stakeholders']/?/?/element[@class='OaseGrid']/element/element[4]/text[@class='Edit']" "R"
wait 1000
clickAt @pm.edit.details.stackholders 200 20
wait 200
clickAt @pm.edit.details.stackholders 200 20
type "/form[@title~'^Product\ management\ -\ edit']/?/?/container[@caption~'^Product\ management\ -\ edit']/?/?/container[@caption='Details']/?/?/container[@caption='Stakeholders']/?/?/element[@class='OaseGrid']/element/element[31]/text[@class='Edit']" "Aut"
rem wait 1000
rem clickAt @pm.edit.details.stackholders 300 20
rem clickAt @pm.edit.details.stackholders 10 20
rem clickAt @pm.edit.details.stackholders 300 20
rem type "/form[@title~'^Product\ management\ -\ edit']/?/?/container[@caption~'^Product\ management\ -\ edit']/?/?/container[@caption='Details']/?/?/container[@caption='Stakeholders']/?/?/element[@class='OaseGrid']/element/element[4]/text[@class='Edit']" "Author	"
wait 1000
clickAt @pm.edit.details.stackholders 700 20
wait 200
clickAt @pm.edit.details.stackholders 700 20
type "/form[@title~'^Product\ management\ -\ edit']/?/?/container[@caption~'^Product\ management\ -\ edit']/?/?/container[@caption='Details']/?/?/container[@caption='Stakeholders']/?/?/element[@class='OaseGrid']/element/element[22]/text[@class='Edit']" "p2012-009"
rem Aut	Author	p2012-009	

click @pm.edit.texts.tab


click @pm.edit.calculation.tab

type @pm.edit.calculation.version 3
type @pm.edit.calculation.price 9
click @pm.edit.calculation.version
click @pm.edit.calculation.price
click *=Product.management;text=Accept$
Repository.properties Program.cs
Basic image recognition function in Java
Simple algorithm to find the (first) position of a smaller image in a larger one. Tip: to run faster, you may check for diagonal or few random points inside the small image before comparing all the other pixels.
1 files attached: ImageDetector.java
ImageDetector.java
package eu.sorescu.mmx;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;

public class ImageDetector {
	public static Rectangle getImagePosition(BufferedImage bigImage,
			BufferedImage smallImage) {
		int w1 = bigImage.getWidth();
		int h1 = bigImage.getHeight();
		int w2 = smallImage.getWidth();
		int h2 = smallImage.getHeight();
		int[] bigPixels = bigImage.getRGB(0, 0, w1, h1, null, 0, w1);
		int[] smallPixels = smallImage.getRGB(0, 0, w2, h2, null, 0, w2);
		for (int x1 = 0; x1 <= w1 - w2; x1++)
			imageLoop: for (int y1 = 0; y1 <= h1 - h2; y1++) {
				for (int y2 = 0; y2 < h2; y2++)
					if (!compare(bigPixels, smallPixels, w1 * (y1 + y2) + x1,
							w2 * y2, w2))
						continue imageLoop;
				return new Rectangle(x1, y1, w2, h2);
			}
		return null;
	}

	private static boolean compare(int[] array1, int[] array2, int a1, int a2,
			int length) {
		for (int i = 0; i < length; i++)
			if (array1[a1 + i] != array2[a2 + i])
				return false;
		return true;
	}
}
My too-simple-to-be-true SMTP web server
My minimal SMTP server in JAVA - I needed it during email functionality tests because:
  • does not require mailbox creation in order to receive an email on any email address;
  • integrated with a minimal HTML page, I can instantly query for the message once it was sent, without waiting for virus scanning, etc.;
  • the server is domain-agnostic (it does not matter on what domain I send the email, as long as it reaches my machine);
  • I have full access to the email source immediately it reached the server, so the automated software can analyse subtle details under the hood of the email representation (alternate representations, email hidden headers, etc.).
All the code is invoked in SMTPServer.
2 files attached: SMTPThread.java SMTPServer.java
SMTPThread.java SMTPServer.java
Parallel JUnit execution runner - just annotate your @Parametrized class with @Parallelized
1 files attached: Parallelized.java
Parallelized.java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.junit.runners.Parameterized;
import org.junit.runners.model.RunnerScheduler;

public class Parallelized extends Parameterized {

	private static class ThreadPoolScheduler implements RunnerScheduler {
		private ExecutorService executor;

		public ThreadPoolScheduler() {
			int numThreads = GenericTestCase.getIntProperty("threads");
			executor = Executors.newFixedThreadPool(numThreads);
		}

		@Override
		public void finished() {
			executor.shutdown();
			try {
				executor.awaitTermination(10, TimeUnit.MINUTES);
			} catch (InterruptedException exc) {
				throw new RuntimeException(exc);
			}
		}

		@Override
		public void schedule(Runnable childStatement) {
			executor.submit(childStatement);
		}
	}

	public Parallelized(Class klass) throws Throwable {
		super(klass);
		setScheduler(new ThreadPoolScheduler());
	}
}
My Java-Groovy joint builder (based on the UberCompile ant task)
(Some of the) Advantages:
  • No Maven or Gradle required;
  • No dependency (except JAVA_HOME and required JARs);
  • Can compile interdependent Java and Groovy code;
(Some of the) Disadvantages:
  • you need to indicate the path to the JARs;
  • Designed to work on Sun VMs;
The eu.sorescu.reflect.JARLoader is written based on Runtime dynamic loading of JARs.
1 files attached: GroovyProjectCompiler.java
GroovyProjectCompiler.java