Category Development

Thought about build infrustructure

What makes software workable?

In Java world it’s obvious that to make software workable we need to compile it and package into jar file or whatever to be deployed to your container or simply ran as desktop application.

With TDD way to develop software we got understandable necessity to compile and run automatic tests. There are different kind of tests (unit, function, integration etc) and approaches like BDD, but the main idea is to automate testing process of what you written. In terms of build there are additional steps to be done to make software ready to be deployed.

So the conclusion is to make software workable not only in Java we need a build scripts. Often build scripts are written in different language then application one, for example, Ant – XML, Buildr – Ruby, Maven – XML etc. And some times teams argue that they required some person to do the build job. But if we account several points depicted above it’s obious that build scripts are part of developing software we’re writing. And team should care about scripts. Another point to this is the ability to know something new with your build tool, infrastructure, environment configuration stuff and etc.

So let’s do your build job by yourself it’s too important to be left to someone else.

Listening podcasts Android

Last week I dived into podcast listening and found out a desire to be able to listen podcasts on my Nexus S.

After some investigation I found out an app in Android Market - RssDemon by Meecel and it’s completely free.

This app provides a lot of features to read RSS and listen podcasts I do not want to mirror an app description here – just go by link above.

BTW there is my OPML file http://webdizz.name/wfiles/Podcasts.opml with podcasts I’m listening which can be easily integrated into RssDemon.

Enjoy!

Naming best practices

There are some thoughts regarding naming best practices.

  • Use short enough and long enough variable names in each scope of code. In most cases length may be 1 char for loop counters, 1 word for condition/loop variables, 1-2 words for methods, 2-3 words for classes, 3-4 words for globals.
  • Use meaningful names for variables. Variable name must be an explanation of its content.
  • It’s a good practice to define and agree a naming standards with a team  and write variable names consistently in your code. BTW you can find a lot of conventions for many languages in internet, for example you can choose a Google’s conventions.
  • It’s a good practice to follow a programming language standards
  • Don’t use lowercase/uppercase characters inconsistently: e.g. firstName, FirstName, FIRST_NAME, …
  • Define a rule for naming variables and constants, generally constants are in upper case.
  • Don’t reuse same variable name in the same class in different contexts: e.g. in method, constructor, class. So you can provide more simplicity for understandability and maintainability.
  • Don’t use same variable for different purposes in a method, conditional etc. Create a new and different named variable instead. This is also important for maintainability and readability.
  • Don’t use too long variable names. Long names decrease readability.
  • It’s a good practice to use natural language for naming, genrally a common practice is to use English.
  • Try to choose meaningful names for methods. The method’s name must tell you what method does and for most cases must start with a verb. (e.g. activateCustomer).
  • Use meaningful names for method parameters, so it can describe itself in case of no documentation.
  • Give narrative-like names for your test cases, this helps you to understand what and why test fails. Generally start your test methods with should e.g. shouldFailIfCustomerIsNull
  • Do not over-comment your variables, methods and classes, sometimes it decreases code readability, use self descriptive names instead.
  • Keep methods small, this helps you to give a right names for them.
  • Keep classes small, this helps you give a right names for them as well.

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.

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

Built on Notes Blog Core
Powered by WordPress