Wednesday, November 7, 2012

How do I convert array into JSON?


Date: 2010-09-16. Category: com.google.gson examples. Hits: 12K time(s).
In the example below you can see how to convert an array into JSON string. We serialize the array to JSON using the Gson.toJson() method. To deserialize a string of JSON into array we use the Gson.fromJson() method.

5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package org.kodejava.example.google.gson;
 
import com.google.gson.Gson;
 
public class ArrayToJson {
    public static void main(String[] args) {
        int[] numbers = {1, 1, 2, 3, 5, 8, 13};
        String[] days = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
 
        //
        // Create a new instance of Gson
        //
        Gson gson = new Gson();
 
        //
        // Convert numbers array into JSON string.
        //
        String numbersJson = gson.toJson(numbers);
 
        //
        // Convert strings array into JSON string
        //
        String daysJson = gson.toJson(days);
        System.out.println("numbersJson = " + numbersJson);
        System.out.println("daysJson = " + daysJson);
 
        //
        // Convert from JSON string to a primitive array of int.
        //
        int[] fibonacci = gson.fromJson(numbersJson, int[].class);
        for (int i = 0; i < fibonacci.length; i++) {
            System.out.print(fibonacci[i] + " ");
        }
        System.out.println("");
 
        //
        // Convert from JSON string to a string array.
        //
        String[] weekDays = gson.fromJson(daysJson, String[].class);
        for (int i = 0; i < weekDays.length; i++) {
            System.out.print(weekDays[i] + " ");
        }
        System.out.println("");
 
        //
        // Converting multidimensional array into JSON
        //
        int[][] data = {{1, 2, 3}, {3, 4, 5}, {4, 5, 6}};
        String json = gson.toJson(data);
        System.out.println("Data = " + json);
 
        //
        // Convert JSON string into multidimensional array of int.
        //
        int[][] dataMap = gson.fromJson(json, int[][].class);
        for (int i = 0; i < data.length; i++) {
            for (int j = 0; j < data[i].length; j++) {
                System.out.print(data[i][j] + " ");
            }
            System.out.println("");
        }
    }
}

Friday, July 6, 2012

JAVA StringWriter


http://www.codingdiary.com/developers/developers/diary/javaapi/java/io/SampleCode/StringWriterWriteExampleCode.html

Java StringWriter write() Example

StringWriter class write() method example. This example shows you how to use write() method.
Syntax is : public void write(char[] cbuf, int off, int len)
This method writes a subArray of specified array to StringWriter buffer.


Here is the code.

/**
 * @(#) WriteStringWriter.java
 * A class representing use of method write() of StringWriter class in 
 java.io Package.
 * @Version  29-May-2008
 @author   Rose India Team
 */
import java.io.*;
public class WriteStringWriter {
     public static void main(String[] args){

         char arrChar[] {' ','P','v','t','.',' ','i','n','d','i','a'};
    // Create object of StringWriter class
        StringWriter obj = new StringWriter();
        // append() method call.
        obj.append("Rose ");
    obj.append("India");
        System.out.println("String in string buffer is : " + obj);
    // write() method call.
    obj.write(arrChar,0,5);
    System.out.println("After writing a sub array StringBuffer is : "+obj);
    }
}


Output of the program.

String in string buffer is : Rose India
After writing a sub array StringBuffer is : Rose India Pvt.

ARRAY LIST IN JAVA


http://www.java-samples.com/showtutorial.php?tutorialid=234

The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed. In Java, standard arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold. But, sometimes, you may not know until run time precisely how large of an array you need. To handle this situation, the collections framework defines ArrayList. In essence, an ArrayList is a variable-length array of object references. That is, an ArrayList can dynamically increase or decrease in size. Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk.
ArrayList has the constructors shown here:
 

ArrayList( )
ArrayList(Collection c)
ArrayList(int capacity)


The first constructor builds an empty array list. The second constructor builds an array list that is initialized with the elements of the collection c. The third constructor builds an array list that has the specified initial capacity. The capacity is the size of the underlying array that is used to store the elements. The capacity grows automatically as elements are added to an array list.
The following program shows a simple use of ArrayList. An array list is created, and then objects of type String are added to it. (Recall that a quoted string is translated into a String object.) The list is then displayed. Some of the elements are removed and the list is displayed again.
 
// Demonstrate ArrayList.
import java.util.*;
class ArrayListDemo {
public static void main(String args[]) {
// create an array list
ArrayList al = new ArrayList();
System.out.println("Initial size of al: " +
al.size());
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " +
al.size());
// display the array list
System.out.println("Contents of al: " + al);
// Remove elements from the array list
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " +
al.size());
System.out.println("Contents of al: " + al);
}
}

 
The output from this program is shown here:
Initial size of al: 0
Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]
Notice that a1 starts out empty and grows as elements are added to it. When elements are removed, its size is reduced.
Although the capacity of an ArrayList object increases automatically as objects are stored in it, you can increase the capacity of an ArrayList object manually by calling ensureCapacity( ). You might want to do this if you know in advance that you will be storing many more items in the collection that it can currently hold. By increasing its capacity once, at the start, you can prevent several reallocations later. Because reallocations are costly in terms of time, preventing unnecessary ones improves performance. The signature for ensureCapacity( ) is shown here:
void ensureCapacity(int cap)
Here, cap is the new capacity. Conversely, if you want to reduce the size of the array that underlies an ArrayList object so that it is precisely as large as the number of items that it is currently holding, call
trimToSize( )
, shown here:
void trimToSize( ) Obtaining an Array from an ArrayList
When working with ArrayList, you will sometimes want to obtain an actual array that contains the contents of the list. As explained earlier, you can do this by calling toArray( ). Several reasons exist why you might want to convert a collection into an array such as:
• To obtain faster processing times for certain operations.
• To pass an array to a method that is not overloaded to accept a collection.
• To integrate your newer, collection-based code with legacy code that does not understand collections.
Whatever the reason, converting an ArrayList to an array is a trivial matter, as the following program shows:
 
// get array
Object ia[] = al.toArray();
int sum = 0;
// sum the array
for(int i=0; i<ia.length; i++)
sum += ((Integer) ia[i]).intValue();
System.out.println("Sum is: " + sum);
}

 
The output from the program is shown here:
 

Contents of al: [1, 2, 3, 4]
Sum is: 10


The program begins by creating a collection of integers. As explained, you cannot store primitive types in a collection, so objects of type Integer are created and stored. Next, toArray( ) is called and it obtains an array of Objects. The contents of this array are cast to Integer, and then the values are summed.

Wednesday, July 4, 2012

CONNECT SSH IN PHP

 
Secara default PHP tidak menyertakan library untuk melakukak SSH. Pada posting ini akan coba dijelasakan untuk melakukan Connection SSH melalui PHP.

Spesifikasi komputer pada posting ini adalah :
  • Operating System Linux Ubuntu Lucid Lynx
  • PHP version 5.3.2
Agar PHP dapat melakukan SSH membutuhkan sebuah library. Library tersebut adalah PHP Secure Communications Library atau biasa di singkat phpseclib

phpseclib adalah sebuah library PHP untuk melakukan berbagai komunikasi melalui SSH, SFTP, Aritmatika Presisi dan berbagai macam Kriptografi. Berikut ini adalah cara menggunakan libary phpseclib untuk SSH.
  1. Download library phpseclib di http://phpseclib.sourceforge.net/
  2. Ekstrak phpseclib0.2.1a.zip di www root/public html web server Anda.
  3. Kemudian buat sebuah file pada folder hasil ekstrak phpseclib0.2.1a.zip lalu sebagi contoh ketikan perintah seperti dibawah ini
  1. <?php  
  2.     include('Net/SSH2.php');  
  3.   
  4.     $ssh = new Net_SSH2('127.0.0.1');  
  5.     if (!$ssh->login('dendie''xxx')) {  
  6.         exit('Login Failed');  
  7.     }  
  8.     echo $ssh->exec('ls');  
  9. ?>  

Pada contoh diatas malakukan connection ssh ke komputer 127.0.0.1 dengan username name dendie dan password xxx Dan $ssh->exec('pwd') adalah perintah command line linux untuk mendapatkan alamat path aktif berada. Hasil perintah di atas adalah sebagai berikut
  1. /home/dendie   

Sebagai Contoh dalam pengembangan selanjutnya Connection SSH melalui PHP dapat dikembangkan untuk melakukan monitoring kapasitas harddisk, CPU Usage, Memori Usage dsb, secara bersamaan dan secara remote kebanyak komputer/server, kemudian hasilnya ditampilkan pada web-page, seperti contoh dibawah ini:



Untuk mempermudah melakukan monitoring serprti di atas dapat menggunakan class actServer, silakan download di klik download

Berikut ini adalah cara menggunakan-nya:
  1. include('actServer.php')  
  2. error_reporting(0);  
  3.   
  4. $act = new actServerClass();  
  5. $act->setServer('127.0.0.1','username','password');  
  6. echo $act->getCpuUsePer(). ' %'//CPU Active processes dalam persen  
  7. echo act->getMemUsePer(). ' %'//Memori Active processes dalam persen  
  8. echo $act->getMemUse(); //Memori Usage (megabyte)  
  9. echo $act->getSpace();  //Harddisk Space  
  10. echo $act->getDetail('mem'); //Detail Active processes Memori  
  11. echo $act->getDetail('cpu'); //Detail Active processes CPU  
  12. $act->setflush()  

Tuesday, July 3, 2012

NGINX

http://blog.s13epy.web.id/instalasi-nginx.html

Apa sih nginx? Nginx adalah webserver sama seperti Apache dan Lighttpd, mungkin bedanya seperti yang saya cari di paman google, klo nginx banyak yang bilang lebih powerfull n lebih cepet, dibandingkan dengan Apache ataupun Lighttpd.
Disini saya akan melakukan instalasi Nginx di LinuxMint 8 (Helena) yang merupakan turunan dari ubuntu 9.10 (Karmic Koala).
Yang pertama kita Instalasi Nginx terlebih dahulu
sudo apt-get install nginx
atau bila kita ingin menggunakan source code
sudo wget http://sysoev.ru/nginx/nginx-0.6.36.tar.gz
tar -xzvf nginx-0.6.36.tar.gz
cd nginx-0.6.36.tar.gz
sudo apt-get install build-essential
./configure
make
sudo make install
untuk settingan di ubuntu ataupun turunannya
./configure –conf-path=/etc/nginx/nginx.conf \
–error-log-path=/var/log/nginx/error.log –pid-path=/var/run/nginx.pid \
–lock-path=/var/lock/nginx.lock –http-log-path=/var/log/nginx/access.log \
–http-client-body-temp-path=/var/lib/nginx/body –http-proxy-temp-path=/var/lib/nginx/proxy \
–http-fastcgi-temp-path=/var/lib/nginx/fastcgi –with-debug –with-http_stub_status_module \
–with-http_flv_module –with-http_ssl_module –with-http_dav_module
make
sudo make install
Setelah itu jalankan nginx
sudo /etc/init.d/nginx start
Agar setiap booting nginx dapat langsung berjalan
sudo update-rc.d nginx defaults
Untuk melihat apakah nginx telah berjalan ketikkan localhost pada browser.
Selanjutnya kita install paket php
sudo apt-get install php5-cgi php5-mysql php5-curl php5-gd php5-idn php-pear php5-imagick php5-imap php5-mcrypt php5-memcache php5-mhash php5-ming php5-pspell php5-recode php5-snmp php5-sqlite php5-tidy php5-xmlrpc php5-xsl
kemudian edit file /etc/php5/cgi/php.ini
sudo gedit /etc/php5/cgi/php.ini
Ubah cgi.fix_pathinfo = 0 menjadi 1
[...]
cgi.fix_pathinfo = 1
Kemudian install
sudo apt-get install spawn-fcgi
gunakan perintah berikut untuk menjalankan php cgi
sudo /usr/bin/spawn-fcgi -a 127.0.0.1 -p 9000 -u www-data -g www-data -f /usr/bin/php5-cgi -P /var/run/fastcgi-php.pid
tambahkan perintah di pada /etc/rc.local
[...]
/usr/bin/spawn-fcgi -a 127.0.0.1 -p 9000 -u www-data -g www-data -f /usr/bin/php5-cgi -P /var/run/fastcgi-php.pid
[...]
edit file nginx.conf
sudo gedit /etc/nginx/nginx.conf
edit bagian berikut
[...]
worker_processes 5;
[...]
keepalive_timeout 2;
[...]
Selajutnya mengubah path file default sesuai keinginan kita
sudo gedit /etc/nginx/sites-available/default
[...]
server {
listen 80;
server_name localhost;
access_log /var/log/nginx/localhost.access.log;
location / {
#root /var/www/nginx-default;
root /home/vq/public_html;
index index.php index.html index.htm;
}
location /doc {
root /usr/share;
autoindex on;
allow 127.0.0.1;
deny all;
}
location /images {
root /usr/share;
autoindex on;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
#root /var/www/nginx-default;
root /home/vq/public_html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
#proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /home/vq/public_html$fastcgi_script_name;
include fastcgi_params;
}
# deny access to .htaccess files, if Apache’s document root
# concurs with nginx’s one
#
location ~ /\.ht {
deny all;
}
}
[...]
Terakhir kita tinggal melakukan restart nginx
sudo /etc/init.d/nginx restart
Untuk melihat apakah php-nya sudah berjalan
sudo gedit /home/vq/public_html/info.php
isi file info.php dengan kode berikut

Sunday, July 1, 2012

Login Logout CodeIgniter

http://www.codefactorycr.com/login-with-codeigniter-php.html


Simple Login with CodeIgniter in PHP

Apr 18, 2011   //   by aarias   //   Blog, PHP  //  No Comments
Code Igniter logoCodeIgniter is an open source Web Application framework built in PHP designed to make your life as a programmer easier, while allowing you good speed for development, and also good performance when the site is up and running.
Being a Java developer for almost 10 years now, when I had to move to PHP I chose CodeIgniter for the following reasons:
  • Easy to install and configure (being a newbie in PHP this was crucial)
  • Clean and elegant MVC implementation
  • Uses Active Record pattern for database access
  • Overall small footprint and good performance
Usually when you are building a program, the login/logout functionality is a must we always have to go through, so this quick tutorial will focus on this functionality, taking advantage of the benefits of using CodeIgniter instead of doing it from scratch in PHP.

Requirements

  • CodeIgniter framework.  By the time this tutorial was done, the latest version was 2.0.2
  • Any Apache/PHP/MySQL stack.  You can install the applications independently, or install one of those packages that have all of them bundled together.

Installing CodeIgniter

To install CodeIgniter, you only need to uncompress the Zip file you download from the site into your htdocs directory and you’re good to go.  We’ll configure the database access later.

Create the database

For this tutorial, you need a MySQL database with the following table:
1CREATE TABLE `users` (
2 `id` tinyint(4) NOT NULL AUTO_INCREMENT,
3 `username` varchar(10) NOT NULL,
4 `password` varchar(100) NOT NULL,
5 PRIMARY KEY (`id`)
6) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Remember also to add at least one user.  We’ll add one user called bob with password supersecret.
1insert into users (username, password) values ('bob', MD5('supersecret'));

Configure CodeIgniter

Database Access

Update the file application/config/database.php in your CodeIgniter installation with your database info:
44$db['default']['hostname'] = 'localhost';
45$db['default']['username'] = 'yourdbusername';
46$db['default']['password'] = 'yourdbpassword';
47$db['default']['database'] = 'yourdbname';

Default Controller

We need to tell CodeIgniter to land into our login page instead of the default welcome page.  Update the file application/config/routes.php in your CodeIgniter installation with you controller’s name.  We’ll call our landing controller login.
41$route['default_controller'] = "login";

Default Libraries

In the file application/config/autoload.php you can configure the default libraries you want to load in all your controllers.  For our case, we’ll load the database and session libraries, since we want to handle user sessions, and also the URL helper for internal link generation
55$autoload['libraries'] = array('database','session');
67$autoload['helper'] = array('url');

Encryption Key

When you use the session library, you need to set the encryption_key in the file application/config/config.php.
227$config['encryption_key'] = 'REALLY_LONG_NUMBER';

The Code

Here are the actual Views, Controllers and Model we are using for the login functionality.

User Model (application/models/user/php)

1<?php
2Class User extends CI_Model
3{
4 function login($username, $password)
5 {
6   $this -> db -> select('id, username, password');
7   $this -> db -> from('users');
8   $this -> db -> where('username = ' . "'" . $username . "'");
9   $this -> db -> where('password = ' . "'" . MD5($password) . "'");
10   $this -> db -> limit(1);
11 
12   $query = $this -> db -> get();
13 
14   if($query -> num_rows() == 1)
15   {
16     return $query->result();
17   }
18   else
19   {
20     return false;
21   }
22 }
23}
24?>

Login Controller (application/controllers/login.php)

1<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
2 
3class Login extends CI_Controller {
4 
5 function __construct()
6 {
7   parent::__construct();
8 }
9 
10 function index()
11 {
12   $this->load->helper(array('form', 'url'));
13   $this->load->view('login_view');
14 }
15 
16}
17 
18?>

Login View (application/views/login_view.php)

1<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3 <head>
4   <title>Simple Login with CodeIgniter</title>
5 </head>
6 <body>
7   <h1>Simple Login with CodeIgniter</h1>
8   <?php echo validation_errors(); ?>
9   <?php echo form_open('verifylogin'); ?>
10     <label for="username">Username:</label>
11     <input type="text" size="20" id="username" name="username"/>
12     <br/>
13     <label for="password">Password:</label>
14     <input type="password" size="20" id="passowrd" name="password"/>
15     <br/>
16     <input type="submit" value="Login"/>
17   </form>
18 </body>
19</html>

VerifyLogin Controller (application/controllers/verifylogin.php)

This controller does the actual validation of the fields and checks the credentials against the database.
1<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
2 
3class VerifyLogin extends CI_Controller {
4 
5 function __construct()
6 {
7   parent::__construct();
8   $this->load->model('user','',TRUE);
9 }
10 
11 function index()
12 {
13   //This method will have the credentials validation
14   $this->load->library('form_validation');
15 
16   $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
17   $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
18 
19   if($this->form_validation->run() == FALSE)
20   {
21     //Field validation failed.  User redirected to login page
22     $this->load->view('login_view');
23   }
24   else
25   {
26     //Go to private area
27     redirect('home', 'refresh');
28   }
29 
30 }
31 
32 function check_database($password)
33 {
34   //Field validation succeeded.  Validate against database
35   $username = $this->input->post('username');
36 
37   //query the database
38   $result = $this->user->login($username, $password);
39 
40   if($result)
41   {
42     $sess_array = array();
43     foreach($result as $row)
44     {
45       $sess_array = array(
46         'id' => $row->id,
47         'username' => $row->username
48       );
49       $this->session->set_userdata('logged_in', $sess_array);
50     }
51     return TRUE;
52   }
53   else
54   {
55     $this->form_validation->set_message('check_database', 'Invalid username or password');
56     return false;
57   }
58 }
59}
60?>

Home Controller (application/controllers/home.php)

This is the private page (only authenticated users can access it).
1<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
2session_start(); //we need to call PHP's session object to access it through CI
3class Home extends CI_Controller {
4 
5 function __construct()
6 {
7   parent::__construct();
8 }
9 
10 function index()
11 {
12   if($this->session->userdata('logged_in'))
13   {
14     $session_data = $this->session->userdata('logged_in');
15     $data['username'] = $session_data['username'];
16     $this->load->view('home_view', $data);
17   }
18   else
19   {
20     //If no session, redirect to login page
21     redirect('login', 'refresh');
22   }
23 }
24 
25 function logout()
26 {
27   $this->session->unset_userdata('logged_in');
28   session_destroy();
29   redirect('home', 'refresh');
30 }
31 
32}
33 
34?>

Home Page View (application/views/home_view.php)

1<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3 <head>
4   <title>Simple Login with CodeIgniter - Private Area</title>
5 </head>
6 <body>
7   <h1>Home</h1>
8   <h2>Welcome <?php echo $username; ?>!</h2>
9   <a href="home/logout">Logout</a>
10 </body>
11</html> 
The code is pretty easy to follow and understand.  Also, you can download the code from here, so you can install it and test it in your location.  You’ll only need a full installation of CodeIgniter 2.0.2 and the table in your MySQL database.  If you need any help, feel free to leave us a comment or shoot us an email.
Also, this code uses a pretty basic form validation from CodeIgniter.  If you need a more complex validation process, check CodeIgniter’s Form Validation docs at their site.