Blogs On Job Interview Questions

Job Interview Tips

Job Interview Tips

by Vibrant Publishers on May 19, 2022
Interviewer: You have 50 minutes to design Google Maps.You: I just realized I should head back home right now.Most projects that you worked on in college and at work already had an established team in place and you were involved in writing features for a very specific component.So, how do you perform this seemingly absurd task single handedly under an hour?Understand what the interviewer is asking for.Draw a box on the (on the white board/laptop screen provided for the interview) that represents the system. Add 5 – 6 major components within this box. Briefly discuss each component to give the interviewer an idea of your thinking process.So even though your interviewer is not really expecting you to design Google Maps from scratch when you meet him, he wants to understand if you will be a good fit for his team which is working on a similar project. This exercise will give him a good idea of your technical skills.Don’t pretend to be an expert in an area which is not yours and don’t rush to give an answer. Keeping these small things in mind will help you for your technology interviews.You can also brush up on your domain knowledge on various IT technologies with the Job Interview Questions Series books by Vibrant Publishers.
How to Prepare for an Interview

How to Prepare for an Interview

by Vibrant Publishers on May 19, 2022
I have always dreaded being told, “ We’ll get back to you.”   Did they not like me?   How many more people are they going to meet for this profile?   Why did they even conduct the interview if they already have someone in mind for this profile?   All these questions ran through my mind whenever an interview ended on this note. On the other hand, when I am told that I will have to attend another round on a particular day or asked to wait back, I know that something positive is coming my way.   Everyone needs help in acing a job interview. The uncertain economic conditions, downsizing due to automation and the need to move up the job ladder make the interview even more crucial. A good prep before the interview will help to avoid the interview day nightmares. Most successful people prepare for a job interview even before they get an actual call.       So how does one prepare for an interview? The first and the most important thing that you should do is go through the company website and understand the job description that you are applying for.   Interviews generally have two types of questions – behavioral and technical, especially if you are applying for jobs in the technology industry.   For the behavioral questions, keep a list of your past work experiences and skills handy. You can talk about how you worked with your team to deliver on a project which had deadlines that looked impossible to begin with. These questions help the company understand your work style and abilities. It is okay to ask questions during the interview if you have genuine queries about the organization or the profile. It shows that you have taken time out to prepare for the interview.   The next important part that you have to tackle are the technical questions. You may be applying for a senior manager or a team leader profile in an area where you are already working like SAS or Android. Or you may want to shift to a newer technology platform. The interviewer here wants to assess your knowledge, ability to think laterally, problem-solving strategies and get a sense of your industry knowledge.   You have studied these subjects in college as well as worked in the area for a couple of years but there will be a lot of new trends which may be out of your purview of work.     How do you quickly brush up the entire subject in a short time? There is a lot of material available online. But how much of it is relevant, written by subject matter experts or reviewed by industry professionals? Also how easily can you get access to all of it in one go without wasting much time?   The Job Interview Questions series by Vibrant Publishers provides accurate and authoritative information on the questions that you will be asked in an interview. A quick reading of these books will help you crack your interview.   Rather than going through big fat college reference books, the Job Interview Questions Series gives you all the information that you need in a question-answer format for the specific technology area that you are applying e.g. Oracle, Python, SAP, SAS, SQL, UNIX or Software Testing.   General HR questions are also covered in the books so all aspects of your interview are taken care of. Real-Life scenario-based examples will give a case study touch to your conceptual base. These books are concise and well written and will give you a great idea about your strengths as well as the level of preparation.   These can be ordered online here or you can pick them up at your nearest bookstore. Try and relate specific work examples to what you are reading in the book. It will help you grasp the topic quickly.   During the technical interview, make sure you clear your doubts and assumptions with the interviewer. It is okay to think aloud when you are trying to arrive at a solution. It gives the interviewer an insight in the way you think. It is important to remember that the interviewer may be more interested in your approach and thought process rather than the actual answer.   At the end of it all, make sure that the questions don’t get to you and keep in mind that making eye contact and a firm handshake with the interviewers is the last impression that you make before exiting the room.
Spring REST Client

Spring REST Client

by Vibrant Publishers on Jan 04, 2022
Introduction The spring framework in Java is used for building enterprise-class applications. This framework has extensive support for building REST-based web services. There are both client-side and server-side libraries available for this. The web applications that leverage the power of the Spring framework can implement REST services in a much faster way. This article will discuss the client-side REST implementation using the Spring framework. The Spring REST Client The client-side implementation of Spring REST will enable a client application to receive web service responses from the server. It also provides a toolset required for building and sending REST API requests from the client application. The main class that enabled the client to use the REST API with Spring was the RestTemplate class. But from the latest version of Spring, ie. Spring 5.0 onwards this class has been deprecated and a new class called WebClient got introduced. It’s a modern alternative to the RestTemplate class. Let us have a detailed look at the WebClient class. WebClient Class From Spring 5.0 onwards the WebClient class will be the gateway of all the web requests and responses in a web application. The advantages of this implementation over its predecessor RestTemplate class are: (a) It is non-blocking in nature. (b)It has a singleton implementation (c) It is reactive in nature. The WebClient class like its predecessor works over protocol HTTP/1.1. While working with the WebClient class the main steps we need to know are the following: 1. Creating an instance. 2. Building a client request. 3. Handling the request & response. Let us get into the details of these processes. Creating an instance The simplest way to create an instance is as shown below: WebClient testClient = WebClient.create(); We can also create the instance by providing a URI: WebClient testClient = WebClient.create(“http://exampleserver.com/8000”); The most advanced way of creating an instance is by providing all the required details for the class. The below given code snippet is an example for that.                                                                             WebClient testClient = WebClient       .builder()       .baseUrl(“http://exampleserver:8000”)       .defaultCookie(“key”, “value”)       .defaultUriVariables(Collections.singletonMap(“url”, “http://exampleserver:8000“))        .defaultHeader(HttpHeaders.CONTENT_TYPE,   MediaType.APPLICATION_JSON_VALUE)     .build();     Building a client request Once we are ready with an instance, the next step is to create a REST API request from the client. One of the main parts of the request is the type of request that we are sending. We must decide the HTTP methods GET, POST, UPDATE & DELETE that we are going to use while sending a request. The following code snippet will do that: WebClient.UriSpec testRequest = testRequest.method(HttpMethod.POST); The next step is to provide a target URL which can be done as given below:                                                             WebClient.RequestBodySpec testURI = testClient     .method(HttpMethod.POST)     .uri(“/resource”);     After this step, we have to provide the other details such as content-type, header details, etc. That can be set as follows:                                                                     WebClient.RequestBodySpec testURI = testClient     .method(HttpMethod.POST)   .uri(“/resources”).body( BodyInserters.fromPublisher( Mono.just(“information”)),   String.class);     Once we are done with setting the body of the request, the WebClient will send the request to the target URI which will invoke the server-side API function.   Handling the request & response There are two ways we can send and receive the information using WebClient. One is using the exchange() method and the other one is using the retrieve() method. The main differences between these two methods are that the first method will return HTTP information like cookies, headers, etc along with the response body while the second method will only return the response body. A sample request & response code will look as follows:                                                                           Class testClass = testClient.post()           .uri(“/resources”)           .body(Mono.just(), String.class)           .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)           .retrieve()           .bodyToMono(String.class);     Here the request is a HTTP POST and the response will be returned as a response body which will be parsed by the bodyToMono() function. If there is a 4xx or 5xx response, this method will throw a WebClientException. Summary Handling requests and responses at the client side are handled in the Spring framework using the WebClient implementation. This is the new standard for handling client web requests and responses after Spring 5.0. There is a rich set of functionalities that makes this implementation an efficient and easier one.  
JAX-RS Client

JAX-RS Client

by Vibrant Publishers on Jan 04, 2022
Introduction Resources form the basic building block of any REST service. These resources are accessed using the REST client libraries. JAX-RS client is such an implementation. This library makes it easy for any Java programmer to access any REST resources over the internet. JAX-RS ClientThe first version of JAX-RS ie. JAX-RS 1.1 does not had any client implementation. It is from JAX-RS 2.0 onwards it started supporting REST clients. The JAX-RS client API can be found under the javax.ws.rs.Client package. Classes under this package provide high-level APIs for accessing any REST resources, not just JAX-RS services. Let us have a look into the basic operations of JAX-RS Client API. Creating a basic client requestBefore defining a client request, we have to set certain things in place. They are: Obtain an instance of javax.ws.rs.Client class. Configure the client with a resource target. Create a request. Invoke the client request. Let’s have a look into these steps by considering the following code snippet: Client apiClient = ClientBuilder.newClient(); String URI = “http://foodchain.com/api/foodmenu”; String foodMenu = client.target(URI).request(MediaType.JSON).get(String.class); client.close(); Here we first created the client instance by declaring the client variable using the newClient() method. Client apiClient = ClientBuilder.newClient();After this step, we are chaining a set of methods with the client instance that will return the API resource to the string variable foodMenu. There are three steps involved in this process. Setting the target by apiClient.target(URI). This is the remote location where the resource is located. Building a REST request entity using the apiClient.request(Mediatype.JSON) statement. Here we also set the media type of the entity. Invoking the HTTP GET request with apiClient.target(URI).request(MediaType.JSON).get(String.class) statement. Also, the return type of the entity is set into String type. Once the client API successfully receives the response, we will close the client connection with the apiClient.close() statement.We have now seen a simple JAX-RS client API call in action. Now let us look into some of the extended use cases of JAX-RS client library.Setting multiple client targetsWe used the client.target() method in the previous example to set the target URI. We can also use the javax.ws.rs.client.WebTarget class for the same purpose. This will help us in handling REST resources where multiple targets are involved. In the given example, we are setting a base target “http://restapi.com/assignments” using the WebTarget class. The base target is used for building several resource targets that will point to different API services provided by a given RESTful resource. Client apiClient = ClientBuilder.newClient(); WebTarget base = apiClient.target(“http://restapi.com/assignments”); // WebTarget at http://restapi.com/assignments/read WebTarget read = base.path(“read”); // WebTarget at http://restapi.com/assignments/write WebTarget write = base.path(“write”);  Invoking the WebTarget.path() method with a path parameter creates a new WebTarget instance by appending it with the base URI.Invoking the requestThe JAX-RS client can invoke every available REST request method. This is accomplished by calling the WebTarget.request() method and passing the relevant media type value. This will provide an instance of javax.ws.rs.client.Invocation.Builder. This helper object will provide HTTP methods for the client API request. In the first example, apiClient.target(URI).request(MediaType.JSON).get(String.class) we had invoked the HTTP GET request and the same process stands for POST(), DELETE(), PUT() methods also. SummaryJAX-RS client API that got introduced in version 2.0 is one of the best implementations of the REST client library. It’s quite easy to make client API calls using this library. We can use this library in Java for accessing any REST resource over the web.  
Introduction to REST

Introduction to REST

by Vibrant Publishers on Dec 22, 2021
Introduction REST stands for Representational State Transfer. It’s a web services access protocol providing standards of communication in the web world. The software systems that follow this style for communication are known as RESTful systems. The other web services access protocols that people use are SOAP, GraphQL, etc.The main characteristics of a RESTful system compared to others are: Stateless. Separate the concerns of the client and server. Uniform Interface. Cacheable. Code-on-demand. Layered System. Why choose REST?The beauty of REST is that it allows you to focus on building app features. You don’t need to break your head thinking client-server interaction, complexity, interoperability, etc. You can build the client-side and server-side independently. They will communicate over a platform-agnostic format that REST provides. Using the same approach, you can build a modular application. Your modules will implement the REST interface and communicate with each other. This makes your application modular, separate and flexible. Each of your modules has the freedom to grow independently. Here each module provides REST endpoints where other modules interact using REST interfaces. The other big advantage of RESTful systems is its statelessness. This indicates that the server does not need to worry about the client and vice versa. The request that comes from a client will have all the details to perform a particular operation on the server-side. In this way, the server doesn’t need to store any previous state or data of the client to operate. This helps RESTful applications to perform quicker, achieve scalability and reliability. Concept of Resources REST uses resources rather than commands. A resource can be anything that we can name. It can be a document, an image, a collection of objects, etc. Each resource has a resource identifier for its unique identification during an operation. Resource representation is the state of a resource at any given time. Every resource representation will have an associated media type as well. RESTful communicationRESTful systems communicate using the REST API (Application Programming Interface). REST APIs work over HTTP and are very light compared to SOAP implementation. There are different HTTP methods available for different operations. REST will leverage these HTTP methods for its operation. The most common methods are: GET, POST, PUT & DELETE.Every resource liking to interact with a REST interface will have API representation. Let’s take an employee management application. At the server, a list of employees can be represented in REST API format as given below:             http://www.employeeapp.com/employeesA client application has to first implement a REST client library to do an API request to the server. In Java, we have a JAX-RS library to do so. Now a client-side GET request will be:           GET http://www.employeeapp.com/employeesFor POST, PUT & DELETE operations you will specify the exact resource identifier also.            DELETE  http://www.employeeapp.com/employees/ID4512The response can have different formats like CSV, JSON, HTML, etc.When using JSON, there are JSON formatters and validators are available to check the sanity of the data. JSON Lint (https://jsonlint.com) is an example.The below given diagram depicts REST service interaction in a client-server environment. SummaryREST is a communication framework between a web client and a server. There are multiple reasons to choose REST over other such web communication frameworks. It’s scalability, flexibility and wide adoption makes this framework popular in the web services world.
Spring REST Request Processing

Spring REST Request Processing

by Vibrant Publishers on Dec 21, 2021
IntroductionDeveloping REST APIs and web services using Spring Boot makes the process very easy and helpful for the developer. It takes out a lot of overheads and helps us to only focus on the core business logic. The rest of the configurations and setup processes are taken care of by the framework itself. In this article, we will focus on the request processing part of a REST API using Spring Boot. The flow of an API Request in Spring When we create a microservice in Spring the main control flow of an incoming request will as shown below:The role of annotations Some of the main annotations for processing a request using spring are as follows: @RestController: This is the heart of any Spring web service. There must be a class declared with this annotation. It will make the class discoverable during classpath scanning. @RequestMapping: The resource methods that are annotated with the above annotation will be exposed as HTTP endpoints. When an API request matches a given @RequestMapping annotation, the resource method will be executed to serve the incoming request. The following code snippet will give you an idea of using these annotations:The request mapping process @RestController @RequestMapping(“/employee”) public class EmployeeController {                 @Autowired                 EmployeeDetails employeeDetails                 @RequestMapping(method = RequestMethod.GET)                 public List findEmployee()                  {                     return employeeDetails.findEmployee();                 } }   When we prepare our classes and resource methods with the given annotations, the Spring Boot takes care of the rest of the processing. Let us consider a sample incoming request as given below:Request: http://localhost:8080/employeeAccept: application/JSONWhen this request reaches the server container, the spring boot will handle this request using a DispatcherServlet. The configuration and initialization of this servlet will be already done by the Spring Boot during the project creation time itself.The Dispatcher ServletThe DispatcherServlet will be the front end controller through which all the requests will be passing through. There are a few steps that the DispatcherServlet will be doing for us to process the request. They are: Intercepting the incoming request to identify the resource. Finding a suitable handler for the given request. This is done by checking the Path parameter, HTTP method, Query parameter & the Request header.   Get the matching controller method for the incoming request. This is possible due to the mapping registry prepared by the spring framework by looking up @RequestMapping annotations. Execute the controller method to process the incoming resource. We can understand the process from the following diagram:SummaryUnderstanding the processes involved in REST request handling by the spring ecosystem is important. This will help us to code efficiently and also in doing better troubleshooting.  
TOP 10 HADOOP BIG DATA QUESTIONS AND ANSWERS

TOP 10 HADOOP BIG DATA QUESTIONS AND ANSWERS

by Vibrant Publishers on Dec 15, 2021
Gartner predicts over 50 percent of new business systems will be use continuous intelligence by 2022. Leading companies such as Morgan Stanley, Standard Chartered, J-P Morgan, etc, are calling upon aspiring candidates to apply for positions like Analytics Professional, Data Management Professionals and Big Data Engineer. This brings a bright future to those skilled in Big data. Yet acing the interview where high-level questions are put forth remains a big hurdle. Take help from these top 10 Big Data Interview Questions highly asked in job interviews.   1) How important is Big data to e-commerce? E-commerce is one of the biggest beneficiaries of Big data processing and analytics. A lot of critical information is gathered from social media sites and search engines that ecommerce companies use to predict better and offer a more effective customer experience. Predictive analysis plays an important role in retaining customers longer on the websites and this is made smoother with Big data. It also helps to fine-tune customer interactions through better personalization. Big data has proven to reduce the cart abandonment rate through prediction and personalization. 2) Describe Operational Big Data. Operational Big data involves real-time data that is instantly analyzed and presented without the help of advanced coding or data scientists. These include interactive systems where data is captured, processed and reported instantly without involving data scientists. NoSQL Big data systems use advanced cloud computing techniques that run complex computations involving such real-time data without having to invest in additional infrastructure. They can manage large volumes of varied data and process them quickly using easy-to-implement technology. 3) Explain the HDFS Architecture. The HDFS architecture consists of nodes and blocks. The Namenode comprises commodity hardware that manages that operating system which is typically Linux and the namenode software. It manages the file system providing access to the file system namespace and data. It allows opening, closing and renaming of files and directories. The datanode consists of hardware, an operating system, and datanode software. The datanode performs the reading and writing of data as per the client’s request. The datanode manages the data blocks including creation, deletion, and replication based on the directions of the namenode. The data is stored in files and each file is divided into different segments and stored in different data nodes. Block is the smallest section of data that’s stored in the HDFS. 4) Explain ls, lsr, du and cat commands in HDFS. The ls, lsr, du and cat commands are used in HDFS to access the file system. ls: This HDFS command is used along with the path to list out the contents of the directory specified in the path. It shows the file names, owner, permissions and modification date for each file in the directory. lsr: This command is used to display all files within the subdirectories in the mentioned path along with the filename, owner, permissions and modification date for each file in each subdirectory. du: This command takes in the path and displays the full HDFS prefixed file names along with the space occupied by each file in the given path. cat: This command takes in a filename and displays the content of the file on the console screen. 5) What is the difference between Hadoop and RDBMS? Hadoop is not a database. Basically, it is a distributed system that lets you store the data in large amounts on cloud machines. An RDBMS is a distributed database system that stores the interrelated data and its dependencies. RDBMS uses relational data and stores it in rows and columns. Hadoop provides various ways to span the data across various mediums and reach out to the data. The storage is spread across multiple local servers. The Hadoop has efficient fault-tolerance, to detect and manage the defect in nodes. As Java is used in Hadoop, it is platform-independent. Hadoop has high scalability as compared to RDBMS. 6) Explain Repartition Join in MapReduce. In Repartition Join, each map works on an input split on the table on either the Left or Right of the join. Each record is tagged with the table to identify. So the key becomes the key and value is the record. These key-value pairs are then partitioned, sorted, and combined. The reducer takes in the key-value pairs and the table tags. For every key in the Right table, all matching records in the Left tables will be fetched. 7) Explain what Flatten does in Pig. Flatten is an operator or modifier that un-nests the tuples and bags in Pig. It is like simplifying the data of unnecessary complications, making data plain. When Flatten is used with bags, the data is simplified into tuples. When tuples are flattened, they are turned into plain data. It works like a ForEach loop where data is cross-joined with each element to relate it to the main key. 8) Does Impala use Caching? Yes Impala uses caching to provide quicker results. In fact, Impala works better with HDFS rather than Hadoop. It caches some of the frequently accessed data so that the database or HDFS does not have to be accessed every time data is requested. You can set up the cache pool and cache limit for the same user as the ImpalaD. Once caching is enabled, for every schema object you have created with the said cache pool will be available in the cache so that it is loaded only once. Thus all frequently accessed tables and partitions can be stored in the cache for quicker access. 9) What are the attributes of AVRO Schemas? AVRO schemas contain four attributes – type of the schema, its namespace, schema name, and the fields in it. The type of the schema determines whether it is a record, map, array or any other primitive or complex data type supported by AVRO. The namespace is where we can find the schema object. Name is the identifier of the schema and the field is an array that contains the name and datatype of the fields used in the schema. 10) Explain the Fork and Join control node in Workflow. A Fork is used when there’s parallel processing required. In the end, the fork consolidates the results that are fed into another job. This consolidation is done by the Join. So every fork ends with a join. After the start node, the forks run parallel to each other and process the jobs that are consolidated by a join. The join passes on the data to the next node only when all nodes connected complete their tasks. Pave the route to your dream job by preparing for your interview with the questions we discussed, along with more questions from our books HR Interview Questions You’ll Most Likely Be Asked (Third Edition) and Leadership Interview Questions You’ll Most Likely Be Asked. These provide a comprehensive list of questions for your interview regardless of your area of expertise. Good luck with your job hunt!
JAX-RS Filters

JAX-RS Filters

by Vibrant Publishers on Dec 14, 2021
Introduction JAX-RS is the Java implementation for REST services.There are a lot of features in this library that helps us to build web services in Java. The JAX-RS Filters are used for processing the incoming and outgoing requests and responses including headers, entity and other parameters. This feature was introduced in JAX-RS 2.0. These filters get executed after a request and before a response.The filters are available for both server and client side processing. Use of filters You might be wondering what is the use of filters in web services. Well, there can be situations where you would like to do a common modification for all the requests originating from a particular client or some signature like “Powered by XX” in all the responses going from a particular server. Instead of doing this implementation on all the service methods we would use a filter which will include this modification in all the API requests and responses. The below given is a diagram that schematically represents the filtering process on both client and server sides.     In the first section we got to know that there are filters available for server side and client side as well. Let us look into the details of their types and implementations. Server Side Filters The server side has got two types of filters. ContainerRequestFilters             They get executed before your JAX-RS request resource method is getting invoked.This filter can be used in two ways post-matching and pre-matching. In post-matching filters will be applied after a suitable resource method selection that processes the actual request. Here the filter will not affect the resource matching process. In certain scenarios, this can become a disadvantage. In-order to solve that problem there is pre-matching. When we mark a server request filter as pre-matching using the @PreMatching annotation, the filters are executed before the request matching process. ContainerResponseFilters        These filters get executed after your response method is invoked.They will help you to alter the outgoing response before it reaches the client. ContainerResponseFilter can only be implemented in the pre-matching way. With this filter one can modify the HTTP headers, media type(json,xml,etc.) and other meta-data. They also have the capability to abort a method execution. Client Side Filters Like we saw on the server side, the client side also has two types of filters. ClientRequestFilters            These filters are executed before the client API request is sent to the server over a network. ClientResponseFilters              These filters will be invoked after the client receives a response from the server, but before it is being unmarshalled. They can modify the response body before it is getting processed by the client side code. Summary JAX-RS filters are useful in dealing with modification of REST API request-response services.These filters can be installed at any point in the REST service pipeline. There can be multiple request-response filters where they are executed in a chain. It is very useful when we are working with API driven applications where we might need modification on multiple REST APIs at a given time.  
10 Most Likely Asked Java/J2EE Design Pattern Interview Questions And Answers

10 Most Likely Asked Java/J2EE Design Pattern Interview Questions And Answers

by Vibrant Publishers on Dec 14, 2021
According to the Bureau of Labor Statistics (BLS), the median annual salary for software developers like J2EE developers is $101,790.The BLS has predicted a job growth rate of 31 percent through 2026, which is much faster than average for all occupations. Demand for developers will grow with the increased demand for computer software. Prepare with the top 10 Java/J2EE Design Patterns Interview Questions highly asked in job interviews. These are the questions that we will be covering today: 1: What does the JTable class do in Design Patterns? 2: What does the getStepCount() Method do in Design Patterns? 3: What is an Abstraction in Design Patterns? 4: What does the Monitor Function do in Design Patterns? 5: What are the differences between factory and abstract factory Patterns? 6: What is the main advantage of the Facade Pattern? 7: What happens with the response to the request in the case of these two patterns? 8: What problem does the Business Delegate Pattern try to solve? 9: How are new Observers added to existing ones? 10: Give some examples of Behavioral Patterns and how they are used. 1: What does the JTable class do in Design Patterns? Answer: The JTable class is used to handle almost every aspect of displaying a table, but cannot know in advance what data the developer wishes to present. It is a main setter for the use of the Adapter. 2: What does the getStepCount() Method do in Design Patterns? Answer: This method is used as an operation in the Process Component class to count the number of steps needed in a process flow; it has to count each step only once and not enter an infinite loop when a process contains a cycle. 3: What is an Abstraction in Design Patterns? Answer: Abstraction is an oops concept where necessary details are hidden from the user, and only relevant details are exposed. It helps in designing a solution to the problem during the design phase. Abstraction can be achieved by an interface or an abstract class. The abstract class consists of abstract methods without providing concrete implementations for the abstract methods. It can also consist of non-abstract methods with core implementation. While the interface only consists of abstract methods without their implementation. 4: What does the Monitor Function do in Design Patterns? Answer: The Monitor Function is a way of designing an application object so that it does not produce unpredictable results when more than one thread tries to access the object at the same time. 5: What are the differences between factory and abstract factory Patterns? Answer: Both Factory and Abstract Factory are creational design patterns. However, there are some differences between the two: a) Factory method design pattern can be implemented by a method; the abstract factory design pattern needs to be implemented via a class b) In the factory method pattern, we define an interface but decide which class to use at runtime. In the abstract factory method, we define interfaces corresponding to the factory classes and decide which factory class to use at runtime. c) The abstract factory design pattern provides a higher level of abstraction as compared to the factory method d) The factory method pattern uses inheritance whereas the Abstract Factory pattern uses Composition 6: What is the main advantage of the Facade Pattern? Answer: The Facade Pattern helps in hiding the complexities of the application beneath the layer of an interface. This interface helps reduce the dependency of the client classes on the subsystem classes, thus resulting in a manageable and user-friendly subsystem. 7: What happens with the response to the request in the case of these two patterns? Answer: In the case of Proxy Pattern, the response to the request is guaranteed, provided the communication between the client and the server locations is working. In the case of Chain of Responsibility, the response is not guaranteed. It means that the request may end up reaching the end of the chain and still might not be processed. 8: What problem does the Business Delegate Pattern try to solve? Answer: When the presentation tier or client application accesses the business tier directly, the business service API is exposed to the client application or presentation tier. So if the business API changes, the corresponding changes will have to be made in the presentation tier. Also, in such an implementation, there is a performance issue as well, since the business service is invoked each time by the client application. Thirdly, this kind of implementation causes a tight coupling between the presentation tier and the business tier. The business delegate pattern solves all these problems. The Business Delegate class is present on the client side and it hides the implementation details of the business tier by providing an abstraction. So the client application only interacts with the delegate class which in turn routes the client’s request to the appropriate business method. 9: How are new Observers added to existing ones? Answer: This is achieved after applying the Observer Pattern and adding them dynamically without requiring any changes to the Subject Class. Also, Observers remain unaffected when the state chance logic of the subject changes. 10: Give some examples of Behavioral Patterns and how they are used. Answer: Some of the most common Behavioral Patterns are: a) Iterator -This design pattern is used to access elements of a collection sequentially hiding the internal implementation. b) Chain of Responsibilities – This design pattern is used where a chain of objects is used to handle the responsibilities. In this design pattern, a request to process the client call is only passed to the next object when the first object fails to process the same. c) Observer – It is used where a one-to-many relationship exists among the objects and modifying a single object can impact the dependent objects. d) Mediator -This design pattern encapsulates the communication complexity that takes place between different objects and acts as an intermediary between the objects for communication. To have a successful career as a Java/J2EE developer, one must get a good start. Refer to our book HR Interview Questions You’ll Most Likely Be Asked (Third Edition) to find out interview questions for your HR round, and prepare yourself for all the aspects of your interview. Good Luck!
Spring REST Response Processing

Spring REST Response Processing

by Vibrant Publishers on Dec 14, 2021
Introduction Requests and Responses are building blocks of any REST API. They must be built and handled properly to make any API to work without glitches. Though the Spring framework takes care of many configurations behind the scene, there are certain things as a developer one must understand. In this article, we will focus on the response processing part of a REST API using Spring Boot.   Spring REST API Responses Once the request is processed by request handlers and resources methods, the next step in the pipeline is to build an appropriate response to the client. The below given diagram is a high level process summary on how responses are handled in REST.     There are multiple ways to build a response using the Spring framework. They are: Response Body Response Entity Response Body   The @ResponseBody annotation in Spring Boot is used for binding a return value from a resource method to a web response body. This is done by the use of HTTP message converters. This conversion is done by looking at the content-type value in the HTTP request header. Let us consider the following example:                                                                       @RequestMapping(path = “/FindEmployee/1234”, produces = “application/json; charset=UTF-8”)   @ResponseBody     public List<Employee> findEmployee() {    var employeeData = (List<Employee>)  employeeDatabase.findAll();       return employeeData; }       in the above code, the request comes to find the employee details for the given employee id. The media type in the request header is JSON. Now the resource method findEmployee() is called that will return the result. Now there is a class in Spring known as RequestResponseBodyMethodProcessor. It will collect the return values from methods that are annotated with @ResponseBody. This value is then written into the body of the response. A suitable HTTP message converter class will be called during this process. In our case since the media type is JSON, the MappingJaxkson2HttpMessageConverter class will be called. This class will read and write JSON using Jackson Object Mapper. Jackson is a popular Java JSON library. The response body is now ready with the response data in the JSON form which can be transported to the client over the network. Response Entity The main difference between the Response Body and Response Entity is that the @ResponseEntity annotation represents the whole of the response including the message body, response header, and the status code. The advantage of using this method is flexibility. We can fully configure the response to the client the way we want. The following code sample will give an idea about the usage of @ResponseEntity.                                                                                 @GetMapping(“/employeeID”)   ResponseEntity<String> getEmployee(@RequestParam(“employeeID”) int employeeID)    {     HttpHeaders httpHeaders = new HttpHeaders();       httpHeaders.add(“My-Header”, “foo”);       if (idNotNumber(employeeID)) {                return new ResponseEntity<>(“Employee ID must be a number”, HttpStatus.BAD_REQUEST);       }         return new ResponseEntity<>(“Employee Details: ” + findEmployee(employeeID), HttpStatus.OK);    }   Here we have used all the major possibilities of @ResponseEntity. We can build a custom response with custom HTTP headers, Status code & message using this method. Summary Building an API response in the Spring framework can be done using ResponseEntity and Response Body annotations. Though @ResponseBody will cater to the basic requirements, @ResponseEntity annotation provides better control and flexibility in building a response. When we need to build responses with a lot of customization, then the @ResponseEntity would be a better choice.  
JSON

JSON

by Vibrant Publishers on Dec 07, 2021
IntroductionThe web services paradigm works with a number of technologies and services. In those data types that are used for exchanging information between the client and the server play a vital role. There are multiple formats available in REST for requests and responses. In this article we are discussing JSON which is a popular data interchange format. JSONJSON is a lightweight data interchange format that is used in exchanging data between client and server in web services implementations. JSON stands for Javascript Object Notation. The JSON files will end with a .json extension. While specifying the HTTP media type it is represented as ‘application/json’.Why JSONJavascript Object Notation is popular compared to its counterparts. This is mainly due to the way JSON stores and processes information. The information in JSON is well organised and easy to access which is in human readable format. You can store any type of data in this format. When compared to other data storing formats, JSON is very light weight and does not need any complicated parsing processes to retrieve information.Creating a JSON ObjectYou can create a JSON object like the same way you create a generic object. For example, in Javascript you will be creating a JSON object like as follows: An empty object:  var JSONObj = {};  A new object: var JSONObj = new Object(); Create & Initialize an object:  var JSONObj = {“car”: “Honda City”, “color”: “red”} JSON Data Storing MechanismThe data in JSON is stored in a Key-Value pair. This is the simplest storage option for network transmission. For example if I create a JSON block with my details, it would be something like as given below:                                                                               1 vivek = { 2 “age” : “30”, 3 “country” : India,IN”, 4 “gender” : “male” 5 }; This will create an object ‘vivek’ through which one can access all the related information. Here the “name” can have multiple “values” of different types. It can be an integer, an array, a string, etc. While retrieving the information it only requires to refer to the object and the corresponding property of that object. For example if we would like to know the age of ‘vivek’ you can get it by accessing the return value of ‘vivek.age’ property.                  var age = vivek.age;This way accessing the information is pretty simple.The below given diagram shows the types of data that  JSON can support.   The main two data structures that JSON support are: A collection: This is the collection of data in name value pairs. An ordered list: This type of data structure can be seen when we store an array, list, etc. in a JSON object. JSON and JSONPOne of the biggest advantages of using JSON in client side programming is its ability to make cross-domain data exchange. This is achieved using JSONP which is known as JSON-Padding.When you send a JSONP enabled request to the server, you will also pass a callback parameter that will enable the server to send the response in such a way that the client will be able to handle the response and execute further actions. The only problem with this method is that once you send the request, you don’t have any handle over it. The response may come or may not, you won’t get any notification or acknowledgement that you can share with your end user.  So you end up using timers and that is not the best choice always. SummaryWe have seen the JSON format and its use in the webservices world. There are many use cases where JSON is really a time saver and makes the process ease and fast. The support for both the client side and the server side for this format is extensive and without doubt JSON is one of the most popular data exchange formats now.  
10 Most Likely Asked Unix Shell Programming Interview Questions And Answers

10 Most Likely Asked Unix Shell Programming Interview Questions And Answers

by Vibrant Publishers on Nov 30, 2021
Unix Shell Programming is one of the top requirements in most IT jobs today, be it an Informatica Developer, a System Administrator, an Ops Developer or an ETL Developer job opening. Prepare from the top 10 Unix Shell Programming Interview Questions highly asked in job interviews for such roles. In this blog, you will find answers to the following 10 questions most definitely asked in Unix Shell programming interviews. We will be covering the following questions: 1: What will the output of the following commands be? Explain.      set names =(Kathrin Chris Jacob)      shift names      echo $#names 2: What do the following lines do? Explain the differences.      ls > filename      ls >! Filename 3: Use awk mathematical functions to calculate the area of a circle (area= PI*rad2) 4: How would the shell interpret the command “echo ??a”? 5: Describe the “and” list execution. 6: Explain whiptail, man and grep. 7: Explain env. 8: Does = and -eq function similarly? 9: What are the functions of echo_style()? 10: What are the file test operators in shell? So, let’s discuss the answers to these questions. 1: What will the output of the following commands be? Explain.      set names =(Kathrin Chris Jacob)      shift names      echo $#names Answer: The output will be 2. shift command gets rid of the first element of the array names. So,the echo command will display 2 as the number of elements of the array. 2: What do the following lines do? Explain the differences.      ls > filename      ls >! Filename Answer: In both forms, the output of ls command is redirected to filename.If filename does not exist, it will be created, otherwise it will be truncated. When the first form is used, if shell parameter noclobber is set and filename is an existing file, an error results. The ‘!’ in the second form is used to suppress that check. 3: Use awk mathematical functions to calculate the area of a circle (area= PI*rad2) Answer: alias mathcalc ‘ awk “BEGIN{ print \!* }” ‘ set rad = 1.3 set circle_area = `mathcalc atan2(0,-1)*${rad}*${rad}` Explanation: The alias defines a kind of mathematical calculator called mathcalc, which uses the “one-liner” awk to perform calculations (limited to the set of mathematical functions available in awk). Then, this calculator is used to calculate the circle’s area. It uses the arctangent function atan2 that evaluates PI. 4: How would the shell interpret the command “echo ??a”? Answer: Before starting the execution of echo, the shell will replace the two ??. For the shell, the ? represents any one character in a filename. But the first dot in a filename cannot be substituted by any character and should be given literally. This command would output any files and subdirectories in the current directory, which have a name comprising of three characters, except the ones starting with a dot. 5: Describe the “and” list execution. Answer: An “and” list is a way of chaining together commands. The syntax is: command 1 && command 2 && … command-n Each command is executed in turn, provided the previous one has given an exit value of TRUE. At the first FALSE return value, the chain terminates, and the remaining commands do not get executed. 6: Explain whiptail, man, and grep. Answer: A whiptail in shell script lets you show user-friendly dialogue boxes to display information or to take user input. The man command is like the help and info commands used to seek help. The difference is that man displays the roffhelp (roff being the first UNIX program with text formatting). The grep is a utility that’s used to search for information in pipes or files. It is used for text search along with other commands, such as the ls command. Suppose you are looking for a file with mynm in its name, you can redirect the output of ls command to a grep command with the text to search for and you will get the file that has it. 7: Explain env. Answer: The env command is used to change a few environment variables only for running a particular script without changing the system environment. You can set the env in the shebang line. For example, you can set the scripting language to Perl for a particular script only using env instead of changing the environment settings. 8: Does = and -eq function similarly? Answer: The = is usually used as the assignment operator, that is, to assign values to a variable. The == is used for comparison. The -eq command is also used for comparison. The difference is that while == does a lexical or string comparison, -eq does a numeric comparison. 9: What are the functions of echo_style()? Answer: a) When set to ‘bsd’, if the first argument is ‘-n’, new line will not be displayed b) When set to ‘sysv’, it interprets backslash as escape sequence characters c) When set to ‘bsd’, it accepts both ‘-n’ and escape sequence 10: What are the file test operators in shell? Answer: The file test operators in shell are used to check the files for specific properties. Here are some: a) -b returns TRUE if the file is a block special file b) -c returns TRUE if the file is a character file special c) -d returns TRUE if it is a directory d) -f returns TRUE if it is a normal file e) -r returns TRUE if it has readable permission f) -w returns TRUE if it has writable permission g) -x returns TRUE if it has executable permission h) -e returns TRUE if it exists either as a file or folder Kickstart your career in UNIX Shell programming by clearing all job interviews you sit for. All the best!  
JAX-RS Security

JAX-RS Security

by Vibrant Publishers on Nov 23, 2021
Introduction Web services play a very vital role in any web application. Since these services deal with data which are of varied criticality, the security considerations of these services are very high. The JAX-RS library implemented to create REST web services in Java uses strict measures to ensure the security of the APIs built on top of it. Let us examine those security features of JAX-RS in detail. JAX-RS Security The JAX-RS library provides a core set of security features at three levels that are as follows. Encryption Authentication Authorization   Encryption    We all know that the REST is built on top of the HTTP protocol. The security of REST services lies in the security of its transfer protocol also. So while implementing APIs developers also make sure that they use HTTPS protocol with SSL certificates to ensure end-to-end encryption. This will block any third party from reading the information by intercepting the network. Authentication         This is another common strategy that people use to make sure the client has access to a particular API resource. This is done by validating the client identity on the server-side. There will be a credential matching process that will confirm the client. In JavaEE containers, there is a web.xml file that can be configured for such processes. Below shown activity diagram shows a sample API authentication process.       Authorization          When a client is authenticated, the next step in the security process is to check whether the client is authorized to access certain resources from the server. In some cases, certain resources are read-only for certain types of clients. Some may have read and update access. So these permissions have to be validated. These settings are also configured in the web.xml file of the application which is hosted in the server container. JAX-RS Security Implementations  We have seen the main ways by which security can be forced into web services. Now let us see how JAX-RS is implementing these measures.  There are three ways by which JAX-RS security can be implemented. They are: Using a deployment descriptor file. Using the security context. Use of annotations.   Using a deployment descriptor file. The deployment descriptor file is an XML file that is part of the container. It is called web.xml. You will configure the web.xml file for web services security in such a way that any client trying to access a resource via an API, it will be asked for authentication and authorization. This is done through the following steps: Define the tag for every URIs or RESTful API resources that we are planning to protect. Use an element that will define a type of authentication that we would like to use. Define one or multiple security roles by including the tag. Once done, map them with security constraints defined in Step.1.   Using the security context The use of SecurityContext class helps us to get the below mentioned security information for a given resource. java.security.Principal object that has the name of the user who is making a request. Authentication type that is used to secure a resource, like FORM_AUTH, BASIC_AUTH, CLIENT_CERT_AUTH. Check whether the authenticated user has been included in any security roles. See whether the request is coming from a secure channel like HTTPS. Use of annotations The javax.annotations.security package in Java provides security annotations. They can be used for securing APIs methods. Following are the common annotations in use:                                                                                     Annotation Usage @PermitAll Specifies that all security roles are allowed to invoke the given resource method. @RolesAllowed Lists out the security roles that are allowed to access a given resource method. @DenyAll It specifies none of the security roles are allowed to invoke the given resource method. @DeclareRoles This will provide the security role of the current user invoking a resource method.   Summary Security implementation in JAX-RS leverages the help of server container and transport protocols. They are implemented mainly using configuration parameters and through annotations. When we are building APIs for web applications, it is always a good practice to include these security features in our API code.    
10 Most Likely Asked ORACLE DBA Interview Questions And Answers

10 Most Likely Asked ORACLE DBA Interview Questions And Answers

by Vibrant Publishers on Nov 23, 2021
$98,122 per year is the average salary of a Database Administrator in the United States, says Indeed.com. An entry-level Oracle Database Administrator (DBA) with less than 1 year of experience can expect to earn an average total compensation (including tips, bonus, and overtime pay) of ₹280,188. An early career Oracle Database Administrator (DBA) with 1-4 years of experience earns an average total compensation of ₹426,638 (Source: Payscale.com) A lucrative career like this makes the job interviews difficult to crash. Take help from these top 10 Oracle DBA Interview Questions highly asked in Administrator job interviews. 1: You as a DBA just gathered the statistics on schema A. Schema A has 1500 tables. You want to know the name of the table with the highest number of records without running a count on each. How do you do this? 2: At what stages does an instance pass while starting up? 3: How does Oracle execute scheduler jobs and which background processes take part in this? 4: What is a materialized view and how does it differ from a regular view? 5: What parts can be found in a regular SELECT statement? 6: From the isolation levels, explain how “serializable” transactions behave? 7: What are the advantages of using ASM (Automatic Storage Management) over a regular file system? 8: Can you have ASM configured with RAC? What are the benefits of having ASM configured? 9: What are the three types of data block buffer states? 10: Explain the Shared Server Architecture in Oracle Networking. Let’s discuss the answers to these questions. 1: You as a DBA just gathered the statistics on schema A. Schema A has 1500 tables. You want to know the name of the table with the highest number of records without running a count on each. How do you do this? Answer: You query the NUM_ROWS column in the DBA_TABLES table. After running the statistics, this field is populated with current and updated data, and it is a simple and quick method for getting this information without going to every table and counting the records. 2: At what stages does an instance pass while starting up? Answer: You can start up a database with the modes below: a) NOMOUNT: This is the first stage. At this mode the instance is started. b) MOUNT: This is the second stage. At this mode, the instance is started and the database is mounted. However, the database is not open so you cannot still access data. However you can perform several maintenance tasks at this stage. c) OPEN: This is the final stage. The database is open and all the data is accessible. The default open mode is “read/write” which means you can read data or write to it. However, it is also possible to open it in “read-only” mode where you can only read data but cannot change it. 3: How does Oracle execute scheduler jobs and which background processes take part in this? Answer: The scheduled jobs are managed by “Oracle Scheduler”. The information about the scheduled jobs is stored in the JOB$ table. The “Oracle Scheduler” spawns a Job Coordinator (CJQ0) process to run the jobs. This process is the coordinator. It will monitor the JOB$ table to see if there is any job waiting to be run. The coordinator will then spawn “job queue slave processes” named “Jnnn” to execute the scheduled tasks. These background processes work dynamically. They may enter a sleep state when they are idle or they might completely shut down if they remain idle for a certain time. They will be re-spawned later when needed in the future. 4: What is a materialized view and how does it differ from a regular view? Answer: A regular view is only a definition of a SELECT query. It only contains the SQL text in the data dictionary. It has no segment and it doesn’t store any data. A materialized view also has a definition which is still an SQL query but this time the materialized view has a segment and the result of the SQL query is stored in that segment. When a user queries a regular view, he is directed to the underlying tables to retrieve data. However, when a user queries a materialized view, he directly retrieves the data in the Materialized view segment. The user doesn’t read the base tables. 5: What parts can be found in a regular SELECT statement? Answer: a) Projection: This is the part where we define a set of columns to read from the table. This means that all the columns will be selected. b) FROM: This is the part where define a set of tables or views which want to read data from. c) Predicate: This is the part where we do filtering. This is also called the “where” clause. d) Sorting: This is the part where you can sort the result according to certain columns. e) Grouping: This is the part where you can group the results according to certain columns.   6: From the isolation levels, explain how “serializable” transactions behave. Answer: A transaction starts implicitly when a DML statement is executed in a session. Multiple statements might be executed until the transaction ends. In a “serializable” transaction, all the SELECT queries will return rows as they were at the time the transaction began. Not the time the SELECT query began. You can still make modifications to data in a serializable transaction, but this data should not have been changed by another transaction after the current transaction began. Otherwise you’ll get an error. 7: What are the advantages of using ASM (Automatic Storage Management) over a regular file system? Answer: When you use ASM, you can make direct I/O to the underlying disks. If you use a file system, there will be an overhead of using the file system. You have to use the interfaces of that file system. The maintenance is easier in ASM. ASM will manage the disks itself. In a file system you need to manage the disks yourself. ASM acts like a volume manager. You can dynamically add disks to it or remove disks from it. Regular file systems don’t have these capabilities. You have to use a separate volume manager. ASM distributes the files to each underlying disk and because of that it provides a better I/O performance. 8: Can you have ASM configured with RAC? What are the benefits of having ASM configured? Answer: Yes you can. They are complementing technologies. ASM provides a storage abstraction level by grouping several disks into one Diskgroup. This simplifies the space administration and allows the creation of failover and mirrored groups,increasing DB reliability. 9: What are the three types of data block buffer states? Answer: A data block in the database buffer cache can be in three states. These are: a) Unused: This block has been created during buffer cache initiation but has never been used. b) Dirty: A data block was read from the disk into the cache and it was updated by a server process. The block on the cache is different from the corresponding block on the disk. c) Clean: The data block in the buffer cache is the same as the corresponding data block on the disk. 10: Explain the Shared Server Architecture in Oracle Networking. Answer: A connection is established between a server process and a client process. The server process executes the incoming requests and sends back the results to client processes. In dedicated server architecture, the server process is exclusive to that client process. In shared server architecture, on server process can serve multiple client requests. The dispatcher processes will accept the request from clients, they will deliver the request to shared server processes for executing and then they will get the results from shared server processes and send them back to the client process which has requested it. To ace other aspects of your interview, refer to our Job Interview Questions Book Series, which includes books such as HR Interview Questions You’ll Most Likely Be Asked (Third Edition) and Innovative Interview Questions You’ll Most Likely Be Asked. All the best!  
JAX-RS Asynchronous Processing

JAX-RS Asynchronous Processing

by Vibrant Publishers on Nov 19, 2021
IntroductionThe JAX-RS library is used for implementing REST web services in Java. They are designed for quick request-response processing to ensure speed and optimal use of the underlying container thread pool. But there can be scenarios where certain resources need to run for a longer time to process and provide a response. To address these scenarios, JAX-RS has implemented an asynchronous processing mechanism. This feature was introduced in JAX-RS version 2.0. Let us have a look into the JAX-RS Asynchronous processing mechanism.Asynchronous processing This means the thread that responds to a request will be a different one than that of the thread that handled the request. In short, the request and response won’t happen in one stretch. There can be a considerable time gap between the two.Why is it required?If you are wondering what is the need for such an implementation, there mainly two benefits: Consider a synchronous request-response scenario. If a JAX-RS client sends a request that requires long waiting for a response from the server, it is blocking the request thread. The same thread, if released faster, could have been used by some other requests. This is avoided by implementing the asynchronous method. Similarly on the server side also, it allows the server to suspend the original request thread and create a new thread for responding to an asynchronous request. Due to the above-said reasons, the implementation will ensure high throughput, responsiveness, and scalability. The below given process diagram will give you a clear picture of this concept. JAX-RS Asynchronous ImplementationThere are separate implementations available on the server-side and client-side for asynchronous APIs.Server-side implementation of Asynchronous processing On the server-side, the asynchronous behavior is ensured by using: AsyncResponse: This class is responsible for bridging the client-side request with the server-side methods. Using this class the server methods update the status of asynchronous processes. Based on this status the underlying logic will take appropriate action. The resource method that is running a long process should call AsyncResponse.resume() so that a response can be sent back to the client. @Suspend: This annotation is used to instruct the container to inject the AsyncResponse method and invoke it asynchronously. The resource methods called with AsyncResponse instance will be in the suspended state. One important thing to remember here is that the resource method that is annotated with @Suspend will not be called using a separate thread. It is the responsibility of the programmer to create a new thread for the long-running process and return the caller thread. One more thing to remember here is to specify a time-out period using AsyncResponse.setTimout(). This will ensure that the client will get back an HTTP 503 (Service Unavailable ) response, in case there are some issues on the server and the resource method could not respond. If this timeout is not specified, the client-side request will end up in a long wait. Client side implementation of Asynchronous processing The client side implementation of asynchronous call is pretty easy. The only thing you need to do is get an instance of the AsyncInvoker. This can be done by executing async() function on an instance of Invocation.Builder class. Let us see an example here:Client restClient = ClientBuilder.newBuilder().build();WebTarget URL = restClient.target(“https://api.example.com/search/menu?query=pasta”);Invocation.Builder requestBuilder = URL.request();AsyncInvoker asyncInvoker = requestBuilder.async();Future futureResponse = asyncInvoker.get();Response apiResponse = futureResponse.get(); String responseBody = apiResponse.readEntity(String.class);In the above example, the highlighted portion explains how to use the asynchronous call on the client-side. Summary There are lots of features in JAX-RS that help for rapid request-response processing. But the asynchronous feature implementation in JAX-RS helps a developer to give a time lag between request and response processing. This is very useful especially when there is heavy server-side processing required on certain client requests.
JAX-RS Miscellaneous

JAX-RS Miscellaneous

by Vibrant Publishers on Nov 02, 2021
Introduction REST APIs serve as the backbone of millions of web applications. This is one of the most commonly used web service standards in today’s world. The JAX-RS provides the REST support in Java and has lots of features that help us build scalable web services. In this article we are going to explore some of the JAX-RS features that are important to know while building a web service. Bootstrapping a JAX-RS applicationIt is very simple to start a JAX-RS application. All you need to do is to create a subclass of  javax.ws.rs.core.Application on your classpath. The below given sample explains how you will do that:                                                                        import javax.ws.rs.core.Application; @ApplicationPath(“api”) public class SampleWebAPIApplication extends Application           {       } The annotation @ApplicationPath provides the context root for all your APIs. In this case the APIs will have a URI starting with ‘/api’. So if you have an API to provide employee details, the URI will look like “http://www.example.com/api/v2/employee/” here the “/v2/” stands for versioning. It’s always a good practice to include versioning while creating APIs. This will be helpful when you want the same resource in custom APIs for different clients. Defining  REST endpointsThe REST endpoints serve as the connection point with the client. The JAX-RS specification has given the @Path annotation to map each HTTP (PUT, DELETE, POST, GET)  method to a java method. Consider the following example:                                                                                 public class EmployeeDatabse {  @GET  @Path(“/{id}”)    public Response getNameById(@PathParam(“id”) Long id,      @QueryParam(“name”)    @DefaultValue(“”) String name) {   @POST       public Response getNameById(Employee employee, @Context UriInfo uriInfo) {  // …  }       // …     } Here the entire class is mapped to “/employee” with different HTTP methods. The @PathParam is used for getting the value of a path variable and the @QueryParam is used for retrieving values for a query parameter of a URL.JAX-RS Providers Providers are extensions of JAX-RS that are responsible for providing functionality to the JAX-RS runtime. Mainly two types of providers are there. Exception mapping providers and Entity providers. Exception Mapping ProvidersThese are responsible for mapping services between JAX-RS response and Java exceptions. The ExceptionMapper interface is provided when a resource method throws a runtime exception. The response provided by these exception mappers are treated as same as the response provided by the resource methods. Entity ProvidersEntity providers provide marshalling / unmarshalling service between Java types and the resource representations (XML/JSON etc.). The MessageBodyReader interface is an entity provider that is used for deserializing a resource representation into a Java type. The reverse operation is performed by another entity provider interface named MessageBodyWriter. Exception Handling The exceptions that are thrown by a resource method are caught by the JAX-RS runtime and they are converted into error responses. By default they are converted into a “HTTP 500 – Server Error” message. There are two ways in JAX-RS to deal with exceptions, the first method is to throw “WebApplicationException” that can customize error response messages. The second method is to use the built in response mechanism of the JAX-RS runtime that will send a default Response to the client when an exception is caught. Summary When dealing with REST implementation using JAX-RS, there are some points that one must know to make use of its full potential. These concepts discussed here will help you build web services that conform to the REST principle.    
Spring REST Exception Handling

Spring REST Exception Handling

by Vibrant Publishers on Oct 29, 2021
Introduction Like in any other field, API development is also prone to errors. We might encounter undesired outputs while working with web services. The success of a developer lies in handing these errors gracefully. This is one of the main topics that a web service developer must understand. In this article, we will be discussing how the Spring framework handles REST API exceptions.   Spring Boot Exception Handling The below-given diagram will provide an overview of the exception handling process in the Spring Boot environment.     Usually, the default response for any error would be an HTTP 500-Internal Server Error message to the client. This wouldn’t be the right message that a client would want to see. We can make the message to the client more verbose and with proper HTTP status codes so that it won’t create any panic.   Types of exception handling There are mainly three ways in which Spring Boot exceptions are handled. Using Http Status Codes with Response Entity Using @ExceptionHandler Annotation Custom exception class with @ResponseStatus Let us have a look into each of these in detail: Using Http Status Codes with Response Entity As we have said, the default error response would be to throw an HTTP 500- Internal Server Error. But we can set the correct HTTP status code and message for exceptions, like HTTP 404 – Resource Not Found. But for doing this we must be using the @ResponseEntity annotation. This will provide us the flexibility to make custom messages and status codes in the response header.   Using @ExceptionHandler Annotation In this method, we declare a custom method to handle exceptions on the controller itself. The custom method will return a void and also will implement the @ExceptionHandler annotation. Here we have to map this method to the HTTP exception status and for that, we will use the @ResponseStatus annotation. The response status annotation will take two arguments. The first argument will define the HTTP status code corresponding to the exception and the second argument defines the reason for the current exception. This message will be sent to the client in JSON /XML format as a response message.   Custom exception class with @ResponseStatus In this method, we will create a custom exception class. This class will extend the Java exception class. When an exception occurs in the web service, the controller will throw this custom exception class. This custom exception class must be mapped to the corresponding HTTP error code. This can be done using the @ResponseStatus annotation.   Summary As we have seen, there are different ways by which one can handle the exceptions that occur in web services. It is the choice of the developer to go with one option. There can be scenarios in which one would use a combination of all the given options. But the important task is to handle the exception properly along with providing clear information to the client.  
Spring REST Basics

Spring REST Basics

by Vibrant Publishers on Oct 20, 2021
Introduction Spring is a popular Java application framework. The spring framework is based on a principle called dependency injection which allows developers to build completely decoupled systems. This framework supports all Java features and also there are extensions for this framework that allows us to build web applications leveraging the JavaEE platform. In this article, we are exploring the basics of REST implementation in the Spring framework.   Spring and REST The REST API specification in the Java world is known as JAX-RS. Spring framework has included this specification and is available under the Spring Web package. The spring framework has support for other Java REST implementations like Jersey as well. Within the Spring framework, there are two ways we can implement the REST web services. Spring MVC: Uses the traditional model-view-control method. Configuration heavy. The below given diagram will provide an idea about the MVC model. This is a typical multi layered approach for handling REST requests and responses.   SpringBoot: Leverages the HTTP message converters. More modern (Spring 3.0) and easy to implement. We will be using SpringBoot for developing our REST applications using Spring. Setting up  a Spring REST application When we develop applications using the Spring framework, it’s a good practice to use the Spring Initializr page. This will help you define the project with all dependencies and generate your project configuration file that will save a lot of your project setup time. All the REST applications using SpringBoot will have a SpringWeb dependency that we will choose while creating the project using the Spring Initializr. There are two build systems available here. Gradle and Maven. Gradle will generate a build configuration file namely build.gradle and Maven will use the pom.xml file for build configurations. All your dependencies and external libraries must be included in this file. We will be using the Gradle build system here. In the configuration, first thing you have to include is the Spring Boot Starter Web dependency. In Gradle it will look like the following: #compile(‘org.springframework.boot:spring-boot-starter-web’ The complete configuration file for the Gradle build will look like something as given below: buildscript {    ext {       springBootVersion = ‘2.2.6.RELEASE’    }    repositories {       mavenCentral()    }       Dependencies{         classpath(   “org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”  )    } } apply plugin:’org.springframework.boot’ apply plugin:’java’ apply plugin:’eclipse’ group = ‘com.example’ version = ‘0.0.1-SNAPSHOT’ sourceCompatibility = 1.8 repositories {    mavenCentral() } Dependencies{    compile( ‘org.springframework.boot:spring-boot-starter-web’ )    testCompile( ‘org.springframework.boot:spring-boot-starter-test’ ) }   Basic Annotations Before we start building the REST application using Spring, let us understand some of the annotations that we will be using in the process. Rest Controller The @RestController annotation is used for including the main artifact of the RESTful API in our code. This is also responsible for providing JSON, XML responses and any other custom responses. Request Mapping @RequestMapping annotation is used for defining the URI to access the endpoints. We will use a request method for consuming and producing resources. The default request method is GET. Path Variable When we need to set a custom request URI. The annotation @PathVariable will be specific to each resource and can have dynamic values. Request Body When we send a request the content type of the request is mentioned using @RequestBody annotation. Request Parameter The @RequestParam annotation is used for extracting parameters from the request URL. This parameter must be included while we send a request. Summary The Spring framework is an enterprise application development framework for Java. The JAX-RS specifications for REST web services are well integrated with Spring and are available with many rich features. The SpringBoot package is the modern implementation in Spring that can be used for creating REST applications with ease and flexibility.  
10 Most Likely Asked SAS Interview Questions And Answers

10 Most Likely Asked SAS Interview Questions And Answers

by Vibrant Publishers on Oct 14, 2021
Globalization brought consumers a plethora of choices to choose from in products as well as boosted e-commerce. This has now increased competition as well. As the companies aim to maximize their profits, they seek to know consumer behavior or track their profits. That’s where the Statistical Analysis System comes to the scene. With each company racing to clock maximum sales the search for a person skilled in SAS is the need of the hour, thus giving a huge scope to this industry. As per studies from payscale, SAS boasts of a massive 6.1% average pay boost which makes this job profile highly valuable. Cognizant, Tata Consultancy Services, Accenture, and GlaxoSmithKline are among the leading companies that who look for professionals talented in SAS to bring value to their company by assuming the role of an SAS Programmer, a Customer Analytics Manager, or an SAS Analyst among many others. With large pay figures along with proper employee care this can be the job of one’s dreams. However, dreaming can give only a motive. With the main task being cracking the interview, this blog, containing the most often-asked questions related to SAS, will surely assist you in your interview prep. Listed below are some questions that are most often asked by interviewers: 1:How do SQL Views help better efficiency? Answer: A View typically consists of a subset of the entire table and hence is more efficient, as it accesses a smaller set of data which is required. View also lets you hide the sensitive columns and complex queries from the user by choosing only what needs to be shown. Views always fetch fresh data from the table as they do not store any data. 2: Explain the SASFILE statement. Answer: The SASFILE statement loads the SAS data file into the memory to be available further to the program. With SASFILE you can free the buffers. Instead, the file is loaded and kept in the system memory with a pointer in the program to access it. The following example explains the use of SASFILE in a simple way. The SASFILE statement opens the data set MyExam.MyClinic and allocates the buffer. It reads the file and loads it into the memory so that it is available to both the PROC PRINT as well as the PROC MEANS step. Finally, the SASFILE data file is closed with the CLOSE statement and the buffer is cleared.                                                                        sasfile MyExam.MyClinic load;   proc print data= MyExam.MyClinic     var. Serial No result;   run;   proc means data= MyExam.MyClinic;   run;     sasfile MyExam.MyClinic close;                                                           3: What is the main difference between an SAS data file and an SAS data view? Answer: The SAS data file and the SAS data view are both SAS data sets. The main difference is that the SAS data file contains both descriptor information and data values. Descriptor information refers to the details of the data set like the name of the data set, number of observations, number of variables, and attributes of variables. The data view contains only descriptor information about the data and does not contain the values. The data view also contains information about how to retrieve the data. 4: What are the main disadvantages of using BY-group processing with an index? Answer: The main disadvantages of using BY-group processing with an index are as follows: a) This requires storage space for index which results in more utilization of disk space b) It is less efficient than sequentially reading a sorted data set as this requires retrieving the entire file to process the data. 5: Explain the significance of the EQUALS option. Answer: The EQUALS option is used to determine the order of observations in the output data set. It is normally used with NODUPRECS or NODUPKEY and it affects which observations are removed. Example: In the following program the value of EQUALS option is used. The use of the NODUPKEY option causes the elimination of observations with the same BY variable value. Since the option EQUALS is used, the order of observations remain the same in both the input data set and output data sets. NOEQUALS do not preserve the same order in the output data set.                                                            proc sort data = exam.results nodupkey equals;   by id;   run;   6: How do you select the variables and control the order in which they appear while creating a list report? Answer: This can be achieved by using the VAR statement in PROC PRINT. Example:                                                                             proc print data= exam.questionset2;   varslno quest1 quest2 quest3;   run;   7: Which keyword is used in the VALUE statement to label the missing value? Answer: The keyword OTHER is used in the VALUE statement to label the missing values as well as unknown values. Example: The following program creates a format – Questfmt. The VALUE statement creates a format Questfmt to assign the descriptive labels. The values which do not fall in the range 1-300 as well as missing/unknown values are labelled using the keyword OTHER.                                                                             proc format lib=library;   value Questfmt   1-100=’initial’;   101-200=’middle’;   201-300=’final’   other=’unknown’;   run;            8: What is the difference between the default output produced by PROC MEANS and PROC SUMMARY? Answer: The results which are produced by PROC MEANS and PROC SUMMARY are the same. But the default output produced is different. PROC MEANS produces a report by default while PROC SUMMARY produces an output data set by default.   9: Explain the significance of the function MDY. Answer: MDY is a function which is used to create a date. It takes month, day and year as input and returns a date value. Example: The following program uses the MDY function to create a date from the input values. The function calculates the date value, March 27, 2012 and assigns it to the date variable.                                                               data exam.questionset4;     set exam.set3;   date= mdy(3, 27, 2012);   Run;         10: Define nonstandard numeric data. Answer: Nonstandard numeric data can be defined as the data which contains: a) special characters such as percentage signs, dollar signs, and commas b) date value or time value c) data in fraction, binary and hexadecimal form Along with these questions, make sure to check out the questions in our Job Interview Questions Book Series, which contains books like HR Interview Questions You’ll Most Likely Be Asked (Third Edition) and Leadership Interview Questions You’ll Most Likely Be Asked. Good luck with your job hunt!