Category Development

Kyiv GTUG HTML5 hackathon #chromekyiv.

Last saturday (23.10.10) I was a participant of the HTML5 hackathon day organized by Kyiv GTUG can be followed in twitter #chromekyiv . There were a lot of fun.

Excellent speech by Michael Mahemoff @mahemoff about HTML5 features and perfect talks at coffee-breaks and lunch. I’ve got a lot of good impressions and spent my day with a big pleasure.

After Michael’s speech we had a lunch, during that we (@yasik and @shooshpanchick and me aka @webdizz) were involved in discussions regarding different aspects of developer’s life and technologies and generating ideas for our demos.

From the beginning of idea generating period of the day we decided to build up an app that will show tweets on the Earth rotating with appropriate speed  from twitter . But after several attempts to get a developer key we’ve got stocked. dev.twitter.com was down:(. It was a really shame.

Then we decided to move to something another and again was in a stock.

And time gone on…

So at last we found out an idea to work with. We decided to build an extension for Google Chrome to grab addresses from current page and display those addresses on the Google Maps or on the Yandex Maps and dived in coding.

Our extension contains HTML5 elements tag “nav” in the menu to choose map to display found addresses on and tag “canvas” circles to highlight found and not found addresses on the Google Maps. Also there is a lot of JavaScript magic.

So, time again was against us and it blown out.

The time for demo begun. We were first to demonstrate our work and seems it was ok according to results.

There are following results, we took first place as a team and one girl between all participants Anna Shaban with CSS3 photo gallery and hard-to-describe visual effect involving your name being shown at a million angles and opacities.

All winners were awarded with great presents and invitation to GDD 2010 in Moscow.

I’d like to thank to people who organized such a great event from Kyiv GTUG and to Michael Mahemoff.

Git survey

If you have something to improve in the Git follow next link and make an influence http://tinyurl.com/GitSurvey2010-Anonymous .

Spring WS difficulties or lack of documentation

В этот раз история будет о неожидонных сложностях, возникшых с одним из замечательных модулей Spring, а именно Spring WS.

На проекте возникла необходимость написания WebService с нуля, было решено использовать Spring и стандартные технологии  в качестве связующей платформы в пользу проприетарных BEA, а теперь уже Oracle принадлежащих решениях. В частности для слоя работы с базой данных мы решили использовать JPA, а в качестве провайдера OpenJPA, до этоо в компании использовалось DSP, честно, первый раз услышал, разбираться не стали. Для WebService стека соответственно Spring WS, вместо чистого JAX WS со связкой через EJB, DAO и BO слои, вы можете сказать, что JAX WS это тоже стандарт, да не могу с вами не согласиться, но Spring WS находится на грани между стандартами и предоставляет гибкость при использовани разных технологий.

В общем после выбора технологий мы принялись за реализацию, и тут нас настигли небольшие трудности… Spring WS навязывает использование подхода – сначала XML потом Java код, это объясняется необхоимостью обеспечения портированности. Это достигается за счет того, что вы продумываете используемые типы данных в WebService и при генерации кода, можно получить не только для языка, с которым вы работаете, но и для любого другого, либо с вашим WebService сможет работать лубой другой клиент, написанный на любом языке.

Так же одной из еще возникших непонятностей, это возвращаемые и принимаемые на вход аргументы и их типы. Как оказалось после дебага в течении итеративных правок кода, сборки, деплоя на WebLogic, и запуском SOATest на запущенном в режиме отладки WebService, было выяснено, что WSDL, предложенный нам архитекторами не совместим с подходом Spring WS. В частности по привычке работы с JAX WS, методы WebService принимали несколько аргументов как примитивных, так и комплексных типов, что так же было присуще и возвращаемым типам данных. По-началу мысли были в стороне приведения типов аргументов и возвращаемых значений к примитивным, но этот фокус не удался. После дальнейшего “дебага” мы наконец-то поняли – Spring WS поддерживает в качестве аргумента только комплексный тип, описанный в XML, при чем аргумент должен быть один. Ну и возвращаемый тип значения тоже должен быть комплексным и описанным в XML. Таким образом если вы возвращаете значение примитивного типа, то вам нужно обвернуть его в комплексный тип и задекларировать в XML (WSDL или XSD).

После приведенных выше правок, наш WebService закрутился на ура, оставалось соглавсовать наши правки в WSDL с архитекторами.

На первый взгляд упомянутые выше ограничения не логичны, но если поразмыслить, то все становится на свои места. Делая обвертки для множества аргументов и примитивных типов возвращаемых значений в виде комплексного типа, мы увеличиваем уровень абстракции и инкапсуляции WebService.

На этом пожалуй мое повествование можно считать завершенным.

Всем удачи и ожидаемых ожиданий ;)

Guitr – the ease of git usage with multi-git-repo-project structure v0.0.6

Today new version 0.0.6 of the Guitr gem was released with following enhancements:

  • git related operations should be silent to not spam if there is nothing to display
  • options resolving logic was rewritten with OptionParser
  • –exec – a new operation allows to invoke commands against repository directory. For example, you can run guitr –exec ‘git status’ command git status will be invoked against repository directory. It will be helpful if you need to perform similar operations against each repository directory but guitr does not support it. Also the command can be any system command.

For now that’s it.

Enjoy playing Guitr ;)

Medeniye loogat Google Chrome extension

Вот и настал этот долгожданный час:) Сегодня вышла первая версия расширения для Google Chrome.

Функциональность расширения заключается в обеспечении возможности поиска перевода для выбранного слова в словаре Medeniye loogat. Для поиска перевода необходимо нажать кнопку Ctrl и кликнуть 2 раза на интересующем слове для его выделения, затем отобразится найденный перевод либо похожие слова.

Описанный выше функционал пожалуй весь арсенал данного расширения, основной же особенностью является техническая сторона, а именно – оно написано полностью на GWT.

Расширение можно установить с этой страници: https://chrome.google.com/extensions/detail/kalnlennobeikiffcdhdnjpnmmbjdigi .

powermock – real power for testing untestable stuff

Last weekend was spent to make my Chrome extension base on GWT working with content scripts written using GWT. As one of main concept is to keep my trust for my code on appropriate level. To achieve this I’m practicing in TDD. For testing purposes I use JUnit 4.x and for mocking Mockito.

I’d like to spend some thime on MockitoMockito is really powerful mocking framework with sweat features, all ones you can find here http://code.google.com/p/mockito/wiki/FeaturesAndMotivations. As for me I really like nice and laconic syntax ans simplicity.

The information above is not a main reason of this post, the main one is to tell about my experience to test code using GWT classes e.g. finals and statics. After some time spent to google something will be helpful I’v found out PowerMock. This framework provides abilities to mock static classes and final methods and as you might know GWT uses a lot of such stuff.

For example I need to test method which handles browser page’ events from content script and pass related data to background page to process those data. The issue was to assign event for whole page, this is impossible as RootPanel.get() does not support event handlers. So I’ve found out another way – use Event.addNativePreviewHandler and NativePreviewHandler to hande events.

So I created implementation of NativePreviewHandler and started from test. Logic is quite simple but I was unable to use GWT code in my POJT (Plain Old Java Test), as NativeEvent returned by NativePreviewEvent as an argument for method NativePreviewHandler.onPreviewNativeEvent requires GWT.create method call, which in turn need a GWT context to be set up. But this is not what I want.  I’d like to have simple and fast tests without necessity to compile Java to JavaScript and only after to test.

In this situation I need mock GWT classes to be able to test my code, but Mockito does not support mocking for static classes and final methods. So PowerMock solved my trouble. Example of usage:

@RunWith(PowerMockRunner.class)
@PrepareOnlyThisForTest({ NativeEvent.class, SelectionProvider.class })
@SuppressStaticInitializationFor({ "com.google.gwt.dom.client.NativeEvent" })
public class ContentScriptEventHandlerTest {
 
        @Mock
	private ChromePort port;
 
        // Creates mock for class with final methods
	private NativeEvent event = PowerMockito.mock(NativeEvent.class);
 
	@Before
	public void setUp() throws Exception {
		MockitoAnnotations.initMocks(this);
                // Creates mock for static class
		PowerMockito.mockStatic(SelectionProvider.class);
                // assign return value for method from static class
		PowerMockito.when(SelectionProvider.getSelection()).thenReturn("word");
                // there was stackoverflow and we do not need to call for equals
		PowerMockito.suppress(event.getClass().getMethod("equals", Object.class));
                // assign return values for final methods
		PowerMockito.doReturn("mouseup").when(event).getType();
		PowerMockito.doReturn(true).when(event).getCtrlKey();
		PowerMockito.doReturn(true).when(event).getAltKey();
	}
 
	@Test
	public void shouldNotConsumeNotMouseupEvent() throws Exception {
		ContentScriptEventHandler eventHandler = new ContentScriptEventHandler(port);
		NativePreviewEvent previewEvent = mock(NativePreviewEvent.class);
		PowerMockito.doReturn("notamouseevent").when(event).getType();
		when(previewEvent.getNativeEvent()).thenReturn(event);
 
		eventHandler.onPreviewNativeEvent(previewEvent);
		verify(previewEvent, never()).consume();
	}
}

That’s it. Have enjoy testing…

Build extension for Google Chrome with GWT

From time-to-time I’m coming back to do some coding to provide Chrome Extension with helping to translate and remember words.

From this repository http://github.com/webdizz/clt now you can download the source code of the extension, however it is in the pre-pre-alpha state. But the main reason of this post is to tell about implemented abilities to write ContentScript using GWT.

Initial code of the GWT linker for Chrome Extension was pulled from SpeedTracer extension, after that I’ve provide some enhancements to support additional features.

  • GWT Linker for Chrome Extension was extracted into separate subproject;
  • ComponentGenerator was refactored and provided with initial pack of tests;
  • ExtensionScript artifact was added – which provides you abilities to define external JavaScript file to be injected into the BackgroundPage and loaded on extension initialization. This is useful for example when you are working with Google Language API or another required JavaScript library which you cannot include as a static content;
  • ContentScript now support all_frames attribute;
  • GwtContentScript artifact was introduced – which provides you abilities to implement ContentScript code with GWT and include it as a static ContentScript into your extension. Example of this you can find in my extension. But there is an issue – I’m not able to resolve path to extracted war to copy generated JavaScript file from GWTContentScript module into extension module, but there is workaround for this – you need to define own launcher (for Eclipse) to build extension. Example launcher can be downloaded here http://github.com/webdizz/clt/blob/master/clt-crx/Build-clt-extension.launch.

That’s it for now, have a nice week.

Guitr – the ease of git usage with multi-git-repo-project structure v0.0.4

Recently new version of the guitr ruby gem was pushed and ready to use.

There are following changes were made since my first post about this gem:

  • –unpushed operation – helps to check what was commited but havn’t pushed yet
  • –pull operation was refactored to a standard git pull command
  • –status operation was refactored to a standard git status command as well
  • git operation error stops guitr invocation bug was fixed
  • spec coverage was enhanced

What’s next.

In the future time I’m going to implement push operation and integrate with http://optionparser.rubyforge.org/ to handle command line arguments.

And in the far future time commits, think it can help to have one message for commits across several repositories related to one feature/user story.

That’s it, thanks for your time.

Enjoy playing guitr ;)

Guitr – the ease of git usage with multi-git-per-project structure

Today I’ve pushed a gem to ease of git pull/status actions on multi-modules projects with git repository per project.

What I mean about multi-modules projects – this is a case when you have some modules/projects with separate git repositories. To avoid manually entering into each directory to perform pulling or checking the status you can install guitr and relax a bit ;)

To install guitr use following command:

[sudo] gem install guitr

To check status use following command:

guitr --status [path_to_repo]  #path is optional argument and if not specified guitr will use current directory as a base directory to start walk from.
guitr --pull [path_to_repo] #Invokes git pull per each git working directory

Fow this time that’s it what guitr can do.

Stay up-to-date here http://webdizz.name/posts/guitr.

Enjoy playing guitr ;)

What’s new in up-coming BuildR

Сегодня заглянул в треккер проекта Buildr и по всей вероятности уже очень скоро можно будет насладится вкусностями, которые обещают включить в версию 1.4.

Итак, что же в этой версии ожидается:

  • поддержка JRuby 1.5, JMock 2.5.1, Ant 1.8.0, JUnit 4.7
  • устранена ошибка падения при работе с rubygems 1.3.6
  • include/exclude методы научились поддерживать лямбда выражения, принимать на вход таски Rake, а так же поддрежка регулярных выражений
  • улучшена поддержка Scala
  • имплементирована поддержка protobuf
  • поддержка в качестве билд-файла файлы buildfile.rb и Buildfile.rb на ряду с buildfile.

Полный список изменений можно узнать тут.

P.S. Немного рекламы – если вы используете Buildr для сборки вашего проекта и ваш проект на Java, то вооспользуйтесь екстеншеном для форматирования кода http://rubygems.org/gems/jstyler.

Copyright © Lead your flow
Just another blog about someone' …

Built on Notes Blog Core
Powered by WordPress