Java tricky interview question

1.public class Test2 {
public static void main(String[] args) {
method(null);
}
public static void method(Object o) {
System.out.println(“Object impl”);
}
public static void method(String s) {
System.out.println(“String impl”);
}
}

output : String impl
As we know that we can assign null to any object, so doesn’t compiler complains about this program? According to java specs, in case of overloading, compiler picks the most specific function. Obviously String class is more specific that Object class, hence it will print “String impl”.

2.long longWithL = 1000*60*60*24*365L;
long longWithoutL = 1000*60*60*24*365;
System.out.println(longWithL);
System.out.println(longWithoutL);

output :
31536000000
1471228928

HTTP GET,POST,HEAD,PUT,DELETE IN angularjs

What is HTTP?
The Hypertext Transfer Protocol (HTTP) is designed to enable communications between clients and servers.

HTTP works as a request-response protocol between a client and server.

A web browser may be the client, and an application on a computer that hosts a web site may be the server.

Example: A client (browser) submits an HTTP request to the server; then the server returns a response to the client. The response contains status information about the request and may also contain the requested content.

HTTP Methods
GET
POST
PUT
HEAD
DELETE
PATCH
OPTIONS
The GET Method
GET is used to request data from a specified resource.

GET is one of the most common HTTP methods.

Note that the query string (name/value pairs) is sent in the URL of a GET request:

/test/demo_form.php?name1=value1&name2=value2
Some other notes on GET requests:

GET requests can be cached
GET requests remain in the browser history
GET requests can be bookmarked
GET requests should never be used when dealing with sensitive data
GET requests have length restrictions
GET requests is only used to request data (not modify)
The POST Method
POST is used to send data to a server to create/update a resource.

The data sent to the server with POST is stored in the request body of the HTTP request:

POST /test/demo_form.php HTTP/1.1
Host: w3schools.com
name1=value1&name2=value2
POST is one of the most common HTTP methods.

Some other notes on POST requests:

POST requests are never cached
POST requests do not remain in the browser history
POST requests cannot be bookmarked
POST requests have no restrictions on data length

The PUT Method
PUT is used to send data to a server to create/update a resource.

The difference between POST and PUT is that PUT requests are idempotent. That is, calling the same PUT request multiple times will always produce the same result. In contrast, calling a POST request repeatedly have side effects of creating the same resource multiple times.

The HEAD Method
HEAD is almost identical to GET, but without the response body.

In other words, if GET /users returns a list of users, then HEAD /users will make the same request but will not return the list of users.

HEAD requests are useful for checking what a GET request will return before actually making a GET request – like before downloading a large file or response body.

The DELETE Method
The DELETE method deletes the specified resource.

The OPTIONS Method
The OPTIONS method describes the communication options for the target resource.

Difference between using MockMvc with SpringBootTest and Using WebMvcTest

@SpringBootTest annotation tells Spring Boot to go and look for a main configuration class (one with @SpringBootApplication for instance), and use that to start a Spring application context. SpringBootTest loads complete application and injects all the beans which is can be slow.

@WebMvcTest is only going to scan the controller you’ve defined and the MVC infrastructure. That’s it. So if your controller has some dependency to other beans from your service layer, the test won’t start until you either load that config yourself or provide a mock for it. This is much faster as we only load a tiny portion of your app. This annotation uses slicing.

this is for testing the controller layer and you need to provide remaining dependencies required using Mock Objects.

Format currency in Angular 2

In Angular, to format a currency, use the currency pipe on a number as shown here.

<tr *ngFor=”#item of data”>
<td><a href=”#”>{{item.invoiceNo}}</a></td>
<td>{{item.invoiceDate}}</td>
<td>{{item.invoiceStatus}}</td>
<td class=”right aligned”>{{item.invoiceTotal | currency:’USD’:true:’1.2-2′}}</td>
</tr>
The first parameter, ‘USD’, of the pipe is an ISO currency code (e.g. ‘USD’,’EUR’, etc.)
The second parameter, true, is an optional boolean to specify whether or not you want to render the currency symbol (‘$’, ‘€’); default is false
The third parameter,’1.2-2′, also optional, specifies how to format the number, using the same formatting rules as apply to the number pipe.
Note, however, that the currency pipe relies on the Internationalization API, which is not available in all browsers. See current browser support for Internationalization API.

Here’s a visual example of what the example shown above renders when used on a decimal number:

Create and Download csv in java and angular 6

java
=====
public void downloadErrorsInCSV(HttpServletResponse response, List<ErrorDto> errors) {
log.info(“DOWNLOAD_ERRORS_IN_CSV_REQ: “);

try {
response.setContentType(“text/csv”);
response.setHeader(“Content-Disposition”,
“attachment; filename=\”sales_transaction_upload_errors.csv\””);
OutputStream fout = response.getOutputStream();
OutputStream bos = new BufferedOutputStream(fout);
OutputStreamWriter outputwriter = new OutputStreamWriter(bos);

CSVWriter writer = new CSVWriter(outputwriter);

String[] headers = {“Row Number”, “Header Name”, “Error Type”, “Error Desc”};
writer.writeNext(headers);

for (ErrorDto error : errors) {
String[] errorRow = {“” + error.getRowNum(), error.getHeaderName(), error.getErrorDesc(),
error.getErrorType().name()};
writer.writeNext(errorRow);
}

outputwriter.flush();
outputwriter.close();

log.info(“DOWNLOAD_ERRORS_IN_CSV_RES: response sent”);
} catch (Exception e) {
log.error(“DOWNLOAD_ERRORS_IN_CSV_REQ: error while downloading errors in csv “, e);
}
}

Angular code started : add this in package.json and do npm intsall
===================================
“file-saver”: “^1.3.8”,

angular6 service
==============
import { Http, Response, RequestOptions, ResponseContentType } from ‘@angular/http’;
@Injectable()
export class DownloadService {
constructor(private spinnerService: Ng4LoadingSpinnerService,private http: HttpClient,private httpDownload: Http) { }

downloadErrorsInCSV(errorList){
let path = ‘/transaction/downloadErrorsInCSV’;
let options = new RequestOptions({responseType: ResponseContentType.Blob, body: errorList});
this.spinnerService.show();
return this.httpDownload.post(path, options)
.map((response: Response) => {
this.spinnerService.hide();
return response;
})
}
}

angular 6 component.ts
====================
import * as FileSaver from ‘file-saver’;

downloadErrorsInCSV(){
if(this.errorList==null || this.errorList.length==0){
return;
}
this.salesTransactionService.downloadErrorsInCSV(this.errorList)
.subscribe(
response => {
let fileName = this.getFileNameFromHttpResponse(response);
if(fileName==null){
this.notifications.error(“”,”File Download failed”,””);
}
else{
let file = new Blob([response.text()], { type: ‘text/csv;charset=utf-8’ });
FileSaver.saveAs(file, fileName);
}
},
error => {
this.spinnerService.hide();
this.notifications.error(“”,”File Download failed”,””);
});
}

getFileNameFromHttpResponse(httpResponse) {
let contentDispositionHeader = httpResponse.headers._headers.get(‘content-disposition’);
let result=null;
if(contentDispositionHeader!=undefined && contentDispositionHeader!=null){
result = contentDispositionHeader[0].split(‘;’)[1].trim().split(‘=’)[1];
result = result.replace(/”/g, ”);
}
return result;
}

angular 6 component.html
======================
<button type=”submit” title=”Export Errors”
class=”btn btn-xs btn-success” (click)=”downloadErrorsInCSV()”>Export
Errors</button>

jmeter install and start a test plan

https://www.digitalocean.com/community/tutorials/how-to-use-apache-jmeter-to-perform-load-testing-on-a-web-server

download apache-jmeter-5.0.tgz and extract and then go to bin folder in command prompt .
then type sh jmeter.sh

jmeter will start…..

steps :
1.create a plan
2.Add a Thread Group
3.Add empty HTTP Cookie Manager (for keeping connection live and login )
4.Add an HTTP Request Sampler(get or post request)
5.Add a View Results in Table Listener(to see result for all request)
6.go to httprequest and then right click add config ellement >http header manager > add content-type as application/json.
7.go to run>start

install plugin manager :
https://jmeter-plugins.org/wiki/PluginsManager/

then add 3 basic graphs from available plugin.and then u can see the graph.