Monday, February 13, 2017

Creating a Test Template in IntelliJ Idea


Here is a quick guide for a test template in intellij. Almost all of the time i am using maven for the java projects i work on and junit and assertj is my primary testing tools. Every time i create test classes i am typing the static includes and a test method annotated with test. Although it's not that much boiler plate this can be prevented thanks to intellij file templates.

We want a test class to be generated automatically for that we are going to create a file template with name "JavaTest" (you can pick any name you want). Here is a quick step by step guide for that:

1. Create a file that contains the things that you want to be part of the template as a java file. (For this case i want junit and assertj static imports to be present along with junit import and a test method annotated with @Test)



2. Select Tools -> Save File As Template from the top menu. This will bring up the Save File As Template Dialog. Give the name "JavaTest" and save the template. (you can change the template as you please)



3.  Right Click to the package you want to create a unit test. From the New menu find the name "JavaTest" and create the file... Voila there you have your tiny little cute test file ready to use :)

As a long term Netbeans user, i find intelliJ easier and faster to use but still from the bottom of my heart i am waiting for Netbeans to make a come back ...





Thursday, November 3, 2016

Maven Snippets

I find maven documentation cryptic to read and hard to understand, even after years of development this aspect of Maven still remains same to me, most of the time i copy snippets from older projects to get things done, Below you can find some common snippets you might need to use time to time in your projects.


1. Deploying Arbitrary Artifact to Nexus

You need to have configured username and password of your nexus server in your settings.xml file for this snippet to work, it uploads the zip artifact to nexus repository.

settings.xml (located in .m2 directory)

<servers>
    <server>
       <id>nexus</id>
       <username>username</username>
       <password>pass</password>
    </server>

  </servers>

Pom.xml

<!-- Deploy File -->
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-deploy-plugin</artifactId>
    <version>2.8.2</version>
    <executions>
        <execution>
            <phase>package</phase>
            <configuration>
                <artifactId>${project.artifactId}</artifactId>
                <groupId>${project.groupId}</groupId>
                <version>${project.version}</version>
                <packaging>zip</packaging>
                <file>target/application-1.0-SNAPSHOT.zip</file>
                <repositoryId>nexus</repositoryId>
                <url>http://xxx.yyy.zz.tt:8081/nexus/content/repositories/snapshots/</url>
            </configuration>
            <goals>
                <goal>deploy-file</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Sunday, November 1, 2015

Configuring CouchDB uuid generation algorithm

CouchDB can generate _id field of documents for you when you store the documents using POST instead of PUT. The algorithm used by CouchDB to generate the _id fields can be changed although the options are small. We can pick below algorithms for couch db to use to generate the _id fields of our documents: (http://wiki.apache.org/couchdb/HttpGetUuids)


  1. sequential: 26 hex character random prefix, followed by 6 hex characters of sequence, which is incremented by random amounts. When the 6 character sequence overflows, a new random prefix is chosen. There are no guarantees of ordering, but most inserted documents will be sequentially ordered. This improves insert speed as most B-tree edits do not happen randomly. Also, if the documents are likely to be accessed sequentially, this improves access speeds.
  2. random: 32 hex characters generated completely at random.
  3. utc_random: First 14 hex characters are microseconds since Jan 1, 1970 (Unix epoch), followed by 18 random hex characters.
To Update the setting ew can use REST api of the couchDB, 

[rozaydin@RO ~]$ curl -X PUT http://localhost:5984/_config/uuids/algorithm -d '"sequential"'
"sequential"
[rozaydin@RO ~]$

As you can see CouchDB responds with the old algorithm it was using to generate the _id fields prior the update. The same configuration should be able to be done using local.ini file however i failed to find the proper name for the setting if you know how please leave a comment :)

Monday, September 7, 2015

Configuring Jetty Server With Security Certificates

  • Download Jetty 9.3.2 version from http://download.eclipse.org/jetty/ and unzip to a directory (This directory will be called Jetty Home)
  • go into Jetty Home directory and create a new directory inside this directory with name SECURE_BASE (This directory will be called Jetty Base)
  • go into Jetty Base directory and create a new file with name start.ini
  • open start.ini with a text editor and edit it to include below lines
# Initialize module server
--module=server
threads.min=10
threads.max=200
threads.timeout=60000
jetty.dump.start=false
jetty.sump.stop=false
--module=deploy
--module=jsp
--module=ext
--module=resources
--module=client
--module=annotations
--module=http
--module=ssl
--module=https
save and exit.
  • Execute below command in Jetty Base directory
java -jar ../start.jar
then terminate the process via issuing kill -9 pid command
  • create a new directory in Jetty Base directory with name etc.
In the end you should have following directory structure in your Jetty Base directory. (secure-base is Jetty Base in below example)
[rozaydin@RO secure-base]$ pwd
/home/rozaydin/WDH/jetty-9.3.2/secure-base
[rozaydin@RO secure-base]$ ls
etc lib resources start.ini webapps
[rozaydin@RO secure-base]$

2 Create SSL Certificate

Create an SSL certificate by issuing below command please ensure you note the password, this file will be used at https negotiation with the client.
$ keytool -keystore keystore -alias keystore -genkey -keyalg RSA -sigalg SHA256withRSA
 Enter keystore password:  password
 What is your first and last name?
   [Unknown]:  Test Test
 What is the name of your organizational unit?
   [Unknown]:  Software Development
 What is the name of your organization?
   [Unknown]:  Test Test
 What is the name of your City or Locality?
   [Unknown]: Istanbul
 What is the name of your State or Province?
   [Unknown]: Istanbul
 What is the two-letter country code for this unit?
   [Unknown]: TR
 Is CN=
Test Test, OU=Software Development, O=Test Test,
 L=Istanbul, ST=Istanbul, C=TR correct?
   [no]:  yes

 Enter key password for <keystore>
         (RETURN if same as keystore password):
 $

After the execution you should have a file with name keystore at the directory you have issued the command.

2 Configure HTTPS on Jetty

  1. Copy the SSL certificate file (keystore file) you have created in previous step to Jetty Base/etc directory

  2. Https configuration is determined by 4 configuration files located under Jetty Home/etc directory these files are
  • jetty.xml
  • jetty-https.xml
  • jetty-ssl.xml
  • jetty-ssl-context.xml
Open the jetty-ssl-context.xml file and modify below lines accordingly

jetty-ssl-context.xml

<?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure_9_3.dtd">
<!-- ============================================================= -->
<!-- SSL ContextFactory configuration -->
<!-- ============================================================= -->
<Configure id="sslContextFactory" class="org.eclipse.jetty.util.ssl.SslContextFactory">
<Set name="KeyStorePath"><Property name="jetty.base" default="." />/<Property name="jetty.sslContext.keyStorePath" deprecated="jetty.keystore" default="etc/keystore"/></Set>
<Set name="KeyStorePassword"><Property name="jetty.sslContext.keyStorePassword" deprecated="jetty.keystore.password" default="test"/></Set>
<Set name="KeyStoreType"><Property name="jetty.sslContext.keyStoreType" default="JKS"/></Set>
<Set name="KeyStoreProvider"><Property name="jetty.sslContext.keyStoreProvider"/></Set>
<Set name="KeyManagerPassword"><Property name="jetty.sslContext.keyManagerPassword" deprecated="jetty.keymanager.password" default="test"/></Set>
<Set name="TrustStorePath"><Property name="jetty.base" default="." />/<Property name="jetty.sslContext.trustStorePath" deprecated="jetty.truststore" default="etc/keystore"/></Set>
<Set name="TrustStorePassword"><Property name="jetty.sslContext.trustStorePassword" deprecated="jetty.truststore.password" default="test"/></Set>
<Set name="TrustStoreType"><Property name="jetty.sslContext.trustStoreType" default="JKS"/></Set>
<Set name="TrustStoreProvider"><Property name="jetty.sslContext.trustStoreProvider"/></Set>
<Set name="EndpointIdentificationAlgorithm"></Set>
<Set name="NeedClientAuth"><Property name="jetty.sslContext.needClientAuth" deprecated="jetty.ssl.needClientAuth" default="false"/></Set>
<Set name="WantClientAuth"><Property name="jetty.sslContext.wantClientAuth" deprecated="jetty.ssl.wantClientAuth" default="false"/></Set>
<Set name="ExcludeCipherSuites">
<Array type="String">
<Item>SSL_RSA_WITH_DES_CBC_SHA</Item>
<Item>SSL_DHE_RSA_WITH_DES_CBC_SHA</Item>
<Item>SSL_DHE_DSS_WITH_DES_CBC_SHA</Item>
<Item>SSL_RSA_EXPORT_WITH_RC4_40_MD5</Item>
<Item>SSL_RSA_EXPORT_WITH_DES40_CBC_SHA</Item>
<Item>SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA</Item>
<Item>SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA</Item>
</Array>
</Set>
<Set name="useCipherSuitesOrder"><Property name="jetty.sslContext.useCipherSuitesOrder" default="true"/></Set>
</Configure>

Here we are setting the password by changing 3 properties listed below, password must be the same as the password that is set to the Certificate file.
<Set name="KeyStorePassword"><Property name="jetty.sslContext.keyStorePassword" deprecated="jetty.keystore.password" default="test"/></Set>
<Set name="KeyManagerPassword"><Property name="jetty.sslContext.keyManagerPassword" deprecated="jetty.keymanager.password" default="test"/></Set>
<Set name="TrustStorePassword"><Property name="jetty.sslContext.trustStorePassword" deprecated="jetty.truststore.password" default="test"/></Set>

4 Run Jetty Server 

After following previous configuration steps, start jetty server by going into Jetty Base directory and issuing command
java -jar ../start.jar
you can access the server using https protocol by using default url https://localhost:8443

Friday, June 12, 2015

Working offline with Maven

While working with projects managed by maven you could run into issues where you have to disconnect your development environment from the internet and continue to work on the code. The experience i had was i had to debug a system deployed to a customer network which had no internet access. I suddenly realized my development environment on my laptop was completely useless. Pretty bad when there are people standing behind you and waiting for you to resolve their problem.

The solution is downloading the maven dependencies to your local by executing below command from the same directory where your pom file is located.

[rozaydin@RO]$ mvn dependency:go-offline

Maven will download all dependencies your project needs and you could be able to continue working with no need to internet access.

Saturday, June 6, 2015

Ucuz Elektrik


Türkiye'de elektrik tarifeleri 3 zamanlı olarak ücretlendirilmekteler. Bu zaman (tarife) dilimleri aşağıda listelenmiştir.

Gündüz (T1)      : 06:00 – 17:00
Puant (T2)          : 17:00 – 22:00
Gece (T3)           : 22:00 – 06:00

En ucuz elektrik 22.00 - 06.00 arasında satılırken en pahalı elektril 17.00 - 22.00 saatleri arasında satılmakta. Hali hazırda geçerli olan ücret tarifelerine göre "Mesken" tipi abonelerin tarifeleri aşağıda listelenmiştir. 


Mesken:

Gündüz: 19,7183
Puant:     35,8753 
Gece:      8,0527 

Görüldüğü gibi en ucuz zaman dilimi GECE tarifesi olmaktadır. Eğer enerji tüketimimizin tamamını gece tarifesi üzerinden yaparsak harcadığımız aynı enerji miktarı için 3 kat daha az ödüyoruz. Basit bir örnek verir ise ortalama enerji faturamız aylık 60 lira ise ödeyeceğimiz rakam 20 liraya düşüyor. 1 sene içerisinde yapacağımız tasarruf miktarı 40 x 12 = 480 lira. Az bir rakam değil. 

Peki enerji tüketimimizin tamamını GECE tarifesi üzerinden yapmak mümkün mü ? Eğer enerjiyi depolayabilir isek evet mümkün. Büyükçe şarj edilebilir bir pilimiz olduğunu düşünün, Tarifenin en ucuz olduğu zaman diliminde kendi kendisini otomatik şarj ediyor ve diğer zaman dilimlerinde ise bu pildeki enerjiyi evimizde kullanıyoruz harcadığımız elektrik miktarını kısmadan ciddi miktarda tasarruf sağladık.

İşte bu şekilde şarj edilebilir bir pil artık var. Elektrikli araçları ile ünlü Amerikan "Tesla" şirketi Power Wall adlı ürün ile karşımızda. Power Wall evinizin duvarına monte ettirebileceğiniz oldukça şık bir ürün. Ancak ürünün fiyatı biraz yüksek 3000$ ve 3500$ fiyat etiketine sahip ki Türkiye standartları için bu ciddi bir rakam. Ancak bu ürünlerin muadilleri daha uygun fiyat etiketi ile çok kısa sürede pazara sürülecektir. Bu durumda daha satın alınabilir bir etiket ile elektrik faturalarımızı ciddi miktarda düşürebilir olacağız.

Monday, May 11, 2015

Latitude Longitude Boundaries on World Map


You might have encountered situations where you wanted to get the latitude and longitude boundaries of an rectangular area on world map, I have put together a simple js application using leaflet js and leaflet.draw plugin to provide the functionality.

  1. You can access the hosted application from here
  2. You can access the sources from here
Enjoy and please comment if you encounter any issues.


Figure 1 - Boundary Application