Translate

пʼятницю, 2 грудня 2011 р.

Android 4 for x86



Компанія Google опублікувала початковий код версії Android 4.0.1для "комп'ютерної" архітектури x86.
Тепер операційну систему можна буде запускати на комп'ютерах, ноутбуках і планшетах на базі процесорів Intel або AMD, повідомляє "Лента.Ру".
Дотепер Android 4.0, також відома під кодовою назвою Ice Cream Sandwich, існувала тільки у версії для мобільного архітектури ARM.
Google заявляє, що поки проект носить характер бета-версії. Деякі функції пристроїв можуть бути недоступні.
Так, у пристроях на базі Intel не працює звук, а також не підтримуються вбудована камера, технологія передачі данихEthernet і апаратне прискорення.
Пристрої на базі Android 4.0 і на архітектурі x86 поки не представив жоден виробник.
Вперше про плани адаптувати Ice Cream Sandwich під "комп'ютерні" чіпи стало відомо у вересні 2011 року зі спільного прес-релізу Intel і Google.
У ньому йшлося про пристрої Android на процесорах Intel Atom.
Раніше Google публікувала для архітектури x86 вихідні коди попередніх версій операційної системи - Android 3.2Android 2.3 іAndroid 2.2.


12-та зустріч преанонс


для проведення 12-ої зустрічі на тему Android девелопмент - розшукується людина яка має бажання поділитись своїм досвідом в цій галузі
Всі хто знають Android  і хочуть поділитись своїм знанням - пишіть мені
skype- diykorey
mail - jug.lviv@gmail.com

вівторок, 1 листопада 2011 р.

Відео та презентація: 11-та зустріч JUG of Lviv


Всі, хто не мав можливості прийти на презентацію про Spring Roo, але дуже-дуже хоче знати, що там відбувалося, а також всі, хто хоче побачити презентацію ще раз, можуть переглянути відео та слайди on-line:


Відео - частина 1:


Відео - частина 2:





вівторок, 4 жовтня 2011 р.

11-та зустріч Java User Group of Lviv


12-го жовтня 2011 року в приміщенні компанії N-ix о 19-00 відбудеться 11 зустріч JUG of Lviv
Запрошуємо всіх бажаючих.
Вхід вільний.

Слухачі матимуть можливість послухати доповідь на тему
"Spring Roo: just try it "
доповідатиме Іван Вергун (Lohika)


Прохання всіх хто планує відвідати зустріч прислати лист на нашу скриньку 
jug.lviv@gmail.com





Час зустрічі 19-00

Дата зустрічі 12-те жовтня 2011 року


Місце зустрічі




середу, 28 вересня 2011 р.

19-го жовтня День технологій Java


19-го жовтня в Києві відбудеться День технологій Java
Вхід платний 160 грн
Інформація про доповіді та реєстрацію - на офіційній сторінці




вівторок, 6 вересня 2011 р.

Отец Java променял Google на стартап





Отец Java променял Google на стартап

Автор одного из самых популярных языков программирования Джеймс Гослинг, менее полугода назад устроившийся в Google, теперь будет помогать развиваться скромному производителю беспилотного морского транспорта.
В апреле прошлого года известный канадский программист уволился из "родной" Sun Microsystems (работая в которой он и создал Java); произошло это из-за "разногласий с новым руководством". В нынешнем марте он перешёл в Google — и вот теперь решил попытать счастья в новой для себя отрасли.
Джеймс Гослинг написал в своём блоге, что такое решение далось ему мучительно, но его просто потрясло то, чем занимается компания Liquid Robotics. А занимается она изготовлением плавучих роботизированных устройств на солнечных батареях, которые могут сутками держаться на поверхности моря-океана, собирая необходимую информацию для учёных, экологов и других заинтересованных лиц.
Программист получил должность ведущего разработчика, а потому будет отвечать за всё программное обеспечение устройств, включая сенсорные и навигационные системы. Кроме того, в его обязанности входит совершенствование коммуникаций между аппаратами, а также создание "облачного" сервиса, в котором будут аккумулироваться собранные данные.
Liquid Robotics недавно привлекла финансирование от частных инвесторов в размере $22 млн, и часть этих средств, надо полагать, пойдёт на оплату услуг "звезды" программирования.
Взято звідси


пʼятницю, 29 липня 2011 р.

Java 7 release


Як відомо багатьом сьодні реліз сьомої джави з чим всіх вас і вітаю
Не обійшлось правда без ложки дьогтю
Читаємо уважно


From: Uwe Schindler
Date: Thu, 28 Jul 2011 23:13:36 +0200
Subject: [WARNING] Index corruption and crashes in Apache Lucene Core / Apache Solr with Java 7

Hello Apache Lucene & Apache Solr users,
Hello users of other Java-based Apache projects,

Oracle released Java 7 today. Unfortunately it contains hotspot compiler
optimizations, which miscompile some loops. This can affect code of several
Apache projects. Sometimes JVMs only crash, but in several cases, results
calculated can be incorrect, leading to bugs in applications (see Hotspot
bugs 7070134 [1], 7044738 [2], 7068051 [3]).

Apache Lucene Core and Apache Solr are two Apache projects, which are
affected by these bugs, namely all versions released until today. Solr users
with the default configuration will have Java crashing with SIGSEGV as soon
as they start to index documents, as one affected part is the well-known
Porter stemmer (see LUCENE-3335 [4]). Other loops in Lucene may be
miscompiled, too, leading to index corruption (especially on Lucene trunk
with pulsing codec; other loops may be affected, too - LUCENE-3346 [5]).

These problems were detected only 5 days before the official Java 7 release,
so Oracle had no time to fix those bugs, affecting also many more
applications. In response to our questions, they proposed to include the
fixes into service release u2 (eventually into service release u1, see [6]).
This means you cannot use Apache Lucene/Solr with Java 7 releases before
Update 2! If you do, please don't open bug reports, it is not the
committers' fault! At least disable loop optimizations using the
-XX:-UseLoopPredicate JVM option to not risk index corruptions.

Please note: Also Java 6 users are affected, if they use one of those JVM
options, which are not enabled by default: -XX:+OptimizeStringConcat or
-XX:+AggressiveOpts

It is strongly recommended not to use any hotspot optimization switches in
any Java version without extensive testing!

In case you upgrade to Java 7, remember that you may have to reindex, as the
unicode version shipped with Java 7 changed and tokenization behaves
differently (e.g. lowercasing). For more information, read
JRE_VERSION_MIGRATION.txt in your distribution package!

On behalf of the Lucene project,
Uwe

[1] http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7070134
[2] http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7044738
[3] http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7068051
[4] https://issues.apache.org/jira/browse/LUCENE-3335
[5] https://issues.apache.org/jira/browse/LUCENE-3346
[6] http://s.apache.org/StQ


Отож будьте уважні

пʼятницю, 24 червня 2011 р.

Зустріч учасників хакатону від JUG


Всі хто хоче представляти JUG на хакатоні - пліз приходьте у середу на сьому годину в Дзигу на Вірменській. Посидимо подумаємо що робити і як
Столик буде зарезервований на Андрія, себто на мене

четвер, 23 червня 2011 р.

Шукаю команду бажаючих взяти участь в хакатоні


Хелло, JUG спільнота
Чи є бажаючі взяти участь в хакатоні під прапорами JUG of Lviv ?
Прошу зголошуватись - обіцяю всеможливу моральну ті інформаційну підтримку, а також ексклюзивні ручки з написом Oracle Academy і хороше пиво або торт(на вибір) у випадку призових місць:)

Для тих хто не в курсі
9-10 липня відбудеться перший у Львові хакатон
Повна інфа на сайті ДОУ

вівторок, 7 червня 2011 р.

Обіцяне відео з 10-тої зустрічі


Перезалив відео з 10-тої зустрічі
http://jug-lviv.blogspot.com/2011/05/10-jug-of-lviv_02.html

понеділок, 2 травня 2011 р.

Відео та презентація:10-та зустріч JUG of Lviv









Звіт: 10-та зустріч JUG of Lviv


14-го квітня відбулась 10-та зустріч нашої групи
Цього разу (вперше, але надіюсь не востаннє) нас приймала компанія Skelia. Всі ми отримали нагоду полюбуватись видом на місто з висоти одинадцятого поверху :)
Доповідь Богдана Бандрівського на  тему dependency injection і зокрема Google Guice викликала зацікавлення в аудиторію та спричинила бурхливий диспут на афтерпаті яке нам любязно організувала Skelia
Велике спасибі компанії за піццу-пиво та гостинну зустріч
Окрема подяка Богдану за доповідь та Крістіні, Насті і Кості за сприяння та організаю зустрічі
Декілька фоток викладаю зараз
відео та презентація буде окремим постом










четвер, 7 квітня 2011 р.

Certification Competence Correlation



Most of my friends and colleagues are very negative about certification schemes in software development, a disdain that I share. This doesn't mean that I think that certifications in software are bad by definition, just that almost every one we see fails a basic test.

For a certification to be useful, it needs a correlation with competence in the thing that it certifies. So if Alice has a certification in, say, clojure programming; then there should be a high probability that Alice is a competent clojure programmer. High probability isn't a guarantee, but it should be significantly higher than the general programmer population. The reason we have disdain for most software certification programs is because we've not seen such a correlation (indeed sometimes we feel there's a negative correlation).
Furthermore, the fact that most certification schemes lack this correlation means that I tend to judge such schemes as guilty until proven innocent. This includes new schemes, which is why I've been deeply wary of getting involved in new certification programs.
A useful certification scheme, one with a respectable competence correlation, would be a Good Thing - particularly if it had a broad focus. Such a scheme would make it easier to hire someone for a task. At the moment the only way you can tell if someone is a good programmer is to find other good programmers to assess their ability. Such assessment is difficult, time-consuming, and needs to be repeated by each hiring organization. If you are a non-programmer looking to hire someone, such an assessment is particularly daunting.
What makes the situation worse is that certification schemes, even the useful ones, are prone to corruption. If you can get recognition for a certification scheme, there is a good money-making opportunity there: courses, assessments, books etc. Sadly there doesn't seem to be much correlation between a certification's ability to make money and its usefulness.
Is it reasonable for a competent person to acquire a useless certification? I wish I could answer no, but the reality is that a certification is often used as an entry gate, even if it is useless. As a result competent people often need a useless certification in order get an interview. (I suppose you could argue that this makes the certification useful, at least in an economic sense, but I prefer to stick with competence correlation.)
I do think that if you hold a useless certification, you should never try to imply that it means anything. Indeed you should take what opportunities you can to educate people about its uselessness. Lousy certifications are a canker to our profession and we should work as much as we can to remove them.
Many people I know and respect offer certifications as part of their training courses. This is bad in that it reinforces the canker, but on the whole I sympathize. Many organizations will only send people on a course if it comes with a certification, and I think it's reasonable to offer a certification to help bring people to a valuable course. Furthermore, as I discussed above, it is reasonable for people to get a useless certification, and I would rather them gain such a certification in a useful course.
Взято звідси


10-та зустріч Java User Group відбудеться 14-го квітня


14-го квітня о 19-00 відбудеться 10-та зустріч  Java User Group
Цього разу нас прийматиме молода компанія Skelia їхній офіс знаходиться за адресою 
Наукова 7-б,  бізнес центр "Optima Plaza", шостий поверх Переглянути мапу
Тема доповіді - Google Guice It’s easy
Доповідач - Богдан Бандрівський(Skelia)

Якщо ви плануєте прийти на зустріч, киньте будь ласка повідомлення листом
на скриньку
jug.lviv@gmail.com


четвер, 31 березня 2011 р.

Многопоточность в Java: ExecutorService


В Java 5 было добавлено много вещей для организации многопоточности и особенно касаемо организации параллельного доступа. В этой и последующих статьях мы пройдемся по некоторыми из них.


ExecutorService


До Java 5 для организации работы с несколькими потоками приходилось использовать сторонние имплеменации пулинга или писать свой. С появлением ExecutorService такая необходимость отпала.

ExecutorService исполняет асинхронный код в одном или нескольких потоках. Создание инстанса ExecutorService'а делается либо вручную через конкретные имплементации (ScheduledThreadPoolExecutor илиThreadPoolExecutor), но проще будет использовать фабрики класса Executors. Например, если надо создать пул с 2мя потоками, то делается это так:
ExecutorService service = Executors.newFixedThreadPool(2);

Если требуется использовать кэширующий пул потоков, который создает потоки по мере необходимости, но переиспользует неактивные потоки (и подчищает потоки, которые были неактивные некоторое время), то это задается следующим образом:
ExecutorService service = Executors.newCachedThreadPool();

Теперь небольшой пример. Допустим, надо запустить какой-нибудь код асинхронно 10 раз. Основываясь на вышесказанном, код будет выглядеть так:
ExecutorService service = Executors.newCachedThreadPool();
for(int i = 0; i < 10; i++) {
 service.submit(new Runnable() {
  public void run() {
   // snip... piece of code
  }
 });
}

Метод submit также возвращает объект Future, который содержит информацию о статусе исполнения переданного Runnable или Callable (который может возвращать значение). Из него можно узнать выполнился ли переданный код успешно, или он еще выполняется. Вызов метода get на объекте Futureвозвратит значение, который возвращает Callable (или null, если используется Runnable). Метод имеет 2 checked-исключения: InterruptedException, который бросается, когда выполнение прервано через методinterrupt(), или ExecutionException если код в Runnable или Callable бросил RuntimeException, что решает проблему поддержки исключений между потоками.

ScheduledExecutorService


Иногда требуется выполнение кода асихронно и периодически или требуется выполнить код через некоторое время, тогда на помощь приходит ScheduledExecutorService. Он позволяет поставить код выполняться в одном или нескольких потоках и сконфигурировать интервал или время, на которое выполненение будет отложено. Интервалом может быть время между двумя последовательными запусками или время между окончанием одного выполнения и началом другого. Методы ScheduledExecutorServiceвозвращают ScheduledFuture, который также содержит значение отсрочки для выполнения ScheduledFuture.

Например, если требуется отложить выполнение на 5 секунд, потребуется следующий код:
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.schedule(new Runnable() { ... }, 5, TimeUnit.SECONDS);

Если требуется назначить выполнение каждую секунду:
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate(new Runnable() { ... }, 0, 1, TimeUnit.SECONDS);

И, наконец, если требуется назначить выполнение кода с промежутком 1 секунда между выполнениями:
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleWithFixedDelay(new Runnable() { ... }, 0, 1, TimeUnit.SECONDS);

Взято звідси 

PRO:PM для true PM'ів


У рамках руху «de:coded» за підтримки ELEKS Software оголошується конкурс під назвою "PRO:PM", присвячений темі управління IT проектами. Командам буде даватись практичне завдання - проект, який необхідно повністю змоделювати, чітно описати та презентувати перед журі. Презентація кейсів відбудеться на всеукраїнському IT фестивалі «de:coded» (сам фест проходитиме у Львові 6-8 травня). Але не все так просто, як здається на перший погляд :)

1.       Для участі у конкурсі буде відібрано 6 команд по 3 людини;
2.       Для них найкращі project manager’и компанії ELEKS попередньо проведуть лекції з управління проектами;
3.       В Вас з’явиться нагода поспілкуватись з професіоналами своєї справи та дізнатись на які підводні камені вони натрапляють щодня;
4.       В Вас зможе з’явитися нагода продовжити свій розвиток, як PM’а в компанії ELEKS;
5.       Команда-переможець отримає можливість продовжити навчання в сфері управління проектами, що буде оплачуватись компанією ELEKS;
6.       Дедлайн на подачу – 4 квітня.

Взяти участь в проекті може кожен. Для цього необхідно заповнити командну або індивідуальнуаплікаційну форму та надіслати резюме на propm@decoded.org.ua.

Зацікавило? Читайте детальніше на сторінці конкурсу.

Взято звідси


пʼятницю, 25 березня 2011 р.

10-та, ювілейна, зустріч JUG of Lviv


Всім привіт
Наступна зустріч буде ювілейна для групи
Хотілось би зробити щось незвичайне ))
Отож приймаються пропозиції та варіанти
Щоб ви хотіли бачити
Як завжди чекаю листи на нашу скриньку jug.lviv.@gmail.com

середу, 16 березня 2011 р.

Відео дев'ятої зустрічі JUG


Викладаю обіцяне відео девятої зустрічі
Велике спасибі Зенику
Ну і як завжди чекаю на ваші відгуки



понеділок, 14 березня 2011 р.

Smartly load your properties




Strive for disk location-independent code nirvana

August 8, 2003
QWhat is the best strategy for loading property and configuration files in Java?
AWhen you think about how to load an external resource in Java, several options immediately come to mind: files, classpath resources, and URLs. Although all of them eventually get the job done, experience shows that classpath resources and URLs are by far the most flexible and user-friendly options.
In general, a configuration file can have an arbitrarily complex structure (e.g., an XML schema definition file). But for simplicity, I assume below that we're dealing with a flat list of name-value pairs (the familiar .properties format). There's no reason, however, why you can't apply the ideas shown below in other situations, as long as the resource in question is constructed from an InputStream.

Evil java.io.File

Using good old files (via FileInputStreamFileReader, and RandomAccessFile) is simple enough and certainly the obvious route to consider for anyone without a Java background. But it is the worst option in terms of ease of Java application deployment. Using absolute filenames in your code is not the way to write portable and disk position-independent code. Using relative filenames seems like a better alternative, but remember that they are resolved relative to the JVM's current directory. This directory setting depends on the details of the JVM's launch process, which can be obfuscated by startup shell scripts, etc. Determining the setting places an unfair amount of configuration burden on the eventual user (and in some cases, an unjustified amount of trust in the user's abilities). And in other contexts (such an Enterprise JavaBeans (EJB)/Web application server), neither you nor the user has much control over the JVM's current directory in the first place.
An ideal Java module is something you add to the classpath, and it's ready to go. Think EJB jars, Web applications packaged in.war files, and other similarly convenient deployment strategies. java.io.File is the least platform-independent area of Java. Unless you absolutely must use them, just say no to files.

Classpath resources

Having dispensed with the above diatribe, let's talk about a better option: loading resources through classloaders. This is much better because classloaders essentially act as a layer of abstraction between a resource name and its actual location on disk (or elsewhere).
Let's say you need to load a classpath resource that corresponds to a some/pkg/resource.properties file. I use classpath resource to mean something that's packaged in one of the application jars or added to the classpath before the application launches. You can add to the classpath via the -classpath JVM option each time the application starts or by placing the file in the \classes directory once and for all. The key point is that deploying a classpath resource is similar to deploying a compiled Java class, and therein lies the convenience.
You can get at some/pkg/resource.properties programmatically from your Java code in several ways. First, try:
ClassLoader.getResourceAsStream ("some/pkg/resource.properties");
  Class.getResourceAsStream ("/some/pkg/resource.properties");
  ResourceBundle.getBundle ("some.pkg.resource");


Additionally, if the code is in a class within a some.pkg Java package, then the following works as well:
Class.getResourceAsStream ("resource.properties");


Note the subtle differences in parameter formatting for these methods. All getResourceAsStream() methods use slashes to separate package name segments, and the resource name includes the file extension. Compare that with resource bundles where the resource name looks more like a Java identifier, with dots separating package name segments (the .properties extension is implied here). Of course, that is because a resource bundle does not have to be backed by a .properties file: it can be a class, for a example.
To slightly complicate the picture, java.lang.Class's getResourceAsStream() instance method can perform package-relative resource searches (which can be handy as well, see "Got Resources?"). To distinguish between relative and absolute resource names, Class.getResourceAsStream() uses leading slashes for absolute names. In general, there's no need to use this method if you are not planning to use package-relative resource naming in code.
It is easy to get mixed up in these small behavioral differences for ClassLoader.getResourceAsStream(),Class.getResourceAsStream(), and ResourceBundle.getBundle(). The following table summarizes the salient points to help you remember:
Behavioral differences
MethodParameter formatLookup failure behaviorUsage example
ClassLoader.
getResourceAsStream()
"/"-separated names; no leading "/" (all names are absolute)Silent (returns null)this.getClass().getClassLoader()
.getResourceAsStream
("some/pkg/resource.properties")
Class.
getResourceAsStream()
"/"-separated names; leading "/" indicates absolute names; all other names are relative to the class's packageSilent (returns null)this.getClass()
.getResourceAsStream
("resource.properties")
ResourceBundle.
getBundle()
"."-separated names; all names are absolute;.propertiessuffix is impliedThrows unchecked
java.util.MissingResourceException
ResourceBundle.getBundle
("some.pkg.resource")


From data streams to java.util.Properties

You might have noticed that some previously mentioned methods are half measures only: they return InputStreams and nothing resembling a list of name-value pairs. Fortunately, loading data into such a list (which can be an instance ofjava.util.Properties) is easy enough. Because you will find yourself doing this over and over again, it makes sense to create a couple of helper methods for this purpose.
The small behavioral difference among Java's built-in methods for classpath resource loading can also be a nuisance, especially if some resource names were hardcoded but you now want to switch to another load method. It makes sense to abstract away little things like whether slashes or dots are used as name separators, etc. Without further ado, here's my PropertyLoaderAPI that you might find useful (available with this article's download):
public abstract class PropertyLoader
{
    /**
     * Looks up a resource named 'name' in the classpath. The resource must map
     * to a file with .properties extention. The name is assumed to be absolute
     * and can use either "/" or "." for package segment separation with an
     * optional leading "/" and optional ".properties" suffix. Thus, the
     * following names refer to the same resource:
     * 
* some.pkg.Resource
     * some.pkg.Resource.properties
     * some/pkg/Resource
     * some/pkg/Resource.properties
     * /some/pkg/Resource
     * /some/pkg/Resource.properties
     * 
* * @param name classpath resource name [may not be null] * @param loader classloader through which to load the resource [null * is equivalent to the application loader] * * @return resource converted to java.util.Properties [may be null if the * resource was not found and THROW_ON_LOAD_FAILURE is false] * @throws IllegalArgumentException if the resource was not found and * THROW_ON_LOAD_FAILURE is true */ public static Properties loadProperties (String name, ClassLoader loader) { if (name == null) throw new IllegalArgumentException ("null input: name"); if (name.startsWith ("/")) name = name.substring (1); if (name.endsWith (SUFFIX)) name = name.substring (0, name.length () - SUFFIX.length ()); Properties result = null; InputStream in = null; try { if (loader == null) loader = ClassLoader.getSystemClassLoader (); if (LOAD_AS_RESOURCE_BUNDLE) { name = name.replace ('/', '.'); // Throws MissingResourceException on lookup failures: final ResourceBundle rb = ResourceBundle.getBundle (name, Locale.getDefault (), loader); result = new Properties (); for (Enumeration keys = rb.getKeys (); keys.hasMoreElements ();) { final String key = (String) keys.nextElement (); final String value = rb.getString (key); result.put (key, value); } } else { name = name.replace ('.', '/'); if (! name.endsWith (SUFFIX)) name = name.concat (SUFFIX); // Returns null on lookup failures: in = loader.getResourceAsStream (name); if (in != null) { result = new Properties (); result.load (in); // Can throw IOException } } } catch (Exception e) { result = null; } finally { if (in != null) try { in.close (); } catch (Throwable ignore) {} } if (THROW_ON_LOAD_FAILURE && (result == null)) { throw new IllegalArgumentException ("could not load [" + name + "]"+ " as " + (LOAD_AS_RESOURCE_BUNDLE ? "a resource bundle" : "a classloader resource")); } return result; } /** * A convenience overload of {@link #loadProperties(String, ClassLoader)} * that uses the current thread's context classloader. */ public static Properties loadProperties (final String name) { return loadProperties (name, Thread.currentThread ().getContextClassLoader ()); } private static final boolean THROW_ON_LOAD_FAILURE = true; private static final boolean LOAD_AS_RESOURCE_BUNDLE = false; private static final String SUFFIX = ".properties"; } // End of class


The Javadoc comment for the loadProperties() method shows that the method's input requirements are quite relaxed: it accepts a resource name formatted according to any of the native method's schemes (except for package-relative names possible with Class.getResourceAsStream()) and normalizes it internally to do the right thing.
The shorter loadProperties() convenience method decides which classloader to use for loading the resource. The solution shown is reasonable but not perfect; you might consider using techniques described in "Find a Way Out of the ClassLoader Maze" instead.
Note that two conditional compilation constants control loadProperties() behavior, and you can tune them to suit your tastes:
  • THROW_ON_LOAD_FAILURE selects whether loadProperties() throws an exception or merely returns null when it can't find the resource
  • LOAD_AS_RESOURCE_BUNDLE selects whether the resource is searched as a resource bundle or as a generic classpath resource


Setting LOAD_AS_RESOURCE_BUNDLE to true isn't advantageous unless you want to benefit from localization support built intojava.util.ResourceBundle. Also, Java internally caches resource bundles, so you can avoid repeated disk file reads for the same resource name.

More things to come

I intentionally omitted an interesting classpath resource loading method, ClassLoader.getResources(). Despite its infrequent use, ClassLoader.getResources() allows for some very intriguing options in designing highly customizable and easily configurable applications.
I didn't discuss ClassLoader.getResources() in this article because it's worthy of a dedicated article. As it happens, this method goes hand in hand with the remaining way to acquire resources: java.net.URLs. You can use these as even more general-purpose resource descriptors than classpath resource name strings. Look for more details in the next Java Q&Ainstallment.

About the author

Vladimir Roubtsov has programmed in a variety of languages for more than 13 years, including Java since 1995. Currently, he develops enterprise software as a senior engineer for Trilogy in Austin, Texas.Read more about Core Java in JavaWorld's Core Java section.



This story appeared on JavaWorld at
http://www.javaworld.com/javaworld/javaqa/2003-08/01-qa-0808-property.html


четвер, 10 березня 2011 р.

Wallaby від Adobe


Восени Adobe  презентувала нову технологію для конвертування Flash в HTML5 під назвою Wallaby. На сайті можна почитати їхні Release Notes. Тепер Wallaby  можна скачати на Adobe Labs

неділю, 6 березня 2011 р.

How to create gwt maven project?


How to create gwt maven project? Easy! Just run

mvn archetype:generate -DarchetypeRepository=repo1.maven.org -DarchetypeGroupId=org.codehaus.mojo -DarchetypeArtifactId=gwt-maven-plugin -DarchetypeVersion=2.1.0-1

This maven plugin generates project based on GWT version 2.1.0  If you prefer to use version 2.2.0, just replace version in pom.xml. Then the following compilation error will occur

java.lang.NoClassDefFoundError: com/google/gwt/core/ext/GeneratorExt
[INFO] at java.lang.ClassLoader.defineClass1(Native Method)
[INFO] at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632)
[INFO] at java.lang.ClassLoader.defineClass(ClassLoader.java:616)

You should add dependency on gwt-dev.jar

<dependency>
        <groupId>com.google.gwt</groupId>
        <artifactId>gwt-dev</artifactId>
        <version>2.2.0</version>
        <type>jar</type>
        <scope>compile</scope>
</dependency>
By maven-googlewebtoolkit2-plugin

суботу, 5 березня 2011 р.

Maven Multi-Module Quickstart



Recently I’ve had lots of questions about how to create multi-module projects, so when I discovered this technique, I thought I’d write this up. This technique exploits a little known feature of the archetype:create plugin, and the Maven site archetype to kickstart your project. Creating a multi-module project has many benefits, one of them being the ability to build every artifact in a project with one simple “mvn compile” command. Another benefit is that if you are using either the maven eclipse:eclipse plugin or the idea:idea plugin, you can enter this command at the root of the project and it will generate all of the project files for all of the contained modules.

First generate the top level project using the maven-archetype-site-simple archetype using the following command,
mvn archetype:create
 -DgroupId=[Java:the project's group id]
 -DartifactId=[Java:the project's artifact id]
 -DarchetypeArtifactId=maven-archetype-site-simple
this will generate a Maven project with the following directory structure.
Maven Site Simple Folder
The project that is generated is the minimum project setup to generate site documentation. The index.apt file is the main index page for the site, and is written in the Almost Plain Text format, which is a wiki like format. You can also generate a more complete site project using the maven-archetype-site archetype like this,
mvn archetype:create
 -DgroupId=[Java:the project's group id]
 -DartifactId=[Java:the project's artifact id]
 -DarchetypeArtifactId=maven-archetype-site
this will generate the following project structure.
Maven Site Folder Structure
After you have generated the site project, edit the pom.xml created from the site archetype plugin. Make sure the the packaging type is set to “pom” like the following.
1<project>
2    <modelversion>4.0.0modelversion>
3    <groupid>com.pillartechnologygroupid>
4    <artifactid>sampleProjectartifactid>
5    <version>1.0-SNAPSHOTversion>
6<packaging>pompackaging>
7...
8project>
By setting the packaging type to “pom”, any projects you generate from the root of the project directory will insert itself into the project by creating an entry into the modules section of the pom.xml for the site. In the root directory of your project that you created above, type in the following command,
mvn archetype:create
 -DgroupId=[Java:the module's group id]
 -DartifactId=[Java:the module's artifact id]
if you now edit the pom.xml for the main project, you should see an entry towards the bottom of the file like the following.
1...
2<modules>
3    <module>sampleModulemodule>
4modules>
5...
взято звідси

 можна також скористатись командою

1
mvn archetype:generate
тоді в інтерактивному діалозі потрібно вибрати потрібний айтем
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Choose archetype:
1: remote -> docbkx-quickstart-archetype (-)
2: remote -> gquery-archetype (-)
3: remote -> gquery-plugin-archetype (-)
...
205: remote -> pom-root (Root project archetype for
creating multi module projects)
...
306: remote -> trails-secure-archetype (-)
307: remote -> tynamo-archetype (-)
308: remote -> wicket-scala-archetype (Basic setup for a
project that combines Scala and Wicket,
        depending on the Wicket-Scala project. 
Includes an example Specs
        test.)
309: remote -> circumflex-archetype (-)
Choose a number: 82:

в даному випадку для батьківського багатомодульного проекту це 205 елемент ну і далі по аналогії створюємо дочірні модулі