Tuesday, December 9, 2008

Reverse-engineer Source Code into UML Diagrams









How to use in maven










org.apache.maven.plugins
maven-javadoc-plugin

org.exoplatform.services.portletcontainer.test
org.umlgraph.doclet.UmlGraphDoc
/home/alexey/java/eXoProjects/portlet-container/trunk/component/core/UmlGraph.jar
-views




































































Install dependency program:

sudo apt-get install graphviz

Maven command:

mvn site












PACKAGE org.exoplatform.services.portletcontainer.pci


1. views
2. inferrel and inferdep
3. inferrel, inferdep, operations and constructors




CLASS ActionInput

1. views
2. inferrel and inferdep

3. inferrel, inferdep, operations and constructors

CLASS Input

1. views
2. inferrel and inferdep
3. inferrel, inferdep, operations and constructors


http://java.dzone.com/articles/reverse-engineer-source-code-u

It works pretty good!!!

Documentation here

What Gets Drawn

-all
Same as -attributes -operations -visibility -types -enumerations -enumconstants
-attributes
Show class attributes (Java fields)
-commentname
Name the element using the text in the javadoc comment, instead of the name of its class.
-constructors
Show a class's constructors
-enumconstants
When showing enumerations, also show the values they can take.
-enumerations
Show enumarations as separate stereotyped primitive types.
-hide
Specify entities to hide from the graph. Matching is done using a non-anchored regular match. For instance, "-hide (Big|\.)Widget" would hide "com.foo.widgets.Widget" and "com.foo.widgets.BigWidget". Can also be used without arguments, in this case it will hide everything (useful in the context of views to selectively unhide some portions of the graph, see the view chapter for further details).
-operations
Show class operations (Java methods)
-qualify
Produce fully-qualified class names.
-types
Add type information to attributes and operations
-view
Specify the fully qualified name of a class that contains a view definition. Only the class diagram specified by this view will be generated.
See the views chapter for more details.
-views
Generate a class diagram for every view found in the source path.
-visibility
Adorn class elements according to their visibility (private, public, protected, package)


Relationship Inference

-collpackages
Specify the classes that will be treated as containers for one to many relationships when inference is enabled. Matching is done using a non-anchored regular match. Empty by default.
-inferdep
Try to automatically infer dependencies between classes by inspecting methods and fields. See the class diagram inference chapter for more details. Disabled by default.
-inferdepinpackage
Enable or disable dependency inference among classes in the same package. This option is disabled by default, because classes in the same package are supposed to be related anyway, and also because there's no working mechanism to actually detect all of these dependencies since imports are not required to use classes in the same package.
-inferdepvis
Specifies the lowest visibility level of elements used to infer dependencies among classes. Possible values are private, package, protected, public, in this order. The default value is private. Use higher levels to limit the number of inferred dependencies.
-inferrel
Try to automatically infer relationships between classes by inspecting field values. See the class diagram inference chapter for further details. Disabled by default.
-inferreltype
The type of relationship inferred when -inferrel is activated. Defaults to "navassoc" (see the class modelling chapter for a list of relationship types).
-useimports
Will also use imports to infer dependencies. Disabled by default, since it does not work properly if there are multiple classes in the same source file (will add dependencies to every class in the source file).










google codesearch ? pom.xml + UmlGraphDoc
google codesearch ? pom.xml + org.umlgraph.doclet.UmlGraphDoc

Friday, December 5, 2008

SAXException2: missing an @XmlRootElement annotation

PROBLEM
Caused by: com.sun.istack.SAXException2: unable to marshal type "org.exoplatform.training.portlet.eventing.AddressBookEntry" as an element because it is missing an @XmlRootElement annotation
at com.sun.xml.bind.v2.runtime.XMLSerializer.reportError(XMLSerializer.java:244)
at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.serializeRoot(ClassBeanInfoImpl.java:303)
at com.sun.xml.bind.v2.runtime.XMLSerializer.childAsRoot(XMLSerializer.java:490)
at com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:328)
... 67 more
[com.sun.istack.SAXException2: unable to marshal type "org.exoplatform.training.portlet.eventing.AddressBookEntry" as an element because it is missing an @XmlRootElement annotation]
at com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:331)
at com.sun.xml.bind.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:257)
at javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(AbstractMarshallerImpl.java:75)
at org.exoplatform.services.portletcontainer.plugins.pc.portletAPIImp.StateAwareResponseImp.validateWithJAXB(StateAwareResponseImp.java:244)
at org.exoplatform.services.portletcontainer.plugins.pc.portletAPIImp.StateAwareResponseImp.setEvent(StateAwareResponseImp.java:263)

SOLUTION

As the error message suggests, one way is to put @XmlRootElement on your class. Another way is to use JAXBElement like this:

marshaller.marshal( new JAXBElement(new QName("nsUri","local"), AddNumbersResponse.class, result), ... );


Sample at here MyEventPub

Thanks to kohsuke at forums.java.net








Wednesday, December 3, 2008

Converting Date from xml unmarshalled format to the standard representation.

Converting from "2008-12-03T12:46:35.896+02:00" to "Wed Dec 03 12:46:35 GMT+02:00 2008".


String dt = "yyyy-MM-dd'T'HH:mm:ss'.'SSSZZZZZ";
SimpleDateFormat sdf = new SimpleDateFormat(dt);
String outDateString = source.substring(0, 26) + source.substring(27, 29);
Date outDate = sdf.parse(outDateString);

Convert a String into an Element

Convert a String into an InputStream

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

StringBuffer stringBuffer1 = new StringBuffer("2008-12-03T13:24:00.408+02:00");
ByteArrayInputStream bis1 = new ByteArrayInputStream(stringBuffer1.toString()
.getBytes("UTF-8"));

Convert an InputStream into Document
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(bis1);

As a result of Element

org.w3c.dom.Element messageElement = document.getDocumentElement();


Tuesday, December 2, 2008

Антран плагины: нельзя два в одном и как проверить проперть

Если вы напишете в поме два плагина антран, то будет валидный только второй.

Вот пример:

===\/=====================================
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<id>000</id>
<phase>clean</phase>
<configuration>
<tasks>
<echo>=== ECHO === [${project.build.directory}] ===</echo>
<echo>=== ECHO === 000 ===</echo>
<echo>=== ECHO === 000 ===</echo>
</tasks>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<id>0</id>
<phase>clean</phase>
<configuration>
<tasks>
<echo>=== ECHO === [${project.build.directory}] ===</echo>
<echo>=== ECHO === 0 ===</echo>
<echo>=== ECHO === 0 ===</echo>
</tasks>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
===/\=====================================

Результат работы:

[INFO] [clean:clean]
[INFO] [antrun:run {execution: 0}]
[INFO] Executing tasks
[echo] === ECHO === [/home/alexey/java/eXoProjects/portlet-container/trunk/applications/tck-tests/target] ===
[echo] === ECHO === 0 ===
[echo] === ECHO === 0 ===
[INFO] Executed tasks


Кстати, таким образом антран плагином можно проверить наличие системной проперти при помощи ECHO!

Затягиваем в Эклипс несобирающийся проект.


Всем привет!

1. Редактируем файл "pom.xml":
    сразу за тегом "<build>" вставляем строки:
-------------------------------------
           <sourceDirectory>src/nosources</sourceDirectory>
    <testSourceDirectory>src/notest</testSourceDirectory>
-------------------------------------

2. Выполняем команду "mvn eclipse:eclipse"
  можно использовать до этого mvn eclipse:clean

3. Редактируем файл ".classpath"
  Сразу после тега " <classpath>" заменяем строки:
-------------------------------------
  <classpathentry kind="src" path="src/main/java"
including="**/*.xml|**/*.xsl|**/*.properties|**/*.ion|**/*.conf|**/*.config"
excluding="**/*.java"/>
  <classpathentry kind="src" path="src/main/resources"
including="**/*.xml|**/*.xsl|**/*.properties|**/login.conf|**/*.ion|**/*.conf|**/*.config"
excluding="**/*.java"/>
  <classpathentry kind="src" path="src/test/java"
output="target/test-classes"
including="**/*.properties|**/*.xml|**/*.txt|**/*.conf|**/*.config"
excluding="**/*.java"/>
  <classpathentry kind="output" path="target/classes"/>
-------------------------------------

на строки:
-------------------------------------
        <classpathentry kind="src" path="src/main/java"/>

        <classpathentry kind="src" path="target/generated"/>

        <classpathentry excluding="**/*.java" including="**/*.xml" kind="src"
path="src/main/resources"/>

        <classpathentry kind="src" output="target/test-classes" path="src/test/java"/>
-------------------------------------

Потом фиксим уже в Эклипсе чего-там не собирается, при этом проверяем
билд с восстановленным файлом "pom.xml"

С уважением,
Алексей.


Monday, December 1, 2008

SAXParseException: Content is not allowed in prolog.

[org.xml.sax.SAXParseException: Content is not allowed in prolog.]
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.createUnmarshalException(AbstractUnmarshallerImpl.java:315)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.createUnmarshalException(UnmarshallerImpl.java:510)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:215)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:190)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:241)
at org.exoplatform.services.wsrp2.utils.StandardPayload.getUnmarshalledObject(StandardPayload.java:95)
at org.exoplatform.services.wsrp2.utils.StandardClasses.getUnmarshalledObject(StandardClasses.java:71)
at org.exoplatform.services.wsrp2.utils.JAXBEventTransformer.getUnmarshalledObject(JAXBEventTransformer.java:254)
at org.exoplatform.services.wsrp2.utils.JAXBEventTransformer.getEventsUnmarshal(JAXBEventTransformer.java:132)
at org.exoplatform.services.wsrp2.consumer.impl.WSRPConsumerPlugin.processAction(WSRPConsumerPlugin.java:745)


Where not a consistent xml to unmarshal.
Первый параметр должен быть репрезентацией валидного хмл.

JAXBElement
unmarshal(Node node, Class declaredType)

JAXBElement stdElement = unmarshaller.unmarshal(messageElement,classT);

Friday, November 28, 2008

Internet: check and restart.

Как проверить интернет?!



Как перезагрузить интернет?!
D-Link 2500 how-to restart.

Pulling down of a monument to Lenin.

Демонтаж(снос) памятника Ленина

Updated Вт дек 02, 2008 11:38 am
На данную минуту идет "демонтаж" первого в мире памятника ногам Ленина, простоявшего всего три дня. :)






http://www.unian.net/rus/news/news-287229.html


Копия картинки с веб-камеры на утро. Слева видно что с памятником что-то не так.



Вот видео этого безобразия.

Web-camera
http://82.207.68.254/mjpg/video.mjpg
http://82.207.68.254/view/index.shtml

Full video



Short video




Было
Жалко этих пенсионеров, это был их праздник, который у них забрали!

Есть сейчас (видимо, снимали из здания обладминистрации)

Давно как было

Тема на Черкасском форуме - Снимают памятник ЛЕНИНА

С другой ветки:
Добавлено: Пт ноя 28, 2008 2:25 pm

Ответы: 13
Просмотры: 211


Решение прнимает не рада а виконком, что он и сделал вчера после сессии.

Итог.
История ничему не учит людей, как тех кто ставил памятник так и тех кто его разрушал.
Как говориться "ломать не строить", а наши чиновники на большее и не способны. Тихо приняли решение и быстро его реализовали. Эх, так бы дороги ремонтировали! И то толком не смогли сделать, так как по видео видно что хотели оторвать за среднюю часть а верхняя отвалилась. Вы хоть его проект брали в руки перед сносом или так просто наняли крановщиков с соседней стройки очередного гипермаркета?

Интересно у нас работают депутаты. Сначала принимают закон об охране памятников, потом некоторые памятники исключают из реестра и, наконец, тихо принимают решения о его сносе.

Хотелось бы увидеть текст решения и кол-во потраченных денег на исполнение! Ведь это же за счет жителей Черкасс, которые исправно платят налоги сделали такое безобразие.

Вы хоть спросили у этих самих жителей мешает ли он им? Лично мне - нет.
Вы бы посмотрели в глаза тем пенсионерам, которые в троллейбусе везут к нему собственно вырощенные цветы.

У ЧЕРКАСАХ ЗВАЛЕНО ПАМЯТНИК ЛЕНІНУ
У ЧЕРКАСАХ  ЗВАЛЕНО ПАМЯТНИК ЛЕНІНУ

Wednesday, November 26, 2008

Оксиенно


Вот, нарисовал на выходных за 10 секунд. Надеюсь он Вам поднимет настроение.
Это логотип просьба не читать как "охуенно", а читать как "оксиенно"! :)

Thursday, November 13, 2008

Improved jar search tools at jarfinder.com

http://www.theserverside.com/news/thread.tss?thread_id=51814

Нашел статейку на серверсайде о том что есть сайт с улучшенным поиском джаров и классов.
Я попробовал найти наши джары, результат отрицательный.

http://www.jarfinder.com/index.php/jars/search/%7Eexo%7E
http://www.jarfinder.com/index.php/java/search/%7EPCConstants%7E

Гораздо лучше искать джар в гугле, внимание метод публикуется впервые! :)
Строка запроса: intitle:"index.of" (JAR) имя_для_поиска

Например: intitle:"index.of" (JAR) portlet-container

=========================
In english.

How to search jar:
in google search type
intitle:"index.of" (JAR) name_to_search
Example: intitle:"index.of" (JAR) portlet-container

Wednesday, November 12, 2008

DLink 2500 admin screenshots

Мой предыдущий пост о модеме d-link-2500u (описание, цена, настройка)

Пары картинок идут так: не работает интернет и работает.
При это проблема решается перезагрузкой модема, при нажатии на кнопку "Save and reboot"

1. D-Link Tools Test



2. D-Link Status Device info



3. D-Link Status Route info



4. D-Link Status ADSL




Unworks and works inet connection screenshots.

Friday, October 31, 2008

Украина "отрубает" российский телеэфир

На Украине завтра прекратят вещание российские телеканалы. Российский МИД расценивает это как нарушение прав граждан Украины. На Смоленской площади заметили, что прекращение трансляций «не очень здоровый симптом общества».
Добавим, горсовет Севастополя отказался исполнять это распоряжение Совета национального телерадиовещания Украины. Депутаты посчитали указ незаконным и противоречащим основным принципам свободы слова и демократии.
Что за фигня?


Wednesday, October 29, 2008

Result of Process to String


Process p = Runtime.getRuntime().exec(...);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
String answer = sb.toString();


Original at here

Tuesday, October 28, 2008

Как поменять имена пакетов в классах джара.

http://code.google.com/p/jarjar/

Этот прекрасный джар может это селать! :)

Если нам нужно использовать стороннюю библиотеку, которая зависит от какого-то пакета в новой библиотеке, но в класспасе у нас есть старая библиотека с тем же пакетом, которую нельзя выкинуть, так как она нужна другим программам (или серверу приложений например).

Используя эту утилиту можно поменять в скомпилированных классах сторонней библиотеки (которую мы хотим использовать) зависимости на другое имя пакета новой библиотеки. Соответственно изменив ту новую библиотеку и подложив её в класспас (или серверу приложений).

Monday, October 27, 2008

wp-cumulus

Tomcat JAAS. Фраза дня :)

логин конфиг в веб-хмл описывает реалм, для реалма прописан логин модуль, который обращается к нашему сервису, а в контексте описан класс приципала, который логин модуль поставит в сабджект

Friday, October 24, 2008

Микроблоги


Вообщем, вчера вечером наткнулся на одну заметку о новом сервисе микроблога.
http://habrahabr.ru/blogs/microblogging/43029/


Хороший простой сервис juick.com, но нашлась одна лазейка для вставки HTML кода и результат вот ...







Вот у меня даже получилась идея макроблоггинг, с возможностью вставлять не такие большие картинки и видео а что-то поменьше. И ресурс с текстом и картинками не больше стольки-то пикселей... становиться веселее! :) ... но это уже другое, не такое грандиозно-простое как было задумано.

Респект создателю! Мне понравилось!

Не пытайтесь это повторить, т.к. после переписки с создателем эта проблема была устранена.

PS: Мое сообщение было тысячным
http://juick.com/zavizionov@jabber.zp.ua/998

Thursday, October 23, 2008

Какая программа такое рисует?


Интересный рисунок, у кого есть какая-нибудь информация об этом?

Monday, October 20, 2008

Прикольный таксист!

Monday, October 13, 2008

The best presentation


Death by PowerPoint

From: thecroaker, 2 years ago


Death by PowerPoint
View SlideShare presentation or Upload your own. (tags: tips powerpoint)



Fighting death by PowerPoint... How to make a presentation and not to bore your audience to death.


SlideShare Link