Oct 10, 2010

Assemble executable JAR with dependencies using Maven

Problem description: As a result of the build process I need following artifacts to be generated and packed into single ZIP archive:
  • JAR with all compiled classes and resources
  • Manifest file with properly configured main class and generated class path
  • all dependencies
This archive could be unpacked and executed with double click on the application jar file or with simple java -jar command.
This problem could be easily solved with Apache Maven build manager.

Sep 15, 2010

MySQL InnoDB RI management

MySQL InnoDB engine supports Reference Integrity checks (RI). Sometimes we need to do some "big" changes in a schema or data (reconstruct table, repopulate data, etc). RI can prevent us from those actions.

Aug 23, 2010

Migration to (Better) Swing Application Framework

This article was inspired by NetBeans Platform Porting Tutorial. I really respect the NetBeans Application Platform, I use the NetBeans IDE on a daily basis, but this tutorial confused me very much. To port a simple application to this platform I have to do a lot of work. What annoys me the most is a significant amount of textual and XML files with configurations. All configurations are just a plain text without any support of refactoring and any kind of the compile time check. It is only a personal preferences, but I always try to stay away from such error-prone solution.

Aug 16, 2010

Как приручить ScrollView? [Android]

Наткнулся на очень полезную и познавательную статью про любимую платформу. В ней очень доходчиво (на пальцах) рассказано об основных трюках работы с одним из основных визуальных компонентов системы - ScrollView. В статье упоминаются недокументированные атрибуты XML, которые сильно облегчают жизнь простого разработчика.

Статья: http://www.curious-creature.org/2010/08/15/scrollviews-handy-trick/

Aug 1, 2010

Android Screen Capture v0.3

It's a desktop application for bloggers and advanced users of Android devices.

Jul 30, 2010

Android Screen Capture

По необходимости начал разбираться с Android и обнаружил, что там не все хорошо со снятием скриншотов экрана.

Jul 28, 2010

REBOL вернулся?!

 В бытность мою аспирантом, я заинтересовался новым на тот момент времени языком от канадских производителей - Rebol, Перевел на русский язык кое-какую документацию, использовал свободную версию языка для решения повседневных задач. Чем же интересен этот язык, или правильнее сказать - платформа?

Jul 6, 2010

Элементы на одном уровне с ScrollView

Неожиданная проблема с полем прокрутки. Оно перекрывает все элементы на экране. В сети есть несколько решений этой проблемы. Но все оказалось очень просто. Для того чтобы ScrollView поделилось местом на экране с другими элементами нужно установить ему android:layout_weight="1". Далее привожу пример кода:
Paste your text here.<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_height="fill_parent" android:layout_width="fill_parent"
  android:orientation="vertical"
>
  
<ScrollView android:id="@+id/ScrollView01" android:layout_weight="1" android:layout_height="wrap_content" android:layout_width="wrap_content">
  <TableLayout android:id="@+id/TableLayout01" android:layout_width="fill_parent" android:layout_weight="1" android:layout_height="fill_parent" android:stretchColumns="0,1">
    <TableRow android:id="@+id/TableRow01" android:layout_height="wrap_content" android:fitsSystemWindows="true" android:layout_width="fill_parent">
      <CheckBox android:id="@+id/CheckBox01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/flyer_01" android:gravity="bottom"></CheckBox>
      <CheckBox android:id="@+id/CheckBox02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/flyer_02" android:gravity="bottom"></CheckBox>
    </TableRow>
    <TableRow android:id="@+id/TableRow02" android:layout_height="wrap_content" android:fitsSystemWindows="true" android:layout_width="fill_parent">
      <CheckBox android:id="@+id/CheckBox03" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/flyer_03" android:gravity="bottom"></CheckBox>
      <CheckBox android:id="@+id/CheckBox04" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/flyer_04" android:gravity="bottom"></CheckBox>
    </TableRow>
        <TableRow android:id="@+id/TableRow02" android:layout_height="wrap_content" android:fitsSystemWindows="true" android:layout_width="fill_parent">
      <CheckBox android:id="@+id/CheckBox05" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/flyer_05" android:gravity="bottom"></CheckBox>
      <CheckBox android:id="@+id/CheckBox06" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/flyer_06" android:gravity="bottom"></CheckBox>
    </TableRow>
  </TableLayout></ScrollView><LinearLayout android:id="@+id/LinearLayout01" android:layout_height="wrap_content" android:layout_width="fill_parent"><TextView android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Add to:"></TextView>
<Spinner android:id="@+id/Spinner01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1"></Spinner>
<ImageButton android:id="@+id/ImageButton01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/add_to_list" android:onClick="onAddToList"></ImageButton>
</LinearLayout>



</LinearLayout>

Jun 5, 2010

Список с кнопками в Android 2.1

Постановка задачи Задача предельно простая. Нужен список элементов, каждая строка должна содержать название элемента и кнопку (кнопки) для управления этим элементом. В разных местах можно найти отрывочные данные по решению проблем, связанных с этой задачей. Собственно список проблем таков:
  1. При добавлении кнопки в строку перестает работать выделение стоки
  2. Кнопка содержит фон, которые может не вписываться в дизайн списка
  3. Обработка событий от кнопок
Есть разные подходы к решению этих проблем, от простых до очень сложных, некоторые подходы вообще не работают на последних SDK. Далее я приведу те решения, которые я нахожу достаточно простыми в реализации и которые работают на Android SDK 2.1. Проблема с фокусом Сама проблема связана с тем, что кнопка перехватывает на себя фокус. В результате чего не вызывается метод onListItemClick. Решение заключается в изменении атрибута android:descendantFocusability у родительского контейнера (группы, которая содержит кнопку и остальные визуальные компоненты, с помощью которых отображается строка списка). Значение этого атрибута должно быть установлено в blocksDescendants. Фон кнопки Если в качестве кнопки вы используете изображение (ImageButton), то предопределенный фон может сильно портить дизайн списка. Решение тривиально - необходимо установить значение атрибута android:background в @android:color/transparent. Однако это порождает другую проблему. Теперь кнопка визуально не подтверждает нажатие и фокус. Возможно такое поведение может быть приемлемым, но если нет, то необходимо использовать различные рисунки для каждого состояния кнопки:
  1. Создать в папке drawable картинки для каждого состояния кнопки: button_pressed.png, button_focused.png, button_normal.png
  2. Создать в папке drawable специальны XML файл, который будет выбирать изображение для каждого состояния (селектор), возможное содержимое этого файла привожу ниже
button_selector.xml:
 xml version="1.0" encoding="utf-8"?>
 xmlns:android="http://schemas.android.com/apk/res/android">
   android:state_pressed="true"
        android:drawable="@drawable/button_pressed" /> 
   android:state_focused="true"
        android:drawable="@drawable/button_focused" /> 
   android:drawable="@drawable/button_normal" /> 
Более подробно можно почитать в документации по ImageButton. Обработка событий Здесь я использовал следующий подход. Каждый компонент типа View содержит атрибут android:onClick. Его значение - это строка, которая определяет метод в данном контексте (обычно текущая активность), который будет вызван при нажатии на этот компонент. Для кнопок этот подход тоже работает. Чтобы им воспользоваться необходимо:
  1. В текущей Activity создать публичный метод с одним параметром типа View, например public void onMyButtonClick(View view) {...}
  2. Установить значение атрибута кнопки android:onClick в "onMyButtonClick"
Открытым остался вопрос, а как же определить, какая именно кнопка была нажата? Тут тоже можно идти разными путями, но я выбрал использование собственной реализации интерфейса SimpleCursorAdapter.ViewBinder. С его помощью я помещаю ID текущего элемента списка в Tag кнопки. Выглядит это примерно следующим образом:
    private final class ItemRowBinder implements SimpleCursorAdapter.ViewBinder {
      private static final String TAG = "ItemRowBinder";

      @Override
      public boolean setViewValue(View view, Cursor cursor, int columnIndex) {

          switch (view.getId()) {
          case R.id.ImageButtonDelete: {
              view.setTag(Long.valueOf(cursor.getLong(columnIndex)));
              return true;
          }
          }

          return false;
      }

  }
Конечно надо не забыть указать привязку поля с ID и компонента кнопки в конструкторе SimpleCursorAdapter.

May 23, 2010

Skype 2.1 Beta 2 for Linux

Тихо и незаметно вышла новая версия Skype для Linux. Ничего революционного я в нем не нашел. Но очень радует, что оно живо и развивается. Ссылки для скачивания: http://www.skype.com/intl/en-us/get-skype/on-your-computer/linux/ Technical details Version 2.1.0.81

What's new

  • Screen sharing
  • Quote a message in chat
  • Localized time formats
  • Support for UI styles
  • Report abuse

May 21, 2010

Isolation levels

Isolation levels provide a degree of control of the effects one transaction can have on another concurrent transaction. Since concurrent effects are determined by the precise ways in which, a particular database handle locks and its drivers may handle these locks differently.

Isolation level

Phantom records

Non-repeatable reads

Dirty reads

Deadlocks

Serializable

-

-

-

+

Repeatable read

+

-

-

-

Read committed

+

+

-

-

Read uncommitted

+

+

+

-

Serializable

Strongest level of isolation. Places a range locks on the data set, preventing other users from updating or inserting rows into the data set until the transaction is complete. Can produce deadlocks.

Repeatable read

Locks are placed on all data that is used in a query, preventing other users from updating the data, but new phantom records can be inserted into the data set by another user and are included in later reads in the current transaction.

Read committed

Can't read uncommitted data by another transactions. Shared locks are held while the data is being read to avoid dirty reads, but the data can be changed before the end of the transaction resulting in non-repeatable reads and phantom records.

Read uncommitted

Can read uncommitted data (dirty reads) by another transaction, and non-repeatable read and phantom records are possible. Least restrictive of all isolation levels. No shared locks are issued and no exclusive locks are honoured.

As the transaction isolation level increases, likely performance degradation follows, as additional locks are required to protect data integrity. If the underlying data doesn't require such a high degree of integrity, the isolation level can be lowered to improve performance.

This post is created with OpenOffice.org.

Apr 22, 2010

JavaFX 1.3 Released

We're very excited to announce the immediate availability of the JavaFX 1.3 platform. This release represents an important upgrade to the product and delivers a range of performance and functional improvements, including: * New and enhanced support for UI controls, CSS skinning, and programmatic layout * Performance improvements in the JavaFX Runtime * New NetBeans IDE 6.9 Beta with improved editing and an updated JavaFX Composer plug-in * New features and enhanced performance in JavaFX Production Suite * A native JavaFX font family called Amble * Support for the development of TV applications, including a new TV emulator * Availability of the mobile emulator on the Mac platform
I'm going to give it a very last try. If this technology is still unusable for the real-life applications, then I will never look at it again! More details at the official site.

Apr 15, 2010

Substance 6.0 official release

It is a great pleasure to announce the availability of the final release or version 6.0 of Substance look-and-feel (code-named Sonoma). The release notes for version 6.0 contain the detailed information on the contents of this release which include the following: * Multi-state animated transitions * New look for text based components (text fields, combo boxes, spinners, date pickers) * Custom component states * Support for drop location
For more detail see official site... Animations in Substance 6.0 are powered by the Trident animation library. You will need to add the matching Trident jar to your classpath. Substance 6.0 is using version 1.2 of Trident which can be downloaded from the main Trident download area or from the Substance 6.0 download area.

Apr 11, 2010

HTTP basic authentication. Credential caching

By default, when using authentication for connections, each host/port (or proxy host/port) is associated with a single set of credentials. A key for the credentials is a string specified as follows: A:[B:]C:D:E[:F] Between 4 and 6 fields separated by ":" where the fields have the following meaning: A is "s" or "p" for server or proxy authentication respectively B is optional and is "D", "B", or "N" for digest, basic or ntlm auth. C is either "http" or "https" D is the hostname E is the port number F is optional and if present is the realm. After being initially requested (and assuming the credentials are valid), any subsequent HttpURLConnections on that host/port (or proxy host/port) will use the same credentials. There are some situations where you may wish to have different sets of authentication credentials for connections going to the same host/port. Unfortunately this caching behaviour is hardcoded in JDK and could not be changed via any configuration. The only solution I have found was using of custom implementation for this cache. This method implies dealing with Sun proprietary classes.
    
import sun.net.www.protocol.http.AuthCache;
import sun.net.www.protocol.http.AuthCacheValue;

.....

AuthCacheValue.setAuthCache(new AuthCache() {
      
      public void remove(String arg0, AuthCacheValue arg1) {
      }
      
      public void put(String arg0, AuthCacheValue arg1) {
      }
      
      public AuthCacheValue get(String arg0, String arg1) {
        return null;
      }
    });
    
    Authenticator.setDefault(new Authenticator() {
      @Override
      protected PasswordAuthentication getPasswordAuthentication() {
        return new MyPasswordAuthentication(...);
      }
    });
In this case no credential are cached at all. It works for me. If you know another way to disable caching of credentials, please share it with me.

Jan 3, 2010

How to update Google Chrome to Beta version?

Google Chrome updates via "channels". There are three channels:
  • Stable channel
  • Beta channel
  • Dev channel
For more information see following link: Early Access Release Channels.