Thursday, September 25, 2014

Raspberry Pi from China

Bought a Raspberry Pi Model B+ recently from Chinese AliExpress.

Ordered here: http://www.aliexpress.com/item/3-IN-1-Rev-2-0-512-ARM-Raspberry-Pi-Project-Board-Model-B-3-heat/1629812034.html

It was equipped with transparent case and 3 heatsinks. The price was: 42$ and shipping was free

Genuine UK version arrived :)




I have only one complaint about a case: a hole for the microUSB power connector is too small - there is a weak connection with cable. But it works and everything else is fine!

Wednesday, September 17, 2014

JBoss 7 datasource + Hibernate + DB2

Hibernate 4
JBoss AS7
IBM DB2 v9.7

Had a problem to make hibernate work with DB2 through the JBoss datasource
org.hibernate.exception.SQLGrammarException
Caused by: com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-204, SQLSTATE=42704, SQLERRMC=DB2ADMIN.TABLE_NAME, DRIVER=3.65.77
JBoss prefixes table name with the DB2 username. But hibernate searches for the table name prefixed with the schema name:
MYSCHEMA.TABLE_NAME
The solution is to add a "currentSchema" parameter to the connection url of the database:
jdbc:db2://localhost:50000/MYSCHEMA:currentSchema=MYSCHEMA;
Another slution:
 in *.hbm.xml entity configuration files:
 <hibernate-mapping>
    <class name="packagename.classname" table="TABLE_NAME" schema="SCHEMANAME">
My working configuration:

hibernate.cfg.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
  "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
       <!-- Database connection settings -->
       <property name="hibernate.connection.datasource">java:jboss/datasources/MYSCHEMA</property>
       <property name="hibernate.current_session_context_class">thread</property>
       <property name="hibernate.dialect">org.hibernate.dialect.DB2Dialect</property>
       <mapping resource="Employee.hbm.xml"/>
       <mapping resource="Customer.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

standalone.xml:

...
<subsystem xmlns="urn:jboss:domain:datasources:1.0">
<datasources>
<datasource jta="true" jndi-name="java:jboss/datasources/MYSCHEMA" pool-name="MYSCHEMA" enabled="true">
 <connection-url>jdbc:db2://localhost:50000/MYSCHEMA:currentSchema=MYSCHEMA;</connection-url>
 <driver>db2</driver>
 <transaction-isolation>TRANSACTION_READ_COMMITTED</transaction-isolation>
 <url-delimiter>|</url-delimiter>
 <pool>
  <min-pool-size>0</min-pool-size>
  <max-pool-size>10</max-pool-size>
  <prefill>false</prefill>
  <use-strict-min>false</use-strict-min>
  <flush-strategy>FailingConnectionOnly</flush-strategy>
 </pool>
 <security>
  <user-name>***</user-name>
  <password>***</password>
 </security>
 <validation>
  <valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.db2.DB2ValidConnectionChecker"/>
  <validate-on-match>true</validate-on-match>
  <background-validation>false</background-validation>
  <background-validation-millis>1</background-validation-millis>
  <use-fast-fail>false</use-fast-fail>
  <stale-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.db2.DB2StaleConnectionChecker"/>
 </validation>
 <timeout>
  <blocking-timeout-millis>30000</blocking-timeout-millis>
  <idle-timeout-minutes>30</idle-timeout-minutes>
  <query-timeout>0</query-timeout>
  <use-try-lock>0</use-try-lock>
  <allocation-retry>0</allocation-retry>
  <allocation-retry-wait-millis>5000</allocation-retry-wait-millis>
 </timeout>
 <statement>
  <track-statements>false</track-statements>
  <prepared-statement-cache-size>0</prepared-statement-cache-size>
 </statement>
</datasource>
...

Friday, December 21, 2012

Hibernate 4 simple project example

Tools:
  • Eclipse Juno 4.2
  • Maven Integration for Eclipse plugin (m2e)
  • Hibernate 4.1.9.Final
  • MySQL 5.5

View and download source code:
https://bitbucket.org/kipchakbaev/hibernate4-example


1. In Eclipse create new Maven project. In Maven Archetype selection window choose maven-archetype-quickstart.
Enter archetype parameters. My parameters:
Group Id: kipchakbaev.hibernate
Artifact Id: hibernate4-example
package: kipchakbaev.hibernate

Click Finish.

2. Go to pom.xml and add dependencies:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>4.1.9.Final</version>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.22</version>
</dependency>

(it is possible to choose hibernate-entitymanager instead hibernate-core)

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>kipchakbaev.hibernate</groupId>
  <artifactId>hibernate4-example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>hibernate4-example</name>
  <url>http://maven.apache.org</url>

  <properties>
       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

   <dependencies>
        <dependency>
    <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
    <version>4.1.9.Final</version>
       </dependency>
       <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.22</version>
       </dependency>
   </dependencies>
</project>

3. In MySQL create schema hibernatedb. Create table customer:

DROP TABLE IF EXISTS customer;
CREATE TABLE customer(
  id INT NOT NULL AUTO_INCREMENT,
  first_name VARCHAR(20) NOT NULL,
  last_name VARCHAR(30) NOT NULL,
  PRIMARY KEY (id)
)

4. In eclipse create folder src/main/resources/:
In your project choose folder src/main/ - right click - new - folder. Folder name: resources.
Right click on resources/ - Build Path - Use as source folder.

5. In src/main/resources/ create folder structure /kipchakbaev/hibernate/common/
In common/ folder create file customer.hbm.xml:


<?xml version='1.0'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="kipchakbaev.hibernate.common.Customer" table="customer" catalog="hibernatedb">
        <id name="id" type="java.lang.Integer">
            <column name="ID" />
            <generator class="identity" />
        </id>
        <property name="firstName" type="string">
            <column name="FIRST_NAME" length="20" not-null="true" />
        </property>
        <property name="lastName" type="string">
            <column name="LAST_NAME" length="30" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

6. Create kipchakbaev.hibernate.common package and put Customer.java in it:

package kipchakbaev.hibernate.common;

public class Customer {

private Integer id;
private String firstName;
private String lastName;

public Customer() {
}

public Customer(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}
}

7. In src/main/resources/ create file hibernate.cfg.xml, replace MySQL username and password to yours:


<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatedb</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <mapping resource="kipchakbaev/hibernate/common/customer.hbm.xml"></mapping>
    </session-factory>
</hibernate-configuration>


8. Create kipchakbaev.hibernate.persistence package and put HibernateUtil.java in it:


package kipchakbaev.hibernate.persistence;

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {
   
    private static SessionFactory sessionFactory;
    private static ServiceRegistry serviceRegistry;

    static
    {
        try
        {
            Configuration configuration = new Configuration().configure();
            serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        }
        catch (HibernateException he)
        {
            System.err.println("Error creating Session: " + he);
            throw new ExceptionInInitializerError(he);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
    // Close caches and connection pools
    getSessionFactory().close();
    }
}


9. Change App.java in package kipchakbaev.hibernate, generated by Maven:

package kipchakbaev.hibernate;

import kipchakbaev.hibernate.common.Customer;
import kipchakbaev.hibernate.persistence.HibernateUtil;
import org.hibernate.Session;

/**
 * Hello hibernate 4!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        System.out.println("Hibernate 4 example");
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Customer customer = new Customer();
        customer.setFirstName("John");
        customer.setLastName("Doe");
        session.save(customer);
        session.getTransaction().commit();
    }
}

Review project structure:






























Run App.java! If successful, you can see last line in eclipse console:

Hibernate: insert into hibernatedb.customer (FIRST_NAME, LAST_NAME) values (?, ?)

View and download source code:
https://bitbucket.org/kipchakbaev/hibernate4-example


Sunday, November 4, 2012

Eclipse Maven Integration plugin behind proxy

I use Eclipse Juno at work behind proxy. When I try to create maven project with m2e plugin I get an error "Could not resolve archetype org.apache.maven.archetypes:maven-archetype-quickstart:RELEASE from any of the configured repositories." The reason is that no proxy settings in maven settings.xml file (even if the proxy settings exists in the Eclipse preferences).

Go to Window - Preferences - Maven - User Settings - Browse. If settings.xml file does not exist, create it with proxy parameters:

<proxies>
    <proxy>
        <id>myId</id>
        <active>true</active>
        <protocol>http</protocol>
        <username>MyUser</username>
        <password>MyPassword</password>
        <host>my.proxy.host</host>
        <port>myproxyport</port>
        <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
</proxies>

Thursday, October 25, 2012

Add derby.jar to Eclipse project

If you are using Apache Derby database with Eclipse project, you need to define path to derby.jar file:

Project - Properties - Java Build Path - Add Eternal JARs

Before I done this, I have been tried to add path to derby.jar in Run Configurations... - Classpath - User Entries, but this is incorrect and I get error: "The archive ... which is referenced by the classpath, does not exist"

Tuesday, October 16, 2012

GitHub


Сегодня начал осваивать Git.

На работе стоит linux и прокси. Столкнулся с проблемой записи обновлений репозитория на сервер:
$ git push origin master
fatal: remote error: You can't push to git ...

Попробовал решение с ssh: создал ключ в ~/.ssh как описано в этом мануале: 
Добавил ключ в account settings на github.com;
Изменил адрес для origin:

$ git remote set-url origin ssh://git@github.com/username/repo_name.git

где username - логин на GitHub, repo_name - имя репозитория

Пробую:
$ git push origin master
ssh: connect to host github.com port 22: Connection refused
fatal: The remote end hung up unexpectedly 

Проверяю доступ по ssh:
$ ssh -T git@github.com
не работает.

Попробовал изменить порт, как сказано здесь: 
Получил:
$ ssh -T git@github.com
ssh: connect to host ssh.github.com port 443: Connection refused

Проверка:
$ ssh -T -p 443 git@ssh.github.com
ssh: connect to host ssh.github.com port 443: Connection refused

Не работает.

Решил дальше сражаться с https-адресом, раз уж с ssh глухо.
Меняю адрес для origin:

git remote set-url https://github.com/username/repo_name.git

Пробую:

$ git push origin master
error: The requested URL returned error: 403 while accessing https://github.com/username/repo_name.git/info/refs

"Для входа по https необходимо определить ваше имя пользователя для git remote:

$ git remote set-url origin https://username@github.com/user/repo.git

где username - ваше имя пользователя на GitHub, остальную часть ссылки исправлять не надо!

Теперь при попытке $ git push будет запрашиваться пароль от аккаунта на GitHub

Пробую:

$ git push origin master
Password: 
Counting objects: 15, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (14/14), done.
Writing objects: 100% (14/14), 3.23 KiB, done.

Ура! Всё получилось!

Tuesday, March 6, 2012

Save schematic to postscript file

To save schematic to postscript do:
1. File - Print... - Plot Options.
Display type: colorplot
Plotter name: EPS
Orientation: automatic
Check boxes Center Plot  and Fit to Page;
Check box Send Plot Only to File and write path and file name.
Press Ok.
2. In the window Submit Plot press Apply.


Now you have a postscript file with your schematic with plotted properties of the each element