Показ дописів із міткою java. Показати всі дописи
Показ дописів із міткою java. Показати всі дописи

субота, 1 червня 2013 р.

JMX batch updates

Some days ago, I found that it would be a good idea to monitor and save (or even set) some JMX metrics in batch style. In other words, what if I have a server farm and wish to get some JMX attribute(s) in a moment from all servers? Or even set up new value. I'd like to have it as command line tool because of I'd like to run it from console (even performed by cron). That's why I started my new repo JMXSample on GitHub. The idea is pretty easy and all implementation is located in the one file which can be compiled by javac. There are another files that are example of JMX managed application, you can ignore them.
To run this utility, you have to create configuration file (see example), which contains JMX commands line by line (currently only two commands are supported: get MBean value and set it, also only primitive Java type, String and Date are supported, check out source code for details). So, the typical line of configuration is following:
ObjectName attributeName [new_value_if_set] host port

Let's look how we can use it. I assumed you reuse sample configuration file and you run ElectroCar sample application (I wrote about it earlier) with the next parameters:

-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=1617
-Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false

After that feel free to run batch JMXCommand util (after compilation, of course), and expected result is following:
java jmxsample.JMXConsole /absilote_path/JMX/example/conf.txt


Expected output will be next (I tagged moment, when maximal speed was updated):

[localhost:1617] Attribute MaxSpeed has value 150
[localhost:1617] Attribute CurrentSpeed has value 55
[localhost:1617] Attribute MaxSpeed has value 250
[localhost:1617] Attribute CurrentSpeed has value 90
[localhost:1617] Attribute CurrentSpeed has value 235

пʼятниця, 31 травня 2013 р.

Incredible simple JMX example

With JMX you can implement management interfaces for Java applications. Let's look at the simplest and most used example. Imagine, you have create some ElectroCar managed by Java application. You wish to get/monitor some parameters and, moreover, set the same of them. 

Ok, you required to create MBean (managed bean that will be controlled by JMX) that will give you read access to 2 car parameters and you will be able to change max speed limit at runtime. To describe it, you need the next interface:




public interface ElectroCarMBean {
    public void setMaxSpeed(int maxSpeed);
    public int getMaxSpeed();
    public int getCurrentSpeed();
}

Implementation will be very short and simple:
public class ElectroCar implements ElectroCarMBean {

    public int maxSpeed = 150;
    private Random rnd = new Random();

    @Override
    public void setMaxSpeed(int maxSpeed) {
        this.maxSpeed = maxSpeed;
    }

    @Override
    public int getMaxSpeed() {
        return this.maxSpeed;
    }

    @Override
    public int getCurrentSpeed() {
        return rnd.nextInt(this.maxSpeed);
    }
}

And after that you need to register you MBean (yeap, manually):
// Get the platform MBeanServer
mbs = ManagementFactory.getPlatformMBeanServer();

// managed bean instance
ElectroCar car = new ElectroCar();
ObjectName carBean = null;

// Uniquely identify the MBeans and register them with the platform MBeanServer
carBean = new ObjectName("FOO:name=jmxsample.ElectroCar");
mbs.registerMBean(car, carBean);

After that, don't forget to add next parameters when you will be run your application:
-Dcom.sun.management.jmxremote \
-Dcom.sun.management.jmxremote.port=1617 \
-Dcom.sun.management.jmxremote.authenticate=false \
-Dcom.sun.management.jmxremote.ssl=false

It means run application w/ enabled JMX on port 1617, but without authentication (everyone can connect). So, your application is ready now! Run jconsole and check the result:

You can see that each attribute has a set of properties and the most important is read/write properties. If write property is 'true' you are able to set up new value from jconsole. Otherwise you could only read this value. In particular example, MaxSpeed can be change in runtime and it makes influence on max speed of the car. However, CurrentSpeed is readonly, and you can only perform monitoring (click 'Refresh' to update value)

As I said, MBean must be registered manually. So, it can be issue if you using some container for beans creation (like Spring). For example, Spring provide special bean MBeanExporter to give you possibility to  MBeaning your classes, read more here 

вівторок, 6 березня 2012 р.

how to add logger to class in one click

Hi! Just a simple genius way to add logger to each java class in one click (for Eclipse)
There is Eclipse template, to add this one go to Windows — Preferences — Java — Editor — Templates — New
And text of template:
${:import(org.slf4j.Logger, org.slf4j.LoggerFactory)}
private static final Logger log = LoggerFactory.getLogger(${primary_type_name}.class);

вівторок, 20 грудня 2011 р.

Poperly reading xs:date from xml

Actually, correctly read xs:date from XML isn't easy task.
Let's investigate how to do it whith famous JodaTime
There is built in formatter for xs:datetime:
ISODateTimeFormat.dateTimeParser()

However, there is not formatter for xs:date - hopefully we can build next custom formatter to handle this situation:
new DateTimeFormaterBuilder().append(null, new DateTimeParser[]{
    DateTimeFormat.forPattern("yyyy'-'MM'-'ddZ").getParser(),
    DateTimeFormat.forPattern("yyyy'-'MM'-'dd").getParser()
}).toFormatter()

It works correcly in the most of cases, but according to standart, xs:date can have leading '-'. To hadle this situation, just add two more formatter with leading '-', and it'll work properly

понеділок, 15 серпня 2011 р.

Atomic Java

Дуже корисна і цікава стаття про неблокуючі операції в джава, засновані на атоміках. Нарешті я побачив реальнокорисне використання атоіків, а не банальний код з лічильниками, яким зазвичай ілюструють цей функціонал.
Отже, в статті потокобезпечна черга та стек, в коді яких не було використано ані синхронізації, ані локів чи якихось мютексів:
http://codeidol.com/java/java-concurrency/Atomic-Variables-and-Nonblocking-Synchronization/Nonblocking-Algorithms/

PS особливого перфомансу слід чекати коли задіяно більше двох потоків

вівторок, 24 травня 2011 р.

Evil Java

Шикарний пост, шикарний код, я счітаю:))

http://thedailywtf.com/Articles/Disgruntled-Bomb-Java-Edition.aspx Alexander Keul took advantage of Java's cached boxing conversions to come up with this concept: package dont.try_this.at_home; import java.lang.*; class ValueMunger extends Thread { public void run() { while(true) { munge(); try { sleep(1000); } catch (Throwable t) { } } } public void munge() { try { Field field = Integer.class.getDeclaredField( "value" ); field.setAccessible( true ); for(int i = -127; i<=128; i++) field.setInt( Integer.valueOf(i), // either the same (90%), +1 (10%), or 42 (1%) Math.random() < 0.9 ? i : Math.random() < 0.1 ? 42 : i+1 ); } catch (Throwable t) { ; } } }

четвер, 13 січня 2011 р.

Groovy Soap Client, Custom Groovy Soap Client, and webservice overloading

It was beautiful winter morning, when I started creating SOAP client to our web-services. I decided to use groovy.net.soap.SoapClient. because of the applciation was written in Groovy language. The examples from official tutorial promise the easy life, so I was wondered when in ten minutes a got completed code which throws exception
XmlSchemaException "Content is not allowed in prolog"
In the line:
proxy = new SoapClient( endpoint )



First of all I checked xml and realized that it's absolutely correct. On the next step I touched: http://www.webservicex.net/CurrencyConvertor.asmx?WSDL
and my code works fine with this URL. So, I started googling...

четвер, 14 жовтня 2010 р.

thrift-protobuf-compare

Чудове порівняння різних аспектів перфомансу сучасних технологій передачі даних між аплікаціями http://code.google.com/p/thrift-protobuf-compare/wiki/BenchmarkingV2

Як на мене, Google ProtoBuf показав себе якнайкраще
Один з графіків (побудований, доречі, за допомогою Google Chart Api:))

вівторок, 31 серпня 2010 р.

Reference types in Java

Окрім знайомих всім "сильних" посилань в Java доступними є "слабкі" посилання, які не гарантують того що об"єкт на який вказує мописаляння досі існує. Посилання в Java наслідуються від абстрактного
java.lang.ref.Reference
У стандартній "поставці" доступними є три типи слабких посилань: Soft, Weak, Phantom.
Давайте розглянемо їх детальніше. Строге посилання це усім звичне стандартне посилання на об"єкт:
Quote quote = new Quote();
Quote strongReference = new Quote();
маємо два посилання на один об"єкт в кучі, і це об"єкт не буде зібраний збірником сміття доти, доки досяжними є хоч одне з написаних нами посилань.
Інша ситуація з "слабкими" посиланнями.
Розглянемо детальніше SoftReference:
Quote quote = new Quote();
SoftReference softQuote = new SoftReference(new Quote());
У цьому випадку життя об"єкта гарантуєтсья лише першим "сильним" посиланням. Якщо він стає недоступним, то... то це ще не означає, що об"єкт буде зібраний GC. GC забере об"єкт в той момент, коли "він" вирішить, що пам"яті недостатньо. Тобто, файтично момент смерті об"єкту передбачити неможливо. Ця особливість корисна для організації різноманітних кешів об"єктів.
WeakReference:
Quote quote = new Quote();
WeakReference softQuote = new WeakReference(new Quote());
є корисними, коли ми хоче, щоб життя об"єкту залежило від одного сильного посилання. Щойно воно стає недоступним. як наступний запуск GC збере його.

PhantomReference:
Quote quote = new Quote();
PhantomReference softQuote = new PhantomReference(new Quote());
Найбільш слабкими посиланнями з існуючих є звісно PhantomReference, для яких PhantomReference.get() завжди повертає null. Фантомні референси символізують об"єкт для якого вже був викликаний finilaze, але він ще не зібраний GC. Їх практична складова знаходиться під сумнівом. У статті http://www.javaspecialists.co.za/archive/Issue098.html розглядаєть створення власного кастомного типу посилань та його використання.

четвер, 8 липня 2010 р.

Будуємо мурашкою

У цьому дописі акцент робиться на:
1) білді антом після успішного проходження юніт тесту
2) автоматична генерація номера білда/допис дати/тощо з подальшим доступом до цих мета-даних білда з коду

Юніт тести виглядає цілком логічним проганяти перед кожним білдом, тому в антовському build.xml цілком логічно написати щось назразок:

  1. <target name="test" depends="compile-test">
  2.    <junit failureProperty="tests.failed">
  3.    <classpath refid="classpath.libs" />
  4.    <classpath>
  5.   <pathelement path="build"/>
  6.   </classpath>
  7.     <formatter type="brief" usefile="false" />
  8.     <test name="my.own.TweetProducerTest" />
  9.    </junit>
  10. </target>
* This source code was highlighted with Source Code Highlighter.

Де compile-test таска для компілу юніт-тестів, а "зміна" tests.failed слугує якраз для відслідковування вдалого проходження тест-кейсу. Лише за умови вдалого проходження тестів таска, що збирає джар:

  1. <target name="build" depends="test" unless="tests.failed">
  2.   <antcall target="jar"/>
  3. </target>
* This source code was highlighted with Source Code Highlighter.

А ось і ця таска, описую також створення маніфесту

  1. <target name="jar" depends="compile">
  2.     <delete file="tweet.jar"/>
  3.     <property name="version.num" value="1.0"/>
  4.     <tstamp>
  5.       <format property="TODAY" pattern="yyyy-MM-dd HH:mm:ss" />
  6.   </tstamp>
  7.      <buildnumber file="build.num"/>
  8.     <manifest file="MANIFEST.MF">
  9.       <attribute name="Built-By" value="${user.name}"/>
  10.       <attribute name="Implementation-Version"
  11.            value="${version.num}-${build.number}"/>  
  12.       <attribute name="Built-Date" value="${TODAY}"/>   
  13.   </manifest>
  14.     <jar destfile="tweet.jar"
  15.       basedir="build"
  16.        includes="**/*.class"
  17.        excludes="**/*Test*.class"
  18.        manifest="MANIFEST.MF"
  19.     />
  20. </target>
* This source code was highlighted with Source Code Highlighter.
Цей код заслуговує на більш детальний розбір. Почнемо з кінця - створення джару - до нього пакуються усі класс-файли за викюченням тих, імена яких закінчуютсья на Test - це юніт-тести і вони нам не потрібні в нашій джарці.

Загадковий  посилається до відповідного файлу на файловій системі (який модифікувати/видаляти треба обережно) і забезпечує нам номер білду.

Найцікавішою частиною звісно є опис файлу маніфесту, який дозволяє нам задати наші додаткові атрибути. Імена атрибутів цілком описують їх значення... Файл маніфесту вийде приблизно таким:

Manifest-Version: 1.0
Ant-Version: Apache Ant 1.7.1
Created-By: 14.1-b02 (Sun Microsystems Inc.)
Build-By: kostya
Implementation-Version: 1.0-5
Build-Date: 2010-06-12 18:47:34

Для читання цих даних можна використати наступний код (Groovy):

Enumeration e = Thread.currentThread().getContextClassLoader().getResources("META-INF/MANIFEST.MF");
while (e.hasMoreElements()){
JarURLConnection jarConnection = (JarURLConnection)(e.nextElement().openConnection());
Manifest mf = jarConnection.getManifest();
Attributes attr = mf.getMainAttributes();
String libraryFor = attr.getValue("LibraryFor");
attr.getValue("Implementation-Version");
String version = attr.getValue("Implementation-Version");