<?xml version="1.0" encoding="utf-8" ?><feed xmlns="http://www.w3.org/2005/Atom" xmlns:tt="http://teletype.in/" xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/"><title>Sravan Cynixit</title><author><name>Sravan Cynixit</name></author><id>https://teletype.in/atom/sravancynixit</id><link rel="self" type="application/atom+xml" href="https://teletype.in/atom/sravancynixit?offset=0"></link><link rel="alternate" type="text/html" href="https://teletype.in/@sravancynixit?utm_source=teletype&amp;utm_medium=feed_atom&amp;utm_campaign=sravancynixit"></link><link rel="next" type="application/rss+xml" href="https://teletype.in/atom/sravancynixit?offset=10"></link><link rel="search" type="application/opensearchdescription+xml" title="Teletype" href="https://teletype.in/opensearch.xml"></link><updated>2026-04-09T08:09:07.513Z</updated><entry><id>sravancynixit:E_pE4_gw7</id><link rel="alternate" type="text/html" href="https://teletype.in/@sravancynixit/E_pE4_gw7?utm_source=teletype&amp;utm_medium=feed_atom&amp;utm_campaign=sravancynixit"></link><title>How To Work with Arrays in Ruby</title><published>2020-05-06T10:09:53.556Z</published><updated>2020-05-06T10:09:53.556Z</updated><summary type="html">&lt;img src=&quot;https://teletype.in/files/3e/9c/3e9cad46-3840-4437-861d-01606e7c2a79.png&quot;&gt;An array is a data structure that represents a list of values, called elements. Arrays let you store multiple values in a single variable. This can condense and organize your code, making it more readable and maintainable. And because arrays are objects with their own methods, they can make working with lists of data much easier.</summary><content type="html">
  &lt;h3&gt;Introduction&lt;/h3&gt;
  &lt;p&gt;An &lt;em&gt;array&lt;/em&gt; is a data structure that represents a list of values, called &lt;em&gt;elements&lt;/em&gt;. Arrays let you store multiple values in a single variable. This can condense and organize your code, making it more readable and maintainable. And because arrays are objects with their own methods, they can make working with lists of data much easier.&lt;/p&gt;
  &lt;p&gt;If you want to Gain In-depth Knowledge on &lt;strong&gt;Ruby On Rails&lt;/strong&gt;, please go through this link &lt;strong&gt;&lt;a href=&quot;https://onlineitguru.com/ruby-on-rails-online-training-placement.html&quot; target=&quot;_blank&quot;&gt;Ruby On Rails Online Training&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;
  &lt;p&gt;In Ruby. arrays can contain any datatype, including numbers, strings, and other Ruby objects.&lt;/p&gt;
  &lt;figure class=&quot;m_original&quot;&gt;
    &lt;img src=&quot;https://teletype.in/files/3e/9c/3e9cad46-3840-4437-861d-01606e7c2a79.png&quot; width=&quot;597&quot; /&gt;
  &lt;/figure&gt;
  &lt;p&gt;Let’s look at a simple example of how powerful arrays can be. Imagine you had to maintain a list of email addresses. Without an array, you might store email addresses in variables, like this:&lt;/p&gt;
  &lt;p&gt;emails.rb&lt;/p&gt;
  &lt;pre&gt;email1 = &amp;quot;ceo@example.com&amp;quot;
email2 = &amp;quot;admin@example.com&amp;quot;
email3 = &amp;quot;support@example.com&amp;quot;
email4 = &amp;quot;sales@example.com&amp;quot;&lt;/pre&gt;
  &lt;p&gt;This approach is verbose and can quickly become difficult to maintain, as it’s not very flexible. Adding another email address means you’d have to add, and track, an additional variable.&lt;/p&gt;
  &lt;p&gt;If you use an array, you can simplify this data:&lt;/p&gt;
  &lt;p&gt;emails.js&lt;/p&gt;
  &lt;pre&gt;emails = [
  &amp;quot;ceo@example.com&amp;quot;,
  &amp;quot;admin@example.com&amp;quot;,
  &amp;quot;support@example.com&amp;quot;,
  &amp;quot;sales@example.com&amp;quot;
]&lt;/pre&gt;
  &lt;p&gt;Instead of creating five separate variables, you now have one variable that contains all four email addresses. In this example, we used square brackets — &lt;code&gt;[]&lt;/code&gt; — to create an array, and separated each entry with a comma. If you had to add an additional email address, you would add another email address to the array rather than creating and managing a new variable.&lt;/p&gt;
  &lt;p&gt;To access a specific item, or &lt;em&gt;element&lt;/em&gt; of an array, you reference its &lt;em&gt;index&lt;/em&gt;, or its position in the array. In Ruby, indexes start at zero. so to retrieve the first element from our &lt;code&gt;emails&lt;/code&gt; array, we append the element’s index to the variable using square brackets, like this:&lt;/p&gt;
  &lt;pre&gt;print emails[0];&lt;/pre&gt;
  &lt;pre&gt;Outputceo@example.com
&lt;/pre&gt;
  &lt;p&gt;In this tutorial, you’ll create arrays, access the values they contain, add, modify, and remove elements in an array, and iterate through the elements in an array to solve more complex problems. Let’s start by looking at how to create arrays in more detail.&lt;/p&gt;
  &lt;h2&gt;Creating an Array&lt;/h2&gt;
  &lt;p&gt;To create an array in a Ruby program, use square brackets: (&lt;code&gt;[]&lt;/code&gt;), and separate the values you want to store with commas.&lt;/p&gt;
  &lt;p&gt;For example, create an array of sharks and assign it to a variable, like this:&lt;/p&gt;
  &lt;p&gt;sharks.rb&lt;/p&gt;
  &lt;pre&gt;sharks = [&amp;quot;Hammerhead&amp;quot;, &amp;quot;Great White&amp;quot;, &amp;quot;Tiger&amp;quot;]&lt;/pre&gt;
  &lt;p&gt;You can print out an entire array with the &lt;code&gt;print&lt;/code&gt; statement, which will display the array’s contents:&lt;/p&gt;
  &lt;pre&gt;print sharks&lt;/pre&gt;
  &lt;pre&gt;Output[&amp;quot;Hammerhead&amp;quot;, &amp;quot;Great White&amp;quot;, &amp;quot;Tiger&amp;quot;] 
&lt;/pre&gt;
  &lt;p&gt;If you want to create an array where each entry is a single word, you can use the &lt;code&gt;%w{}&lt;/code&gt; syntax, which creates a &lt;em&gt;word array&lt;/em&gt;:&lt;/p&gt;
  &lt;pre&gt;days = %w{Monday Tuesday Wednesday Thursday Friday Saturday Sunday}&lt;/pre&gt;
  &lt;p&gt;This is equivalent to creating the array with square braces:&lt;/p&gt;
  &lt;pre&gt;days =  [&amp;quot;Monday&amp;quot;, &amp;quot;Tuesday&amp;quot;, &amp;quot;Wednesday&amp;quot;, &amp;quot;Thursday&amp;quot;, &amp;quot;Friday&amp;quot;, &amp;quot;Saturday&amp;quot;, &amp;quot;Sunday&amp;quot;]&lt;/pre&gt;
  &lt;p&gt;However, notice that the &lt;code&gt;%w{}&lt;/code&gt; method lets you skip the quotes and the commas.&lt;/p&gt;
  &lt;p&gt;Arrays are often used to group together lists of similar data types, but in Ruby, arrays can contain any value or a mix of values, including other arrays. Here’s an example of an array that contains a string, a &lt;code&gt;nil&lt;/code&gt; value, an integer, and an array of strings:&lt;/p&gt;
  &lt;p&gt;mixed_data.rb&lt;/p&gt;
  &lt;pre&gt;record = [
    &amp;quot;Sammy&amp;quot;,
    null,
    7,
    [
        &amp;quot;another&amp;quot;,
        &amp;quot;array&amp;quot;,
    ]
]&lt;/pre&gt;
  &lt;p&gt;Now let’s look at how we access data stored in arrays.&lt;/p&gt;
  &lt;h2&gt;Accessing Items in Arrays&lt;/h2&gt;
  &lt;p&gt;You access an item in a Ruby array by referring to the &lt;em&gt;index&lt;/em&gt; of the item in square brackets.&lt;/p&gt;
  &lt;p&gt;Let’s explore this concept with our array of sharks, assigned to the variable &lt;code&gt;sharks&lt;/code&gt;:&lt;/p&gt;
  &lt;p&gt;sharks.rb&lt;/p&gt;
  &lt;pre&gt;sharks = [&amp;quot;Hammerhead&amp;quot;, &amp;quot;Great White&amp;quot;, &amp;quot;Tiger&amp;quot;]&lt;/pre&gt;
  &lt;p&gt;The &lt;code&gt;sharks&lt;/code&gt; array has three elements. Here is a breakdown of how each element in the &lt;code&gt;sharks&lt;/code&gt; array is indexed.&lt;/p&gt;
  &lt;p&gt;Hammerhead&lt;/p&gt;
  &lt;p&gt;Greate White&lt;/p&gt;
  &lt;p&gt;Tiger&lt;/p&gt;
  &lt;p&gt;The first element in the array is &lt;code&gt;Hammerhead&lt;/code&gt;, which is indexed at &lt;code&gt;0&lt;/code&gt;. The last element is &lt;code&gt;Tiger&lt;/code&gt;, which is indexed at &lt;code&gt;2&lt;/code&gt;. Counting starts with &lt;code&gt;0&lt;/code&gt; in indices, which goes against our natural intuition to start counting at 1, so you’ll want to keep this in mind until it becomes natural.&lt;/p&gt;
  &lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: It might help you to think of the index as an offset; it’s the number of places from the start of the array. The first element is at the beginning, so its offset, or index, is &lt;code&gt;0&lt;/code&gt;. The second element is one spot away from the first entry in the array, so its offset, or index, is &lt;code&gt;1&lt;/code&gt;.&lt;br /&gt;&lt;/p&gt;
  &lt;p&gt;You can find out how many elements are in an array with the &lt;code&gt;length&lt;/code&gt; method.&lt;/p&gt;
  &lt;pre&gt;sharks.length&lt;/pre&gt;
  &lt;pre&gt;Output3
&lt;/pre&gt;
  &lt;p&gt;Although the indices of &lt;code&gt;sharks&lt;/code&gt; start at &lt;code&gt;0&lt;/code&gt; and go to &lt;code&gt;2&lt;/code&gt;, the &lt;code&gt;length&lt;/code&gt; property returns the number of elements in the array, which is &lt;code&gt;3&lt;/code&gt;. It’s not concerned with the indices at all.&lt;/p&gt;
  &lt;p&gt;If you wanted to find out the index number of a specific element in an array, such as &lt;code&gt;seahorse&lt;/code&gt;, use the &lt;code&gt;index()&lt;/code&gt; method:&lt;/p&gt;
  &lt;pre&gt;print sharks.index(&amp;quot;Tiger&amp;quot;)&lt;/pre&gt;
  &lt;pre&gt;Output2
&lt;/pre&gt;
  &lt;p&gt;This returns the index of the first element containing that text. If an index number is not found, such as for a value that does not exist, the console will return &lt;code&gt;nil&lt;/code&gt;.&lt;/p&gt;
  &lt;pre&gt;print sharks.index(&amp;quot;Whale&amp;quot;)&lt;/pre&gt;
  &lt;pre&gt;Outputnil
&lt;/pre&gt;
  &lt;p&gt;To get the last element of an array in Ruby, use the index &lt;code&gt;-1&lt;/code&gt;:&lt;/p&gt;
  &lt;pre&gt;print sharks[-1]&lt;/pre&gt;
  &lt;pre&gt;Output&amp;quot;Tiger&amp;quot;
&lt;/pre&gt;
  &lt;p&gt;Ruby also provides the &lt;code&gt;first&lt;/code&gt; and &lt;code&gt;last&lt;/code&gt; methods to get the first and last elements without using indices:&lt;/p&gt;
  &lt;pre&gt;puts sharks.first
puts sharks.last&lt;/pre&gt;
  &lt;pre&gt;Output&amp;quot;Hammerhead&amp;quot;
&amp;quot;Tiger&amp;quot;
&lt;/pre&gt;
  &lt;p&gt;Attempting to access an index that doesn’t exist will return &lt;code&gt;nil&lt;/code&gt;.&lt;/p&gt;
  &lt;pre&gt;sharks[10]&lt;/pre&gt;
  &lt;pre&gt;Outputnil
&lt;/pre&gt;
  &lt;p&gt;Arrays can contain other arrays, which we call &lt;em&gt;nested arrays&lt;/em&gt;. This is one way to model two-dimentional data sets in a program. Here’s an example of a nested array:&lt;/p&gt;
  &lt;pre&gt;nested_array = [
    [
        &amp;quot;salmon&amp;quot;,
        &amp;quot;halibut&amp;quot;,
    ],
    [
        &amp;quot;coral&amp;quot;,
        &amp;quot;reef&amp;quot;,
    ]
]&lt;/pre&gt;
  &lt;p&gt;In order to access elements in a nested array, you would add another index number to correspond to the inner array. For example, to retrive the value &lt;code&gt;coral&lt;/code&gt; from this nested array, you’d use the following statement:&lt;/p&gt;
  &lt;pre&gt;print nested_array[1][0];&lt;/pre&gt;
  &lt;pre&gt;Outputcoral
&lt;/pre&gt;
  &lt;p&gt;In this example, we accessed the array at position &lt;code&gt;1&lt;/code&gt; of the &lt;code&gt;nested_array&lt;/code&gt; variable, which returned the array &lt;code&gt;[&amp;quot;coral&amp;quot;, &amp;quot;reef&amp;quot;]&lt;/code&gt;. We then accessed the elements at position &lt;code&gt;0&lt;/code&gt; of that array, which was &lt;code&gt;&amp;quot;coral&amp;quot;&lt;/code&gt;.&lt;/p&gt;
  &lt;blockquote&gt;Take your career to new heights of success with an &lt;strong&gt;&lt;a href=&quot;https://onlineitguru.com/ruby-on-rails-online-training-placement.html&quot; target=&quot;_blank&quot;&gt;Ruby On Rails Online Course&lt;/a&gt;&lt;/strong&gt;&lt;/blockquote&gt;
  &lt;p&gt;Now let’s look at how to add elements to an array.&lt;/p&gt;
  &lt;h2&gt;Adding Elements&lt;/h2&gt;
  &lt;p&gt;We have three elements in our &lt;code&gt;sharks&lt;/code&gt; array, which are indexed from &lt;code&gt;0&lt;/code&gt; to &lt;code&gt;2&lt;/code&gt;:&lt;/p&gt;
  &lt;p&gt;sharks.rb&lt;/p&gt;
  &lt;pre&gt;sharks = [&amp;quot;Hammerhead&amp;quot;, &amp;quot;Great White&amp;quot;, &amp;quot;Tiger&amp;quot;]&lt;/pre&gt;
  &lt;p&gt;There are a few ways to add a new element. You could assign a value to the next index, which in this case would be &lt;code&gt;3&lt;/code&gt;:&lt;/p&gt;
  &lt;pre&gt;sharks[3] = &amp;quot;whale&amp;quot;;

print sharks&lt;/pre&gt;
  &lt;pre&gt;Output[&amp;quot;Hammerhead&amp;quot;, &amp;quot;Great White&amp;quot;, &amp;quot;Tiger&amp;quot;, &amp;quot;Whale&amp;quot;] 
&lt;/pre&gt;
  &lt;p&gt;This method is error-prone though. If you add an element and accidentally skip an index, it will create a &lt;code&gt;nil&lt;/code&gt; element in the array.&lt;/p&gt;
  &lt;pre&gt;sharks[5] = &amp;quot;Sand&amp;quot;;

print sharks;&lt;/pre&gt;
  &lt;pre&gt;Output[&amp;quot;Hammerhead&amp;quot;, &amp;quot;Great White&amp;quot;, &amp;quot;Tiger&amp;quot;, &amp;quot;Whale&amp;quot;, nil, &amp;quot;Sand&amp;quot;]
&lt;/pre&gt;
  &lt;p&gt;Attempting to access the extra array element will return its value, which will be &lt;code&gt;nil&lt;/code&gt;.&lt;/p&gt;
  &lt;pre&gt;sharks[4]&lt;/pre&gt;
  &lt;pre&gt;Outputnil
&lt;/pre&gt;
  &lt;p&gt;Finding the next available index in an array is error-prone and takes extra time. Avoid errors by using the &lt;code&gt;push&lt;/code&gt; method, which adds an element to the end of an array:&lt;/p&gt;
  &lt;pre&gt;sharks.push(&amp;quot;thresher&amp;quot;)
print sharks&lt;/pre&gt;
  &lt;pre&gt;Output[&amp;quot;Hammerhead&amp;quot;, &amp;quot;Great White&amp;quot;, &amp;quot;Tiger&amp;quot;, &amp;quot;Whale&amp;quot;, nil, &amp;quot;Whale&amp;quot;, &amp;quot;Thresher&amp;quot;]
&lt;/pre&gt;
  &lt;p&gt;You can also use the &lt;code&gt;&amp;lt;&amp;lt;&lt;/code&gt; syntax instead of the &lt;code&gt;push&lt;/code&gt; method to add an element to the end of an array:&lt;/p&gt;
  &lt;pre&gt;sharks &amp;lt;&amp;lt; &amp;quot;Bullhead&amp;quot;&lt;/pre&gt;
  &lt;pre&gt;Output[&amp;quot;Hammerhead&amp;quot;, &amp;quot;Great White&amp;quot;, &amp;quot;Tiger&amp;quot;, &amp;quot;Whale&amp;quot;, nil, &amp;quot;Whale&amp;quot;, &amp;quot;Thresher&amp;quot;, &amp;quot;Bullhead&amp;quot;]
&lt;/pre&gt;
  &lt;p&gt;To add an element to the beginning of an array, use the &lt;code&gt;unshift()&lt;/code&gt; method:&lt;/p&gt;
  &lt;pre&gt;sharks.unshift(&amp;quot;Angel&amp;quot;)
print sharks&lt;/pre&gt;
  &lt;pre&gt;Output[&amp;quot;Angel&amp;quot;, &amp;quot;Hammerhead&amp;quot;, &amp;quot;Great White&amp;quot;, &amp;quot;Tiger&amp;quot;, &amp;quot;Whale&amp;quot;, nil, &amp;quot;Whale&amp;quot;, &amp;quot;Thresher&amp;quot;, &amp;quot;Bullhead&amp;quot;]
&lt;/pre&gt;
  &lt;p&gt;Now that you know how to add elements, let’s look at removing them.&lt;/p&gt;
  &lt;h2&gt;Removing Elements&lt;/h2&gt;
  &lt;p&gt;To remove a specific element from an array, use the &lt;code&gt;delete&lt;/code&gt; or &lt;code&gt;delete_at&lt;/code&gt; methods. In the &lt;code&gt;sharks&lt;/code&gt; array, we accidentally created a &lt;code&gt;nil&lt;/code&gt; array element earlier. Let’s get rid of it.&lt;/p&gt;
  &lt;p&gt;First, find its position in the array. You can use the &lt;code&gt;index&lt;/code&gt; method to do that:&lt;/p&gt;
  &lt;pre&gt;print sharks.index(nil)&lt;/pre&gt;
  &lt;pre&gt;Output4
&lt;/pre&gt;
  &lt;p&gt;Then use &lt;code&gt;delete_at&lt;/code&gt; to remove the element at index &lt;code&gt;4&lt;/code&gt; and print the array:&lt;/p&gt;
  &lt;pre&gt;sharks.delete_at(4)
print sharks&lt;/pre&gt;
  &lt;pre&gt;Output[&amp;quot;Angel&amp;quot;, &amp;quot;Hammerhead&amp;quot;, &amp;quot;Great White&amp;quot;, &amp;quot;Tiger&amp;quot;, &amp;quot;Whale&amp;quot;, &amp;quot;Thresher&amp;quot;, &amp;quot;Bullhead&amp;quot;]
&lt;/pre&gt;
  &lt;p&gt;The &lt;code&gt;delete&lt;/code&gt; method removes elements from an array that match the value you pass in. Use it to remove &lt;code&gt;Whale&lt;/code&gt; from the array:&lt;/p&gt;
  &lt;pre&gt;sharks.delete(&amp;quot;Whale&amp;quot;)
print sharks;&lt;/pre&gt;
  &lt;pre&gt;Output[&amp;quot;Angel&amp;quot;, &amp;quot;Hammerhead&amp;quot;, &amp;quot;Great White&amp;quot;, &amp;quot;Tiger&amp;quot;, &amp;quot;Thresher&amp;quot;, &amp;quot;Bullhead&amp;quot;]
&lt;/pre&gt;
  &lt;p&gt;The &lt;code&gt;delete&lt;/code&gt; method will remove &lt;em&gt;all&lt;/em&gt; occurances of the value you pass, so if your array has duplicate elements, they’ll all be removed.&lt;/p&gt;
  &lt;p&gt;The &lt;code&gt;pop&lt;/code&gt; method will remove the last element in an array.&lt;/p&gt;
  &lt;pre&gt;sharks.pop
print sharks;&lt;/pre&gt;
  &lt;pre&gt;Output[&amp;quot;Angel&amp;quot;, &amp;quot;Hammerhead&amp;quot;, &amp;quot;Great White&amp;quot;, &amp;quot;Tiger&amp;quot;, &amp;quot;Thresher&amp;quot;]
&lt;/pre&gt;
  &lt;p&gt;&lt;code&gt;Bullhead&lt;/code&gt; has been removed as the last element of the array. In order to remove the first element of the array, use the &lt;code&gt;shift&lt;/code&gt; method.&lt;/p&gt;
  &lt;pre&gt;sharks.shift
print sharks&lt;/pre&gt;
  &lt;pre&gt;Output[&amp;quot;Hammerhead&amp;quot;, &amp;quot;Great White&amp;quot;, &amp;quot;Tiger&amp;quot;, &amp;quot;Thresher&amp;quot;]
&lt;/pre&gt;
  &lt;p&gt;This time, &lt;code&gt;Angel&lt;/code&gt; was removed from the beginning of the array.&lt;/p&gt;
  &lt;p&gt;By using &lt;code&gt;pop&lt;/code&gt; and &lt;code&gt;shift&lt;/code&gt;, you can remove elements from the beginning and the end of arrays. Using &lt;code&gt;pop&lt;/code&gt; is preferred wherever possible, as the rest of the items in the array retain their original index numbers.&lt;/p&gt;
  &lt;p&gt;The &lt;code&gt;delete_at&lt;/code&gt;, &lt;code&gt;pop&lt;/code&gt;, and &lt;code&gt;shift&lt;/code&gt; methods all change the original array and return the element you deleted. Try this example:&lt;/p&gt;
  &lt;p&gt;sharks.rb&lt;/p&gt;
  &lt;pre&gt;sharks = [&amp;quot;Hammerhead&amp;quot;, &amp;quot;Great White&amp;quot;, &amp;quot;Tiger&amp;quot;, &amp;quot;Whale&amp;quot;]
deleted_at_element = sharks.delete_at(1)
popped_element = sharks.pop

puts &amp;quot;Deleted_at element: #{deleted_at_element}&amp;quot;
puts &amp;quot;Popped element: #{popped_element}&amp;quot;

puts &amp;quot;Remaining array: #{sharks}&amp;quot;&lt;/pre&gt;
  &lt;pre&gt;OuptutDeleted_at element: Great White
Popped element: Whale
Remaining array: [&amp;quot;Hammerhead&amp;quot;, &amp;quot;Tiger&amp;quot;]
&lt;/pre&gt;
  &lt;p&gt;You now know several ways to remove elements from an array. Now let’s look at how to modify the element we already have.&lt;/p&gt;
  &lt;h2&gt;Modifying Existing Elements&lt;/h2&gt;
  &lt;p&gt;To update an element in the array, assign a new value to the element’s index by using the assignment operator, just like you would with a regular variable.&lt;/p&gt;
  &lt;p&gt;Given a new array of sharks, with &lt;code&gt;&amp;quot;Hammerhead&amp;quot;&lt;/code&gt; at index &lt;code&gt;0&lt;/code&gt;, let’s replace &lt;code&gt;&amp;quot;Hammerhead&amp;quot;&lt;/code&gt; with &lt;code&gt;&amp;quot;Angel&amp;quot;&lt;/code&gt;:&lt;/p&gt;
  &lt;pre&gt;sharks = [&amp;quot;Hammerhead&amp;quot;, &amp;quot;Great White&amp;quot;, &amp;quot;Tiger&amp;quot;, &amp;quot;Whale&amp;quot;]
sharks[0] = &amp;quot;Angel&amp;quot;
print sharks;&lt;/pre&gt;
  &lt;pre&gt;Output[&amp;quot;Angel&amp;quot;, &amp;quot;Great White&amp;quot;, &amp;quot;Tiger&amp;quot;, &amp;quot;Whale&amp;quot;]
&lt;/pre&gt;
  &lt;p&gt;To make sure you update the right element, you could use the &lt;code&gt;index&lt;/code&gt; method to locate the element first, just like you did to find the element you wanted to delete.&lt;/p&gt;
  &lt;p&gt;Now let’s look at how to work with all of the elements in the array.&lt;/p&gt;
  &lt;h2&gt;Iterating Over an Array&lt;/h2&gt;
  &lt;p&gt;Ruby provides many ways to iterate over an array, and each method you use depends on the kind of work you want to perform. In this article, we’ll explore how to iterate over an array and display each of its elements.&lt;/p&gt;
  &lt;p&gt;Ruby provides the &lt;code&gt;for..in&lt;/code&gt; syntax, which looks like this:&lt;/p&gt;
  &lt;pre&gt;sharks = [&amp;quot;Hammerhead&amp;quot;, &amp;quot;Great White&amp;quot;, &amp;quot;Tiger&amp;quot;, &amp;quot;Whale&amp;quot;]
for shark in sharks do
  puts shark
end&lt;/pre&gt;
  &lt;p&gt;Here’s how it works. For each element in the &lt;code&gt;sharks&lt;/code&gt; array, Ruby assigns that element to the local variable &lt;code&gt;shark&lt;/code&gt;. We can then print the element’s value using &lt;code&gt;puts&lt;/code&gt;.&lt;/p&gt;
  &lt;p&gt;You won’t see &lt;code&gt;for..in&lt;/code&gt; very often though. Ruby arrays are objects, and they provide the &lt;code&gt;each&lt;/code&gt; method for working with elements. The &lt;code&gt;each&lt;/code&gt; method works in a similar fashion to &lt;code&gt;for..in&lt;/code&gt;, but has a different syntax:&lt;/p&gt;
  &lt;p&gt;each.rb&lt;/p&gt;
  &lt;pre&gt;sharks = [&amp;quot;Hammerhead&amp;quot;, &amp;quot;Great White&amp;quot;, &amp;quot;Tiger&amp;quot;, &amp;quot;Whale&amp;quot;]
sharks.each do |shark|
  puts shark
end&lt;/pre&gt;
  &lt;p&gt;The &lt;code&gt;each&lt;/code&gt; method uses a syntax you’ll see often in Ruby programming. It takes a Ruby block as its argument. A &lt;em&gt;block&lt;/em&gt; is some code that will be executed later in the context of the method. In this case, the code is &lt;code&gt;puts shark&lt;/code&gt;. The &lt;code&gt;shark&lt;/code&gt; keyword, enclosed in the pipe characters (&lt;code&gt;|&lt;/code&gt;), is the local variable that represents the element in the array that the block will access. Ruby assigns the element to this variable and executes the code in the block. The &lt;code&gt;each&lt;/code&gt; method repeats this process for each element in the array. The result looks like this:&lt;/p&gt;
  &lt;pre&gt;OutputHammerhead
Great White
Tiger
Whale
&lt;/pre&gt;
  &lt;p&gt;When the block is only a single line, you often see Ruby developers replace the &lt;code&gt;do&lt;/code&gt; and &lt;code&gt;end&lt;/code&gt; keywords with curly braces and condense the whole statement into a single line, like this:&lt;/p&gt;
  &lt;p&gt;each.rb&lt;/p&gt;
  &lt;pre&gt;...
sharks.each {|shark| puts shark }&lt;/pre&gt;
  &lt;p&gt;This produces the same results but uses fewer lines of code.&lt;/p&gt;
  &lt;p&gt;The &lt;code&gt;each_with_index&lt;/code&gt; method works in a similar manner, but it also gives you access to the index of the array element. This program uses &lt;code&gt;each_with_index&lt;/code&gt; to print out the index and the value for each element:&lt;/p&gt;
  &lt;p&gt;each_with_index.rb&lt;/p&gt;
  &lt;pre&gt;sharks = [&amp;quot;Hammerhead&amp;quot;, &amp;quot;Great White&amp;quot;, &amp;quot;Tiger&amp;quot;, &amp;quot;Whale&amp;quot;]
sharks.each_with_index do |shark, index|
  puts &amp;quot;The index is #{index}&amp;quot;
  puts &amp;quot;The value is #{shark}&amp;quot;
end&lt;/pre&gt;
  &lt;p&gt;For each element in the array, Ruby assigns the element to the variable &lt;code&gt;shark&lt;/code&gt;, and assigns the current index to the &lt;code&gt;index&lt;/code&gt; variable. We can then reference both of those variables in the block.&lt;/p&gt;
  &lt;p&gt;The result of this program looks like this:&lt;/p&gt;
  &lt;pre&gt;OutputThe index is 0
The value is Hammerhead
The index is 1
The value is Great White
The index is 2
The value is Tiger
The index is 3
The value is Whale
&lt;/pre&gt;
  &lt;p&gt;You’ll interate over the elements in an array often in your own programs, such as when you need to display the items from a database on a website, or when you’re reading lines from a file and processing their contents.&lt;/p&gt;
  &lt;h2&gt;Conclusion&lt;/h2&gt;
  &lt;p&gt;Arrays are an extremely versatile and fundamental part of programming in Ruby. In this tutorial, you created arrays and accessed individual elements. You also added, removed, and modified elements in an array. Finally, you explored two ways to iterate over an array and display its contents, which is used as a common method to display data.&lt;/p&gt;

</content></entry><entry><id>sravancynixit:ovM09myPV</id><link rel="alternate" type="text/html" href="https://teletype.in/@sravancynixit/ovM09myPV?utm_source=teletype&amp;utm_medium=feed_atom&amp;utm_campaign=sravancynixit"></link><title>Spring Boot And Spring MVC Detailed Comparision As Of 2020 It Eliminates All Your Doubts</title><published>2020-05-02T09:32:13.158Z</published><updated>2020-05-02T09:32:13.158Z</updated><summary type="html">&lt;img src=&quot;https://teletype.in/files/19/2a/192a7151-f560-420c-a41f-f49f2ede7761.png&quot;&gt;Spring is an application framework highly popular for the development of enterprise applications. It is built for Java and allows software developers to implement the enterprise systems of various sizes including POS, e-commerce, ERP, banking, and so on. The Spring Framework offers a comprehensive configuration and programming model for the latest enterprise applications based on Java on any type of deployment platform.</summary><content type="html">
  &lt;h1&gt;Introduction&lt;/h1&gt;
  &lt;p&gt;Spring is an application framework highly popular for the development of enterprise applications. It is built for Java and allows software developers to implement the enterprise systems of various sizes including POS, e-commerce, ERP, banking, and so on. The Spring Framework offers a comprehensive configuration and programming model for the latest enterprise applications based on Java on any type of deployment platform.&lt;/p&gt;
  &lt;figure class=&quot;m_original&quot;&gt;
    &lt;img src=&quot;https://teletype.in/files/19/2a/192a7151-f560-420c-a41f-f49f2ede7761.png&quot; width=&quot;500&quot; /&gt;
  &lt;/figure&gt;
  &lt;p&gt;Spring 5 is the latest version of Spring framework and it has the support for reactive web applications. Being reactive implies that a system is elastic, message-driven, responsive, and resilient. Spring Framework’s two of the most important features are inversion of control (IOC) and dependency injection (DI). This is because, we can build loosely coupled applications when DI and IOC are used properly. More Latest Information At &lt;a href=&quot;https://onlineitguru.com/spring-boot-training.html&quot; target=&quot;_blank&quot;&gt;&lt;strong&gt;Spring Boot Online Training&lt;/strong&gt;&lt;/a&gt;&lt;/p&gt;
  &lt;h1&gt;What is Spring MVC?&lt;/h1&gt;
  &lt;p&gt;One of the modules of the Web layer of the Spring Framework is the Web-Servlet module. This module consists of Spring Framework’s MVC (model-view-controller) implementation for web applications. It provides a model-view-controller architecture and ready elements that can be utilized to build loosely coupled and flexible web applications.&lt;/p&gt;
  &lt;p&gt;The model-view-controller pattern results in dissociating the various aspects of application such as UI logic, business logic, input logic while offering a loose coupling between these components. Spring MVC is designed around a DispatcherServlet that deals with the HTTP requests and responses.&lt;/p&gt;
  &lt;h1&gt;What is Spring Boot?&lt;/h1&gt;
  &lt;p&gt;Spring Boot is a way to ease the creation of stand-alone application with zero or minimal configurations. It is basically an approach to build applications based on Spring framework with minimal configuration. Spring Boot makes it easy for the creation of production-grade, spring powered services and applications with minimum confusion.&lt;/p&gt;
  &lt;p&gt;It can be used for traditional WAR deployments or for the creation of stand-alone Java applications. Spring Boot provides a widely accessible and a radically faster ‘getting started’ experience for the entire Spring development.&lt;/p&gt;
  &lt;p&gt;Wish to Learn Spring Boot? Learn it from industry experts.! on &lt;strong&gt;Spring Boot Certification&lt;/strong&gt;&lt;/p&gt;
  &lt;h1&gt;Comparing Spring Boot and Spring MVC&lt;/h1&gt;
  &lt;p&gt;In the above paragraphs, we have learnt what is Spring Framework, Spring Boot, and Spring MVC. Now, let’s compare Spring MVC and Spring Boot. One of the most common dilemmas for the newbie developers who want to use Spring Framework is which one they should go for, either for Spring MVC or Spring Boot.&lt;/p&gt;
  &lt;p&gt;Well, if you are a new developer, you may think you should go for Spring Boot as it is the latest one. So, let’s dig deeper into the comparison part and understand which one is more recommended than the other.&lt;/p&gt;
  &lt;blockquote&gt;Wish to Learn Spring Boot? Learn it from industry experts.! on &lt;a href=&quot;https://onlineitguru.com/spring-boot-training.html&quot; target=&quot;_blank&quot;&gt;&lt;strong&gt;Spring Boot Certification&lt;/strong&gt;&lt;/a&gt;&lt;/blockquote&gt;
  &lt;h2&gt;Spring MVC&lt;/h2&gt;
  &lt;ol&gt;
    &lt;li&gt;Spring MVC is a HTTP oriented web application development framework and is a module of Spring framework.&lt;/li&gt;
    &lt;li&gt;It provides a decoupled way of building web applications. It will let you implement your web application in accordance with the model-view-controller design pattern.&lt;/li&gt;
    &lt;li&gt;Spring MVC is equivalent to JSF(Java Server Faces) in the JavaEE stack. Classes annotated with @Controller are the most popular elements in Spring MVC.&lt;/li&gt;
    &lt;li&gt;For the implementation of REST-based APIs, Spring MVC has an equivalent @RestController.&lt;/li&gt;
  &lt;/ol&gt;
  &lt;h2&gt;Spring Boot&lt;/h2&gt;
  &lt;ol&gt;
    &lt;li&gt;Spring Boot enables you to rapidly build and create Spring applications utilizing the Spring framework.&lt;/li&gt;
    &lt;li&gt;You need more configuration on your part if you choose to avoid Spring Boot.&lt;/li&gt;
    &lt;li&gt;The features that only Spring Boot can offer are the capability to create standalone web applications and auto-configuration.&lt;/li&gt;
    &lt;li&gt;You can do things such as incorporate H2 on the build path with the help of auto-configuration. For an in-memory database, Spring will auto-configure the connection details without any further configuration.&lt;/li&gt;
    &lt;li&gt;The starter projects provided by Spring Boot will increase productivity by providing defaults and configurations to minimize the effort of a developer avoiding writing a lot of XML configuration, annotations, and boilerplate code.&lt;/li&gt;
    &lt;li&gt;Spring Boot also offers embedded http servers such as Jetty, Tomcat, etc. which you can package together with your applications for creating executable war files.&lt;/li&gt;
    &lt;li&gt;With the help of Spring Boot, you can tell Spring how many of its modules(spring-web, spring-date, spring-core, and so on) to use and you will also get a quick setup for them.&lt;/li&gt;
  &lt;/ol&gt;
  &lt;p&gt;You can use Spring MVC if you want to develop a web application with Spring. However, for the development of general Spring applications or beginning to learn Spring, it is recommended that you use Spring Boot as it is production ready, mitigates the job, and is being quickly adopted. Also, Spring Boot can use Spring MVC and autoconfigure it. In this case, the choice won’t be between MVC and Boot but between Boot or Bootless. This depends on how open to associated risks and innovation your organization is.&lt;/p&gt;
  &lt;p&gt;Today, most of the Spring projects are integrated completely with Boot and even the Spring community began to develop various applications based on Spring Boot(monitoring and managing for example). You can benefit from very nice and useful features like remote shell and actuator for monitoring and managing with Boot. This enhances your application with production-ready features.&lt;/p&gt;
  &lt;p&gt;Spring Boot has very powerful and nice configuration controls. Because of these, you can extend the Boot in a very simple and impressive way. Boot is one of the first microservice ready platforms.&lt;/p&gt;
  &lt;p&gt;Your project configuration will be very simple with the help of Boot and you need not maintain an XML file as well. Boot provides a lot of default implementation and JPA integration and Spring Hibernate will be pretty simple.&lt;/p&gt;
  &lt;h1&gt;Conclusion&lt;/h1&gt;
  &lt;p&gt;So, if you look at the comparison part, Spring Boot is more useful when compared with Spring MVC as it has many inbuilt features and benefits which make it more reliable to use than MVC. Most of the things are auto configured using Boot. Just like Tomcat, Boot bundles a war file with server runtime. This enables for easy deployment and distribution of web applications. To get in-depth knowledge, enroll for a live free demo on &lt;a href=&quot;https://onlineitguru.com/spring-boot-training.html&quot; target=&quot;_blank&quot;&gt;&lt;strong&gt;Spring Boot Training&lt;/strong&gt;&lt;/a&gt;&lt;/p&gt;
  &lt;p&gt;Spring Boot is quite useful for container based deployments as industry is moving towards them. Though Spring MVC is the oldest and widely used JVM web framework and it has a large community of followers which are quite helpful and have provided numerous answers and tutorials, the popularity of Spring Boot is growing at a rapid pace and the reasons are mentioned clearly in the above section.&lt;/p&gt;

</content></entry><entry><id>sravancynixit:XWxiKZkRL</id><link rel="alternate" type="text/html" href="https://teletype.in/@sravancynixit/XWxiKZkRL?utm_source=teletype&amp;utm_medium=feed_atom&amp;utm_campaign=sravancynixit"></link><title>Introduction to Spring Framework</title><published>2020-05-01T06:40:48.156Z</published><updated>2020-05-01T06:40:48.156Z</updated><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://teletype.in/files/b2/c8/b2c8ad6a-f799-433a-99be-5f0d5954e778.png"></media:thumbnail><summary type="html">&lt;img src=&quot;https://teletype.in/files/ed/3a/ed3a1043-b19b-4da4-88e2-1e3e5b49e7cd.png&quot;&gt;Prior to the advent of Enterprise Java Beans (EJB), Java developers needed to use Java Beans to create Web applications. Although JavaBeans helped in the development of user interface (UI) components, they were not able to provide services, such as transaction management and security, which were required for developing robust and secure enterprise applications. The advent of EJB was seen as a solution to this problem EJB extends the Java components, such as Web and enterprise components, and provides services that help in enterprise application development. However, developing an enterprise application with EJB was not easy, as the developer needed to perform various tasks, such as creating Home and Remote interfaces and implementing...</summary><content type="html">
  &lt;h2&gt;Introduction:&lt;/h2&gt;
  &lt;p&gt;Prior to the advent of Enterprise Java Beans (EJB), Java developers needed to use Java Beans to create Web applications. Although JavaBeans helped in the development of user interface (UI) components, they were not able to provide services, such as transaction management and security, which were required for developing robust and secure enterprise applications. The advent of EJB was seen as a solution to this problem EJB extends the Java components, such as Web and enterprise components, and provides services that help in enterprise application development. However, developing an enterprise application with EJB was not easy, as the developer needed to perform various tasks, such as creating Home and Remote interfaces and implementing lifecycle callback methods which lead to the complexity of providing code for EJBs Due to this complication, developers started looking for an easier way to develop enterprise applications. &lt;/p&gt;
  &lt;p&gt; If you want to Gain In-depth Knowledge on &lt;strong&gt;Spring Boot&lt;/strong&gt;, please go through this link &lt;a href=&quot;https://onlineitguru.com/spring-boot-training.html&quot; target=&quot;_blank&quot;&gt;&lt;strong&gt;Spring Boot Online Training&lt;/strong&gt;&lt;/a&gt;&lt;/p&gt;
  &lt;p&gt;The Spring framework has emerged as a solution to all these complications This framework uses various new techniques such as Aspect-Oriented Programming (AOP), Plain Old Java Object (POJO), and dependency injection (DI), to develop enterprise applications, thereby removing the complexities involved while developing enterprise applications using EJB, Spring is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier as compared to classic Java frameworks and Application Programming Interfaces (APIs), such as Java database connectivity(JDBC), JavaServer Pages(JSP), and Java Servlet.&lt;/p&gt;
  &lt;p&gt;The Spring framework can be considered as a collection of sub-frameworks, also called layers, such as Spring AOP. Spring Object-Relational Mapping (Spring ORM). Spring Web Flow, and Spring Web MVC. You can use any of these modules separately while constructing a Web application. The modules may also be grouped together to provide better functionalities in a Web application.&lt;/p&gt;
  &lt;h2&gt;Features of te Spring Framework:&lt;/h2&gt;
  &lt;figure class=&quot;m_original&quot;&gt;
    &lt;img src=&quot;https://teletype.in/files/ed/3a/ed3a1043-b19b-4da4-88e2-1e3e5b49e7cd.png&quot; width=&quot;700&quot; /&gt;
  &lt;/figure&gt;
  &lt;p&gt;The features of the Spring framework such as IoC, AOP, and transaction management, make it unique among the list of frameworks. Some of the most important features of the Spring framework are as follows:&lt;/p&gt;
  &lt;ul&gt;
    &lt;li&gt;&lt;strong&gt;IoC container:- &lt;/strong&gt;Refers to the core container that uses the DI or IoC pattern to implicitly provide an object reference in a class during runtime. This pattern acts as an alternative to the service locator pattern. The IoC container contains assembler code that handles the configuration management of application objects.&lt;br /&gt;The Spring framework provides two packages, namely org.springframework.beans and org.springframework.context which helps in providing the functionality of the IoC container.&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;Data access framework:- &lt;/strong&gt;Allows the developers to use persistence APIs, such as JDBC and Hibernate, for storing persistence data in the database. It helps in solving various problems of the developer, such as how to interact with a database connection, how to make sure that the connection is closed, how to deal with exceptions, and how to implement transaction management It also enables the developers to easily write code to access the persistence data throughout the application. For more Additional info at &lt;strong&gt;&lt;a href=&quot;https://onlineitguru.com/spring-boot-training.html&quot; target=&quot;_blank&quot;&gt;Spring Boot Online Course&lt;/a&gt;&lt;/strong&gt;&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;Spring MVC framework:- &lt;/strong&gt;Allows you to build Web applications based on MVC architecture. All the requests made by a user first go through the controller and are then dispatched to different views, that is, to different JSP pages or Servlets. The form handling and form validating features of the Spring MVC framework can be easily integrated with all popular view technologies such as ISP, Jasper Report, FreeMarker, and Velocity.&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;Transaction management:- &lt;/strong&gt;Helps in handling transaction management of an application without affecting its code. This framework provides Java Transaction API (JTA) for global transactions managed by an application server and local transactions managed by using the JDBC Hibernate, Java Data Objects (JDO), or other data access APIs. It enables the developer to model a wide range of transactions on the basis of Spring’s declarative and programmatic transaction management.&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;Spring Web Service:- &lt;/strong&gt;Generates Web service endpoints and definitions based on Java classes, but it is difficult to manage them in an application. To solve this problem, Spring Web Service provides layered-based approaches that are separately managed by Extensible Markup Language (XML) parsing (the technique of reading and manipulating XML). Spring provides effective mapping for transmitting incoming XML message request to an object and the developer to easily distribute XML message (object) between two machines.&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;JDBC abstraction layer:- &lt;/strong&gt;Helps the users in handling errors in an easy and efficient manner. The JDBC programming code can be reduced when this abstraction layer is implemented in a Web application. This layer handles exceptions such as DriverNotFound. All SQLExceptions are translated into the DataAccessException class. Spring’s data access exception is not JDBC specific and hence Data Access Objects (DAO) are not bound to JDBC only.&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;Spring TestContext Framework:- &lt;/strong&gt;Provides facilities of the unit and integration testing for the Spring applications. Moreover, the Spring TestContext framework provides specific integration testing functionalities such as context management and caching DI of test fixtures, and transactional test management with default rollback semantics.&lt;/li&gt;
  &lt;/ul&gt;
  &lt;p&gt;&lt;a href=&quot;https://scrapbox.io/sravancynixit-55602833/What_Is_Spring_Boot%3F&quot; target=&quot;_blank&quot;&gt;What Is Spring Boot? — Sravan Cynixit’s projectSpring Boot is an open-source micro framework maintained by a company called Pivotal. It provides Java developers with…scrapbox.io&lt;/a&gt;&lt;/p&gt;
  &lt;h2&gt;Evolution of Spring Framework&lt;/h2&gt;
  &lt;p&gt;The Spring Framework was first released in 2004. After that there has been a significant major revision, such as Spring 2.0 provided XML namespaces and AspectJ support, Spring 2.5 provide annotation-driven configuration, Spring 3.0 provided a Java-based @Configuration model. The latest release of the spring framework is 4.0. it is released with the support for Java 8 and Java EE 7 technologies. Though you can still use Spring with an older version of java, the minimum requirement is restricted to Java SE 6. Spring 4.0 also supports Java EE 7 technologies, such as java message service (JMS) 2.0, java Persistence API (JPA) 2.1, Bean validation 1.1, servlet 3.1, and JCache.&lt;/p&gt;
  &lt;h2&gt;Spring Framework Architecture&lt;/h2&gt;
  &lt;figure class=&quot;m_original&quot;&gt;
    &lt;img src=&quot;https://teletype.in/files/37/14/3714dc9b-c436-4d40-8b90-319ca3a66b9d.png&quot; width=&quot;650&quot; /&gt;
  &lt;/figure&gt;
  &lt;p&gt;The Spring Framework consists of seven modules which are shown in the above Figure. These modules are Spring Core, Spring AOP, Spring Web MVC, Spring DAO, Spring ORM, Spring context, and Spring Web Flow. These modules provide different platforms to develop different enterprise applications; for example, you can use the Spring Web MVC module for developing MVC-based applications.&lt;/p&gt;
  &lt;h2&gt;Spring Framework Modules&lt;/h2&gt;
  &lt;ul&gt;
    &lt;li&gt;&lt;strong&gt;Spring Core Module:- &lt;/strong&gt;The Spring Core module, which is the core component of the Spring framework, provides the IoC container There are two types of implementations of the Spring container, namely, bean factory and application context. Bean factory is defined using the &lt;em&gt;org.springframework.beans.factory.BeanFactory&lt;/em&gt; interface and acts as a container for beans. The Bean factory container allows you to decouple the configuration and specification of dependencies from program logic. In the Spring framework, the Bean factory acts as a central IoC container that is responsible for instantiating application objects. It also configures and assembles the dependencies between these objects. There are numerous implementations of the BeanFactory interface. The XmlBeanFactory class is the most common implementation of the BeanFactory interface. This allows you to express the object to compose your application and remove interdependencies between application objects.&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;Spring AOP Module:- &lt;/strong&gt;Similar to Object-Oriented Programming (OOP), which breaks down the applications into hierarchy of objects, AOP breaks down the programs into aspects or concerns. Spring AOP module allows you to implement concerns or aspects in a Spring application in Spring AOP, the aspects are the regular Spring beans or regular classes annotated with @Aspect annotation. These aspects help in transaction management and logging and failure monitoring of an application. For example, transaction management is required in bank operations such as transferring an amount from one account to another Spring AOP module provides a transaction management abstraction layer that can be applied to transaction APIs.&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;Spring ORM Module:- &lt;/strong&gt;The Spring ORM module is used for accessing data from databases in an application. It provides APIs for manipulating databases with JDO, Hibernate, and iBatis. Spring ORM supports DAO, which provides a convenient way to build the following DAOs-based ORM solutions:&lt;br /&gt;• Simple declarative transaction management&lt;br /&gt;• Transparent exception handling&lt;br /&gt;• Thread-safe, lightweight template classes&lt;br /&gt;• DAO support classes&lt;br /&gt;• Resource management&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;Spring Web MVC Module:- &lt;/strong&gt;The Web MVC module of Spring implements the MVC architecture for creating Web applications. It separates the code of model and view components of a Web application. In Spring MVC, when a request is generated from the browser, it first goes to the &lt;em&gt;DispatcherServlet class&lt;/em&gt; (Front Controller), which dispatches the request to a controller (&lt;em&gt;SimpleFormController class or AbstractWizardformController class&lt;/em&gt;) using a set of handler mappings. The controller extracts and processes the information embedded in a request and sends the result to the DispatcherServlet class in the form of the model object. Finally, the DispatcherServlet class uses ViewResolver classes to send the results to a view, which displays these results to the users.&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;Spring Web Flow Module:- &lt;/strong&gt;The Spring Web Flow module is an extension of the Spring Web MVC module. Spring Web MVC framework provides form controllers, such as class SimpleFormController and &lt;em&gt;AbstractWizardFormController class&lt;/em&gt;, to implement predefined workflow. The Spring Web Flow helps in defining XML file or Java Class that manages the workflow between different pages of a Web application. The Spring Web Flow is distributed separately and can be downloaded through &lt;em&gt;http://www.springframework.org&lt;/em&gt; website.&lt;br /&gt;&lt;strong&gt;The following are the advantages of Spring Web Flow:&lt;/strong&gt;&lt;br /&gt;• The flow between different UIs of the application is clearly provided by defining Web flow in XML file.&lt;br /&gt;• Web flow definitions help you to virtually split an application in different modules and reuse these modules in multiple situations.&lt;br /&gt;•Spring Web Flow lifecycle can be managed automatically&lt;/li&gt;
  &lt;/ul&gt;
  &lt;blockquote&gt;To get in-depth knowledge on Spring Boot, Enroll for live free demo on &lt;a href=&quot;https://onlineitguru.com/spring-boot-training.html&quot; target=&quot;_blank&quot;&gt;&lt;strong&gt;Spring Boot Training&lt;/strong&gt;&lt;/a&gt;&lt;/blockquote&gt;
  &lt;ul&gt;
    &lt;li&gt;&lt;strong&gt;Spring Web DAO Module:- &lt;/strong&gt;The DAO package in the Spring framework provides DAO support by using data access technologies such as JDBC, Hibernate, or JDO. This module introduces a JDBC abstraction layer by eliminating the need for providing tedious JDBC coding. It also provides programmatic as well as declarative transaction management classes. Spring DAO package supports heterogeneous Java Database Connectivity and O/R mapping, which helps Spring work with several data access technologies. For easy and quick access to database resources, the Spring framework provides abstract DAO base classes. Multiple implementations are available for each data access technology supported by the Spring framework. For example, in JDBC, the JdbcDaoSupport class and its methods are used to access the DataSource instance and a preconfigured JdbcTemplate instance. You need to simply extend the JdbcDaoSupport class and provide a mapping to the actual DataSource instance in an application context configuration to access a DAO-based application.&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;Spring Application Context Module:- &lt;/strong&gt;The Spring Application context module is based on the Core module. Application context &lt;em&gt;org.springframework.context.ApplicationContext&lt;/em&gt; is an interface of BeanFactory. This module derives its feature from the &lt;em&gt;org.springframework.beans&lt;/em&gt; package and also supports functionalities such as internationalization (I18N), validation, event propagation, and resource loading. The Application context implements Message Source interface and provides the messaging functionality to an application.&lt;/li&gt;
  &lt;/ul&gt;

</content></entry><entry><id>sravancynixit:SdDF2Rqd5</id><link rel="alternate" type="text/html" href="https://teletype.in/@sravancynixit/SdDF2Rqd5?utm_source=teletype&amp;utm_medium=feed_atom&amp;utm_campaign=sravancynixit"></link><title>Spring Boot Security + JWT Hello World Example</title><published>2020-04-30T07:43:50.723Z</published><updated>2020-04-30T07:43:50.723Z</updated><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://teletype.in/files/e8/80/e88041ef-1c4b-4aa7-930f-27dae9fe5577.png"></media:thumbnail><summary type="html">&lt;img src=&quot;https://teletype.in/files/c6/27/c627a9f1-dfe3-4058-8403-1400cc423daf.png&quot;&gt;In this tutorial, we will be developing a Spring Boot application that makes use of JWT authentication for securing an exposed REST API. In this example, we will be making use of hard-coded user values for user authentication. In the next tutorial, we will be implementing Spring Boot + JWT + MYSQL JPA for storing and fetching user credentials. Any user will be able to consume this API only if it has a valid JSON Web Token (JWT). In a previous tutorial, we learned what is JWT and when and how to use it.</summary><content type="html">
  &lt;p&gt;In this tutorial, we will be developing a Spring Boot application that makes use of JWT authentication for securing an exposed REST API. In this example, we will be making use of hard-coded user values for user authentication. In the next tutorial, we will be implementing Spring Boot + JWT + MYSQL JPA for storing and fetching user credentials. Any user will be able to consume this API only if it has a valid JSON Web Token (JWT). In a previous tutorial, we learned what is JWT and when and how to use it.&lt;/p&gt;
  &lt;p&gt;If you want to Gain In-depth Knowledge on &lt;strong&gt;Spring Boot&lt;/strong&gt;, please go through this link &lt;strong&gt;&lt;a href=&quot;https://onlineitguru.com/spring-boot-training.html&quot; target=&quot;_blank&quot;&gt;Spring Boot Training&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;
  &lt;p&gt;For better understanding, we will be developing the project in stages:&lt;/p&gt;
  &lt;p&gt;Develop a Spring Boot application that exposes a simple REST GET API with mapping /hello.&lt;/p&gt;
  &lt;p&gt;Configure Spring Security for JWT. Expose REST POST API with mapping/authenticate using which User will get a valid JSON Web Token. And then, allow the user access to the API /hello only if it has a valid token&lt;/p&gt;
  &lt;figure class=&quot;m_original&quot;&gt;
    &lt;img src=&quot;https://teletype.in/files/c6/27/c627a9f1-dfe3-4058-8403-1400cc423daf.png&quot; width=&quot;645&quot; /&gt;
  &lt;/figure&gt;
  &lt;h1&gt;Develop a Spring Boot Application That Exposes a GET REST API&lt;/h1&gt;
  &lt;p&gt;The Maven project will look as follows:&lt;/p&gt;
  &lt;p&gt;&lt;/p&gt;
  &lt;p&gt;The pom.xml is as follows:&lt;/p&gt;
  &lt;pre&gt;&amp;lt;project xmlns=&amp;quot;http://maven.apache.org/POM/4.0.0&amp;quot; xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;	xsi:schemaLocation=&amp;quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&amp;quot;&amp;gt;	&amp;lt;modelVersion&amp;gt;4.0.0&amp;lt;/modelVersion&amp;gt;	&amp;lt;groupId&amp;gt;com.javainuse&amp;lt;/groupId&amp;gt;	&amp;lt;artifactId&amp;gt;spring-boot-jwt&amp;lt;/artifactId&amp;gt;	&amp;lt;version&amp;gt;0.0.1-SNAPSHOT&amp;lt;/version&amp;gt;	&amp;lt;parent&amp;gt;		&amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;		&amp;lt;artifactId&amp;gt;spring-boot-starter-parent&amp;lt;/artifactId&amp;gt;		&amp;lt;version&amp;gt;2.1.1.RELEASE&amp;lt;/version&amp;gt;		&amp;lt;relativePath /&amp;gt; &amp;lt;!-- lookup parent from repository --&amp;gt;	&amp;lt;/parent&amp;gt;	&amp;lt;properties&amp;gt;		&amp;lt;project.build.sourceEncoding&amp;gt;UTF-8&amp;lt;/project.build.sourceEncoding&amp;gt;		&amp;lt;project.reporting.outputEncoding&amp;gt;UTF-8&amp;lt;/project.reporting.outputEncoding&amp;gt;		&amp;lt;java.version&amp;gt;1.8&amp;lt;/java.version&amp;gt;	&amp;lt;/properties&amp;gt;	&amp;lt;dependencies&amp;gt;		&amp;lt;dependency&amp;gt;			&amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;			&amp;lt;artifactId&amp;gt;spring-boot-starter-web&amp;lt;/artifactId&amp;gt;		&amp;lt;/dependency&amp;gt;	&amp;lt;/dependencies&amp;gt;&amp;lt;/project&amp;gt;&lt;/pre&gt;
  &lt;figure class=&quot;m_original&quot;&gt;
    &lt;img src=&quot;https://teletype.in/files/5c/05/5c05faa8-7b6a-45a4-9c42-508f90fa75a9.png&quot; width=&quot;300&quot; /&gt;
  &lt;/figure&gt;
  &lt;pre&gt;package com.javainuse.controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class HelloWorldController {	@RequestMapping({ &amp;quot;/hello&amp;quot; })	public String firstPage() {		return &amp;quot;Hello World&amp;quot;;	}}&lt;/pre&gt;
  &lt;p&gt;Create the bootstrap class with Spring Boot Annotation&lt;/p&gt;
  &lt;pre&gt;package com.javainuse;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class SpringBootHelloWorldApplication {	public static void main(String[] args) {		SpringApplication.run(SpringBootHelloWorldApplication.class, args);	}}&lt;/pre&gt;
  &lt;p&gt;Compile and the run the SpringBootHelloWorldApplication.java as a Java application.&lt;br /&gt;Go to &lt;strong&gt;localhost:8080/hello&lt;/strong&gt;&lt;/p&gt;
  &lt;figure class=&quot;m_original&quot;&gt;
    &lt;img src=&quot;https://teletype.in/files/07/49/07499ad3-3f0a-4341-8057-2712ad88b1cd.png&quot; width=&quot;421&quot; /&gt;
  &lt;/figure&gt;
  &lt;h1&gt;Spring Security and JWT Configuration&lt;/h1&gt;
  &lt;p&gt;We will be configuring Spring Security and JWT for performing 2 operations-&lt;/p&gt;
  &lt;ul&gt;
    &lt;li&gt;&lt;strong&gt;Generating JWT&lt;/strong&gt; — Expose a POST API with mapping &lt;strong&gt;/authenticate&lt;/strong&gt;. On passing correct username and password it will generate a JSON Web Token(JWT)&lt;/li&gt;
    &lt;li&gt;&lt;strong&gt;Validating JWT&lt;/strong&gt; — If user tries to access GET API with mapping &lt;strong&gt;/hello&lt;/strong&gt;. It will allow access only if request has a valid JSON Web Token(JWT) at &lt;em&gt;&lt;strong&gt;&lt;a href=&quot;https://onlineitguru.com/spring-boot-training.html&quot; target=&quot;_blank&quot;&gt;Spring Boot Online Training&lt;/a&gt;&lt;/strong&gt;&lt;/em&gt;&lt;/li&gt;
  &lt;/ul&gt;
  &lt;p&gt;Maven Project will be as follows-&lt;/p&gt;
  &lt;figure class=&quot;m_original&quot;&gt;
    &lt;img src=&quot;https://teletype.in/files/d7/19/d719890f-bb60-4c65-bdfd-48e70ca9fe9c.png&quot; width=&quot;301&quot; /&gt;
  &lt;/figure&gt;
  &lt;p&gt;The sequence flow for these operations will be as follows-&lt;/p&gt;
  &lt;h1&gt;Generating JWT&lt;/h1&gt;
  &lt;figure class=&quot;m_original&quot;&gt;
    &lt;img src=&quot;https://teletype.in/files/2e/23/2e23068a-c849-49b0-8fd5-64430bf481cf.png&quot; width=&quot;949&quot; /&gt;
  &lt;/figure&gt;
  &lt;p&gt;&lt;/p&gt;
  &lt;figure class=&quot;m_original&quot;&gt;
    &lt;img src=&quot;https://teletype.in/files/75/6a/756acc46-5b62-4ea0-8554-052293b2d4a3.png&quot; width=&quot;601&quot; /&gt;
  &lt;/figure&gt;
  &lt;figure class=&quot;m_original&quot;&gt;
    &lt;img src=&quot;https://teletype.in/files/95/8f/958f0394-051d-4e99-9d87-2425a92c10a2.png&quot; width=&quot;775&quot; /&gt;
  &lt;/figure&gt;
  &lt;p&gt;Add the Spring Security and JWT dependencies&lt;/p&gt;
  &lt;pre&gt;&amp;lt;project xmlns=&amp;quot;http://maven.apache.org/POM/4.0.0&amp;quot; xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;	xsi:schemaLocation=&amp;quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&amp;quot;&amp;gt;	&amp;lt;modelVersion&amp;gt;4.0.0&amp;lt;/modelVersion&amp;gt;	&amp;lt;groupId&amp;gt;com.javainuse&amp;lt;/groupId&amp;gt;	&amp;lt;artifactId&amp;gt;spring-boot-jwt&amp;lt;/artifactId&amp;gt;	&amp;lt;version&amp;gt;0.0.1-SNAPSHOT&amp;lt;/version&amp;gt;	&amp;lt;parent&amp;gt;		&amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;		&amp;lt;artifactId&amp;gt;spring-boot-starter-parent&amp;lt;/artifactId&amp;gt;		&amp;lt;version&amp;gt;2.1.1.RELEASE&amp;lt;/version&amp;gt;		&amp;lt;relativePath /&amp;gt; &amp;lt;!-- lookup parent from repository --&amp;gt;	&amp;lt;/parent&amp;gt;	&amp;lt;properties&amp;gt;		&amp;lt;project.build.sourceEncoding&amp;gt;UTF-8&amp;lt;/project.build.sourceEncoding&amp;gt;		&amp;lt;project.reporting.outputEncoding&amp;gt;UTF-8&amp;lt;/project.reporting.outputEncoding&amp;gt;		&amp;lt;java.version&amp;gt;1.8&amp;lt;/java.version&amp;gt;	&amp;lt;/properties&amp;gt;	&amp;lt;dependencies&amp;gt;		&amp;lt;dependency&amp;gt;			&amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;			&amp;lt;artifactId&amp;gt;spring-boot-starter-web&amp;lt;/artifactId&amp;gt;		&amp;lt;/dependency&amp;gt;		&amp;lt;dependency&amp;gt;			&amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;			&amp;lt;artifactId&amp;gt;spring-boot-starter-security&amp;lt;/artifactId&amp;gt;		&amp;lt;/dependency&amp;gt;		&amp;lt;dependency&amp;gt;			&amp;lt;groupId&amp;gt;io.jsonwebtoken&amp;lt;/groupId&amp;gt;			&amp;lt;artifactId&amp;gt;jjwt&amp;lt;/artifactId&amp;gt;			&amp;lt;version&amp;gt;0.9.1&amp;lt;/version&amp;gt;		&amp;lt;/dependency&amp;gt;	&amp;lt;/dependencies&amp;gt;&amp;lt;/project&amp;gt;&lt;/pre&gt;
  &lt;p&gt;Define the application.properties. As see in previous JWT tutorial, we specify the secret key using which we will be using for hashing algorithm. The secret key is combined with the header and the payload to create a unique hash. We are only able to verify this hash if you have the secret key.&lt;/p&gt;
  &lt;pre&gt;jwt.secret=javainuse&lt;/pre&gt;
  &lt;h2&gt;JwtTokenUtil&lt;/h2&gt;
  &lt;p&gt;The JwtTokenUtil is responsible for performing JWT operations like creation and validation.It makes use of the io.jsonwebtoken.Jwts for achieving this.&lt;/p&gt;
  &lt;pre&gt;package com.javainuse.config;import java.io.Serializable;import java.util.Date;import java.util.HashMap;import java.util.Map;import java.util.function.Function;import org.springframework.beans.factory.annotation.Value;import org.springframework.security.core.userdetails.UserDetails;import org.springframework.stereotype.Component;import io.jsonwebtoken.Claims;import io.jsonwebtoken.Jwts;import io.jsonwebtoken.SignatureAlgorithm;@Componentpublic class JwtTokenUtil implements Serializable {	private static final long serialVersionUID = -2550185165626007488L;	public static final long JWT_TOKEN_VALIDITY = 5 * 60 * 60;	@Value(&amp;quot;${jwt.secret}&amp;quot;)	private String secret;	//retrieve username from jwt token	public String getUsernameFromToken(String token) {		return getClaimFromToken(token, Claims::getSubject);	}	//retrieve expiration date from jwt token	public Date getExpirationDateFromToken(String token) {		return getClaimFromToken(token, Claims::getExpiration);	}	public &amp;lt;T&amp;gt; T getClaimFromToken(String token, Function&amp;lt;Claims, T&amp;gt; claimsResolver) {		final Claims claims = getAllClaimsFromToken(token);		return claimsResolver.apply(claims);	}    //for retrieveing any information from token we will need the secret key	private Claims getAllClaimsFromToken(String token) {		return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();	}	//check if the token has expired	private Boolean isTokenExpired(String token) {		final Date expiration = getExpirationDateFromToken(token);		return expiration.before(new Date());	}	//generate token for user	public String generateToken(UserDetails userDetails) {		Map&amp;lt;String, Object&amp;gt; claims = new HashMap&amp;lt;&amp;gt;();		return doGenerateToken(claims, userDetails.getUsername());	}	//while creating the token -	//1. Define  claims of the token, like Issuer, Expiration, Subject, and the ID	//2. Sign the JWT using the HS512 algorithm and secret key.	//3. According to JWS Compact Serialization(https://tools.ietf.org/html/draft-ietf-jose-json-web-signature-41#section-3.1)	//   compaction of the JWT to a URL-safe string 	private String doGenerateToken(Map&amp;lt;String, Object&amp;gt; claims, String subject) {		return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))				.setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY * 1000))				.signWith(SignatureAlgorithm.HS512, secret).compact();	}	//validate token	public Boolean validateToken(String token, UserDetails userDetails) {		final String username = getUsernameFromToken(token);		return (username.equals(userDetails.getUsername()) &amp;amp;&amp;amp; !isTokenExpired(token));	}}&lt;/pre&gt;
  &lt;h2&gt;JWTUserDetailsService&lt;/h2&gt;
  &lt;p&gt;JWTUserDetailsService implements the Spring Security UserDetailsService interface. It overrides the loadUserByUsername for fetching user details from the database using the username. The Spring Security Authentication Manager calls this method for getting the user details from the database when authenticating the user details provided by the user. Here we are getting the &lt;strong&gt;user details from a hardcoded User List&lt;/strong&gt;. In the next tutorial we will be adding the DAO implementation for fetching User Details from the Database. Also the password for a user is stored in encrypted format using BCrypt. Previously we have seenSpring Boot Security — Password Encoding Using Bcrypt. Here using the Online Bcrypt Generator you can generate the Bcrypt for a password.&lt;/p&gt;
  &lt;pre&gt;package com.javainuse.service;import java.util.ArrayList;import org.springframework.security.core.userdetails.User;import org.springframework.security.core.userdetails.UserDetails;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.core.userdetails.UsernameNotFoundException;import org.springframework.stereotype.Service;@Servicepublic class JwtUserDetailsService implements UserDetailsService {	@Override	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {		if (&amp;quot;javainuse&amp;quot;.equals(username)) {			return new User(&amp;quot;javainuse&amp;quot;, &amp;quot;$2a$10$slYQmyNdGzTn7ZLBXBChFOC9f6kFjAqPhccnP6DxlWXx2lPk1C3G6&amp;quot;,					new ArrayList&amp;lt;&amp;gt;());		} else {			throw new UsernameNotFoundException(&amp;quot;User not found with username: &amp;quot; + username);		}	}}&lt;/pre&gt;
  &lt;h2&gt;JwtAuthenticationController&lt;/h2&gt;
  &lt;p&gt;Expose a POST API /authenticate using the JwtAuthenticationController. The POST API gets username and password in the body- Using Spring Authentication Manager we authenticate the username and password.If the credentials are valid, a JWT token is created using the JWTTokenUtil and provided to the client.&lt;/p&gt;
  &lt;pre&gt;package com.javainuse.controller;import java.util.Objects;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.ResponseEntity;import org.springframework.security.authentication.AuthenticationManager;import org.springframework.security.authentication.BadCredentialsException;import org.springframework.security.authentication.DisabledException;import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;import org.springframework.security.core.userdetails.UserDetails;import org.springframework.web.bind.annotation.CrossOrigin;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;import com.javainuse.service.JwtUserDetailsService;import com.javainuse.config.JwtTokenUtil;import com.javainuse.model.JwtRequest;import com.javainuse.model.JwtResponse;@RestController@CrossOriginpublic class JwtAuthenticationController {	@Autowired	private AuthenticationManager authenticationManager;	@Autowired	private JwtTokenUtil jwtTokenUtil;	@Autowired	private JwtUserDetailsService userDetailsService;	@RequestMapping(value = &amp;quot;/authenticate&amp;quot;, method = RequestMethod.POST)	public ResponseEntity&amp;lt;?&amp;gt; createAuthenticationToken(@RequestBody JwtRequest authenticationRequest) throws Exception {		authenticate(authenticationRequest.getUsername(), authenticationRequest.getPassword());		final UserDetails userDetails = userDetailsService				.loadUserByUsername(authenticationRequest.getUsername());		final String token = jwtTokenUtil.generateToken(userDetails);		return ResponseEntity.ok(new JwtResponse(token));	}	private void authenticate(String username, String password) throws Exception {		try {			authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));		} catch (DisabledException e) {			throw new Exception(&amp;quot;USER_DISABLED&amp;quot;, e);		} catch (BadCredentialsException e) {			throw new Exception(&amp;quot;INVALID_CREDENTIALS&amp;quot;, e);		}	}}&lt;/pre&gt;
  &lt;h2&gt;JwtRequest&lt;/h2&gt;
  &lt;p&gt;This class is required for storing the username and password we recieve from the client.&lt;/p&gt;
  &lt;pre&gt;package com.javainuse.model;import java.io.Serializable;public class JwtRequest implements Serializable {	private static final long serialVersionUID = 5926468583005150707L;		private String username;	private String password;		//need default constructor for JSON Parsing	public JwtRequest()	{			}	public JwtRequest(String username, String password) {		this.setUsername(username);		this.setPassword(password);	}	public String getUsername() {		return this.username;	}	public void setUsername(String username) {		this.username = username;	}	public String getPassword() {		return this.password;	}	public void setPassword(String password) {		this.password = password;	}}&lt;/pre&gt;
  &lt;h2&gt;JwtResponse&lt;/h2&gt;
  &lt;p&gt;This is class is required for creating a response containing the JWT to be returned to the user.&lt;/p&gt;
  &lt;pre&gt;package com.javainuse.model;import java.io.Serializable;public class JwtResponse implements Serializable {	private static final long serialVersionUID = -8091879091924046844L;	private final String jwttoken;	public JwtResponse(String jwttoken) {		this.jwttoken = jwttoken;	}	public String getToken() {		return this.jwttoken;	}}&lt;/pre&gt;
  &lt;h2&gt;JwtRequestFilter&lt;/h2&gt;
  &lt;p&gt;The JwtRequestFilter extends the Spring Web Filter OncePerRequestFilter class. For any incoming request this Filter class gets executed. It checks if the request has a valid JWT token. If it has a valid JWT Token then it sets the Authentication in the context, to specify that the current user is authenticated.&lt;/p&gt;
  &lt;pre&gt;package com.javainuse.config;import java.io.IOException;import javax.servlet.FilterChain;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;import org.springframework.security.core.context.SecurityContextHolder;import org.springframework.security.core.userdetails.UserDetails;import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;import org.springframework.stereotype.Component;import org.springframework.web.filter.OncePerRequestFilter;import com.javainuse.service.JwtUserDetailsService;import io.jsonwebtoken.ExpiredJwtException;@Componentpublic class JwtRequestFilter extends OncePerRequestFilter {	@Autowired	private JwtUserDetailsService jwtUserDetailsService;	@Autowired	private JwtTokenUtil jwtTokenUtil;	@Override	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)			throws ServletException, IOException {		final String requestTokenHeader = request.getHeader(&amp;quot;Authorization&amp;quot;);		String username = null;		String jwtToken = null;		// JWT Token is in the form &amp;quot;Bearer token&amp;quot;. Remove Bearer word and get		// only the Token		if (requestTokenHeader != null &amp;amp;&amp;amp; requestTokenHeader.startsWith(&amp;quot;Bearer &amp;quot;)) {			jwtToken = requestTokenHeader.substring(7);			try {				username = jwtTokenUtil.getUsernameFromToken(jwtToken);			} catch (IllegalArgumentException e) {				System.out.println(&amp;quot;Unable to get JWT Token&amp;quot;);			} catch (ExpiredJwtException e) {				System.out.println(&amp;quot;JWT Token has expired&amp;quot;);			}		} else {			logger.warn(&amp;quot;JWT Token does not begin with Bearer String&amp;quot;);		}		// Once we get the token validate it.		if (username != null &amp;amp;&amp;amp; SecurityContextHolder.getContext().getAuthentication() == null) {			UserDetails userDetails = this.jwtUserDetailsService.loadUserByUsername(username);			// if token is valid configure Spring Security to manually set			// authentication			if (jwtTokenUtil.validateToken(jwtToken, userDetails)) {				UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(						userDetails, null, userDetails.getAuthorities());				usernamePasswordAuthenticationToken						.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));				// After setting the Authentication in the context, we specify				// that the current user is authenticated. So it passes the				// Spring Security Configurations successfully.				SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);			}		}		chain.doFilter(request, response);	}}&lt;/pre&gt;
  &lt;h2&gt;JwtAuthenticationEntryPoint&lt;/h2&gt;
  &lt;p&gt;This class will extend Spring’s AuthenticationEntryPoint class and override its method commence. It rejects every unauthenticated request and send error code 401&lt;/p&gt;
  &lt;pre&gt;package com.javainuse.config;import java.io.IOException;import java.io.Serializable;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.security.core.AuthenticationException;import org.springframework.security.web.AuthenticationEntryPoint;import org.springframework.stereotype.Component;@Componentpublic class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {	private static final long serialVersionUID = -7858869558953243875L;	@Override	public void commence(HttpServletRequest request, HttpServletResponse response,			AuthenticationException authException) throws IOException {		response.sendError(HttpServletResponse.SC_UNAUTHORIZED, &amp;quot;Unauthorized&amp;quot;);	}}&lt;/pre&gt;
  &lt;h2&gt;WebSecurityConfig&lt;/h2&gt;
  &lt;p&gt;This class extends the WebSecurityConfigurerAdapter is a convenience class that allows customization to both WebSecurity and HttpSecurity.&lt;/p&gt;
  &lt;blockquote&gt;Take your career to new heights of success with an &lt;strong&gt;&lt;a href=&quot;https://onlineitguru.com/spring-boot-training.html&quot; target=&quot;_blank&quot;&gt;Spring Boot Online Course&lt;/a&gt;&lt;/strong&gt;&lt;/blockquote&gt;
  &lt;pre&gt;package com.javainuse.config;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.authentication.AuthenticationManager;import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.config.http.SessionCreationPolicy;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;import org.springframework.security.crypto.password.PasswordEncoder;import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;@Configuration@EnableWebSecurity@EnableGlobalMethodSecurity(prePostEnabled = true)public class WebSecurityConfig extends WebSecurityConfigurerAdapter {	@Autowired	private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;	@Autowired	private UserDetailsService jwtUserDetailsService;	@Autowired	private JwtRequestFilter jwtRequestFilter;	@Autowired	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {		// configure AuthenticationManager so that it knows from where to load		// user for matching credentials		// Use BCryptPasswordEncoder		auth.userDetailsService(jwtUserDetailsService).passwordEncoder(passwordEncoder());	}	@Bean	public PasswordEncoder passwordEncoder() {		return new BCryptPasswordEncoder();	}	@Bean	@Override	public AuthenticationManager authenticationManagerBean() throws Exception {		return super.authenticationManagerBean();	}	@Override	protected void configure(HttpSecurity httpSecurity) throws Exception {		// We don&amp;#x27;t need CSRF for this example		httpSecurity.csrf().disable()				// dont authenticate this particular request				.authorizeRequests().antMatchers(&amp;quot;/authenticate&amp;quot;).permitAll().				// all other requests need to be authenticated				anyRequest().authenticated().and().				// make sure we use stateless session; session won&amp;#x27;t be used to				// store user&amp;#x27;s state.				exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()				.sessionCreationPolicy(SessionCreationPolicy.STATELESS);		// Add a filter to validate the tokens with every request		httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);	}}&lt;/pre&gt;
  &lt;p&gt;Start the Spring Boot Application&lt;/p&gt;
  &lt;ul&gt;
    &lt;li&gt;Generate a JSON Web Token -&lt;/li&gt;
    &lt;li&gt;Create a POST request with url localhost:8080/authenticate. Body should have valid username and password. In our case username is javainuse and password is password.&lt;/li&gt;
  &lt;/ul&gt;
  &lt;figure class=&quot;m_original&quot;&gt;
    &lt;img src=&quot;https://teletype.in/files/b9/4c/b94c41f6-ed95-4c6a-b6b8-3af91dc66e8b.png&quot; width=&quot;820&quot; /&gt;
  &lt;/figure&gt;
  &lt;ul&gt;
    &lt;li&gt;Validate the JSON Web Token&lt;/li&gt;
    &lt;li&gt;- Try accessing the url localhost:8080/hello using the above generated token in the header as follows&lt;/li&gt;
  &lt;/ul&gt;
  &lt;figure class=&quot;m_original&quot;&gt;
    &lt;img src=&quot;https://teletype.in/files/57/c8/57c860e8-0166-4661-b6fe-0d35e4e2e23d.png&quot; width=&quot;830&quot; /&gt;
  &lt;/figure&gt;

</content></entry><entry><id>sravancynixit:kAQgFU3LT</id><link rel="alternate" type="text/html" href="https://teletype.in/@sravancynixit/kAQgFU3LT?utm_source=teletype&amp;utm_medium=feed_atom&amp;utm_campaign=sravancynixit"></link><title>Top 10 Spring Boot Interview Questions</title><published>2020-04-27T12:50:36.971Z</published><updated>2020-04-27T12:50:36.971Z</updated><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://teletype.in/files/59/4c/594c913f-a6d4-4fcc-89a3-e63911377f79.png"></media:thumbnail><summary type="html">&lt;img src=&quot;https://teletype.in/files/63/95/63954d78-a722-4d13-a6bb-87bae5b54996.png&quot;&gt;In this article, we will discuss some top 10 interview questions in Spring Boot. These questions are a bit tricky and trending heavily, nowadays, in the job market.</summary><content type="html">
  &lt;h1&gt;Prepare for your next Spring Boot interview with these common interview questions.&lt;/h1&gt;
  &lt;p&gt;In this article, we will discuss some top 10 interview questions in Spring Boot. These questions are a bit tricky and trending heavily, nowadays, in the job market.&lt;/p&gt;
  &lt;figure class=&quot;m_original&quot;&gt;
    &lt;img src=&quot;https://teletype.in/files/63/95/63954d78-a722-4d13-a6bb-87bae5b54996.png&quot; width=&quot;700&quot; /&gt;
  &lt;/figure&gt;
  &lt;p&gt;&lt;strong&gt;1) What does the Spring Boot Application annotation do internally?&lt;/strong&gt;&lt;/p&gt;
  &lt;p&gt;As per the Spring Boot doc, the Spring Boot Application annotation is equivalent to using Configuration, Enable Auto Configuration, and Component Scan with their default attributes. Spring Boot enables the developer to use a single annotation instead of using multiple. But, as we know, Spring provided loosely coupled features that we can use for each individual annotation as per our project needs &lt;a href=&quot;https://onlineitguru.com/spring-boot-training.html&quot; target=&quot;_blank&quot;&gt;&lt;strong&gt;Spring Boot Online Training&lt;/strong&gt;&lt;/a&gt;.&lt;/p&gt;
  &lt;p&gt;&lt;strong&gt;2) How to exclude any package without using the &lt;code&gt;basePackages&lt;/code&gt; filter?&lt;/strong&gt;&lt;/p&gt;
  &lt;p&gt;There are different ways you can filter any package. But Spring Boot provides a trickier option for achieving this without touching the component scan. You can use the &lt;code&gt;exclude&lt;/code&gt; attribute while using the annotation &lt;code&gt;@SpringBootApplication&lt;/code&gt;. See the following code snippet:&lt;/p&gt;
  &lt;pre&gt;@SpringBootApplication(exclude= {Employee.class})public class FooAppConfiguration {}&lt;/pre&gt;
  &lt;p&gt;&lt;strong&gt;3) How to disable a specific auto-configuration class?&lt;/strong&gt;&lt;/p&gt;
  &lt;p&gt;You can use the &lt;code&gt;exclude&lt;/code&gt; attribute of&lt;code&gt;@EnableAutoConfiguration&lt;/code&gt;, if you find any specific auto-configuration classes that you do not want are being applied.&lt;/p&gt;
  &lt;pre&gt;//By using &amp;quot;exclude&amp;quot;@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})&lt;/pre&gt;
  &lt;p&gt;On the other foot, if the class is not on the classpath, you can use the &lt;code&gt;excludeName&lt;/code&gt; attribute of the annotation and specify the fully qualified name instead.&lt;/p&gt;
  &lt;pre&gt;//By using &amp;quot;excludeName&amp;quot;@EnableAutoConfiguration(excludeName={Foo.class})&lt;/pre&gt;
  &lt;p&gt;Also, Spring Boot provides the facility to control the list of auto-configuration classes to exclude by using the &lt;code&gt;spring.autoconfigure.exclude&lt;/code&gt; property. You can add into the application.properties. And you can add multiple classes with comma separated.&lt;/p&gt;
  &lt;pre&gt;//By using property filespring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration&lt;/pre&gt;
  &lt;p&gt;&lt;strong&gt;4) What is Spring Actuator? What are its advantages?&lt;/strong&gt;&lt;/p&gt;
  &lt;p&gt;This is one of the most common interview questions in Spring Boot. As per the Spring doc:&lt;/p&gt;
  &lt;p&gt;As we know, Spring Boot provides lots of auto-configuration features that help developers quickly develop production components. But if you think about debugging and how to debug, if something goes wrong, we always need to analyze the logs and dig through the data flow of our application to check to see what’s going on. So, the Spring Actuator provides easy access to those kinds of features. It provides many features, i.e. what beans are created, the mapping in the controller, the CPU usage, etc. Automatically gathering and auditing health and metrics can then be applied to your application.&lt;/p&gt;
  &lt;p&gt;It provides a very easy way to access the few production-ready REST endpoints and fetch all kinds of information from the web. But by using these endpoints, you can do many things to see here the endpoint docs. There is no need to worry about security; if Spring Security is present, then these endpoints are secured by default using Spring Security’s content-negotiation strategy. Or else, we can configure custom security by the help of &lt;code&gt;RequestMatcher&lt;/code&gt;.&lt;/p&gt;
  &lt;p&gt;&lt;strong&gt;5) How to enable/disable the Actuator?&lt;/strong&gt;&lt;/p&gt;
  &lt;p&gt;Enabling/disabling the actuator is easy; the simplest way is to enable features to add the dependency (Maven/Gradle) to the &lt;em&gt;spring-boot-starter-actuator,&lt;/em&gt; i.e. Starter. If you don’t want the actuator to be enabled, then don’t add the dependency.&lt;/p&gt;
  &lt;p&gt;&lt;strong&gt;Maven dependency:&lt;/strong&gt;&lt;/p&gt;
  &lt;pre&gt;&amp;lt;dependencies&amp;gt;&amp;lt;dependency&amp;gt;&amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;&amp;lt;artifactId&amp;gt;spring-boot-starter-actuator&amp;lt;/artifactId&amp;gt;&amp;lt;/dependency&amp;gt;&amp;lt;/dependencies&amp;gt;&lt;/pre&gt;
  &lt;p&gt;&lt;strong&gt;6) What is the Spring Initializer?&lt;/strong&gt;&lt;/p&gt;
  &lt;p&gt;This may not be a difficult question, but the interviewer always checks the subject knowledge of the candidate. It’s often that you can’t always expect questions that you have prepared. However, this is a very common question asked almost all of the time.&lt;/p&gt;
  &lt;p&gt;The Spring Initializer is a web application that generates a Spring Boot project with everything you need to start it quickly. As always, we need a good skeleton of the project; it helps you to create a project structure/skeleton properly.&lt;/p&gt;
  &lt;p&gt;&lt;strong&gt;7) What is a shutdown in the actuator?&lt;/strong&gt;&lt;/p&gt;
  &lt;p&gt;Shutdown is an endpoint that allows the application to be gracefully shutdown. This feature is not enabled by default. You can enable this by using &lt;em&gt;management.endpoint.shutdown.enabled=true&lt;/em&gt; in your application.properties file. But be careful about this if you are using this.&lt;/p&gt;
  &lt;p&gt;&lt;strong&gt;8) Is this possible to change the port of Embedded Tomcat server in Spring boot?&lt;/strong&gt;&lt;/p&gt;
  &lt;p&gt;Yes, it’s possible to change the port. You can use the application.properties file to change the port. But you need to mention “&lt;em&gt;server.port&lt;/em&gt;” &lt;em&gt;(i.e. server.port=8081)&lt;/em&gt;. Make sure you have application.properties in your project classpath; REST Spring framework will take care of the rest. If you mention &lt;em&gt;server.port=0&lt;/em&gt; , then it will automatically assign any available port. You can learn more about the Embedded Tomcat Server here &lt;strong&gt;&lt;a href=&quot;https://onlineitguru.com/spring-boot-training.html&quot; target=&quot;_blank&quot;&gt;Spring Boot Online Course&lt;/a&gt;.&lt;/strong&gt;&lt;/p&gt;
  &lt;p&gt;&lt;strong&gt;9) Can we override or replace the Embedded Tomcat server in Spring Boot?&lt;/strong&gt;&lt;/p&gt;
  &lt;p&gt;Yes, we can replace the Embedded Tomcat with any other servers by using the Starter dependencies. You can use &lt;code&gt;spring-boot-starter-jetty&lt;/code&gt; or &lt;code&gt;spring-boot-starter-undertow&lt;/code&gt; as a dependency for each project as you need.&lt;/p&gt;
  &lt;p&gt;&lt;strong&gt;10) Can we disable the default web server in the Spring Boot application?&lt;/strong&gt;&lt;/p&gt;
  &lt;p&gt;The major strong point in Spring is to provide flexibility to build your application loosely coupled. Spring provides features to disable the web server in a quick configuration. Yes, we can use the application.properties to configure the web application type, i.e. &lt;code&gt;spring.main.web-application-type=none&lt;/code&gt;.&lt;/p&gt;
  &lt;p&gt;All the best!&lt;/p&gt;

</content></entry><entry><id>sravancynixit:2W9yyPEJc</id><link rel="alternate" type="text/html" href="https://teletype.in/@sravancynixit/2W9yyPEJc?utm_source=teletype&amp;utm_medium=feed_atom&amp;utm_campaign=sravancynixit"></link><title>Netflix OSS and Spring Boot — Coming Full Circle</title><published>2020-04-25T13:12:54.381Z</published><updated>2020-04-25T13:12:54.381Z</updated><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://teletype.in/files/ed/3c/ed3c8b78-670f-4b2b-b156-66169e13f29a.png"></media:thumbnail><summary type="html">&lt;img src=&quot;https://teletype.in/files/91/71/91713727-b5fd-4c92-9292-2de1d9015bc9.png&quot;&gt;In 2007, Netflix started on a long road towards fully operating in the cloud. Much of Netflix’s backend and mid-tier applications are built using Java, and as part of this effort Netflix engineering built several cloud infrastructure libraries and systems — Ribbon for load balancing, Eureka for service discovery, and Hystrix for fault tolerance. To stitch all of these components together, additional libraries were created — Governator for dependency injection with lifecycle management and Archaius for configuration. All of these Netflix libraries and systems were open-sourced around 2012 and are still used by the community to this day.</summary><content type="html">
  &lt;p&gt;In 2007, Netflix started on a long road towards fully operating in the cloud. Much of Netflix’s backend and mid-tier applications are built using Java, and as part of this effort Netflix engineering built several cloud infrastructure libraries and systems — Ribbon for load balancing, Eureka for service discovery, and Hystrix for fault tolerance. To stitch all of these components together, additional libraries were created — Governator for dependency injection with lifecycle management and Archaius for configuration. All of these Netflix libraries and systems were open-sourced around 2012 and are still used by the community to this day.&lt;/p&gt;
  &lt;p&gt;If you want to Gain In-depth Knowledge on &lt;strong&gt;Java Spring Boot&lt;/strong&gt;, please go through this link &lt;strong&gt;&lt;a href=&quot;https://onlineitguru.com/spring-boot-training.html&quot; target=&quot;_blank&quot;&gt;Spring Boot Online Training&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;
  &lt;p&gt;In 2015, Spring Cloud Netflix reached 1.0. This was a community effort to stitch together the Netflix OSS components using Spring Boot instead of Netflix internal solutions. Over time this has become the preferred way for the community to adopt Netflix’s Open Source software. We are happy to announce that starting in 2018, Netflix is also making the transition to Spring Boot as our core Java framework, leveraging the community’s contributions via Spring Cloud Netflix.&lt;/p&gt;
  &lt;figure class=&quot;m_original&quot;&gt;
    &lt;img src=&quot;https://teletype.in/files/91/71/91713727-b5fd-4c92-9292-2de1d9015bc9.png&quot; width=&quot;1017&quot; /&gt;
  &lt;/figure&gt;
  &lt;p&gt;Why is Netflix adopting Spring Boot after having invested so much in internal solutions? In the early 2010s, key requirements for Netflix cloud infrastructure were reliability, scalability, efficiency, and security. Lacking suitable alternatives, we created solutions in-house. Fast forward to 2018, the Spring product has evolved and expanded to meet all of these requirements, some through the usage and adaptation of Netflix’s very own software! In addition, community solutions have evolved beyond Netflix’s original needs. Spring provides great experiences for data access (spring-data), complex security management (spring-security), integration with cloud providers (spring-cloud-aws), and many many more.&lt;/p&gt;
  &lt;p&gt;The evolution of Spring and its features align very well with where we want to go as a company. Spring has shown that they are able to provide well-thought-out, documented, and long lasting abstractions and APIs. Together with the community they have also provided quality implementations from these abstractions and APIs. This abstract-and-implement methodology match well with a core Netflix principle of being “highly aligned, loosely coupled”. Leveraging Spring Boot will allow us to build for the enterprise while remaining agile for our business.&lt;/p&gt;
  &lt;blockquote&gt;Let&amp;#x27;s Get more knowledge on spring Kubernetes go with &lt;strong&gt;&lt;a href=&quot;https://onlineitguru.com/blogger/how-to-utilize-spring-boot-microservices-on-kubernetes&quot; target=&quot;_blank&quot;&gt;How to utilize Spring Boot Microservices on Kubernetes&lt;/a&gt;&lt;/strong&gt;&lt;/blockquote&gt;
  &lt;p&gt;The Spring Boot transition is not something we are undertaking alone. We have been in collaboration with Pivotal throughout the process. Whether it be Github issues and feature requests, in-person conversations at conferences or real-time chats over Gitter/Slack, the responses from Pivotal have been excellent. This level of communication and support gives us great confidence in Pivotal’s ability to maintain and evolve the Spring ecosystem.&lt;/p&gt;
  &lt;p&gt;Moving forward, we plan to leverage the strong abstractions within Spring to further modularize and evolve the Netflix infrastructure. Where there is existing strong community direction — such as the upcoming Spring Cloud Load Balancer — we intend to leverage these to replace aging Netflix software. Where there is new innovation to bring — such as the new Netflix Adaptive Concurrency Limiters — we want to help contribute these back to the community.&lt;/p&gt;
  &lt;p&gt;The union of Netflix OSS and Spring Boot began outside of Netflix. We now embrace it inside of Netflix. This is just the beginning of a long journey, and we will be sure to provide updates and interesting findings as we go. We want to give special thanks to the many people who have contributed to this effort over the years and hope to be part of future innovations to come.&lt;/p&gt;

</content></entry><entry><id>sravancynixit:3JCDEAAz6</id><link rel="alternate" type="text/html" href="https://teletype.in/@sravancynixit/3JCDEAAz6?utm_source=teletype&amp;utm_medium=feed_atom&amp;utm_campaign=sravancynixit"></link><title>The autoload Method in Ruby</title><published>2020-04-24T11:40:47.809Z</published><updated>2020-04-24T11:40:47.809Z</updated><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://teletype.in/files/21/fa/21fa0e7a-b2a7-4e92-a352-d83d402eec5a.png"></media:thumbnail><summary type="html">&lt;img src=&quot;https://teletype.in/files/11/3e/113e5268-7835-400f-8ace-5b4247065b31.png&quot;&gt;In this article we’re going to explore the following topics:</summary><content type="html">
  &lt;p&gt;In this article we’re going to explore the following topics:&lt;/p&gt;
  &lt;ul&gt;
    &lt;li&gt;&lt;code&gt;autoload&lt;/code&gt; registration &amp;amp; lazy loading&lt;/li&gt;
    &lt;li&gt;the &lt;code&gt;Module#autoload?&lt;/code&gt; method&lt;/li&gt;
    &lt;li&gt;the &lt;code&gt;Module#autoload&lt;/code&gt; method behind the scene&lt;/li&gt;
  &lt;/ul&gt;
  &lt;p&gt;If you want to Gain In-depth Knowledge on &lt;strong&gt;Ruby On Rails&lt;/strong&gt;, please go through this link &lt;strong&gt;&lt;a href=&quot;https://onlineitguru.com/ruby-on-rails-online-training-placement.html&quot; target=&quot;_blank&quot;&gt;Ruby On Rails Online Training&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;
  &lt;h1&gt;&lt;code&gt;autoload&lt;/code&gt; registration &amp;amp; lazy loading&lt;/h1&gt;
  &lt;p&gt;The &lt;code&gt;Module#autoload&lt;/code&gt; method registers a file path to be loaded the first time that a specified module or class is accessed in the namespace of the calling module or class.&lt;/p&gt;
  &lt;figure class=&quot;m_original&quot;&gt;
    &lt;img src=&quot;https://teletype.in/files/11/3e/113e5268-7835-400f-8ace-5b4247065b31.png&quot; width=&quot;638&quot; /&gt;
  &lt;/figure&gt;
  &lt;p&gt;Let’s detail a simple example to break down the previous assertion.&lt;/p&gt;
  &lt;pre&gt;module Car
  autoload(:Engine, &amp;#x27;./engine.rb&amp;#x27;)

  puts &amp;quot;The Engine module isn&amp;#x27;t yet loaded!&amp;quot;
  Engine
  puts &amp;quot;The Engine module has been successfully loaded!&amp;quot;
end&lt;/pre&gt;
  &lt;pre&gt;module Engine
  puts &amp;#x27;The Engine module is loading!&amp;#x27;
end&lt;/pre&gt;
  &lt;p&gt;now let’s run our Ruby script&lt;/p&gt;
  &lt;pre&gt;$&amp;gt; ruby car.rbThe Engine module isn’t yet loaded!The Engine module is loading!The Engine module has been successfully loaded!&lt;/pre&gt;
  &lt;p&gt;Here we see that after a call to &lt;code&gt;autoload(:Engine, ‘./engine.rb’)&lt;/code&gt; The &lt;code&gt;engine.rb&lt;/code&gt; is not yet loaded.&lt;/p&gt;
  &lt;p&gt;In effect, this file is only loaded when we explicitly call the &lt;code&gt;Engine&lt;/code&gt; module.&lt;/p&gt;
  &lt;p&gt;This mechanism allows Ruby to only load the files that contain the modules/classes used by the execution flow of the running program.&lt;/p&gt;
  &lt;h1&gt;The &lt;code&gt;Module#autoload?&lt;/code&gt; method&lt;/h1&gt;
  &lt;p&gt;The &lt;code&gt;Module#autoload?&lt;/code&gt; is in charge of checking if a registered module/class in a specific namespace has already been loaded or not.&lt;/p&gt;
  &lt;p&gt;It’s also used for checking if a module is registered (or not) as autoload in a specific namespace&lt;/p&gt;
  &lt;pre&gt;module A
  autoload(:B, &amp;#x27;./b.rb&amp;#x27;)

  p autoload?(:B)
  B
  p autoload?(:B)
end&lt;/pre&gt;
  &lt;pre&gt;module B
  puts &amp;#x27;The module B is loading!&amp;#x27;
end&lt;/pre&gt;
  &lt;p&gt;produces&lt;/p&gt;
  &lt;pre&gt;&amp;quot;./b.rb&amp;quot;The module B is loading!nil&lt;/pre&gt;
  &lt;p&gt;The first call to &lt;code&gt;autoload? :B&lt;/code&gt; returns the &lt;code&gt;&amp;quot;./b.rb&amp;quot;&lt;/code&gt; file path.&lt;/p&gt;
  &lt;p&gt;Then the &lt;code&gt;B&lt;/code&gt; module is loaded via a loading of the &lt;code&gt;b.rb&lt;/code&gt; file.&lt;/p&gt;
  &lt;p&gt;Finally, the second call to &lt;code&gt;autoload? :B&lt;/code&gt; returns &lt;code&gt;nil&lt;/code&gt; because the &lt;code&gt;B&lt;/code&gt; module is already loaded.&lt;/p&gt;
  &lt;p&gt;So, let’s &lt;code&gt;autoload&lt;/code&gt; a &lt;code&gt;C&lt;/code&gt; module outside of the the &lt;code&gt;A&lt;/code&gt; namespace&lt;/p&gt;
  &lt;pre&gt;autoload(:C, &amp;#x27;./c.rb&amp;#x27;)

module A
  p autoload? :C
end

p autoload? :C&lt;/pre&gt;
  &lt;pre&gt;module C
end&lt;/pre&gt;
  &lt;p&gt;produces&lt;/p&gt;
  &lt;pre&gt;nil&amp;quot;./c.rb&amp;quot;&lt;/pre&gt;
  &lt;p&gt;The call to &lt;code&gt;autoload? :C&lt;/code&gt; within the &lt;code&gt;A&lt;/code&gt; namespace returns &lt;code&gt;nil&lt;/code&gt; because the &lt;code&gt;:C&lt;/code&gt; module is registered as &lt;code&gt;autoload&lt;/code&gt; in the top-level namespace and not in the &lt;code&gt;A&lt;/code&gt; namespace.&lt;/p&gt;
  &lt;blockquote&gt;Take your career to new heights of success with an &lt;strong&gt;&lt;a href=&quot;https://onlineitguru.com/ruby-on-rails-online-training-placement.html&quot; target=&quot;_blank&quot;&gt;Ruby On Rails Training&lt;/a&gt;&lt;/strong&gt;&lt;/blockquote&gt;
  &lt;p&gt;In contrary, the second call to &lt;code&gt;autoload? :C&lt;/code&gt; is invoked within the top-level namespace. As it’s within the same namespace as the &lt;code&gt;autoload(:C, &amp;#x27;./c.rb&amp;#x27;)&lt;/code&gt; registration then it returns the &lt;code&gt;&amp;quot;./c.rb&amp;quot;&lt;/code&gt; file path.&lt;/p&gt;
  &lt;p&gt;Now that we are more familiar with the &lt;code&gt;autoload&lt;/code&gt; registration mechanism, let’s dive into what happens behind the scene when we register and call a module.&lt;/p&gt;
  &lt;h1&gt;The &lt;code&gt;Module#autoload&lt;/code&gt; method behind the scene&lt;/h1&gt;
  &lt;p&gt;When the &lt;code&gt;Module#autoload&lt;/code&gt; method is called within a specific namespace then the module/class and the file path given as arguments of the method are stored in an internal hash table.&lt;/p&gt;
  &lt;p&gt;Let’s have a look to this example&lt;/p&gt;
  &lt;pre&gt;module A
  autoload(:B, &amp;#x27;./b.rb&amp;#x27;)
  
  p constants
end&lt;/pre&gt;
  &lt;pre&gt;module B
end&lt;/pre&gt;
  &lt;p&gt;produces&lt;/p&gt;
  &lt;pre&gt;[:B]&lt;/pre&gt;
  &lt;p&gt;Here, we can see that the &lt;code&gt;B&lt;/code&gt; constant exists even if it hasn’t been loaded yet.&lt;/p&gt;
  &lt;p&gt;In effect, a call to &lt;code&gt;autoload&lt;/code&gt; will automatically create a constant named as the first argument of the method and flagged as &lt;code&gt;autoload&lt;/code&gt; registered. The value of this constant will be undefined and NOT &lt;code&gt;nil&lt;/code&gt;.&lt;/p&gt;
  &lt;p&gt;When the &lt;code&gt;B&lt;/code&gt; module will be invoked then Ruby will search for the &lt;code&gt;B&lt;/code&gt; entry within the &lt;strong&gt;constants&lt;/strong&gt; hash table of the &lt;code&gt;A&lt;/code&gt; namespace.&lt;/p&gt;
  &lt;p&gt;It’ll then load the file using the &lt;code&gt;Kernel#require&lt;/code&gt; method&lt;/p&gt;
  &lt;p&gt;Finally the constant hash table will unflag as &lt;code&gt;autoload&lt;/code&gt; the &lt;code&gt;B&lt;/code&gt; module.&lt;/p&gt;
  &lt;figure class=&quot;m_retina&quot;&gt;
    &lt;img src=&quot;https://teletype.in/files/9f/54/9f54c54d-292e-4506-ac1e-b781925dcd4a.png&quot; width=&quot;700&quot; /&gt;
  &lt;/figure&gt;

</content></entry><entry><id>sravancynixit:lH2GH0FI2</id><link rel="alternate" type="text/html" href="https://teletype.in/@sravancynixit/lH2GH0FI2?utm_source=teletype&amp;utm_medium=feed_atom&amp;utm_campaign=sravancynixit"></link><title>Deploying Spring Boot Applications</title><published>2020-04-23T11:42:18.041Z</published><updated>2020-04-23T11:42:18.041Z</updated><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://teletype.in/files/cc/d2/ccd2a20f-1a2d-4a6b-8ff8-b74af0490c23.png"></media:thumbnail><summary type="html">&lt;img src=&quot;https://teletype.in/files/c5/df/c5df1fb6-feab-4116-9b86-39f525af6d29.png&quot;&gt;Spring Boot applications can be deployed into production systems with various methods. In this article, we will go through step by step deployment of Spring Boot applications via the following 5 methods:</summary><content type="html">
  &lt;p&gt;Spring Boot applications can be deployed into production systems with various methods. In this article, we will go through step by step deployment of Spring Boot applications via the following 5 methods:&lt;/p&gt;
  &lt;p&gt;If you want to Gain In-depth Knowledge on Spring Boot, please go through this link &lt;strong&gt;&lt;a href=&quot;https://onlineitguru.com/spring-boot-training.html&quot; target=&quot;_blank&quot;&gt;Spring Boot Online Training&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;
  &lt;ul&gt;
    &lt;li&gt;Deploying in Java Archive (JAR) as a standalone application,&lt;/li&gt;
    &lt;li&gt;Deploying as Web Application Archive (WAR) into a servlet container,&lt;/li&gt;
    &lt;li&gt;Deploying in Docker Container,&lt;/li&gt;
    &lt;li&gt;Deploying behind NGINX web server — direct setup,&lt;/li&gt;
    &lt;li&gt;Deploying behind NGINX web server — containerized setup.&lt;/li&gt;
  &lt;/ul&gt;
  &lt;figure class=&quot;m_retina&quot;&gt;
    &lt;img src=&quot;https://teletype.in/files/c5/df/c5df1fb6-feab-4116-9b86-39f525af6d29.png&quot; width=&quot;600&quot; /&gt;
  &lt;/figure&gt;
  &lt;h2&gt;Deploying in Java Archive (JAR) as a standalone application&lt;/h2&gt;
  &lt;p&gt;Spring Boot applications can easily be packaged into JAR files and deployed as standalone applications. This is done by the &lt;em&gt;spring-boot-maven-plugin&lt;/em&gt;. The plugin is automatically added to pom.xml once the Spring project is created via Spring Initializr as a Maven project.&lt;/p&gt;
  &lt;pre&gt;&amp;lt;build&amp;gt;  &amp;lt;plugins&amp;gt;    &amp;lt;plugin&amp;gt;      &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;      &amp;lt;artifactId&amp;gt;spring-boot-maven-plugin&amp;lt;/artifactId&amp;gt;    &amp;lt;/plugin&amp;gt;  &amp;lt;/plugins&amp;gt;&amp;lt;/build&amp;gt;&lt;/pre&gt;
  &lt;p&gt;In order to package the application in a single (fat) jar file, run the maven command &lt;code&gt;mvn package&lt;/code&gt; under project directory. This will package the application inside an executable jar file with all its dependencies (including the embedded servlet container — if its a web application). To run the jar file, use the following standard JVM command &lt;code&gt;java -jar &amp;lt;jar-file-name&amp;gt;.jar&lt;/code&gt;.&lt;/p&gt;
  &lt;h2&gt;Deploying as Web Application Archive (WAR) into a servlet container&lt;/h2&gt;
  &lt;p&gt;Spring Boot applications can be packaged into WAR files to be deployed into existing servlet containers (such as Tomcat, Jetty etc.). This can be done as follows:&lt;/p&gt;
  &lt;p&gt;Specify WAR packaging in pom.xml file via &lt;code&gt;&amp;lt;packaging&amp;gt;war&amp;lt;/packaging&amp;gt;&lt;/code&gt;. This will package the application into a WAR file (instead of JAR). On the second step, set the scope of Tomcat (servlet container) dependency to provided (so that it is not deployed into WAR file):&lt;/p&gt;
  &lt;pre&gt;&amp;lt;dependency&amp;gt;  &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;  &amp;lt;artifactId&amp;gt;spring-boot-starter-tomcat&amp;lt;/artifactId  &amp;lt;scope&amp;gt;provided&amp;lt;/scope&amp;gt;&amp;lt;/dependency&amp;gt;&lt;/pre&gt;
  &lt;p&gt;Initialise the Servlet context required by Tomcat by extending &lt;em&gt;SpringBootServletInitializer&lt;/em&gt; and overriding &lt;em&gt;configure&lt;/em&gt; method as follows:&lt;/p&gt;
  &lt;pre&gt;@SpringBootApplicationpublic class DemoApp extends SpringBootServletInitializer {  @Override  protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {    return builder.sources(DemoApp.class);  }  public static void main(String[] args) {    SpringApplication.run(DemoApp.class, args);  }}&lt;/pre&gt;
  &lt;p&gt;In order to package the application in a war file, run the standard maven command &lt;code&gt;mvn clean package&lt;/code&gt; under project directory. This will generate the WAR package which can be deployed into a servlet container. To run the application inside an existing Tomcat container, copy the generated WAR file to &lt;code&gt;tomcat/webapps/&lt;/code&gt; directory.&lt;/p&gt;
  &lt;h2&gt;Deploying in Docker Container&lt;/h2&gt;
  &lt;p&gt;Before deploying the application into a Docker container, we will first package the application in a (fat) JAR file. This process is previously explained, therefore I will assume we have a jar file.&lt;/p&gt;
  &lt;p&gt;On the first step, we need to build a container image. For this, we start with creating a &lt;em&gt;Dockerfile&lt;/em&gt; in the project root directory as follows:&lt;/p&gt;
  &lt;pre&gt;# latest oracle openjdk is the basisFROM openjdk:oracle# copy jar file into container image under app directoryCOPY target/demoApp.jar app/demoApp.jar# expose server port accept connectionsEXPOSE 8080# start applicationCMD [&amp;quot;java&amp;quot;, &amp;quot;-jar&amp;quot;, &amp;quot;app/demoApp.jar&amp;quot;]&lt;/pre&gt;
  &lt;p&gt;Note that, in the above snippet, we assumed that the application JAR file ‘&lt;em&gt;demoApp.jar’&lt;/em&gt; is located under the target directory of our project. We also assumed that the embedded servlet port is 8080 (which is the default case for Tomcat).&lt;/p&gt;
  &lt;p&gt;Take your career to new heights of success with an &lt;strong&gt;&lt;a href=&quot;https://onlineitguru.com/spring-boot-training.html&quot; target=&quot;_blank&quot;&gt;Spring Boot Online Course&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;
  &lt;p&gt;We can now build the Docker image with the following command (from where the Dockerfile is located):&lt;/p&gt;
  &lt;pre&gt;docker image build -t demo-app:latest .&lt;/pre&gt;
  &lt;p&gt;where &lt;code&gt;-t&lt;/code&gt; is the name and tag of the image to be built. Once the image is built, we can create and run the container via:&lt;/p&gt;
  &lt;pre&gt;docker container run -p 8080:8080 -d --name app-container demo-app&lt;/pre&gt;
  &lt;p&gt;where &lt;code&gt;-p&lt;/code&gt; publishes (maps) host port to container port (in this case both are 8080). The option &lt;code&gt;-d&lt;/code&gt; (detach) runs the container in background, and &lt;code&gt;--name&lt;/code&gt; specifies the name of the container.&lt;/p&gt;
  &lt;h2&gt;Deploying behind NGINX web server — direct setup&lt;/h2&gt;
  &lt;p&gt;Configuring servlet containers (such as Tomcat or Jetty) for real production (i.e. running on port 80, without root user and with SSL) may not be straight forward (but doable). Therefore, it is recommended to use a web server (such as Nginx) in front of your Spring Boot applications. This can be done in two ways; direct setup or containerized setup. In this section, we will demonstrate the direct setup.&lt;/p&gt;
  &lt;p&gt;In direct setup, we run the Nginx web server and the Spring Boot applications directly on localhost (on different ports of course). And we let Ngnix proxy REST requests to Spring Boot applications. For this:&lt;/p&gt;
  &lt;ol&gt;
    &lt;li&gt;Install Nginx web server on Linux via &lt;code&gt;sudo apt-get install nginx&lt;/code&gt;,&lt;/li&gt;
    &lt;li&gt;Open the file &lt;code&gt;/etc/ngnix/sites-available/default&lt;/code&gt; with a text editor,&lt;/li&gt;
    &lt;li&gt;Say, we have two Spring Boot applications to be proxied. Then replace the &lt;em&gt;‘location’&lt;/em&gt; block in the file with following blocks for two Spring Boot applications. Note that, all Nginx-Java configs can be found here.&lt;/li&gt;
  &lt;/ol&gt;
  &lt;pre&gt;location /app1 {  proxy_pass http://localhost:8080;}location /app2 {  proxy_pass http://localhost:9000;}&lt;/pre&gt;
  &lt;p&gt;based on which the requests coming to &lt;code&gt;http://localhost/app1/&lt;/code&gt; will be directed to &lt;code&gt;/http://localhost:8080/&lt;/code&gt;, and requests coming to &lt;code&gt;http://localhost/app2/&lt;/code&gt; will be directed to &lt;code&gt;/http://localhost:9000/&lt;/code&gt;.&lt;/p&gt;
  &lt;h2&gt;Load balancing&lt;/h2&gt;
  &lt;p&gt;If you are running multiple instances of a Spring Boot application, you can enable Nginx to apply &lt;strong&gt;load-balancing&lt;/strong&gt;. For example, if we have 3 instances of app1 running on ports 8080, 8081 and 8082. We can load-balance among these servers as follows:&lt;/p&gt;
  &lt;p&gt;Open the file &lt;code&gt;/etc/ngnix/sites-available/default&lt;/code&gt; and add the following block at the top of the file (before server block):&lt;/p&gt;
  &lt;pre&gt;# configure load-balancingupstream backend {  server localhost:8080;  server localhost:8081;  server localhost:8082;}&lt;/pre&gt;
  &lt;p&gt;Modify the &lt;em&gt;proxy_pass&lt;/em&gt; parameter of app1 as follows:&lt;/p&gt;
  &lt;pre&gt;location /app1 {  proxy_pass http://backend;}&lt;/pre&gt;
  &lt;p&gt;based on which the requests coming to &lt;code&gt;http://localhost/app1/&lt;/code&gt; will be directed to one of&lt;code&gt;/http://localhost:8080/&lt;/code&gt;, &lt;code&gt;/http://localhost:8081/&lt;/code&gt; or &lt;code&gt;/http://localhost:8082/&lt;/code&gt;.&lt;/p&gt;
  &lt;h2&gt;Deploying behind NGINX web server — containerized setup&lt;/h2&gt;
  &lt;p&gt;In containerized setup, we deploy the Nginx web server and all the Spring Boot applications on separate Docker containers. And we let Nginx (running in its own container) proxy REST requests to Spring Boot application containers.&lt;/p&gt;
  &lt;p&gt;We start by packaging all Spring Boot applications in (fat) jar files (which is previously explained). At this point, pay attention to setting individual server ports and root context paths to each Spring Boot application by adding following lines to &lt;em&gt;application.properties&lt;/em&gt; (or &lt;em&gt;application.yml&lt;/em&gt;) files:&lt;/p&gt;
  &lt;pre&gt;server.port=8082server.servlet.context-path=/search-service&lt;/pre&gt;
  &lt;p&gt;Then we deploy the generated jar packages in separate Docker containers (which is also previously explained).&lt;/p&gt;
  &lt;p&gt;As an example, we deploy four Spring Boot applications; single instance of ‘analysis-service’ application and three instances of ‘search-service’ application. The three instances of search-service application will be load-balanced by Nginx. Our basic architecture looks like follows:&lt;/p&gt;
  &lt;figure class=&quot;m_retina&quot;&gt;
    &lt;img src=&quot;https://teletype.in/files/06/a4/06a4f520-bc0f-495d-8193-e3f8ed6d6fb2.png&quot; width=&quot;700&quot; /&gt;
  &lt;/figure&gt;
  &lt;p&gt;We create a Nginx configuration file &lt;strong&gt;nginx.conf&lt;/strong&gt; based on the default configurations. We add load-balancing and proxy information for each service as follows:&lt;/p&gt;
  &lt;pre&gt;http {  upstream backend {    server search-service-1:8080;    server search-service-2:8081;    server search-service-3:8082;  }  server {    listen 80 default_server;    listen [::]:80 default_server;    root /var/www/html;    server_name _;    location /search-service {      proxy_pass http://backend/search-service;    }    location /analysis-service {      proxy_pass http://analysis-service:8083/analysis-service;    }  }}events { worker_connections 1024; }&lt;/pre&gt;
  &lt;p&gt;based on which the requests coming to &lt;code&gt;http://localhost/search-service/&lt;/code&gt; will be directed to one of&lt;code&gt;/http://search-service-1:8080/search-service/&lt;/code&gt;, &lt;code&gt;/http://search-service-2:8081/search-service/&lt;/code&gt; and &lt;code&gt;/http://search-service-3:8082/search-service/&lt;/code&gt;, and requests coming to &lt;code&gt;http://localhost/analysis-service/&lt;/code&gt; will be directed to &lt;code&gt;/http://analysis-service:8083/analysis-service/&lt;/code&gt;.&lt;/p&gt;
  &lt;p&gt;After the configuration file (nginx.conf) is created, we will deploy the Nginx web server in a Docker container. For this, we create a &lt;em&gt;Dockerfile&lt;/em&gt; as follows:&lt;/p&gt;
  &lt;pre&gt;# latest nginxFROM nginx# copy custom configuration fileCOPY nginx.conf /etc/nginx/nginx.conf# expose server portEXPOSE 80# start serverCMD [&amp;quot;nginx&amp;quot;, &amp;quot;-g&amp;quot;, &amp;quot;daemon off;&amp;quot;]&lt;/pre&gt;
  &lt;p&gt;And we build a Docker image for Nginx web server as follows:&lt;/p&gt;
  &lt;pre&gt;docker image build -t custom-nginx:latest .&lt;/pre&gt;
  &lt;p&gt;Once all Docker images are built, all system can be deployed by running &lt;code&gt;docker-compose up&lt;/code&gt; command on the following &lt;em&gt;docker-compose.yml&lt;/em&gt; file:&lt;/p&gt;
  &lt;pre&gt;version: &amp;#x27;3.7&amp;#x27;services:  nginx_server:    image: custom-nginx    ports:      - &amp;#x27;80:80&amp;#x27;    networks:      - demo-network    depends_on:      - &amp;quot;search-service-1&amp;quot;      - &amp;quot;search-service-2&amp;quot;      - &amp;quot;search-service-3&amp;quot;      - &amp;quot;analysis-service&amp;quot;search-service-1:  image: search-service-1  ports:    - &amp;#x27;8080:8080&amp;#x27;  networks:    - demo-networksearch-service-2:  image: search-service-2  ports:    - &amp;#x27;8081:8081&amp;#x27;  networks:    - demo-networksearch-service-3:  image: search-service-3  ports:    - &amp;#x27;8082:8082&amp;#x27;  networks:    - demo-networkanalysis-service:  image: analysis-service  ports:    - &amp;#x27;8083:8083&amp;#x27;  networks:    - demo-networknetworks:  demo-network:    name: demo-network&lt;/pre&gt;

</content></entry><entry><id>sravancynixit:xbXdZeTZC</id><link rel="alternate" type="text/html" href="https://teletype.in/@sravancynixit/xbXdZeTZC?utm_source=teletype&amp;utm_medium=feed_atom&amp;utm_campaign=sravancynixit"></link><title>Deploying a full-stack Spring boot, Mysql, and React app on Kubernetes with Persistent Volumes and Secrets</title><published>2020-04-21T11:06:51.982Z</published><updated>2020-04-21T11:06:51.982Z</updated><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://teletype.in/files/d1/26/d1267c8d-bb02-448a-acf7-163cdb755a8e.png"></media:thumbnail><summary type="html">&lt;img src=&quot;https://teletype.in/files/01/10/0110e9a0-ec82-4408-9feb-27f298e85489.png&quot;&gt;In this article, you’ll learn how to deploy a Stateful app built with Spring Boot, Mysql, and React on Kubernetes. We’ll use a local minikube cluster to deploy the application. Please make sure that you have kubectl and minikube installed in your system.</summary><content type="html">
  &lt;h2&gt;Introduction&lt;/h2&gt;
  &lt;p&gt;In this article, you’ll learn how to deploy a Stateful app built with Spring Boot, Mysql, and React on Kubernetes. We’ll use a local minikube cluster to deploy the application. Please make sure that you have kubectl and minikube installed in your system.&lt;/p&gt;
  &lt;p&gt;If you want to Gain In-depth Knowledge on &lt;strong&gt;Full Stack Spring Boot&lt;/strong&gt;, please go through this link &lt;strong&gt;&lt;a href=&quot;https://onlineitguru.com/spring-boot-training.html&quot; target=&quot;_blank&quot;&gt;Spring Boot Online Training&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;
  &lt;p&gt;If you’re new to Kubernetes, I recommend reading the following hands-on guides before reading this one-&lt;/p&gt;
  &lt;ul&gt;
    &lt;li&gt;Deploying a containerized Go app on Kubernetes&lt;/li&gt;
    &lt;li&gt;Deploying a multi-container Go app with Redis on Kubernetes&lt;/li&gt;
  &lt;/ul&gt;
  &lt;figure class=&quot;m_original&quot;&gt;
    &lt;img src=&quot;https://teletype.in/files/01/10/0110e9a0-ec82-4408-9feb-27f298e85489.png&quot; /&gt;
  &lt;/figure&gt;
  &lt;p&gt;The sample application that we’ll deploy on Kubernetes in this article can be downloaded from Github:&lt;/p&gt;
  &lt;ul&gt;
    &lt;li&gt;Spring Boot, Mysql, React, Ant design Polling App&lt;/li&gt;
  &lt;/ul&gt;
  &lt;p&gt;It is a full-stack Polling app where users can login, create a Poll, and vote for a Poll.&lt;/p&gt;
  &lt;p&gt;To deploy this application, we’ll use few additional concepts in Kubernetes called PersistentVolumes and Secrets. Let’s first get a basic understanding of these concepts before moving to the hands-on deployment guide. Let&amp;#x27;s See How the Kubernetes helps to &lt;strong&gt;&lt;a href=&quot;https://onlineitguru.com/spring-boot-training.html&quot; target=&quot;_blank&quot;&gt;Spring Boot Training&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;
  &lt;h3&gt;Kubernetes Persistent Volume&lt;/h3&gt;
  &lt;p&gt;We’ll use Kubernetes &lt;strong&gt;Persistent Volumes&lt;/strong&gt; to deploy Mysql. A PersistentVolume (&lt;code&gt;PV&lt;/code&gt;) is a piece of storage in the cluster. It is a resource in the cluster just like a node. The Persistent volume’s lifecycle is independent from Pod lifecycles. It preserves data through restarting, rescheduling, and even deleting Pods.&lt;/p&gt;
  &lt;p&gt;PersistentVolumes are consumed by something called a &lt;strong&gt;PersistentVolumeClaim&lt;/strong&gt; (&lt;code&gt;PVC&lt;/code&gt;). A PVC is a request for storage by a user. It is similar to a Pod. Pods consume node resources and PVCs consume PV resources. Pods can request specific levels of resources (CPU and Memory). PVCs can request specific size and access modes (e.g. read-write or read-only).&lt;/p&gt;
  &lt;h3&gt;Kubernetes Secrets&lt;/h3&gt;
  &lt;p&gt;We’ll make use of Kubernetes secrets to store the Database credentials. A Secret is an object in Kubernetes that lets you store and manage sensitive information, such as passwords, tokens, ssh keys etc. The secrets are stored in Kubernetes backing store, etcd. You can enable encryption to store secrets in encrypted form in etcd.&lt;/p&gt;
  &lt;h2&gt;Deploying Mysql on Kubernetes using PersistentVolume and Secrets&lt;/h2&gt;
  &lt;p&gt;Following is the Kubernetes manifest for MySQL deployment. I’ve added comments alongside each configuration to make sure that its usage is clear to you.&lt;/p&gt;
  &lt;pre&gt;apiVersion: v1
kind: PersistentVolume            # Create a PersistentVolume
metadata:
  name: mysql-pv
  labels:
    type: local
spec:
  storageClassName: standard      # Storage class. A PV Claim requesting the same storageClass can be bound to this volume. 
  capacity:
    storage: 250Mi
  accessModes:
    - ReadWriteOnce
  hostPath:                       # hostPath PersistentVolume is used for development and testing. It uses a file/directory on the Node to emulate network-attached storage
    path: &amp;quot;/mnt/data&amp;quot;
  persistentVolumeReclaimPolicy: Retain  # Retain the PersistentVolume even after PersistentVolumeClaim is deleted. The volume is considered “released”. But it is not yet available for another claim because the previous claimant’s data remains on the volume. 
---    
apiVersion: v1
kind: PersistentVolumeClaim        # Create a PersistentVolumeClaim to request a PersistentVolume storage
metadata:                          # Claim name and labels
  name: mysql-pv-claim
  labels:
    app: polling-app
spec:                              # Access mode and resource limits
  storageClassName: standard       # Request a certain storage class
  accessModes:
    - ReadWriteOnce                # ReadWriteOnce means the volume can be mounted as read-write by a single Node
  resources:
    requests:
      storage: 250Mi
---
apiVersion: v1                    # API version
kind: Service                     # Type of kubernetes resource 
metadata:
  name: polling-app-mysql         # Name of the resource
  labels:                         # Labels that will be applied to the resource
    app: polling-app
spec:
  ports:
    - port: 3306
  selector:                       # Selects any Pod with labels &amp;#x60;app=polling-app,tier=mysql&amp;#x60;
    app: polling-app
    tier: mysql
  clusterIP: None
---
apiVersion: apps/v1
kind: Deployment                    # Type of the kubernetes resource
metadata:
  name: polling-app-mysql           # Name of the deployment
  labels:                           # Labels applied to this deployment 
    app: polling-app
spec:
  selector:
    matchLabels:                    # This deployment applies to the Pods matching the specified labels
      app: polling-app
      tier: mysql
  strategy:
    type: Recreate
  template:                         # Template for the Pods in this deployment
    metadata:
      labels:                       # Labels to be applied to the Pods in this deployment
        app: polling-app
        tier: mysql
    spec:                           # The spec for the containers that will be run inside the Pods in this deployment
      containers:
      - image: mysql:5.6            # The container image
        name: mysql
        env:                        # Environment variables passed to the container 
        - name: MYSQL_ROOT_PASSWORD 
          valueFrom:                # Read environment variables from kubernetes secrets
            secretKeyRef:
              name: mysql-root-pass
              key: password
        - name: MYSQL_DATABASE
          valueFrom:
            secretKeyRef:
              name: mysql-db-url
              key: database
        - name: MYSQL_USER
          valueFrom:
            secretKeyRef:
              name: mysql-user-pass
              key: username
        - name: MYSQL_PASSWORD
          valueFrom:
            secretKeyRef:
              name: mysql-user-pass
              key: password
        ports:
        - containerPort: 3306        # The port that the container exposes       
          name: mysql
        volumeMounts:
        - name: mysql-persistent-storage  # This name should match the name specified in &amp;#x60;volumes.name&amp;#x60;
          mountPath: /var/lib/mysql
      volumes:                       # A PersistentVolume is mounted as a volume to the Pod  
      - name: mysql-persistent-storage
        persistentVolumeClaim:
          claimName: mysql-pv-claim&lt;/pre&gt;
  &lt;p&gt;We’re creating four resources in the above manifest file. A PersistentVolume, a PersistentVolumeClaim for requesting access to the PersistentVolume resource, a service for having a static endpoint for the MySQL database, and a deployment for running and managing the MySQL pod.&lt;/p&gt;
  &lt;p&gt;The MySQL container reads database credentials from environment variables. The environment variables access these credentials from Kubernetes secrets.&lt;/p&gt;
  &lt;p&gt;Let’s start a minikube cluster, create kubernetes secrets to store database credentials, and deploy the Mysql instance:&lt;/p&gt;
  &lt;h4&gt;Starting a Minikube cluster&lt;/h4&gt;
  &lt;pre&gt;$ minikube start
&lt;/pre&gt;
  &lt;h4&gt;Creating the secrets&lt;/h4&gt;
  &lt;p&gt;You can create secrets manually from a literal or file using the &lt;code&gt;kubectl create secret&lt;/code&gt; command, or you can create them from a generator using Kustomize.&lt;/p&gt;
  &lt;p&gt;In this article, we’re gonna create the secrets manually:&lt;/p&gt;
  &lt;pre&gt;$ kubectl create secret generic mysql-root-pass --from-literal=password=R00t
secret/mysql-root-pass created

$ kubectl create secret generic mysql-user-pass --from-literal=username=callicoder --from-literal=password=c@ll1c0d3r
secret/mysql-user-pass created

$ kubectl create secret generic mysql-db-url --from-literal=database=polls --from-literal=url=&amp;#x27;jdbc:mysql://polling-app-mysql:3306/polls?useSSL=false&amp;amp;serverTimezone=UTC&amp;amp;useLegacyDatetimeCode=false&amp;#x27;
secret/mysql-db-url created
&lt;/pre&gt;
  &lt;p&gt;You can get the secrets like this -&lt;/p&gt;
  &lt;pre&gt;$ kubectl get secrets
NAME                         TYPE                                  DATA   AGE
default-token-tkrx5          kubernetes.io/service-account-token   3      3d23h
mysql-db-url                 Opaque                                2      2m32s
mysql-root-pass              Opaque                                1      3m19s
mysql-user-pass              Opaque                                2      3m6s
&lt;/pre&gt;
  &lt;p&gt;You can also find more details about a secret like so -&lt;/p&gt;
  &lt;pre&gt;$ kubectl describe secrets mysql-user-pass
Name:         mysql-user-pass
Namespace:    default
Labels:       &amp;lt;none&amp;gt;
Annotations:  &amp;lt;none&amp;gt;

Type:  Opaque

Data
====
username:  10 bytes
password:  10 bytes&lt;/pre&gt;
  &lt;h4&gt;Deploying MySQL&lt;/h4&gt;
  &lt;p&gt;Let’s now deploy MySQL by applying the yaml configuration -&lt;/p&gt;
  &lt;pre&gt;$ kubectl apply -f deployments/mysql-deployment.yaml
service/polling-app-mysql created
persistentvolumeclaim/mysql-pv-claim created
deployment.apps/polling-app-mysql created
&lt;/pre&gt;
  &lt;p&gt;That’s it! You can check all the resources created in the cluster using the following commands -&lt;/p&gt;
  &lt;pre&gt;$ kubectl get persistentvolumes
NAME       CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS   CLAIM                    STORAGECLASS   REASON   AGE
mysql-pv   250Mi      RWO            Retain           Bound    default/mysql-pv-claim   standard                30s
&lt;/pre&gt;
  &lt;pre&gt;$ kubectl get persistentvolumeclaims
NAME             STATUS   VOLUME     CAPACITY   ACCESS MODES   STORAGECLASS   AGE
mysql-pv-claim   Bound    mysql-pv   250Mi      RWO            standard       50s
&lt;/pre&gt;
  &lt;pre&gt;$ kubectl get services
NAME                TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)    AGE
kubernetes          ClusterIP   10.96.0.1    &amp;lt;none&amp;gt;        443/TCP    5m36s
polling-app-mysql   ClusterIP   None         &amp;lt;none&amp;gt;        3306/TCP   2m57s
&lt;/pre&gt;
  &lt;pre&gt;$ kubectl get deployments
NAME                READY   UP-TO-DATE   AVAILABLE   AGE
polling-app-mysql   1/1     1            1           3m14s
&lt;/pre&gt;
  &lt;h4&gt;Logging into the MySQL pod&lt;/h4&gt;
  &lt;p&gt;You can get the MySQL pod and use &lt;code&gt;kubectl exec&lt;/code&gt; command to login to the Pod.&lt;/p&gt;
  &lt;pre&gt;$ kubectl get pods
NAME                                 READY   STATUS    RESTARTS   AGE
polling-app-mysql-6b94bc9d9f-td6l4   1/1     Running   0          4m23s

$ kubectl exec -it polling-app-mysql-6b94bc9d9f-td6l4 -- /bin/bash
root@polling-app-mysql-6b94bc9d9f-td6l4:/#
&lt;/pre&gt;
  &lt;h2&gt;Deploying the Spring Boot app on Kubernetes&lt;/h2&gt;
  &lt;p&gt;All right! Now that we have the MySQL instance deployed, Let’s proceed with the deployment of the Spring Boot app at &lt;strong&gt;&lt;a href=&quot;https://onlineitguru.com/spring-boot-training.html&quot; target=&quot;_blank&quot;&gt;Spring Boot Online Course&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;
  &lt;p&gt;Following is the deployment manifest for the Spring Boot app -&lt;/p&gt;
  &lt;pre&gt;---
apiVersion: apps/v1           # API version
kind: Deployment              # Type of kubernetes resource
metadata:
  name: polling-app-server    # Name of the kubernetes resource
  labels:                     # Labels that will be applied to this resource
    app: polling-app-server
spec:
  replicas: 1                 # No. of replicas/pods to run in this deployment
  selector:
    matchLabels:              # The deployment applies to any pods mayching the specified labels
      app: polling-app-server
  template:                   # Template for creating the pods in this deployment
    metadata:
      labels:                 # Labels that will be applied to each Pod in this deployment
        app: polling-app-server
    spec:                     # Spec for the containers that will be run in the Pods
      containers:
      - name: polling-app-server
        image: callicoder/polling-app-server:1.0.0
        imagePullPolicy: IfNotPresent
        ports:
          - name: http
            containerPort: 8080 # The port that the container exposes
        resources:
          limits:
            cpu: 0.2
            memory: &amp;quot;200Mi&amp;quot;
        env:                  # Environment variables supplied to the Pod
        - name: SPRING_DATASOURCE_USERNAME # Name of the environment variable
          valueFrom:          # Get the value of environment variable from kubernetes secrets
            secretKeyRef:
              name: mysql-user-pass
              key: username
        - name: SPRING_DATASOURCE_PASSWORD
          valueFrom:
            secretKeyRef:
              name: mysql-user-pass
              key: password
        - name: SPRING_DATASOURCE_URL
          valueFrom:
            secretKeyRef:
              name: mysql-db-url
              key: url
---
apiVersion: v1                # API version
kind: Service                 # Type of the kubernetes resource
metadata:                     
  name: polling-app-server    # Name of the kubernetes resource
  labels:                     # Labels that will be applied to this resource
    app: polling-app-server
spec:                         
  type: NodePort              # The service will be exposed by opening a Port on each node and proxying it. 
  selector:
    app: polling-app-server   # The service exposes Pods with label &amp;#x60;app=polling-app-server&amp;#x60;
  ports:                      # Forward incoming connections on port 8080 to the target port 8080
  - name: http
    port: 8080
    targetPort: 8080
&lt;/pre&gt;
  &lt;p&gt;The above deployment uses the Secrets stored in &lt;code&gt;mysql-user-pass&lt;/code&gt; and &lt;code&gt;mysql-db-url&lt;/code&gt; that we created in the previous section.&lt;/p&gt;
  &lt;p&gt;Let’s apply the manifest file to create the resources -&lt;/p&gt;
  &lt;pre&gt;$ kubectl apply -f deployments/polling-app-server.yaml
deployment.apps/polling-app-server created
service/polling-app-server created
&lt;/pre&gt;
  &lt;p&gt;You can check the created Pods like this -&lt;/p&gt;
  &lt;pre&gt;$ kubectl get pods
NAME                                  READY   STATUS    RESTARTS   AGE
polling-app-mysql-6b94bc9d9f-td6l4    1/1     Running   0          21m
polling-app-server-744b47f866-s2bpf   1/1     Running   0          31s
&lt;/pre&gt;
  &lt;p&gt;Now, type the following command to get the polling-app-server service URL -&lt;/p&gt;
  &lt;pre&gt;$ minikube service polling-app-server --url
http://192.168.99.100:31550
&lt;/pre&gt;
  &lt;p&gt;You can now use the above endpoint to interact with the service -&lt;/p&gt;
  &lt;pre&gt;$ curl http://192.168.99.100:31550
{&amp;quot;timestamp&amp;quot;:&amp;quot;2019-07-30T17:55:11.366+0000&amp;quot;,&amp;quot;status&amp;quot;:404,&amp;quot;error&amp;quot;:&amp;quot;Not Found&amp;quot;,&amp;quot;message&amp;quot;:&amp;quot;No message available&amp;quot;,&amp;quot;path&amp;quot;:&amp;quot;/&amp;quot;}
&lt;/pre&gt;
  &lt;h2&gt;Deploying the React app on Kubernetes&lt;/h2&gt;
  &lt;p&gt;Finally, Let’s deploy the frontend app using Kubernetes. Here is the deployment manifest -&lt;/p&gt;
  &lt;pre&gt;apiVersion: apps/v1             # API version
kind: Deployment                # Type of kubernetes resource
metadata:
  name: polling-app-client      # Name of the kubernetes resource
spec:
  replicas: 1                   # No of replicas/pods to run
  selector:                     
    matchLabels:                # This deployment applies to Pods matching the specified labels
      app: polling-app-client
  template:                     # Template for creating the Pods in this deployment
    metadata:
      labels:                   # Labels that will be applied to all the Pods in this deployment
        app: polling-app-client
    spec:                       # Spec for the containers that will run inside the Pods
      containers:
      - name: polling-app-client
        image: callicoder/polling-app-client:1.0.0
        imagePullPolicy: IfNotPresent
        ports:
          - name: http
            containerPort: 80   # Should match the Port that the container listens on
        resources:
          limits:
            cpu: 0.2
            memory: &amp;quot;10Mi&amp;quot;
---
apiVersion: v1                  # API version
kind: Service                   # Type of kubernetes resource
metadata:
  name: polling-app-client      # Name of the kubernetes resource
spec:
  type: NodePort                # Exposes the service by opening a port on each node
  selector:
    app: polling-app-client     # Any Pod matching the label &amp;#x60;app=polling-app-client&amp;#x60; will be picked up by this service
  ports:                        # Forward incoming connections on port 80 to the target port 80 in the Pod
  - name: http
    port: 80
    targetPort: 80
&lt;/pre&gt;
  &lt;p&gt;Let’s apply the above manifest file to deploy the frontend app -&lt;/p&gt;
  &lt;pre&gt;$ kubectl apply -f deployments/polling-app-client.yaml
deployment.apps/polling-app-client created
service/polling-app-client created
&lt;/pre&gt;
  &lt;p&gt;Let’s check all the Pods in the cluster -&lt;/p&gt;
  &lt;pre&gt;$ kubectl get pods
NAME                                  READY   STATUS    RESTARTS   AGE
polling-app-client-6b6d979b-7pgxq     1/1     Running   0          26m
polling-app-mysql-6b94bc9d9f-td6l4    1/1     Running   0          21m
polling-app-server-744b47f866-s2bpf   1/1     Running   0          31s
&lt;/pre&gt;
  &lt;p&gt;Type the following command to open the frontend service in the default browser -&lt;/p&gt;
  &lt;pre&gt;$ minikube service polling-app-client
&lt;/pre&gt;
  &lt;p&gt;You’ll notice that the backend api calls from the frontend app is failing because the frontend app tries to access the backend APIs at &lt;code&gt;localhost:8080&lt;/code&gt;. Ideally, in a real-world, you’ll have a public domain for your backend server. But since our entire setup is locally installed, we can use &lt;code&gt;kubectl port-forward&lt;/code&gt; command to map the &lt;code&gt;localhost:8080&lt;/code&gt; endpoint to the backend service -&lt;/p&gt;
  &lt;pre&gt;$ kubectl port-forward service/polling-app-server 8080:8080
&lt;/pre&gt;
  &lt;p&gt;That’s it! Now, you’ll be able to use the frontend app. Here is how the app looks like -&lt;/p&gt;
  &lt;figure class=&quot;m_original&quot;&gt;
    &lt;img src=&quot;https://www.callicoder.com/assets/images/post/large/kubernetes-persistent-volume-secrets-full-stack-deployment-example.jpg&quot; width=&quot;1000&quot; /&gt;
  &lt;/figure&gt;

</content></entry><entry><id>sravancynixit:jmtHSExwb</id><link rel="alternate" type="text/html" href="https://teletype.in/@sravancynixit/jmtHSExwb?utm_source=teletype&amp;utm_medium=feed_atom&amp;utm_campaign=sravancynixit"></link><title>10 Useful Tips For Ruby On Rails Developers</title><published>2020-04-20T13:59:15.671Z</published><updated>2020-04-20T13:59:15.671Z</updated><summary type="html">&lt;img src=&quot;https://miro.medium.com/max/30/0*uh6OACL_BgEAGJXJ.png?q=20&quot;&gt;Rails is a model-view-controller Web framework written in the Ruby programming language. One of its great appeals is being able to quickly crank out CRUD-based Web applications. A big advantage of Rails over other frameworks is that it values convention over configuration. If you follow the correct conventions, you can avoid lengthy configuration of files, and things just work! Therefore, you spend less time writing boring config files and more time focusing on business logic.</summary><content type="html">
  &lt;p&gt;&lt;em&gt;Rails is a model-view-controller Web framework written in the Ruby programming language. One of its great appeals is being able to quickly crank out CRUD-based Web applications. A big advantage of Rails over other frameworks is that it values convention over configuration. If you follow the correct conventions, you can avoid lengthy configuration of files, and things just work! Therefore, you spend less time writing boring config files and more time focusing on business logic.&lt;/em&gt;&lt;/p&gt;
  &lt;figure class=&quot;m_custom&quot;&gt;
    &lt;img src=&quot;https://miro.medium.com/max/30/0*uh6OACL_BgEAGJXJ.png?q=20&quot; width=&quot;1400&quot; /&gt;
  &lt;/figure&gt;
  &lt;p&gt;In the overview below we present &lt;strong&gt;10 useful tips, ideas, and resources for Ruby on Rails-developers&lt;/strong&gt; (both newbies and professionals). Please feel free to share your tips, ideas and suggestions in the comments to this post!&lt;/p&gt;
  &lt;p&gt;If you want to Gain In-depth Knowledge on Ruby On Rails, please go through this link &lt;a href=&quot;https://onlineitguru.com/ruby-on-rails-online-training-placement.html&quot; target=&quot;_blank&quot;&gt;&lt;strong&gt;Ruby On Rails Training&lt;/strong&gt;&lt;/a&gt;&lt;/p&gt;
  &lt;h1&gt;1. Plug-Ins Save Time&lt;/h1&gt;
  &lt;p&gt;Rails has a well defined plug-in structure that enables you to easily install and use plug-ins in your application. David Heinemeier Hansson, the father of Rails, once stated that he uses five to six plug-ins in each Rails application.&lt;/p&gt;
  &lt;p&gt;There’s an old nugget of developer wisdom that “the best code is no code at all.” Part of what makes us so &lt;strong&gt;productive when developing in Rails&lt;/strong&gt; is that all the code that we &lt;em&gt;don’t&lt;/em&gt; have to write because someone else in the community has already written a plug-in that provides the functionality we need.&lt;/p&gt;
  &lt;p&gt;There are a few ways to install a plug-in in Rails, however the most common is using script:&lt;/p&gt;
  &lt;pre&gt;# Install from a git reposcript/plugin install git://github.com/mislav/will_paginate.git# Install from a urlscript/plugin install http://topfunky.net/svn/plugins/calendar_helper&lt;/pre&gt;
  &lt;p&gt;You can save yourself a ton of time and hassle by becoming good at searching the Web (and especially the almighty GitHub). A couple of places to find plug-ins are Core Rails, Railsify and Rails Plug-in Directory. Need to integrate with an existing API or consume some kind of standard format data? Need tagging, pagination, or another common Web application feature? Odds are that some great Rails or Ruby developer out there already has a project going that will get you at least most of the way there.&lt;/p&gt;
  &lt;h1&gt;2. Testing Is Fun And Easy With Rspec&lt;/h1&gt;
  &lt;p&gt;For most people, the word “test” brings back scary memories of school exams. When working with Rails, however, &lt;strong&gt;automated testing&lt;/strong&gt; can make your development experience much more enjoyable. While lots of people have strong, nearly religious, opinions about them, at their core, automated tests are just little helper programs you write that run bits of your main code to make sure they do the right thing. When done right, testing will improve your workflow and increase your confidence in the results.&lt;/p&gt;
  &lt;p&gt;Rails ships with a test framework baked right in, but for the last couple of years all the cool kids have been using an alternative called Rspec. Rspec’s biggest advantage is its syntax for specifying tests:&lt;/p&gt;
  &lt;pre&gt;describe &amp;quot;My Cool library&amp;quot; do before do    @cool = Cool.new end  it &amp;quot;should be full of penguins.&amp;quot; do    @cool.get_penguins!    @cool.penguin_count.should == 10  end  it &amp;quot;should melt if it gets too warm&amp;quot;end&lt;/pre&gt;
  &lt;p&gt;What’s &lt;strong&gt;great about Rspec’s syntax is how much English it uses&lt;/strong&gt;. The describe block that sets the context and each assertion within it takes strings that you use to explain what your code should do. Often, this is the most important stage: you sit down to write the assertion, getting as far as you can, and then you think, “Right, what should this code actually do then?”&lt;/p&gt;
  &lt;p&gt;Because Rspec lets you leave off the block that implements the assertion (as in the second melt example), you can quickly brainstorm all of your functionality, and then go back and implement the tests later as you write the code. In the meantime, Rspec will consider those tests as “pending” and give you little reminders about them in your test runs.&lt;/p&gt;
  &lt;p&gt;Besides helping you write code in the first place, another great thing about tests is that, once you have enough of them, they let you see how all of your code is related, making it easy to know if your recent change broke anything else in your application. &lt;strong&gt;Rspec makes it easy to get good test coverage&lt;/strong&gt; through the use of custom generators that create the tests right along with the rest of your code:&lt;/p&gt;
  &lt;pre&gt;$ script/generate rpsec_scaffold MyModel&lt;/pre&gt;
  &lt;p&gt;Once you’ve got tests to ensure that the basic functionality works successfully, you can make changes and add new code with confidence without worrying about introducing invisible bugs. As long as you run your tests regularly, you’ll know as soon as you break something. And as GI Joe taught us, knowing is half the battle!&lt;/p&gt;
  &lt;h1&gt;3. Save Time, Use Rake&lt;/h1&gt;
  &lt;p&gt;Projects often include more than just application-specific code. Sample data have to be created, Web services have to be queried, files have to be moved, code snippets rewritten, etc. Resist the urge to shell script or to cram in a migration or controller. Use Rake. It rocks!&lt;/p&gt;
  &lt;p&gt;Rake is a build tool written in Ruby, very similar to make. Rails projects have several Rake tasks already defined; to see these, run the rake -T command.&lt;/p&gt;
  &lt;pre&gt;macbook$ rake -Trake data:bootstrap     # load in some basic data [caution: will nuke and replcace cate...rake db:create:all      # Create all the local databases defined in config/database.ymlrake db:drop         # Drops the database for the current RAILS_ENV...rake ts:run          # Stop if running, then start a Sphinx searchd daemon using Thi...rake ts:start        # Start a Sphinx searchd daemon using Thinking Sphinx&amp;#x27;s settingsrake ts:stop         # Stop Sphinx using Thinking Sphinx&amp;#x27;s settings&lt;/pre&gt;
  &lt;p&gt;Adding your own Rake tasks is quite easy. In the example below, you see that the task is name-spaced and has a description and task name, allowing you to write in Ruby.&lt;/p&gt;
  &lt;pre&gt;namespace :data do desc &amp;quot;load in some basic data [caution: will nuke and replcace categories, categorizations and inventory items]&amp;quot;  task :bootstrap =&amp;gt; :environment do    # clean out existing:    [Category, Categorization, InventoryItem].each{|m| m.find(:all).each{|i| i.destroy}}    InventoryItem.create! :name =&amp;gt; &amp;quot;Compass&amp;quot;    c = Category.create! :name =&amp;gt; &amp;quot;Basic Apparel&amp;quot;    [&amp;quot;Men’s Heavyweight Cotton T&amp;quot;,    &amp;quot;Men’s Heavyweight Polo&amp;quot;,    &amp;quot;Women’s Organic Cotton Fitted T&amp;quot;,    &amp;quot;Women’s Fitted Polo&amp;quot;,    &amp;quot;Children’s T-Shirt&amp;quot;,    &amp;quot;Jr’s Distressed Hoodie&amp;quot;,    &amp;quot;Hemp Messenger Bag&amp;quot;].each do |name|      c.inventory_items.create! :name =&amp;gt; name    end   ...end&lt;/pre&gt;
  &lt;h1&gt;4. Track Application Exceptions&lt;/h1&gt;
  &lt;p&gt;Exceptions happen, and when they do, you want to know about them! Your client shouldn’t be the one telling you that a problem has occurred; you should already be aware of the issue and working to resolve it. Exception notification has been available in Rails for a while. There are exception notification plug-ins that make it easy to be notified. However, some services such as Airbrake Bug Tracker and Get Exceptional add a lot of value to your application.&lt;/p&gt;
  &lt;p&gt;Both of these services are easy to install and provide a great UI for tracking your exceptions. You can even sign up for a free account to try things out.&lt;/p&gt;
  &lt;p&gt;By &lt;strong&gt;centralizing the application exceptions&lt;/strong&gt;, you are able to see how frequently these exceptions occur, what environment they occur in (a particular browser? a particular location?), what parameters were present and the full stack trace. This centralization of data helps you see patterns and resolve the issue more quickly, which results in a better application and happier users.&lt;/p&gt;
  &lt;h1&gt;5. Mix And Match Between Frameworks And Servers With Rails On Rack&lt;/h1&gt;
  &lt;p&gt;As of version 2.3, Rails runs on top of Rack. Rack makes it possible to mix and match between Ruby Web frameworks and servers. If you’re using a framework that supports it (like Rails, Sinatra, Camping, etc), you can choose from any of the servers that do also (Mongrel, Thin, Phusion Passenger, etc.), and vice versa.&lt;/p&gt;
  &lt;p&gt;In addition to introducing all kinds of new options for deployment, this change means that Rails now has access to the exciting world of Rack middleware. Because Rack lives at the intersection of your app and your server, it can provide all kinds of common functionality directly. A great example of this is Rack::Cache.&lt;/p&gt;
  &lt;p&gt;Rack::Cache provides a &lt;strong&gt;caching layer&lt;/strong&gt; for your application that you control simply by sending the correct headers in your responses. In other words, all you have to do is install a bit of code in the Rack config file:&lt;/p&gt;
  &lt;pre&gt;require &amp;#x27;rack/cache&amp;#x27;use Rack::Cache,  :metastore =&amp;gt; &amp;#x27;file:/tmp/rack_meta_dir&amp;#x27;,  :entitystore =&amp;gt; &amp;#x27;file:/tmp/rack_body_dir&amp;#x27;,  :verbose =&amp;gt; true&lt;/pre&gt;
  &lt;p&gt;And make sure your controller actions send the right headers (for example, by setting &lt;code&gt;request.headers[“Cache-Control”]&lt;/code&gt;) and Bam!, you’ve got caching.&lt;/p&gt;
  &lt;h1&gt;6. Easy Data Dumping&lt;/h1&gt;
  &lt;p&gt;You’ll often need to get data from production to dev or dev to your local or your local to another developer’s local. One plug-in we use over and over is Yaml_db. This nifty little plug-in enables you to &lt;strong&gt;dump or load data by issuing a Rake command&lt;/strong&gt;. The data is persisted in a yaml file located in db/data.yml. This is very portable and easy to read if you need to examine the data.&lt;/p&gt;
  &lt;pre&gt;rake db:data:dumpexample data found in db/data.yml---campaigns:  columns:  - id  - client_id  - name  - created_at  - updated_at  - token records:  - - &amp;quot;1&amp;quot;    - &amp;quot;1&amp;quot;    - First push    - 2008-11-03 18:23:53    - 2008-11-03 18:23:53    - 3f2523f6a665  - - &amp;quot;2&amp;quot;    - &amp;quot;2&amp;quot;    - First push    - 2008-11-03 18:26:57    - 2008-11-03 18:26:57    - 9ee8bc427d94&lt;/pre&gt;
  &lt;h1&gt;7. Keep Your Constants In One Place&lt;/h1&gt;
  &lt;p&gt;All applications have constants, variables that are defined with data that don’t change, such as the name of the application, the tagline, values for crucial options, etc. We use the &lt;strong&gt;Rails initializer feature&lt;/strong&gt; to define a &lt;code&gt;config/initializers/site_config.rb&lt;/code&gt;for housing these constants. By using this convention, all developers on a project know exactly where to look for the constants and can quickly make changes.&lt;/p&gt;
  &lt;p&gt;Many people have questions about when to put a constant in the &lt;code&gt;site_config.rb&lt;/code&gt; instead of the class it is used in. For a constant that are only used in a single class, we suggest putting it in that class. However, if the constant is used in more than one location, put it in the site_config.rb. For more on constants, have a look at Rubylearning.&lt;/p&gt;
  &lt;pre&gt;# File config/initializers/site_config.rbREPORT_RECIPIENT = &amp;#x27;jenn@scg.com&amp;#x27;REPORT_ADMIN = &amp;#x27;michael@scg.com&amp;#x27;&lt;/pre&gt;
  &lt;h1&gt;8. Console For Working On Code&lt;/h1&gt;
  &lt;p&gt;Sometimes you may have code that you’re curious about. Will it work this way? What’s the output? What can I change? Rails ships with a wonderful tool called console. By running script/console you will enter an &lt;strong&gt;interactive environment where you can access your Rails code&lt;/strong&gt; just as though the application were running.&lt;/p&gt;
  &lt;p&gt;This environment is incredibly helpful. It is often used in production environments at times to quickly peek at data without having to log in to the database. To do this in a production environment, use script/console RAILS_ENV=production:&lt;/p&gt;
  &lt;pre&gt;macbook$ ./script/consoleLoading development environment (Rails 2.1.1)&amp;gt;&amp;gt; a = Album.find(:first)=&amp;gt; #&amp;gt;&amp;gt;&lt;/pre&gt;
  &lt;h1&gt;9. Ugly Views Getting You Down? Try Haml.&lt;/h1&gt;
  &lt;p&gt;Views are how your Rails application generates the HTML pages your visitors actually see and use. By default, Rails uses the ERb templating system to let you embed bits of Ruby in your markup so that you can insert your data as needed. However, recent versions of Rails let you take your pick of templating languages, and nowadays the Ruby interwebs have been all abuzz about an alternative system called Haml.&lt;/p&gt;
  &lt;p&gt;Haml is marketed as “markup Haiku.” Its &lt;strong&gt;CSS-inspired syntax lets you focus on the semantics of your data&lt;/strong&gt; rather than worrying about closing all the angle brackets that come with using ERb and HTML.&lt;/p&gt;
  &lt;p&gt;For comparison, here’s a bit of markup in standard ERb:&lt;/p&gt;
  &lt;pre&gt;&amp;lt;%= print_date %&amp;gt;&amp;lt;%= current_user.address %&amp;gt;&amp;lt;%= current_user.email %&amp;gt;&amp;lt;%= h current_user.bio %&amp;gt;&lt;/pre&gt;
  &lt;p&gt;And here’s the equivalent in Haml:&lt;/p&gt;
  &lt;pre&gt;#profile  .left.column    #date= print_date    #address= current_user.address  .right_column    #email= current_user.email    #bio= h(current_user.bio)&lt;/pre&gt;
  &lt;p&gt;Haml’s not for everyone, and many people will find this syntax quite alien. But if you value concision and are fluent in CSS, Haml may be just the ticket.&lt;/p&gt;
  &lt;h1&gt;10. Know Where To Watch What’s Happening In Rails&lt;/h1&gt;
  &lt;p&gt;Rails and Ruby both have &lt;strong&gt;large and active communities&lt;/strong&gt; that constantly generate changes, improvements and new projects. Trying to keep up with all the activity can be daunting, but it’s essential if you want to benefit from the community’s best work and continue to increase your Rails and Ruby knowledge.&lt;/p&gt;

</content></entry></feed>