Top Level Namespace

Defined Under Namespace

Modules: ApolloCommonsRuby, HTTP, JSON, MarioConfig, Operation, TemplatesTasks Classes: Configuration, CreateCollectionItem, CreateTemplatePayload, DomainEvent, LineReplacementProperties, MarioEvent, ResolveTemplate, SecretConfig, String, Template, TemplateBuilder, TemplateConfig, TemplateMapping, ViewGroup, ViewGroupComponent, ViewGroupDefinition

Instance Method Summary collapse

Instance Method Details

#add_translations_for_language(module_name, languages) ⇒ Object



444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 444

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

#additional_template_data(configuration) ⇒ Object



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

def additional_template_data(configuration)
  collection_data = {}
  begin
    file_path = configuration.additional_data_file_path
    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
      collection_data = data
    else
      collection_data = {}
    end
  rescue Exception => e
    puts "Additional Data loading from #{file_path} failed with error: #{e}"
    collection_data = {}
  end
  return collection_data
end

#all_directory_and_sub_directory_in_dir_path(dir_path) ⇒ Object



768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 768

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



752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 752

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



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

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 == '..'
        puts "har: #{har}"
        harFile = File.read(harsLocation + "/" + har)
        harJson = JSON.parse harFile
        harsArr.push(harJson)
    end
    $domain_event.requestBody["hars"] = harsArr
end

#associate_user_details_transformer_in_request_bodyObject



83
84
85
86
87
88
# File 'lib/apollo_commons_ruby/DomainEvent.rb', line 83

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



90
91
92
93
94
95
# File 'lib/apollo_commons_ruby/DomainEvent.rb', line 90

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

#cached_template_data(configuration) ⇒ Object



542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 542

def cached_template_data(configuration)
  collection_data = {}
  begin
    file_path = configuration.common_data_file_path
    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
      collection_data = data
    else
      collection_data = {}
    end
  rescue Exception => e
    puts "Cached Data loading from #{file_path} failed with error: #{e}"
    collection_data = {}
  end
  return collection_data
end

#change_line_in_file(line_replacement_list) ⇒ Object



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

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

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

require “google/cloud/translate”



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

def create_template_from_file (is_mario_template, configuration, template_group, language, view, template_name, template_path, is_apollo_config, tenant_id, project_id)
  begin

    puts "template_name #{template_name}"
    #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).to_json
      presentation = ResolveTemplate.new.resolveLang(presentation.to_json, configuration,language)
      presentation = JSON.parse(presentation, :quirks_mode => true)
    end
    if presentation_file_path.end_with? ".html"
      presentation = ResolveTemplate.new.resolveLang(presentation, configuration, language)
      presentation = Base64.encode64(presentation).newline
    else
      presentation = ResolveTemplate.new.resolveLang(presentation, configuration, language)
      presentation = Base64.encode64(presentation.newline).newline
    end

    #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

    #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)
    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_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

#deploy_all_templatesObject



484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
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
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 484

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

  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)
  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|
    #template_group = "MCCS-grant-VOUCHER"
    shouldIgnore = false;
    iter+=1
    if shouldIgnore
      puts "Task #{iter}/#{total_tasks_size}: Ignoring for templateGroup #{template_group} because already done in previous build"
      next
    else
      puts "Task #{iter}/#{total_tasks_size}: Scheduling deployment for template_group #{template_group}"
    end
    ENV['environment'] = environment
    ENV['template_group'] = template_group

    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.should_update_inbox = false
    task_to_schedule.tenant_id = ENV['tenant_id']
    task_to_schedule.project_id = ENV['project_id']
    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
  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_template(task) ⇒ Object



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
586
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
627
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
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 557

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
  should_update_inbox = task.should_update_inbox
  tenant_id = task.tenant_id
  project_id = task.project_id
  is_mario_template = task.is_mario_template

  configuration = Configuration.new(environment)
  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(environment, configuration, template_group, scope_id, tenant_id, project_id)
        end
        upsert_template_group_apollo_config(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(is_mario_template, configuration, 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(is_mario_template, configuration, 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(is_mario_template, configuration, 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, 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(is_mario_template, configuration, 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, 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, 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, configuration, scope_id, template_group, language, view_type, templateMappingsPayload, version)
      puts "DONE FOR #{task.task_id}: #{template_group} \n"
    end

  end
end

#directory_exists?(directory) ⇒ Boolean

Returns:

  • (Boolean)


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

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

#directory_list(dir_path) ⇒ Object



742
743
744
745
746
747
748
749
750
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 742

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



722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 722

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

#file_exists?(file_name) ⇒ Boolean

Returns:

  • (Boolean)


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

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

#file_of_name_in_dir_path(dir_path, file_name) ⇒ Object



562
563
564
565
566
567
568
569
570
571
572
573
574
575
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 562

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_subscribtion_infoObject



97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/apollo_commons_ruby/DomainEvent.rb', line 97

def form_subscribtion_info
    if $domain_event.requestBody["subscribtionInfo"] == nil
        raise "No subscribtion Info Present in Domain Event Properties"
    end
    if $domain_event.requestBody["subscribtionInfo"]["topicTenantId"] == nil
        raise "No topic tenant id present in Subscribtion Info"
    end
    subscribtionTransformerLocation = $domain_event.location + "/atropos_subscribtion_transformer.js"
    subscribtionTransformer = File.read(subscribtionTransformerLocation)
    raise_exception_if_string_empty(subscribtionTransformer, "atropos_subscribtion_transformer")
    $domain_event.requestBody["subscribtionInfo"]["transformer"] = subscribtionTransformer
end

#format_translated_line(text) ⇒ Object



376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 376

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_appropriate_line(line, line_replacement_details) ⇒ Object



423
424
425
426
427
428
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 423

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



252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
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
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 252

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_modified_replacement_property(line_replacement_details) ⇒ Object



436
437
438
439
440
441
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 436

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_template_group_details(configuration, template_group) ⇒ Object



214
215
216
217
218
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 214

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_translated_line(text, target_language) ⇒ Object

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

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

)



364
365
366
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 364

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



48
49
50
51
52
53
# File 'lib/apollo_commons_ruby/DomainEvent.rb', line 48

def handle_domain_event(viewGroupDefinitionName, environment, tenantId, projectId, component, topic, eventName, operation)
  $operation = operation
  load_environment_properties(environment, tenantId, projectId)
  prepare_domain_event(viewGroupDefinitionName, component, topic, eventName)
  perform_domain_event_operation
end

#handle_domain_event_task(env, operation) ⇒ Object



37
38
39
40
41
42
43
44
45
46
# File 'lib/apollo_commons_ruby/DomainEvent.rb', line 37

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"]
    handle_domain_event(viewGroupDefinitionName, environment, tenantId, projectId, component, topic, eventName, operation)
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, tenantUserId, operation) ⇒ Object



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

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

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



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

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

#handle_view_group_component_task(env, operation) ⇒ Object



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

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"]
  handle_view_group_component(viewGroupDefinitionName, environment, tenantId, projectId, component, operation)
end

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



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

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

#handle_view_group_definition_task(env, operation) ⇒ Object



29
30
31
32
33
34
35
# File 'lib/apollo_commons_ruby/ViewGroupDefinition.rb', line 29

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

#handle_view_group_task(env, operation) ⇒ Object



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

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

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



391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 391

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

#is_alpha_char(char) ⇒ Object



368
369
370
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 368

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

#is_numeric_char(char) ⇒ Object



372
373
374
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 372

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



6
7
8
9
10
# File 'lib/apollo_commons_ruby/FileUtils.rb', line 6

def load_environment_properties(environment)
    environmentFile = File.read("./environments/" + environment + "/env.json")
    $environmentProperties = JSON.parse environmentFile
    $secretConfig = SecretConfig.new(environment)
end

#log_error(message) ⇒ Object



657
658
659
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 657

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

#log_info(message) ⇒ Object



661
662
663
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 661

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

#make_collection_GET_request(url, query_params = nil) ⇒ Object



472
473
474
475
476
477
478
479
480
481
482
483
484
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 472

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



457
458
459
460
461
462
463
464
465
466
467
468
469
470
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 457

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_DELETE_request(url, body, authToken, query_params = nil, should_log = true) ⇒ Object



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

def make_DELETE_request (url, authtoken)
  if authtoken == nil
    authtoken = ""
  end
  uri = URI.parse(url)

  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
                                  })

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

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



424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 424

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 = {'Content-Type' =>'application/json', 'X-Zeta-AuthToken' => authToken})

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

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



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/apollo_commons_ruby/NetworkUtils.rb', line 28

def make_POST_request (url, body, authtoken)
  if authtoken == nil
    authtoken = ""
  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
                              })
  request.body = body

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

#make_PUT_request(url, body, authtoken) ⇒ Object



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

def make_PUT_request (url, body, authtoken)
  if authtoken == nil
    authtoken = ""
  end
  uri = URI.parse(url)
  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
                              })
  request.body = body

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

#modify_data_template_if_its_mario_template(data_template) ⇒ Object



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 182

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
  return data_template
end

#modify_file_line(line_replacement_details) ⇒ Object



413
414
415
416
417
418
419
420
421
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 413

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

#perform_domain_event_operationObject



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/apollo_commons_ruby/DomainEvent.rb', line 67

def perform_domain_event_operation
    baseMarioUrl = $environmentProperties["apolloMarioBaseUrl"]
    authToken = $secretConfig.authToken
    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
        make_PUT_request(marioUrl,
        replace_environment_based_config_in_string(JSON.generate($domain_event.requestBody), $environmentProperties),
        authToken)
        return
    end
    if $operation == Operation::DELETE
        make_DELETE_request(marioUrl, authToken)
    end
end

#perform_git_checksObject



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

def perform_git_checks
  current_branch = `git rev-parse --abbrev-ref HEAD`
  if current_branch.eql?("master")
    raise "Rake update in Prod can be performed only from master branch."
  end

  system("git fetch origin master > /dev/null 2>&1") or raise "Unable to fetch origin/master from git remote"
  master = `git rev-parse master`
  origin_master = `git rev-parse origin/master`

  if !master.eql?(origin_master)
    raise "Master is not in sync with Origin. Pull changes from remote and retry."
  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



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

def perform_view_group_component_operation
    raise_exception_if_string_empty($viewGroupComponent.requestBody["templateGroup"], "templateGroup")
    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
        make_PUT_request(marioUrl,
            replace_environment_based_config_in_string(JSON.generate($viewGroupComponent.requestBody), $environmentProperties),
            authToken)
        return
    end
    if $operation == Operation::DELETE
        make_DELETE_request(marioUrl, authToken)
    end
end

#perform_view_group_definition_operationObject



48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/apollo_commons_ruby/ViewGroupDefinition.rb', line 48

def perform_view_group_definition_operation
    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
        make_PUT_request(marioUrl, replace_environment_based_config_in_string(JSON.generate($viewGroupDefinition.requestBody), $environmentProperties), authToken)
        return
    end
    if $operation == Operation::DELETE
        make_DELETE_request(marioUrl, authToken)
    end
end

#perform_view_group_operationObject



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

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 + "/tenant-users/" + $viewGroup.tenantUserId + "/view-group-definitions/" + $viewGroup.viewGroupDefinition + "/view-groups/" + $viewGroup.viewGroupName
    replace_environment_based_config_in_string(marioUrl, $environmentProperties)
    if $operation == Operation::DELETE
        make_DELETE_request(marioUrl, authToken)
    end
end

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



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

def prepare_domain_event(view_group_definition, component, topic, event_name)
    puts "view_group_definition: #{view_group_definition}"
    puts "component: #{component}"
    puts "topic: #{topic}"
    puts "event_name: #{event_name}"
    $domain_event = DomainEvent.new($environmentProperties, view_group_definition, component, topic, event_name)
    associate_user_details_transformer_in_request_body
    associate_view_group_context_transformer_in_request_body
    form_subscribtion_info
    associate_hars_with_in_request_body
end

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



50
51
52
# File 'lib/apollo_commons_ruby/ViewGroup.rb', line 50

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

#prepare_view_group_component(view_group_definition, component) ⇒ Object



47
48
49
# File 'lib/apollo_commons_ruby/ViewGroupComponent.rb', line 47

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



44
45
46
# File 'lib/apollo_commons_ruby/ViewGroupDefinition.rb', line 44

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


651
652
653
654
655
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 651

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


647
648
649
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 647

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


718
719
720
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 718

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

#raise_exception_if_string_empty(string, identifier) ⇒ Object



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

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



577
578
579
580
581
582
583
584
585
586
587
588
589
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 577

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



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

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



699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 699

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



665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 665

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



608
609
610
611
612
613
614
615
616
617
618
619
620
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 608

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



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

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



622
623
624
625
626
627
628
629
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 622

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_environment_based_config_in_string(body, environment) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/apollo_commons_ruby/FileUtils.rb', line 22

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

#setup_appID_uiview_template_group_directory(template_group, appID) ⇒ Object



631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 631

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



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

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_existing_translations(source_path, language_resource_path) ⇒ Object



302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
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
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 302

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(environment, configuration, template_group, scope_id, tenant_id, project_id) ⇒ Object



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

def update_template_group_inbox(environment, configuration, template_group, scope_id, tenant_id, project_id)
  query_params = {
    :templateGroup => template_group
  }
  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(environment, configuration, scope_id, template_group, view, version, tenant_id, project_id) ⇒ Object



794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 794

def upsert_template_group_apollo_config(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)

  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
  }

  url = configuration.apollo_config_base_url + "/scopes/#{scope_id}/templateGroups/#{template_group}"

  puts "\n*[Apollo-config]: Upsert template group API call*\n"
  invoke_API(environment, url, HTTP::POST, nil, request_payload.to_json)
end

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



818
819
820
821
822
823
824
825
826
827
828
829
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 818

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

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

  url = configuration.apollo_config_base_url + "/scopes/#{scope_id}/templateGroups/#{template_group}/languages/#{language}/views/#{view}/mappings/"

  puts "\n*[Apollo-config]: Upsert template mappings API call*\n"
  invoke_API(environment, url, HTTP::POST, nil, request_payload.to_json)
end

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



831
832
833
834
835
836
837
838
839
840
841
842
# File 'lib/apollo_commons_ruby/TemplatesRakefile.rb', line 831

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

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

  url = configuration.apollo_config_base_url + "/scopes/#{scope_id}/templateGroups/#{template_group}/languages/#{language}/views/#{view}/templates/"

  puts "\n*[Apollo-config]: Upsert templates API call*\n"
  invoke_API(environment, url, HTTP::POST, nil, request_payload.to_json)
end

#verify_and_get_template_version(version) ⇒ Object



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

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

#write_collection_data_to_file(collection_data, file_path) ⇒ Object



504
505
506
507
508
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 504

def write_collection_data_to_file(collection_data, file_path)
  out_file = File.new(file_path, "w")
  out_file.puts JSON.pretty_generate collection_data
  out_file.close
end

#write_common_data_to_file(configuration, collection_data) ⇒ Object



498
499
500
501
502
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 498

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

#write_data_to_file(file_path, data) ⇒ Object



486
487
488
489
490
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 486

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

#write_plain_text_to_file(file_path, data) ⇒ Object



492
493
494
495
496
# File 'lib/apollo_commons_ruby/TemplatesHelper.rb', line 492

def write_plain_text_to_file(file_path, data)
  out_file = File.new(file_path, "w")
  out_file.puts data
  out_file.close
end

#write_templated_data_to_file(configuration, collection_data) ⇒ Object



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

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_templated_data_to_file_for_zebugger(configuration, collection_data) ⇒ Object



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

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