Показаны сообщения с ярлыком Java. Показать все сообщения
Показаны сообщения с ярлыком Java. Показать все сообщения

пятница, 30 мая 2014 г.

SSL configuration of the Websphere MQ Java/JMS client

Introduction

This article shows you how to configure an Secure Sockets Layer (SSL) connection from a Java™/JMS client to an IBM® WebSphere® MQ Queue Manager. It covers the creation of test certificates but does not cover any MQ configuration information. It is purely a Java/JMS client guide and requires an IBM SDK.
Steps 1, 3, and 4 below are required to configure an SSL connection. Do Step 2 only if you wish to configure client authentication. To reduce complexity and simplify debugging of any potential problems, I recommend that you not use client authentication initially. After you have a basic SSL connection, you can move up to client authentication.
If you experience configuration problems, it may help to specify the debug flag: -Djavax.net.debug=true.

среда, 22 мая 2013 г.

GELF appender for log4j2

I start project gelfj2. It's very simple GELF implementation in pure Java with the Log4j2 appender.

It uses log4j2 logging library and supports chunked messages which allows you to send large log messages (stacktraces, environment variables, additional fields, etc.) to a Graylog2 server.

Проверка является ли число степенью 2

Очень простой метод. Реализация на java

if (Integer.bitCount(bufferSize) == 1) {
         //степень 2
} else {
        //не является степенью 2
}
И метод bitCount из Java SDK
/**
     * Returns the number of one-bits in the two's complement binary
     * representation of the specified <tt>int</tt> value.  This function is
     * sometimes referred to as the <i>population count</i>.
     *
     * @return the number of one-bits in the two's complement binary
     *     representation of the specified <tt>int</tt> value.
     * @since 1.5
     */
    public static int bitCount(int i) {
        // HD, Figure 5-2
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
return i & 0x3f;
    } 

понедельник, 20 мая 2013 г.

Calculate the next power of 2, greater than or equal to x


Very short and simple method =) Use for yourself

/**
     * Calculate the next power of 2, greater than or equal to x.<p>
     * From Hacker's Delight, Chapter 3, Harry S. Warren Jr.
     *
     * @param x Value to round up
     * @return The next power of 2 from x inclusive
     */
    public static int ceilingNextPowerOfTwo(final int x)
    {
        return 1 << (32 - Integer.numberOfLeadingZeros(x - 1));
    }

четверг, 25 апреля 2013 г.

JavaOne 2013 Moscow

Посетил Java One 2013 в Москве.

Народу было много. При регистрации выдали неплохие рюкзаки (3 из 5). Обеды так себе. Гамбургеры с холодной котлетой.

Очень много докладов было с прошлых Java  One и других конференций. Почему то все считают, что им нужно что-то знать про performance в java, хотя сами верстают jsp/jsf странички.

Для себя познал несколько полезных инструментов и технологий:

  • JMH - benchmark framework от Oracle. Уже начал использовать :)
  • Мутационнное тестирование - валит тесты, которые ничего не тестируют
  • JavaFX - deployment, mobile(ios, android) implementations
  • NetBeans Platform - swing платформа для создания десктопных приложений. Очень уж ее рекламировали во 2 день
И все таки круто, что Java портировали на ARM. Большая перспектива наклевывается. Программировать мини-устройства на таком высокоуровнем языке как Java. 

среда, 27 февраля 2013 г.

Java Static Fields

Большинство людей, начинающих разрабатывать на Java не понимают различая между "public static String" и "public String" и расницу между классом и объектом. Здесь будет представлено коротрое объянения.

четверг, 21 февраля 2013 г.

Обмен значениями двух численных переменных

Есть 3 очень простых способа поменять значения 2х числовых переменных без использования временной переменной

Может кому-нибудь пригодится

Релизациях на Java

1) Сумма-Разность

int a = 10;
int b = 20;

System.out.println("value of a and b before swapping, a: " + a +" b: " + b);

//swapping value of two numbers without using temp variable
= a+ b; //now a is 30 and b is 20
= a -b; //now a is 30 but b is 10 (original value of a)
= a -b; //now a is 20 and b is 10, numbers are swapped

System.out.println("value of a and b after swapping, a: " + a +" b: " + b);

Output:
value of a and b before swapping, a: 10 b: 20
value of a and b after swapping, a: 20 b: 10


четверг, 31 января 2013 г.

Perf4J is System.currentTimeMillis() as log4j is to System.out.println()

Perf4J is a set of utilities for calculating and displaying performance statistics for Java code.
Perf4J is to System.currentTimeMillis() as log4j is to System.out.println()
Similarly, when new Java developers discover that they need to time specified blocks of code for performance logging and monitoring reasons, they often do something like this:
long start = System.currentTimeMillis();
// execute the block of code to be timed
System.out.println("ms for block n was: " + (System.currentTimeMillis() - start));
Perf4J provides these features and more:
  • A simple stop watch mechanism for succinct timing statements.
  • A command line tool for parsing log files that generates aggregated statistics and performance graphs.
  • Easy integration with the most common logging frameworks and facades: log4j, java.util.logging, Apache Commons Logging and SLF4J (including logback).
  • Custom log4j and logback appenders to generate statistics and graphs in a running application.
  • The ability to expose performance statistics as JMX attributes, and to send notifications when statistics exceed specified thresholds.
  • A servlet for exposing performance graphs in a web application.
  • Profiled annotation and a set of custom aspects that allow unobstrusive timing statements when coupled with an AOP framework such as AspectJ or Spring AOP.
  • An extensible architecture.
Link

Некоторые примеры утечек памяти в Java

Чаще всего память утекает из-за:

  • Handle Leak
  • Class Loader Leak
  • Thread Leak
  • Unchecked arrays
  • Bugs in the code
  • Unchecked hash map growth
  • Programmers forgetting to close prepared statements, sockets or file handles

пятница, 9 ноября 2012 г.

Tips about writing micro benchmarks from the creators of Java HotSpot:


Rule 0: Read a reputable paper on JVMs and micro-benchmarking. A good one is Brian Goetz, 2005. Do not expect too much from micro-benchmarks; they measure only a limited range of JVM performance characteristics.
Rule 1: Always include a warmup phase which runs your test kernel all the way through, enough to trigger all initializations and compilations before timing phase(s). (Fewer iterations is OK on the warmup phase. The rule of thumb is several tens of thousands of inner loop iterations.)
Rule 2: Always run with -XX:+PrintCompilation-verbose:gc, etc., so you can verify that the compiler and other parts of the JVM are not doing unexpected work during your timing phase.

четверг, 18 октября 2012 г.

Inject SLF4J Logger by Annotation

Предлагается несложный способ заинжектить создание логгера с использованием Spring Framework.

Главной идеей является использование интерфейса BeanPostProcessors.
Класс инджектор будет получать SLF4J логгер и и присваивать его к полю класса. Чтобы определить в какому именно полю будет присвоен логгер. Создадим аннотацию Loggable.

вторник, 2 октября 2012 г.

Java program to determine Type of object at runtime


/**
 * Java program to determine type of Object at runtime in Java.
 * you can identify type of any object by three ways i..e by using instanceof,
 * getClass() and isInstance() method of java.lang.Class.
 * Java does have capability to find out type of object but its not called
 * as RTTI (Runtime type Identification) in C++.
 *
 * @author Javarevisited
 */

четверг, 6 сентября 2012 г.

Различие в методах yield(), sleep(0), wait(0,1) and parkNanos(1)

В описание к методам yield(), sleep(0), wait(0,1) and parkNanos(1) написано, что они делают одно и тоже.

На самом деле это не так. Существует различие во времени отработки этих функций для коротких промежутков времени.

Java memory leaks detector

Попробовал утилиту для выявления утечек памяти в java приложения. Называется Plumbr.Программка бесплатная, но если она найдет утечку, то отчет будет стоить денег.

Запустил на нашем Терминале ( http://www.1prime.ru/projects/primeterminal/ ), пока ничего не нашлось. "И это хорошо!".

P.S. Пока хз насколько эффективен этот детектор!

вторник, 10 апреля 2012 г.

Spring + X = CMS. Поиск X.

Из чего будем выбирать:

1) Magnolia - www.magnolia-cms.com

Отдельный модуль для интеграции со Spring

2) Riot - http://www.riotfamily.org/index.html
http://habrahabr.ru/post/100984/

3) Walrus - http://walrus.lt/

4) Hippo - http://www.onehippo.com/en/products/cms

5) Liferay Portal - http://www.liferay.com/products/liferay-portal/overview

6) Alfresco - http://www.alfresco.com/

7) DaisyCMS - http://daisycms.org/daisy/index.html

среда, 3 августа 2011 г.

Derby DB. Настройка соединения из Java

Derby DB представляет собой очень маленькую базу данных и размещается в файловой системе. Ее можно использовать для небольших проектов. БД очень проста в администрировании и настройке. Тем самым ее использование позволит разрабатывать быстрее несложные проекты.

В пакет JDK 1.6.0_26 не входить библиотеки для работы с Derby DB. Так что работы с БД нужно их скачать. Также Derby DB входить в среду NetBeans 7.0.
В данной статье будет рассмотрен случай работы с Derby DB, который входит в NetBeans 7.
На вкладке "Службы" в листе "Databases" уже есть настроенное соединение к базе "sample".

Раскрыв узел с соединения, можно увидеть список схем, таблиц и названия колонок. Также возможно выполнять sql-команды.
Для соединения к базе данных из java кода необходимо к существующему проекту добавить jdbc классы.

Далее создать Global library под названием "Derby" и "DerbyClient" и выбрать соответствующие jar файлы derby.jar и derbyclient.jar. Первая будет использоваться для соединения к БД напрямую, а вторая через сеть(даже если БД размещена на локальной машине). Jar файлы можно найти в папке 
C:\Program Files\glassfish-3.1\javadb\lib.
Теперь можно перейти к написанию кода. Собственно код для соединения к базе выглядит так:

package ru.mashintsev.db.derby;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

/**
 *
 * @author MIV
 */
public class TestDerby {

    public void connectAndSelect() {
        Connection connection = null;
        Statement statement = null;
        try {
            String driverDerby = "org.apache.derby.jdbc.ClientDriver";
            Class.forName(driverDerby).newInstance();
            Properties props = new Properties();
            props.setProperty("user", "app");
            props.setProperty("password", "app");
            connection = DriverManager.getConnection("jdbc:derby://localhost:1527/sample", props);
            statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery("select * from customer");
          
            while (resultSet.next()) {
                System.out.println(resultSet.getString("name"));
            }
        } catch (Exception e) {
            e.printStackTrace(System.out);
        } finally {
            try {
                if (statement != null) {
                    statement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (Exception e) {
                e.printStackTrace(System.out);
            }
        }
    }
}

Начинаю изучать книгу "Profesional Java. JDK6 Edition"

С первого взгляда книжка показалась достаточно интересной и полезной. Прочитав пару десятков страниц узнал много нового. Будем изучать дальше. В процессе чтения буду стараться писать код. Так сказать закреплять изученное. Может быть кому-нибудь пригодится)))