Top Level Namespace

Defined Under Namespace

Modules: ApolloCommonsRuby, HTTP, JSON, MarioConfig, Operation, PermissionsTasks, ShopHooksTasks, TemplatesTasks Classes: Configuration, ConvertPresentationPayload, CreateCollectionItem, CreateTemplatePayload, DebugSecretConfig, DomainEvent, ExecuteShellCommand, LineReplacementProperties, MarioDebugger, MarioEvent, ResolveTemplate, SecretConfig, String, Template, TemplateConfig, TemplateGroupDetails, TemplateMapping, Templates, ViewGroup, ViewGroupComponent, ViewGroupDefinition

Instance Method Summary collapse

Instance Method Details

#adb_push_presentation(configuration, environment, template_group, template_path, is_root, language, view_type, platform, is_real_device_connected, is_simulator_connected) ⇒ Object

Push only presentation



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/apollo_commons_ruby/TemplatePusher.rb', line 35

def adb_push_presentation(configuration, environment, template_group, template_path, is_root, language, view_type, platform, is_real_device_connected, is_simulator_connected)
  # create_zebuggerX_folder()
  presentation = get_presentation_after_conversion_if_neeeded(configuration.apollo_config_base_url, environment, template_path)
  presentation = JSON.parse(presentation, :quirks_mode => true)
  presentation_file_path_to_push = template_path + '/' + 'presentation_file.json'
  write_data_to_file(presentation_file_path_to_push, presentation)
  if(platform == "iOS")
    source_file_path = presentation_file_path_to_push
    destination_file_path = "/Documents/presentation_#{template_group}_#{language}_#{view_type}.json"
    adb_push_to_ios(source_file_path, destination_file_path, is_real_device_connected, is_simulator_connected)
  else
    adb_push_to_android(presentation_file_path_to_push, '/storage/emulated/0/Android/media/in.zeta.android.apollo.zebugger/files/zebuggerX/' + (is_root ? 'root_presentation' : ('presentation+' + template_group)) + '.json')

    adb_push_to_android(presentation_file_path_to_push, '/storage/emulated/0/Download/zebuggerX/' + (is_root ? 'root_presentation' : ('presentation+' + template_group)) + '.json')
  end
  File.delete(presentation_file_path_to_push) if File.exist?(presentation_file_path_to_push)
end

#adb_push_template_data(template_group, language, view_type, platform, is_real_device_connected, is_simulator_connected) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/apollo_commons_ruby/TemplatePusher.rb', line 53

def adb_push_template_data(template_group, language, view_type, platform, is_real_device_connected, is_simulator_connected)
  # create_zebuggerX_folder()
  template_data_file_path = Dir.pwd + '/scripts/commonData/' + 'generatedTemplatedData.json'
  template_data_file_path = '"' + template_data_file_path + '"'
  
  if(platform == "iOS")
    source_file_path = template_data_file_path
    destination_file_path = "/Documents/dataTemplate_#{template_group}_#{language}_#{view_type}.json"
    adb_push_to_ios(source_file_path, destination_file_path, is_real_device_connected, is_simulator_connected)
  else
    adb_push_to_android(template_data_file_path, '/storage/emulated/0/Android/media/in.zeta.android.apollo.zebugger/files/zebuggerX/data.json')
    adb_push_to_android(template_data_file_path, '/storage/emulated/0/Download/zebuggerX/data.json')
    system("adb shell am force-stop in.zeta.android.apollo.youtube")
    system("adb shell am start -n in.zeta.android.apollo.youtube/zebuggerx.zetlet.MainActivity")
  end
end

#adb_push_to_android(source_file_path, destination_file_path) ⇒ Object



70
71
72
73
74
# File 'lib/apollo_commons_ruby/TemplatePusher.rb', line 70

def adb_push_to_android(source_file_path, destination_file_path)
  cmd = 'adb push "' + source_file_path + '" "' + destination_file_path + '"'
  puts "Pushing file #{source_file_path} to Android device"
  system(cmd)
end

#adb_push_to_ios(source_file_path, destination_file_path, is_real_device_connected, is_simulator_connected) ⇒ Object



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/apollo_commons_ruby/TemplatePusher.rb', line 76

def adb_push_to_ios(source_file_path, destination_file_path, is_real_device_connected, is_simulator_connected)
  if is_real_device_connected
    push_to_ios_device($zebugger_ios_bundle_id, source_file_path, destination_file_path)

    #Pushing to old bundle id for backward compatibility
    push_to_ios_device($old_zebugger_ios_bundle_id, source_file_path, destination_file_path)
  end
  
  if is_simulator_connected
    push_to_ios_simulator($zebugger_ios_bundle_id, source_file_path, destination_file_path)

    #Pushing to old bundle id for backward compatibility
    push_to_ios_simulator($old_zebugger_ios_bundle_id, source_file_path, destination_file_path)
  end
end

#add_translations_for_language(module_name, languages) ⇒ Object



459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 459

def add_translations_for_language(module_name, languages)
    languages.split(",").each do |language|
    if ("en-EN" == language)
        puts "Default language is English. No need for translations"
        next
    end
    target_language = language.split("-")[0]
    target_file = language.split("-")[1] + ".json"
        base_path = "./Resources/"
        File.delete(base_path + target_file) if File.exist?(base_path + target_file)
        puts "Removing file #{target_file}" if File.exist?(base_path + target_file)
        file_name = "EN.json"
        target_file_path = base_path + target_file
        FileUtils.cp(base_path + file_name, target_file_path)
        IO.readlines(target_file_path).map do |line|
            trimmed_line = line.strip
            if trimmed_line.length != 0
                begin
                    value = trimmed_line.split(":")[1]
                    translated_line = format_translated_line(get_translated_line(value, target_language))
                    if (!translated_line.to_s.end_with? ",")
                       translated_line = translated_line + ","
                    end
                    formatted_line = trimmed_line.split(":")[0] + ": " + translated_line.to_s.strip
                    puts "Translated Line #{formatted_line}"
                    $LINE_REPLACEMENT_DETAILS_LIST.push(LineReplacementProperties.new(target_file_path, line, line.gsub(trimmed_line, formatted_line)))
                rescue
                    puts "Translation failed. Using the default line in place"
                    $LINE_REPLACEMENT_DETAILS_LIST.push(LineReplacementProperties.new(target_file_path, line, line))
                end
            end
        end
    #Remove ending }
    $LINE_REPLACEMENT_DETAILS_LIST.pop()
    #Modify the last element which has , appended to it
    $LINE_REPLACEMENT_DETAILS_LIST.push(get_modified_replacement_property($LINE_REPLACEMENT_DETAILS_LIST.pop()))
    change_line_in_file($LINE_REPLACEMENT_DETAILS_LIST)
      end
end

#all_directory_and_sub_directory_in_dir_path(dir_path) ⇒ Object



728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 728

def all_directory_and_sub_directory_in_dir_path(dir_path)
  dirNames = Hash.new
  Dir.entries(dir_path).select {
    |entry| File.directory? File.join(dir_path,entry) and !(entry =='.' || entry == '..')
  }.each do |item|
    dir_path_of_item = File.join(dir_path,item)
    dir_names_of_item = directory_list(dir_path_of_item)
    if dir_names_of_item.count > 0
      dirNames[item] = File.join(dir_path,item)
      dirNames = dirNames.merge(all_directory_and_sub_directory_in_dir_path(dir_path_of_item))
    else
      dirNames[item] = File.join(dir_path,item)
    end
  end
  return dirNames
end

#all_directory_and_sub_directory_with_character_not_in_dir_path(dir_path, character) ⇒ Object



712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 712

def all_directory_and_sub_directory_with_character_not_in_dir_path(dir_path, character)
  dirNames = Hash.new
  Dir.entries(dir_path).select {
    |entry| File.directory? File.join(dir_path,entry) and !(entry =='.' || entry == '..')
  }.each do |item|
    indexOfCharacter = item.index(character)
    indexOfTemplater = item.index("{{")
    if indexOfCharacter and indexOfCharacter >= 0 and (!indexOfTemplater || indexOfCharacter < indexOfTemplater)
      dirNames = dirNames.merge(all_directory_and_sub_directory_with_character_not_in_dir_path(File.join(dir_path,item), character))
    else
      dirNames[item] = File.join(dir_path,item)
    end
  end
  return dirNames
end

#associate_hars_with_in_request_bodyObject



154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/apollo_commons_ruby/DomainEvent.rb', line 154

def associate_hars_with_in_request_body
    return if File.directory?($domain_event.location + "/hars") == false
    harsLocation =  $domain_event.location + "/hars"
    harsArr = []
    Dir.entries(harsLocation).sort.each do |har|
        next if har == '.' || har == '..' || har == '.DS_Store'
        puts "har: #{har}"
        harFile = File.read(harsLocation + "/" + har)
        harJson = JSON.parse harFile
        harJson = JSON.parse replace_single_quote(JSON.generate(harJson))
        harsArr.push(harJson)
    end
    $domain_event.requestBody["hars"] = harsArr
end

#associate_user_details_transformer_in_request_bodyObject



125
126
127
128
129
130
# File 'lib/apollo_commons_ruby/DomainEvent.rb', line 125

def associate_user_details_transformer_in_request_body
    userDetailsTransformerLocation = $domain_event.location + "/user_details_transformer.js"
    userDetailsTransformer = File.read(userDetailsTransformerLocation)
    raise_exception_if_string_empty(userDetailsTransformer, "user_details_transformer")
    $domain_event.requestBody["userDetailsTransformer"] = userDetailsTransformer
end

#associate_view_group_context_transformer_in_request_bodyObject



132
133
134
135
136
137
# File 'lib/apollo_commons_ruby/DomainEvent.rb', line 132

def associate_view_group_context_transformer_in_request_body
    viewGroupContextTransformerLocation = $domain_event.location + "/view_group_context_transformer.js"
    viewGroupContextTransformer = File.read(viewGroupContextTransformerLocation)
    raise_exception_if_string_empty(viewGroupContextTransformer, "view_group_context_transformer")
    $domain_event.requestBody["viewGroupContextTransformer"] = "<% " + viewGroupContextTransformer + " %>"
end

#backfill_sample_data_for_configs(env) ⇒ Object



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
# File 'lib/apollo_commons_ruby/BackfillSampleData.rb', line 8

def backfill_sample_data_for_configs(env)
    environment = env['environment']
    env["is_local"] = "true"
    load_environment_properties_for_debug(env['environment'], env['tenant_id'], env['project_id'])
    all_domain_events = get_all_domain_events(env)
    if all_domain_events == nil
        puts "DOMAIN EVENT DATA IS NULL. COULD NOT PROCEED"
        return
    end
    all_domain_events = JSON.parse(all_domain_events)
    all_domain_events.each do |domainEventData|
              domain_event_data_json = JSON.parse(domainEventData.to_json)
              viewGroupDefinition = domain_event_data_json['viewGroupDefinition']
              component = domain_event_data_json['component']
              domainEventName = domain_event_data_json['domainEventName']
              topic = domain_event_data_json['topic']
              next if domain_event_data_json['attrs'] == nil || domain_event_data_json['attrs']['sampleData'] == nil || domain_event_data_json['attrs']['sampleData'].size == 0
              counter = 0
              domain_event_data_json['attrs']['sampleData'].each do |sampleData|
                  begin
                          base_location = "/configs/" + viewGroupDefinition + "/" + component + "/" + topic + "/" + domainEventName
                          base_location = reverse_replace_environment_based_config_in_string(base_location, $environmentProperties)
                          base_location = Dir.pwd + base_location
                          create_dir_at_path(base_location + "/sampleData")
                          create_dir_at_path(base_location + "/sampleData/" + env['environment'])
                          sample_data_location = base_location + "/sampleData/" + env['environment'] + "/sampleData_" + counter.to_s + ".json"
                          write_to_file(sample_data_location, sampleData.to_json)
                          counter = counter + 1
                  rescue => exception
                    puts exception
                  end
              end
    end
end

#build_template(task, templated_data_ready = false) ⇒ Object



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
# File 'lib/apollo_commons_ruby/Zebugger.rb', line 8

def build_template(task, templated_data_ready = false)
  environment = task.environment
  template_group = task.template_group
  language = task.language
  view_type = task.view_type
  template_name = "default"
  platform = task.platform
  tenant_id = task.tenant_id
  project_id = task.project_id
  puts ("Zebugger for #{platform}")
  
  configuration = Configuration.allocate
  configuration.setup(environment, tenant_id, project_id)

  template_path = resolve_template_path(configuration, template_group, language, view_type, template_name)

  templates = create_template_from_file_for_zebugger(tenant_id, project_id, configuration, environment, template_group, language, view_type, template_name, template_path, false).create_hash

  puts "template_group = #{template_group}"
  puts "language = #{language}"
  puts "view_type = #{view_type}"

  presentation = Base64.decode64(templates["default"]["presentationBase64"])
  data_template = Base64.decode64(templates["default"]["dataTemplateBase64"])

  puts "presentation: #{presentation}"
  puts "data_template: #{data_template}"

  if(templated_data_ready)
    templated_data = File.read('./scripts/commonData/generatedTemplatedData.json')
    puts "\n\n#{templated_data}\n\n"
    finalTemplatedData = JSON.parse(templated_data)
    write_templated_data_to_file(configuration, finalTemplatedData)
    template_id_set = Set.new
    generatedTemplatedData = IO.read('./scripts/commonData/generatedTemplatedData.json')
    dependent_template_ids = get_dependent_template_ids(generatedTemplatedData, template_id_set)
    dependent_template_ids = get_dependent_template_ids(presentation, template_id_set)
    template_id_set.each do |item|
      puts "Dependent template #{item}"
    end
    push_templates_to_device(configuration, environment, template_group, template_path, dependent_template_ids, language, view_type, platform)
  else
    finalTemplatedData = JSON.parse(data_template.escnewline)
    puts "\n\n#{finalTemplatedData}\n\n"
    write_templated_data_to_file(configuration, finalTemplatedData)

    dependent_template_ids = get_dependent_template_ids(presentation)
    dependent_template_ids = get_dependent_template_ids(data_template, dependent_template_ids)
    push_templates_to_device(configuration, environment, template_group, template_path, dependent_template_ids, language, view_type, platform)
  end
end

#change_line_in_file(line_replacement_list) ⇒ Object



445
446
447
448
449
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 445

def change_line_in_file(line_replacement_list)
  line_replacement_list.each do |line_replacement_details|
      modify_file_line(line_replacement_details)
  end
end

#check_for_device_connection(platform) ⇒ Object



128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/apollo_commons_ruby/TemplatePusher.rb', line 128

def check_for_device_connection(platform)
  is_real_device_connected = false
  is_simulator_connected = false
  if(platform == "iOS")
    is_real_device_connected = false
    stdout, stderr, status = Open3.capture3("ios-deploy --detect --timeout 1")
    if stdout.include? "Found"
      is_real_device_connected = true
    end
  
    is_app_simulator_connected = check_ios_simulator_availability($zebugger_ios_bundle_id)

    #Checking for old app simulator for backward compatibility
    is_old_app_simulator_connected = check_ios_simulator_availability($old_zebugger_ios_bundle_id)

    is_simulator_connected = is_app_simulator_connected || is_old_app_simulator_connected
  end
  
  return is_real_device_connected, is_simulator_connected
end

#check_ios_simulator_availability(bundle_id) ⇒ Object



149
150
151
152
153
154
155
156
157
158
159
# File 'lib/apollo_commons_ruby/TemplatePusher.rb', line 149

def check_ios_simulator_availability(bundle_id)
  is_simulator_connected = true
  stdout, stderr, status = Open3.capture3("xcrun simctl get_app_container booted #{bundle_id} data")
  if stderr.include? "No devices are booted."
    is_simulator_connected = false
  end
  if stderr.include? "No such file or directory"
    is_simulator_connected = false
  end
  return is_simulator_connected
end

#compose_message(env, message) ⇒ Object

Migrate away from flock terminologies in webhook message



136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
# File 'lib/apollo_commons_ruby/MarioConfigsStability.rb', line 136

def compose_message(env, message)
    # to get the current repo
    repo_url = `git config --get remote.origin.url`
    #current_branch = `git branch --show-current`
    
    if repo_url.include? "@"
        repo_url = repo_url.gsub(":","/")
        first_part =  repo_url.split("@")[0]
        second_part = repo_url.split("@")[1].split(".git")[0] + "/src/master"
        first_part = "https://"
        repo_url = first_part.concat(second_part)
    else
        repo_url = repo_url.split(".git")[0] + "/src/master"
    end


    str = "<br/> <flockml><span style='color:#4CB659'><b> REPO URL = <a href=\'"+ repo_url +"\'>"+ repo_url+"</a></b></span></flockml><br/>TENANT ID = " + env["tenant_id"] + "<br/>PROJECT ID = " + env["project_id"] + "<br/>VIEW GROUP DEFINITION = " + env["view_group_definition"] +
      + "<br/>VIEW GROUP COMPONENT = " + env["view_group_component"] + "<br/>TOPIC = " + env["topic"].gsub("<","&lt;").gsub(">","&gt;") +
      + " <br/>EVENT NAME = " + env["event_name"] + "<br/>REQUEST DATA FILE = " + env["request_data_file"] + "<br/><br/><br/>"
    line = "<br/>=================================================  ";

    if(message.include? "logs")
      if JSON.parse(message)["status"] == 'failure'
        return str.concat("<flockml><span style='color:#dd3416'><b>").concat((JSON.parse(message)["logs"].last).to_json).concat("</b></span></flockml>").concat(line)
      end
    elsif(message.include? "INVALID PATH")
      puts  message.gsub("&lt;","<").gsub("&gt;",">").red
      last_element_in_the_path = message.split("/").last
      path = message.split(":")[1].gsub(Dir.pwd,"").gsub(last_element_in_the_path,"")
      return str.gsub(repo_url,repo_url+path).concat("<flockml><span style='color:#dd3416'><b>").concat(message).concat(":</b></span></flockml>").concat(line)
    elsif(message.include? "RuntimeException")
      error_log = "PLEASE CHECK ATROPOS SUBSCRIPTION FILE, THERE IS A RUNTIME EXCEPTION" +
        + "<br/><br/>" + message
      puts error_log.red
      return str.gsub(repo_url,repo_url).concat("<flockml><span style='color:#dd3416'><b>").concat(error_log).concat(":</b></span></flockml>").concat(line)
    elsif (message.include? "data")
      if (JSON.parse(message)["data"] == nil)
        message = "PLEASE CHECK ATROPOS SUBSCRIPTION FILE, AFTER VALIDATION OF ATROPOS SUBSCRIPTION FILE, THE RESULTANT TRANSFORMED PAYLOAD IS NULL" +
          + "<br/><br/> "
        puts message.red
        return str.gsub(repo_url,repo_url).concat("<flockml><span style='color:#dd3416'><b>").concat(message).concat(":</b></span></flockml>").concat(line)
      end
    else
      return str.gsub(repo_url, repo_url).concat("<flockml><span style='color:#dd3416'><b>").concat(line).concat(message).concat(":</b></span></flockml>")
    end
end

#convert_xml_presentation_to_json(environment, apolloConfigBaseUrl, presentation) ⇒ Object



802
803
804
805
806
807
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 802

def convert_xml_presentation_to_json(environment, apolloConfigBaseUrl, presentation)
  request_payload = ConvertPresentationPayload.new(presentation, "XML", "JSON")
  endpoint = "#{apolloConfigBaseUrl}/1.0/presentation/convert"
  converted_presentation = invoke_API(environment, endpoint, HTTP::POST, nil, request_payload.to_json)
  return converted_presentation["presentation"].unesc
end

#create_dir_at_path(path) ⇒ Object



22
23
24
# File 'lib/apollo_commons_ruby/RequestDataUtils.rb', line 22

def create_dir_at_path(path)
    FileUtils.mkdir_p (path)
end

#create_template_from_file(is_mario_template, configuration, environment, template_group, language, view, template_name, template_path, is_apollo_config, tenant_id, project_id) ⇒ Object

require “google/cloud/translate”



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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 7

def create_template_from_file (is_mario_template, configuration, environment, template_group, language, view, template_name, template_path, is_apollo_config, tenant_id, project_id)
  begin
    presentation =  get_presentation_after_conversion_if_neeeded(configuration.apollo_config_base_url, environment, template_path)
    presentation = JSON.parse(presentation).to_json
    presentation = ResolveTemplate.new.resolveLang(presentation.to_json, configuration, language)
    presentation = JSON.parse(presentation, :quirks_mode => true)
    presentation = ResolveTemplate.new.resolveLang(presentation, configuration, language)
    presentation = Base64.encode64(presentation.newline).newline
    #Parsing Default Content
    default_content_file_path = file_of_name_in_dir_path(template_path,"defaultContent")
    #many templates will not support defaultContent, hence initializing a default value
    default_content = {}
    if !(default_content_file_path == nil)
      #Default Content file is present
      begin
        default_content = read_data_from_file_path(default_content_file_path)
      rescue Exception => e
        #Mostly this should not happen, but a sanity check
        puts "ERROR: default content file not found #{e}"
      end
      #If default content is read from file, it should be definitely be of JSON format because i.e. what the API expects
      if !JSON.is_valid_json?(default_content)
        #If not, throw exception
        raise "ERROR: default content is not a valid JSON"
      else
        #Convert json file read to hash so that it is passed to API in json form
        default_content = JSON.parse(default_content)
        default_content = ResolveTemplate.new.resolveEnv( default_content.to_json, configuration, tenant_id, project_id)
        default_content = JSON.parse(default_content)
      end
    end
    default_content_string = default_content.to_json

    transformer_file_path = file_of_name_in_dir_path(configuration.template_group_dir_path_for_template(template_group), "clientTransformer")

    isClientTransformerFound = false
    if !(transformer_file_path == nil)

      isClientTransformerFound = true

      begin
        client_transformer = get_client_transformer_without_require(transformer_file_path)
      rescue Exception => e
        #Mostly this should not happen, but a sanity check
        puts "ERROR: client transformer file not found #{e}"
      end


      if client_transformer == nil
        client_transformer = "";
      end

      client_transformer = client_transformer.newline.tabs

    end

    #Parsing data template
    data_template_file_path = file_of_name_in_dir_path(template_path,"dataTemplate")
    puts "data_template_file_path #{data_template_file_path}"
    #many templates will not support dataTemplate, hence initializing a default value
    data_template = "{}"
    if !(data_template_file_path == nil)
      #data template file is present
      begin
        data_template = read_data_from_file_path(data_template_file_path)
      rescue Exception => e
        #Mostly this should not happen, but a sanity check
        puts "ERROR: data template file not found #{e}"
      end
      if data_template_file_path.end_with? ".json" and !data_template.newline.empty?
        #if data template file is json, then enforce proper json
        if !JSON.is_valid_json?(data_template)
          raise "ERROR: data template is not a valid JSON"
        end
        data_template = "#{data_template}"
      end
    end

    #Parsing client transformer specific to individual template
    specific_client_transformer_file_path = file_of_name_in_dir_path(template_path,"clientTransformer")
    puts "Specific_client_transformer_file_path #{specific_client_transformer_file_path}"
    specific_client_transformer = "{}";
    if !(specific_client_transformer_file_path == nil)
      begin
        specific_client_transformer = get_client_transformer_without_require(specific_client_transformer_file_path)
      rescue Exception => e
        puts "ERROR: specific client transformer file not found #{e}"
      end
      if isClientTransformerFound
        client_transformer = client_transformer + "\n" + specific_client_transformer
      elsif specific_client_transformer
        client_transformer = specific_client_transformer
        isClientTransformerFound = true
      end
    end

    if view == 'MARIO'
      begin
        #Parsing local transformer specific to individual template
        specific_local_transformer_file_path = file_of_name_in_dir_path(template_path,"localTransformer")
        puts "specific_local_transformer_file_path #{specific_local_transformer_file_path}"
        specific_local_transformer = "{}";
        if !(specific_local_transformer_file_path == nil)
          begin
            specific_local_transformer = get_client_transformer_without_require(specific_local_transformer_file_path)
          rescue Exception => e
            puts "ERROR: specific local transformer file not found #{e}"
          end
          puts "specific_local_transformer #{specific_local_transformer}"
          if isClientTransformerFound
            client_transformer = client_transformer + "\n" + specific_local_transformer
          elsif specific_local_transformer
            client_transformer = specific_local_transformer
          end
        end
      end
    end

    #Parsing attrs json
    attrs_json_file_path = file_of_name_in_dir_path(template_path, "attrs")
    puts "attrs_json_file_path #{attrs_json_file_path}"
    #many templates will not have attrs json, hence initializing a default value
    attrs_json = "{}"
    if !(attrs_json_file_path == nil)
      #attrs file is present
      begin
        attrs_json = read_data_from_file_path(attrs_json_file_path)
      rescue Exception => e
        #Mostly this should not happen, but a sanity check
        puts "ERROR: attrs file not found #{e}"
      end
      if attrs_json_file_path.end_with? ".json" and !attrs_json.newline.empty?
        #if attrs file is json, then enforce proper json
        if !JSON.is_valid_json?(attrs_json)
          raise "ERROR: attrs is not a valid JSON"
        end
        attrs_json = "#{attrs_json}"
      end
    end

    if isClientTransformerFound
      client_transformer = client_transformer.newline.tabs
      if client_transformer.scan(/^\s*<%.*%>\s*$/).length == 0
        client_transformer = "<% #{client_transformer} %>"
      end
      if JSON.is_valid_json?(data_template)
        data_template_hash_new = Hash.new
        data_template_hash_new["__transformer"] = client_transformer
        data_template_hash = JSON.parse(data_template)
        data_template_hash_new.merge!(data_template_hash)
        data_template = data_template_hash_new.to_json
      else
        data_template = "#{client_transformer}#{data_template}"
      end
    end

    data_template = ResolveTemplate.new.resolveEnv(data_template, configuration, tenant_id, project_id)
    data_template = ResolveTemplate.new.resolveLang(data_template, configuration, language)
    if is_mario_template
      data_template = modify_data_template_if_its_mario_template(data_template)
      attrs_json = modify_data_template_if_its_mario_template(attrs_json)
    end
    data_template = Base64.encode64(data_template.newline).newline

    if is_apollo_config
      Template.new(template_name, default_content_string, data_template, presentation, attrs_json)
    else
      Template.new(template_name, default_content, data_template, presentation, attrs_json)
    end
  rescue Exception => e
    puts "ERROR: Template loading from #{template_group} failed with error: #{e}"
  end
end

#create_template_from_file_for_zebugger(tenant_id, project_id, configuration, environment, template_group, language, view, template_name, template_path, is_apollo_config) ⇒ Object



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/apollo_commons_ruby/Zebugger.rb', line 81

def create_template_from_file_for_zebugger (tenant_id, project_id, configuration, environment, template_group, language, view, template_name, template_path, is_apollo_config)
  begin

    presentation =  get_presentation_after_conversion_if_neeeded(configuration.apollo_config_base_url, environment, template_path)
    presentation = JSON.parse(presentation).to_json
    presentation = ResolveTemplate.new.resolveLang(presentation.to_json, configuration, language)
    presentation = JSON.parse(presentation, :quirks_mode => true)
    presentation = ResolveTemplate.new.resolveLang(presentation, configuration, language)
    presentation = Base64.encode64(presentation.newline).newline

    #Parsing data template
    data_template_file_path = file_of_name_in_dir_path(template_path,"dataTemplate")
    puts "data_template_file_path #{data_template_file_path}"
    #many templates will not support dataTemplate, hence initializing a default value
    data_template = "{}"
    if !(data_template_file_path == nil)
      #data template file is present
      begin
        data_template = read_data_from_file_path(data_template_file_path)
      rescue Exception => e
        #Mostly this should not happen, but a sanity check
        puts "ERROR: data template file not found #{e}"
      end
      if data_template_file_path.end_with? ".json" and !data_template.newline.empty?
        #if data template file is json, then enforce proper json
        if !JSON.is_valid_json?(data_template)
          raise "ERROR: data template is not a valid JSON"
        end
        data_template = "#{data_template}"
      end
    end

    data_template = ResolveTemplate.new.resolveEnv(data_template, configuration, tenant_id, project_id)
    data_template = ResolveTemplate.new.resolveLang(data_template, configuration, language)
    data_template = Base64.encode64(data_template.newline).newline

    if is_apollo_config
      Template.new(template_name, '', data_template, presentation, "")
    else
      Template.new(template_name, '', data_template, presentation, "")
    end
  rescue Exception => e
    puts "ERROR: Template loading from #{template_group} failed with error: #{e}"
  end
end

#create_template_from_files(template_directory, template_group, language, view, template_name, template_path, tenant_id, project_id, environment) ⇒ Object



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/apollo_commons_ruby/TemplateDebug.rb', line 81

def create_template_from_files(template_directory, template_group, language, view, template_name, template_path, tenant_id, project_id, environment)
    begin
      presentation =  get_presentation_after_conversion_if_neeeded($environmentProperties["apolloConfigBaseUrl"], environment, template_path)
      presentation = JSON.parse(presentation).to_json
      presentation = resolveLang(presentation.to_json, template_directory,language)
      presentation = JSON.parse(presentation, :quirks_mode => true)
      #Parsing data template
      data_template_file_path = file_of_name_in_dir_path(template_path,"dataTemplate")
      puts "data_template_file_path #{data_template_file_path}"
      #many templates will not support dataTemplate, hence initializing a default value
      data_template = "{}"
      if !(data_template_file_path == nil)
        #data template file is present
        begin
          data_template = read_data_from_file_path(data_template_file_path)
        rescue Exception => e
          #Mostly this should not happen, but a sanity check
          puts "ERROR: data template file not found #{e}"
        end
        if data_template_file_path.end_with? ".json" and !data_template.newline.empty?
          #if data template file is json, then enforce proper json
          if !JSON.is_valid_json?(data_template)
            raise "ERROR: data template is not a valid JSON"
          end
          data_template = "#{data_template}"
        end
      end

      client_transformer = ""
      isClientTransformerFound = true
  
      begin
        #Parsing local transformer specific to individual template
        specific_local_transformer_file_path = file_of_name_in_dir_path(template_path,"localTransformer")
        puts "specific_local_transformer_file_path #{specific_local_transformer_file_path}"
        specific_local_transformer = "{}";
        if !(specific_local_transformer_file_path == nil)
          begin
            specific_local_transformer = get_client_transformer_without_require(specific_local_transformer_file_path)
          rescue Exception => e
            puts "ERROR: specific local transformer file not found #{e}"
          end
          puts "specific_local_transformer #{specific_local_transformer}"
          client_transformer = specific_local_transformer
        end
      end
      
      #Parsing attrs json
      attrs_json_file_path = file_of_name_in_dir_path(template_path, "attrs")
      puts "attrs_json_file_path #{attrs_json_file_path}"
      #many templates will not have attrs json, hence initializing a default value
      attrs_json = "{}"
      if !(attrs_json_file_path == nil)
        #attrs file is present
        begin
          attrs_json = read_data_from_file_path(attrs_json_file_path)
        rescue Exception => e
          #Mostly this should not happen, but a sanity check
          puts "ERROR: attrs file not found #{e}"
        end
        if attrs_json_file_path.end_with? ".json" and !attrs_json.newline.empty?
          #if attrs file is json, then enforce proper json
          if !JSON.is_valid_json?(attrs_json)
            raise "ERROR: attrs is not a valid JSON"
          end
          attrs_json = "#{attrs_json}"
        end
      end
  
      if isClientTransformerFound
        client_transformer = client_transformer.newline.tabs
        if client_transformer.scan(/^\s*<%.*%>\s*$/).length == 0
          client_transformer = "<% #{client_transformer} %>"
        end
        if JSON.is_valid_json?(data_template)
          data_template_hash_new = Hash.new
          data_template_hash_new["__transformer"] = client_transformer
          data_template_hash = JSON.parse(data_template)
          data_template_hash_new.merge!(data_template_hash)
          data_template = data_template_hash_new.to_json
        else
          data_template = "#{client_transformer}#{data_template}"
        end
      end
  
      data_template = resolveEnv(data_template, template_directory, environment, tenant_id, project_id)
      data_template = resolveLang(data_template, template_directory, language)
      data_template = modify_data_template_if_its_mario_template(data_template)
      attrs_json = modify_data_template_if_its_mario_template(attrs_json)
      return Templates.new(project_id, template_group, language, view, template_name, presentation, data_template, attrs_json)
    rescue Exception => e
      puts "ERROR: Template loading from #{template_group} failed with error: #{e}"
    end
end

#create_template_mapping_payload(template_group, language, view_type, templateMappings, version) ⇒ Object



204
205
206
207
208
209
210
211
212
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 204

def create_template_mapping_payload(template_group, language, view_type, templateMappings, version)
  body = {
      "templateGroup" => template_group,
      "language" => language,
      "viewType" => view_type,
      "templateMappings" => templateMappings,
      "version" => version
    }
end

#create_zebuggerX_folderObject



107
108
109
110
# File 'lib/apollo_commons_ruby/TemplatePusher.rb', line 107

def create_zebuggerX_folder()
  adb_cmd = 'adb shell mkdir "/storage/emulated/0/Download/zebuggerX"'
  system(adb_cmd)
end

#delete_dir_at_path(path) ⇒ Object



26
27
28
# File 'lib/apollo_commons_ruby/RequestDataUtils.rb', line 26

def delete_dir_at_path(path)
    FileUtils.rm_rf(Dir.pwd + path)
end

#deploy_all_templatesObject



499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 499

def deploy_all_templates()
  # current_dir = Dir.pwd
  # if !current_dir.include? "/Users/ios-ci/.jenkins/jobs/"
  #   puts "This rake command is no more supported. Please use jenkins build http://iosci.corp.zeta.in:8080/job/"
  #   return nil
  # end
  if ENV['should_update_inbox'] == 'true'
    should_update_inbox = true
  else
    should_update_inbox = false
  end

  environment = ENV['environment']
  if environment == nil
    puts "`environment` has to be passed. Environment = `Prod`/'PreProd'/`Staging`"
    return
  end

  if environment.eql?("Prod")
    #perform_git_checks
  end

  require 'ostruct'
  require 'parallel'
  configuration = Configuration.new(environment, nil)
  template_groups = directory_list(configuration.base_folder_path)
  total_tasks_size = 0
  if template_groups
    total_tasks_size = template_groups.size
  end
  puts "Total number of tasks to execute: #{total_tasks_size}"
  puts "\n\n"
  iter = 0
  tasks = []
  template_groups.each do |template_group|
    language_folders = directory_list(configuration.base_folder_path + "/#{template_group}")
    template_group_details = get_parsed_template_group_details(configuration, template_group)
    supported_languages = []
    if template_group_details["supportedLanguages"] != nil
      supported_languages = template_group_details["supportedLanguages"]
    end
    supported_languages.each do |language|
      language_folder = "common"
      if language_folders.include? language
        language_folder = language
      end
      view_types = directory_list(configuration.base_folder_path + "/#{template_group}/#{language_folder}")
      view_types.each do |view_type|
          iter+=1
          puts "Task #{iter}/#{total_tasks_size}: Scheduling deployment for template_group #{template_group} #{language} #{view_type}"
          ENV['environment'] = environment
          ENV['template_group'] = template_group
          ENV['view_type'] = view_type
          ENV['language'] = language

          task_to_schedule = OpenStruct.new
          task_to_schedule.environment = ENV['environment']
          task_to_schedule.template_group = ENV['template_group']
          task_to_schedule.language = ENV['language']
          task_to_schedule.view_type = ENV['view_type']
          task_to_schedule.template_name = ENV['template_name']
          task_to_schedule.version = ENV['version']
          task_to_schedule.tenant_id = ENV['tenant_id']
          task_to_schedule.project_id = ENV['project_id']
          task_to_schedule.should_update_inbox = should_update_inbox
          if ENV['scope_id'] === nil
            raise "scope_id is mandatory for deploying templates."
          end
          task_to_schedule.scope_id = ENV['scope_id']
          task_to_schedule.task_id = iter
          tasks << task_to_schedule
      end
    end
  end
  puts "STARTING DEPLOYMENT NOW"
  results = Parallel.map(tasks, progress: "DEPLOYING ALL TEMPLATES", :in_processes => 1) do |task|
  begin
    deploy_one_template(task)
      rescue Exception => e
      puts "Error for template " + task.template_group + " " + e.backtrace.to_s
      File.open("templateScopeError.txt", "a") do |f|
          f.puts(task.template_group )
      end
    end
  end
  puts "DONE!"
end

#deploy_one_permission(environment, tenantId, projectId, permissionConfigCollectionId, itemId) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/apollo_commons_ruby/Permission.rb', line 38

def deploy_one_permission(environment, tenantId, projectId, permissionConfigCollectionId, itemId)
  permissionConfig = read_data_from_file_path("./permissions/" + itemId + ".json")

  permissionConfig = JSON.pretty_generate(JSON.parse(permissionConfig)).gsub("\n", '').gsub("\t", '')

  request_payload = {
    :itemID => itemId,
    :data => permissionConfig
  }

  url = $environmentProperties["omsBaseUrl"] + "/zeta.in/collections/1.0/setCollectionItem2?to=#{permissionConfigCollectionId}"

  get_token_and_make_request(HTTP::POST, environment, tenantId, projectId, url, request_payload.to_json)
end

#deploy_one_shophook(tenantId, projectId, shophookName, tenantAuthToken) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/apollo_commons_ruby/ShopHook.rb', line 60

def deploy_one_shophook(tenantId, projectId, shophookName, tenantAuthToken)
  shophookConfig = read_data_from_file_path("./shophooks/" + shophookName + ".json")
  raise_exception_if_string_empty(shophookConfig["shopHookId"], "shopHookId")

  shophookConfig = shophookConfig.gsub("\n", ' ').squeeze(' ')

  request_payload = {
    :config => shophookConfig
  }

  url = $environmentProperties["apolloConfigBaseUrl"] + "/1.0/tenant/#{tenantId}/scopes/#{projectId}/shophooks/#{shophookName}"

  code, response = make_GET_request(url, tenantAuthToken)

  if (code == "200" || code == "201")
    return
  end

  make_POST_request(url, request_payload.to_json, tenantAuthToken)
end

#deploy_one_template(task) ⇒ Object



628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 628

def deploy_one_template(task)
  environment = task.environment
  template_group = task.template_group
  language = task.language
  view_type = task.view_type
  template_name = task.template_name
  version = task.version
  scope_id = task.scope_id
  tenant_id = task.tenant_id
  project_id = task.project_id
  should_update_inbox = task.should_update_inbox
  is_mario_template = false
  if (view_type == 'MARIO')
    is_mario_template = true
  end

  configuration = Configuration.new(environment, nil)
  return if configuration == nil

  version = verify_and_get_template_version(version)

  didOnce = false
  template_group_details = get_parsed_template_group_details(configuration,template_group)

  languages = []
  if language == nil
    languages = template_group_details["supportedLanguages"]
  else
    languages.push(language)
  end

  specific_language_folders = []
  dir_path = configuration.template_group_dir_path_for_template(template_group)
  specific_language_folders = directory_list(dir_path)

  if languages.empty?
    return "No language found"
  end

  puts "languages #{languages}"

  languageMappings = template_group_details["languageMappings"]

  languages.each do |language|
    template_language_folder = language
    if !specific_language_folders.include?(language)
      template_language_folder = "common"
    end

    viewTypes = []
    if view_type == nil
      dir_path = configuration.language_dir_path_for_template(template_group, template_language_folder)
      viewTypes = directory_list(dir_path)
    else
      viewTypes.push(view_type)
    end

    if viewTypes.empty?
      return "No view types found"
    end

    puts "viewTypes #{viewTypes}"

    viewTypes.each do |view_type|

      allTemplateVariants = Set.new

      selectedTemplateMappingsInbox = []
      scopeConfigsMercury = []
      dir_path = ""
      if version == nil
        dir_path = configuration.view_type_dir_path_for_template(template_group, template_language_folder, view_type)
      else
        dir_path = configuration.view_type_dir_path_for_template_with_version(template_group, template_language_folder, view_type, version)
      end
      allProbableTemplateNames = all_directory_and_sub_directory_with_character_not_in_dir_path(dir_path, "_")
      puts "For ViewType #{view_type} allProbableTemplateNames #{allProbableTemplateNames}"
      if !(template_name == nil)
        selectedProbableTemplateNames = allProbableTemplateNames.select{|key,value| key == template_name }
      else
        selectedProbableTemplateNames = allProbableTemplateNames
      end

      if selectedProbableTemplateNames.empty?
        puts "Error: No template names found"
        next
      end

      if !languageMappings.nil?
        languageMappingForLanguage = languageMappings[language];
      else
        languageMappingForLanguage = nil;
      end
      puts "languageMapping For #{language} =  #{languageMappingForLanguage}"

      selectedProbableTemplateNames.each do |key, value|
        if !language.eql?("EN") && !key.eql?("default") && !languageMappingForLanguage.nil? && !languageMappingForLanguage.include?(key)
          puts "#{key} not included in languageMappings for #{language}"
          next
        end
        template_mapping = template_mapping_in_dir_path_file_path_with_character(dir_path, value.clone, "_")
        key = ResolveTemplate.new.resolveEnv(key.dup, configuration, tenant_id, project_id)
        template_mapping_inbox = ResolveTemplate.new.resolveEnv(template_mapping.dup, configuration, tenant_id, project_id)
        selectedTemplateMappingsInbox.push(TemplateMapping.new(key, value, template_mapping_inbox))
      end

      if !didOnce
        puts "\n**Updating template group**\n\n"
        if should_update_inbox
           update_template_group_inbox(configuration, template_group, tenant_id, scope_id)
        end
        upsert_template_group_apollo_config(is_mario_template, environment, configuration, scope_id, template_group, view_type, version, tenant_id, project_id)
        didOnce = true
      end

      puts "\n**Updating Templates for language #{language} view_type #{view_type}**\n"
      if should_update_inbox
              puts "\n*Insert default template in inbox*\n"
              selectedTemplateMappingsInbox.each do |template_mapping|
                template_mapping_hash = template_mapping.create_hash
                if template_mapping_hash["template_name"] == "default"
                  if version == nil
                    puts "\n*For template_name #{template_mapping_hash["template_name"]}*\n"
                    templates = create_template_from_file(false, configuration, environment, template_group, language, view_type, template_mapping_hash["template_name"], template_mapping_hash["template_path"], false, tenant_id, project_id).create_hash
                  else
                    puts "\n*For template_name #{template_mapping_hash["template_name"]}*\n"
                    version_path = "#{dir_path}"
                    templates = create_template_from_file(false, configuration, environment, template_group, language, view_type, template_mapping_hash["template_name"], template_mapping_hash["template_path"], false, tenant_id, project_id).create_hash
                  end
                end
                request_payload = CreateTemplatePayload.new(template_group, language, view_type, templates, version)
                puts "\n*Insert Call*\n"
                invoke_API(environment, configuration.post_insert_templates_url, HTTP::POST, nil, request_payload.to_json)
              end
      end

      #Update Templates
      puts "\n*Update templates API Call*\n"

      selectedTemplateMappingsInbox.each do |template_mapping|
        inbox_template_name = scope_id
        if version == nil
          template_mapping_hash = template_mapping.create_hash
          puts "\n*For template_name #{template_mapping_hash["template_name"]}*\n"
          templates = create_template_from_file(false, configuration, environment, template_group, language, view_type, inbox_template_name, template_mapping_hash["template_path"], false, tenant_id, project_id).create_hash
          apollo_config_templates = create_template_from_file(is_mario_template, configuration, environment, template_group, language, view_type, template_mapping_hash["template_name"], template_mapping_hash["template_path"], true, tenant_id, project_id).create_hash
        else
          template_mapping_hash = template_mapping.create_hash
          puts "\n*For template_name #{template_mapping_hash["template_name"]}*\n"
          version_path = "#{dir_path}"
          templates = create_template_from_file(false, configuration, environment, template_group, language, view_type, inbox_template_name, template_mapping_hash["template_path"], false, tenant_id, project_id).create_hash
          apollo_config_templates = create_template_from_file(is_mario_template, configuration, environment, template_group, language, view_type, template_mapping_hash["template_name"], template_mapping_hash["template_path"], true, tenant_id, project_id).create_hash
        end
        if should_update_inbox
           request_payload = CreateTemplatePayload.new(template_group, language, view_type, templates, version)
           puts "\n*Insert Call*\n"
           invoke_API(environment, configuration.post_insert_templates_url, HTTP::POST, nil, request_payload.to_json)
           puts "\n*Update Call*\n"
           invoke_API(environment, configuration.post_update_templates_url, HTTP::POST, nil, request_payload.to_json)
        end
        upsert_templates_apollo_config(environment, configuration, tenant_id, scope_id, template_group, language, view_type, apollo_config_templates, version)
      end

      #Upsert Template Mappings
      puts "\n*Upsert template mapping API Call*\n"
      query_params = {
        :templateGroup => template_group,
        :language => language,
        :viewType => view_type
      }

      if should_update_inbox
              get_templates_for_view_response = invoke_API(environment, configuration.get_templates_for_view_url, HTTP::GET, query_params)
              allTemplateMappingsInbox = get_templates_for_view_response["mappings"]
              if allTemplateMappingsInbox == nil
                allTemplateMappingsInbox = {}
              end
              if !allTemplateMappingsInbox.key?(scope_id)
                allTemplateMappingsInbox.merge!("#{scope_id}": scope_id)
              end
              selectedTemplateMappingsInbox.each do |template_mapping|
                template_mapping_hash = template_mapping.create_mapping
                allTemplateMappingsInbox.merge!(template_mapping_hash)
              end
              request_payload = create_template_mapping_payload(template_group, language, view_type, allTemplateMappingsInbox, version)
              invoke_API(environment, configuration.post_upsert_template_mappings_url, HTTP::POST, nil, request_payload.to_json)
      end
      
      templateMappingsPayload = {}
      selectedTemplateMappingsInbox.each do |template_mapping|
        template_mapping_hash = template_mapping.create_mapping
        templateMappingsPayload.merge!(template_mapping_hash)
      end
      upsert_template_mappings_apollo_config(environment, tenant_id, configuration, scope_id, template_group, language, view_type, templateMappingsPayload, version)
      puts "DONE FOR #{task.task_id}: #{template_group} \n"
    end

  end
end

#deploy_permissions(env) ⇒ Object



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
# File 'lib/apollo_commons_ruby/Permission.rb', line 11

def deploy_permissions(env)
  environment = env["environment"]
  tenantId = env["tenantId"]
  projectId = env["projectId"]
  itemId = env["itemId"]

  raise_exception_if_string_empty(environment, "environment")
  raise_exception_if_string_empty(tenantId, "tenantId")
  raise_exception_if_string_empty(projectId, "projectId")

  load_environment_properties(environment, tenantId, projectId)

  permissionConfigCollectionId = "scopeID." + projectId + "[email protected]"

  if itemId == nil || itemId.empty?
    files = Dir["./permissions/*.json"]
    files.each do |path|
      itemId = File.basename(path, ".json")
      puts "Deploying permission " + itemId
      deploy_one_permission(environment, tenantId, projectId, permissionConfigCollectionId, itemId)
    end
  else
    puts "Deploying permission " + itemId
    deploy_one_permission(environment, tenantId, projectId, permissionConfigCollectionId, itemId)
  end
end

#deploy_shophooks(env) ⇒ Object



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
# File 'lib/apollo_commons_ruby/ShopHook.rb', line 11

def deploy_shophooks(env)
  environment = env["environment"]
  tenantId = env["tenantId"]
  projectId = env["projectId"]
  shophookName = env["shophookName"]

  raise_exception_if_string_empty(environment, "environment")
  raise_exception_if_string_empty(tenantId, "tenantId")
  raise_exception_if_string_empty(projectId, "projectId")

  load_environment_properties(environment, tenantId, projectId)

  if file_exists?("./.apollo/#{environment}.json")
    apolloEnvFile = File.read("./.apollo/#{environment}.json")
    apolloEnv = JSON.parse apolloEnvFile
    tenantAuthToken = apolloEnv["tenantAuthToken"]

  else
    heraAuthToken = env["heraAuthToken"]
    raise_exception_if_string_empty(heraAuthToken, "heraAuthToken")

    puts "getting tenant auth token from apollo app"

    apolloAppUrl = $environmentProperties["apolloAppBaseUrl"] + "/apollo-app/1.0/tenants/#{tenantId}/access-token"

    code, response = make_GET_request(apolloAppUrl, heraAuthToken)

    jsonResponse = JSON.parse(response)
    tenantAuthToken = jsonResponse["access_token"]
  end

  if (tenantAuthToken == nil)
    raise "Failed to get tenantAuthToken from apollo-app"
    return
  end

  if shophookName == nil || shophookName.empty?
    files = Dir["./shophooks/*.json"]
    files.each do |path|
      shophookName = File.basename(path, ".json")
      puts "Deploying shophook " + shophookName
      deploy_one_shophook(tenantId, projectId, shophookName, tenantAuthToken)
    end
  else
    puts "Deploying shophook " + shophookName
    deploy_one_shophook(tenantId, projectId, shophookName, tenantAuthToken)
  end
end

#directory_exists?(directory) ⇒ Boolean

Returns:

  • (Boolean)


457
458
459
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 457

def directory_exists?(directory)
  File.directory?(directory)
end

#directory_list(dir_path) ⇒ Object



702
703
704
705
706
707
708
709
710
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 702

def directory_list(dir_path)
  dirNames = []
  Dir.entries(dir_path).select {
    |entry| File.directory? File.join(dir_path,entry) and !(entry =='.' || entry == '..')
  }.each do |item|
    dirNames.push(item)
  end
  return dirNames
end

#does_templated_data_has_payment_instrument_as_states(templated_data, activePaymentInstrumentID, os) ⇒ Object



682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 682

def does_templated_data_has_payment_instrument_as_states(templated_data, activePaymentInstrumentID, os)
  if os == "android"
    outer_states = templated_data["states"]
    if outer_states
      if !outer_states.empty?
        inner_states = outer_states["states"]
        if !inner_states.empty?
          keys = inner_states.keys
          return keys.include? activePaymentInstrumentID
        end
      end
    end
  end
  if os == "ios"
    outer_states = templated_data["states"]
    keys = outer_states.keys
    return keys.include? activePaymentInstrumentID
  end
end

#extract_json_from_command_output(console_output) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/apollo_commons_ruby/AtroposSubscription.rb', line 63

def extract_json_from_command_output(console_output)
  if console_output.include? "java.lang.RuntimeException"
    return nil
  elsif(console_output.include? "Transformed payload")
    get_transformed_payload = String.new
    put_value_in_get_transformed_payload = false

    console_output.each_line.with_index do |line, index|

      if put_value_in_get_transformed_payload == true
        get_transformed_payload.concat(line)
      end

      if line.include? "Transformed payload"
        put_value_in_get_transformed_payload = true
      end
    end

    get_transformed_payload = JSON.parse(get_transformed_payload.to_s.uncolorize)

    output_json = {:data => get_transformed_payload }.to_json
    return output_json
  else
    return output_json 
  end
end

#file_exists?(file_name) ⇒ Boolean

Returns:

  • (Boolean)


461
462
463
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 461

def file_exists?(file_name)
  File.file?(file_name)
end

#file_of_name_in_dir_path(dir_path, file_name) ⇒ Object



522
523
524
525
526
527
528
529
530
531
532
533
534
535
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 522

def file_of_name_in_dir_path(dir_path, file_name)
  file_path = ""
  begin
    file_path = Dir.entries(dir_path).select {
      |entry| entry.include? file_name
    }.first
    if !(file_path == nil)
      file_path = File.join(dir_path,file_path)
    end
  rescue Exception => e
    puts "ERROR: file_of_name_in_dir_path #{dir_path} #{file_name} #{e}"
  end
  return file_path
end

#form_subscription_infoObject



139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/apollo_commons_ruby/DomainEvent.rb', line 139

def form_subscription_info
    if $domain_event.requestBody["subscriptionInfo"] == nil
        raise "No subscription Info Present in Domain Event Properties"
    end
    if $domain_event.requestBody["subscriptionInfo"]["topicTenantId"] == nil
        raise "No topic tenant id present in subscription Info"
    end
    subscriptionTransformerLocation = $domain_event.location + "/atropos_subscription_transformer.js"
    subscriptionTransformer = File.read(subscriptionTransformerLocation)
    raise_exception_if_string_empty(subscriptionTransformer, "atropos_subscription_transformer")
    $domain_event.requestBody["subscriptionInfo"]["transformer"] = replace_double_quote_with_single_quote(subscriptionTransformer)
    # Only for prod. Remove when changes are deployed in prod
    $domain_event.requestBody["subscribtionInfo"] = $domain_event.requestBody["subscriptionInfo"]
end

#format_translated_line(text) ⇒ Object



391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 391

def format_translated_line(text)
    text = text.to_s.gsub("&#39;", " ")
    text = text.to_s.gsub("&quot;", "\"")
    text = text.to_s.gsub("&lt;", "<")
    text = text.to_s.gsub("&gt;", ">")
    index = 0
    output = ""
    length = text.length
    while index < length
        char = text[index]
        if (char == "%" && index + 1 < length && text[index + 1] == " " && index + 2 < length && is_alpha_char(text[index + 2]))
            output = output + " " + "%" + text[index + 2]
            index = index + 2
        elsif (char == "%" && index + 1 < length && text[index + 1] == " " && index + 2 < length && is_numeric_char(text[index + 2]) &&
            index + 3 < length && text[index + 3] == " " && index + 4 < length && text[index + 4] == "$" &&
            index + 5 < length && text[index + 5] == " " && index + 6 < length && is_alpha_char(text[index + 6]))
            output = output + " " + "%" + text[index + 2] + "$" + text[index + 6]
            index = index + 6
        elsif (char == "\\" && index + 1 < length && text[index + 1] == " " && index + 2 < length && text[index + 2] == "n")
            output = output + "\n"
            index = index + 2
        elsif (char == " " && index + 1 < length && text[index + 1] == "%" && index + 2 < length && text[index + 2] == " " &&
            index + 3 < length && text[index + 3] == "%")
            output = output + "%% "
            index = index + 3
        elsif (char == "<" && index + 1 < length && text[index + 1] == "%" && index + 2 < length && text[index + 2] == " " &&
            index + 3 < length && text[index + 3] == "=")
            output = output + "<%= "
            index = index + 3
        else
            output = output + text[index]
        end
        index = index + 1
    end
    return output
end

#get_all_domain_events(env) ⇒ Object



169
170
171
172
173
174
175
176
177
178
179
180
181
# File 'lib/apollo_commons_ruby/DomainEvent.rb', line 169

def get_all_domain_events(env)
    if env["is_local"] == "false"
        load_environment_properties(env['environment'], env['tenant_id'], env['project_id'])
    else
        load_environment_properties_for_debug(env['environment'], env['tenant_id'], env['project_id'])
    end
    baseMarioUrl = $environmentProperties["apolloMarioBaseUrl"]
    $environment = env['environment']
    marioUrl = baseMarioUrl + "/apollo-mario/1.0/tenants/" + env["tenant_id"] + "/projects/" + env["project_id"] + "/domain-events"
    if env["is_local"] == "false"
         return get_tenant_token_and_make_request(HTTP::GET, $environment, env['tenant_id'], env['project_id'], marioUrl)
    end
end

#get_appropriate_line(line, line_replacement_details) ⇒ Object



438
439
440
441
442
443
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 438

def get_appropriate_line(line, line_replacement_details)
  if (line.strip.start_with?(line_replacement_details.redundant_line_prefix.strip))
      return line_replacement_details.updated_line
  end
  return line
end

#get_client_transformer_without_require(file) ⇒ Object

if !master.eql?(origin_master)

  raise "Master is not in sync with Origin. Pull changes from remote and retry."
end

end



267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 267

def get_client_transformer_without_require(file)
    input_file_path = file.to_s
    final_transformer_output = ""
    line_number_of_require_in_input_file = 0
    line_numbers_to_delete = []
    terminate_processing_of_require_line = false
    #Filter require lines and compute the path to transformer from the line
    File.readlines(input_file_path).each do |require_line|
      line_number_of_require_in_input_file += 1
      is_requires = require_line.index("require ") == 0
      #Iterate through the require lines, until the match is not found.
      #Ignore rest of the lines that match 'require'.
      if is_requires and !terminate_processing_of_require_line then
        #Mark the lines that contain 'require' in the top part of the file
        line_numbers_to_delete << line_number_of_require_in_input_file
        require_line.slice! "require "
        require_line = require_line.strip
        require_line = require_line.gsub('"', '')
        if !file_exists?(require_line)
          raise "ERROR: Transformer file #{require_line} not found"
        end
        transformer_output = read_plain_text_data_from_file_path(require_line)
        if (transformer_output == "")
          raise "ERROR: Transformer file #{require_line} empty"
        end
        #Append transformers in the order of the require statements
        final_transformer_output = final_transformer_output +  transformer_output + "\n"
      else
        terminate_processing_of_require_line = true
      end
    end
    current_file_output = read_plain_text_data_from_file_path(input_file_path)
    if final_transformer_output == "" then
      current_file_output
    else
      current_line_number = 0
      #Strip off 'require' commands from the current file's data(does not modify the file) present in the form of a variable
      client_transformer_with_no_require_lines = ""
      current_file_output.each_line do |line|
        current_line_number += 1
        should_remove_line = line_numbers_to_delete.include? current_line_number
        #Remove the line if we had marked it for removal earlier
        client_transformer_with_no_require_lines << line unless should_remove_line
      end
      #Prepend all the transformers to the script to be updated to the script that does not have 'require' command
      client_transformer_with_no_require_lines = final_transformer_output + "\n" + client_transformer_with_no_require_lines
      client_transformer_with_no_require_lines
    end
end

#get_dependent_template_ids(string, template_id_set = Set.new) ⇒ Object



112
113
114
115
116
117
118
# File 'lib/apollo_commons_ruby/TemplatePusher.rb', line 112

def get_dependent_template_ids(string, template_id_set = Set.new)
  string.scan /templateID\\*\":\s*\\*\"([a-zA-Z0-9\-]*)(_[A-Z][A-Z]*_[A-Z][A-Z]*)?\\*\"/ do |match|
    template_id_set.add(match[0])
  end

  return template_id_set
end

#get_hera_token_and_make_request(type, environment, tenantId, projectId, url, body = nil, query_params = nil, should_log = true) ⇒ Object



97
98
99
# File 'lib/apollo_commons_ruby/NetworkUtils.rb', line 97

def get_hera_token_and_make_request(type, environment, tenantId, projectId, url, body = nil, query_params = nil, should_log = true)
    return get_token_and_make_request(type, environment, tenantId, projectId, url, body, query_params, should_log, false)
end

#get_modified_replacement_property(line_replacement_details) ⇒ Object



451
452
453
454
455
456
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 451

def get_modified_replacement_property(line_replacement_details)
  file_path = line_replacement_details.file_path
  redundant_line_prefix = line_replacement_details.redundant_line_prefix
  updated_line = line_replacement_details.updated_line.to_s[0...-2]
  return LineReplacementProperties.new(file_path, redundant_line_prefix, updated_line)
end

#get_parsed_sample_data_details(configuration, template_group) ⇒ Object



220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 220

def get_parsed_sample_data_details(configuration,template_group)
  sample_data_file_path = configuration.sample_data_file_path_for_template(template_group)
  sampleDataFilesMap = {}
  Dir.glob("#{sample_data_file_path}/*.json") do |json_filename|
    # Do work on files & directories ending in .json
    sample_data_details = read_json_data_from_file_path("#{json_filename}")
    json_filename.delete_prefix!("#{sample_data_file_path}/")
    sampleDataFilesMap[:"#{json_filename}"] = JSON.parse(sample_data_details)
  end
  if sampleDataFilesMap == nil || sampleDataFilesMap == {}
    return nil
  end
  return sampleDataFilesMap
end

#get_parsed_template_group_details(configuration, template_group) ⇒ Object



75
76
77
78
79
# File 'lib/apollo_commons_ruby/Zebugger.rb', line 75

def get_parsed_template_group_details(configuration, template_group)
  template_group_details_file_path = configuration.template_group_details_file_path_for_template(template_group)
  template_group_details = read_json_data_from_file_path(template_group_details_file_path)
  return JSON.parse(template_group_details)
end

#get_presentation_after_conversion_if_neeeded(apolloConfigBaseUrl, environment, template_path) ⇒ Object



771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 771

def get_presentation_after_conversion_if_neeeded(apolloConfigBaseUrl, environment, template_path)
  begin
    #Parsing Presentation
    presentation_file_path = file_of_name_in_dir_path(template_path,"presentation")
    puts "presentation_file_path #{presentation_file_path}"
    presentation = read_data_from_file_path(presentation_file_path)

    #template should fail if presentation file is not present at all
    if presentation_file_path == nil
      raise "ERROR: Presentation file not found at path: #{presentation_file_path}"
    end

    if presentation_file_path.end_with? ".json"
      #if presentation file is json, then enforce proper json
      if !JSON.is_valid_json?(presentation)
        raise "ERROR: Presentation is not a valid JSON"
      end
      presentation = JSON.parse(presentation, :quirks_mode => true).to_json
      return presentation
    elsif presentation_file_path.end_with? ".xml"
      presentation = presentation.newline
      puts "converting presentation xml #{presentation}"
      json_presentation_string = convert_xml_presentation_to_json(environment, apolloConfigBaseUrl, presentation)
      puts "converted presentation to json #{json_presentation_string}"
      return json_presentation_string
    end
  rescue Exception => e
    puts "ERROR: Template loading from #{template_path} failed with error: #{e}"
  end
end

#get_sample_data_path_from_directory(env) ⇒ Object



4
5
6
7
8
9
10
11
# File 'lib/apollo_commons_ruby/RequestDataUtils.rb', line 4

def get_sample_data_path_from_directory(env)
    sampleDataLocation =  Dir.pwd + "/configs/" + env["view_group_definition"] + "/" + env["view_group_component"] + "/" + env["topic"] + "/" + env["event_name"] +  "/sampleData/" + env['environment']
    Dir.entries(sampleDataLocation).sort.each do |sampleData|
        next if sampleData == '.' || sampleData == '..' || sampleData == '.DS_Store'
        return sampleDataLocation + "/" + sampleData
    end
    return nil
end

#get_sample_data_path_from_directory_name(env) ⇒ Object



13
14
15
16
17
18
19
20
# File 'lib/apollo_commons_ruby/RequestDataUtils.rb', line 13

def get_sample_data_path_from_directory_name(env)
    sampleDataLocation =  Dir.pwd + "/configs/" + env["view_group_definition"] + "/" + env["view_group_component"] + "/" + env["topic"] + "/" + env["event_name"] +  "/sampleData/" + env['environment']
    Dir.entries(sampleDataLocation).sort.each do |sampleData|
        next if sampleData == '.' || sampleData == '..' || sampleData == '.DS_Store'
        return sampleData.split(".")[0]
    end
    return nil
end

#get_template_group(env, viewGroupComponent, template_directory) ⇒ Object



202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# File 'lib/apollo_commons_ruby/VerifyMarioConfig.rb', line 202

def get_template_group(env, viewGroupComponent, template_directory)
  task = OpenStruct.new
  task.environment = env['environment']
  task.template_group = viewGroupComponent["templateGroup"]
  task.view_type = 'MARIO'
  task.template_name = 'default'
  task.tenant_id = env['tenant_id']
  task.project_id = env['project_id']
  task.should_update_inbox = false
  task.scope_id = env['project_id']
  if(env['language'] != nil)
    task.language = env['language']
  else
    task.language = 'EN'
  end
  task.is_debug_api = true
  task.template_directory = template_directory
  return get_template_group_details(task)
end

#get_template_group_details(task) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/apollo_commons_ruby/TemplateDebug.rb', line 57

def get_template_group_details(task)
    #Get path
    template_group_directory = task.template_directory + "/Templates/#{task.template_group}"

    #Form the template group
    template_group_transformer = read_data_from_file_path(template_group_directory + "/transformer.js")
    templateGroupDetails = TemplateGroupDetails.new(task.scope_id, task.template_group, template_group_transformer.newline.tabs)

    #Find all the languages
    languages = directory_list(template_group_directory)
    resolved_language = "common"
    languages.each do |language|
      if (language == task.language)
        resolved_language = language
      end
    end
    template = create_template_from_files(task.template_directory, task.template_group, task.language, task.view_type, task.template_name,
    template_group_directory + "/#{resolved_language}/#{task.view_type}/#{task.template_name}", task.tenant_id, task.project_id, task.environment)
    templateGroupDetails.templates.push(template.body)
    templateGroupDetails.body["templates"] = templateGroupDetails.templates
    return templateGroupDetails.body
end

#get_tenant_info(env) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/apollo_commons_ruby/TenantInfo.rb', line 14

def get_tenant_info(env)
    if env["is_local"] == "false"
        load_environment_properties(env['environment'], env['tenant_id'], env['project_id'])
    else
        load_environment_properties_for_debug(env['environment'], env['tenant_id'], env['project_id'])
    end
    baseMarioUrl = $environmentProperties["apolloMarioBaseUrl"]
    $environment = env['environment']
    marioUrl = baseMarioUrl + "/apollo-mario/1.0/tenants/" + env["tenant_id"] + "/projects/" + env["project_id"] + "/tenant-info"
    if env["is_local"] == "false"
         return get_hera_token_and_make_request(HTTP::GET, $environment, env['tenant_id'], env['project_id'], marioUrl)
    end
end

#get_tenant_token(apolloAppBaseUrl, tenantId, heraAuthToken) ⇒ Object



151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/apollo_commons_ruby/NetworkUtils.rb', line 151

def get_tenant_token(apolloAppBaseUrl, tenantId, heraAuthToken)
  if $tenant_token != nil
    puts "Using cached token"
    return $tenant_token
  end
  puts "getting tenant auth token from apollo app"

  newHeraAuthToken = "eyJhbGciOiJFZERTQSJ9.eyJzdWIiOiJOS2ppY0lWbHV4Mmo2YmVsWmpZUndBPT0iLCJ2ZXIiOiIyIiwiaXNzIjoiMC1hZG1pbi5JbmRpYSIsInNhbmRib3giOiIxIiwiYWRkaXRpb25hbF9jbGFpbXMiOnt9LCJhdWQiOiJjaXBoZXIiLCJzdWJqZWN0SklEIjoiTktqaWNJVmx1eDJqNmJlbFpqWVJ3QT09QGF1dGhQcm9maWxlLjAtYWRtaW4uSW5kaWEvOSIsInNjb3BlcyI6WyJhZG1pbiIsImFwaHJvZGl0ZS1hZG1pbiJdLCJleHAiOjE3NzcxMDMyODgsImlhdCI6MTc0NTk5OTI4OCwianRpIjoicHJvdGV1c18xNzQ1OTk5Mjg4ODU0X2ZhZGIwZThmLTkyOGYtNDNiOS05MzRiLTA5M2EyOWI4MmMyZiIsInRlbmFudCI6IjAifQ.Co1rEtIEyXcdCDYsB5N56gxF8YFJGEbuzQEohp57_L7tPWqdia15xOHfO9eRIz46az5sKXm8pa7wmipFgcvhBQ"
  puts "Using Hera Auth Token: #{newHeraAuthToken}"

  apolloAppUrl = apolloAppBaseUrl + "/apollo-app/1.0/tenants/#{tenantId}/access-token"
  code, response = make_GET_request(apolloAppUrl, newHeraAuthToken, nil, false)

  jsonResponse = JSON.parse(response)
  $tenant_token = jsonResponse["access_token"]

  if ($tenant_token == nil)
    raise "Failed to get tenantAuthToken from apollo-app"
    return nil
  end

  return $tenant_token
end

#get_tenant_token_and_make_request(type, environment, tenantId, projectId, url, body = nil, query_params = nil, should_log = true) ⇒ Object



101
102
103
# File 'lib/apollo_commons_ruby/NetworkUtils.rb', line 101

def get_tenant_token_and_make_request(type, environment, tenantId, projectId, url, body = nil, query_params = nil, should_log = true)
    return get_token_and_make_request(type, environment, tenantId, projectId, url, body, query_params, should_log, true)
end

#get_tenant_token_from_apollo_app(env) ⇒ Object



7
8
9
10
11
12
13
14
15
16
# File 'lib/apollo_commons_ruby/TenantTokenCreator.rb', line 7

def get_tenant_token_from_apollo_app(env)
    tenantId = env["tenantId"]
    raise_exception_if_string_empty(tenantId, "tenantId")
    apolloAppBaseUrl = env["apolloAppBaseUrl"]
    heraAuthToken = env["heraAuthToken"]
    tenantToken = get_tenant_token(apolloAppBaseUrl, tenantId, heraAuthToken)
    if tenantToken != nil
        puts "Tenant Token : " + tenantToken
    end
end

#get_token(tenantId, use_tenant_token) ⇒ Object



143
144
145
146
147
148
149
# File 'lib/apollo_commons_ruby/NetworkUtils.rb', line 143

def get_token(tenantId, use_tenant_token)
  if use_tenant_token
    get_tenant_token($environmentProperties["apolloAppBaseUrl"], tenantId, $secretConfig.heraAuthToken)
  else
    $secretConfig.heraAuthToken
  end
end

#get_token_and_make_request(type, environment, tenantId, projectId, url, body = nil, query_params = nil, should_log = true, use_tenant_token = true) ⇒ Object



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/apollo_commons_ruby/NetworkUtils.rb', line 105

def get_token_and_make_request(type, environment, tenantId, projectId, url, body = nil, query_params = nil, should_log = true, use_tenant_token = true)
  if file_exists?("./.apollo/#{environment}.json")
    conf_file = File.read(File.expand_path("./.apollo/#{environment}.json"))
    conf = JSON.parse conf_file
    if use_tenant_token
      authToken = conf["tenantAuthToken"]
    else
      authToken = conf["heraAuthToken"]
    end

  else
    raise_exception_if_string_empty(environment, "environment")
    raise_exception_if_string_empty(tenantId, "tenantId")
    raise_exception_if_string_empty(projectId, "projectId")

    load_environment_properties(environment, tenantId, projectId)
    raise_exception_if_string_empty($environmentProperties["apolloAppBaseUrl"], "apolloAppBaseUrl")

    authToken = get_token(tenantId, use_tenant_token)
  end

  if (authToken == nil)
    raise "Failed to get authToken from apollo-app"
    return
  end

  if type == HTTP::GET
    code, response = make_GET_request(url, authToken, query_params, true)
    return response
  elsif type == HTTP::POST
    response = make_POST_request(url, body, authToken, query_params, true)
  elsif type == HTTP::DELETE
    response = make_DELETE_request(url, body, authToken, query_params, true)
  elsif type == HTTP::PUT
    response = make_PUT_request(url, body, authToken, query_params, true)
  end
end

#get_translated_line(text, target_language) ⇒ Object

$LINE_REPLACEMENT_DETAILS_LIST = Array.new $TRANSLATOR = Google::Cloud::Translate.new(

project_id: "zeta-pay",
credentials: "./keyfile.json"

)



379
380
381
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 379

def get_translated_line(text, target_language)
    return $TRANSLATOR.translate text, to: target_language
end

#handle_domain_event(viewGroupDefinitionName, environment, tenantId, projectId, component, topic, eventName, operation) ⇒ Object



86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/apollo_commons_ruby/DomainEvent.rb', line 86

def handle_domain_event(viewGroupDefinitionName, environment, tenantId, projectId, component, topic, eventName, operation)
  $operation = operation
  $environment = environment
  load_environment_properties(environment, tenantId, projectId)
  puts "view_group_definition: #{viewGroupDefinitionName}"
  puts "component: #{component}"
  puts "topic: #{topic}"
  puts "event_name: #{eventName}"
  $domain_event = DomainEvent.new($environmentProperties, viewGroupDefinitionName, component, topic, eventName)
  if $operation != Operation::DELETE
    prepare_domain_event(viewGroupDefinitionName, component, topic, eventName)
  end
  return perform_domain_event_operation
end

#handle_domain_event_task(env, operation) ⇒ Object



75
76
77
78
79
80
81
82
83
84
# File 'lib/apollo_commons_ruby/DomainEvent.rb', line 75

def handle_domain_event_task(env, operation)
    viewGroupDefinitionName = env["view_group_definition"]
    $environment = env["environment"]
    component = env["view_group_component"]
    topic = env["topic"]
    eventName = env["event_name"]
    tenantId = env["tenant_id"]
    projectId = env["project_id"]
    return handle_domain_event(viewGroupDefinitionName, $environment, tenantId, projectId, component, topic, eventName, operation)
end

#handle_mario_debugger(env, request_data_file_identifier, requestDataJson, is_for_debugging = false, should_pass_local_config_data = false, display_in_zebugger = false) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/apollo_commons_ruby/VerifyMarioConfig.rb', line 52

def handle_mario_debugger(env, request_data_file_identifier, requestDataJson, is_for_debugging = false, should_pass_local_config_data = false, display_in_zebugger = false)
  viewGroupDefinition = env['view_group_definition']
  environment = env['environment']
  component = env['view_group_component']
  topic = env['topic']
  eventName = env['event_name']
  tenantId = env['tenant_id']
  projectId = env['project_id']
  template_directory = nil
  userId = nil
  domainId = nil
  if is_for_debugging == true
    load_environment_properties_for_debug(environment, tenantId, projectId)
    template_directory = $secretConfig.templateDirectory
    userId = $secretConfig.userId
    domainId = $secretConfig.domainId
    authToken = $secretConfig.authToken
  else
    load_environment_properties(environment, tenantId, projectId)
  end
  authToken = $secretConfig.authToken
  $mario_debugger = MarioDebugger.new($environmentProperties, viewGroupDefinition, component, topic, eventName)
  viewGroupComponent = nil
  if is_for_debugging == true
    viewGroupComponent = handle_view_group_component_task(env, Operation::DEBUG)
  end
  response = verify_mario_config(environment, authToken, env, request_data_file_identifier, requestDataJson, is_for_debugging, should_pass_local_config_data, viewGroupComponent, template_directory, userId, domainId)
  if JSON.parse(response)["status"] == 'success' && display_in_zebugger == true
    view_template_on_zebugger(env, viewGroupComponent, template_directory)
  end
  return response
end

#handle_mario_event(viewGroupDefinitionName, environment, tenantId, projectId, component, topic, eventName, requestBody) ⇒ Object



33
34
35
36
37
# File 'lib/apollo_commons_ruby/MarioEvent.rb', line 33

def handle_mario_event(viewGroupDefinitionName, environment, tenantId, projectId, component, topic, eventName, requestBody)
  load_environment_properties(environment, tenantId, projectId)
  $mario_event = MarioEvent.new($environmentProperties, viewGroupDefinitionName, component, topic, eventName, requestBody)
  perform_mario_event_operation
end

#handle_view_group(viewGroupDefinitionName, environment, tenantId, projectId, viewGroupName, domainId, apolloUserId, operation) ⇒ Object



44
45
46
47
48
49
50
# File 'lib/apollo_commons_ruby/ViewGroup.rb', line 44

def handle_view_group(viewGroupDefinitionName, environment, tenantId, projectId, viewGroupName, domainId, apolloUserId, operation)
    $operation = operation
    $environment = environment
    load_environment_properties(environment, tenantId, projectId)
    prepare_view_group(viewGroupDefinitionName, viewGroupName, domainId, apolloUserId)
    perform_view_group_operation
end

#handle_view_group_component(viewGroupDefinitionName, environment, tenantId, projectId, component, operation) ⇒ Object



44
45
46
47
48
49
50
# File 'lib/apollo_commons_ruby/ViewGroupComponent.rb', line 44

def handle_view_group_component(viewGroupDefinitionName, environment, tenantId, projectId, component, operation)
    $operation = operation
    $environment = environment
    load_environment_properties(environment, tenantId, projectId)
    prepare_view_group_component(viewGroupDefinitionName, component)
    return perform_view_group_component_operation
end

#handle_view_group_component_task(env, operation) ⇒ Object



35
36
37
38
39
40
41
42
# File 'lib/apollo_commons_ruby/ViewGroupComponent.rb', line 35

def handle_view_group_component_task(env, operation)
  viewGroupDefinitionName = env["view_group_definition"]
  $environment = env["environment"]
  component = env["view_group_component"]
  tenantId = ENV["tenant_id"]
  projectId = ENV["project_id"]
  return handle_view_group_component(viewGroupDefinitionName, $environment, tenantId, projectId, component, operation)
end

#handle_view_group_definition(viewGroupDefinitionName, environment, tenantId, projectId, operation) ⇒ Object



40
41
42
43
44
45
46
# File 'lib/apollo_commons_ruby/ViewGroupDefinition.rb', line 40

def handle_view_group_definition(viewGroupDefinitionName, environment, tenantId, projectId, operation)
  $operation = operation
  $environment = environment
  load_environment_properties(environment, tenantId, projectId)
  prepare_view_group_definition(viewGroupDefinitionName)
  return perform_view_group_definition_operation
end

#handle_view_group_definition_task(env, operation) ⇒ Object



32
33
34
35
36
37
38
# File 'lib/apollo_commons_ruby/ViewGroupDefinition.rb', line 32

def handle_view_group_definition_task(env, operation)
    viewGroupDefinitionName = env["view_group_definition"]
    $environment = env["environment"]
    tenantId = ENV["tenant_id"]
    projectId = ENV["project_id"]
    return handle_view_group_definition(viewGroupDefinitionName, $environment, tenantId, projectId, operation)
end

#handle_view_group_task(env, operation) ⇒ Object



33
34
35
36
37
38
39
40
41
42
# File 'lib/apollo_commons_ruby/ViewGroup.rb', line 33

def handle_view_group_task(env, operation)
  viewGroupDefinitionName = env["view_group_definition"]
  $environment = env["environment"]
  viewGroupName = env["view_group_name"]
  domainId = env["domain"]
  apolloUserId = env["apollo_user_id"]
  tenantId = ENV["tenant_id"]
  projectId = ENV["project_id"]
  handle_view_group(viewGroupDefinitionName, $environment, tenantId, projectId, viewGroupName, domainId, apolloUserId, operation)
end

#invoke_API(environment, url, type, query_params = nil, body = nil, authToken = nil) ⇒ Object



175
176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'lib/apollo_commons_ruby/NetworkUtils.rb', line 175

def invoke_API(environment, url, type, query_params = nil, body = nil, authToken = nil)
  secretConfig = SecretConfig.new(environment);
  query_params = query_params == nil ? {} : query_params
  if type == HTTP::GET
    code, response = make_GET_request(url, authToken == nil ? secretConfig.authToken : authToken, query_params, true)
  elsif type == HTTP::POST
    response = make_POST_request(url, body, authToken == nil ? secretConfig.authToken : authToken, query_params, true)
  elsif type == HTTP::DELETE
    response = make_DELETE_request(url, body, authToken == nil ? secretConfig.authToken : authToken, query_params, true)
  end
  if response
    JSON.parse response
  end
end

#is_alpha_char(char) ⇒ Object



383
384
385
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 383

def is_alpha_char(char)
    return char == "s" || char == "f" || char == "d"
end

#is_numeric_char(char) ⇒ Object



387
388
389
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 387

def is_numeric_char(char)
    return char == "1" || char == "2" || char == "3" || char == "4" || char == "5" || char == "6" || char == "7" || char == "8" || char == "9"
end

#load_environment_properties(environment, tenantId, projectId) ⇒ Object



36
37
38
39
# File 'lib/apollo_commons_ruby/FileUtils.rb', line 36

def load_environment_properties(environment, tenantId, projectId)
    load_environment_properties_file(environment, tenantId, projectId)
    load_secret_config_file(environment)
end

#load_environment_properties_file(environment, tenantId, projectId) ⇒ Object



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
# File 'lib/apollo_commons_ruby/FileUtils.rb', line 6

def load_environment_properties_file(environment, tenantId, projectId)
    if file_exists?("./.apollo/#{environment}.json")
        apolloEnvFile = File.read("./.apollo/#{environment}.json")
        
        if file_exists?("./environments/#{environment}.json")
            tenantEnvFile = File.read("./environments/#{environment}.json")
        end

        if apolloEnvFile != nil && tenantEnvFile != nil
            $environmentProperties = JSON.parse(tenantEnvFile).merge(JSON.parse(apolloEnvFile))
        elsif tenantEnvFile != nil
            $environmentProperties = JSON.parse tenantEnvFile
        else
            $environmentProperties = JSON.parse apolloEnvFile
        end
    else
        if (environment == 'PreProd')
            environment = 'Preprod'
        end
        envFile = "./environments/" + environment + "/env_" + tenantId + "_" + projectId + ".json"
        if tenantId != nil && projectId != nil && file_exists?(envFile)
            environmentFile = File.read(envFile)
        else
            environmentFile = File.read("./environments/" + environment + "/env.json")
        end

        $environmentProperties = JSON.parse environmentFile
    end
end

#load_environment_properties_for_debug(environment, tenantId, projectId) ⇒ Object



49
50
51
52
53
54
55
56
57
# File 'lib/apollo_commons_ruby/FileUtils.rb', line 49

def load_environment_properties_for_debug(environment, tenantId, projectId)
    if(tenantId != nil && projectId != nil)
        load_environment_properties_file(environment, tenantId, projectId)
        if (environment == 'PreProd')
            environment = 'Preprod'
        end
    end
    $secretConfig = DebugSecretConfig.new(environment)
end

#load_secret_config_file(environment) ⇒ Object



41
42
43
44
45
46
47
# File 'lib/apollo_commons_ruby/FileUtils.rb', line 41

def load_secret_config_file(environment)
  begin
      $secretConfig = SecretConfig.new(environment)
  rescue
      print "Running in local. If on jenkins check secret config file"
  end
end

#log_error(message) ⇒ Object



617
618
619
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 617

def log_error(message)
  puts "ERROR: #{message}".bold.red
end

#log_info(message) ⇒ Object



621
622
623
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 621

def log_info(message)
  puts "INFO: #{message}".bold
end

#make_collection_GET_request(url, query_params = nil) ⇒ Object



495
496
497
498
499
500
501
502
503
504
505
506
507
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 495

def make_collection_GET_request (url, query_params = nil)
  uri = URI(url)
  uri.query = URI.encode_www_form(query_params) if query_params != nil

  response = Net::HTTP.get_response(uri)
  if response.is_a?(Net::HTTPSuccess)
    utf8_encoded = response.body.force_encoding("UTF-8")
    JSON.parse utf8_encoded
  else
    puts "Error occured while loading #{url}\nquery_params: #{query_params}
    Error: #{response.inspect}, #{response.body}"
  end
end

#make_collection_POST_request(url, body, authToken, query_params = nil) ⇒ Object



480
481
482
483
484
485
486
487
488
489
490
491
492
493
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 480

def make_collection_POST_request (url, body, authToken, query_params = nil)
  uri = URI.parse(url)
  uri.query = URI.encode_www_form(query_params) if query_params != nil

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  request = Net::HTTP::Post.new(uri.request_uri,
    initheader = {'Content-Type' =>'application/json', 'X-Zeta-AuthToken' => authToken})
  request.body = body

  puts "#{uri}\n\n"
  puts "#{request.body}\n\n"
  http.request(request).body
end

#make_debug_request(use_tenant_token, environment, tenantId, projectId, url, body, authtoken, request_data_file_identifier, requestDataJson, is_for_debugging, template_directory = nil) ⇒ Object



103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/apollo_commons_ruby/VerifyMarioConfig.rb', line 103

def make_debug_request (use_tenant_token, environment, tenantId, projectId, url, body, authtoken, request_data_file_identifier, requestDataJson, is_for_debugging, template_directory = nil)
  if authtoken == nil
    authtoken = ""
  end
  if use_tenant_token == true
    load_environment_properties(environment, tenantId, projectId)
    authtoken = get_tenant_token($environmentProperties["apolloAppBaseUrl"], tenantId, $secretConfig.heraAuthToken)
  end
  uri = URI.parse(url)
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  request = Net::HTTP::Post.new(uri.request_uri,
                                initheader = {
                                  'Content-Type' =>'application/json',
                                  'X-Zeta-AuthToken' => authtoken,
                                  'Authorization' => 'Bearer ' + authtoken
                              })
  request.body = body
  response = http.request(request)
  base_directory = "./temp/"
  if is_for_debugging == true
    base_directory = "./"
  end
  FileUtils.mkdir_p (base_directory + "configs/" + $mario_debugger.viewGroupDefinition + "/" + $mario_debugger.viewGroupComponent + "/" + $mario_debugger.topic + "/" + $mario_debugger.eventName  + "/debugOutputs")
  # Initialize Logger File Path
  $LOGGER_FILE = base_directory + "configs/" + $mario_debugger.viewGroupDefinition + "/" + $mario_debugger.viewGroupComponent + "/" + $mario_debugger.topic + "/" + $mario_debugger.eventName  + "/debugOutputs/logs_" + request_data_file_identifier + ".log"
  # Verify if file exists or not
  if(File.exist?($LOGGER_FILE))
    File.delete($LOGGER_FILE)
  end

  # Create new file
  log = Logger.new($LOGGER_FILE)
    #Write to output file
    output_file = base_directory + "configs/" + $mario_debugger.viewGroupDefinition + "/" + $mario_debugger.viewGroupComponent + "/" + $mario_debugger.topic + "/" + $mario_debugger.eventName  + "/debugOutputs/output_" + request_data_file_identifier + ".json"

  # Write api response
  if (JSON.parse(response.body)["status"] == 'success')
    log.info "\n\n\nURL :" + url
    log.info "\n\nRequest Body :" + JSON.pretty_generate(JSON.parse(request.body))
    log.info "\n\n\nResponse Body:" + JSON.pretty_generate(JSON.parse(response.body))
    puts "#{JSON.pretty_generate(JSON.parse(response.body))}"
    write_output_to_files(output_file, request_data_file_identifier, response, template_directory)
    return response.body
  else
    log.info "\n\n\nURL :" + url
    log.info "\n\nRequest Body :" + JSON.pretty_generate(JSON.parse(request.body))
    stringified_response = JSON.pretty_generate(JSON.parse(response.body))
    log.info "\n\n\nResponse Body :"+ stringified_response
    puts "#{stringified_response}"

    failure_reason = '{"Failure Reason" : "Unable to get template Data"}'
    if stringified_response.include? "in.zeta.springframework.boot.commons.authorization.sandboxAccessControl.UnauthorizedException"
        message = "Invalid Tenant Token in userInfo. Get tenant token from https://apollo-ci.zetaapps.in/view/Apollo%20Automation/job/get-tenant-token/build".red
        failure_reason = '{"Failure Reason" : "#{message}"}'
        raise "#{message}"
    elsif stringified_response.include? "UNAUTHORIZED"
        message = "Invalid Tenant Token in userInfo. Get tenant token from https://apollo-ci.zetaapps.in/view/Apollo%20Automation/job/get-tenant-token/build".red
        failure_reason = '{"Failure Reason" : "#{message}"}'
        raise "#{message}"
    end
    if stringified_response.include? "View Group Context Transformer Compilation Error"
       failure_reason = '{"Failure Reason" : "Invalid View Group Context Transformer. Check if the js has missing variable, unescaped double quotes, comments, unstringified undefined or strings begin with double quote"}'
    elsif stringified_response.include? "WebClientResponseException"
       failure_reason = '{"Failure Reason" : "Har Api Call is failing. If unauthorized is present check the auth token else contact the respective service owner and notify them about the issue"}'
    elsif stringified_response.include? "TimeoutException"
       failure_reason = '{"Failure Reason" : "Har Api Call is timing out. Contact the service owner and tell them to check. To unblock yourself for testing purposes add timeoutDuration in Har Config. Give the the duration in milliseconds"}'
    elsif stringified_response.include? "TypeError: Cannot read property"
       failure_reason = '{"Failure Reason" : "Check your transformer.js file. The compilation is failing. Check if the js has missing variable, unescaped double quotes, comments, unstringified undefined or strings begin with double quote"}'
    elsif stringified_response.include? "Invalid Template Group Transformer, not appending transformer data Reason"
       failure_reason = '{"Failure Reason" : "Check your transformer.js file. The compilation is failing. Check if the js has missing variable, unescaped double quotes, comments, unstringified undefined or strings begin with double quote"}'
    elsif stringified_response.include? "Unable to get itemid templating data list for device"
       failure_reason = '{"Failure Reason" : "Check your view group context item id transformer js string. The compilation is failing. Check if the js has missing variable, unescaped double quotes, comments, unstringified undefined or strings begin with double quote"}'
    end
    write_data_to_file(output_file, JSON.parse(failure_reason))
    return response.body
  end
end

#make_DELETE_request(url, body = nil, authToken = nil, query_params = nil, should_log = true) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/apollo_commons_ruby/NetworkUtils.rb', line 55

def make_DELETE_request (url, body = nil, authToken = nil, query_params = nil, should_log = true)
  uri = URI.parse(url)
  uri.query = URI.encode_www_form(query_params) if query_params != nil

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  request = Net::HTTP::Delete.new(uri.request_uri,
                                  initheader = {
                                    'Content-Type' =>'application/json',
                                    'X-Zeta-AuthToken' => authToken,
                                    'Authorization' => 'Bearer ' + authToken
                                  })
  if body != nil
    request.body = body
  end

  puts "#{uri}\n\n" if should_log
  puts "#{request.body}\n\n" if should_log
  response = http.request(request)
  puts "#{response.body}\n\n" if should_log
  return response.body
end

#make_GET_request(url, authToken, query_params = nil, should_log = true) ⇒ Object



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/apollo_commons_ruby/NetworkUtils.rb', line 78

def make_GET_request (url, authToken, query_params = nil, should_log = true)
  uri = URI.parse(url)
  uri.query = URI.encode_www_form(query_params) if query_params != nil

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  request = Net::HTTP::Get.new(uri.request_uri,
                                  initheader = {
                                    'X-Zeta-AuthToken' => authToken,
                                    'Authorization' => 'Bearer ' + authToken
                                  })

  puts "#{uri}\n\n" if should_log
  puts "#{request.body}\n\n" if should_log
  response = http.request(request)
  puts "#{response.body}\n\n" if should_log
  return response.code, response.body
end

#make_POST_request(url, body, authtoken, query_params = nil, should_log = true) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/apollo_commons_ruby/NetworkUtils.rb', line 31

def make_POST_request (url, body, authtoken, query_params = nil, should_log = true)
  if authtoken == nil
    authtoken = ""
  end
  uri = URI.parse(url)
  uri.query = URI.encode_www_form(query_params) if query_params != nil
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  request = Net::HTTP::Post.new(uri.request_uri,
                                initheader = {
                                  'Content-Type' =>'application/json',
                                  'X-Zeta-AuthToken' => authtoken,
                                  'Authorization' => 'Bearer ' + authtoken
                              })
  request.body = body

  puts "#{uri}\n\n" if should_log
  puts "#{request.body}\n\n" if should_log
  response = http.request(request)
  puts "#{response.body}\n\n" if should_log
  return response.body
end

#make_PUT_request(url, body, authtoken, query_params = nil, should_log = true) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/apollo_commons_ruby/NetworkUtils.rb', line 8

def make_PUT_request (url, body, authtoken, query_params = nil, should_log = true)
  if authtoken == nil
    authtoken = ""
  end
  uri = URI.parse(url)
  uri.query = URI.encode_www_form(query_params) if query_params != nil
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  request = Net::HTTP::Put.new(uri.request_uri,
                                initheader = {
                                  'Content-Type' =>'application/json',
                                  'X-Zeta-AuthToken' => authtoken,
                                  'Authorization' => 'Bearer ' + authtoken
                              })
  request.body = body

  puts "#{uri}\n\n" if should_log
  puts "#{request.body}\n\n" if should_log
  response = http.request(request)
  puts "#{response.body}\n\n" if should_log
  return response.body
end

#modify_data_template_if_its_mario_template(data_template) ⇒ Object



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 181

def modify_data_template_if_its_mario_template(data_template)
  if data_template.include? "'\\n'"
    data_template.gsub! "'\\n'", "'$$n$$'"
  end
  if data_template.include? "\\\""
    data_template.gsub! "\\\"", "$$q$$"
  end
  if data_template.include? "\n"
    data_template.gsub! "\n", ""
  end
  if data_template.include? "\""
    data_template.gsub! "\"", "'"
  end
  if data_template.include? "'$$n$$'"
    data_template.gsub! "'$$n$$'", "'\\n'"
  end
  if data_template.include? "$$q$$"
    data_template.gsub! "$$q$$", "\\\”"
  end
  puts "After Apollo Mario V8 modifications \n" + data_template
  return data_template
end

#modify_file_line(line_replacement_details) ⇒ Object



428
429
430
431
432
433
434
435
436
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 428

def modify_file_line(line_replacement_details)
  file_path = line_replacement_details.file_path
  modified_file = IO.readlines(file_path).map do |line|
      get_appropriate_line(line, line_replacement_details)
  end
  File.open(file_path, 'w') do |file|
      file.puts modified_file
  end
end

#parse_template_id(configuration, template_id, language, view_type) ⇒ Object



120
121
122
123
124
125
126
# File 'lib/apollo_commons_ruby/TemplatePusher.rb', line 120

def parse_template_id(configuration, template_id, language, view_type)
  template_id_parts = template_id.split('_')
  template_group = template_id_parts[0]
  template_name = "default"
  template_path = resolve_template_path(configuration, template_group, language, view_type, template_name)
  return template_path
end

#perform_domain_event_operationObject



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/apollo_commons_ruby/DomainEvent.rb', line 108

def perform_domain_event_operation
    if $operation == Operation::DEBUG
        return $domain_event.requestBody
    end
    baseMarioUrl = $environmentProperties["apolloMarioBaseUrl"]
    marioUrl = baseMarioUrl + "/apollo-mario/1.0/tenants/" + $domain_event.tenantId + "/projects/" + $domain_event.projectId + "/view-group-definitions/" + $domain_event.viewGroupDefinition + "/components/" + $domain_event.viewGroupComponent + "/topics/" + $domain_event.topic + "/domain-events/" + $domain_event.eventName
    replace_environment_based_config_in_string(marioUrl, $environmentProperties)
    if $operation == Operation::PUT
        get_tenant_token_and_make_request(HTTP::PUT, $environment, $domain_event.tenantId, $domain_event.projectId, marioUrl,
                    replace_environment_based_config_in_string(JSON.generate($domain_event.requestBody), $environmentProperties))
        return
    end
    if $operation == Operation::DELETE
        get_tenant_token_and_make_request(HTTP::DELETE, $environment, $domain_event.tenantId, $domain_event.projectId, marioUrl)
    end
end

#perform_mario_event_operationObject



39
40
41
42
43
44
45
# File 'lib/apollo_commons_ruby/MarioEvent.rb', line 39

def perform_mario_event_operation
    baseMarioUrl = $environmentProperties["apolloMarioBaseUrl"]
    authToken = $secretConfig.authToken
    marioUrl = baseMarioUrl + "/apollo-mario/1.0/tenants/" + $mario_event.tenantId + "/projects/" + $mario_event.projectId + "/view-group-definitions/" + $mario_event.viewGroupDefinition + "/components/" + $mario_event.viewGroupComponent + "/topics/" + $mario_event.topic + "/events/" + $mario_event.eventName + "/subscription"
    replace_environment_based_config_in_string(marioUrl, $environmentProperties)
    make_POST_request(marioUrl,replace_environment_based_config_in_string(JSON.generate(JSON.parse $mario_event.requestBody), $environmentProperties), authToken)
end

#perform_view_group_component_operationObject



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/apollo_commons_ruby/ViewGroupComponent.rb', line 56

def perform_view_group_component_operation
    raise_exception_if_string_empty($viewGroupComponent.requestBody["templateGroup"], "templateGroup")
    if $operation == Operation::DEBUG
        return $viewGroupComponent.requestBody
    end
    baseMarioUrl = $environmentProperties["apolloMarioBaseUrl"]
    authToken = $secretConfig.authToken
    marioUrl = baseMarioUrl + "/apollo-mario/1.0/tenants/" + $viewGroupComponent.tenantId + "/projects/" + $viewGroupComponent.projectId + "/view-group-definitions/" + $viewGroupComponent.viewGroupDefinition + "/components/" + $viewGroupComponent.viewGroupComponent
    replace_environment_based_config_in_string(marioUrl, $environmentProperties)
    if $operation == Operation::PUT
       get_tenant_token_and_make_request(HTTP::PUT, $environment, $viewGroupComponent.tenantId, $viewGroupComponent.projectId, marioUrl,
            replace_environment_based_config_in_string(JSON.generate($viewGroupComponent.requestBody), $environmentProperties))
       return
    end
    if $operation == Operation::DELETE
       get_tenant_token_and_make_request(HTTP::DELETE, $environment, $viewGroupComponent.tenantId, $viewGroupComponent.projectId, marioUrl)
    end
end

#perform_view_group_definition_operationObject



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/apollo_commons_ruby/ViewGroupDefinition.rb', line 52

def perform_view_group_definition_operation
    if $operation == Operation::DEBUG
        return $viewGroupDefinition.requestBody
    end
    baseMarioUrl = $environmentProperties["apolloMarioBaseUrl"]
    authToken = $secretConfig.authToken
    marioUrl = baseMarioUrl + "/apollo-mario/1.0/tenants/" + $viewGroupDefinition.tenantId + "/projects/" + $viewGroupDefinition.projectId + "/view-group-definitions/" + $viewGroupDefinition.viewGroupDefinition
    replace_environment_based_config_in_string(marioUrl, $environmentProperties)
    if $operation == Operation::PUT
        get_tenant_token_and_make_request(HTTP::PUT, $environment, $viewGroupDefinition.tenantId, $viewGroupDefinition.projectId,
                marioUrl, replace_environment_based_config_in_string(JSON.generate($viewGroupDefinition.requestBody), $environmentProperties))
        return
    end
    if $operation == Operation::DELETE
        get_tenant_token_and_make_request(HTTP::DELETE, $environment, $viewGroupDefinition.tenantId, $viewGroupDefinition.projectId, marioUrl)
    end
end

#perform_view_group_operationObject



56
57
58
59
60
61
62
63
64
# File 'lib/apollo_commons_ruby/ViewGroup.rb', line 56

def perform_view_group_operation
    baseMarioUrl = $environmentProperties["apolloMarioBaseUrl"]
    authToken = $secretConfig.authToken
    marioUrl = baseMarioUrl + "/apollo-mario/1.0/tenants/" + $viewGroup.tenantId + "/projects/" + $viewGroup.projectId + "/domains/" + $viewGroup.domainId + "/users/" + $viewGroup.apolloUserId + "/view-group-definitions/" + $viewGroup.viewGroupDefinition + "/view-groups/" + $viewGroup.viewGroupName
    replace_environment_based_config_in_string(marioUrl, $environmentProperties)
    if $operation == Operation::DELETE
        get_tenant_token_and_make_request(HTTP::DELETE, $environment, $viewGroup.tenantId, $viewGroup.projectId, marioUrl)
    end
end

#prepare_domain_event(view_group_definition, component, topic, event_name) ⇒ Object



101
102
103
104
105
106
# File 'lib/apollo_commons_ruby/DomainEvent.rb', line 101

def prepare_domain_event(view_group_definition, component, topic, event_name)
    associate_user_details_transformer_in_request_body
    associate_view_group_context_transformer_in_request_body
    form_subscription_info
    associate_hars_with_in_request_body
end

#prepare_view_group(viewGroupDefinitionName, viewGroupName, domainId, apolloUserId) ⇒ Object



52
53
54
# File 'lib/apollo_commons_ruby/ViewGroup.rb', line 52

def prepare_view_group(viewGroupDefinitionName, viewGroupName, domainId, apolloUserId)
    $viewGroup = ViewGroup.new($environmentProperties, viewGroupDefinitionName, viewGroupName, domainId, apolloUserId)
end

#prepare_view_group_component(view_group_definition, component) ⇒ Object



52
53
54
# File 'lib/apollo_commons_ruby/ViewGroupComponent.rb', line 52

def prepare_view_group_component(view_group_definition, component)
    $viewGroupComponent = ViewGroupComponent.new($environmentProperties, view_group_definition, component)
end

#prepare_view_group_definition(view_group_definition) ⇒ Object



48
49
50
# File 'lib/apollo_commons_ruby/ViewGroupDefinition.rb', line 48

def prepare_view_group_definition(view_group_definition)
    $viewGroupDefinition = ViewGroupDefinition.new($environmentProperties, view_group_definition)
end


611
612
613
614
615
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 611

def print_header(message)
  print_separator()
  puts message.bold.magenta
  print_separator()
end


607
608
609
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 607

def print_separator()
  puts "------------------------------------------------------------------------------------------------".green
end


678
679
680
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 678

def print_separator_line()
  puts "--------------------------------------------------------------------------------------------------------------------------------------"
end

#push_templates_to_device(configuration, environment, template_group, template_path, dependent_template_ids, language, view_type, platform) ⇒ Object



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
# File 'lib/apollo_commons_ruby/TemplatePusher.rb', line 8

def push_templates_to_device(configuration, environment, template_group, template_path, dependent_template_ids, language, view_type, platform)
  templates_set_including_root = Set.new
  templates_set_including_root.add(template_group)
  templates_set_including_root.merge dependent_template_ids
  print_separator_line()
  puts "Found " + templates_set_including_root.size().to_s + " file(s) in total to be pushed to device"
  print_separator_line()
  
  is_real_device_connected, is_simulator_connected = check_for_device_connection(platform)
  
  adb_push_presentation(configuration, environment, template_group, template_path, true, language, view_type, platform, is_real_device_connected, is_simulator_connected)

  dependent_template_ids.each do |item|
    item = item.tr('"','')
    dependent_template_path = parse_template_id(configuration, item, language, view_type)
    if dependent_template_path == nil
      puts "invalid template id #{item}"
      next
    end
    dependent_template_group = item.split('_')[0]
    adb_push_presentation(configuration, environment, dependent_template_group, dependent_template_path, false, language, view_type, platform, is_real_device_connected, is_simulator_connected)
  end

  adb_push_template_data(template_group, language, view_type, platform, is_real_device_connected, is_simulator_connected)
end

#push_to_ios_device(bundle_id, source_file_path, destination_file_path) ⇒ Object



92
93
94
95
96
# File 'lib/apollo_commons_ruby/TemplatePusher.rb', line 92

def push_to_ios_device(bundle_id, source_file_path, destination_file_path)
  cmd = "ios-deploy --bundle_id #{bundle_id} --upload #{source_file_path} --to #{destination_file_path}"
  puts "Pushing file #{source_file_path} to connected ios device for bundleId #{bundle_id}"
  system(cmd)
end

#push_to_ios_simulator(bundle_id, source_file_path, destination_file_path) ⇒ Object



98
99
100
101
102
103
104
105
# File 'lib/apollo_commons_ruby/TemplatePusher.rb', line 98

def push_to_ios_simulator(bundle_id, source_file_path, destination_file_path)
  final_destination_file_path = `xcrun simctl get_app_container booted #{bundle_id} data`
  final_destination_file_path.to_s.delete!("\n")
  final_destination_file_path = final_destination_file_path + "#{destination_file_path}"
  cmd = "cp #{source_file_path} #{final_destination_file_path}"
  puts "Pushing file #{source_file_path} to newest opened ios simulator for bundleId #{bundle_id}"
  system(cmd)
end

#raise_exception_if_string_empty(string, identifier) ⇒ Object



107
108
109
110
111
# File 'lib/apollo_commons_ruby/FileUtils.rb', line 107

def raise_exception_if_string_empty(string, identifier)
    if string == nil || string.empty?
        raise "Empty " + identifier
    end
end

#read_data_from_file_of_name_in_dir_path(dir_path, file_name) ⇒ Object



537
538
539
540
541
542
543
544
545
546
547
548
549
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 537

def read_data_from_file_of_name_in_dir_path(dir_path, file_name)
  file_data = {}
  begin
    file_path = Dir.entries(dir_path).select {
      |entry| entry.include? file_name
    }.first
    file_path = File.join(dir_path,file_path)
    file_data = File.read(file_path)
  rescue Exception => e
    puts "Reading from #{file_path} failed with error: #{e}"
  end
  return file_data
end

#read_data_from_file_path(file_path) ⇒ Object



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/apollo_commons_ruby/FileUtils.rb', line 121

def read_data_from_file_path(file_path)
  file_data = {}
  begin
    if (file_exists?(file_path))
      in_file = File.read(file_path)
      return if in_file == nil
      file_data = in_file
    else
      file_data = {}
    end
  rescue Exception => e
    puts "Reading from #{file_path} failed with error: #{e}"
    file_data = {}
  end
  return file_data
end

#read_json_data_from_file_path(file_path) ⇒ Object



659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 659

def read_json_data_from_file_path(file_path)
  file_data = {}
  begin
    if (file_exists?(file_path))
      in_file = File.read(file_path)
      return if in_file == nil
      data = JSON.parse(in_file)
      data = data.to_json
      file_data = data
    else
      file_data = {}
    end
  rescue Exception => e
    puts "Reading from #{file_path} failed with error: #{e}"
    file_data = {}
  end
  return file_data
end

#read_new_app_template_groups_from_configObject



625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 625

def read_new_app_template_groups_from_config()
  new_app_template_groups = Array.new
  file_path = "new_app_template_groups.json"

  begin
    new_app_templates_config = read_raw_json_data_from_file_path(file_path)
    if new_app_templates_config["templateGroups"].is_a?(Array)
      new_app_template_groups = new_app_templates_config["templateGroups"]
    else
      throw "templateGroups inside config is not an array"
    end
  rescue Exception => e
    log_error("Failed to read new_app_template_groups_config with error: #{e}")
  end
  return new_app_template_groups
end

#read_plain_text_data_from_file_path(file_path) ⇒ Object



568
569
570
571
572
573
574
575
576
577
578
579
580
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 568

def read_plain_text_data_from_file_path(file_path)
  file_data = ""
  begin
    if (file_exists?(file_path))
      in_file = File.read(file_path)
      return if in_file == nil
      file_data = in_file
    end
  rescue Exception => e
    puts "Reading from #{file_path} failed with error: #{e}"
  end
  return file_data
end

#read_raw_json_data_from_file_path(file_path) ⇒ Object



642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 642

def read_raw_json_data_from_file_path(file_path)
  data = Hash.new
  begin
    if(file_exists?(file_path))
      in_file = File.read(file_path)
      if in_file != nil
        data = JSON.parse(in_file)
      else
        throw "Contents are nil"
      end
    end
  rescue Exception => e
    log_error("Failed to read contents of file at path [#{file_path}]with error: #{e}")
  end
  return data
end

#read_res_data_from_file_path(file_path) ⇒ Object



582
583
584
585
586
587
588
589
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 582

def read_res_data_from_file_path(file_path)
  file_data = {}
  if (!file_exists?(file_path))
    file_path = "./Resources/EN.json"
  end
  file_data = read_data_from_file_path(file_path)
  return file_data
end

#replace_double_quote_with_single_quote(body) ⇒ Object



93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/apollo_commons_ruby/FileUtils.rb', line 93

def replace_double_quote_with_single_quote(body)
    if body.include? "\\\""
        body.gsub! "\\\"", "$$q$$"
    end
    if body.include? "\""
        puts "Replacing \" with '"
        body.gsub! "\"", "'"
    end
    if body.include? "$$q$$"
        body.gsub! "$$q$$", "\\\”"
    end
    return body
end

#replace_environment_based_config_in_string(body, environment) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/apollo_commons_ruby/FileUtils.rb', line 59

def replace_environment_based_config_in_string(body, environment)
    environment.each do |key, value|
        substring_key = "<<" + key + ">>"
        if body.include? substring_key
            puts "Replacing " + substring_key
            body.gsub! substring_key, value
        end
    end
    if body.include? "\\n"
        puts "Replacing " + "\\n"
        body.gsub! "\\n", ""
    end
    return body
end

#replace_single_quote(body) ⇒ Object



85
86
87
88
89
90
91
# File 'lib/apollo_commons_ruby/FileUtils.rb', line 85

def replace_single_quote(body)
    if body.include? "'"
        puts "Replacing " + "'"
        body.gsub! "'", "\\\""
    end
    return body
end

#resolve_template_path(configuration, template_group, language, view_type, template_name) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/apollo_commons_ruby/Zebugger.rb', line 60

def resolve_template_path(configuration, template_group, language, view_type, template_name)
  template_group_details = get_parsed_template_group_details(configuration, template_group)

  specific_language_folders = []
  dir_path = configuration.template_group_dir_path_for_template(template_group)
  specific_language_folders = directory_list(dir_path)

  template_language_folder = language
  if !specific_language_folders.include?(language)
    template_language_folder = "common"
  end

  return Dir.pwd + "/Templates/#{template_group}/#{template_language_folder}/#{view_type}/#{template_name}"
end

#resolveEnv(data_template, template_directory, environment, tenantId, project_id) ⇒ Object



176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/apollo_commons_ruby/TemplateDebug.rb', line 176

def resolveEnv(data_template, template_directory, environment, tenantId, project_id)
    if environment == 'PreProd'
        environment = 'Preprod'
    end
    envFilePath = template_directory + "/environments/#{environment}/env_#{tenantId}_#{project_id}.json"
    envData = read_data_from_file_path(envFilePath)
    envData = JSON.parse(envData)
    data_template = data_template.force_encoding("UTF-8")
    envData.each do |key, value|
        substring_key = "{{" + key + "}}"
        if data_template.include? substring_key
            puts "Replacing " + substring_key
            data_template.gsub! substring_key, value
        end
    end
    return data_template
end

#resolveLang(data_template, template_directory, language) ⇒ Object



194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/apollo_commons_ruby/TemplateDebug.rb', line 194

def resolveLang(data_template, template_directory, language)
    langFilePath = template_directory + "/Resources/#{language}.json"
    langData = read_res_data_from_file_path(langFilePath)
    langData = JSON.parse(langData)
    data_template = data_template.force_encoding("UTF-8")
    langData.each do |key, value|
        substring_key = "<<" + key + ">>"
        if data_template.include? substring_key
            puts "Replacing " + substring_key
            data_template.gsub! substring_key, value
        end
    end
    return data_template
end

#reverse_replace_environment_based_config_in_string(body, environment) ⇒ Object



74
75
76
77
78
79
80
81
82
83
# File 'lib/apollo_commons_ruby/FileUtils.rb', line 74

def reverse_replace_environment_based_config_in_string(body, environment)
    environment.each do |key, value|
        substring_key = "<<" + key + ">>"
        if body.include? value
            puts "Replacing " + value
            body.gsub! value, substring_key
        end
    end
    return body
end

#send_webhook_message(env, message) ⇒ Object



5
6
7
8
9
10
11
12
13
# File 'lib/apollo_commons_ruby/WebhookReporting.rb', line 5

def send_webhook_message(env, message)
  load_environment_properties(env['environment'], env['tenant_id'], env['project_id'])
  if $environmentProperties['webhookUrl'] == nil
    puts "MESSAGE COULD NOT BE SENT SINCE WEBHOOKURL IN ENVIRONMENT FILE IS MISSING".red
  else
    requestBody = { "flockml":message }.to_json
    return make_POST_request($environmentProperties['webhookUrl'], requestBody, "")
  end
end

#setup_appID_uiview_template_group_directory(template_group, appID) ⇒ Object



591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 591

def setup_appID_uiview_template_group_directory(template_group, appID)
  base_path = TemplateConfig.template_group_parent_directory_path_for_appID(template_group, appID)
  contents_path = TemplateConfig.template_group_contents_path_for_appID(template_group, appID)
  if (directory_exists?(base_path))
    puts "Template parent directory for appID: #{appID} already exists at path: #{base_path}"
  else
    Dir.mkdir base_path
  end

  if (directory_exists?(contents_path))
    puts "Template contents directory for appID: #{appID} already exists at path: #{contents_path}"
  else
    Dir.mkdir contents_path
  end
end

#template_mapping_in_dir_path_file_path_with_character(dir_path, file_path, character) ⇒ Object



745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 745

def template_mapping_in_dir_path_file_path_with_character(dir_path, file_path, character)
  dir_path += "/"
  file_path.slice! dir_path
  mapping_components = file_path.split('/')
  template_mapping = "";
  mapping_components.each do |item|
    if item == "default"
      template_mapping = "*"
    else
      length = item.length
      indexOfCharacter = item.index(character)
      indexOfTemplater = item.index("{{")
      if indexOfCharacter and indexOfCharacter >= 0 and (!indexOfTemplater || indexOfCharacter < indexOfTemplater)
        item_component = item.slice!(indexOfCharacter+1..length-1)
        if template_mapping.empty?
          mapping = item_component
        else
          mapping = "_" + item_component
        end
        template_mapping += mapping
      end
    end
  end
  return template_mapping
end

#update_domain_event(env) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/apollo_commons_ruby/DomainEvent.rb', line 55

def update_domain_event(env)
    begin
            atropos_transformer_js_validation_jar_output_data = validate_atropos_transformer_and_get_output(env, nil)
            if atropos_transformer_js_validation_jar_output_data == nil
                puts "Invalid Atropos subscription Transformer"
                return nil
            else
                is_valid_config = validate_mario_config(env, get_sample_data_path_from_directory_name(env), atropos_transformer_js_validation_jar_output_data, false, true)
                if is_valid_config != true
                    puts "There might be issues in the config. Please fix and deploy again".red
                end
            end
        rescue
            puts "Unable to validate Domain Event"
    end
        handle_view_group_definition_task(env, Operation::PUT)
        handle_view_group_component_task(env, Operation::PUT)
        handle_domain_event_task(env, Operation::PUT)
end

#update_existing_translations(source_path, language_resource_path) ⇒ Object



317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 317

def update_existing_translations(source_path, language_resource_path)
  if (!file_exists?(language_resource_path))
    log_error("Update Failed! No translation resource found at path [ #{language_resource_path} ]")
    abort()
  end

  if (!file_exists?(source_path))
    log_error("No source file found at path [ #{source_path} ]")
    abort()
  end

  source_file_plain_text_data = read_plain_text_data_from_file_path(source_path)

  new_translations = Hash.new
  source_file_plain_text_data.split("\r\n").each { |value|
    key_value_array = value.split(',')
    # puts "Value: #{value} key_value_array: #{key_value_array}"
    # abort()
    if key_value_array.length >= 2
      key = key_value_array[0]
      key_value_array.delete_at(0)
      value = key_value_array.join

      new_translations[key] = value
    else
      log_error("Terminating! Found incorrect translation key,pair [ #{key_value_array}]")
      abort()
    end
  }

  old_translations = read_raw_json_data_from_file_path(language_resource_path);

  new_translations.each { |key, value|
    if old_translations.has_key?(key)
      old_translations[key] = value
      log_info("Updated translation for key [ #{key} ] with value: [ #{value} ]")
    else
      log_error("Key #{key} does not exist in existing translations. Ignoring it")
    end
  }

  if new_translations.length > 0
    log_info("Writing updated translations to file at path [ #{language_resource_path}]")
    write_data_to_file(language_resource_path, old_translations)
  else
    log_info("Translations not updated due to no new updates")
  end

end

#update_template_group_inbox(configuration, template_group, tenant_id, project_id) ⇒ Object



587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 587

def update_template_group_inbox(configuration, template_group, tenant_id, project_id)
  query_params = {
    :templateGroup => template_group
  }
  environment = configuration.environment
  puts "\n*Fetching template group details API call*\n"
  template_group_details_response = invoke_API(environment, configuration.get_template_group_details_url, HTTP::GET, query_params)

  shouldMakeUpdateTemplateGroupCall = false

  if template_group_details_response["templateGroup"] == template_group
    shouldMakeUpdateTemplateGroupCall = true
  end

  template_group_details = get_parsed_template_group_details(configuration,template_group)

  transformer_file_path = configuration.transfomer_file_path_for_template(template_group)
  transformer_data = read_data_from_file_path(transformer_file_path)
  transformer_data = ResolveTemplate.new.resolveEnv(transformer_data, configuration, tenant_id, project_id)

  field_ordering = template_group_details["fieldOrdering"]
  expected_data = template_group_details["expectedData"]

  # TODO: Handle case where field_ordering is not empty.
  field_ordering = ["appID"]

  request_payload = {
    :templateGroup => template_group,
    :expectedData => expected_data,
    :fieldOrdering => field_ordering,
    :transformer => transformer_data
  }

  puts "\n*Update template group API call*\n"
  if shouldMakeUpdateTemplateGroupCall
    invoke_API(environment, configuration.post_update_template_group_url, HTTP::POST, nil, request_payload.to_json)
  else
    invoke_API(environment, configuration.post_insert_template_group_url, HTTP::POST, nil, request_payload.to_json)
  end
end

#upsert_template_group_apollo_config(is_mario_template, environment, configuration, scope_id, template_group, view, version, tenant_id, project_id) ⇒ Object



828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 828

def upsert_template_group_apollo_config(is_mario_template, environment, configuration, scope_id, template_group, view, version, tenant_id, project_id)

  template_group_details = get_parsed_template_group_details(configuration, template_group)

  transformer_file_path = configuration.transfomer_file_path_for_template(template_group)
  transformer_data = read_data_from_file_path(transformer_file_path)
  transformer_data = ResolveTemplate.new.resolveEnv(transformer_data, configuration, tenant_id, project_id)
  if is_mario_template
    transformer_data = modify_data_template_if_its_mario_template(transformer_data)
  end
  sample_data_details = get_parsed_sample_data_details(configuration,template_group)
  attrs = {
    :sampleData => sample_data_details
  }

  field_ordering = template_group_details["fieldOrdering"]
  expected_data = template_group_details["expectedData"]

  request_payload = {
    :expectedData => expected_data,
    :fieldOrdering => field_ordering,
    :transformer => transformer_data,
    :version => version,
    :attrs => attrs.to_json
  }

  puts "\n*[Apollo-config]: Upsert template group API call*\n"
  url = configuration.apollo_config_base_url + "/1.0/tenant/#{tenant_id}/scopes/#{scope_id}/templateGroups/#{template_group}"
  get_tenant_token_and_make_request(HTTP::POST, environment, tenant_id, scope_id, url, request_payload.to_json)
end

#upsert_template_mappings_apollo_config(environment, tenant_id, configuration, scope_id, template_group, language, view, mappings, version) ⇒ Object



859
860
861
862
863
864
865
866
867
868
869
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 859

def upsert_template_mappings_apollo_config(environment, tenant_id, configuration, scope_id, template_group, language, view, mappings, version)

  request_payload = {
    :mappings => mappings,
    :version => version
  }

  puts "\n*[Apollo-config]: Upsert template mappings API call*\n"
  url = configuration.apollo_config_base_url + "/1.0/tenant/#{tenant_id}/scopes/#{scope_id}/templateGroups/#{template_group}/languages/#{language}/views/#{view}/mappings"
  get_tenant_token_and_make_request(HTTP::POST, environment, tenant_id, scope_id, url, request_payload.to_json)
end

#upsert_templates_apollo_config(environment, configuration, tenant_id, scope_id, template_group, language, view, templates, version) ⇒ Object



871
872
873
874
875
876
877
878
879
880
881
882
883
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 871

def upsert_templates_apollo_config(environment, configuration, tenant_id, scope_id, template_group, language, view, templates, version)

  request_payload = {
    :templates => templates,
    :version => version,
    :tenantID => tenant_id
  }

  puts "\n*[Apollo-config]: Upsert templates API call*\n"
  url = configuration.apollo_config_base_url + "/1.0/tenant/#{tenant_id}/scopes/#{scope_id}/templateGroups/#{template_group}/languages/#{language}/views/#{view}/templates"
  get_tenant_token_and_make_request(HTTP::POST, environment, tenant_id, scope_id, url, request_payload.to_json)

end

#validate_atropos_subscription_js_file(jarFilePath, sample_data_file, transformer_file_path) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/apollo_commons_ruby/AtroposSubscription.rb', line 38

def validate_atropos_subscription_js_file(jarFilePath, sample_data_file, transformer_file_path)
  if sample_data_file == nil
      puts "Sample Data File Not Provided. Skipping Domain Event Validation. Please update sample data to ensure domain event stability"
      raise "Sample Data not provided"
  end
  if sample_data_file.include? "<"
      sample_data_file = sample_data_file.to_s.gsub! "<", "\\<"
  end
  if sample_data_file.include? ">"
      sample_data_file = sample_data_file.to_s.gsub! ">", "\\>"
  end
  if transformer_file_path.include? "<"
      transformer_file_path = transformer_file_path.to_s.gsub! "<", "\\<"
  end
  if transformer_file_path.include? ">"
      transformer_file_path = transformer_file_path.to_s.gsub! ">", "\\>"
  end
  puts "Transformer File Path => #{transformer_file_path}".green
  puts "Sample Data File Path => #{sample_data_file}".green
  puts "Jar File Path => #{jarFilePath}".green
  command = "java -jar " + jarFilePath + " transform webhook "+ sample_data_file + " " + transformer_file_path
  executeShellCommand = ExecuteShellCommand.new
  return executeShellCommand.run_command(command)
end

#validate_atropos_transformer_and_get_output(env, sample_data_file_path, transformer_file_path = nil) ⇒ Object



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
# File 'lib/apollo_commons_ruby/AtroposSubscription.rb', line 12

def validate_atropos_transformer_and_get_output(env, sample_data_file_path, transformer_file_path = nil)

  load_environment_properties(env['environment'], env["tenant_id"], env["project_id"])

  if sample_data_file_path == nil
      sample_data_file_path = get_sample_data_path_from_directory(env)
  end

  is_temp_transformer_file_used = false
  if transformer_file_path == nil
      is_temp_transformer_file_used = true
      transformer_file_path_base = Dir.pwd + "/configs/" + env["view_group_definition"] + "/" + env["view_group_component"]+ "/" + env["topic"] + "/" + env["event_name"]
      transformer_file_path =  transformer_file_path_base + "/atropos_subscription_transformer_temp.js"
      write_to_file(transformer_file_path, replace_environment_based_config_in_string(File.read(transformer_file_path_base + "/atropos_subscription_transformer.js"), $environmentProperties))
  end

  jarFilePath = File.dirname(File.dirname(File.join(File.dirname(File.expand_path(__FILE__)),'/jar'))) + '/jar/v1_atroposDevTools.jar'

  command_output = validate_atropos_subscription_js_file(jarFilePath, sample_data_file_path, transformer_file_path)

  if is_temp_transformer_file_used == true
      File.delete(Dir.pwd + "/configs/" + env["view_group_definition"] + "/" + env["view_group_component"]+ "/" + env["topic"] + "/" + env["event_name"] + "/atropos_subscription_transformer_temp.js")
  end
  return extract_json_from_command_output(command_output)
end

#validate_local_configs(env) ⇒ Object



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/apollo_commons_ruby/MarioConfigsStability.rb', line 84

def validate_local_configs(env)
        environment = env["environment"]
        tenantId = env["tenant_id"]
        projectId = env["project_id"]

        Dir.foreach('./configs') do |viewGroupDefinition|
            next if viewGroupDefinition == '.' || viewGroupDefinition == '..' ||  viewGroupDefinition == '.DS_Store'
            Dir.foreach('./configs/' + viewGroupDefinition) do |viewGroupComponent|
                next if viewGroupComponent == '.' || viewGroupComponent == '..' || viewGroupComponent == 'view_group_definition_properties.json' ||  viewGroupComponent == '.DS_Store'
                Dir.foreach('./configs/' + viewGroupDefinition + "/" + viewGroupComponent) do |topic|
                    next if topic == '.' || topic == '..' || topic == 'view_group_component_properties.json' ||  topic == '.DS_Store'
                    Dir.foreach('./configs/' + viewGroupDefinition + "/" + viewGroupComponent + "/" + topic) do |eventName|
                        next if eventName == '.' || eventName == '..' ||  eventName == '.DS_Store'
                        puts "Debugging domain event for topic " + topic + " and eventName = " + eventName + " and viewGroupDefinition = " + viewGroupDefinition + " and component = " + viewGroupComponent
                        task = Hash.new
                        task['environment'] = env['environment']
                        task['view_group_definition'] = viewGroupDefinition
                        task['view_group_component'] = viewGroupComponent
                        task['topic'] = topic
                        task['event_name'] = eventName
                        task['tenant_id'] = env['tenant_id']
                        task['project_id'] = env['project_id']
                        begin
                            task['request_data_file'] = get_sample_data_path_from_directory_name(task)
                            begin
                                validate_local_domain_event(task)
                            rescue => exception
                                puts "Unable to validate mario config"
                                puts exception.backtrace
                            end
                        rescue => exception
                            puts "Sample Data not present"
                        end
                    end
                end
            end
        end
end

#validate_local_domain_event(env) ⇒ Object



123
124
125
126
127
128
129
130
131
132
133
# File 'lib/apollo_commons_ruby/MarioConfigsStability.rb', line 123

def validate_local_domain_event(env)
    atropos_transformer_js_validation_jar_output_data = validate_atropos_transformer_and_get_output(env, nil)
    if atropos_transformer_js_validation_jar_output_data == nil
       puts "Invalid Atropos Subscription Transformer"
       raise "Invalid Atropos Subscription Transformer"
    end
    status = validate_mario_config(env, env['request_data_file'], atropos_transformer_js_validation_jar_output_data, true, true)
    if status == false
        raise "Invalid Configuration"
    end
end

#validate_mario_config(env, request_data_file_identifier, request_data, is_for_debugging, should_pass_local_config_data) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/apollo_commons_ruby/VerifyMarioConfig.rb', line 38

def validate_mario_config(env, request_data_file_identifier, request_data, is_for_debugging, should_pass_local_config_data)
       debug_api_response = handle_mario_debugger(env, request_data_file_identifier, request_data, is_for_debugging, should_pass_local_config_data, false)
       if JSON.parse(debug_api_response)["status"] == 'failure' || JSON.parse(debug_api_response)["status"] == nil
          stringified_response = JSON.pretty_generate(JSON.parse(debug_api_response))
          puts "Failure Response : #{stringified_response}"
          # Api call failure. Allow the configuration to be updated
          if stringified_response.include? "WebClientResponseException"
            return true
          end
          return false
       end
       return true
end

#validate_mario_configs(env) ⇒ Object



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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/apollo_commons_ruby/MarioConfigsStability.rb', line 13

def validate_mario_configs(env)
    environment = env['environment']
    env["is_local"] = "false"
    load_environment_properties(env['environment'], env['tenant_id'], env['project_id'])
    tenant_info = get_tenant_info(env)
    tenant_info = JSON.parse(tenant_info)
    if tenant_info['isEnabled'] == false
        puts "TENANT IS DISABLED. NOT PROCEEDING"
        return
    end
    all_domain_events = get_all_domain_events(env)
    if all_domain_events == nil
        puts "DOMAIN EVENT DATA IS NULL. COULD NOT PROCEED"
        return
    end
    all_domain_events = JSON.parse(all_domain_events)
    all_domain_events.each do |domainEventData|
              domain_event_data_json = JSON.parse(domainEventData.to_json)
              viewGroupDefinition = domain_event_data_json['viewGroupDefinition']
              component = domain_event_data_json['component']
              domainEventName = domain_event_data_json['domainEventName']
              topic = domain_event_data_json['topic']
              atroposTransformer = nil
              atroposTransformer = replace_double_quote_with_single_quote(domain_event_data_json['subscriptionInfo']['transformer'])
              next if domain_event_data_json['attrs'] == nil || domain_event_data_json['attrs']['sampleData'] == nil || domain_event_data_json['attrs']['sampleData'].size == 0
              sampleData = domain_event_data_json['attrs']['sampleData'][0]
              task = Hash.new
              task['environment'] = env['environment']
              task['view_group_definition'] = viewGroupDefinition
              task['view_group_component'] = component
              task['topic'] = topic
              task['event_name'] = domainEventName
              task['tenant_id'] = env['tenant_id']
              task['project_id'] = env['project_id']
              task['request_data_file'] = "sampleData"
              begin
                      base_location = Dir.pwd + "/temp/configs/" + task["view_group_definition"] + "/" + task["view_group_component"] + "/" + task["topic"] + "/" + task["event_name"]
                      create_dir_at_path(Dir.pwd + "/temp")
                      create_dir_at_path(Dir.pwd + "/temp/configs")
                      create_dir_at_path(Dir.pwd + "/temp/configs/" + task["view_group_definition"])
                      create_dir_at_path(Dir.pwd + "/temp/configs/" + task["view_group_definition"] + "/" + task["view_group_component"])
                      create_dir_at_path(Dir.pwd + "/temp/configs/" + task["view_group_definition"] + "/" + task["view_group_component"] + "/" + task["topic"])
                      create_dir_at_path(Dir.pwd + "/temp/configs/" + task["view_group_definition"] + "/" + task["view_group_component"] + "/" + task["topic"] + "/" + task["event_name"])
                      create_dir_at_path(Dir.pwd + "/temp/configs/" + task["view_group_definition"] + "/" + task["view_group_component"] + "/" + task["topic"] + "/" + task["event_name"] + "/sampleData")
                      create_dir_at_path(Dir.pwd + "/temp/configs/" + task["view_group_definition"] + "/" + task["view_group_component"] + "/" + task["topic"] + "/" + task["event_name"] + "/sampleData/" + env['environment'])
                      atropos_transformer_location_temp = base_location + "/atropos_subscription_transformer.js"
                      sample_data_location_temp = base_location + "/sampleData/" + env['environment'] + "/sampleData.json"
                      write_to_file(atropos_transformer_location_temp, atroposTransformer)
                      write_to_file(sample_data_location_temp, sampleData.to_json)
                      requestData = validate_atropos_transformer_and_get_output(task, sample_data_location_temp, atropos_transformer_location_temp)
                      if requestData == nil
                         send_webhook_message(task, compose_message(task, "Invalid Atropos Subscription Transformer"))
                      else
                         debug_api_response = handle_mario_debugger(task, "sampleData", requestData, false, false)
                         if JSON.parse(debug_api_response)["status"] == 'failure' || JSON.parse(debug_api_response)["status"] == nil
                             stringified_response = JSON.pretty_generate(JSON.parse(debug_api_response))
                             send_webhook_message(task, compose_message(task, stringified_response))
                         end
                      end
              rescue => exception
                puts exception
                send_webhook_message(task, compose_message(task, "Invalid Configuration"))
              end
              begin
                delete_dir_at_path("/temp")
              rescue => exception
                puts "Unable to delete temp directory"
              end
    end
end

#verify_and_get_template_version(version) ⇒ Object



235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 235

def verify_and_get_template_version(version)
  allowed_versions = {"v2" => "iOS_v2", "v3" => "iOS_v3"}
  if version == nil
    return nil
  end

  if allowed_versions.has_value?(version)
    return version
  end

  if allowed_versions.key?(version)
    return allowed_versions[version]
  end

  raise "Unsupported template version: #{version}"
end

#verify_mario_config(environment, authToken, env, request_data_file_identifier, requestDataJson, is_for_debugging, should_pass_local_config_data, viewGroupComponent, template_directory = nil, userId = nil, domainId = nil) ⇒ Object



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/apollo_commons_ruby/VerifyMarioConfig.rb', line 85

def verify_mario_config(environment, authToken, env, request_data_file_identifier, requestDataJson, is_for_debugging, should_pass_local_config_data, viewGroupComponent, template_directory = nil, userId = nil, domainId = nil)
  baseMarioUrl = $environmentProperties["apolloMarioBaseUrl"]
  marioUrl = baseMarioUrl + "/apollo-mario/1.0/tenants/" + $mario_debugger.tenantId + "/projects/" + $mario_debugger.projectId + "/view-group-definitions/" + $mario_debugger.viewGroupDefinition + "/components/" + $mario_debugger.viewGroupComponent + "/topics/" + $mario_debugger.topic + "/events/" + $mario_debugger.eventName + "/debug"
  requestDataJson = JSON.parse(requestDataJson)
  if should_pass_local_config_data == true
      requestDataJson["viewGroupDefinition"] = handle_view_group_definition_task(env, Operation::DEBUG)
      requestDataJson["viewGroupComponent"] = viewGroupComponent
      requestDataJson["domainEvent"] = handle_domain_event_task(env, Operation::DEBUG)
  end
  if is_for_debugging == true
     requestDataJson["templateGroupDetails"] = get_template_group(env, viewGroupComponent, template_directory)
  end
  requestDataJson["useMockViewGroup"] = true
  # make a post request
  return make_debug_request(!is_for_debugging, environment, $mario_debugger.tenantId, $mario_debugger.projectId, replace_environment_based_config_in_string(marioUrl, $environmentProperties),
         replace_environment_based_config_in_string(JSON.generate(requestDataJson), $environmentProperties), authToken, request_data_file_identifier, requestDataJson, is_for_debugging, template_directory)
end

#view_template_on_zebugger(env, viewGroupComponent, templateDirectory) ⇒ Object



193
194
195
196
197
198
199
# File 'lib/apollo_commons_ruby/VerifyMarioConfig.rb', line 193

def view_template_on_zebugger(env, viewGroupComponent, templateDirectory)
  zebugger_cmd = "cd #{templateDirectory}; rake zebugger environment=#{env["environment"]} " + "template_group=#{viewGroupComponent["templateGroup"]} language=EN view_type=MARIO platform=#{env["platform"]} tenant_id=#{env['tenant_id']} project_id=#{env['project_id']} templated_data_ready=true"
  begin 
    system(zebugger_cmd)
  rescue
  end
end

#write_data_to_file(file_path, data) ⇒ Object



509
510
511
512
513
514
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 509

def write_data_to_file(file_path, data)
  out_file = File.new(file_path, "w")
  out_file.truncate(0)
  out_file.puts JSON.pretty_generate data
  out_file.close
end

#write_output_to_files(output_file, requestDataJson, response, templateDirectory) ⇒ Object



182
183
184
185
186
187
188
189
190
191
# File 'lib/apollo_commons_ruby/VerifyMarioConfig.rb', line 182

def write_output_to_files(output_file, requestDataJson, response, templateDirectory)
  templateData = JSON.parse(JSON.parse(response.body)["items"][0]["data"])["payloads"]["payload1"]["templateData"]
  write_data_to_file(output_file, templateData)

  if templateDirectory != nil
    #Write to templates directory
    FileUtils.mkdir_p templateDirectory + "/scripts/commonData"
    write_data_to_file(templateDirectory + "/scripts/commonData/generatedTemplatedData.json", templateData)
  end
end

#write_templated_data_to_file(configuration, collection_data) ⇒ Object



516
517
518
519
520
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 516

def write_templated_data_to_file(configuration, collection_data)
  out_file = File.new(configuration.templated_data_file_path, "w")
  out_file.puts JSON.pretty_generate collection_data
  out_file.close
end

#write_to_file(output_file, data) ⇒ Object



113
114
115
116
117
118
119
# File 'lib/apollo_commons_ruby/FileUtils.rb', line 113

def write_to_file(output_file, data)
    File.new(output_file, 'w+')
      File.open(output_file, 'w') {|file| file.truncate(0) }
      File.open(output_file, "w") do |f|
        f.write(data)
      end
end