Sparkles

that were shone when I got tempered!

How to fix the “Unable to receive files via bluetooth” issue in Linux.

leave a comment »

I got this resolved as mentioned below.

 

1. Open the Persional File Sharing window by searching it as follows.

or you can run below command.

 gnome-file-share-properties 

2. If above one is not installed, install package gnome-user-share. Otherwise jump to step 4

sudo apt install gnome-user-share

3. Open Persional File Sharing window through step 1.

 

4. Allow (tick) “Receive files in downloads folder over bluetooth” as mentioned below.

 

References :

Advertisements

Written by Namal Fernando

April 25, 2018 at 11:55 am

Posted in Linux, TroubleShooting

Tagged with ,

Java 8 – Method References

leave a comment »

Method references can be used with the Lambda Expressions. They can be used to refer method of functional interface. It allows to reuse the method implementation among Lambda expressions.

Simple example with zero parameter

@FunctionalInterface 
interface MyInterface{  
    void display();  
}  
public class Example {

    public void myMethod(){  
		System.out.println("Instance Method");  
    }  

    public static void main(String[] args) {  
		Example obj = new Example();   
		MyInterface ref = obj::myMethod;  
		ref.display();  
    }  

}

Simple example with two parameters and for static method.

@FunctionalInterface 
interface MyInterface{  
	void display(String one, String two);  
}  
public class Example {

	public static void myMethod(String one, String two){  
		System.out.println("Instance Method for "+one+" and " + two);  
	}  

	public static void main(String[] args) {  
		MyInterface ref = Example::myMethod;  
		ref.display("ONE", "TWO");  
	}  

}

Simple example with one parameter and using constructor.

@FunctionalInterface 
interface MyInterface{  
    Hello display(String say);  
}  

class Hello{  
    public Hello(String say){  
        System.out.print(say);  
    }  
}

public class Example {  
    public static void main(String[] args) {
        MyInterface ref = Hello::new;  
        ref.display("Hello World!");  
    }  
}

References :.

Written by Namal Fernando

April 16, 2018 at 9:31 pm

Posted in Java

Tagged with

Java 8 – Lambda Expressions

leave a comment »

This is available since Java 8.
This is very usefull in java Collection Framework.

Lambda expressions can be only used with the functional interfaces. (An interface which has only one abstract method). Functional Interfaces can be annotated with @FunctionalInterface.
Here, because of Lambda expressions, we don’t need to define the method again to provide the implementation for abstract method of the Functional Interface.

Java Lambda expressions are treated as functions. So, no .class file will be created.

 

Java Lambda Expression syntax :

(argument-list) -> {body}

  • argument-list : empty / single or multiple
  • body : expressions and statements for the Lambda expressions.

 

Basic Exaple


@FunctionalInterface
interface Drawable{
public void draw();
}

int width=10;

// without Lambda
Drawable d = new Drawable(){
public void draw(){
System.out.println("Drawing "+width);
}
};

// with Lambda
Drawable d2 = () -> {
System.out.println("Drawing "+width);
};

d2.draw();

 

No Parameter Example


interface Sayable{
public String say();
}

Sayable s = ()-> {
return "I have nothing to say.";
};

System.out.println(s.say());

 

Multiple Parameters


interface Addable{
int add(int a,int b);
}

// Multiple parameters in lambda expression
Addable ad1 = (a,b)->(a+b);
System.out.println(ad1.add(10,20));

// Multiple parameters with data type in lambda expression
Addable ad2 = (int a,int b) -> (a+b);
System.out.println(ad2.add(100,200));

 

forEach loop


List list=new ArrayList();
list.add("ankit");
list.add("mayank");
list.add("irfan");
list.add("jai");

list.forEach(
(n)->System.out.println(n)
);

 

References :

Written by Namal Fernando

April 15, 2018 at 7:50 pm

Posted in Java

Tagged with ,

How to synchronize/ lock multiple SQL commands from multiple server platform in java

leave a comment »

Here, the problem/solution explains here is one of approach taken to synchronize / lock multiple SQL commands from multiple server platform in java.

Technology :

  • Java
  • MySQL – InnoDB

 

A.java


Here, checkAndEnter(String) method checks some flags, modify them using SQL commands. So, only one must be do this operations at a time.

monitorAndEnter(String) method.


	while(count++ < recheckCount) {
		
		if(checkAndEnter(messageId)) {
			
			return true;
			
		}else {
			
			try {
				Thread.sleep(recheckDelay * 1000);
			} catch (InterruptedException e) {
				return false;
			}
			
		}
		
	}

checkAndEnter(String) method.

Here, since we have used the synchronized block over the messageId, only one request per message Id will acquire the lock and enter to the block. We have used the intern here to get the string from the pool. But the catch is, this synchronizations happens within the JVM. So, it will not effect to multiple servers (multiple JVMs) unless they have been clustered with Terracotta or JGroup.


	private static boolean checkAndEnter(String messageId) {
		
		String 			lockKey 				= messageId.intern();
		
		synchronized (lockKey) {
			
			return B.getInstance().checkAndEnter(messageId, maxConnections);
			
		}
		
	}

 

B.java


checkAndEnter(Strng, int) method.


	public boolean checkAndEnter(String indexKey, int maxConetions) {

		String 				query 		= null;
		CallableStatement 		ps 		= null;
		Connection 			connection 	= null;

		try {

			connection 	= getMySQLConnection();

			query 		= "{ call schm.checkAndSee(?,?,?) }";

			ps = conn.prepareCall(query);

			ps.setString(1, indexKey);
			ps.setInt(2, maxConetions);
			ps.registerOutParameter(3, java.sql.Types.BOOLEAN);

			ps.execute();
			
			return ps.getBoolean(3);

		} catch (SQLException e) {

			return false;

		}finally {


		}

	}

 

Stored procedure


Here, we do the record lock on table record for execute queries in below stored procedures. So, once a hit comes to this one until it exits from this transaction block others will not be able to use that table record. (for update, select etc). 
CREATE DEFINER=`abc`@`%` PROCEDURE `checkAndSee`(in indexKey varchar(30), in maxIndxs int, out eligibility boolean)
BEGIN
    DECLARE currentIndxs INT;
	START TRANSACTION;
	SELECT currentIndexes INTO currentIndxs FROM schm.index_log WHERE id = indexKey FOR UPDATE;

    if (currentIndxs < maxIndxs) then
		UPDATE schm.index_log set currentIndexes = currentIndexes + 1 WHERE id = indexKey;
        set eligibility = true;
    else 
        set eligibility = false;
    end if;
    SELECT eligibility;
    COMMIT;
END

 

You can test the SP in workbench as mentioned below.

set @id="testId";
set @maxIndxs=2;
CALL `schm`.`checkAndSee`(@id, @maxIndxs, @eligibility);
select @eligibility;

 

References :


Written by Namal Fernando

April 5, 2018 at 9:03 pm

Posted in MySQL

Tagged with , , ,

Using anchors for adding references for properties / objects within yaml file

leave a comment »

When u want to add a reference for a property / object in yaml, you can use yaml anchors as mentioned below.

Code to be modified.


lookUpParseJsonAssessor :
  routingId : direct-groovy
  messageName : LookupParseJSONAssessor
  specialRq : true
  trafficProps :
    mustEnter : true
    maxConn : 1
    group : lookupServiceID
lookupOutputJsonAssessor :
  routingId : direct-groovy
  messageName : GroovyAccessor
  specialRq : true
  trafficProps :
    mustExit : true
    maxConn : 1
    group : lookupServiceID

Equalant Anchroed code.


lookUpParseJsonAssessor :
  routingId : direct-groovy
  messageName : LookupParseJSONAssessor
  specialRq : true
  trafficProps :
    mustEnter : true
    <<: &lookupServiceAnchor
      maxConn : 1
      group : lookupServiceID
lookupOutputJsonAssessor :
  routingId : direct-groovy
  messageName : GroovyAccessor
  specialRq : true
  trafficProps :
    mustExit : true
    <<: *lookupServiceAnchor

 

References :

Written by Namal Fernando

April 3, 2018 at 8:51 pm

Posted in Uncategorized

Tagged with ,

How to extend the history of Linux.

leave a comment »

I printed the current history size as mentioned below

echo $HISTSIZE

Then I increased it as

export HISTSIZE = 2000

Alternatives

Put that into .bashrc. You can get unlimitted history by mentioning it as below.

export HISTFILESIZE=
export HISTSIZE=

References :

Written by Namal Fernando

February 23, 2018 at 9:35 am

Posted in Linux

Tagged with ,

Dancing with Docker… !!!

leave a comment »

Traditional Virtualisation

In the traditional virtualisation, Host OS is there and top of that the Hypervisor (HyperV, VMWare, TVM etc) must be there. Then top of that, you install the virtual machines. Virtualisation layer provides virtualized Motherboard, CPU Memory etc. Thre you install the virtual OS (Linux / Windows etc), binaries libraries and the applications.

But here it emulates the hyperwisor, the whole virtual machines. So, there is an overhead. And the density (number of OS’s are also ) is also limitted.

Docker virtualisation

In Docker virtualisation, you don’t have to install guest OS’s, you dont have to provide virtualize CPUs, Motherboards so on. So, this is container vritualisations. And it also boots faster since you don’t want to emulate the hardware.

 

Once we have an dokcer image, we can create multiple containers according to the configurations we want. (eg : using one image we can create two containers with different configurations).

You can get the docker images using the docker hub [2]. There are official images and there are thrid party (comunity) images also. So, try to use select them care using the ratings / reviews number downloads etc.

Sample scenario 1 : Step to download the images and run:

1. docker pull nginx:1.10.2-alpine
– Pull the image from the hub

2. docker images
– Check the pulled images

3. docker run –name my-nginx -p 80:80 nginx:1.10.1-alpine
– Start the image.
– –name : This is the name of the image.
– p :
Ports running in the docker container are with the container itself. They are not exposed in the host machine. So, you need to map them to the host machine. So, 80:80 means, docker container 80 is mapped to host machine’s port 80.
– then the downloaded image name (nginx:1.10.2-alpine)

4. Now you have nginx in your machine.

 

Actually if you don’t have the image locally, run command will download it for you and run upon it!

Adding another runtime parameter with -d which means it should run as a detached mode.

docker run --name my-nginx -d -p 80:80 nginx:1.10.1-alpine

Here I will get a long ID. It is running in the background in detached mode.

Adding another parameter / modify parameter (port mapping etc) to the existing container can’t be done. Even you stopped it you cannot do it. Because you created the container and it has the parameters.
You can launch and crete a new container with another name. Instead you can remove the container and add another. (stop, remove and run).

But if you create anther container that means all the previous data will be disappear. (eg : if you have mariadb in one port, then you start another instance in another port, then all the [provious content will be disappear).

So, because of this, data is normally put to the outside of the container and map them with the container using valumes.

 

Mapping volumes :

For this, we are using -v. like -v docker-local-file-with-path : machine-local-file-with-path.
eg :

docker run --name my-custom-nginx-container -v /host/path/nginx.conf:/etc/nginx/nginx.conf:ro -d nginx

This will map the docker’s /host/path/nginx.conf file to local /etc/nginx/nginx.conf file. ‘ro’ means read only(so container runtime will not change it).

Instead of a single file you can mount an entire directoty also.

 

How to build our own docker images or how to extend an image :

The file you need to consider is the “Dockerfile”.

Dockerfile has below like commands.
FROM <image name>
– This means we starts our image from this image.

COPY / ADD
– copy a local file to the docker container. So, we don’t want to map. So, when the container starts these files will be a part of that. You can use ADD also for this.

RUN, CMD and ENTRYPOINT
These can be used in the Dockerfiles to extend an image.
All three instructions (RUN, CMD and ENTRYPOINT) can be specified in shell form or exec form.

Shell form
<instruction> <command>

Examples:

RUN apt-get install python3
CMD echo “Hello world”
ENTRYPOINT echo “Hello world”

When instruction is executed in shell form it calls /bin/sh -c <command> under the hood and normal shell processing happens.

For example, the following snippet in Dockerfile


ENV name John Dow
ENTRYPOINT echo "Hello, $name"

when container runs as docker run -it <image> will produce output

Hello, John Dow .

Exec form
This is the preferred form for CMD and ENTRYPOINT instructions.

<instruction> [“executable”, “param1”, “param2”, …]

Examples:

RUN [“apt-get”, “install”, “python3”]
CMD [“/bin/echo”, “Hello world”]
ENTRYPOINT [“/bin/echo”, “Hello world”]

When instruction is executed in exec form it calls executable directly, and shell processing does not happen.
So, if you need to run bash (or any other interpreter but sh), use exec form with /bin/bash as executable.

eg :

ENV name John Dow
ENTRYPOINT ["/bin/bash", "-c", "echo Hello, $name"]

RUN
It executes any commands on top of the current image and creates a new layer by committing the results.

RUN means it creates an intermediate container, runs the script and freeze the new state of that container in a new intermediate image. The script won’t be run after that: your final image is supposed to reflect the result of that script.

And RUN runs at the time of building the image. Not at the time it is run.

RUN has two forms:

RUN <command> (shell form)
RUN [“executable”, “param1”, “param2”] (exec form)

eg :

RUN apt-get update && apt-get install -y \
bzr \
cvs \
git \
mercurial \
subversion

CMD

CMD instruction allows you to set a default command, which will be executed only when you run container without specifying a command. If Docker container runs with a command, the default command will be ignored. If Dockerfile has more than one CMD instruction, all but last CMD instructions are ignored.

CMD has three forms:

CMD [“executable”,”param1″,”param2″] (exec form, preferred)
CMD [“param1″,”param2”] (sets additional default parameters for ENTRYPOINT in exec form)
CMD command param1 param2 (shell form)

eg : when container runs with a command, e.g., docker run -it <image> /bin/bash, CMD is ignored and bash interpreter runs instead

ENTRYPOINT

ENTRYPOINT instruction allows you to configure a container that will run as an executable. It looks similar to CMD, because it also allows you to specify a command with parameters. The difference is ENTRYPOINT command and parameters are not ignored when Docker container runs with command line parameters. (There is a way to ignore ENTTRYPOINT, but it is unlikely that you will do it.)

ENTRYPOINT means your image (which has not executed the script yet) will create a container, and runs that script.

ENTRYPOINT has two forms:

ENTRYPOINT [“executable”, “param1”, “param2”] (exec form, preferred)
ENTRYPOINT command param1 param2 (shell form)

Be very careful when choosing ENTRYPOINT form, because forms behaviour differs significantly.

Once you have the dockerfile, you ca build a docker image as mentioned below.

docker build -t=zip-nginx:1.0 . or docker build -t zip-nginx:1.0 .

-t – means the tag. tag means name and the version. the default version is ‘latest’
. – (dot) means to use the current directory to build the docker image. So, it will look for the Dockerfile in the current directory.

 

Sample scenario 2 : Start new container from the new image.

1. cd /[PATH_TO_MAGNIFY]/Magnify/DockerImage/magnify-docker

Files/Folders contained in above path:

/bin
/fusepatch
/modules
/Dockerfile
/hawtio-wildfly-1.5.3.war
/standalone.xml

Dockerfile content :

FROM camunda/camunda-bpm-platform:wildfly-latest
ADD standalone.xml standalone/configuration/
ADD bin/ bin/
ADD fusepatch/ fusepatch/
ADD modules/ modules/
ADD hawtio-wildfly-1.5.3.war standalone/deployments/

This will build an image downloading from the camunda/camunda-bpm-platform:wildfly-latest docker hub image and adding above artifacts.

2. docker build –tag=magnify
This will build the docker image as metion abve.

3. docker images
Check the docker images

4. sudo docker run -d –name magnify –net=”host” -p 7070:7070 -v [PATH_TO_MAGNIFY]/Magnify/DockerImage/docker-volumes/applicationConfigs:/camunda/applicationConfigs -v [PATH_TO_MAGNIFY]/Magnify/DockerImage/docker-volumes/modules/magnify:/camunda/modules/magnify -v [PATH_TO_MAGNIFY]/Magnify/DockerImage/docker-volumes/deployments:/camunda/standalone/deployments magnify

-d : run in detached mode
–name magnify : use magnify as the name.
–net=”host” : [need to know]
-p 7070:7070 : map docker 7070 port to host machines 7070 port.
-v [PATH_TO_MAGNIFY]/Magnify/DockerImage/docker-volumes/applicationConfigs:/camunda/applicationConfigs : Map LHS local pc files to RHS docker container files.
-v [PATH_TO_MAGNIFY]/Magnify/DockerImage/docker-volumes/modules/magnify:/camunda/modules/magnify : Map LHS local pc files to RHS docker container files.
-v [PATH_TO_MAGNIFY]/Magnify/DockerImage/docker-volumes/deployments:/camunda/standalone/deployments magnify : : Map LHS local pc files to RHS docker container files.

Sharing an entire image/container as it is.

For this you can use, docker save an image or docker export a container. This will output a tar file to standard output, so you will like to do something like docker save ‘dockerizeit/agent’ > dk.agent.lastest.tar. Then you can use docker load or docker import in a different host.

eg :

docker save busybox > busybox.tar
docker load < busybox.tar.gz

docker export red_panda > latest.target
docker import /path/to/exampleimage.tgz

Instead of this we can share the artifacts with the Dockerfile also. At that time, consumer must build the image using docker build and run as needed.

 

Running docker in the interactive mode

We can use below format to run the docker in the interactive mode.

docker run -ti ubuntu:14.04 /bin/bash

In this case ‘t’ means we are using the host terminal. ‘i’ means interactive. /bin/bash is needed to be added at the end since we need to access to the docekr’s terminal.

Press CTRL + P + Q to get back to the host terminal again. Don’t hit CTRL+C! Becuase it will leave from the tearminal as well as the Docker container.

If you want to go back to the docker terminal again, type

docker attach <container id/name>

You can get the container id by using docker ps.

You can enter to the shell of a container as mentioned below also.

docker exec-ti my-nginx /bin/sh

exec – This is a docker command that can execute in a running container.

 

Docker cheat sheet :

docker pull nginx:1.10.2-alpine
– pull the nginx:1.10.2-alpine from the docker hub

docker build -t=friendlyname . or docker build -t friendlyname .
– Create image using this directory’s Dockerfile. Last dot is very important and it says the dockerfile is at the same location.

docker run -p 4000:80 friendlyname
– Run “friendlyname” mapping port 4000 to 80

docker run -d -p 4000:80 friendlyname
– Same thing, but in detached mode

docker run -it -p 4000:80 friendlyname /bin/bash
– Same thing, but in interactive mode.

docker run username/repository:tag
– Run image from a registry

docker ps
– this will list all the currently running container

docker ps -a
– this will list all the containers that are running and not running

docker ps -a –no-trunc
– this will list all the content without truncating

docker container ls
– List all running containers

docker container ls -a
– List all containers, even those not running

docker start <container id/name>
– gracefully start the container

docker stop <container id/name>
– gracefully stop the container

docker container stop <hash>
– Gracefully stop the specified container

docker container kill <hash>
– Force shutdown of the specified container

docker rm <container id/name>
This will remove the container.

docker container rm <hash>
– Remove specified container from this machine

docker container rm $(docker container ls -a -q)
– Remove all containers

docker images
– List images on this machine. This is used to check the image is installed etc.

docker images -a
– List all images on this machine

docker image ls -a
– List all images on this machine

docker rmi <image name/id>
– remove specific image

docker image rm <image id>
– Remove specified image from this machine

docker image rm $(docker image ls -a -q)
– Remove all images from this machine

docker login
– Log in this CLI session using your Docker credentials

docker tag <image> username/repository:tag
– Tag <image> for upload to registry

docker push username/repository:tag
– Upload tagged image to registry

docker –version
– will show the docker version

docker save
Save docker image

docker load < busybox.tar.gz
Load the saved image

docker export
Export the container

docker import /path/to/exampleimage.tgz
Import the container

docker top <container id/name>
– Running processors in docker container


References :

[1] : https://docs.docker.com/
[2] : https://hub.docker.com/explore/
[3] : https://hub.docker.com/_/nginx/
[4] : http://takacsmark.com/getting-started-with-docker-in-your-project-step-by-step-tutorial/
[5] : https://www.youtube.com/watch?v=Vyp5_F42NGs
[6] : https://www.youtube.com/watch?v=UV3cw4QLJLs – further
[7] : https://deis.com/blog/2015/creating-sharing-first-docker-image/
[8] : https://stackoverflow.com/questions/24482822/how-to-share-my-docker-image-without-using-the-docker-hub
[9] : https://docs.docker.com/engine/reference/commandline/save/#extended-description
[10] : http://goinbigdata.com/docker-run-vs-cmd-vs-entrypoint/
[11] : https://stackoverflow.com/questions/34549859/run-a-script-in-dockerfile

Written by Namal Fernando

December 13, 2017 at 1:57 pm

Posted in Uncategorized

Tagged with

Ruth's Reflections

Contemplations from quakey quirky Christchurch

TED Blog

The TED Blog shares interesting news about TED, TED Talks video, the TED Prize and more.

Ziplok

Learn and discover simple things

Meihta Dwiguna Saputra's Knowledge Base

~In learning you will teach and in teaching you will (re)learn~

The Java Blog

Thoughts, tips and tricks about the Java programming language

Sparkles

that were shone when I got tempered!