Monday, September 15, 2014

Dialog BOX in Custom Base Adaptor

package com.example.dlistview;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Application;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class CustomAdapter extends BaseAdapter {

     private static final String TAG = CustomAdapter.class.getSimpleName();
        ArrayList<DataModel> listArray;
        public CustomAdapter() {
           /* listArray = new ArrayList<DataModel>(5);
            listArray.add(new DataModel("name1", 5, 1.8, "Java"));
            listArray.add(new DataModel("name2", 10, 2.8, "Python"));
            listArray.add(new DataModel("name3", 15, 3.8, "Django"));
            listArray.add(new DataModel("name4", 20, 4.8, "Groovy"));
            listArray.add(new DataModel("name5", 25, 5.8, "Maven")); */
           
            listArray = new ArrayList<DataModel>(5);
            listArray.add(new DataModel("Class 1",1));
            listArray.add(new DataModel("Class 2",2));
            listArray.add(new DataModel("Class 3",3));
            listArray.add(new DataModel("Class 4",4));
            listArray.add(new DataModel("Class 5",5));
        }
   
        @Override
        public int getCount() {
            return listArray.size();    // total number of elements in the list
        }
   
        @Override
        public Object getItem(int i) {
            return listArray.get(i);    // single item in the list
        }
   
        @Override
        public long getItemId(int i) {
            return i;                   // index number
        }
   
        @Override
        public View getView(int index, View view, final ViewGroup parent) {
   
            if (view == null) {
                LayoutInflater inflater = LayoutInflater.from(parent.getContext());
              // view = inflater.inflate(R.layout.single_list_item, parent, false);
                view = inflater.inflate(R.layout.linear_test,parent,false);
            }
   
            //final DataModel dataModel = listArray.get(index);
           final  DataModel  dataModel = listArray.get(index);
   
           /* TextView textView = (TextView) view.findViewById(R.id.tv_string_data);
            textView.setText(dataModel.getName());
   
            Button button = (Button) view.findViewById(R.id.btn_number_data);
            button.setText("" + dataModel.getAnInt());
   
            textView = (TextView) view.findViewById(R.id.tv_double_data);
            textView.setText("" + dataModel.getaDouble()); */
           
         TextView textView = (TextView) view.findViewById(R.id.tv_question);
         textView.setText(dataModel.getName());
   
         Button btnyes = (Button) view.findViewById(R.id.button2);
         Button btnno = (Button) view.findViewById(R.id.button1);
        
        
         btnyes.setOnClickListener(new View.OnClickListener() {
           
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                //Toast.makeText(parent.getContext(), "Button Clicked"+ dataModel.getName(),Toast.LENGTH_LONG).show();
                //Intent yes= new Intent(parent.getContext(), yes(dataModel.getName().class));
                switch( dataModel.getAnInt()){
                case 1:
                    Intent intent = new Intent(parent.getContext(),Yes1.class);
                    parent.getContext().startActivity(intent);
                    break;
                   
                case 2:
                    Toast.makeText(parent.getContext(), "Button Clicked"+ dataModel.getName(),Toast.LENGTH_LONG).show();
                showmessagebox(parent.getContext(),dataModel.getName(),dataModel.getAnInt());
                    break;
   
                case 3:    
                    Toast.makeText(parent.getContext(), "Button Clicked"+ dataModel.getName(),Toast.LENGTH_LONG).show();
                default:
               
                }
               
            }
        });
        
        

        
        
        
        // button click listener
            // this chunk of code will run, if user click the button
            // because, we set the click listener on the button only
   
           /* button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Log.d(TAG, "string: " + dataModel.getName());
                 //   Log.d(TAG, "int: " + dataModel.getAnInt());
                  //  Log.d(TAG, "double: " + dataModel.getaDouble());
                   // Log.d(TAG, "otherData: " + dataModel.getOtherData());
   
                    Toast.makeText(parent.getContext(), "button clicked: " + dataModel.getName(), Toast.LENGTH_SHORT).show();
                }
            });   */
   
   
            // if you commented out the above chunk of code and
            // activate this chunk of code
            // then if user click on any view inside the list view (except button)
            // this chunk of code will execute
            // because we set the click listener on the whole view
   
   
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Log.d(TAG, "string: " + dataModel.getName());
                   // Log.d(TAG, "int: " + dataModel.getAnInt());
                    //Log.d(TAG, "double: " + dataModel.getaDouble());
                    //Log.d(TAG, "otherData: " + dataModel.getOtherData());
   
                    Toast.makeText(parent.getContext(), "view clicked: " + dataModel.getName(), Toast.LENGTH_SHORT).show();
                }
            });
   
            return view;
        }



        public void showmessagebox(final Context context, String msg, final int position)
        {
            AlertDialog ad = new AlertDialog.Builder(context)
            .setMessage(msg)
            .setIcon(R.drawable.ic_launcher)
            .setTitle("Terms of Service")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    switch(position){
                    case 1:


                        break;
                       
                    case 2:
                        Intent intent = new Intent(context,Yes1.class);
                        context.startActivity(intent);
                        break;
       
                    case 3:    


                    default:
                   
                    }

                }

               
            })
       // .setNegativeButton("No", this)
        //    .setNeutralButton("Cancel", this)
            .setCancelable(false)
            .create();
            ad.show();   
        }
   
}
Read more ...

Saturday, September 6, 2014

OnClick Listner on Button on ListView/ Base Adaptor

Here is how i did onClick Listner event on button on ListView with startActivity inside BaseAdaptor.


main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent" >
    <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="ListView Button Click Example" />

    <ListView android:id="@+id/list_data"
              android:layout_height="match_parent"
              android:layout_width="match_parent" />
</LinearLayout>



linear_test.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layoutContainer"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="5"
    android:orientation="horizontal" >

    <LinearLayout
        android:id="@+id/LinearLayout1"
        android:layout_width="match_parent"
        android:layout_weight="3"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/tv_question"
            android:layout_width="wrap_content"
            android:layout_height="48dp"
            android:text="Are you Sure want to make sure you can do this ?" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/LinearLayout1"
        
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Yes" />

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="No" />
    </LinearLayout>

</LinearLayout>



MainActivity.java


package com.example.dlistview;

import java.util.ArrayList;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.os.Build;
import android.app.Activity;
import android.view.ViewGroup.LayoutParams;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
           
            final String TAG = MainActivity.class.getSimpleName();
       
                ListView listView = (ListView) findViewById(R.id.list_data);
       
                CustomAdapter customAdapter = new CustomAdapter();
       
                listView.setAdapter(customAdapter);
       

            }
        }   



dataModel.java

package com.example.dlistview;

public class DataModel {
    private String name;
   private int anInt;


    public DataModel(String name, int anInt) {
        this.name = name;
        this.anInt=anInt;
      
    }



    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAnInt() {
        return anInt;
    }

    public void setAnInt(int anInt) {
        this.anInt = anInt;
    }
}



CustomAdaptor.java

package com.example.dlistview;

import java.util.ArrayList;

import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class CustomAdapter extends BaseAdapter {

     private static final String TAG = CustomAdapter.class.getSimpleName();
        ArrayList<DataModel> listArray;
   
        public CustomAdapter() {
           
            listArray = new ArrayList<DataModel>(5);
            listArray.add(new DataModel("Class 1",1));
            listArray.add(new DataModel("Class 2",2));
            listArray.add(new DataModel("Class 3",3));
            listArray.add(new DataModel("Class 4",4));
            listArray.add(new DataModel("Class 5",5));
        }
   
        @Override
        public int getCount() {
            return listArray.size();    // total number of elements in the list
        }
   
        @Override
        public Object getItem(int i) {
            return listArray.get(i);    // single item in the list
        }
   
        @Override
        public long getItemId(int i) {
            return i;                   // index number
        }
   
        @Override
        public View getView(int index, View view, final ViewGroup parent) {
   
            if (view == null) {
                LayoutInflater inflater = LayoutInflater.from(parent.getContext());
                    view = inflater.inflate(R.layout.linear_test,parent,false);
            }
   
            final DataModel dataModel = listArray.get(index);
   
           
         TextView textView = (TextView) view.findViewById(R.id.tv_question);
         textView.setText(dataModel.getName());
   
         Button btnyes = (Button) view.findViewById(R.id.button2);
         Button btnno = (Button) view.findViewById(R.id.button1);
        
        
         btnyes.setOnClickListener(new View.OnClickListener() {
           
            @Override
            public void onClick(View v) {
                   switch( dataModel.getAnInt()){
                case 1:
                    Intent intent = new Intent(parent.getContext(),Yes1.class);
                    parent.getContext().startActivity(intent);
                   
                   
                case 2:
                    Toast.makeText(parent.getContext(), "Button Clicked"+ dataModel.getName(),Toast.LENGTH_LONG).show();
                   
                case 3:    
                    Toast.makeText(parent.getContext(), "Button Clicked"+ dataModel.getName(),Toast.LENGTH_LONG).show();
                default:
               
                }
               
            }
        });
             
   
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Log.d(TAG, "string: " + dataModel.getName());
                         Toast.makeText(parent.getContext(), "view clicked: " + dataModel.getName(), Toast.LENGTH_SHORT).show();
                }
            });
   
            return view;
        }
    }


Here is the screenshot


Read more ...

Thursday, June 5, 2014

Dyanmic List using code

package com.example.dynamicview;

import java.util.ArrayList;

import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.os.Build;

public class MainActivity extends Activity {

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

       
//        String[] StringArray = { "one", "two", "three", "four", "five" };
    /*    ArrayList<String> name = new ArrayList<String>();
        name.add("Google");
        name.add("Microsoft");
        name.add("Apple");
        name.add("Oracle");
        int topval=100;
       
        RelativeLayout layout = new RelativeLayout(this);
        RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        for (int i = 0; i < name.size(); i++) {
            TextView tv = new TextView(getApplicationContext());
            tv.setText(name.get(i));
            relativeParams.addRule(RelativeLayout.BELOW, tv.getId());
            relativeParams.topMargin=topval+100;
            layout.addView(tv, relativeParams);
        }       
       
        setContentView(layout);*/
       
        ArrayList<Person> namelist = new ArrayList<Person>();
        namelist.add(new Person("Ram","Bagbazar","98011234534"));
        namelist.add(new Person("Ram","Bagbazar","98011234534"));
        namelist.add(new Person("Ram","Bagbazar","98011234534"));
        namelist.add(new Person("Ram","Bagbazar","98011234534"));
        namelist.add(new Person("Ram","Bagbazar","98011234534"));
        namelist.add(new Person("Ram","Bagbazar","98011234534"));
        namelist.add(new Person("Ram","Bagbazar","98011234534"));
        namelist.add(new Person("Ram","Bagbazar","98011234534"));
        namelist.add(new Person("Ram","Bagbazar","98011234534"));
        namelist.add(new Person("Ram","Bagbazar","98011234534"));
        namelist.add(new Person("Ram","Bagbazar","98011234534"));
        namelist.add(new Person("Ram","Bagbazar","98011234534"));
        namelist.add(new Person("Ram","Bagbazar","98011234534"));
        namelist.add(new Person("Ram","Bagbazar","98011234534"));
        namelist.add(new Person("Ram","Bagbazar","98011234534"));
        namelist.add(new Person("Ram","Bagbazar","98011234534"));
        namelist.add(new Person("Ram","Bagbazar","98011234534"));
        namelist.add(new Person("Ram","Bagbazar","98011234534"));
       
        LinearLayout layout;
        layout = (LinearLayout) findViewById(R.id.wrapper);
       
        for(int i=0;i<namelist.size();i++){
       
    View row=    getLayoutInflater().inflate(R.layout.list_row, null);
       
        TextView list_name = (TextView) row.findViewById(R.id.list_text);
        TextView list_address = (TextView) row.findViewById(R.id.list_address);
        TextView list_phone = (TextView) row.findViewById(R.id.list_phone);
   
        list_name.setText(namelist.get(i).getName());
        list_address.setText(namelist.get(i).getAddress());
        list_phone.setText(namelist.get(i).getPhone());
       
        layout.addView(row);
        }
        //setContentView(layout);
}
}











//list_view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp" >
        <TextView
            android:id="@+id/tvName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:hint="Amir Shrestha"
            android:textSize="20sp" />
        <TextView
            android:id="@+id/tvPhone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/tvName"
            android:hint="9801165310" />
        <TextView
            android:id="@+id/tvAddress"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/tvPhone"
            android:layout_marginLeft="20dp"
            android:layout_toRightOf="@+id/tvName"
            android:hint="Dhapasi" />
        <View
            android:id="@+id/view1"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_alignRight="@+id/imPhone"
            android:layout_below="@+id/tvPhone"
            android:background="#B2BEB5"
            android:paddingBottom="10dp"
            android:paddingTop="10dp" />
        <ImageView
            android:id="@+id/imPhone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:layout_marginRight="20dp"
            android:src="@android:drawable/ic_menu_call" />
    </RelativeLayout>
</LinearLayout>


//activity_main.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
   
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    >
   
   
    <LinearLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    android:id="@+id/wrapper">
   
   

</LinearLayout>
   
   

</RelativeLayout>
</ScrollView>
Read more ...

Dynamic Array and component intialization in Android

package com.example.dynamicview;

import java.util.ArrayList;

import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.os.Build;

public class MainActivity extends Activity {

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

       
//        String[] StringArray = { "one", "two", "three", "four", "five" };
        ArrayList<String> name = new ArrayList<String>();
        name.add("Google");
        name.add("Microsoft");
        name.add("Apple");
        name.add("Oracle");
        int topval=100;
       
        RelativeLayout layout = new RelativeLayout(this);
        RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        for (int i = 0; i < name.size(); i++) {
            TextView tv = new TextView(getApplicationContext());
            tv.setText(name.get(i));
            relativeParams.addRule(RelativeLayout.BELOW, tv.getId());
            relativeParams.topMargin=topval+100;
            layout.addView(tv, relativeParams);
        }       
       
        setContentView(layout);
    }
   

}
Read more ...

Wednesday, January 29, 2014

Access Control List (ACL) using setfacl/getfacl in Linux


Access Control List using setfacl/getfacl in Linux

The basic Linux permission model lets you specify permissions for the file's owner and group, and all others. This article assumes that you are familiar with the basic permissions, and know how to set them. The Access Control List (ACL) feature extends the model to allow much finer control: you can specify permissions for each individual user and group defined in your system.

Consider this scenario: your server supports multiple office departments: Sales, Marketing, and Helpdesk. Each department has a manager, and one or more staff members.

You define a group for each department that comprises of its manager and staff members: sales-g, marketing-g, and helpdesk-g. Then, you also define a managers only group: managers-g.

It is normal that some departments need to share files among each other, but not with all departments. For instance, Sales needs to share a file with Marketing, but not with HelpDesk. To set that up using only the basic permissions, you can define yet more groups: sales-marketing-g, sales-marketing-managers-g, etc.

Alternatively, you can use ACL to assign permissions to individual group and user.

Before you can use ACL, you must explicitly turn it on for the partitions you want to have the ACL feature available.

As root, edit /etc/fstab. Find the partition that you want ACL enabled, and add the mount option acl.
/dev/mapper/allabtlinux-home /home ext3  defaults,acl 0 2


Next, assuming that your partition is already mounted, then either reboot the system, or better yet, remount dynamically:
mount -o remount,acl /home
                                                            

Next, you need to make sure that you have 2 ACL utilities installed: getfacl, and setfacl.

On a Debian/Ubuntu system, install the utilities like this:
$ apt-get install acl


Now, you are ready to take ACL using getfacl and setfacl command.

Let's start simple: you have a file /home/linuxacldemo/demofile.txt that you want to share between sales-g, marketing-g, and an user named aarav.
$ cd /home/linuxacldemo
$ ls -l
total 64
-rw-r--r-- 1 linuxacldemo linuxacldemo 80000 2013-12-28 10:55 demofile.txt


Use setfacl -m to set Access Control List for the file.
$ setfacl -m group:sales-g:rw-   demofile.txt


The group:sales-g:rw- parameter specifies Read and Write permissions (rw) for the group: sales-g.

To enable the Read/Write permissions for the Marketing department, and aarav the user:
$ setfacl -m group:marketing-g:rw-,user:aarav:rw- demofile.txt
$ ls -l
total 68
-rw-rw-r--+ 1 linuxacldemo linuxacldemo 8000 2013-12-28 10:55 demofile.txt


Note that ls -l does not display the actual ACL of a file. It only tells you that ACL is defined for that file: a plus character (+) is displayed to the right of the permissions.

To examine the actual ACL, run getfacl.
$ getfacl demofile.txt
# file: demofile.txt
# owner: linuxacldemo
# group: linuxacldemo
user::rw-
user:aarav:rw-
group::r--
group:sales-g:rw-
group:marketing-g:rw-
mask::rw-
other::r--


Often, you want to share files among certain groups and specific users. It is a good practice to designate a directory for that purpose. You want to allow those groups and users to read, and write files in that directory, as well as create new files into the directory.

Let's first create the directory named testacldirectory.
$ mkdir testacldirectory
$ ls -ld testacldirectory/
drwxr-xr-x 2 linuxacldemo linuxacldemo 4096 2013-12-28 14:33 testacldirectory/


We want to share the directory among the marketing-g and sales-g groups and the user named aarav. Sales, marketing and aarav need to have full access to the directory including the creation of new files in that directory.
$ setfacl -m user:aarav:rwx,group:sales-g:rwx,group:marketing-g:rwx testacldirectory
$ getfacl testacldirectory/
# file: testacldirectory
# owner: linuxacldemo
# group: linuxacldemo
user::rwx
user:aarav:rwx
group::r-x
group:sales-g:rwx
group:marketing-g:rwx
mask::rwx
other::r-x


OK, aarav, go ahead to create a file in testacldirectory.
$ su - aarav
...
$ cd /home/linuxacldemo/testacldirectory
$ touch demofile.txt
$ ls -l demofile.txt
-rw-r--r-- 1 aarav aarav 0 2013-12-28 15:06 demofile.txt
$ getfacl demofile.txt
# file: demofile.txt
# owner: aarav
# group: aarav
user::rw-
group::r--
other::r--


Now, sales and marketing, and aarav can create or copy new files into testacldirectory.

There is a slight problem: only the creator of a file can edit it. Alas only aarav can modify the above targets file.

Yes, we can manually adjust the ACL of a file after its creation by running setfacl -m on the file. A much better way is to configure the testacldirectory directory such that by default all files created under it will automatically have the proper ACL.
$ setfacl -m d:user:aarav:rwx,d:group:sales-g:rwx,d:group:marketing-g:rwx testacldirectory


Note that the d in d:user:aarav:rwx means default. That is, all files created in testacldirectory will have by default read/write/execute permission for the user named aarav.
$ getfacl testacldirectory/
# file: testacldirectory
# owner: linuxacldemo
# group: linuxacldemo
user::rwx
user:aarav:rwx
group::r-x
group:sales-g:rwx
group:marketing-g:rwx
mask::rwx
other::r-x
default:user::rwx
default:user:aarav:rwx
default:group::r-x
default:group:sales-g:rwx
default:group:marketing-g:rwx
default:mask::rwx
default:other::r-x


Now, sales, marketing, and aarav can edit mutual files.

Don't believe me, aarav? See for yourself.
$ su - aarav
$ cd /home/linuxacldemo/testacldirectory
$ touch figures.txt
$ ls -l figures.txt
-rw-rw-r--+ 1 aarav aarav 0 2013-12-28 17:32 figures.txt
$ getfacl figures.txt
# file: figures.txt
# owner: aarav
# group: aarav
user::rw-
user:aarav:rwx                 #effective:rw-
group::r-x                      #effective:r--
group:sales-g:rwx               #effective:rw-
group:marketing-g:rwx           #effective:rw-
mask::rw-
other::r--


The ACL for the newly created figures.txt file is configured with the default entries from its parent directory.

To summarize, if you want to share a directory (say some_dir) between some_user and some_group such that both will have full access to the directory, including creating new files and modifying each others' files, run these commands:
$ setfacl -m   user:some_user:rwx,group:some_group:rwx    some_dir
$ setfacl -m d:user:some_user:rwx,d:group:some_group:rwx  some_dir


To remove the ACL from a file or directory, use setfacl -b like this:
$ setfacl -b /home/linuxacldemo/testacldirectory


Note that this removes all but the very basic user/group/others ACL entries. If all you want is to delete the default ACL for the directory, execute this instead:
$ setfacl -k /home/linuxacldemo/testacldirectory

you can fine more redhat/centos reference on https://access.redhat.com/site/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/Storage_Administration_Guide/ch-acls.html

Read more ...

using ifconfig command

Ifconfig  is  used to configure the kernel-resident network interfaces. It is used at boot time to set up interfaces as necessary.  After that,it  is  usually  only  needed  when  debugging or when system tuning is needed. The ifconfig command simply is used for displaying current network configuration information, setting up an ip address along with netmask or broadcast address to network interface, creating an alias for network interface as well setting up hardware address and enable or disable network interfaces.

Here is basic usages of ifconfig command based on  scenario 

Ø  To view all activated  network interfaces
root@server-82:~# ifconfig 

Ø  To view the all network interface
root@server-82:~# ifconfig -a

Ø  3. To view specific network interface
root@server-82:~# ifconfig eth0

Ø  4. How to enable/disable network interface
root@server-82:~# ifconfig eth0 up or ifup eth0
root@server-82:~# ifconfig eth0 down or ifdown eth0

Ø   To assign a Ip address/netmask to network interface
 root@server-82:~# ifconfig eth0 10.10.10.1 netmask 255.255.255.0

Please note that the previous ip address of network interface will overlapped
           with this new ip address assigned and is will temporarily assigned. If you donot want to change in its network configuration file for permanently assigned, you can put it in /etc/rc.local file for startup automatic ip address setup.

Ø  To assign a broadcast address
 root@server-82:~# ifconfig eth0 broadcast 10.10.10.255

Ø  To change MTU for an network interface
root@server-82:~# ifconfig eth0 mtu 1454

Ø  To enable/disable promiscuous mode
 
Generally when a packet is received by a network card, it verifies whether the packet belongs to itself or not, if not then it drops the packet however in promiscuous mode, the network card will accept all the packets passed through it.

root@server-82:~# ifconfig eth0 promisc (for enable)

root@server-82:~# ifconfig eth0 –promisc ( for disable)

Ø  To add/remove new alias to network interface

             The alias is needed when we need multiple range of ips in single interface or
             when you are making your network interface using as trunk for manageable switch.

root@server-82:~# ifconfig eth0:0  10.11.11.1 netmask 255.255.255.0
           root@server-82:~# ifconfig eth0:0 down ( To remove the alias)

Ø  To change mac address of network interface
 
root@server-82:~# ifconfig eth0 hw ether AA:BB:CC:DD:EE:FF

Read more ...

Monday, January 13, 2014

Enable Timestamps in History Command

History command is used to check the history of commands with command number and command but sometime when we need to check the date and time of the command entered then we need to enable timestamps but how :)

#To view the history commands
root@GW:~# history | more
 1030  route -n
 1031  ifconfig eth7 down
 1032  ifconfig eth7 up


The list of history command is found in your home directory with hidden filename .bash_history. Here is the partial view of the file

root@GW:~# cat .bash_history
route -n
ifconfig eth7 down
ifconfig eth7 up


Now enabling timestamps using following command
 root@GW:~# export HISTTIMEFORMAT="%F %T "

And here is the output now
root@GW:~# history | more
 1030  2014-01-13 13:43:14 route -n
 1031  2014-01-13 13:43:14 ifconfig eth7 down
 1032  2014-01-13 13:43:14 ifconfig eth7 up


This will temporarily enable timestamps for this sessions To make it permanent, Please do following 
root@GW:~# vi ~/.bashrc and enter the following lines @ top

HISTTIMEFORMAT="%F %T "

If you want to disable history command list temporarily then you can set HISTSIZE=0 in terminal and if you want to permanently disable then make HISTSIZE = 0 in .bashrc file.



 

Read more ...

Sunday, January 12, 2014

clearing arp cache in linux

 Arp manipulates or displays the kernel's IPv4 network neighbour cache.
 It can add entries to the table, delete one or display the current content.


ARP  stands  for Address Resolution Protocol, which is used to find the media access control address of a network neighbour for  a  given  IPv4 Address.

Command to list the current arp entries 

root@server-82:~# arp -n
Address                  HWtype  HWaddress           Flags Mask            Iface
1.1.1.1             ether   00:0f:f8:a6:6d:40   C                     eth0
1.1.1.2             ether   08:00:27:62:cd:e9   C                     eth0
root@server-82:~#



The following command will clear all the arp cache entries.
root@server-82: ~# ip -s -s neigh flush all

 Deleting arp entries of  specific host
root@server-82~# arp -d 1.1.1.1

Assigning static arp entries for specific host
root@server-82~# arp -s 1.1.1.1  00:0f:f8:a6:6d:40 
  
This will answer ARP requests for 1.1.1.1 on eth0 with the MAC address for eth1.
 arp -i eth0 -Ds 1.1.1.1 eth1 pub



Read more ...

Thursday, January 9, 2014

simple mac-binding using iptables

This script/article is useful when your have linux gateway as distribution and you want to bind the mac address of your client to specific ip address. We are using iptables here for this tasks.

#create a file called macfilter.sh using touch command with following contents

#!/bin/bash
#info@allaboutlinux.info


#display messages
echo "Mac Filter Staring"
/sbin/iptables -F             #flushing iptables rules


/sbin/iptables A INPUT -s ipaddress -m mac --mac-source macaddress -j ACCEPT
/sbin/iptables -A INPUT -s ipaddress -j DROP
/sbin/iptables -A INPUT -m mac --mac-source macaddress -j DROP

/sbin/iptables A FORWARD -s ipaddress -m mac --mac-source macaddress -j ACCEPT
/sbin/iptables -A FORWARD -s ipaddress -j DROP
/sbin/iptables -A FORWARD -m mac --mac-source macaddress -j DROP

echo "Mac Filter Applied"

Make sure you have given execute permission using chmod a+x /etc/macfilter.sh and put it in startup at /etc/rc.local :)


This is very basic script and need lots of lines if you have multiple clients. Here is simplified version using input from file.



#!/bin/bash
#info@allaboutlinux.info

echo "Mac Filter Staring"
/sbin/iptables -F             #flushing iptables rules



while read ipadd macadd clientname; do
        echo "Binding IP " $ipadd "with mac" $macadd  "of client" $clientname "\n"
        /sbin/iptables -A INPUT -s $ipadd -m mac --mac-source $macadd -j ACCEPT
        /sbin/iptables -A INPUT -s $ipadd -j DROP
        /sbin/iptables -A INPUT -m mac --mac-source $macadd -j DROP

        /sbin/iptables -A FORWARD -s $ipadd -m mac --mac-source $macadd -j ACCEPT
        /sbin/iptables -A FORWARD -s $ipadd -j DROP
        /sbin/iptables -A FORWARD -m mac --mac-source $macadd -j DROP

done < "/etc/mac.txt"


Create a file mac.txt in /etc with following contents in order
ipaddress       macaddress       clientname (just to show the order, donot include this in file)

1.1.1.1      00:00:00:11:11:11       ClientA

sample output 







Further the scripts can be make more efficient using perl or bash scripting with mysql as backend so that everything can be controlled from frontend without logging into the machine itself :) .




Read more ...

Apache Benchmark with ab command

ab command comes with apache server itself is used to benchmarking to simulate a high load to gather data for analysis. We can generate graphs using gnuplot from the data we get from ab tool.

Let's do some benchmarking for our server http://www.allaboutlinux.info/index.html

root@server-82:~# ab -n 1000 -c 50 -g allaboutlinuxdata.txt http://www.allaboutlinux.info/index.html

n = no of connection ( 1000 here)
c = no of concurrent user (50 here)

This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking www.allaboutlinux.info (be patient)
Completed 100 requests
Completed 200 requests
Completed 300 requests
Completed 400 requests
Completed 500 requests
Completed 600 requests
Completed 700 requests
Completed 800 requests
Completed 900 requests
Completed 1000 requests
Finished 1000 requests


Server Software:        GSE
Server Hostname:        www.allaboutlinux.info
Server Port:            80

Document Path:          /index.html
Document Length:        90579 bytes

Concurrency Level:      50
Time taken for tests:   1.702 seconds
Complete requests:      1000
Failed requests:        928
   (Connect: 0, Receive: 0, Length: 928, Exceptions: 0)
Write errors:           0
Non-2xx responses:      928
Total transferred:      7007408 bytes
HTML transferred:       6671096 bytes
Requests per second:    587.57 [#/sec] (mean)
Time per request:       85.097 [ms] (mean)
Time per request:       1.702 [ms] (mean, across all concurrent requests)
Transfer rate:          4020.83 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:       22   26   9.8     25     312
Processing:    26   57 119.8     29    1623
Waiting:       26   39  51.8     29     911
Total:         49   83 120.8     54    1650

Percentage of the requests served within a certain time (ms)
  50%     54
  66%     55
  75%     57
  80%     58
  90%     67
  95%    293
  98%    521
  99%    630
 100%   1650 (longest request)


Now we are going to generate graphs based on the data using gnuplot

root@server-82:~# gnuplot

        G N U P L O T
        Version 4.4 patchlevel 3
        last modified March 2011
        System: Linux 3.2.0-29-generic

        Copyright (C) 1986-1993, 1998, 2004, 2007-2010
        Thomas Williams, Colin Kelley and many others

        gnuplot home:     http://www.gnuplot.info
        faq, bugs, etc:   type "help seeking-assistance"
        immediate help:   type "help"
        plot window:      hit 'h'

Terminal type set to 'wxt'
gnuplot> set terminal png
Terminal type set to 'png'
Could not find/open font when opening font "/usr/share/fonts/truetype/ttf-liberation/LiberationSans                                                                     -Regular.ttf", using internal non-scalable font
Options are 'nocrop medium size 640,480 '
gnuplot>  set output "ABRallaboutlinux.png"
gnuplot>  set title "Apache Benchmark for Allaboutlinux.info"
gnuplot> set xlabel 'request'
gnuplot>  set ylabel 'ms'
gnuplot> plot "allaboutlinuxdata.txt" using 10 with lines title 'Benchmark from allaboutlinux'
gnuplot>
gnuplot>
gnuplot>
gnuplot>


And here is the graphs


Read more ...

Wednesday, January 8, 2014

command to find number of running process in linux using pgrep

pgrep looks through the currently running processes and lists the process IDs which matches the selection criteria to stdout.  

#pgrep processname will returns process id for that processname. 
root@server-82:~# pgrep apache
19823
22774
22843
22902
22918
22949
22982
22994
23291
23351
23382
root@server-82:~#


#counting number of running processes using pgrep
root@server-82:~# pgrep apache | wc -l
11
root@server-82:~#
 

#counting number of processes under  username root
root@server-82:~# pgrep -u root apache | wc -l
1
root@server-82:~#

Here root is username and apache is process.

#counting number of processes under username www-data for user root
root@server-82:~# pgrep -u www-data apache | wc -l
10
root@server-82:~#
 



 




Read more ...