1 Mar 2014

Откуда берутся русофобы

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

Я относился к Бандере без особого негатива, как к человеку, который несомненно боролся за свободу Украины, но и без какой-либо симпатии. Не потому, что он сотрудничал с Гитлером (СССР, Англия, Франция и прочие сотрудничали с ним намного дольше). А потому, что я не считал приемлемыми ни его террористические методы, ни его взгляды на устройство свободной Украины, согласно которым она должна была стать мононациональным однопартийным государством с вождем во главе по типу фашистской Италии. В связи с этим я не использовал националистическое приветствие "Слава Україні! - Героям слава!", и мне не нравилось, когда его кричали ультрас "Шахтера" во время матчей, так как я считал его скомпрометированным.

Я плохо относился к Януковичу и почти так же плохо относился к Тимошенко, Тягнибоку и прочей официальной оппозиции. К ультраправым я относился еще хуже.

Я прожил несколько лет в Санкт-Петербурге. Я получил там образование такого уровня, какого, как мне кажется, я не смог бы получить ни в одном ВУЗе Украины, а также бесценный опыт работы. У меня в России много родственников, друзей и просто знакомых. Русский - мой родной язык, и я знаю его лучше, чем подавляющее большинство россиян. 

Кое в чем я был неправ. Нельзя построить нормальное общество и государство, если каждый раз, когда появляется даже небольшой шанс это сделать, с северо-востока заявляются вооруженные орды без знаков различия и начинают "защищать" нас от мифических ужасов (устраивая при этом ужас вполне реальный).

Согласно одному из определений, быдло определяется через неспособность критически оценить собственные действия с точки зрения окружающих. Россия - это гопник мирового масштаба, которому даже в голову не приходит задуматься, какую реакцию вызывают его операции у соседних народов. Когда же реакция следуют, она объясняется мировым заговором, тем, что все плохие и только русские - Д'Артаньяны, и прочим бредом, верить в который на протяжении сотен лет могут только русские. Русские, в принципе, хотят жить хорошо, но намного приятнее им жить в говне, но чтобы их все вокруг боялись. Именно поэтому в России внутренняя политика является продолжением внешней, а нормальная человеческая власть невозможна. 

День, когда эта самая крупная в мире держава раковая опухоль наконец развалится на естественные составляющие, станет одним из самых счастливых дней в истории человечества. Возможно, он станет счастливым днем и для русского народа - при условии, что он избавится от своих дебильных "имперских" комплексов и гнилой привычки хапать все, что, по его мнению, плохо лежит (а понятие "плохолежащести" у него весьма свободное). За нормальную жизнь придется заплатить потерей большей части захваченных территорий - но, как показывает совсем недавний опыт Великобритании, Франции и других метрополий бывших колониальных империй, это не так уж страшно.

Где там записывают в русофобы, бандеровцы, нацики, западенцы или как там они еще нас называют? Запишите и меня тоже.

P.S. Массовость употребления вышеупомянутого приветствия во время событий последних месяцев была таковой, что теперь оно ассоциируется не с ОУН и не с УПА (кстати, это две разные организации, для тех, кто не в курсе). Оно ассоциируется с желанием жить свободно, а не под властью бандитов или иностранных оккупантов.

Слава Україні!
Героям слава!

23 Jan 2012

Invalid validation 2

Получил письмо от ФК "Шахтер":

Уважаемый болельщик!

Приглашаем Вас принять участие в небольшом опросе.

Для того чтобы Вы могли получать еще больше комфорта и сервиса от каждого посещения «Донбасс Арены», просим Вас уделить 15 минут и ответить на несколько вопросов, перейдя по ссылке ниже:

http://shakhtar.com/ru/poll/?idv=18

"Кто же не хочет получать еще больше комфорта и сервиса?" - подумал я и перешел по ссылке. Вопросов оказалось порядком, но я честно дал ответ на все те из них, на которые смог. А смог я ответить не на все, так как варианты ответов в некоторых случаях не давали такой возможности. Например:



Оставалась робкая надежда на то, что на все вопросы отвечать необязательно, но увы:



Не судьба мне получить еще больше комфорта и сервиса :(.

Потребительское

Смотрим раз:


Смотрим два:



Товарищи! Будьте бдительны! 1,25 л должно стоить дешевле 1 л! Не дайте себя обмануть! Требуйте долива после отстоя пены!

1 Jul 2011

Не тягни до рота усіляку гидоту

Нередко (все чаще) можно встретить людей, пафосно заявляющих нечто вроде "А я считаю, что нужно брать от жизни все!" (к этому обычно добавляется "... пока мы молоды"). Однако, если присмотреться к тому, что именно они предпочитают "брать", то немедленно выясняется следующее:
  1. Не много же они берут.
  2. Качество взятого в большинстве случаев таково, что гораздо более актуальным (и полезным) для них был бы лозунг "Брось каку".

29 Apr 2011

Краткое содержание

Содержание фильмов "Санткум", "127 часов" и им подобных сводится к следующему:
  1. Главный герой или группа главных героев направляется в место, в котором, как всем известно, время от времени случается херня.
  2. Херня случается.
  3. Героическое преодоление последствий херни.
В принципе, фильмы такого рода вполне могут быть сняты хорошо. Операторская работа, игра актеров, тонкий психологизм и все такое. Но кое-что мешает досматривать их до конца с интересом. А именно: отсутствие сочувствия к главным героям вследствие п. 1.

20 Mar 2011

JSF 2: immediate view parameters

The common opinion about JSF versions prior to 2.0 is that they are not well suited for POST-Redirect-GET pattern and bookmarkability. Actually the situation is not that bad. Consider the typical scenario: one page holds a list of entities, each with the link to the entity's own page; that page contains a form for entity properties editing and button to save new values; after button is clicked and entity is updated on server side, redirect is issued to the same entity page. How could this be implemented using JSF 1.2 with facelets?

Each link to the entity page will contain id as a parameter. So table listing entities with links to their page can be implemented as simple as follows:

<h:dataTable var="entity" value="#{entitieBean.entities}">
<h:column>
<a href="entity.jsf?id=#{entity.id}">#{entity.name}"/></a>
</h:column>
</h:dataTable>

entitiesBean implementation is straightforward. When specific entity page is requested, id from request parameter is converted and injected into entityBean. Setter method loads target entity from database and stores it in bean aloowing to be displayed/edited on page. Here is the corresponding config in faces-config.xml:

<managed-bean>
<managed-bean-name>entityBean</managed-bean-name>
<managed-bean-class>test.jsf.EntityBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>entityId</property-name>
<property-class>java.lang.Integer</property-class>
<value>#{param.id}</value>
</managed-property>
</managed-bean>

and EntityBean.java implementation:

public class EntityBean {

private Entity entity;

public void setEntityId(Integer id) {
//load entity from database by id;
}

public Entity getEntity() {
return entity;
}

public void validateName(FacesContext context, UIComponent component, Object value) {
//validate entity name on uniquiness
}

public String save() {
//save entity changes to datatabase
return "success";//action outcome - to be mapped in navigation rules
}

}

on the page, entity form will look like this:

<h:form id="entityForm">
<input type="hidden" name="id" value="#{entityBean.entity.id}"/>
<h:panelGrid columns="2">
<f:facet name="footer">
<h:commandButton action="#{entityBean.save}" value="Save"/>
</f:facet>
<h:outputLabel for="name" value="Name:"/>
<h:panelGroup>
<h:inputText id="name" value="#{entityBean.entity.name}" required="true" validator="#{entityBean.validateName}"/>
<h:message for="name"/>
</h:panelGroup>
</h:panelGrid>
</h:form>

Notice hidden input populated with entity id value: this is required in order to correctly load entity on postback (that is, when "Save" button is clicked) using the same routine as for initial GET request.

So far standard features of JSF were sufficient to implement bookmarkability. The only required feature which is not supported out of the box, is redirect with query parameters. One will need to implement custom NavigationHandler and/or ViewHandler in order to be able to write navigation rules like this:

<navigation-rule>
<from-view-id>/entity.xhtml</from-view-id>
<navigation-case>
<from-action>#{entityBean.save}</from-action>
<from-outcome>success</from-outcome>
<to-view-id>/entity.xhtml?id=#{entityBean.entity.id}</to-view-id>
<redirect/>
</navigation-case>
</navigation-rule>

Once this done, the described scenario is fully implemented. This solution works, hovewer, it still leaves something to be desired:
  • No good way to process conversion errors on id injection
  • No good way perform id validation
  • Custom *Handler must be implemented
  • No tool support for custom format of navigation rules
  • Non-faces hidden input must be added to the forms
Now, with continuing adoption of JSF 2, one of the main target of which was bookmarkabiity support, we can try to rewrite the solution above using new standard features and, especially, view parameters, which at first glance is an elegant solution for id passing.

Side note: the main problem which arises on this way is that view parameters are poorly documented. Actually, this is case for almost all new features. In the JSF 1.1 times specification was written beautifully - one has the option to read spec and be able to fully understand what is going on. Now technology itself is much more attractive but its specification is horrible. For example, when talking about view parameters, it says the following: "The normative specification for this feature is spread out across several places... This leads to a very diffuse field of specification requirements... To aid in understanding the feature, this section provides a nonnormative overview of the feature. Consider a web application that uses this feature exclusively on every page... Every page has at least one <h:link> or <h:button> with the appropriate parameters nested within it. No other kind of navigation components are used in the application.". In other words, spec says that it fails to describe feature in readable way and in order to fix this fail it provides an example (aiming to give us a better understanding of the idea) and this example does not uses form submissions. What if you want to know what happens with view parameters during postback? Spec says nothing about it.
In order to get a better understanding I've bought the "JavaServer Faces 2.0, The Complete Reference" book, but it appears to be written as horribly as the specification itself. So the most information about JSF 2.0 may be found in various blogs and online articles. I used the great one by Dan Allen when investigating view parameters feature.


What we need to do is to add "id" parameter to the entity page. On GET request it will be processed, converted, validated and applied to the model; moreover, it will be saved in view and applied during postback without any additional actions from developer side. Looks promising, isn't it?

Entity list page will not really differ; probably one would use specialized component

<h:link outcome="entity">
<f:parameter name="id" value="#{entity.id}"/>
#{entity.name}
</h:link>

instead of the raw <a> links. Now it's time for entity page. We add an id viewParameter to the view:

<f:metadata>
<f:viewParam id="id" name="id" value="#{entityBean.entityId}" required="true"/>
</f:metadata>

It is also possible to provide additional conversion and validation settings for view parameter but it is not required for now. Then remove hidden id param from the form in hope that it will not be needed anymore. That's all changes required for enity page.

In the page bean we make the following changes. First, add managed bean annotation (or, even better, utilize CDI). Second, add getter for entityId property; in order to provide implementation for it we also need to store value of the entityId in the bean field during setter invocation. We will also utilize implicit navigation feature of JSF 2.0 in action method. The resulting bean class looks as follows:

@ManagedBean
@RequestScoped
public class EntityBean {

private Integer entityId;
private Entity entity;

public void setEntityId(Integer id) {
entityID = id;
//load entity from database by id;
}

public Integer getEntityId() {
return entityId;
}

public Entity getEntity() {
return entity;
}

public void validateName(FacesContext context, UIComponent component, Object value) {
//validate entity name on uniquiness
}

public String save() {
//save entity changes to datatabase
return "/entity?faces-redirect=true&includeViewParams=true";//implicit navigation - no need for navigation rule
}

}

The last step is removing managed bean and navigation sections from faces-config.xml. The obtained solution looks much better then pre-JSF 2 one. Now it's time to test it.

When tested, entities page works well as do entity page when being accessed by GET request. But when form on entity page is submitted we get "Target unreachable" exception.

The reason for this error is that now value of the id parameter is being applied to the model not immediately after managed bean instantiation, but during Update Model Values phase of the standard JSF request processing lifecycle. This means that entity in the managed bean is null before this phase but it is required earlier - at the Process Validations phase, for converting and validating new value of the name property.

How can this error be avoided? The mentioned "JavaServer Faces 2.0, The Complete Reference" book utilizes the following approach for handling postbacks in POST,REDIRECT,GET pattern:
  1. Create method loadEntity(ComponentSystemEvent cse) in the backing bean, which loads entity by id into bean and also stores it in the Flash (say under "selectedEntity" name).
  2. Add <f:event type="preRenderView" listener="#{entityBean.loadEntity}"/> to the metadata section of the page so that this method will be executed before Render View phase.
  3. Add <c:if test="#{! empty flash.selectedEntity}"><c:set target="#{entityBean}" property="entity" value="#{flash.selectedEntity}"/></c:if> to the <h:form>.
This solution has the following disadvantages:
  • A lot of additional code must be written for such easy thing as loading entity by its id. The code is not typesafe (when dealing with Flash).
  • Code and presentation are mixed (that <c:set ..." is a code which is incorporated inside view (facelet page)).
  • It is hard to maintain.
  • It looks ugly.
What we really need is a way to tell JSF runtime that view parameters must be processed and applied before processing of the form components. Sounds familiar... Yes, we need immediate attribute for UIViewParameter!

What can we do in absence of this attribute? I found the following solution working. Add validator method to the managed bean which will validate valued of the id param and move entity loading inside that method :

public void validateID(FacesContext context, UIComponent component, Object value) {
if (value != null) {
entityId = (Integer) value;
//load entity from database by id;
if (entity == null) throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Entity with id = " + entityId + " was not found", null));
}
}

And associate this method with id parameter:

<f:viewParam name="id" value="#{entityBean.countryId}" required="true" validator="#{entityBean.validateID}"/>

Using this solution, entity will be loaded at the Process Validation phase and it will be loaded before processing of the other form components during thesame phase (because view parameter was defined earlier in the page).

While this solution works it still not ideal because loading entity during validation is not what validation designed for. Let's hope that future versions of JSF provide us with some better way for utilizing view parameters during postbacks.

21 Jan 2011

Нам ни павизло, брат

Самый простой и распространенный способ определить модель мобильного устройства, зашедшего на сайт - использовать его user-agent. Несмотря на великое разнообразие принципов формирования агентов и откровенную мерзость некоторых из них, при наличии разумно устроенной базы данных, вдумчивого его наполнения и несложного алгоритма поиска правильно определить телефон можно практически всегда, кроме нескольких клинических случаев. Одним из таких случаев является MAUI.

MAUI WAP Browser - это, как можно догадаться, мобильный браузер, созданный в незапаматные времена как бы не в Siemens, который некоторые не слишком умные производители телефонов пихают в свои изделия. Особенность это браузера (или этих производителей?) в исключительно информативном агенте вида "MAUI_WAP_Browser" (или "MAUI WAP Browser", или "Maui Browser", или другие, аналогичные по своей беспощадности вариации на ту же тему). Поскольку никакого намека на модель в этих агентах не наблюдается (более того, разные телефоны имеют один и тот же user-agent), определить эту самую модель в таком случае не представляется возможным (и UAProf, как обычно, не помогает).

Подводя итог достаточно унылого обсуждения этого прискорбного факта, Luca Passani (создатель WURFLa и вообще известный в кругах разработчиков мобильных сайтов человек), горестно изрек: "Nam ni pavislo, brat.".

Вывод: в безвыходных ситуациях даже итальянцы переходят на русский.