Tag Archives: java

Comet на Embedded Jetty. Первый блин)

комом. Мой первый эксперимент с COMET и с Embedded Jetty. “Пощупать” COMET хотелось уже давно. Во-первых сама по себе технология достаточно интересная, а во-вторых — хотелось попробовать что-то новенькое. Jetty был выбран в качестве сервера для экспериментов как наиболее легковесный (особенно в embedded-варианте) из известных мне Java-серверов.

В качестве примера напишем простенький чат. Будем использовать технику long polling. Допустим у нас запущен Jetty-сервер с приложением-чатом, к которому подключились два клиента Саша и Маша. На диаграмме все их мучения будут выглядеть так:

comet

Теперь попробуем объяснить увиденное с небольшими вставками кода (полный исходный код можно скачать в конце статьи).

Continue reading

Jersey: how to get temporary file

I use Jersey with flash uploader and the problem I met is that I need to determine “file partialy uploaded” situation ’cause user has an opportunity to cancel it at any time. All solutions that I found for this problem were on PHP (look for The uploaded file was only partially uploaded text). I didn’t find any standart technics how to get size of uploaded file (uploaded file’s input stream doesn’t has such information) to compare it with actual file size. So I used a “little reflection magic” to get it. ’cause classes that we’ll use to get information is private for org.jvnet.mimepull package we need to create out util class in exactly the same package. Then we can use reflection to get any infomation that we need.

Continue reading

Fix for Jersey’s russian files names bug

In our project we use Sun/Oracle implementation of JAX-RS — Jersey ’cause it’s greate framework for build REST-services. But there are some troubles with uploading files feature. When you uploading file with latin chars in file name everything is fine, you read this file name on server and it’s exactly the same as on client computer. But when you trying to upload file with russian chars in file name you get “abracadabra” instead of them. For example:

Original file name Received file name
Test123.txt Test123.txt
Тест123.txt Тест123.txt

Continue reading

ImageMagick “convert: Non-conforming drawing primitive definition `image” problem

ImageMagick is the great set of image processing utilities. But there are some problems to interact with it from your programs (java program in my case). About one of them I would like to talk. In one of our latest projects we used ImageMagick to resize images and put a watermark on them. Everything was fine on developers machines with OS Windows, but when we put project on Unix server… Agrrr. WTF?! We got this error: “convert: Non-conforming drawing primitive definition `image”. Magic… ImageMagick! Here is the best article that I have founded about this problem. It doesn’t help me ’cause it describes a little different problem, but it may be helpful for you) Ok, let us see the code that throws the error (in this example I removed resize parameter ’cause it works fine and the problem only in draw):

public void convertImage() {
    // List of commands that we want to execute
    List commands = new ArrayList();
 
    // Executable file
    commands.add("convert");
 
    // Executable file parameters
    commands.add("-gravity");
    commands.add("South-East");
    commands.add("-draw");
    commands.add(""image Over 0,0 0,0 'im-watermark.png'"");
    commands.add("im-image.png");
    commands.add("im-new.png");
 
    try {
        // I also tried to use Runtime.getRuntime().exec(...), but got the same result and it doesn't wonder
        // 'cause it use ProcessBuilder
        ProcessBuilder processBuilder = new ProcessBuilder();
        processBuilder.command(commands);
        Process process = processBuilder.start();
 
        BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
 
        // Check if we have an error...
        if (error.ready()) {
            // ...then print them
            String line;
 
            while ((line = error.readLine()) != null) {
                System.out.println("error: " + line);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

The process builder that we use in our code example must generate such command:

convert -gravity South-East -draw "image Over 0,0 0,0 'im-watermark.png'" im-image.png im-new.jpeg

Looks correct, but doesn’t work. Ok, let’s try to run this command from Unix shell. I can’t belive it! It works! In shell, but not from our program( I think that something happens with convert command parameters when JVM run it or may be it is some kind of Unix feature. I don’t know. So, I did this trick:

  1. create shell script “im-convert-proxy.sh” (don’t forget to execute “chmod +x im-convert-proxy.sh” command. It allows you to execute this script) with code:

    eval 'convert '$@

    How you can see it just runs convert command with all parmeters that we passed to script from our java program.

  2. replace executable file from “convert” to “im-convert-proxy.sh”:

    commands.add("im-convert-proxy.sh"); // was commands.add("convert");

That’s all! Everything works, everyone is happy)

P.S.: if you have found a better solution, please write me.