# File lib/rhc-common.rb, line 477
  def self.create_app(libra_server, net_http, user_info, app_name, app_type, rhlogin, password, repo_dir=nil, no_dns=false, no_git=false, is_embedded_jenkins=false, gear_size='small',scale=false)

    # Need to have a fake HTTPResponse object for passing to print_reponse_err
    # May already be initialized if called from another piece of code
    # FIXME: remove this requirement when refactoring rhc
    begin
      Struct::FakeResponse
    rescue NameError
      Struct.new('FakeResponse',:body,:code,:content_type)
    end

    domains = user_info['user_info']['domains']
    if domains.empty?
      emessage = "Please create a domain with 'rhc domain create -n <namespace>' before creating applications."
      print_response_err(Struct::FakeResponse.new(emessage,403))
    end
    namespace = domains[0]['namespace']
    puts "Creating application: #{app_name} in #{namespace}"
    data = {:cartridge => app_type,
            :action => 'configure',
            :node_profile => gear_size,
            :app_name => app_name,
            :rhlogin => rhlogin
           }
    if @mydebug
      data[:debug] = true
    end    

    # Need to use the new REST API for scaling apps
    #  We'll need to then get the new application using the existing
    #  API in order to access the rest of the logic in this function
    if scale
      end_point = "https://#{libra_server}/broker/rest/api"
      client = RHC::Rest::Client.new(end_point, rhlogin, password)

      domain = client.find_domain(user_info['user_info']['domains'][0]['namespace'])

      namespace = domain.id
      # Catch errors
      begin
        application = domain.add_application(app_name,{:cartridge => app_type, :scale => true, :gear_profile => gear_size})

        # Variables that are needed for the rest of the function
        app_uuid = application.uuid
        result = "Successfully created application: #{app_name}"

        # health check path now returned by the API
        health_check_path = application.health_check_path

        puts "DEBUG: '#{app_name}' creation returned success." if @mydebug
      rescue RHC::Rest::ConnectionException, RHC::Rest::ResourceAccessException => e
        print_response_err(Struct::FakeResponse.new(e.message,e.code))
      rescue RHC::Rest::ValidationException => e
        validation_error_code = (e.code.nil?) ? 406 : e.code
        print_response_err(Struct::FakeResponse.new(e.message, validation_error_code))
      rescue RHC::Rest::ServerErrorException => e
        error_code = (e.code.nil?) ? 500 : e.code
        print_response_err(Struct::FakeResponse.new(e.message, error_code))
      end
    else
      json_data = generate_json(data)

      url = URI.parse("https://#{libra_server}/broker/cartridge")
      response = http_post(net_http, url, json_data, password)

      if response.code == '200'
        json_resp = json_decode(response.body)
        print_response_success(json_resp)
        json_data = json_decode(json_resp['data'])
        health_check_path = json_data['health_check_path']
        app_uuid = json_data['uuid']
        result = json_resp['result']
        puts "DEBUG: '#{app_name}' creation returned success." if @mydebug
      else
        print_response_err(response)
      end
    end

    #
    # At this point, we need to register a handler to guarantee app
    # cleanup on any exceptions or calls to exit
    #
    at_exit do
      unless $!.nil? || $!.is_a?(SystemExit) && $!.success?
        puts "Cleaning up application"
        destroy_app(libra_server, net_http, app_name, rhlogin, password)
      end
    end

    rhc_domain = user_info['user_info']['rhc_domain']

    fqdn = "#{app_name}-#{namespace}.#{rhc_domain}"

    loop = 0
    #
    # Confirm that the host exists in DNS
    #
    unless no_dns
      puts "Now your new domain name is being propagated worldwide (this might take a minute)..."
  
      # Allow DNS to propogate
      sleep 15
  
      # Now start checking for DNS
      sleep_time = 2
      while loop < MAX_RETRIES && !hostexist?(fqdn)
          sleep sleep_time
          loop+=1
          print CLEAR_LINE + "    retry # #{loop} - Waiting for DNS: #{fqdn}"
          $stdout.flush
          sleep_time = delay(sleep_time)
      end
    end
    
    # if we have executed print statements, then move to the next line
    if loop > 0
      puts
    end
    
    # construct the Git URL
    git_url = "ssh://#{app_uuid}@#{app_name}-#{namespace}.#{rhc_domain}/~/git/#{app_name}.git/"

    # If the hostname couldn't be resolved, print out the git URL
    # and exit cleanly.  This will help solve issues where DNS times
    # out in APAC, etc on resolution.
    if loop >= MAX_RETRIES
        puts "\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\nWARNING: We were unable to lookup your hostname (\#{fqdn}) \nin a reasonable amount of time.  This can happen periodically and will just\ntake an extra minute or two to propagate depending on where you are in the\nworld.  Once you are able to access your application in a browser, you can then\nclone your git repository.\n\n  Application URL: http://\#{fqdn}\n\n  Git Repository URL: \#{git_url}\n\n  Git Clone command: \n    git clone \#{git_url} \#{repo_dir}\n\nIf you can't get your application '\#{app_name}' running in the browser, you can\nalso try destroying and recreating the application as well using:\n\n  rhc app destroy -a \#{app_name} -l \#{rhlogin}\n\nIf this doesn't work for you, let us know in the forums or in IRC and we'll\nmake sure to get you up and running.\n\n  Forums: https://openshift.redhat.com/community/forums/openshift\n\n  IRC: #openshift (on Freenode)\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n"
        exit 0
    end
    
    #
    # Pull new repo locally
    #
    
    unless no_git
        puts "Pulling new repo down" if @mydebug
    
        quiet = (@mydebug ? ' ' : '--quiet ')
        puts "git clone #{quiet}#{git_url} #{repo_dir}" if @mydebug
        git_clone = %x[git clone #{quiet} #{git_url} #{repo_dir} 2>&1]
        if $?.exitstatus != 0

          if RHC::Helpers.windows? 

            `nslookup #{app_name}-#{namespace}.#{rhc_domain}`
            windows_nslookup = $?.exitstatus == 0
            `ping #{app_name}-#{namespace}.#{rhc_domain} -n 2`
            windows_ping = $?.exitstatus == 0
            
            if windows_nslookup and !windows_ping # this is related to BZ #826769
              puts "\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\nWARNING: We were unable to lookup your hostname (\#{fqdn}) \nin a reasonable amount of time.  This can happen periodically and will just\ntake up to 10 extra minutes to propagate depending on where you are in the\nworld. This may also be related to an issue with Winsock on Windows [1][2]. \nWe recommend you wait a few minutes then clone your git repository manually.\n\n  Git Clone command: \n    git clone \#{git_url} \#{repo_dir}\n\n[1] http://support.microsoft.com/kb/299357\n[2] http://support.microsoft.com/kb/811259\n\nIf this doesn't work for you, let us know in the forums or in IRC and we'll\nmake sure to get you up and running.\n\n  Forums: https://openshift.redhat.com/community/forums/openshift\n\n  IRC: #openshift (on Freenode)\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n"
              exit 0
            end
          end
          puts "Error in git clone"
          puts git_clone
          exit 216
        end
    else
      if is_embedded_jenkins
        # if this is a jenkins client application to be embedded, 
        # then print this message only in debug mode
        if @mydebug
          puts "
Note: There is a git repo for your Jenkins application '#{app_name}'
but it isn't being downloaded as part of this process.  In most cases
it isn't needed but you can always clone it later.

"
        end
      else         
        puts "\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\nIMPORTANT: Since the -n flag was specified, no local repo has been created.\nThis means you can't make changes to your published application until after\nyou clone the repo yourself.  See the git url below for more information.\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n"
      end
    end
    
    #
    # At this point, we need to register a handler to guarantee git
    # repo cleanup on any exceptions or calls to exit
    #
    unless no_git
      at_exit do
          unless $!.nil? || $!.is_a?(SystemExit) && $!.success?
              puts "Cleaning up git repo"
              FileUtils.rm_rf repo_dir
          end
      end
    end
    return {:app_name => app_name,
            :fqdn => fqdn,
            :health_check_path => health_check_path,
            :git_url => git_url,
            :repo_dir => repo_dir,
            :result => result
           }
  end