Installing CouchDB on Ubuntu Linux (Part 2)

In part I post, I explained step by step how to install CouchDB in your machine and how to use it. in this post we will go over a little bit further to find out how we can use the couchDB to do what we really need in Clustering environment. for example how to modify the Local.ini and default.ini files to get what we want to.

after you install a fresh copy of the couchdb database. you can modify and adjust the configuration to make that enable to work on a seperate machine and let the other applications communicate with it over HTTP or HTTPS. in this post we will focus over the HTTP communication only.

get the couchdb configuration files’ location from command line.

couchdb -c

below will be the result

/etc/couchdb/local.ini/etc/couchdb/default.ini

then you can use VI and also using the sudo since it needs root access; then modify below parts in these files to make sure it can be redeuce the security and allow others to communiate with this DB for now.

make a backup and modify the local.ini file for accepting all the traffic and make sure couchDB service can listen to traffics from all IP addresses. NOTE: if you have any specifiv IP address you can just add that expcept 0.0.0.0

sudo cp /etc/couchdb/local.ini /etc/couchdb/local.ini_bak

then edit the file with your favorit text editor.

sudo vi /etc/couchdb/local.ini

or using gedit

sudo gedit /etc/couchdb/local.ini

look for a section that has the

;bind_address = 127.0.0.1

and change that to

bind_address = 0.0.0.0

then restart the couchdb service

sudo service couchdb restart

then try with your IP address, you can use ifconfig to find your ip address for example mine is something like

curl -k http://10.0.2.15:5984

and the result will be the same as part 1 with a JSOn representation of a greeting message. now you have a functioning running Couchdb.

NOTE: right now everyone can do everything in that couchdb so for further security you need to modify the local.ini or default.ini with the proper admin account and password, the password will entered as cleartext however it will get encrypted in the file after save so no worries with that.

 

 

 

 

 

Advertisements

Installing CouchDB on Ubuntu Linux (Part 1)

Recently I got the opportunity to work on Apache openWhisk, however since I wasn’t that much familiar with that environment, I tried to first install that on my Virtual box and see if I can take care of it; anyway. I start  folling around and installing related dependncies which one of the was a JSON database named: CouchDB. below are the steps:

prepare the environemnt first. you can take a look at the official website:  http://docs.couchdb.org/en/2.0.0/install/unix.html#debian-based-systems

update the linux first. and then add the PPA repository to the list. and the refresh the package manager, and then start downloading and installing the CouchDB.

  1. make sure your environment is up to date
    sudo apt-get update
  2. then upgrade the linux
    sudo apt-get upgrade
  3. then install softwre properties common
    sudo apt-get install software-properties-common
  4. and add PPA Repository to the linux package manager(since you want to get the stable version and not the alpha or betta versions)
    sudo add-apt-repository ppa:couchdb/stable
  5. then refresh the package manager to let it aware of this change
    sudo apt-get update
  6. install database ( it might ask you to enter yer or no in between of installation)
     sudo apt-get install couchdb
  7. start testing it and make sure it’s up and running
    curl -k http://127.0.0.1:5984
  8. you should be able to receive something like a below greeting JSON response

couchdbGreeting

since this is a JSON database you can communicate with it over HTTP with its methods, like adding a new database or remove it and add records, etc.

you can get the list of current databases via curl command below

curl localhost:5984/_all_dbs

or an alternative command

curl -k http://127.0.0.1:5984/_all_dbs

now you have a functioning Fresh CouchDB database running in your machine.

Android: Passing Objects between Activities

most of the times you would need to pass a POJO object through some activities to make sure you have everything related to a sample topic in one place as an OOP best practice. so to pass an object between some activities you need to do something like this …

inside the first activity you need to create your POJO and then add that to the nextScreen, then you need to make sure your POJO can be serialized, and then in nextScreen Activity read that POJO back and after unmarshaling back to the object shape read its content.
Step #1:

for example, I have a component that enables the app to start reading the QR code like this method.

public class Home extends AppCompatActivity implements View.OnClickListener {

private static MyObj obj1 = new MyObj();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);

}


public void onActivityResult(int requestCode, int resultCode, Intent intent) {

IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);

if (scanningResult != null) {

String scanContent = scanningResult.getContents();
String scanFormat = scanningResult.getFormatName();

Intent nextScreen = null;
if (isInFieldPath) {
nextScreen = new Intent(getApplicationContext(), FieldOptionMenu.class);

} else {
nextScreen = new Intent(getApplicationContext(), LabOptionMenu.class);
}

nextScreen.putExtra("format", scanFormat);
nextScreen.putExtra("content", scanContent);

polioData.setQrCodeContent(scanContent);
polioData.setQrCodeFormat(scanFormat);
nextScreen.putExtra("MySimpleObj",obj1);

startActivity(nextScreen);


} else {
Toast toast = Toast.makeText(getApplicationContext(), "No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}

}

Step #2:

you need to implement below items inside your POJO to make that serializable in android.


public class MyObject implements Parcelable {

private String something = "Navidamo Navidam";


public MyObject() {
super();
}

protected MyObject(Parcel in) {
something = in.readString();

}

public String getUsername() {
return something;
}

public void setUsername(String something) {
this.something = something;
}



// writing and serialization process

@Override
public int describeContents() {
return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(something);

}

//reading back to object from serilization process - unmarshaling data
public static final Creator<MyObject> CREATOR = new Creator<MyObject>() {
@Override
public MyObject createFromParcel(Parcel in) {
return new MyObject(in);
}

@Override
public MyObject[] newArray(int size) {
return new MyObject[size];
}
};


}

Step #3:

and inside the destination activity simply use the below lines wherever you can get the intent.

MyObject obj = (MyObject) getIntent().getParcelableExtra("MySimpleObj");
Toast.makeText(getApplicationContext(),
obj.getSomething() + "wiht out bundle", Toast.LENGTH_LONG).show();

//            one way of getting data from Extra
//            Bundle bundle = getIntent().getExtras();
//            obj = (MyObject) bundle.getParcelable("MySimpleObj");
//            Toast.makeText(getApplicationContext(),
//                    obj.getSomething() + "with bundle", Toast.LENGTH_LONG).show();

 

Spring @Scope

in Spring frameworks, sometimes you need to take control of beans scope, in that case you can add AOP jar files which will come if you use BOM, and Context set of dependencies and then easily use the @Scope annotation on beans. Below is a set of bean scope available in Spring:

  • Singleton = only one object in entire Spring container
  • prototype = a new object per every time calling applicationContext.getBean(…)
  • web based bean scope:
    • request // a new object per request – a little bit longer than prototype since that was being called by getbean method every time.
    • session // an object per session and will be renewed whenever we hit the timeout for that session
    • globalsession // an object for entire application

example:


@service("myservice")

@scope("singleton") // this is the default bean scope
//or using this @Scope(ConfirgurableFactoryBean.SCOPE_SINGLETON)

public class MyServiceImple extends MyService{

//....

}

 

 

Optional DataType JDK 8

how do you normally do a NULL check inside the java application. if you’re using older jdk, just using the if to check whether the object is null or not, something like below …

 

if(myObject != null){
... // do something
}

by using new JDK 8, there is a wrapper class that could wrap object type and basically provides some features for developers and in simple words, do the heavy lifting internally, make the code compact and more readable.

 

please check below example.


Optional<MyDataType> returnedInstance = myObjInstance.getMeSomething();

 

Notes:
1. mechanism to check whether the return type contains the NULL pointer exception or not.
2.decrease the null pointer exception thrown by the application.
3. due to suggestion by openJDK mailing list — only use the Optional in return tye
3.a: still needed to check for input params for functions and methods inside the classes.
4. Checked exception can be used with Optional to handle and signal the entier application whenever the unexpected status would be met.
5. something like this …
Optional<TypeIAmExpecting> = getMySomething(String input);

ifPresent() — return true if value is not null and would be presented.
orElse(defultValue);
get(); — get the value
isPresent() — check in ifelse statement and ha get() or handle the no-exited stateus.

when to use: as return type

 

 

Testing in Java Part 1 – Basics

Different types of testing:

  1. System test / End to End test normally will be done via QA
  2. Aggregate Test / testing component to make sure the business functionalities with all the dependencies could be done as they supposed to. it took longer than unit test since it has a database to set up and tear down, or clean up some stuff, etc.
  3. Unit test / testing each individual functionality. no dependencies.

 

3 Stages every test case needs to have:

  1.  prepare the environment for testing (preparing any requirement before actually testing the behaviour – it might happen in every method.)
  2. the behaviour to test (the actual function you want to test – if that’s too big, you’re testing a lot of functionalities and if something happened you need a way to find that between that complex tests)
  3. checking the result (Assertions)

making testing in orders might make dependencies between unit tests which don’t have any meaning other than, Aggregate testing instead of testing every individual function.

NOTE: every test methods in your test class, should only test one behaviour, even if preparing and function parts of couple test methods will be similar but and the differences will be in assertion parts, then it might show that you are testing differents parts/ behaviours of the function.

NOTE: Make your test methods names, expressing the behaviour of testing, make sure they expose what you want to test.

NOTE: One test class for one Class object.

NOTE: testing the throwing of an exception in the case of a failure of the application?

<br data-mce-bogus="1">

<strong>@Test(Expected=MyTypeOfException.class)</strong>

&nbsp;

 

 

 

 

Data Structure – Merge Sort

under divide and conquer algorithms in sort category, we are reaching to Merge Sort, which basically

  1. Takes the input array and BREAK/DIVIDE it into half.
  2. call the same BREAK/DIVIDE function on the smaller halves , again – RECURSIVE function, with a base condition of array.size =1
  3. array.size() = 1 counted as SORTED. now rebuilding.
  4. in the time of rebuilding process for the smaller chunk of data, we are using previous smaller chunk in each step, meaning, smaller sorted data as a result of last previous recursive call.
  5. and then rebuild the array after sorting the smaller previous parts.

NOTE: in this sorting algorithm, we need a copy of the array, in a merging process and that’s the tricky part.

 big picture:

we have two main function in Merge Sort

  1. Partitioning(array, startIndex, endIndex) // breaking into pieces
  2. Merging(array, startIndex, midIndex, endIndex) // sorting and rebuilding

/**
* breaking the array into smaller pieces, RECURSIVE happened here.
*
* @param arrSRC
* @param startIndex
* @param endIndex
*/
public void partitioning(int[] arrSRC, int startIndex, int endIndex) {

System.out.println("Begin Dividing/Breaking by this array...");
showContent(arrSRC, startIndex, endIndex);

if (endIndex - 1 == startIndex) {
System.out.println("Dividing/Breaking - into smaller chunk - found only one item in array, so it's counted as SORTED.");
return;
}

System.out.println("Dividing/Breaking - into smaller chunk - Finding Mid Index.");
int mid = (startIndex + endIndex) / 2;

System.out.printf("Dividing/Breaking - into smaller chunk -  startIndex: %d - endIndex: %d = midIndex:%d\n", startIndex, endIndex, mid);

partitioning(arrSRC, startIndex, mid);
partitioning(arrSRC, mid, endIndex);

doMerge(arrSRC, startIndex, mid, endIndex);

}

/**
* do the actual merge/build task.
*
* @param arrSrc
* @param startIndex
* @param mid
* @param endIndex
*/
private void doMerge(int[] arrSrc, int startIndex, int mid, int endIndex) {

//tricky partitioning in MERGE SORT since we need a semi-sorted array which was made in previous recursive function call.
System.out.println("Begin Conquering/ building array again...");

arrayCopy(arrSrc, tempArr, startIndex, endIndex);

int leftIndex = startIndex;
int rightIndex = mid;
int index = startIndex;

while (leftIndex < mid && rightIndex < endIndex) {
if (tempArr[leftIndex] <= tempArr[rightIndex]) {

arrSrc[index] = tempArr[leftIndex];
leftIndex++;

} else {
arrSrc[index] = tempArr[rightIndex];
rightIndex++;
}
index++;
}

while (leftIndex < mid) {
arrSrc[index] = tempArr[leftIndex];
leftIndex++;
index++;
}
while (rightIndex < endIndex) {
arrSrc[index] = tempArr[rightIndex];
rightIndex++;
index++;
}

System.out.print("Final Result ... \n\t ");
showContent(arrSrc, startIndex, endIndex);
System.out.println("");

}

Orders:

in the worst case scenario O(N x LogN), since it’s breaking the target into a smaller chunk. so it’s good for large unsorted data sets.

when to use?

when you want to do the sort in a multi-thread environment so every thread can do one part of sorting and then one manager thread can stick the parts together.

how to implement?


package com.navid.ds.practice.sorting.divideconqure;

/**
*
* @author Unknown_
*/
public class MergeSort {

public static int[] myArray = new int[]{10, 2, 5, 20, 90, 12, 31, 5};
private static int[] tempArr = null;

public MergeSort() {

tempArr = new int[myArray.length];

}

/**
* breaking the array into smaller pieces, RECURSIVE happened here.
*
* @param arrSRC
* @param startIndex
* @param endIndex
*/
public void partitioning(int[] arrSRC, int startIndex, int endIndex) {

System.out.println("Begin Dividing/Breaking by this array...");
showContent(arrSRC, startIndex, endIndex);

if (endIndex - 1 == startIndex) {
System.out.println("Dividing/Breaking - into smaller chunk - found only one item in array, so it's counted as SORTED.");
return;
}

System.out.println("Dividing/Breaking - into smaller chunk - Finding Mid Index.");
int mid = (startIndex + endIndex) / 2;

System.out.printf("Dividing/Breaking - into smaller chunk -  startIndex: %d - endIndex: %d = midIndex:%d\n", startIndex, endIndex, mid);

partitioning(arrSRC, startIndex, mid);
partitioning(arrSRC, mid, endIndex);

doMerge(arrSRC, startIndex, mid, endIndex);

}

/**
* do the actual merge/build task.
*
* @param arrSrc
* @param startIndex
* @param mid
* @param endIndex
*/
private void doMerge(int[] arrSrc, int startIndex, int mid, int endIndex) {

//tricky partitioning in MERGE SORT since we need a semi-sorted array which was made in previous recursive function call.
System.out.println("Begin Conquering/ building array again...");

arrayCopy(arrSrc, tempArr, startIndex, endIndex);

int leftIndex = startIndex;
int rightIndex = mid;
int index = startIndex;

while (leftIndex < mid && rightIndex < endIndex) {
if (tempArr[leftIndex] <= tempArr[rightIndex]) {

arrSrc[index] = tempArr[leftIndex];
leftIndex++;

} else {
arrSrc[index] = tempArr[rightIndex];
rightIndex++;
}
index++;
}

while (leftIndex < mid) {
arrSrc[index] = tempArr[leftIndex];
leftIndex++;
index++;
}
while (rightIndex < endIndex) {
arrSrc[index] = tempArr[rightIndex];
rightIndex++;
index++;
}

System.out.print("Final Result ... \n\t ");
showContent(arrSrc, startIndex, endIndex);
System.out.println("");

}

/**
* This array Copy method is just an effort to expose the
*
* @param arrSrc
* @param arrDest
* @param lowerIndex
* @param higherIndex
*/
public void arrayCopy(int[] arrSrc, int[] arrDest, int lowerIndex, int higherIndex) {

for (int i = lowerIndex; i < higherIndex; i++) {
arrDest[i] = arrSrc[i];
}

}

public void showContent(int[] arr, int start, int end) {

System.out.print("[ ");
for (int i = start; i < end; i++) {
System.out.printf("%d, ", arr[i]);

}
System.out.println(" ]");
}

public static void main(String[] args) {

MergeSort ms = new MergeSort();

ms.partitioning(myArray, 0, myArray.length);

}

}

 

 

output

run:
Begin Dividing/Breaking by this array...
[ 10, 2, 5, 20, 90, 12, 31, 5,  ]
Dividing/Breaking - into smaller chunk - startIndex: 0 - endIndex: 8 = midIndex:4
Begin Dividing/Breaking by this array...
[ 10, 2, 5, 20,  ]
Dividing/Breaking - into smaller chunk - startIndex: 0 - endIndex: 4 = midIndex:2
Begin Dividing/Breaking by this array...
[ 10, 2,  ]
Dividing/Breaking - into smaller chunk - startIndex: 0 - endIndex: 2 = midIndex:1
Begin Dividing/Breaking by this array...
[ 10,  ]
Dividing/Breaking - into smaller chunk - found only one item in array, so it's counted as SORTED.
Begin Dividing/Breaking by this array...
[ 2,  ]
Dividing/Breaking - into smaller chunk - found only one item in array, so it's counted as SORTED.
Begin Conquering/ building array again...
Final Result ... 
     [ 2, 10,  ]

Begin Dividing/Breaking by this array...
[ 5, 20,  ]
Dividing/Breaking - into smaller chunk - startIndex: 2 - endIndex: 4 = midIndex:3
Begin Dividing/Breaking by this array...
[ 5,  ]
Dividing/Breaking - into smaller chunk - found only one item in array, so it's counted as SORTED.
Begin Dividing/Breaking by this array...
[ 20,  ]
Dividing/Breaking - into smaller chunk - found only one item in array, so it's counted as SORTED.
Begin Conquering/ building array again...
Final Result ... 
     [ 5, 20,  ]

Begin Conquering/ building array again...
Final Result ... 
     [ 2, 5, 10, 20,  ]

Begin Dividing/Breaking by this array...
[ 90, 12, 31, 5,  ]
Dividing/Breaking - into smaller chunk - startIndex: 4 - endIndex: 8 = midIndex:6
Begin Dividing/Breaking by this array...
[ 90, 12,  ]
Dividing/Breaking - into smaller chunk - startIndex: 4 - endIndex: 6 = midIndex:5
Begin Dividing/Breaking by this array...
[ 90,  ]
Dividing/Breaking - into smaller chunk - found only one item in array, so it's counted as SORTED.
Begin Dividing/Breaking by this array...
[ 12,  ]
Dividing/Breaking - into smaller chunk - found only one item in array, so it's counted as SORTED.
Begin Conquering/ building array again...
Final Result ... 
     [ 12, 90,  ]

Begin Dividing/Breaking by this array...
[ 31, 5,  ]
Dividing/Breaking - into smaller chunk - startIndex: 6 - endIndex: 8 = midIndex:7
Begin Dividing/Breaking by this array...
[ 31,  ]
Dividing/Breaking - into smaller chunk - found only one item in array, so it's counted as SORTED.
Begin Dividing/Breaking by this array...
[ 5,  ]
Dividing/Breaking - into smaller chunk - found only one item in array, so it's counted as SORTED.
Begin Conquering/ building array again...
Final Result ... 
     [ 5, 31,  ]

Begin Conquering/ building array again...
Final Result ... 
     [ 5, 12, 31, 90,  ]

Begin Conquering/ building array again...
Final Result ... 
     [ 2, 5, 5, 10, 12, 20, 31, 90,  ]

BUILD SUCCESSFUL (total time: 0 seconds)