Get MIME Type on Android

    public String getMimeType(String url) {
        String type = null;
        String extension = MimeTypeMap.getFileExtensionFromUrl(url);
        if (extension != null) {
            type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        }
        return type;
    }

Work with BlockingQueue in Java

Unbounded Queue

BlockingQueue<String> blockingQueue = new LinkedBlockingDeque<>();

Bounded Queue

BlockingQueue<String> blockingQueue = new LinkedBlockingDeque<>(10);

Adding Elements

  • add() – returns true if insertion was successful, otherwise throws an IllegalStateException
  • put() – inserts the specified element into a queue, waiting for a free slot if necessary
  • offer() – returns true if insertion was successful, otherwise false
  • offer(E e, long timeout, TimeUnit unit) – tries to insert element into a queue and waits for an available slot within a specified timeout

Retrieving Elements

  • take() – waits for a head element of a queue and removes it. If the queue is empty, it blocks and waits for an element to become available
  • poll(long timeout, TimeUnit unit) – retrieves and removes the head of the queue, waiting up to the specified wait time if necessary for an element to become available. Returns null after a timeout

References
http://www.baeldung.com/java-blocking-queue
https://pupli.net/2017/07/24/remote-procedure-call-rpc-sample-in-rabbitmq/

Work with Go Http Server

package main

import (
	"io"
	"net/http"
)

func main() {
	http.HandleFunc("/",sayHello)
	http.HandleFunc("/index", serverFile)
	http.ListenAndServe(":8000", nil)
}

func sayHello(writer http.ResponseWriter, request *http.Request)  {
	io.WriteString(writer,"Hello World")
}

func serverFile(responseWriter http.ResponseWriter, request *http.Request) {
	http.ServeFile(responseWriter,request,"index.html")
}

References

Remote procedure call (RPC) Sample in RabbitMQ

Client

public class Main {


    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {


        int count = 0;

        while (count < 100) {
            String time = getTime();
            System.out.println(time);

            Thread.sleep(1000);
            count++;
        }

    }

    private static String getTime() throws IOException, InterruptedException, TimeoutException {

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");

        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        String requestQueueName = "rpc01";
        String replyQueueName = channel.queueDeclare().getQueue();

        String corrId = UUID.randomUUID().toString();

        AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder()
                .correlationId(corrId)
                .replyTo(replyQueueName)
                .build();

        String message = "Mahmood";

        // use to block until there is a response available
        BlockingQueue<String> response = new ArrayBlockingQueue<String>(1);

        channel.basicPublish("", requestQueueName, properties, message.getBytes("UTF-8"));

        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope,
                                       AMQP.BasicProperties properties, byte[] body) throws IOException {

                if (properties.getCorrelationId().equals(corrId)) {
                    // save in the response queue
                    // so the queue can release the blockage
                    response.offer(new String(body, "UTF-8"));
                }
            }
        };

        channel.basicConsume(replyQueueName, true, consumer);

        // block until there is a response available
        String result=response.take();

        channel.close();
        connection.close();

        return result;
    }

}

Server

public class Main {

    private static String requestQueueName = "rpc01";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");

        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(requestQueueName, false, false, false, null);
        channel.basicQos(1);

        System.out.println(" [x] Awaiting RPC requests");

        Consumer consumer = new DefaultConsumer(channel) {

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope,
                                       AMQP.BasicProperties properties, byte[] body) throws IOException {

                String responseQueueName = properties.getReplyTo();
                String correlationId = properties.getCorrelationId();

                System.out.println(String.format("CorrelationId: %s, Response Queue: %s", correlationId, responseQueueName));

                String message = new String(body, "UTF-8");
                String response = String.format("Hello %s, Time is : %s", message, new Date().toString());


                AMQP.BasicProperties responseProperties = new AMQP.BasicProperties().builder()
                        .correlationId(correlationId)
                        .build();

                channel.basicPublish("", responseQueueName, responseProperties, response.getBytes("UTF-8"));
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        };

        channel.basicConsume(requestQueueName, false, consumer);
    }

}

References
https://www.rabbitmq.com/tutorials/tutorial-six-java.html
https://github.com/mhdr/RabbitMQSamples/tree/master/006_RPC

Check whether there is an Internet connection available on Android

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager 
          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

References
https://stackoverflow.com/questions/4238921/detect-whether-there-is-an-internet-connection-available-on-android

Configure Hibernate With MySQL in Gradle and do CRUD – JPA Persistence Way

Employee.java

import javax.persistence.*;

@Entity
@Table(name = "EMPLOYEE")
public class Employee {
    @Id
    @GeneratedValue
    @Column(name = "id")
    private int id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @Column(name = "salary")
    private int salary;

    public Employee() {
    }

    public Employee(String fname, String lname, int salary) {
        this.firstName = fname;
        this.lastName = lname;
        this.salary = salary;
    }

    public int getId() {
        return id;
    }

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

    public String getFirstName() {
        return firstName;
    }

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

    public String getLastName() {
        return lastName;
    }

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

    public int getSalary() {
        return salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }
}

resources/META-INF/persistence.xml

<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence

http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"

             version="2.1">

    <persistence-unit name="ir.mhdr.jpaDemo" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <class>Employee</class>

        <properties>
            <!-- Configuring JDBC properties -->
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/testdb?useUnicode=yes&amp;characterEncoding=UTF-8&amp;useJDBCCompliantTimezoneShift=true&amp;useLegacyDatetimeCode=false&amp;serverTimezone=UTC" />
            <property name="javax.persistence.jdbc.user" value="root" />
            <property name="javax.persistence.jdbc.password" value="sampad622" />
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />

            <!-- Hibernate properties -->
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.format_sql" value="true" />
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL57Dialect" />
            <property name="hibernate.hbm2ddl.auto" value="create" />

            <!-- Configuring Connection Pool -->
            <property name="hibernate.c3p0.min_size" value="5" />
            <property name="hibernate.c3p0.max_size" value="20" />
            <property name="hibernate.c3p0.timeout" value="500" />
            <property name="hibernate.c3p0.max_statements" value="50" />
            <property name="hibernate.c3p0.idle_test_period" value="2000" />
        </properties>
    </persistence-unit>
</persistence>

EmployeeBL.java

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.criteria.internal.CriteriaUpdateImpl;

import javax.persistence.*;
import javax.persistence.criteria.CriteriaUpdate;
import javax.transaction.Transaction;
import java.util.Iterator;
import java.util.List;

public class EmployeeBL {

    private EntityManagerFactory factory;

    public EmployeeBL() {
        factory = Persistence.createEntityManagerFactory("ir.mhdr.jpaDemo");
    }

    public void close() {
        factory.close();
    }

    /* Method to CREATE an employee in the database */
    public void addEmployee(String fname, String lname, int salary) {
        EntityManager entityManager = factory.createEntityManager();
        EntityTransaction tx = null;

        try {
            tx = entityManager.getTransaction();
            tx.begin();

            Employee employee = new Employee(fname, lname, salary);
            entityManager.persist(employee);

            tx.commit();
        } catch (Exception ex) {

            if (tx != null) tx.rollback();
            ex.printStackTrace();

        } finally {

            entityManager.close();
        }
    }


    /* Method to  READ all the employees */
    public void listEmployees() {
        EntityManager entityManager = factory.createEntityManager();
        EntityTransaction tx = null;

        try {
            tx = entityManager.getTransaction();
            tx.begin();

            List employees = entityManager.createQuery("from Employee").getResultList();
            for (Iterator iterator =
                 employees.iterator(); iterator.hasNext(); ) {
                Employee employee = (Employee) iterator.next();
                System.out.print("First Name: " + employee.getFirstName());
                System.out.print("  Last Name: " + employee.getLastName());
                System.out.println("  Salary: " + employee.getSalary());
            }

            tx.commit();
        } catch (Exception ex) {
            if (tx != null) tx.rollback();
            ex.printStackTrace();
        } finally {

            entityManager.close();

        }
    }


    /* Method to UPDATE salary for an employee */
    public void updateEmployee(Integer EmployeeID, int salary) {

        EntityManager entityManager = factory.createEntityManager();
        EntityTransaction tx = null;

        try {
            tx = entityManager.getTransaction();
            tx.begin();

            TypedQuery<Employee> query = entityManager.createQuery("select emp from Employee emp where id=:id", Employee.class);
            query.setParameter("id", EmployeeID);
            Employee employee = query.getSingleResult();

            employee.setSalary(salary);

            entityManager.persist(employee);

            tx.commit();
        } catch (Exception ex) {
            if (tx != null) tx.rollback();
            ex.printStackTrace();
        } finally {
            entityManager.close();
        }
    }


    /* Method to DELETE an employee from the records */
    public void deleteEmployee(Integer EmployeeID) {

        EntityManager entityManager = factory.createEntityManager();
        EntityTransaction tx = null;

        try {

            tx = entityManager.getTransaction();
            tx.begin();

            Employee employee = entityManager.find(Employee.class, EmployeeID);
            entityManager.remove(employee);

            tx.commit();

        } catch (Exception ex) {
            if (tx != null) tx.rollback();
            ex.printStackTrace();
        } finally {
            entityManager.close();
        }
    }
}

Main.java

public class Main {


    public static void main(String[] args)
    {
        EmployeeBL employeeBL=new EmployeeBL();
        employeeBL.addEmployee("Mahmood","Ramzani",1000);
        employeeBL.close();
    }
}

References
https://github.com/mhdr/HibernateSamples/tree/master/004_Persistent
http://docs.jboss.org/hibernate/orm/5.2/quickstart/html_single/#tutorial_jpa
https://dzone.com/articles/a-curious-java-language-feature-and-how-it-produce
https://www.sitepoint.com/5-reasons-to-use-jpa-hibernate/

Install Go on Ubuntu and Windows

tar xvf go1.6.linux-amd64.tar.gz

You should now have a directory called go in your home directory

sudo chown -R root:root ./go
sudo mv go /usr/local
sudo nano ~/.profile
export GOPATH=$HOME/go
export PATH=$PATH:/usr/local/go/bin:$GOPATH/bin
source ~/.profile

Windows
Set GOROOT, GOPATH, GOBIN System Variable
References
https://www.digitalocean.com/community/tutorials/how-to-install-go-1-6-on-ubuntu-16-04
http://www.wadewegner.com/2014/12/easy-go-programming-setup-for-windows/
https://stackoverflow.com/questions/25216765/gobin-not-set-cannot-run-go-install