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