Monday, October 30, 2017

Java 9 features

In this post we will know some of the important features of JAVA 9. There are lots of new enhancements which are going to affect your programming style. The most important improvement is modularization  of java,which should make java platform more scalable while improving its deployments on smaller devices. 


Here are list of Java 9 features:



  1.     Modularity
  2.   interface Private Methods
  3.     Strings
  4.     Diagnostics
  5.     JVM options
  6.     Logging
  7.     HTTP2 Client
  8.     JavaScript/HTTP
  9.     Native Platform
  10.     Java Docs updates
  11.     Images
  12.     Unicode
Modularity:

This is core feature of Java 9. A module is new construct like we already have packages. An application, developed using new modular programming, can be seen as collection of interacting modules with a well-defined boundaries and dependencies between those modules.

Private Methods:

 Private methods will improve code re-usability inside interfaces. For example, if two default methods needed to share code, a private interface method would allow them to do so, but without exposing that private method to it’s implementing classes.

String:

Two interesting string-related features, Compact Strings and Indify String Concatenation will be part of JDK 9. JEP 254, the compact strings optimization for OpenJDK 9 will improve the footprint of Java String and related classes while preserving full compatibility for all related Java and native interfaces. JEP 280, Indify String Concatenation will enable invokedynamic to concatenate strings, to free runtime implementors for optimizing string concatenation without pushing users to recompile their programs.

Diagnostics:

It describes in detail the diagnostic tools in JDK 9 and troubleshooting tools specific to various operating systems. 


HTTP2/Client:

HTTP/1.1 client was released on 1997. A lot has changed since. So for Java 9 a new API been introduced that is cleaner and clearer to use and which also adds support for HTTP/2. New API uses 3 major classes i.e. HttpClient, HttpRequest and HttpResponse.The beta HTTP/2 client API has come to JDK 9, implementing in Java the upgrade to the web’s core HTTP protocol. WebSocket is supported by the API as well.

The HTTP/2 API can replace the HttpURLConnection API, which has had problems, including being designed with now-defunct protocols, predating HTTP/1, being too abstract, and being hard to use.

JVM Options:

The defining feature for Java 9 is an all-new module system. When codebases grow larger, the odds of creating complicated, tangled “spaghetti code” increase exponentially. There are two fundamental problems: It is hard to truly encapsulate code, and there is no notion of explicit dependencies between different parts (JAR files) of a system. Every public class can be accessed by any other public class on the classpath, leading to inadvertent usage of classes that weren't meant to be public API. Furthermore, the classpath itself is problematic: How do you know whether all the required JARs are there, or if there are duplicate entries? The module system addresses both issues.

Modular JAR files contain an additional module descriptor. In this module descriptor, dependencies on other modules are expressed through`requires` statements. Additionally, `exports` statements control which packages are accessible to other modules. All non-exported packages are encapsulated in the module by default. Here's an example of a module descriptor, which lives in module-info.java

Logging:

Java 9 will introduce a common logging system for all JVM components. This will overhaul how the JVM reports events in its subsystems and add common logging command-line options for loggers.

Unicode:

In JDK 9, the Javadoc documentation tool is enhanced to generate HTML5 markup. The Unicode 8.0 encoding standard—which adds 8,000 characters, 10 blocks, and six scripts—is supported as well.











Python Program to find Armstrong Number

In this article we will learn Python program to check whether the given number is Armstrong or not. First let us understand what is Armstrong?. An Armstrong number is a number that is equal to the sum of the Nth power of its individual digits.

Let me take one example, 153 is a 3 digit Armstrong number then 1^3 +5^3+3^3=153

Now we will write the code to find Armstrong Number in Python Script:

print("Enter the number")
#get the number
number = int(input())
#store it in a temp
temp = int(number)
Sum = 0

#loop till the quotient is 0
while(temp != 0):
rem  = temp % 10 #find reminder
Sum  = Sum + (rem * rem * rem) #cube reminder and add it to the Sum
temp = temp / 10 #find quotient, if 0 then loop again

#if the entered number and the Sum value matches, it is an Armstrong number
if(number == Sum):
print ("Armstrong Number")
else:
print ("Not an Armstrong Number")

Output:

Enter the number: 153
Armstrong Number

Python program to check whether the given number is Armstrong or not using For loop:


Number = int(input("\n Enter the number: "))
 # Initializing Sum and Number of Digits
Sum = 0
number = 0
# Calculating Number of individual digits
Temp = Number
while Temp > 0:
           number = number + 1
           Temp = Temp // 10

# Finding Armstrong Number
Temp = Number
for n in range(1, Temp + 1):
           Reminder = Temp % 10
           Sum = Sum + (Reminder ** number)
           Temp //= 10

if Number == Sum:
           print("\n %d is Armstrong Number.\n" %Number)
else:
           print("\n %d is Not a Armstrong Number.\n" %Number)

Output:

Enter the Number: 370
370 is Armstrong Number

Python Program to find Armstrong Number using recursion:

In this program allows the user to enter any positive integer and then, we will find given number is Armstrong or not using recursion

# Initializing Number of Digits
Sum = 0
Times = 0

# Calculating Number of individual digits
def Count_Of_Digits(Number):
           global Times
           if(Number > 0):
                      Times = Times + 1
                      Count_Of_Digits(Number // 10)
           return Times
#End of Count Of Digits Function

# Finding Armstrong Number
def Armstrong_Number(Number, Times):
           global Sum
           if(Number > 0):
                      Reminder = Number % 10
                      Sum = Sum + (Reminder ** Times)
                      Armstrong_Number(Number //10, Times)
           return Sum
#End of Armstrong Function

#User Input
Number = int(input("\n Enter the Number: "))

Times = Count_Of_Digits(Number)
Sum = Armstrong_Number(Number, Times)
if (Number == Sum):
    print("\n %d is Armstrong Number.\n" %Number)
else:
    print("\n %d is Not a Armstrong Number.\n" %Number) 


Output:

Enter the Number: 370

370 is Armstrong Number



Wednesday, October 25, 2017

SQL Best Books To Learn

In this post i am going to explore  list of highly recommended SQL books that can help beginners learn from scratch at the same time experienced programmers can brush up their skills. The SQL (Structured Query Language) is one of the most important skills of a programmer.You might have any kind of professional programmer like JAVA,C#,.NET you must have work with SQL. Since a database is an integral part of any modern Java or Web application, Interviewer always preferred candidates with good SQL skills. Whether you are a programmer, data analyst or a business intelligence end user, SQL is an invaluable skill for anyone who deals with data. SQL isn’t just for database administrators (DBAs). Learning SQL is helpful for querying databases, operating Business Intelligence (BI) Tools and using these BI platforms’ advanced features. Having a basic understanding of SQL is beneficial even for those who don’t deal directly with a database. Business Intelligence software, such as datapine, offer intuitive drag and drop interfaces, allowing for data querying without any SQL knowledge. That said, knowing the SQL basics will help you understand your organization’s data and better generate actionable insights.

There are two types of books, one that is useful for the novice and other is essential for the experienced users who want to take their skill to a new level. Now you can pick a good SQL book that will suite your needs.

1. Learning SQL By Alan BeauLieu:



SQL (Structured Query Language) is a standard
programming language for generating, manipulating,
and retrieving information from a relational database.
 If you're working with a relational database--whether
you're writing applications, performing administrative
tasks, or generating reports--you need to know
how to interact with your data. Even if you are
using a tool that generates SQL for you, such
as a reporting tool, there may still be cases
where you need to bypass the automatic generation
feature and write your own SQL statements.



2.HEAD FIRST SQL:

This is the one of the best book for beginners. I have been
recommending this book for beginner programmers. This
book provides lots of examples with diagrams,puzzles.This
books takes fun approach to showing the fundamentals of
SQL.








3. Beginning SQL Queries:


This is another beginner books, probably for the absolute beginner who doesn't know how to write SQL queries. AS title suggests this book will help you not only to write SQL queries, but also to write correct SQL queries and help you to become a professional SQL developer. Not a must read, but good SQL books for beginners.








4) SQL: QuickStart Guide 


A standard language for RDBMs or Relational Database Management Systems, the programming of SQL enables the user to perform many important functions such as create, analyze, delete and manage within a comprehensive database only with a few commands. However for that, the user need to know the structure of SQL and this is the best book that imparts the required knowledge such as the definition of RDBMs and their structure, the importance and the fundamentals of programming SQL among the others.




5) SQL Cook Book:


If you are working with SQL for some time and decide that now is the time to get more in-depth knowledge about SQL, this is the best book for you. It is a fact that SQL is a simple language to learn, however, most people do not learn beyond simple functions. This book offers you extensive knowledge that includes window functions; many powerful and database-specific features such as Oracle's MODEL clause and SQL Server's PIVOT and UNPIVOT operators.





Watch Video for More Information: BEST SQL BOOKS FOR BEGINNERS

That's all about to learn some of the most important books to learn SQL for Beginners.

Monday, October 23, 2017

Python Interview Questions and answers

In this post we will learn frequently asked Python Interview Questions and answers for freshers and also for experienced developers.In previous post we had discussed about why Python so powerful for Data Science, one of the frequently raised question that one so go through that post as well.

1) What is Python?

Ans: Python is a high level ,Object oriented,most successful interpreted language. It is a portable language,since it can run on different platforms such as Windows,Linux,Unix,Mac...It is a interpreted language that means when write a Python script it doesn't need to get compiled before execution.

2) What are the Benefits of Python?

Ans:

  1. Python is a Object Oriented Programming language as you can define classes along with the composition and Inheritance. It doesn't use any access specifier like Public or private
  2. It provides very high level dynamic data types and supports dynamic type checking
  3. It can be use as Scripting language or can be compiled to byte-code for building large applications.
  4. We can use Python for developing Web applications,automation,Scientific Modeling,Big Data applications etc..
  5. It can be easily integrated with C,C++,JAVA,COBRA,COM .
  6. It is extensible
3) What are the Data types in Python?

Ans: Python has 5 Standard Data types:

  1. Numbers
  2. String
  3. List
  4. Tuple
  5. Dictiornary
4) Is Multithreading supports in Python?

Ans: YES,Python has multi-threading package. It has a Construct called Global Interpreter Lock(GIL). This GIL makes you feeling only one thread is 'executing' at any one time.This happens very quickly so to the human eye it may seem like your threads are executing in parallel, but they are really just taking turns using the same CPU core.This means that if you want to make your code run faster then using the threading package often isn’t a good idea.

5)What is the output of print str if str = ‘Hello World!’?


Ans: Hello World!.

6) How to overload methods in Python?

Ans: Python's constructor: 
_init__ () is a first method of a class. Whenever we try to instantiate a object __init__() is automatically invoked by python to initialize members of an object.

7)How To Find Bugs Or Perform Static Analysis In A Python Application?

Ans: You can use PyChecker, which is a static analyzer. It identifies the bugs in Python project and also reveals the style and complexity related bugs.Another tool is Pylint, which checks whether the Python module satisfies the coding standard.

8) How to achieve Inheritance in Python?

Ans: Inheritance allows One class to gain all the members(say attributes and methods) of another class. Inheritance provides code re-usability, makes it easier to create and maintain an application. The class from which we are inheriting is called super-class and the class that is inherited is called a derived / child class.

9) What is the usage of help() and dir() function in Python?

Ans: Help() and dir() both functions are accessible from the Python interpreter and used for viewing a consolidated dump of built-in functions. 

Help() function: The help() function is used to display the documentation string and also facilitates you to see the help related to modules, keywords, attributes, etc.
Dir() function: The dir() function is used to display the defined symbols.

10)How is memory managed in Python?

Ans: Python memory is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have an access to this private heap and interpreter takes care of this Python private heap. 
The allocation of Python heap space for Python objects is done by Python memory manager. The core API gives access to some tools for the programmer to code.
Python also have an inbuilt garbage collector, which recycle all the unused memory and frees the memory and makes it available to the heap space.

11)What is dictionary in Python?

Ans: The built-in datatypes in Python is called dictionary. It defines one-to-one relationship between keys and values. Dictionaries contain pair of keys and their corresponding values. Dictionaries are indexed by keys.

Let’s take an example:

The following example contains some keys. Country, State & Captain. Their corresponding values are India, Andhra and Kohili respectively.


dict={'Country':'India','State':'Andhra','Captain':'kohli'}
print dict[Country]
India
print dict[State]
Andhra
print dict[Captian]
Kohli

12)What is pickling and unpickling in Python?

Ans: Pickling is a process in which a pickle module accepts any Python object, converts it into a string representation and dumps it into a file by using dump() function.
Unpickling is a process of retrieving original Python object from the stored string representation for use.

13) How Python does Compile-time and Run-time code checking?

Ans: In Python some amount of coding is done at compile time, but most of the checking such as type, name, etc. are postponed until code execution. Consequently, if the Python code references a user -defined function that does not exist, the code will compile successfully. The Python code will fail only with an exception when the code execution path does not exist.

14)Which command is used to exit help window or help command prompt?

Ans: "quit" command is used to exit help window or help command prompt.

15)What Is The Key Difference Between A List And The Tuple?
Ans: 
The major difference between a list and the tuple is that the list is mutable while tuple is not. A tuple is allowed to be hashed, for example, using it as a key for dictionaries.

16)Is There A Switch Or Case Statement In Python? If Not Then What Is The Reason For The Same?

Ans:
No, Python does not have a Switch statement, but you can write a Switch function and then use it.

 17)What Is A Built-In Function That Python Uses To Iterate Over A Number Sequence?

Ans: 
range() generates a list of numbers, which is used to iterate over for loops.
Example:
for i in range(5):
    print(i)

The range() function accompanies two sets of parameters.

range(stop)
stop: It is the no. of integers to generate and starts from zero. eg. range(4) == [0, 1, 2,3].
range([start], stop[, step])
start: It is the starting no. of the sequence.
stop: It specifies the upper limit of the sequence.
step: It is the incrementing factor for generating the sequence.

Points to note:
Only integer arguments are allowed.
Parameters can be positive or negative.

18)What are the Popular Frameworks of Python.

Ans: Major Frameworks: Django and Pyramid

Minor Frameworks: Bottle and Flask

19) How to take input from the User in Python?

Python provides a built-in method to accept input from the user.
It is as follows: input(“Enter the Input”)
However, in order to store the input in a variable, you must write a variable name before the input() method.
It can done as follows: var1=input(“Enter the input”)

20)What are the various Exceptions identified by Python?

Ans: The various exceptions identified by Python Environment are as follows:
1. IOError
2. IndexError
3. KeyError
4. NameError
5. SyntaxError
6. ValueError
7. TypeError

21)What is a Frame in Python GUI?

Ans: A Frame in Python can be related as a storage holder for other Graphical User Interface or GUI elements such as Label, Text Entry, Text Box, Check Button, RadioButton, etc.

22)What is the difference between input() method and raw_input() method?

Ans: raw_input() method returns string values whereas input() method returns integer vaues.
Input() method was used in Python 2.x versions whereas Python 3.x and later versions use raw_input() method. However, input()method has been replaced by raw_input() method in Python 3.x.

24)What is range() method in Python?

Ans: Range() method is Python is used as a Looping construct. It takes in 2 mandatory parameters and 1 optional parameter.

Example: range(1,20,2)
This method prints numbers after every alternate iterations between 1 and 10. It prints 1 3 5 7 9,11,13,15,17,19

25)Which method is used to find out the location of the pointer in a file?
Ans: The tell() method is used to return the current location or position of the read/write pointer within the file. This method doesn’t require any parameter to be passed in it.

Syntax:
FileVariableName.tell()

26)Why is Finally Block used in Python Exception Handling?

Ans: A Finally Block is generally used in association with try and catch blocks in Python. A Finally Block executes itself no matter if an error occurs at run time or not. It is the default execution block in Python Exception Handling technique.

27)How do you print the sum of digits from 1 to 100 in Python?

Ans:   print(sum(range(1,101))
This command would print in the sum of digits from 1 to 100.

28) How do you copy an object in Python?

Ans. Using the functions copy.copy() and copy.deepcopy()

29)How Do I Generate Random Numbers In Python?

Ans: The standard module random implements a random number generator.
Usage is simple:
import random
random.random()
This returns a random floating point number in the range [0, 1).

30)How Do I Interface To C++ Objects From Python?

Ans: Depending on your requirements, there are many approaches. To do this manually, begin by reading the "Extending and Embedding" document. Realize that for the Python run-time system, there isn't a whole lot of difference between C and C++ -- so the strategy of building a new Python type around a C structure (pointer) type will also work for C++ objects.






Why Python is so Powerful for Data Science

In this post we will Discuss about why python is so powerful for Data Science, Why Data Scientists love coding in Python? Python is the language of choice for data scientists because it is easy to learn, scalable, awesome visualization packages and excellent python community where you can find data science libraries.Python's popularity for data science is largely due to the strength of its core libraries (NumPy, SciPy, pandas, matplotlib, IPython), high productivity for prototyping and building small and reusable systems, and its strength as a general purpose programming language. 

Python is a language that builds upon and extends over 50 years of research in numerical methods and scientific computing. It is possible to apply very complex, well developed algorithms to real world data problems quickly and cleanly.Python has great tools, like IPython Notebooks, for Agile programming and collaboration.  It is very easy to sit down with a client and knock out prototype algos for them in a matter of days.  It is easy to iterate, and the handoff is working prototype that can readily be productionalized by other team members.   Compare this to say R, which is comparatively hard to get into production, or Java, which takes 10 times longer to code up.


Since data scientists are also often involved with wiring together network applications, programming for the web, scripting and automating data processing jobs and other processes, and lots of ad hoc data munging (the kind of stuff people loved using Perl for in the 90s), it's very desirable to be able to do all these things, in addition to the actual analysis and modeling, in a single language.By using Python you can build a program very quickly, profile and identify bottlenecks, then optimize by using better array programming techniques.

Data scientists need to use data visualizations to clearly communicate outputs and predictions to stakeholders at any level of a business. This is the real value a great data scientist can provide – without this, it’s a zero-sum game.Hence, Python has become a programing language that links between different units across the business and a direct channel for data sharing and processing language. 

IPython-Notebook:

This is just a GREAT tool. You can run multiple lines/blocks of code in different cells, you can play with them, move them up or down, and you can even get your results appear just underneath the cell. It really is like the magical organizer that Data Scientists (and people who run code and want to iterate) have always dreamed of.  You can also write R, SQL, Scala, and other languages in IPython-Notebook which makes the work-flow much easier and efficient.

Python is easy to learn:

Python's main advantage is that anyone can learn it quickly and easily. The language was designed to be simple.

Scalability:

Relative to other language/Packages for Data Science (as MatLab, Stata, R) Python is much faster. It’s true that Java and Scala are much faster than Python (x3), but with Anaconda (Continuum Analytics) Python has caught up to speed!
As a Data Scientist, I prefer to run my code and get my output in Python relative to the traditional languages that are computationally slower. As always, there are trade-offs. 

Growing Data Analytics Libraries:

With Python, you can find a large variety of Data Analytics/Data Science Libraries (as others have mentioned here: NumPy, SciPy, StatsModels, Scikit-Learn, Pandas, etc.) - which are exponentially growing over time. Constraints (in optimization methods/functions) that were missing a year ago are no longer an issue, and you can find a proper robust solution that works reliably. 

Visualization / Graphics: 

Python is not as good as R (yet), but we’ll see more and more cool APIs (e.g., Plotly) and Data Visualization libraries that make the partial advantage of R insignificant compared to Python. You can do really cool stuff with Python.

Powerful statistical and numerical packages:

  1. NumPy and pandas (Python Data Analysis Library) allow you to read/manipulate data efficiently and easily.
  2. Matplotlib allows you to create useful and powerful data visualizations. I have also listed more data visualization packages in Python: Yilun (Tom) Zhang's answer to What's some good python data visualization website?
  3. Scikit-learn allows you to train and apply machine learning algorithms to your data and make predictions.
  4. Cython allows you to convert your code and run them in C environment to largely reduce the runtime and improve your model performance.
  5. PyMySQL allows you to easily connect to MySQL database, execute queries and extract data.
  6. BeautifulSoup to easily read in XML and HTML type data which is quite common nowadays.
  7. iPython notebook for interactive programming as in R.
  8. Multi-paradigm. You can write object-oriented and functional code.
  9. Interactiveness. Thanks to iPython and Jupyter notebooks. 
  10. A strong community
  11. Scripting powers. Dealing with thousands of files, scrapping websites, requesting different APIs..

Python’s increase in the share over 2015 rose by 51% demonstrating its influence as a popular data science tool.It is perfect when data analysis tasks involve integration with web apps or when there is a need to incorporate statistical code into the production database. The full-fledged programming nature of Python makes it a perfect fit for implementing algorithms.

This is fantastic, and opens up the door to do very creative and powerful things. That's all about why choose Python So Powerful for Data Science.If any comments on this post let me know.. 




Thursday, October 19, 2017

Python Vs Java which is best for Project

One of the most frequently asked question is should I learn Java or Python, Is Python is good programming language to start with, Which programming language would you recommend for beginners to learn first etc.Python and Java are two very different programming languages, but both can be useful tools for modern developers.

Most programmers agree that Python is an easier language for novice programmers to learn. You will progress faster if you are learning Python as a first language than Java. However, the popularity of Java means that learning this powerful language is essential if you want to develop apps for Android.

The great advantage of Java is that it can be used to create platform-independent applications. Any computer or mobile device that is able to run the Java virtual machine can run a Java application, whereas to run Python programs you need a compiler that can turn Python code into code that your particular operating system can understand. Thanks to the popularity of Java for web applications and simple desktop programs, most devices already have the Java virtual machine installed, so a Java programmer can be confident that their application will be usable by almost all users. The disadvantage of running inside a virtual machine is that Java programs run more slowly than Python programs.

One of the biggest differences between Python and Java is the way that each language handles variables. Java forces you to define the type of a variable when you first declare it and will not allow you to change the type later in the program. This is known as static typing. In contrast, Python uses dynamic typing, which allows you to change the type of a variable, by replacing an integer with a string, for example.

Dynamic typing is easier for the novice programmer to get to grips with, because it means you can just use your variables as you want to without worrying too much about their types. However, many developers would argue that static typing reduces the risk of undetected errors plaguing your program. When variables do not need to be explicitly declared before you use them, it is easy to misspell a variable name and accidentally create a whole new variable.

java’s speed allows it to outperform other languages and frameworks, which is a big part of why it’s so well suited to large-scale applications. These performance gains are what prompted Twitter to shift its search engine to Java from Ruby on Rails and move more of its back-end stack to the Java Virtual Machine.

Another key component of Java is that it comes as close to being 100% object-oriented as you can get. With that comes all the benefits of object-oriented programming, from ease of development to modular software to flexibility and extensibility. As one of the most widely known programming languages, it’s easy to find and hire talented developers. What’s more, Java’s massive community of developers means that there’s lots of excellent documentation around.

Like Java, Python is built to handle high-traffic sites. It’s fast and efficient, with an emphasis on code readability. Python’s motto is “there should be one—and preferably only one—obvious way to do it.” That can mean there’s a bit of a learning curve as developers learn the ins and outs of Python syntax, but the upside is an ability to express concepts with fewer lines of code than would be possible in languages like C++ or Java.

Python’s other great strength is an extensive set of libraries that allow it to perform a wide array of tasks. In particular, the libraries NumPy and matplotlib enable Python to perform many of the analysis and plotting functionalities of MATLAB. These libraries have since been built upon by a number of other libraries that extend Python’s functionality even further.




Tuesday, October 17, 2017

Spring Security Interview Questions and Answers

In this post we will learn frequently asked Spring Security Interview Questions. Since every programmer must aware to give security for their software while they developing projects. Spring Security gives highly powerful and customizable authentication and access-control framework. It provides Authentication and Authorization mechanism. Now we will see some important Spring Security Interview Questions

1)What is Spring Security?

Spring security is a project under spring framework umbrella, which provides support for security requirements of enterprise Java projects. Spring Security formerly known as aegis security provides out of box support for creating login screen, remember me cookie support, securing URL, authentication provider to authenticate user from database, LDAP and in memory, concurrent active session management support and many more. In order to use Spring security in a Spring MVC based project, you need to include spring-security.jar and configure it in application-Context-security.xml file, you can name it whatever you want, but make sure to supply this to ContextLoaderListener, which is responsible for creating Spring context and initializing dispatcher servlet.


2) Why do you need method security? What type of object is typically secured at the method level?

Ans: Spring Security uses AOP for security at the method level

  • annotations based on Spring annotations or JSR-250 annotations
  • Java configuration to activate detection of annotations
  • It typically secure your services
  • Do not access repositories directly, bypasses security (and transactions) 
3) Will Spring Security secures all the Applications?

Ans: No, in web applications, we need some more things to secure full application to save from hackers.


4) How is Security mechanism implemented using Spring?
Ans:  Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications. Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is found in how easily it can be extended to meet custom requirements. 

Spring makes use of the DelegatingFilterProxy for implementing security mechanisms. It is a Proxy for standard Servlet Filter, delegating to a Spring-managed bean that implements the Filter interface. Its the starting point in the springSecurityFilterChain which instantiates the Spring Security filters according to the Spring configuration
Some of the features of Spring Security are: 
  1. Comprehensive and extensible support for both Authentication and Authorization
  2. Protection against attacks like session fixation, clickjacking, cross site request forgery, etc
  3. Servlet API integration Optional integration with Spring Web MVC

5)How to enable Spring Security in Web Application?

You can enable the Spring security by adding the Filter org.springframework.web.filter.DelegatingFilterProxy in your application’s web.xml.
6)What is the delegating filter proxy?
Spring’s DelegatingFilterProxy provides the link between web.xml and the application context. In Spring Security, the filter classes are also Spring beans defined in the application context and thus able to take advantage of Spring’s rich dependency-injection facilities and lifecycle interfaces.

Example:
filter>
<filter-name>myFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>myFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

7)What is the security filter chain? 
In Spring Security you have a lot of filters for web application and these filters are Spring Beans. Each Spring security filter bean that require in your application you have to declare in your application context file and as we know that filters would be applied to application only when they would be declared on web.xml. Now DelegatingFilterProxy comes into picture for delegating the request to fillter which declared into application context file by adding a corresponding DelegatingFilterProxy entry to web.xml for each filter and we have to make sure about ordered, it should be define correctly, but this would be cumbersome and would clutter up the web.xml file quickly if you have a lot of filters. FilterChainProxy lets us add a single entry to web.xml and deal entirely with the application context file for managing our web security beans.

Example:

<bean id="filterChainProxy" class="org.springframework.security.web.FilterChainProxy">
<constructor-arg>
 <list>
 <sec:filter-chain pattern="/restful/**" filters="
  securityContextPersistenceFilterWithASCFalse,
  basicAuthenticationFilter,
  exceptionTranslationFilter,
  filterSecurityInterceptor" />
 <sec:filter-chain pattern="/**" filters="
  securityContextPersistenceFilterWithASCTrue,
  formLoginFilter,
  exceptionTranslationFilter,
  filterSecurityInterceptor" />
 </list>
</constructor-arg>
</bean>

8)From the applications perspective, how many user roles needed in spring security?
Answer:
Three user roles are there in spring:

Supervisors
Tellers
Plain Users

9) How to configure Spring Security with jdbc configuration?
Ans: 
 @Autowired
private DataSource dataSource;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) 
  throws Exception 
{
auth.jdbcAuthentication().dataSource(dataSource)
      .withDefaultSchema()
      .withUser("user").password("password").roles("USER")
      .and()
      .withUser("admin").password("password").roles("USER", "ADMIN");

10)What is authentication and authorization? Which must come first?

  • Authentication – Establishing that a principal’s credentials are valid
  • Authorization – Deciding if a principal is allowed to perform an action
Authentication comes first before Authorization because authorization process needs principal object with authority votes to decide user allow to perform a action for secured resource.

11)Does Spring Security support password hashing? What is salting?

Ans: Yes, Spring Security provides support for password hashing. The salt is used to prevent dictionary attacks against the key in the event your encrypted data is compromised.

12)What's the difference between @Secured and @PreAuthorize in spring security?
Ans:  if you wanted to do something like access the method only if the user has Role1 and Role2 the you would have to use @PreAuthorize @PreAuthorize("hasRole('ROLE_role1') and hasRole('ROLE_role2')") Using @Secured({"role1", "role2"}) is treated as an OR 

That is all about Spring Security Interview Questions subscribe me for latest updates.



Friday, October 13, 2017

MapReduce Tutorial

In this post i am going to introduce to you MapReduce, which is one of the framework for writing applications to process huge amount of data(It might be structured or unstructured data) in HDFS. It is specially designed for commodity hardware. It allows us to perform parallel and distributed processing  on huge data sets. These MapReduce programs can be written in various languages such as JAVA,Python,C++.

MapReduce actually refers to two separate and distinct tasks that Hadoop programs perform. The first job is Map job, which takes a set of data and converts it into another set of data where individual elements are broken down into touple(key/value pairs). Then reduce job is takes the output from a map as input and combines those data tuples into a smaller set of tuples. We should remember one point is,reduce job is always performed after the map job.

Advantages of MapReduce:

1. Parallel Processing:

In MapReduce, we are dividing the job among multiple nodes and each node works with a part of the job simultaneously. So, MapReduce is based on Divide and Conquer paradigm which helps us to process the data using different machines. As the data is processed by multiple machine instead of a single machine in parallel, the time taken to process the data gets reduced by a tremendous amount.

2. Data Locality: 

Instead of moving data to the processing unit, we are moving processing unit to the data in the MapReduce Framework.  In the traditional system, we used to bring data to the processing unit and process it. But, as the data grew and became very huge, bringing this huge amount of data to the processing unit posed following issues: 

Moving huge data to processing is costly and deteriorates the network performance. 
Processing takes time as the data is processed by a single unit which becomes the bottleneck.
Master node can get over-burdened and may fail.  
Now, MapReduce allows us to overcome above issues by bringing the processing unit to the data. So, as you can see in the above image that the data is distributed among multiple nodes where each node processes the part of the data residing on it. This allows us to have the following advantages:

It is very cost effective to move processing unit to the data.
The processing time is reduced as all the nodes are working with their part of the data in parallel.
Every node gets a part of the data to process and therefore, there is no chance of a node getting overburdened. 

MapReduce Example:

Let's assume we have three tables and each table contains two columns that represent a company name and corresponding profit. In this example, company name is the key and profit is the value.



In the above data, we have to find the maximum profit for each company across all of the tables(note each table might have the same company represented multiple times). Using the MapReduce framework,we can break this down into three map tasks,where each mapper works on one of the three tables and mapper task goes through the data and returns the maximum profit for each company.

For example,the results produced from one mapper task for table A would like this:

[(abc,34),(pqr,15),(xyz,32)]

Same,the results produced from one mapper task(working on the other two tables)would like this:

[(abc,23),(pqr,34),(xyz,18)]
[(abc,34),(pqr,34),(xyz,23)]

All three of these output streams would be fed into the reduce tasks,which combine the input results and output a single value for each company,producing a final result set as follows:

[(abc,34),(pqr,34),(xyz,32)]

MapReduce PROGRAM:

In this i have taken word count example where i have to find out number of concurrences of each word.

mport java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.fs.Path;

public class WordCount
{
public static class Map extends Mapper<LongWritable,Text,Text,IntWritable> {
public void map(LongWritable key, Text value,Context context)throws IOException,InterruptedException{

String line = value.toString();
StringTokenizer tokenizer = new StringTokenizer(line);
while (tokenizer.hasMoreTokens()) {
value.set(tokenizer.nextToken());
context.write(value, new IntWritable(1));
}
}
}
public static class Reduce extends Reducer<Text,IntWritable,Text,IntWritable> {
public void reduce(Text key, Iterable<IntWritable> values,Context context) throws IOException,InterruptedException {
int sum=0;
for(IntWritable x: values)
{
sum+=x.get();
}
context.write(key, new IntWritable(sum));
}
}
 public static void main(String[] args) throws Exception {
 Configuration conf= new Configuration();
Job job = new Job(conf,"My Word Count Program");
job.setJarByClass(WordCount.class);
job.setMapperClass(Map.class);
job.setReducerClass(Reduce.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
job.setInputFormatClass(TextInputFormat.class);
job.setOutputFormatClass(TextOutputFormat.class);
Path outputPath = new Path(args[1]);
//Configuring the input/output path from the filesystem into the job
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
//deleting the output path automatically from hdfs so that we don't have to delete it explicitly
outputPath.getFileSystem(conf).delete(outputPath);
//exiting the job only if the flag value becomes false
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}

Run the MapReduce code:
The command for running a MapReduce code is:
hadoop jar hadoop-mapreduce-example.jar WordCount /sample/input /sample/output




ConcurrentHashMap in Java8 with Example

In this post we will learn about concurrentHashMap in Java 8. We will cover the concepts what is concurrentHashMap,advantage of concurrentHashMap with simple examples and also we will check how to create concurrentHashSet from the concurrentHashMap.

From Java5 ConcurrentHashMap is introduced as another alternative for HashTable.There is no ConcurrentHashSet in JDK8 but you can still create one for yourself by using the ConcurrentHashMap class of java.util.concurrent package. There is a new method added into ConcurrentHashMap in JDK 8, newKeySet(), which allows you to create a concurrent hash set backed by a concurrent hash map.If you remember whenever you get keys from the map they are returned in a Set e.g. for the old keySet() method because map only has unique keys. Since map doesn't allow duplicate keys, it can be used as a set, as long as you only care for keys or just one element. That's why Java designers are added newKeySet() method to convert a map to set. This is also a static method, which means you don't need a ConcurrentHashMap object to create a concurrent hash set.

How Performance improved:

ConcurrentHashMap is also a hash based map like HashMap, how it differs is the locking strategy used by ConcurrentHashMap. Unlike HashTable (or synchronized HashMap) it doesn't synchronize every method on a common lock. ConcurrentHashMap uses separate lock for separate buckets thus locking only a portion of the Map. Just for information ConcurrentHashMap uses ReentrantLock for locking.

How to create simple example of ConcurrentHashMap:

public class Demo {
public static void main(String[] args) {
// Creating ConcurrentHashMap
Map<String, String> cityTemperatureMap = new ConcurrentHashMap<String, String>();
// Storing elements
cityTemperatureMap.put("Mumbai", "38");
cityTemperatureMap.put("chennai", "40");
//cityTemperatureMap.put(null, "23");
cityTemperatureMap.put("Bangalore", "26");
cityTemperatureMap.put("Hyderabad", "34" );
for (Map.Entry e : cityTemperatureMap.entrySet()) {
System.out.println(e.getKey() + " = " + e.getValue());
}
}
}

Null is not allowed
Though HashMap allows one null as key but ConcurrentHashMap doesn't allow null as key. In the previous example you can uncomment the line which has null key. While trying to execute the program it will throw null pointer exception.

Exception in thread "main" java.lang.NullPointerException
 at java.util.concurrent.ConcurrentHashMap.putVal(Unknown Source)
 at java.util.concurrent.ConcurrentHashMap.put(Unknown Source)
 at byluckysir.prog.Demo.main(Demo.java:16)

Java Program to create ConcurrentHashSet:
Here is our Java program to demonstrate how you can generate a ConcurrentHashSet in JDK 8 by using the newKeSet() method added into java.util.concurrent.ConcurrentHashMap class. Even though I have used an object of the concurrent hash map here, it's not required because unlike keySet(), the newKeySet() is a static method.

Let's the code to actually generate a concurrent hash set in Java 8:

import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/*
 * Java Program to create ConcurrentHashSet from ConcurrentHashMap
 * This code requires JDK 8 because we use newKeySet() method
 * which is only available in ConcurrentHashMap class from JDK 8. 
 */
public class Test {
public static void main(String[] args) throws Exception {
// step 1 - create a concurrent hashmap (optional)
 ConcurrentHashMap<String, Integer> wordLengh = new ConcurrentHashMap<>();
// step 2 - create a set from map by using newKeySet() method
// provide size to prevent resizing and better performance
Set<String> words = ConcurrentHashMap.newKeySet(wordLengh.size());
// step 3 - you can add elements into set
 words.add("JavaBook");
words.add("JavaScript");
// step 4 - you can remove elements from set
words.remove("JavaScript");
// step 5 - you can also pass this set to any method expecting set
System.out.println(words);
}
}
Output:
Java

You can see that you can easily add and remove elements from the Set returned by newKeySet() method. As I said, the Set is backed by ConcurrentHashMap, which means multiple readers can retrieve values at the same time and also multiple writers can insert values into the set without blocking, until the read and write operation is happening in the same segment.

concurrent hash map never locks the whole map, instead, it divides the map into several segments, by default 16, also knowns as concurrency level and only locks the segment where modification is happening. This means multiple writes is possible if they are happening at different segments.

The concurrent hash set is not only thread-safe set which is available in JDK, you have some more choices e.g. you can use CopyOnWriteArraySet, which is similar to CopyOnWriteArrayList i.e. it copies the whole collection into new one whenever a write happens but because of this behavior they are only useful for a set with small number of elements with infrequent write.

When ConcurrentHashMap is a better choice:

ConcurrentHashMap is a better choice when there are more reads than writes. As mentioned above retrieval operations are non-blocking so many concurrent threads can read without any performance problem. If there are more writes and that too many threads operating on the same segment then the threads will block which will deteriorate the performance.

Points to Remember:

  • ConcurrentHashMap is also a hash based map like HashMap, but ConcurrentHashMap is thread safe.
  • In ConcurrentHashMap thread safety is ensured by having separate locks for separate buckets, resulting in better performance.
  • By default the bucket size is 16 and the concurrency level is also 16.
  • No null keys are allowed in ConcurrentHashMap.
  • Iterator provided by the ConcurrentHashMap is fail-safe, which means it will not throw ConcurrentModificationException.
  • Retrieval operations (like get) don't block so may overlap with update operations (including put and remove).


This is all about concept of ConcurrentHashMap in java 8. If you have doubt or any suggestions to make drop a comment..






High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...