Thursday, October 30, 2008

NetBeans

Without blaming it (there are cool features despite its slowness in general, e.g. built-in reverse engineering tool), but I have a question:

Is there any purpose for putting the "show line numbers in my java editor" THAT deep?

Tools->Options->Advanced Options (button in the bottom of the opened dialog)->Options->Editing->Editor Settings, Properties in the right frame->Line Numbers->tick.

Uf.

Product Version: NetBeans IDE 6.1 (Build 200805300101)
Java: 1.6.0_07; Java HotSpot(TM) Client VM 10.0-b23
System: Windows XP version 5.1 running on x86; Cp1252; en_US (nb)

This year NetBeans celebrates its 10 anniversary. Despite what I have just written above, I wish the NetBeans team good luck!

It has been my first IDE for Java development, when I developed a first 'serious' java application (3 months course project officially, 2 weeks of man work in practice). Thank you, guys.

Wednesday, October 29, 2008

Сервис и продукт: разница

Привет,

этот блог-пост решил сделать по-русски. Такой вот у меня получается блог-полиглот.

Подумал сегодня, как описать далёкому от IT в целом и программирования в частности человеку, что есть сервис и в чём разница между сервисом и продуктом. И первое, и второе продаётся за деньги. Вопрос: что лучше? Но об этом после объяснения.

Представьте себе сапожника. Хорошего сапожника. В маленьком городке. У него уже своя клиентура. Люди передают из уст в уста. Когда народу набирается много, у сапожника hands dirty all the time - много работы. Это сервис. И вдруг сапожнику в одну из бессонных ночей (программисты поймут: во время сложного проекта бывает иногда не до сна или просто не можешь долго успокоиться, потому что постоянно думаешь) приходит в голову гениальная мысль: создать сапожно-починочный механизм (воображаемый в рамках этой иллюстрации). Теперь сапожник постепенно переключается на продажу механизма, который чинит сапоги. Это называется продукт. Разница тоже очевидна: когда сервис, сапожник за каждый раз получает деньги, пусть не большие, но каждый раз, когда клиенту нужно починить обувь (а это может быть не так и редко). А когда продукт - механизм, - от каждой продажи можно выручить немаленькие деньги, но - одному клиенту продал, он исчез. Когда механизм забархлит, может быть, клиент вернётся за починкой сапожно-починочного механизма. Теперь нужно расширяться - ездить в соседние города и продавать механизм уже там.

Теперь мнение. Такое: на мой взгляд IT индустрия начала плавный, но уверенный поворот в сторону сервисов. Все профессиональные сапож.. программисты понимают, что создание сервисно-ориентированной схемы бизнеса - это прибыльно и более предсказуемо: вся начинка по сути остаётся в руках компании, а результат достаётся клиенту. Как и в случае с продуктом. А ведь может быть такой продукт, который уже немеренно поедает ресурсов компьютера клиента, чтобы выполнить свою задачу. Что же тогда? Тогда клиенту нужно закупать новые компьютеры, создавать кластер, распараллеливать... Вообщем, долгая история. А создателю продукта это сделать проще: у него есть конкретная цель и фокус на рынке. Значит, многие продукты начнут постепенно переходить в состояние сервисов. Пример: раньше антивирус съедал процессорное время, память и запись / чтение диска, теперь будет функционировать в виде сервиса, где вся работа выполняется удалённо. Что нужно? Преотличный интернет (постепенный, но уверенный процесс роста в этом смысле налицо). Плюс нужно решить задачу с безопасностью, security. Ведь с продуктом вроде легче: купил, установил, настроил, разрешил в файерволе и вперёд. В случае сервиса нужно основательно продумать архитектуру взаимодействия пользовтеля с сервисом: чтобы противостоять натиску желающих воспользоваться чужим паролем.


Собственно, всё. Надеюсь, пример с сапожником окажется полезным, если Вы захотите объяснить / понять разницу между продуктом и сервисом. Подумайте над примерами сервисно- и продуктно-ориентированной бизнес-моделей. Возьмите крупные компании (лучше всего конкурентов).

Monday, October 27, 2008

JSP: how to get form parameter values

Hi,

As I have spent almost a day figuring out, how to get the values of html form's parameters and use them in a jsp code, I have decided to post my solution here.

One can argue, that there are lots of materials on the topic from JavaEE adepts. Well, I hope this message will be as well useful for a stranger in the Internet.

Note: this solution does not pretend to be general and suitable for any task you are solving. There is no WARRANTY for it as well. Do not kill your granny, if this code breaks your computer. Just get some JavaEE book and dive into all odds and ends.

So, if you need to have one html with embedded jsp code, go ahead and create one. Here is an example:




<%@ page contentType="text/html; charset=utf-8"
import="java.io.PrintWriter,
java.util.Map,
java.util.Iterator"
session="false" %>

<%!
/*
* Allows you to post and see the value you have just posted
* @author Dmitry Kan
*/
/**
* get servlet version string
*
*/
public String getServletVersion() {
ServletContext context=getServletConfig().getServletContext();
int major = context.getMajorVersion();
int minor = context.getMinorVersion();
return Integer.toString(major) + '.' + Integer.toString(minor);
}

String lineSeparator = System.getProperty("line.separator");

// an important for this message code starts here
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
Map paramMap = request.getParameterMap();
try {
PrintWriter out = response.getWriter();
String name = null;
String value[] = null;

Iterator iterator = paramMap.keySet().iterator();
while (iterator. hasNext()) {
name = (String)iterator.next();
value = (String[])paramMap.get(name);
out.print (name + "=" + value[0]);
}
} catch (java.io.IOException e) {
}
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
{
doGet(request, response);
}

%>






<head>
<title>SOAPPoster servlet, version <% out.print(getServletVersion()); %></title>
</head>
<body>
<h3>JSP POSTing machine</h3>
<form action="?" method="post" name="actionform">
<table border="0">
<tr>
<td>Copy paste or type your message here:</td>
</tr>
<tr>
<td><textarea rows="10" cols="50" onclick="document.actionform.value=''" name="xmlTextArea"></textarea></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="post!" onclick=<% doPost(request,response); %> /></td>
</tr>
</table>
</form>
</body>
</html>



That's it. Here are some screenshots:



Saturday, October 25, 2008

Alt party



is going right now. Yesterday, during the first day, the folks have eaten the 10th anniversary cake and played games on 10-15 years old machines such like VAX100.
The exhibition has been at higher scale than any of the previous years, according to organizers.



Lenin's printer










The C program I have written in VAX100

Saturday, October 18, 2008

Yandex Cup IX

Кубок Яндекса

Кубок Яндекса

Участвовал в игре Кубка Яндекса по поиску под ником D_K, набрал 10 из 20.
Осталось 3 игры, участвовать можно в любой из них или во всех.

Monday, October 13, 2008

Programming languages' evolution

It took decades for programming languages to evolve as well as for the paradigm shifts to happen.

Currently, young programmers need to really jump over decades when learning one language per years (not decades anymore) before they start their programming career (where you may learn different languages even faster if you want to survive on the market).

What a paradigm shift must be happening in their minds within just few years!

Mood: Impressed after reading first chapters of a book on programming languages and after watching a couple of Standford University video lectures on Computer Science.

Thursday, October 9, 2008

static context in Java

Hi,

Did you know that this:


passwordBase64Str = org.apache.xerces.impl.dv.util.Base64().encode(password.getBytes());


---> leads to a warning inside Eclipse IDE (Version: 3.4.0 Build, id: I20080617-2000), when you get the underlined (by default) yellow line of your code? It tells about static context, in which you need to access the method encode().

Eclipse suggests to resolve the warning this way:


new org.apache.xerces.impl.dv.util.Base64();
passwordBase64Str = Base64.encode(password.getBytes());


I.e. first, you create an (anonymous?) object of type Base64(). Second, you call its method encode().



Now the tricky point for me was understanding the instruction


new org.apache.xerces.impl.dv.util.Base64();


Is this supposed to create an anonymous class, which will (upon creation) be known as exactly "Base64" inside the JVM?

It is further interesting, that if I substitute Base64() in the original call (in the beginning of this post)


org.apache.xerces.impl.dv.util.Base64().encode(password.getBytes());


for the suggested by the IDE


new org.apache.xerces.impl.dv.util.Base64()


I get:


passwordBase64Str = (new org.apache.xerces.impl.dv.util.Base64()).encode(password.getBytes());


for which, the Eclipse produces the same warning above.

Does it confuse you?



upd: when I turned to explaining the issue second time to one friend of mine, I have realized that from these two lines:


new org.apache.xerces.impl.dv.util.Base64();
passwordBase64Str = Base64.encode(password.getBytes());


the first one is obsolete. So this is just a "bug" (a "feature") in the Eclipse IDE.

Friday, October 3, 2008

The British

Hi,

I was just wondering whether the following is true: do British people like to stroke (the proper noun for this is effleurage from the point I see it) their colleagues, mates - people they chat to (not the ones in love with them)?

I have a british colleague doing this and actually this is just cute.