Status Update

Welcome Back!

Just when actual readers started to appear, there was a “misunderstanding” with the nice people hosting the server and due to preoccupied admins (and me not being able to reach any of them, nor being in direct contact with the hosting company myself) it took quite a while to get this site up and running again and I hope for a long uptime with our new hosting provider.

Apologies to anyone trying to reach this site while it was off-line.

As I am already talking about non-topical stuff, I’d like to take the opportunity to thank the admins of cowproxy.eu for allowing me to host this site on their server.

LogEval – Java Server Log Analyzer and Parser

LogEval parses and analyses server log files such as Apache or Nginx logs. LogEval can be used instead of web-analysis tools such as Google Analytics or Piwik to save resources or in addition to those tools to get a broader picture of the webserver traffic.

Continue

Java Function Passing

Function passing in Java is not directly supported because no constructs like lambda exist in the Java programming language. But there are alternatives, and in this post I will describe some of them.


Interfaces / Strategy Pattern


With an interface, it is possible to mimic function passing in Java. An example:

    /**
     * returns the added results of func. Func recieves [0..times-1].
     */
    private int accumulate(Function func, int times) {
        int result = 0;
        for (int i = 0; i < times; i++) {
            result += func.calc(i);
        }
        return result;
    }
    /**
     * A function interface.
     */
    interface Function {
        int calc(int x);
    }
We can now use this structure to calculate various things:

    /**
     * adds all the numbers from 1 to the given number.
     */
    public int addNumbersTo(int limit) {
        return accumulate(new Function() {
            @Override
            public int calc(int x) {
                return x + 1;
            }
        }, limit);
    }
    /*
     * adds up the first X even numbers.
     */
    public int addFirstXEvenNumbers(int x) {
        return accumulate(new Function() {
            @Override
            public int calc(int x) {
                return (2 * x) + 2;
            }
        }, x);
    }
It is also possible that the calc function accepts an unknown number of arguments by using a list.

Basically, this is the Strategy Pattern without context and with anonymous implementations of the interfaces.

Advantages:
I hope the advantage of doing this becomes clear: We can extract code that is used by a whole lot of functions to make the code cleaner and easier to maintain.

Disadvantages:
The code is quite verbose in Java.
Speed: it is slower than writing all functions individually. There are two reasons for this: the general overhead from function calling (which can generally be neglected) and the fact that the Java compiler is not able to perform a lot of optimizations. Most of the time, the speed difference will not matter though.


Template Method Pattern


In some situations it makes more sense to use the template method pattern.

public abstract class Accumulator {
    /**
     * returns the added results of this accumulator.
     */
    public int accumulate(int times) {
        int result = 0;
        for (int i = 0; i < times; i++) {
            result += getNextNumber(i);
        }
        return result;
    }
    /**
     * returns the i'th number.
     */
    abstract int getNextNumber(int i);
}
public class AllNumberAcc extends Accumulator {
    @Override
    int getNextNumber(int i) {
        return i + 1;
    }
}
public class EvenNumberAcc extends Accumulator {
    
    @Override
    int getNextNumber(int i) {
        return (2 * i) + 2;
    }
}
And use it like this:

EvenNumberAcc ena = new EvenNumberAcc();
ena.accumulate(10);
Advantages:
It is more flexible than the approach described above

Disadvantages:
It is more work to add a new function and if too many are needed, the many classes may get confusing.


Think about alternatives


If the code is only used by some functions which do nearly the same think about how the function can be changed (sometimes it is enough to add an extra boolean parameter to the signature and an if clause to the method body).

If for example you can be sure that anything you will ever accumulate are numbers up to ten or the first ten even numbers, the above example could look like this:

    /**
     * returns the added results of func. Func receives [0..times-1].
     */
    private int accumulate(boolean allNumbers, int times) {
        int result = 0;
        for (int i = 0; i < times; i++) {
            if (allNumbers) {
                result += (i + 1);
            } else {
                result += ((2 * i) + 2);
            }
        }
        return result;
    }
    /**
     * adds all the numbers from 1 to 10 (result will always be 55).
     */
    public int addNumbersToTen() {
        return accumulate(true, 10);
    }
    /*
     * adds up the first ten even numbers.
     */
    public int addFirstTenEvenNumbers() {
        return accumulate(false, 10);
    }
If you have for example three different cases you could use an Enum and a switch statement. But if the cases become too many, this can get ugly quite quickly.
Also, there is a performance loss as the if statement has to be executed each time. But again, in most cases this can be neglected.

The above solution is fine for smaller programs, but Java is an object oriented programming language, so that is what should generally be used (most of the time it is a bad idea to fight against the way a language was designed).


The three ways to mimic function passing in Java are quite similar, but they are not the same. It depends on the situation which one to use (or if it would be better to use something entirely different).

WordPress Security – General Strategy Guide

This is a strategy guide for WordPress security including removal of vulnerabilities, damage control, information hiding and what to do after an attack.
First – and most important – the things that should not need saying (but sadly, they do):
Use good passwords! Use different Passwords!
Always use latest version of WordPress and plugins! (and really of any software you are using).

Remove vulnerabilities

Choose wisely which plugins to use. The security of WordPress itself got a lot better in the last years. Sadly, this cannot be said about the plugins. Search the web if there are public exploits/vulnerability descriptions for the plugins you are using. If you really want to make sure they are save to use: Check the source code yourself. Best to read it line by line, but that might be a bit too much work, so instead just scan for the pieces which most likely are affected (such as any direct database actions; include, require, etc; handling user input).

Limit damage an attacker can make

add
define(‘DISALLOW_FILE_EDIT’,true);
in wp-config.php
It will disable the theme and plugin editor (which – if only one php file is accidentally writable – are big security risks).
Check all rights (including mysql user rights, file permissions, user right on server, etc). The database user WordPress uses should not be allowed to write into files for example.

Hide information

Security through obscurity is not ideal. But it does help and the information hiding I suggest below is easily done. On its own it is not worth much, but in combination with the other techniques it does some good.

Stop the listing of directory content (such as plugins). If someone knows what plugins are installed, it makes it easier to attack your web site. Most plugins can be identified in other ways than seeing them listed, but it is a lot more work. Do this either by using Options -Indexes or add an index.html file with a generic error message.

Hide version of WordPress. It is nearly impossible to do this completely (you would have to create all the files that WordPress dropped since earlier releases, somehow hide that files exist that did not in earlier releases, etc), but at least remove the generator meta tag.

Do not use admin as username and remove all login error messages. Change the default table prefix. You might also not want to put WordPress in a directory named /wordpress or /blog, as these can be easily found and identified by crawlers (on the other hand, naming them something obscure is not very user-friendly).

Notice intruders and act on it

Read your error log regular. Of course, an attacker can clean up after him-/herself but they don’t always.
If you connect to the server, check the last login message.
Be observant: If you find files that you did not put there, check them out. If the server load went up without any apparent reason, check out why.
Search your php files for code that generally is present in shells.

If you noticed an intruder you can either set the whole server up from scratch. This is the best approach, but also quite a lot of work. At a minimum you should change all passwords, find the weakness the intruder exploited (and fix it), search for any shells the intruder might have placed (so search for any newly created files, but also check inside all old files for dangerous code).

Resources for secure WordPress

Read and follow the security tips by WordPress and search Google for even more tips.

There are also security plugins for WordPress, but I have not tested any of them till now so I am not commenting on them.

When and How to improve Java performance

header: java performance

When to increase performance (and when not to)

Most of the time, there is a trade-off: You can either have fast code, or you can have clean code. And most of the time, clean code is more important. but there are cases when speed actually matters and one is willing” to sacrifice quality and maintainability of the code for an performance increase. Generally, clean, readable code is a lot more important than speeding up the whole code by some percentage with dirty hacks. But if a function is called a lot (depending on function size from a couple thousand to a couple million times) performance might be more important. In that case: comment it. A function that nobody understands just calls for bugs later on.  Here are some tips and ideas on performance increase in Java and how to achieve it. But remember: Premature optimization is the root of all evil.

General tips to Improve Performance of Java Code

  • find a better algorithm (really! if you find one, it is a lot more helpful than anything i write here).
  • profile and remove bottlenecks. Do not try to increase performance in code that is not a bottleneck. It is not worth destroying nice code for a performance increase of point-something percent.
  • Exceptions are only for exceptional cases. They are expensive because an exception object has to be created each time one is thrown, so they should not be used to implement logic.
  • use Java build in functions instead of writing your own function. also: use the CORRECT build in function. for example do not use + to concatenate lots of strings in a loop, but StringBuilder; use Java Collection depending on actions you perform on it, etc.
  • do not use objects when using primitives will get the job done.
  • reuse objects when possible. Do this by changing the values of an object/resetting an object instead of creating a new one. Another example where one can avoid creating objects: instead of:
    
    public void oftenCalledMethod() {
    g.setColor(new Color(100,100,100));
    // do something
    g.setColor(new Color(200,200,200));
    // do some more
    }
    
    save the color somewhere (in a local field or in an utility/options class) and reuse the color object.
  • If something is constant, declare it as static constant. Especially when it is big (like a list/array) and present in many instances. Static class variables are only created once while non-static variables have to be created for every object.

Increase Java performance in big loops

 

Reduce method calls to objects

Reducing method calls to objects is a good idea as calling a method is not for free (performance wise). For example, if the loop termination variable is stored in an object and you are sure that it does not change, save it in a local variable:

int size = myObject.getSize(); // size does not change and is really big
for (int i = 0; i &lt; size; i++) {
// do something
}
If size is just a constant, it probably does not matter as the compiler will inline it. But often it is not, for example when it returns the size of an internal list.

Rephrasing mathematical statements

If using mathematical operations, think about what they are doing and how expensive they are. As a rule of thumb: addition is faster than multiplication is faster than division is faster than exponent. An example: instead of

int[] somethingToCalulate;
int constant;
for (int i = 0; i &lt; giantSize; i++) {
somethingToCalulate[i] = i * constant;
}
you might want to use:

int[] somethingToCalulate;
int constant;
int accumulated = 0;
for (int i = 0; i &lt; giantSize; i++) {
somethingToCalulate[i] = accumulated;
accumulated += constant;
}

 Calculate once, use as often as you like

A generalization of the above: If you are calculating things twice, stop that. Save the result and use that instead. This is generally a good idea, not only when performance matters as it generally results in cleaner code. For example instead of:

int[] somethingToCalulate;
int[] somethingOtherToCalulate;
for (int i = 0; i &lt; giantSize; i++) {
somethingToCalulate[i] = i * (constant - i);
somethingOtherToCalulate = i * (constant - i) * otherConstant;
}
One could use:

int[] somethingToCalulate;
int[] somethingOtherToCalulate;
for (int i = 0; i &lt; giantSize; i++) {
int temp = i * (constant - i);
somethingToCalulate[i] = temp;
somethingOtherToCalulate = temp * otherConstant;
}
In this example it is pretty obvious, but there are cases where the double calculation is not that easy to spot. If temp would be a constant factor (ie not depent on i or anything other that is done in the loop) calculate it outside the loop.

Unrolling Loops

I found that unrolling loops does not help to increase speed, but it definitely makes it harder to read and maintain.  

Netbeans Profiler

The Netbeans profiler may be used to identify and localize performance problems. This makes it easier to resolve them. Continue