Tuesday, 1 August 2017

Textual Representation of logo

Domain not available error Cloudhub Redeployment Issue

While deploying an application which was deployed successfully to Cloudhub previously using maven, I got the following error :
[INFO] Deploying application MyApp-dev to Cloudhub
[ERROR] Domain MyApp-dev is not available. Aborting.
[ERROR] Failed to deploy MyApp-dev: Domain MyApp-dev is not available. Aborting.
org.mule.tools.maven.plugin.mule.DeploymentException: Domain MyApp-dev is not available. Aborting.
                at org.mule.tools.maven.plugin.mule.cloudhub.CloudhubDeployer.deploy(CloudhubDeployer.java:89)
                at org.mule.tools.maven.plugin.mule.DeployMojo.deployWithDeployer(DeployMojo.java:216)
                at org.mule.tools.maven.plugin.mule.DeployMojo.cloudhub(DeployMojo.java:193)
                at org.mule.tools.maven.plugin.mule.DeployMojo.doExecute(DeployMojo.java:179)
                at org.mule.tools.maven.plugin.mule.AbstractMuleMojo.execute(AbstractMuleMojo.java:176)
                at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
                at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:207)
                at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
                at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
                at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
                at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
                at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
                at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
                at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
                at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
                at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
                at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863)
                at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288)
                at org.apache.maven.cli.MavenCli.main(MavenCli.java:199)
                at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
                at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
                at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
                at java.lang.reflect.Method.invoke(Method.java:498)
                at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
                at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
                at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
                at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)

This error comes only when the application already exists in Cloudhub. Ideally, it should just update the existing application in Cloudhub.
To rectify this error, you need to make sure that your application name in your pom file contains only lower case letters, because of a possible bug.
<applicationName>MyApp-${cloudHubAppSuffix}</applicationName>
So, the application name should be changed to :
<applicationName>myapp-${cloudHubAppSuffix}</applicationName>
Post Comments And Suggestions !!!

Wednesday, 19 July 2017

Textual Representation of logo

How to read and write XL Files in Java

Below Examples shows how to write and read XLSX and XLS files using Java .
package com.sun;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


/**
 * Created with IntelliJ IDEA.
 * User: javaroots
 * Date: 10/21/13
 * Time: 11:46 AM
 * To change this template use File | Settings | File Templates.
 */
public class XLSReader {

    public static void main(String[] args) throws IOException 
    {
        XSSFWorkbook workbook = new XSSFWorkbook();
     XSSFSheet sheet = workbook.createSheet("Employee Data");
        
        //This data needs to be written (Object[])
        Map data = new TreeMap();
        data.put("1", new Object[] {"ID", "NAME", "LASTNAME"});
        data.put("2", new Object[] {1, "Amit", "Shukla"});
        data.put("3", new Object[] {2, "Lokesh", "Gupta"});
        data.put("4", new Object[] {3, "John", "Adwards"});
        data.put("5", new Object[] {4, "Brian", "Schultz"});
        
        
        
        //Iterate over data and write to sheet
        Set keyset = data.keySet();
        int rownum = 0;
        for (String key : keyset)
        {
            Row row = sheet.createRow(rownum++);
            Object [] objArr = data.get(key);
            int cellnum = 0;
            for (Object obj : objArr)
            {
               Cell cell = row.createCell(cellnum++);
               if(obj instanceof String)
                    cell.setCellValue((String)obj);
                else if(obj instanceof Integer)
                    cell.setCellValue((Integer)obj);
            }
        }
        try
        {
           //Write the workbook in file system
            FileOutputStream out = new FileOutputStream(new File("C://xlFileMoreThan65000Test.xlsx"));
            
            workbook.write(out);
            out.close();
         
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        
        
    }
}



package com.sun;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


/**
 * Created with IntelliJ IDEA.
 * User: javaroots
 * Date: 10/21/13
 * Time: 11:46 AM
 * To change this template use File | Settings | File Templates.
 */
public class XLSReader {

    public static void main(String[] args) throws IOException 
    {
       
        try
        {
           
            long startTime = System.currentTimeMillis();
            for(int i =0 ;i<10 ;i++)
            {
             FileInputStream in = new FileInputStream(new File("C://xlFileMoreThan65000Test.xlsx"));
                
              OPCPackage pkg = OPCPackage.open("C://xlFileMoreThan65000Test.xlsx");
             
             
             
                XSSFWorkbook workbook1 = new XSSFWorkbook(pkg);
                XSSFSheet sheet1 = workbook1.getSheetAt(0);
                int newRow = sheet1.getLastRowNum();
                System.out.println("last row is : " + newRow);
                for(int j=0;j <1000 ;j++)
                {
                 newRow = newRow + 1 ;
                    
                    Row row = sheet1.createRow(newRow);
                    
                    Object [] objArr = data.get("2");
                    
                    int cellnum = 0;
                    for (Object obj : objArr)
                    {
                     Cell cell = row.createCell(cellnum++);
                        cell.setCellValue("abc");
                    }
                }
                FileOutputStream out = new FileOutputStream(new File("C://xlFileMoreThan65000Test.xlsx"));
                workbook1.write(out);
                out.close();
                in.close();
                pkg.close();
            }
            
            System.out.println("Time taken is " + (System.currentTimeMillis()-startTime));
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        
        
    }
}

Post Comments And Suggestions !!!

Wednesday, 12 July 2017

Textual description of firstImageUrl

How to enable DEBUG Logging In CloudHub

cloudHub ignores the local log4j.xml configuration and even if we enable DEBUG logging in the xml file , and deploy it in cloudhub , we see no changes .

To enable logging in cloud hub , we can add following configurations in out log4j .xml
<Log4J2CloudhubLogAppender name="CLOUDHUB"
                                   addressProvider="com.mulesoft.ch.logging.DefaultAggregatorAddressProvider"
                                   applicationContext="com.mulesoft.ch.logging.DefaultApplicationContext"
                                   appendRetryIntervalMs="${sys:logging.appendRetryInterval}"
                                   appendMaxAttempts="${sys:logging.appendMaxAttempts}"
                                   batchSendIntervalMs="${sys:logging.batchSendInterval}"
                                   batchMaxRecords="${sys:logging.batchMaxRecords}"
                                   memBufferMaxSize="${sys:logging.memBufferMaxSize}"
                                   journalMaxWriteBatchSize="${sys:logging.journalMaxBatchSize}"
                                   journalMaxFileSize="${sys:logging.journalMaxFileSize}"
                                   clientMaxPacketSize="${sys:logging.clientMaxPacketSize}"
                                   clientConnectTimeoutMs="${sys:logging.clientConnectTimeout}"
                                   clientSocketTimeoutMs="${sys:logging.clientSocketTimeout}"
                                   serverAddressPollIntervalMs="${sys:logging.serverAddressPollInterval}"
                                   serverHeartbeatSendIntervalMs="${sys:logging.serverHeartbeatSendIntervalMs}"
                                   statisticsPrintIntervalMs="${sys:logging.statisticsPrintIntervalMs}">

            <PatternLayout pattern="[%d{MM-dd HH:mm:ss}] %-5p %c{1} [%t] CUSTOM: %m%n"/>
        </Log4J2CloudhubLogAppender>

And add this appender along with your file appender .
<AppenderRef ref="CLOUDHUB"/>
Now you can deploy it on cloud hub and it should work fine .
You can also change Additional log levels and categories to include in logs in cloud hub .
Just click on Manage Application -> Settings -> Logging

There you can see logging levels , select desired logging level from drop down and write your package name , like com.mulesoft . And then click on apply changes . And those changes will be affected in your cloudhub logs



Provide Comments and Suggestions !!!

Thursday, 8 June 2017

Textual Representation of logo

How to make Poller Component Efficient In MULE ESB

Poller in MULE ESB is a very important component when you want to keep polling a endpoint for changes and then process it . Most of the times we do not know how big the changes will be and how much time will it take to complete . So setting polling interval becomes very crucial , because you do not want to trigger a new process before completing the existing task , and also you do not want to lose too much time waiting for the next trigger , if you complete the process earlier .

Following code snippet solves your problem , it achieves synchronous behavior and poller will wait if the process is taking some time , it also achieves asynchornous efficiency where if you have 10 results then 10 separate process will be executed and main poller flow will still wait for them to complete .


Code is self explanatory , i have used simple request reply and aggregator pattern , hope it helps .
<?xml version="1.0" encoding="UTF-8"?>

<mule xmlns:vm="http://www.mulesoft.org/schema/mule/vm" xmlns:scripting="http://www.mulesoft.org/schema/mule/scripting" xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns:metadata="http://www.mulesoft.org/schema/mule/metadata" xmlns:dw="http://www.mulesoft.org/schema/mule/ee/dw" xmlns:db="http://www.mulesoft.org/schema/mule/db" xmlns:batch="http://www.mulesoft.org/schema/mule/batch" xmlns:sfdc="http://www.mulesoft.org/schema/mule/sfdc" xmlns:tracking="http://www.mulesoft.org/schema/mule/ee/tracking" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
 xmlns:spring="http://www.springframework.org/schema/beans" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.mulesoft.org/schema/mule/vm http://www.mulesoft.org/schema/mule/vm/current/mule-vm.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/ee/tracking http://www.mulesoft.org/schema/mule/ee/tracking/current/mule-tracking-ee.xsd
http://www.mulesoft.org/schema/mule/db http://www.mulesoft.org/schema/mule/db/current/mule-db.xsd
http://www.mulesoft.org/schema/mule/sfdc http://www.mulesoft.org/schema/mule/sfdc/current/mule-sfdc.xsd
http://www.mulesoft.org/schema/mule/batch http://www.mulesoft.org/schema/mule/batch/current/mule-batch.xsd
http://www.mulesoft.org/schema/mule/ee/dw http://www.mulesoft.org/schema/mule/ee/dw/current/dw.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/scripting http://www.mulesoft.org/schema/mule/scripting/current/mule-scripting.xsd">
    
    
    
    <flow name="exampleFlow" processingStrategy="synchronous" >
     
         <poll doc:name="Poll" >
          <fixed-frequency-scheduler frequency="10000" timeUnit="MILLISECONDS"></fixed-frequency-scheduler>
          <logger message="Upload tour poll started" level="DEBUG"></logger>
          
         </poll>
        
        <expression-component>
         payload = new java.util.ArrayList();
         payload.add("test");
         payload.add("test2");
        </expression-component>
        <choice >
         <when expression="#[payload.size()  &gt;0]">
          <request-reply doc:name="Request-Reply" >
               <vm:outbound-endpoint exchange-pattern="one-way" path="download_tour_vm" doc:name="VM">
                           <collection-splitter />
               </vm:outbound-endpoint>
               <vm:inbound-endpoint exchange-pattern="one-way" path="aggregated_download_tour_vm" doc:name="VM">
                           <collection-aggregator />
               </vm:inbound-endpoint>
    </request-reply>
           <logger message="COMPLETED EXAMPLE" level="INFO"/> 
         </when>
         <otherwise>
          <logger message="No Record To Process" level="INFO"/>
         </otherwise>
        
        </choice>   
        
    </flow>
    
    
    
    
    
    
    <flow name="downloadTour">
       <vm:inbound-endpoint  path="download_tour_vm" doc:name="VM"/>
       
       <scripting:component doc:name="Groovy">
            <scripting:script engine="Groovy"><![CDATA[sleep(20000);
return message.payload;]]></scripting:script>
        </scripting:component>
    </flow>

    
</mule>

Post comments and suggestions .!!

Friday, 17 February 2017

Textual description of firstImageUrl

How to create AWS - s3 bucket using terraform

                   Digitized and Automated Infrastructure is all we need !!!
 Before we begin learning and coding our infrastructure, let us know why we need it.

Think you have an infrastructure in AWS where you have multiple s3 buckets/instances/ELB/ALB/SG/ VPC/Gateways/NAT attached to these resources and most importantly everything is bought up manually.

?? What happens when some resource goes down (😨 😨) and most of them are dependent, you break your head in this mundane job searching and fixing your resources one at a time and testing everything.

?? What if we come up with an idea to write the infrastructure and enable debugging with fixing at a place where every resource will be up and running. And it is all about spinning and getting out of your infrastructure in less or no time. Here is what Terraform  provides you .


Terraform enables you to safely and predictably create, change, and improve infrastructure.
It is an open source tool that codifies APIs into declarative configuration files that can be shared amongst team members, treated as code, edited, reviewed, and versioned. 



Terraform Features:
  • Infrastructure as Code
  • Execution Plans
  • Resource Graph
  • Change Automation

Running a marathon using terraform ....


Let's not waste our time and start creating an s3 bucket in AWS  using terraform.

Terraform supports almost all of the providers, I choose AWS to create my infra in this blog, You can use yours.

Before proceeding make sure you have an AWS account to create your infrastructure. Follow the steps to create a s3 infra :(Install terraform from Terraform Installation Guide )
mkdir ~/terraform_infra
cd ~/terraform_infra
touch s3.tf
Lets go through the Code Step wise :



Provider.tf

The provider block here says we are using aws as our provider where :

  • region : Region where our resource will be created
  • Key/Secret : Provided by AWS

resource.tf

The resource block says what resource we are creating in infra.
Here aws_s3_bucket is resource which terraform understands to create bucket
echo_stage_bucket is our reference to s3 bucket

  • bucket: bucket name that will be created in aws
  • acl: bucket type (public/private)
  • tags: tags your environment
Bootstrap Thumbnail Third

storage.tf

data block (terraform_remote_stage) is used to say terraform that where we want to store our terraform state file

This is needed because once we create the infrastructure we need to version and maintain state if we loose it , we lost our infrastruture state , Here I am using s3 to store my tf state
  • backend: where to store the state file
  • bucket: bucket name we are referencing the bucket that we have created
  • key : filename that will be saved

Final Script s3.tf :


 ➜ terraform plan

+ aws_s3_bucket.echo_stage_bucket
    acceleration_status: ""
    acl:                 "private"
    arn:                 ""
    bucket:              "echo_stage_test_bucket"
    bucket_domain_name:  ""
    force_destroy:       "false"
    hosted_zone_id:      ""
    region:              ""
    request_payer:       ""
    tags.%:              "2"
    tags.Environment:    "Dev"
    tags.Name:           "EchoStage Bucket"
    versioning.#:        ""
    website_domain:      ""
    website_endpoint:    ""

<= data.terraform_remote_state.store_tf_state
    backend:        "s3"
    config.%:       "4"
    config.bucket:  "echo_stage_test_bucket"
    config.key:     "state_file/terraform.tfstate"
    config.profile: "default"
    config.region:  "us-east-1"


Plan: 1 to add, 0 to change, 0 to destroy.


Lets Create the infra : 


➜ terraform apply
aws_s3_bucket.echo_stage_bucket: Creating...
  acceleration_status: "" => ""
  acl:                 "" => "private"
  arn:                 "" => ""
  bucket:              "" => "echo_stage_test_bucket"
  bucket_domain_name:  "" => ""
  force_destroy:       "" => "false"
  hosted_zone_id:      "" => ""
  region:              "" => ""
  request_payer:       "" => ""
  tags.%:              "" => "2"
  tags.Environment:    "" => "Dev"
  tags.Name:           "" => "EchoStage Bucket"
  versioning.#:        "" => ""
  website_domain:      "" => ""
  website_endpoint:    "" => ""
aws_s3_bucket.echo_stage_bucket: Still creating... (10s elapsed)
aws_s3_bucket.echo_stage_bucket: Creation complete
data.terraform_remote_state.store_tf_state: Refreshing state...

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

The state of your infrastructure has been saved to the path
below. This state is required to modify and destroy your
infrastructure, so keep it safe. To inspect the complete state
use the `terraform show` command.

State path: terraform.tfstate

 
You would have got the terraform.tfstate state file in your local , Lets push this to created s3 bucket:

Exceute:
➜  terraform-infra terraform remote  config -backend=s3  -backend-config="bucket=echo_stage_test_bucket" -backend-config="key=state_file/terraform.tfstate" -backend-config="region=us-east-1"

Remote state management enabled

Remote state configured and pulled.


For any Queries Send Mail

Monday, 13 February 2017

Textual Representation of logo

How to use Apache HttpClient 4.5 for Https Connections

This is a simple example on how to use Apache HttpClient 4.5 with connection pool manager to request https urls .
package com.javaroots;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.net.ssl.*;

import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContexts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.javaroots.DummyTrustManager;

public class HttpClientFactory {

    private static CloseableHttpClient client;

    private static PoolingHttpClientConnectionManager connPool = null;

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientFactory.class);

    static{
        try
        {
            SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(new TrustSelfSignedStrategy()).build();
            sslcontext.init(new KeyManager[0], new TrustManager[] { new DummyTrustManager() }, new SecureRandom());
            sslcontext.init(null, new X509TrustManager[]{new HttpsTrustManager()}, new SecureRandom());
            SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
                    new HostnameVerifier() {
                        @Override
                        public boolean verify(final String s, final SSLSession sslSession) {

                            return true;
                        }
                    });

            Registry r = RegistryBuilder. create()
                    .register("https", factory).build();

            connPool = new PoolingHttpClientConnectionManager(r);
            // Increase max total connection to 200
            connPool.setMaxTotal(200);
            
            connPool.setDefaultMaxPerRoute(20);


            client = HttpClients.custom().
                    setConnectionManagerShared(true).
                    setConnectionManager(connPool).
                    setSSLSocketFactory(factory).build();
        }
        catch(Exception e){
            LOGGER.error("Error initiliazing HttpClientFactory :: ",e);
        }
    }

    public static CloseableHttpClient getHttpsClient() throws KeyManagementException, NoSuchAlgorithmException  {

        if (client != null) {
            return client;
        }
        throw new RuntimeException("Client is not initiliazed properly");

    }
    public static void releaseInstance() {
        client = null;
    }
}

In above code if you do not use setConnectionManagerShared(true) , you might get following error .
java.lang.IllegalStateException: Connection pool shut down
Now if you want to use HttpClient to call Https Urls and with help of connection pools , you have to add a registry in your connection pool , otherwise it will ignore your SSLContext configurations , and give following error .
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
 at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
 at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
 at sun.security.validator.Validator.validate(Validator.java:260)
 at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
 at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
 at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
 at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1491)
 ... 80 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
 at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
 at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
 at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
 at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
 ... 86 more
package com.javaroots;

import java.io.IOException;
import java.net.URI;

import javax.ws.rs.core.MediaType;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;



public class ApacheClient {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApacheClient.class);


 public static void main(String[] args) throws Exception{
  CloseableHttpClient apacheClient = HttpClientFactory.getHttpsClient();


  CloseableHttpResponse response2 = null;
  HttpGet httpPost = new HttpGet("https://mms.nw.ru/");
  RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(30000).setSocketTimeout(30000)
    .build();
  HttpEntity entity2 = null;
  try {
   httpPost.setConfig(defaultRequestConfig);
   response2 = apacheClient.execute(httpPost);

   System.out.println(response2.getStatusLine());

  } catch (Exception e) {
   LOGGER.error("Error while getting response: ", e);
   throw new HttpClientException(e);
  } finally {
   try {
    response2.close();
    apacheClient.close();
   } catch (Exception e) {

   }

  }
 }



}

Monday, 6 February 2017

Textual Representation of logo

Dockerizing an existing Rails application

  Docker is a relatively new and rapidly growing project that allows creating very light “virtual machines”.

Prerequisites

There are no specific skills needed for this tutorial beyond a basic comfort with the command line and using a text editor. The following services are needed:
  • Docker Hub (Login - Signup if you haven't )
  • A Rails application

Setting up your computer

Getting all the tooling setup on your computer can be a daunting task, but thankfully as Docker has become stable, getting Docker up and running on your favorite OS has become very easy. First, we'll install Docker.
Until a few releases ago, running Docker on OSX and Windows was quite a hassle. Lately, however, Docker has invested significantly into improving the onboarding experience for its users on these OSes, thus running Docker now is a cakewalk. The getting started guide on Docker has detailed instructions for setting up Docker on Mac, Linux, and Windows.
Once you are done installing Docker, test your Docker installation by running the following:
$ docker run hello-world

Hello from Docker.

This message shows that your installation appears to be working correctly.
...
Starting with a Rails Application: I will not be going through docker commands as that would be found on dockers website and many blog sites. There are different ways you can deploy your Ruby applications in a Docker container. You can either choose one of the many existing Ruby images on the public docker registry

Building the base image

This image will set a base for the rest of the post as we will use the resulting image to create our set of Rails images.
The image will contain all the things Rails expects to compile and run properly on a Debian based OS. I am not going to talk about the required packages, instead, I am going to focus on the separation of concerns and configuration of the set of images.
One thing to keep in mind is that the image we’ll build is only for RubyOnRails and will not contain any database related packages. If there’s a need to install a gem with native extensions requiring “extra” packages those should go into that specific image unless all of your apps require it.
What should you expect from this image?
This image will not complain about any TTY warnings during installation because of the flag(noninteractive) we are using, all your applications will use as encoding(en_US.UTF-8) .thencoding.
Find the below Image and explanation as followed.
  • I am using ruby 1.9.3 for my Project.
  • Gemfile is already built with rails 3.2.3, You can use your own Gemfile.
#Dockerfile
FROM ubuntu:trusty  # Using Ubuntu OS
MAINTAINER "Santosh Mohanty <santa.jyp@gmail.com>" # Maintainer Name
RUN apt-get update # Updating OS

ENV PATH /usr/local/rvm/bin:$PATH  # Set ENV Path

RUN apt-get update && apt-get -y upgrade && apt-get -y install ruby 1.9.3 # Installation of Ruby
RUN ln -sf /usr/bin/ruby1.9.3 /etc/alternatives/ruby

# basics
RUN apt-get install -y build-essential
RUN apt-get install -y mysql-client libmysqlclient-dev openssl libreadline6 
                       libreadline6-dev curl zlib1g zlib1g-dev libssl-dev libyaml-dev
                       libsqlite3-dev sqlite3 libxml2-dev libxslt-dev autoconf libc6-dev
                       ncurses-dev automake libtool bison subversion pkg-  config gawk 
                       libgdbm-dev libffi-dev npm

RUN gem install bundler
ADD Gemfile /app/Gemfile
ADD Gemfile.lock /app/Gemfile.lock
WORKDIR /app
RUN bundle install
ADD . /app      # Adds your Project Structure to docker
ENV ENVIRONMENT development
CMD ["rails","s"]

EXPOSE 3000 # Exposing PORT 3000 for Development

Executing the Image:

Follow the Below steps to Build your Docker Image from Dockerfile:
docker build -t rails_image ~/workspace/PATH_TO_DOCKERFILE
docker run -p 3000:3000 rails_image # Mapping container port 3000 to local port 3000
This would run your rails application inside docker container
Few Imp commands:
docker run -it rails_image /bin/bash # this would bring up the bash prompt of docker
docker images # List Images
docker rmi IMAGE_ID -f  # remove Image
docker ps  # for listing running containers.
You may find difficulties in connecting to DB from Container, This can be solved running a DB Image or pointing to Specific IP of DB instead of local IP.

I will be writing a blog on how to connect MySQL DB Image to Rails Image using docker compose.