Sunday, November 04, 2012

Socket.IO for Erlang

I have created new Socket.IO 0.7+ compatible  server for Erlang. The server supports long-polling and websocket transports only. You can fork it from github.

Sunday, July 01, 2012

Drink Adventure. Press release.


Drink-adventure is a very innovative android application for all weekends.

We are pleased to present you the mobile application that simple as vodka and reliable like AK-47. It’s a favorite game of all scientists from secret Siberian University of Dance and Social Problems. Certainly, it’s the hit of current summer, the best entertainment application for parties - Drink Adventure. Wow!
We used the best mechanics from similar games to make the game. Imagine “spin the bottle”,  “truth or dare” together then multiply two times and you’ll get the Drink Adventure game! To play you need android device and friends (from 1 to 7). The rule is very simple. Don’t forget to throw dice, perform assignments and smile. Good mood is guaranteed! Winner will get memorial and place in Hall of Fame!

Stay tuned! In the future you will get the following features:
  • standalone mode with Andrew Barman;
  • android Toaster;
  • more maps and assignments for all situations.

The game is absolutely free!
You can download the application here.
Share your ideas and assignments for maps using the official game site.

Thursday, June 28, 2012

Drink Adventure Game!

The best remedy against boredom at a party - Drink Adventure!!!! Try and enjoy! The best application for Friday!

Friday, May 04, 2012

Russian Roulette Pro on Kongregate!

Free Russian Roulette online game on Kongregate. Play and enjoy!

Tuesday, January 03, 2012

How to create typed AS3 objects from JSON

JSON is very simple and convenient format for communication between Adobe Flash/Flex client and server side. as3corelib library contains class for JSON deserialization from String to Object. It's not good idea to use simple Object because you cannot use Bindable tag in Flex application. Re-factoring will be nightmare for you without typed objects. To solve that problem I created util class to convert Object into typed one. Source code you can see on gist: https://gist.github.com/1556693. I have MessageVO.as class with two attributes: data and type. Type contains information about data. For example, if type equals "user" it means that data will contains object of UserVO class.
public class MessageVO {
    public var type:String;
    public var data:Object;
}
...
[Bindable]
public class UserVO {
    public var id:Number;
    public var nickname:String;
}

To convert object into typed object you should execute the following code:

    var object:* = Converter.convertData(jsonObject, UserVO);

In my project I use dictionary where key is type (string) and value is class. For example:
    var typeToClassMap:Dictionary = new Dictionary;
    ...
    typeToClassMap["user", UserVO];
    typeToClassMap["chatMessage", ChatMessageVO];
    ...
    var jsonObject = JSON.decode(jsonString);
    var object:* = Converter.convertData(jsonObject.data, typeToClassMap[jsonObject.type]);

object variable will contain typed object converted from jsonObject.

How to make release without erts

Erlang OTP has very interesting thing like release. You can upgrade or downgrade your application in real-time. Release contains erts. It means that your release will contain erlang package. If you builds release with ubuntu 10.10/64bit then you cannot use release in archlinux/32bit because of binary incompatibility. Sometimes it's a big problem. I have found way to remove that disadvantages. I modified standard node startup script and created makefile to make package archive. The example you can find in my github project (https://github.com/sinnus/erlang_without_erts_example). Folder release contains bin and etc sub-folders. "bin" sub-folder contains startup scripts (node and nodetool), "etc" sub-folder contains standard  configuration for prod and dev environments (app.config and vm.vargs). Take a look at node shell script. You should replace ERTS_PATH on your real erts path and STARTUP_MODULE on your startup module like https://github.com/sinnus/erlang_without_erts_example/blob/master/src/start_mod.erl. To build package you should run "make package_dev" for dev environment. The package will be in root project folder (example-prod.tar.gz). To run application you should extract package (or use existed target folder) and execute from shell "node console" script. You also can see all available options if you run script without arguments (). There is no problem to run package on other operation system now. I haven't tested upgrade and downgrade release because it was not necessary for my project.

Friday, December 23, 2011

Java, Erlang and Rock'n'Roll

Есть у меня игровой проект под названием Russian Roulette Pro. Адрес Вконтакте http://vkontakte.ru/app2417844, в фейсбуке http://apps.facebook.com/russianroulettepro. Это клиент-серверное приложение. Клиент написан на Adobe Flex, а сервер на Java, используя Netty. Соединение между Adobe Flex и Java сокетное. Но как известно, много кто играет в игры из офиса, где стоят всякие прокси-сервера, которые поддерживают только HTTP протокол. Тут я решил сделать соединение long-polling. Вменяемую реализацию для Netty я не нашел, да и шибко не хотелось, поэтому решил я заюзать модный ныне Erlang для реализации long-polling соединения. Начал искать готовые решения и таки нашел: https://github.com/yrashk/socket.io-erlang. Я вначале обрадовался, что вот она рыба моей мечты, но тестирование показало, что там блокирующая архитектура, в общем решил сделать форк https://github.com/sinnus/socket.io-erlang/tree/dev. Пофиксил некоторые баги, убрал блокирующий процесс. Этот сервер использует протокол Socket.IO (http://socket.io/) версии 0.6. Готовый клиент существовал только для JavaScript, а мне нужен был Adobe Flash клиент. Долго думать не стал и запилил клиент для флеша: https://github.com/sinnus/socket.io-flash. Он поддерживает long-polling и Websocket. Websocket, конечно, работает через сокетные соединения со всеми вытекающими последствиями, как настройка отдачи полиси через сокет. Я в своей рулетке решил воспользоваться только long-polling. Теперь встал вопрос, а как же все это дело прицепить к существующему серверу? Не выбрасывать же существующий код на джаве, не для того он писался, чтобы его выкидывать на помойку! Решение было простое - сделать socket.io-erlang  проксирующим сервером. Клиент подцепляется к 80 порту по Socket.IO протоколу, который слушает erlang. Erlang процесс создает сокетный коннект к Java серверу и затем редиректит сообщения от клиента на Java сервер. В общем, получился такой nginx в мире long-polling - socket. Решение уже работает несколько месяцев и пока проблем не было. Протестировано под всеми браузерами, полет тоже нормальный. Как говорится, Erlang your penis!

Monday, October 24, 2011

How to use JRebel in Eclipse with Jetty plugin

Add VM arguments:
-javaagent:${JRABEL_HOME}/jrebel.jar -Drebel.log=true ${jrebel_args}

Wednesday, August 31, 2011

My own game on facebook!!!

My own game (Russian Roulette Pro) on facebook!!!

Play it!

Tuesday, May 03, 2011

Москва - Минск или как задосить РЖД

Купили (ключевое слово) билеты из Москвы до Минска через интернет. Как обычно приехали на вокзал за час до отправления, чтобы их получить через терминал. Вместо четырех работающих было только три рабочих. За каждым простералась очередь из примерно двадцати человек. Хочется сказать, что терминалы эти достаточно не эргономичные и тормозные при печати билетов, т.е. на получение билета в среднем уходило около пяти - семи минут. Пассажири подтягивались. И вдруг, внезапно, один из терминалов перестает работать, видать не выдержал DoS-атаки, но умный админ (какой-то важный мужик) заранее начал налаживать третий! Такой лоад балансир. Но и он пал под натиском желающих попутешествовать вместе с РЖД. Разьяренные пассажири ломанулись к администратору Белорусского вокзала. Громко возле него кричали и махали руками, пока из администраторской не повеяло валерьнкой и полицейскими. Собственно, администратор вынесла вердикт, что они ни в чем не виноваты и сами дураки, что не успели получить КУПЛЕННЫЕ билеты. Пришлось все-таки стоять одну очередь, чтобы получить билеты через терминал, другую, чтобы купить билеты на следующий поезд и третью, чтобы сдать билеты на уже ушедший поезд.

"Летайте" поездами РЖД, ведь других попросту нет!


Thursday, June 04, 2009

Digester, validation and XSD

How to validate XML using XSD in Digester (1.8 version)? There is no clear answer in Digester documentation.
Here you can see how to validate XML using XSD:

File xsdFile = new File(${location});
Digester digester = new Digester();
digester.setValidating(true);
digester.setNamespaceAware(true);
digester.setErrorHandler(myErrorHandler); // Don't forget to set custom error handler
digester.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
"http://www.w3.org/2001/XMLSchema");
digester.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", xsdFile); // You can use File, String, InputStream, InputSource or an array of these type
digester.parse(...);

Saturday, November 22, 2008

How to install flex-mojo

Add repository to ~/.m2/settings.xml:

<settings>
<profiles>
<profile>
<id>flex-mojos</id>
<repositories>
<repository>
<id>flex-mojos-repository</id>
<url>http://svn.sonatype.org/flexmojos/repository/</url>
<snapshots> <enabled>true</enabled> </snapshots>
<releases> <enabled>true</enabled> </releases>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>local</id>
<url>http://svn.sonatype.org/flexmojos/repository/</url>
<snapshots> <enabled>true</enabled> </snapshots>
<releases> <enabled>true</enabled> </releases>
</pluginRepository>
</pluginRepositories>
</profile>
</profiles>
<activeProfiles>
<activeProfile>flex-mojos</activeProfile>
</activeProfiles>
</settings>


Invoke the following command:

mvn info.flex-mojos:install-mojo:install-sdk -Dflex.sdk.folder="C:\Program Files\Adobe\Flex Builder 3 Plug-in\sdks\3.1.0" -Dversion=3.1.0



You can find additional information on google code site http://code.google.com/p/flex-mojos/ and blog http://blog.flex-mojos.info/

Friday, June 20, 2008

Spamgourmet

The Molotov Cocktail for the war on spam is here

Saturday, April 26, 2008

Tuesday, April 15, 2008

Audacious. Gnome. Multimedia keys.

Unfortunately, multimedia keys don't work in Audacious plug-ins like global hotkeys if ones were binded in gnome-keybinding-properties application. I wrote the following plug-in to enable multimedia keys (play, stop, prev, and next) in Audacious player. The plug-in was tested in Ubuntu 7.10. Here is it:
Audacious - Gnome Mmkeys

Friday, April 11, 2008

Ubuntu 7.10 + Jabra BT620s + Jabra 320s

I have bought bluetooth headphones and adapter. Here is an instruction how to configure bluetooth audio under Ubuntu 7.10. Maybe it will be helpful for other distros.

At first you should obtain MAC for you bluetooth audio device:

hcitool scan

Obtained address you should replace in scripts and configuration below instead of "XX:XX:XX:XX:XX:XX".

Create the following file in home directory to configure alsa plug in:
~/.asoundrc
pcm.bluetooth {
type bluetooth
device XX:XX:XX:XX:XX:XX
profile "auto"
}

Then create python scripts. The first script turns on headset profile, the second one turns on A2DP profile for stereo streaming.

Headset proifle (headset.py file):

#!/usr/bin/env python

import dbus
bus = dbus.SystemBus()
manager = dbus.Interface(bus.get_object('org.bluez', '/org/bluez'), 'org.bluez.Manager')

bus_id = manager.ActivateService('audio')
audio = dbus.Interface(bus.get_object(bus_id, '/org/bluez/audio'), 'org.bluez.audio.Manager')

path = audio.CreateHeadset('XX:XX:XX:XX:XX:XX')
#audio.ChangeDefaultHeadset(path) #change the device to be used by default
headset = dbus.Interface (bus.get_object(bus_id, path), 'org.bluez.audio.Headset')

#Connect and Play are not required in PCM mode
headset.Connect()
headset.Play()

A2DP profile (a2dp.py file):

#!/usr/bin/env python

import dbus
bus = dbus.SystemBus()
manager = dbus.Interface(bus.get_object('org.bluez', '/org/bluez'), 'org.bluez.Manager')

bus_id = manager.ActivateService('audio')
audio = dbus.Interface(bus.get_object(bus_id, '/org/bluez/audio'), 'org.bluez.audio.Manager')

path = audio.CreateDevice('XX:XX:XX:XX:XX:X')
#audio.ChangeDefaultDevice(path) #change the device to be used by default
sink = dbus.Interface (bus.get_object(bus_id, path), 'org.bluez.audio.Sink')

sink.Connect()

Okay. bluetooth-applet should be run. To turn on A2DP profile you should execute a2dp.py and to turn on Headset profile you should execute headset.py. Now you can test sound via audacious: options->preferences->Audio->Current Output Plugin->ALSA
Output Plugin Preferences->Device Settings->audio device: "bluetooth". In other players you should select "bluetooth" device instead of default or any other. See here how to set bluetooth support to another players.

Another way to set bluetooth support is to install Blueman manager.

URLs:
UPD: Audacous writes to console: ALSA lib pcm_bluetooth.c:238:(playback_hw_thread) poll error: Interrupted system call (4). I don't know what it means...

Monday, April 07, 2008

#! /bin/bash
# eth0 - local network
# ppp0 - internet
# eth1 - home wnetwork

IPTABLES=/sbin/iptables

echo 1 > /proc/sys/net/ipv4/ip_forward

# Clearing
$IPTABLES -P INPUT ACCEPTs
$IPTABLES -F INPUT
$IPTABLES -P OUTPUT ACCEPT
$IPTABLES -F OUTPUT
$IPTABLES -P FORWARD DROP
$IPTABLES -F FORWARD
$IPTABLES -t nat -F

$IPTABLES -t nat -A POSTROUTING -o eth0 -j MASQUERADE
$IPTABLES -t nat -A POSTROUTING -o ppp0 -j MASQUERADE

$IPTABLES -A FORWARD -i eth0 -o eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT
$IPTABLES -A FORWARD -i eth1 -o eth0 -j ACCEPT
$IPTABLES -A FORWARD -i ppp0 -o eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT
$IPTABLES -A FORWARD -i eth1 -o ppp0 -j ACCEPT

Sunday, March 23, 2008

Network card don't work after unplug/replug

ifplugd is a Linux daemon which will automatically configure your ethernet device when a cable is plugged in and automatically unconfigure it if the cable is pulled. This is useful on laptops with onboard network adapters, since it will only configure the interface when a cable is really connected.

http://0pointer.de/lennart/projects/ifplugd