Thursday, 26 February 2015

Healper classes in Ruby using singletons

class Generics  include Singleton
  # creates Singleton Object for Product Update  def self.obj    Generics.instance
  end
  def text_comparison(str1, str2, ignore_case)
    if ignore_case or ignore_case == 'yes'      str1 = str1.strip.downcase
      str2 = str2.strip.downcase
    end    begin      flag = (str1 == str2)
      raise Exception, "String #{str1.inspect} not matching with #{str2.inspect}" if not flag    end  end
end

class UserHelper
  def self.generics
    Generics.obj
  end
end

UserHelper.generics

Read/Write XML in Ruby using Nokogiri

require 'nokogiri'

$imgNode= "<METADATA order=\"22\" key=\"Key22\"><![CDATA[2 cm]]></METADATA>"class ReadXMLNodes  def initialize()
    @file = File.open('../Orders/ShoeTemplate.xml')
    @xmlObj= Nokogiri::XML(@file)
    puts @xmlObj.to_s
    puts 'Node Count: '+ @xmlObj.xpath('//PRODUCT/P_NR').count.to_s
  end
  def getNode(strNodeXPath)
    @xmlObj.xpath(strNodeXPath)
  end
  def saveXML()
    @timeStamp= Time.new
    timestmp= @timeStamp.strftime("%Y-%m-%d-%H-%M-%S-%s")
    File.delete('../Results/FileOutput'+ timestmp+ ".xml") if File.exist? ('../Results/FileOutput'+ timestmp+ ".xml")
    @fileWr=File.new('../Results/FileOutput'+ timestmp+ ".xml", "w")
    @fileWr.write(@xmlObj.to_xml)
    @fileWr.close
  end
  def getFirstNode(strNodeXPath)
    @xmlObj.xpath(strNodeXPath).first()  #Or    # @xmlObj.xpath(strNodeXPath)[0]  end
  def getLasttNode(strNodeXPath)
    @xmlObj.xpath(strNodeXPath).last()  #Or    # @xmlObj.xpath(strNodeXPath)[0]  end
  def readFirstNodeContent(strXpath, strAttrVal)
    # @xmlObj.xpath("//P_ACTIVE[@channel='"+ strAttrVal + "']")[0].content    @xmlObj.xpath(strXpath + "'"+ strAttrVal + "']")[0].content  #If we dont keep content here, it reads the whole node value  end
  def readLastNodeContent(strXpath, strAttrVal)
    # @xmlObj.xpath("//P_ACTIVE[@channel='"+ strAttrVal + "']")[0].content    @xmlObj.xpath(strXpath + "'"+ strAttrVal + "']").last().content  #If we dont keep content here, it reads the whole node value  end
  def readNodeContent(strXpath, index)
    # @xmlObj.xpath(strXpath).last().content    @xmlObj.xpath(strXpath)[index.to_i].content
  end
  def removeNode(strNodeXPath)
    @xmlObj.xpath(strNodeXPath).remove
  end  def removeFirstNode(strNodeXPath)
    @xmlObj.xpath(strNodeXPath)[0].remove
  end  def removeLastNode(strNodeXPath)
    @xmlObj.xpath(strNodeXPath).last().remove
  end
  def countNodes(strXpath)
    @xmlObj.xpath(strXpath).count
  end
  def modify_node_content(strXpath, strValue)
    @xmlObj.xpath(strXpath)[0].content=strValue  end
  def AddNode(strXpath, strNode, index)
    if @xmlObj.xpath(strXpath).count >= 0      @xmlObj.xpath(strXpath)[index].add_next_sibling(strNode)
    end  end
  def getAttributeValue(strXpath, strAttribute)
    node= @xmlObj.xpath(strXpath)[0]
    node.attributes[strAttribute].value
  end  def modify_attribute_val(strXpath, strAttribute, val_to_assign)
    node= @xmlObj.xpath(strXpath)[0]
    node.attributes[strAttribute].value=val_to_assign  endend

readNodes= ReadXMLNodes.new
puts 'First Node is: '+ readNodes.getFirstNode('//A_MEDIADATA/A_MEDIA')
puts 'Last Node is: '+ readNodes.getLasttNode('//A_MEDIADATA/A_MEDIA')
puts 'Convert to xml: '+ readNodes.getLasttNode('//A_MEDIADATA/A_MEDIA').to_xml

# puts 'Read Node: '+ readNodes.getNode('//P_METADATA/METADATA')# puts 'Remove Node: '+ readNodes.removeNode('//P_METADATA/METADATA')# puts 'Read Node: '+ readNodes.getNode('//P_METADATA/METADATA')
puts '++++++++++++++++++ First Read+++++++++++++++++++++++++++'puts readNodes.getNode('//P_METADATA/METADATA')
puts '++++++++++++++++++ Remove Node +++++++++++++++++++++++++++'puts readNodes.removeLastNode('//P_METADATA/METADATA')
puts readNodes.removeNode('//P_METADATA/METADATA')
puts '++++++++++++++++++ Read After +++++++++++++++++++++++++++'puts readNodes.getNode('//P_METADATA/METADATA')
puts readNodes.readFirstNodeContent('//P_ACTIVE[@channel=', 'tiau')
puts readNodes.readLastNodeContent('//A_PRICEDATA/A_PRICE[@channel=', 'test')
puts readNodes.readLastNodeContent('//A_MEDIADATA/A_MEDIA[@type=', 'image')
puts 'Print Node content'puts readNodes.readNodeContent("//A_MEDIADATA/A_MEDIA[@type='image']", 4)

print "Counting Nodes: "puts readNodes.countNodes("//A_MEDIADATA/A_MEDIA")
puts readNodes.modify_node_content("//P_ACTIVE[@channel='test']", "Venu")
puts readNodes.modify_node_content("//ARTICLEDATA/ARTICLE/NR", "999999")
puts "testing"puts readNodes.AddNode('//A_MEDIADATA/A_MEDIA', $imgNode, 4)
puts 'reading attribute value'puts readNodes.getAttributeValue('//P_ACTIVE', 'channel')
puts 'modify attribute value: 'readNodes.modify_attribute_val('//P_ACTIVE', 'channel', 'AttributeValChanged')
print 'Changed attribute value is: 'puts readNodes.getAttributeValue('//P_ACTIVE', 'channel')
puts readNodes.saveXML

=begin1. Add Nodes2. Add Attribute3. Modify Attribute4. Remove Attribute5. Read Attribute value6.=end

Wednesday, 25 February 2015

class UserHelper 

 
def self.sd_sftp_user  SftpHelper.obj.connect_sftp FigNewton.sftp.mass.sftp_host,
                              FigNewton.sftp.mass.sftp_uname,
                              FigNewton.sftp.mass.sftp_key
  SftpHelper.obj
end
 
 
def self.dynamo_user  @dynamo_db = AWS::DynamoDB.new(access_key_id: FigNewton.dynamodb.access_key_id,
                                 secret_access_key: FigNewton.dynamodb.secret_access_key,
                                 region: FigNewton.dynamodb.region)
  @dynamo_dbend 

end


class Dynamo  include Singleton  def initialize 
 # @dynamo_db = AWS::DynamoDB.new(access_key_id: FigNewton.dynamodb.access_key_id,    #                                secret_access_key: FigNewton.dynamodb.secret_access_key,    #                                region: FigNewton.dynamodb.region)
    @dynamo_db = AWS::DynamoDB.new(access_key_id: 'enter access key id ',
                                   secret_access_key: 'enter secret key here,
                                   region: 'enter region id')
  end  

  
  # {'email' => 'mai@email.com', 'rollno' => 3},'name')   
def get_col_values(table_name, ref_column_hash, col_name)
    items = []
    table = @dynamo_db.tables[table_name]
    table.load_schema
    rows = table.items
    ref_column_hash.each do |key, value|
      rows = rows.where(key.to_sym=>value)
    end    rows.each do |row|
      items.push row.attributes[col_name]
    end    items 
 end
  def get_rows(table_name, ref_column_name, ref_col_value, col_name)
    items = []
    table = @dynamo_db.tables[table_name]
    table.load_schema
    table.items.select(ref_column_name.to_sym,col_name.to_sym ) do |row|
      if row.attributes[ref_column_name].to_i.equal? ref_col_value.to_i
        items.push row      end    end    items  end
  # returns the table object  def get_table(table_name)
    table = @dynamo_db.tables[table_name]
    table.load_schema
    table  end
  
end
 
# A helper class to access information stored in S3.
 class S3Helper   
include Singleton 
 # creates the singleton object   
def self.obj 
 S3Helper.instance
end
  
 # Initialize the helper and get the AWS S3 object. 
 def initialize     
# @s3_object = AWS::S3.new access_key_id: FigNewton.s3.access_key_id,    #                          secret_access_key: FigNewton.s3.secret_access_key    
 end 
 
 # Read a file from an S3 bucket.  #  # ==== Attributes  #  #   +fname+ - The name of the file to read from S3.  #  # ==== Examples  #  #   # To read a file from an S3 bucket, call the .read_file method from  #   # your code in the following way:  #   @s3_user.read_file 'test.xml'  def read_file(fname)
    @s3_object.buckets[@bucket].objects[fname].read
  end
 
end   


UserHelper.sd_sftp_user.read_file('folder/test.csv')
 

How to fail a test in selenium with Ruby and Cucumber

fail 'message to display in console'

This will fail the test when executed.

Saturday, 14 February 2015

Filesystem in Ruby - accessing parent files based on current folder/file path


puts File.expand_path(File.dirname(__FILE__) + "/../src/google_finance.rb")
puts File.dirname(__FILE__)

puts File.expand_path(File.dirname(__FILE__) + "/../../data")

#Webser            -- Root folder
#  +--data          --folder
#  +--sample         --folder
#    +--lib
#    +--src
#         +--google.rb
#         +--testing.rb
#    +--config.rb 
 

#to access data folder:
puts File.expand_path(File.dirname(__FILE__) + "/../../data")
#Output: C:/Users/user/workspace/WebservicesTest/data

#to access current folder:
puts File.dirname(__FILE__)
#C:/Users/user/workspace/WebservicesTest/sample/src

#to access google.rb file from testing.rb file:
puts File.expand_path(File.dirname(__FILE__) + "/../src/google_finance.rb")
#C:/Users/user/workspace/WebservicesTest/sample/src/google_finance.rb

#WE CAN REQUIRE LIKE THIS AS WELL
#require File.expand_path(File.dirname(__FILE__) + "/../lib/wrest")

Thursday, 12 February 2015

get parent or sibling folder/file based on current file location

def create_temp_file()
  @temp_fpath= ''  begin    @temp_fpath = File.absolute_path('..\src\features\data\tempfile.txt')
    create_file(@temp_fpath, 'Sample text')
  rescue Exception => e    puts e.message
  end  @temp_fpathend

rest client chrome/firefox plugins

Advance Rest Client
DHC Rest client
RestClient

Ruby Rest Service: get all the tags - api.del.icio.us api

require 'net/https'
http= Net::HTTP.new('api.del.icio.us', 443)
http.use_ssl = true
http.start do |http|
  req=Net::HTTP::Get.new('/v1/tags/get') 
  req.basic_auth 'myusername', 'password'
    @resp= http.request(req)
end

puts @resp.body

Output:
<?xml version="1.0" encoding="UTF-8"?>
<tags>
  <tag count="1" tag="!fromtwitter"/>
  <tag count="1" tag="social"/>
  <tag count="1" tag="ecommerce"/>
   <tag count="1" tag="flipkart"/>
</tags>


links:
http://www.rubyinside.com/nethttp-cheat-sheet-2940.html
https://github.com/augustl/net-http-cheat-sheet