Android Debug Keystore

by GarciaPL on Tuesday 23 December 2014

For some of you I have this very useful command line for getting Android Debug Key which can be used for signing Android applications.

keytool -keystore /home/lukasz/.android/debug.keystore -v -list -alias androiddebugkey -storepass android -keypass android

After executing this command you will some something like that :


Alias name: androiddebugkey
Creation date: 2014-12-18
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=Android Debug, O=Android, C=US
Issuer: CN=Android Debug, O=Android, C=US
Serial number: 32435620
Valid from: Thu Dec 18 21:04:11 CET 2014 until: Sat Dec 10 21:04:11 CET 2044
Certificate fingerprints:
  MD5:  XXX
  SHA1: XXX
  SHA256: XXX
  Signature algorithm name: SHA256withRSA
  Version: 3

Extensions: 

#1: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: 20 B4 60 1E 46 B5 AD B0   45 49 93 48 C2 D6 0C BF   .`.F...EI.H....
0010: 9C CD 8D 02                                        ....
]
]
Information under SHA1 can be used to signing Android apps. More information about signing Android apps you can find under this link Developer.android.com - App Signing.

ADB Not Responding in Intellij IDEA

by GarciaPL on Sunday 21 December 2014

When you get this message - "ADB not responding. You can wait more or kill adb ..." just use this command :

fuser 5037/tcp

and after executing that command you will receive some PID (if your adb is still running) :

sudo kill -9 PID

BIHAPI Competition

by GarciaPL on Saturday 6 December 2014

Recently in October, Orange with local authorities of towns such as Warsaw, Gdansk and Poznan, start new competition called BIHAPI (Business Intelligence Hackathon API) [1] which aims to stimulate creation of innovative applications, system and services built using API (Application Developer Interfaces). For every participant there is available about 81 API (including data cites of Warsaw, Gdansk, Poznan and Orange Telco API). More information about competition you can find under website [1].

Reference :
[1] BIHAPI

Spring Remoting - RmiServiceExporter

by GarciaPL on Saturday 22 November 2014

I would like to present you very quick cheat sheet about how implement RMI (Remote Method Invocation) [3] which performs the object-oriented equivalent of RPC in Spring using RmiServiceExporter [1] (used to expose RMI interface) and RmiProxyFactoryBean [2] (used to consume RMI interface).

First of all, you must create some interface which will be used to expose your methods [4]

public interface IUser {
        UserDTO retrieveUserById(Long userId);
        UserDTO register(UserDTO user) throws RegisterException;
}

Next provide some implementation for interface IUser in the form of class [5]

public class UserManager implements IUser {
    private IUserDao userDao;
 
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public UserDTO retrieveUserById(Long userId) {
        return userDao.retrieveUserById(userId);
    }
 
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class)
    public UserDTO register(final UserDTO user) throws AVValidationException {
 
        if (user == null) {
            throw new IllegalArgumentException("Wrong params. user cannot be NULL");
        }
 
        return userDao.register(user);
    }
 
    public IUserDao getUserDao() {
        return userDao;
    }
 
    public void setUserDao(final IUserDao userDao) {
        this.userDao = userDao;
    }
}
And of course you must provide XML Bean definition [6].
Next in your XML with Beans you should export RMI using RmiServiceExporter [7].
Now you can use this RMI exposed under service name called JSUserManager after providing definition in XML Bean [8].
Please do not forget about initialization your RMI like below [9].
    private void run() {
        logger.info("creating ctx...");
        final AbstractApplicationContext ctx;
        try {
            ctx = new ClassPathXmlApplicationContext(
                    "/garciapl-service-rmi-ctx.xml"
            );
            logger.info("ctx created; registering shutdown hook");
            ctx.registerShutdownHook();
 
            logger.info("Starting up the application.  Stand by... ;)");
 
            logger.info("Creating MP service...");
            ctx.getBean("userManagerRMI");
 
        } catch (Throwable e) {
            logger.fatal("exception caught during initialization: ", e);
            System.exit(-1);
        }
        logger.info("app is up and running");
 
        synchronized (this) {
            try {
                wait();
            } catch (InterruptedException e) {
                logger.error("wait interrupted", e);
            }
        }
        logger.info("Exiting...");
        System.exit(0);
    }

Reference : [1] Spring Docs - RmiServiceExporter [2] Spring Docs - RmiProxyFactoryBean [3] Oracle Docs - RMI [4] Pastebin - RMI Interface [5] Pastebin - Interface implementation [6] Pastebin - Interface implementation XML Bean [7] Pastebin - RmiServiceExporter [8] Pastebin - RmiProxyFactoryBean [9] Pastebin - Register RMI

SQL Developer Freezes on Ubuntu

by GarciaPL on Wednesday 12 November 2014

Some of you have faced the problem when SQL Developer on Ubuntu which just freeze after some idle time. More information about this issue and solution can be found under [1]. I must to admit that this solution is quite complex, so I decided to prepare some very simple tool called SQLDeveloper Killer. Below I paste some source code in Java which aims to list all processes which are alive in system and find particular process which corresponds to SQL Developer process (contains "sqldeveloper.conf" in CMD description).

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package killsqldeveloper;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 *
 * @author lciesluk
 */
public class KillSQLDeveloper {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            Process exec = Runtime.getRuntime().exec(new String[]{"ps", "-ef"});
            exec.waitFor();

            BufferedReader reader
                    = new BufferedReader(new InputStreamReader(exec.getInputStream()));

            String line = "";
            while ((line = reader.readLine()) != null) {
                if (line.contains("sqldeveloper.conf")) {
                    System.out.println(line);
                    String[] split = line.split(" ");
                    if (split.length > 2) {
                        System.out.println(split[1]);
                        if (!split[1].equals("")) {
                            Process execKill = Runtime.getRuntime().exec(new String[]{"kill", "-9", split[1]});
                            execKill.waitFor();
                        } else {
                            Process execKill = Runtime.getRuntime().exec(new String[]{"kill", "-9", split[2]});
                            execKill.waitFor();
                        }
                    }
                    break;
                }
            }

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}


After you paste this code to your IDE, you can install very useful tool called alacarte to create Unity launcher on Ubuntu.

SQL Developer Killer


Reference : [1] Alexeymoseyev.wordpress.com - Oracle SQL Developer hangs on Linux [2] Pastebin.com - Source Code [3] Alacarte - Ubuntu menu editor

Google Custom Search in Java

by GarciaPL on Saturday 18 October 2014

When I am starting to search something using of course Google, from my point of view it is quite annoying that when you would like to exclude some search results in search bar, in way as you can see below, you can only exclude probably about 20 sites.


So, to get the most hidden results from Google, I decided to create small tool which uses Google Custom Search API.
Before you can start your journey with this very interesting API you should (see [2] in Reference) :
1) Create search engine and get it's ID 2) Generate API key for Custom Search API
After you successfully received all the necessary data from above steps, you can simply download small Java program developed by me ([3]), which can be used by you to go deeper and deeper with your searching of web!

public class WarsawDeveloperJava {
    public static void main(String[] args) throws Exception {
 
        String searchText = "Warsaw java developer";
        String key = "CUSTOM_SEARCH_API_KEY";
        String cx = "SEARCH_ENGINE_ID";
 
        JsonFactory jsonFactory = new JacksonFactory();
        HttpRequestInitializer httpRequestInitializer = new HttpRequestInitializer() {
 
            @Override
            public void initialize(HttpRequest request) throws IOException {
 
            }
        };
        Customsearch customsearch = new Customsearch(new NetHttpTransport(), jsonFactory, httpRequestInitializer);
        Customsearch.Cse.List list = customsearch.cse().list(searchText);
        list.setCx(cx);
        list.setCr("countryPL"); //country origin of search result
        list.setDateRestrict("m2"); //results should be no older than 2 months
        list.setKey(key);
 
        Search results = list.execute();
        List listResult = (List) results.getItems();
 
        Iterator iterator = listResult.iterator();
        while(iterator.hasNext()) {
            Result next = (Result)iterator.next();
            System.out.println(next.getLink());
        }
    }
}

Reference :
[1] Developers.google.com - Custom Search API
[2] Weblog4j.com - Having Fun with Google Custom Search API and Java
[3] Pastebin.com Source Code

Brother DCP-J152W setup scanner

by GarciaPL on Sunday 14 September 2014

Printing some docs on Ubuntu using one of the printer delivered by Brother is quite easy. You just need to install appropriate packages (deb or rpm) and after that you can easily setup your Brother printer (in my case Brother DCP-J152W) connected via USB or WiFi due to future prints.

Linux user may deal with some problem when there is a need to use scanner built-in Brother device. Fortunately there is a solution of this problem. In this case Brother printer is connected to router byWiFi :

  1. Download and install those packages : brscan4brscan-skey and brother-udev-rule.
  2. Check if you Brother model is available to configure - run command in terminal - brsaneconfig4 -q
  3. If you Brother model is on the list after perform previous step, then you can configure it - brsaneconfig4 -a name=DCPJ152W model=DCP-J152W ip=192.168.1.102
  4. Test if your Brother printer is available through the network - brsaneconfig4 -p. If your device is responding, you can go to the next step.
  5. Finally use tools like XSane or VueScan to scan your docs using Brother scanner.

Reference : [1] Support.brother.com - DCP-J152W Downloads [2] Support.brother.com - Scanner driver install for network [3] Unix.stackexchange.com - Brother DCP-J315W is active in terminal but not detected in Elementary OS [4] Secure.kitserve.org.uk - Ubuntu Brother Printer-Scanner Network Setup

Send email using Gmail account

by GarciaPL on Wednesday 10 September 2014

I would like to share with you a small snippet which will allow you to send email using Gmail account. In this case I will use JavaMail (javax.mail) interface for sending email messages. More information about JavaMail API reference you can find below.

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

private void sendEmail() {

        String sender = "sender@gmail.com";
        String receiver = "receiver@gmail.com";
        String title = "YOUR_TITLE_TEXT";
        String body = "YOUR_BODY_TEXT";

        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "25");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.EnableSSL.enable", "true");
        props.put("mail.smtp.auth", "true");
        props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.port", "465");
        props.setProperty("mail.smtp.socketFactory.port", "465");

        Authenticator authenticator = new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("login@gmail.com", "password");
            }
        };

        Session session = Session.getDefaultInstance(props, authenticator);

        try {
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(sender));
            msg.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(receiver, receiver));
            msg.setSubject(title);
            msg.setText(body);
            Transport.send(msg);
        } catch (MessagingException e) {
            System.out.println("sendEmail (MessagingException) : " + e.getMessage());
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            System.out.println("sendEmail (UnsupportedEncodingException) : " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("sendEmail (Exception) : " + e.getMessage());
            e.printStackTrace();
        }
}
If you are using Gmail account to send emails, properties related with smtp configuration in this snippet will remain, but you should change variables like sender, receiver, title and body to your needs. You should also change login and password in below line which will be used to authenticate with gmail account :


return new PasswordAuthentication("login@gmail.com", "password");
Reference : [1] Oracle®'s JavaMail API reference [2] Pastebin Source

SQL Developer

by GarciaPL on Thursday 31 July 2014

If you have difficulties with running SQL Developer (in my case 4.0.2.15.21) from Oracle in console on Linux you can see such stack trace :

# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x00007feb22ed8be0, pid=32116, tid=140649711318784
#
# JRE version: Java(TM) SE Runtime Environment (7.0_65-b17) (build 1.7.0_65-b17)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (24.65-b04 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# C  0x00007feb22ed8be0
#
# Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
#
# An error report file with more information is saved as:
# /home/lukasz/sqldeveloper/sqldeveloper/bin/hs_err_pid32116.log
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.sun.com/bugreport/crash.jsp
#
/home/lukasz/sqldeveloper/sqldeveloper/bin/../../ide/bin/launcher.sh: line 1193: 32116 Przerwane               (core dumped) ${JAVA} "${APP_VM_OPTS[@]}" ${APP_ENV_VARS} -classpath ${APP_CLASSPATH} ${APP_MAIN_CLASS} "${APP_APP_OPTS[@]}"

So, fix of this problem is quite easy - go to file sqldeveloper.sh which is located in folder of your SQL Developer and add at the beginning of this file the following line :
unset GNOME_DESKTOP_SESSION_ID

SQLDeveloper.sh
SQLDeveloper.sh


Oracle DB 11g Errors Guide

by GarciaPL on Tuesday 15 July 2014

I would like only to announce that I have created a small application in Android called Oracle DB 11g Errors Guide. This application helps you as a developer or administrator of Oracle ® Database 11g Release 1 find solutions of problems which you are faced with during your work. Each error message contains the message statement, an explanation of the probable causes and a recommended action.

More information about Oracle ® Database 11g Release 1 Error Messages you can find under hyperlink - Oracle® Database Error Messages 11g Release 1 (11.1) Documentation

Hyperlink to Google Play Store - Google Play Store GarciaPL

Eclipse menu bug in Ubuntu

by GarciaPL on Saturday 28 June 2014

Recently I had to deal with an error during using Eclipse on my Ubuntu 13.10. When I clicked in Eclipse on any menu item there was nothing showed up. As far as I know this error is related with Unity graphical shell created for GNOME. One of the fix which I found is to run Eclipse with some extra additional parameters. I also created some shell script which will help to enjoy again a menu features in Eclipse.


#!/bin/bash
#
# Run Eclipse due to menu bug
#
eclipsepath="/home/user/Desktop/eclipse/eclipse"
Exec=env UBUNTU_MENUPROXY=0 $eclipsepath

Of course in this script you must edit eclipsepath variable value to path which really guides to eclipse. You can run script in terminal using ./eclipse.sh, but before doing that you must give executable permission to script using this command chmod +x eclipse.sh.
Reference : [1] askubuntu.com Eclipse menus are cut off or dont show [2] stackoverflow.com Eclipse menus dont show up after upgrading to ubuntu 13.10 [3] Pastebin.com Source Code

FFmpeg Picture in Picture

by GarciaPL on Thursday 29 May 2014

In this post you can find a small piece of code which should allows you to make picture in picture using ffmpeg. More information about this effect you can find in reference section of this post.

ffmpeg -i \tmp\stream1.mp4 -r 29.97 -vf "movie=\tmp\stream2.mp4, scale=212:120 [vid2]; [in][vid2] overlay=main_w-overlay_w-10:10 [out]" \tmp\output.mp4 &

I used ampersand at the end of this command because I would like to create a new process of merging those two input videos files in background. I also uploaded below some example how it should looks like in final. I pointed using red circle the video which was added using stream2.mp4 source. Do not hesitate to modify this command above. I'm sure that you will adapt it for your own purposes.

Picture in Picture using FFmpeg

Reference : [1] Picture-in-picture Wikipedia

Jitsi Create new contact

by GarciaPL on Wednesday 21 May 2014

A few days ago I had a problem to adding new contact using Java of course to Jitsi SIP client. So, I would like to share with you with this small piece of code :

UtilActivator.getContactListService().createMetaContact(ProtocolProviderService,
MetaContactGroup, UserID);

I figured out that adding contact can be executed only when your SIP account is Online (connected to server for instance FreeSWITCH). Thank you very much for your attention ;)

Reference: [1] Jitsi.org [2] jitsi-dev - Create new contact

Facebook Profiles Manager

by GarciaPL on Saturday 17 May 2014

I would like to present you some showcase of using PHP SDK to integrate with Facebook which was developed by Naitik Shah one of the Facebook employee. Appropriate reference to this very powerful SDK you can find in reference below.

So, I have created some small showcase which aims to show how to retrieve Facebook profile (not person, but some organisation or business) and print entries which was published on it's wall. Every entry is described by Name, Image (if was uploaded), Creation time, Title and Description as on screenshot below.

FB Profile list of entries

As you can see you can also set post range for FB Profile which posts are listed. Default FB Profile is set as 'Google'.

The project has been removed from github.

There is a also one additionally page which allows user to add and remove FB profiles. Once you are going to add new FB profile you should provide FB Profile name which should strictly defined it and FB Url name. You can get more information how to obtain this Url name through hovering the mouse over the words "(Show hint)". All FB profiles are stored in SQLite database. More information about it's structure you can find in fb_db.sql file.

FB Profile Manager

Reference: [1] PHP SDK for Facebook [2] CSS Globe - Easiest Tooltip and Image Preview Using jQuery

Kill FFmpeg process smoothly

by GarciaPL on Thursday 3 April 2014

Let's assume that you use FFmpeg distribution in your application. One of your function is for instance saving some HLS stream (HTTP Live Streaming) into file. I suppose you are using python subprocess module to create process in Linux OS to obtain this stream to your hard disk.

In normal way if you would like to stop saving this content using FFmpeg on your storage, you will just press 'q' button while you are in terminal. Due to this FFmpeg will be able to finish saving content and do not damage the file at the end.

There is some kind of problem if you would like to kill this FFmpeg process in smooth way without damaging the file while you do not have access to the terminal.

You can use below solution written in Python to kill this FFmpeg process from your application. Only input which you need to ensure is PID (Process IDentifier) which describes your  process. You can use below shell code in Linux :

ps -ef | grep ffmpeg | awk '{print $2}'

Once you know PID of your FFmpeg process just use this Python code :
import psutil
import os
import signal

pids = psutil.get_pid_list()

for pid in pids:
      if (pid == <your_PID>):
            os.kill(pid,signal.SIGINT)
One thing is worthy of attention. You suppose to use mainly signal.SIGINT while you invoke os.kill function, because of it simulates in FFmpeg case the user interrupt of this process (typically initiated by pressing Control-C) which allow to FFmpeg to end his work properly.

Reference : [1] Python.org Subprocess Docs [2] Thelightfromtheblackhole.blogspot.com Sending sighup signal to some external [3] Unix signal - SIGINT


FFmpeg parse video/audio bitrate

by GarciaPL on Tuesday 25 March 2014

Have you ever thought how receive the bitrate of your video/audio file using ffmpeg in command line ? Before I will show you a solution of this problem I would like to paste below some example output of video file which can be obtained using ffmpeg :

ffmpeg version git-2013-10-30-94a80e3 Copyright (c) 2000-2013 the FFmpeg developers
  built on Oct 30 2013 15:46:23 with gcc 4.8 (Ubuntu/Linaro 4.8.1-10ubuntu8)
  configuration: --prefix=/home/user/ffmpeg_build --extra-cflags=-I/home/user/ffmpeg_build/include --extra-ldflags=-L/home/luszcwoj/ffmpeg_build/lib --bindir=/home/luszcwoj/bin --extra-libs=-ldl --enable-gpl --enable-libass --enable-libfdk-aac --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvorbis --enable-libvpx --enable-libx264 --enable-nonfree --enable-x11grab
  libavutil      52. 48.100 / 52. 48.100
  libavcodec     55. 39.100 / 55. 39.100
  libavformat    55. 19.104 / 55. 19.104
  libavdevice    55.  5.100 / 55.  5.100
  libavfilter     3. 90.100 /  3. 90.100
  libswscale      2.  5.101 /  2.  5.101
  libswresample   0. 17.104 /  0. 17.104
  libpostproc    52.  3.100 / 52.  3.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'aquarium.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 0
    compatible_brands: isom3gp4
    creation_time   : 2013-09-08 23:38:41
  Duration: 00:00:03.44, start: 0.000000, bitrate: 3933 kb/s
    Stream #0:0(eng): Video: h264 (Baseline) (avc1 / 0x31637661), yuvj420p(pc), 640x480 [SAR 1:1 DAR 4:3], 2250 kb/s, 29.70 fps, 29.67 tbr, 90k tbn, 30 tbc (default)
    Metadata:
      creation_time   : 2013-09-08 23:38:41
      handler_name    : VideoHandle
    Stream #0:1(eng): Audio: aac (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 123 kb/s (default)
    Metadata:
      creation_time   : 2013-09-08 23:38:41
      handler_name    : SoundHandle


If you would like to get the bitrate just use this command :
ffmpeg -i aquarium.mp4 2>&1 | grep bitrate: | awk '{print $6}'

Reference : [1] FFmpeg Home Page

Remove all tables from a MySQL schema

by GarciaPL on Thursday 6 March 2014

A few days ago I found very useful solution (thanks for Biomathematicus!) for deleting tables from a MySQL schema. I know that it could be quite difficult for some developers (also for me) to manually remove every table from schema without removing this schema itself. So, there is a two-step solution which is going to help you removing a lot of tables from SQL database.

1) List all tables in the MySQL schema :

SELECT CONCAT('drop table ',table_name,'; ')
FROM information_schema.tables
WHERE table_schema = 'yourDatabaseName';

2) Copy result and paste it to query window and execute.
drop table table1; 
drop table table2;

Reference : [1] Biomathematicus.blogspot.com Remove all tables from mysql schema

Confitura 2013 - my participation

by GarciaPL on Sunday 9 February 2014

I really really would like to share with a video of my participation on conference called "Confitura" in the year 2013.

Confitura is the largest free conference for Java developers in Europe and even the largest event of its kind in Poland. 6 July this year on the campus of the University of Warsaw will be the next edition of our conference. From year to year we develop and we host a growing number of enthusiasts programming, a year ago there were more than 800. This year we expect nearly 1,000 people, for whom we have prepared five parallel tracks of almost 30 lectures.

More information you can find on : http://2013.confitura.pl/

Video : http://www.youtube.com/watch?v=HAuVAgeBqyQ



You can see when I am talking a lot of about many interesting and clever things starting from 0:34 second of this video ;) Enjoy.

Django - 'charmap' codec can't encode characters in position

by GarciaPL on Wednesday 1 January 2014

I used to have a problem while I was developing some application using Django (Python Web Framework). This problem occurs when I received some data from some kind of source using for example JSON notation. When this data contains some custom characters which should be saved in Unicode notation, I received and error like this one :

'charmap' codec can't encode characters in position
The solution of this issue is quite easy - everything applies to encoding of your file with source code. In this case I used to editor called PyDev (Eclipse based) in which you should go to :
Windows -> Preferences -> General -> Workspace
after that change option 'Text File Encoding' to UTF-8

References : [1] Django Python Web Framework [2] Stackoverflow.com Newcomer error in parsing tweet json unicodeencodeerror charmap codec cant encode characters in position 13-63: character maps to <undefined>