Thursday, January 19, 2017

Shell script: How to loop through directory

Hi

Today we will learn, how to loop through directory or folder with shell script.

Some days ago, working on a project, we have a requirement where we have to change the origin of a app directory. Because we have shifted our git repository to another server. There were 500 apps. So changing manually for each directory, it was time consuming.

What we do then, made a shell script for looping through each directory and excute a command to change origin.

First I made a origin.sh file in root folder and put the below script in that file.

 #!/bin/bash  
 for f in /home/username/your_directory_path/apps/*;  
  do   
    [ -d $f ] && cd "$f" && git remote set-url origin your_new_origin_url  
  done;  

And now run the file with below command in terminal

 sh ./origin.sh  


By running this command, it will excute the command written in origin.sh file.
It will loop through each directory of given path and excute the command.

Thanks

Sunday, January 8, 2017

Laravel migration : Resetting and Re-running all

Hi

Today we will learn how to resetting migration and re-running in laravel.

To reset migration we use command

 php artisan migrate:reset  

and to run migration we use command

 php artisan migrate  


But running above 2 command, we can do it by 1 command.

 php artisan migrate:refresh  

By running above command, it will reset and and run all the migration again.

Thanks

Tuesday, December 27, 2016

How to upload multiple array of images in laravel

Hi

First of all Happy New Year to all of you.

Today we will learn how to upload multiple array of images in laravel.

When we build dynamic view to add images then we put our field name in array. Like below

 <input type="file" name="images[]" accept="image/*" class="input-group">  


For saving these kind of file or images we needed a controller in laravel.

Below is my controller code for uploading files and images:

 <?php  
 namespace App\Http\Controllers;  
 use Validator;  
 use Redirect;  
 use Request;  
 use Session;  
 class FileController extends Controller {  
  public function multiple_upload(Request $request) {  
   // getting all of the images form post data  
   $fileName=$request->file('images');  
   // Making counting of uploaded images  
   $file_count = count($fileName);  
   // $uploadcount = 0;  
   foreach($fileName as $file) {  
    $rules = array('images' => 'required'); //'required|mimes:png,gif,jpeg,txt,pdf,doc': if we want to validate specific extension  
    $validator = Validator::make(array('images'=> $file), $rules);  
    if($validator->fails()){  
     $destinationPath = public_path("/images");  
     $file = $file->getClientOriginalName();  
     $upload_success = $file->move($destinationPath, $file);  
     $uploadcount ++;  
    }  
   }  
   if($uploadcount == $file_count){  
    Session::flash('success', 'Upload successfully');  
    return Redirect::to('your_route_name');  
   }  
   else {  
    return Redirect::to('your_route_name')->withInput()->withErrors($validator);  
   }  
  }  

Thanks.


Thursday, December 15, 2016

Running Laravel Queue Listner with Supervisor

Hi

Today, we learn how to run queue listener with supervisor.

To run Laravel's queue listener, we use below command:

 php artisan queue:listen --timeout=60 --tries=3 

However this process won't be restarted when the process ends. So We have to use Supervisor to keep this queue listener process active at all times. Below are instructions for Ubuntu

Install Supervisor with following command

 sudo apt-get install supervisor

Ensure it's started with

 sudo service supervisor restart

Supervisor configuration files are typically stored in the /etc/supervisor/conf.d directory. Within this directory, we may create any number of configuration files that instruct supervisor how our processes should be monitored. For example, let's create a laravel-queue.conf file that starts and monitors a queue:listen process:

To create laravel_queue.conf file, run following command

 sudo nano /etc/supervisor/conf.d/laravel_queue.conf

 [program:laravel_queue]
 process_name=%(program_name)s_%(process_num)02d
 command=php /home/username/path_to_laravel/artisan queue:listen --timeout=60 --tries=2
 autostart=true
 autorestart=true 
 user=username 
 stderr_logfile=/var/log/laraqueue.err.log
 stdout_logfile=/var/log/laraqueue.out.log 
 

Now give it execute permissions:

 chmod +x /etc/supervisor/conf.d/laravel_queue.conf

Once the configuration file will be created, we update the Supervisor configuration and start the processes using the following commands:

 sudo supervisorctl reread  
 
 sudo supervisorctl update
 
 sudo supervisorctl start laravel-worker:*  

Below 2 command are necessary, whenever we will change our configuration file.

 sudo supervisorctl reread  
 sudo supervisorctl update  

Thanks

Thursday, December 8, 2016

Time Synchronisation with NTP

Last week working on one of project, I found that my server UTC time is running 2 min 30 seconds behind actual UTC time.

I asked one of my senior and he told me to run following command :

 sudo ntpdate pool.ntp.org  

This gave me the desired result and my server time is synched with actual UTC time.

After that I googled the command and found more facts about this.

What is NTP

NTP (Network Time Protocol)  is a TCP/IP protocol for synchronising time over a network. Basically a client requests the current time from a server, and uses it to set its own clock.

For fixing the time I run the "ntpdate" command but "ntpdate" is not an action that should be taken regularly because it syncs the virtual server’s time so quickly, the jump in time may cause issues with time sensitive software. Therefore, it is best to run this only once, prior to setting up NTP, and then let NTP take over—otherwise, if the server’s time is too far off, NTP may not launch altogether.

Installing the NTP

To download or install NTP, run the following command on Ubuntu

 sudo apt-get install ntp  

Configuring the NTP Servers

After installing, open the following configuration file

 sudo nano /etc/ntp.conf  

It will show the lists of NTP Pool Project servers like below

 server 0.ubuntu.pool.ntp.org;  
 server 1.ubuntu.pool.ntp.org;  
 server 2.ubuntu.pool.ntp.org;  
 server 3.ubuntu.pool.ntp.org;  

Each line then refers to a set of hourly-changing random servers that provide our server with the correct time. The servers that are set up are located all around the world, and we can see the details of the volunteer servers that provide the time with the following command

 ntpq -p  

This command will output like below

  remote      refid   st t when poll reach  delay  offset jitter  
 ================================================================  
 -mail.fspproduct 209.51.161.238  2 u  50 128 377  1.852  2.768  0.672  
 *higgins.chrtf.o 18.26.4.105   2 u 113 128 377  14.579  -0.408  2.817  
 +mdnworldwide.co 108.71.253.18  2 u  33 128 377  47.309  -0.572  1.033  
 -xen1.rack911.co 209.51.161.238  2 u  44 128 377  87.449  -5.716  0.605  
 +europium.canoni 193.79.237.14  2 u 127 128 377  75.755  -2.797  0.718  

Although these servers will accomplish the task of setting and maintaining server time, we can set our time much more effectively by limiting the ntp to the ones in our region (europe, north-america, oceania or asia), or even to the ones in our country, for example in America:

 us.pool.ntp.org  

We can find the list international country codes (although not all of the countries have codes) here

Once all of the information is in the configuration file, restart ntp with following command:

 sudo service ntp restart  

NTP will slowly start to adjust the virtual private server’s time.

Thanks

Sunday, November 27, 2016

Swagger implementation in laravel 5

Hi Everybody

Today we will learn how to integrate swagger into laravel 5.

Swagger creates the RESTful contract for our API, detailing all of its resources and operations in a readable format for easy development and integration.

Installation

For Swagger 2.0

 composer require "darkaonline/l5-swagger:~3.0"  

Open your AppServiceProvider (located in app/Providers) and add this line in register function

  $this->app->register(\L5Swagger\L5SwaggerServiceProvider::class);  

open your config/app.php and add this line in providers section

 \L5Swagger\L5SwaggerServiceProvider::class  

Configuration

 Run php artisan l5-swagger:publish to publish everything  
 Run php artisan l5-swagger:publish-config to publish configs (config/l5-swagger.php)  
 Run php artisan l5-swagger:publish-assets to publish swagger-ui to your public folder (public/vendor/l5-swagger)  
 Run php artisan l5-swagger:publish-views to publish views (resources/views/vendor/l5-swagger)  
 Run php artisan l5-swagger:generate to generate docs or set generate_always param to true in your config or .env file  

Now open your controller and write following script above class definition to define basic information about your api.

 /**  
  * @SWG\Swagger(  
  *   schemes={"http","https"},  
  *   host="dev.eduru.com",  
  *   basePath="/",  
  *   @SWG\Info(  
  *     version="1.0.0",  
  *     title="This is my website cool API",  
  *     description="Api description...",  
  *     termsOfService="",  
  *     @SWG\Contact(  
  *       email="contact@mysite.com"  
  *     ),  
  *     @SWG\License(  
  *       name="Private License",  
  *       url="URL to the license"  
  *     )  
  *   ),  
  *   @SWG\ExternalDocumentation(  
  *     description="Find out more about my website",  
  *     url="http..."  
  *   )  
  * )  
  */  
 class ProductController extends Controller  


Write following script above your function where you have defined your api functionality.

 /**  
    * @SWG\Get(  
    *   path="/api/v1/products",  
    *   description="Returns all pets from the system that the user has access to",  
    *   operationId="findPets",  
    *   produces={"application/json", "application/xml", "text/xml", "text/html"},  
    *   @SWG\Parameter(  
    *     name="tags",  
    *     in="query",  
    *     description="tags to filter by",  
    *     required=false,  
    *     type="array",  
    *     @SWG\Items(type="string"),  
    *     collectionFormat="csv"  
    *   ),  
    *   @SWG\Parameter(  
    *     name="limit",  
    *     in="query",  
    *     description="maximum number of results to return",  
    *     required=false,  
    *     type="integer",  
    *     format="int32"  
    *   ),  
    *   @SWG\Response(  
    *     response=200,  
    *     description="pet response",  
    *     @SWG\Schema(  
    *       type="array",  
    *       @SWG\Items(ref="#/definitions/pet")  
    *     ),  
    *   ),  
    *   @SWG\Response(  
    *     response="default",  
    *     description="unexpected error",  
    *     @SWG\Schema(  
    *       ref="#/definitions/errorModel"  
    *     )  
    *   )  
    * )  
    */  
 /**  
    * Display a listing of the resource.  
    * 
    */  
   public function getProducts()  
   {  
     //  
   }  


Now run follwoing command to publish.

 php artisan l5-swagger:publish  

Now open following link in your browser

http://yourdomain.com/api/documentation

In above link, we can see our api documentation and its implementation.

Thanks

Sunday, November 20, 2016

Filesystem in laravel

Hi

Today we will learn, how to store file in laravel.

Laravel framework comes with built in storage handling which is compatible with a variety of systems. It is built upon the popular library Flysystem and therefore integrates with lots of services via the same common interface.

Storage configuration resides in the “config/filesystems.php” file. We can add multiple engines such as local drives and cloud drives.

Basic file operations

The filesystem integration provides a straight forward way of interacting with files. Basic write/read operations are illustrated below.

 // Write content to file  
 $content = 'File content ...';  
 Storage::put( 'my_file.txt', $content );  
 // Read content from file  
 $content = Storage::get( 'my_file.txt' );  
 // Delete file  
 Storage::delete( 'my_file.txt' );  
 You can also append/prepend content easily to existing files.  
 // Append content to file  
 $append = 'Appended text...';  
 Storage::append( 'my_file.txt', $append );  
 // Prepend content to file  
 $prepend = 'Prepended text...';  
 Storage::prepend( 'my_file.txt', $prepend );  

Listing files and directories

Sometimes we need to read your file structure which can be done with the listing methods.
We can list both files and directories in one level or recursively.

 // List all files in directory  
 $files = Storage::files($directory);  
 // List all files & directories in directory  
 $files = Storage::allFiles($directory);  
 // List all directories in directory  
 $directories = Storage::directories($directory);  
 // List all directories recursively in directory  
 $directories = Storage::allDirectories($directory);  


Thanks