Wednesday, March 7, 2018

AutoSizeColumn effects on performance in Apache POI

AutoSizeColumn effects on performance in Apache POI

autoSizeColumn() method of apache poi is used to resize the column according to its content length. The most common mistake is to use this method every time, you write some value in a column. e.g. If I need to write 15k rows in excel and call this method is every cell in that iteration, then it will take you forever to write that file. autoSizeColumn() is clearly too slow if used in writing of each cell and resizing it.

Solution:- Write all the data in excel. Then on final excel call this method once in every column. It will resize the data of a column in one go. You will see a drastic change in performance of writing excel.

How to Start a jar as background process | nohup Command

To Start a jar as background process
 In case we want to start a service using a java jar, without associating it to current terminal command is:-


nohup java -jar user-demo.jar  &
nohup will start the jar as background process.  

nohup java -jar user-demo.jar  & > output.txt
output of process will be written to output.txt in current directory where command was executed.

Directly starting the jar with java -jar command will attach the process to the current terminal. As soon you log out from the terminal or get disconnected from the window, the process will be killed. If you are deploying a jar on the remote server, you need to start it as a background process.

Using '&' will return you immediately to current terminal and will print the process id number.

Prefixing any command with nohup prevents the command from being terminated when you exit the shell.




How to install R Packages

Install R Packages:- R should be already installed on your system. 
To install R Packages, execute below commands:

sudo R

install.packages('PackageName', dep = TRUE)
e.g. if you want to install dbscan package.
install.packages('dbscan', dep = TRUE)

Parameter dep true means, it will also install transitive dependencies of current package.


 

How to Check History of a file in Git

Check History of a file in Git:-
It's very simple to check changes made in particular file through command line tool

gitk Path-to-file
e.g. gitk /home/username/projects/Demo/PDFUtil.java

 Path-to-file can be complete path or relative path to any file.
Note:- you need to have git version control system installed on your system.



HTML To PDF Generation in Java

HTML To PDF Generation in Java:- Below code snippet will help in generating the Pdf file from HTML Code. It will convert the HTML to PDF and save the file on your system. This code can be used according your requirement.

Maven Dependency:-
   <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itextpdf</artifactId>
        <version>5.4.1</version>
    </dependency>

    <dependency>
        <groupId>com.itextpdf.tool</groupId>
        <artifactId>xmlworker</artifactId>
        <version>5.4.1</version>
    </dependency>

Java Class:-

package com.mettl.certification.systemAdmin.web.controller;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;

public class HTMLToPdfUtil {
   
    /**
     * This method accepts the
     * @param html code that will be written to PDF.
     */
    public static void createPDF(String html) {
        try {
            //Path to file system, where file will be saved.
            OutputStream file = new FileOutputStream(new File("/home/HTMLtoPDF.pdf"));
            Document document = new Document();
            PdfWriter writer = PdfWriter.getInstance(document, file);
            document.open();
            StringBuffer str = new StringBuffer();
            str.append("<html><head><title>PDF</title></head><body>");
            str.append(html).append("</body></html>");
            InputStream is = new ByteArrayInputStream(str.toString().getBytes());
           
            XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
            document.close();
            file.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
   
    public static void main(String args[]) {
        HTMLToPdfUtil.createPDF("Test Content");
    }
}

Tuesday, March 6, 2018

Google OAuth API Client 2.0 java Library

Purpose: This doc provides java code for OAuth 2.0 functions offered by the Google OAuth Client Library for Java. 

To start using Google APIs for google Auth, a project needs to be setup on the Google API Console for auth, Your application can be a mobile application or web server etc.

Reference Documentation:- https://support.google.com/cloud/answer/6158849?hl=en&ref_topic=6262490

 
You will get Client id and client secret key after following above steps in google developer console.


Google OAuth authorization code flow for Java

Jsp Page:- This page will call the controller to get the redirect URL for google, where user will get authenticated and return to Succes redirect url provided by our application.
<form:form id="formAuth" action="loginGoogleAuth" name="loginGoogleAuth" >
        <p><strong>Proceed for Authentication via Google</strong></p>
        <br/><div> <button type="submit" id="submitButton">Sign In</button></div>
        </div>
 </form:form>
Contoller:- Google API does not return user info directly into response on successful redirection. So we need to call 2 apis, one to get authtoken using auth code and Second using authtoken user details can be fetched.

 "/loginGoogleAuth" method will return the google redirect uri.
@RequestMapping(value = "/loginGoogleAuth", method = { RequestMethod.POST, RequestMethod.GET })
    public String loginGoogleAuth(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
        return "redirect:" + googleOAuth2LoginService.getOAuthURL();
    }

"/googleOAuth2callback" will be called if authentication is successful with google. In Response call, we get auth code, that will be used to get the auth token from goggle using auth api. Then using this auth token, We can fetch basic user details from google.    
 @RequestMapping(value = "/googleOAuth2callback", method = { RequestMethod.POST, RequestMethod.GET })
    public String googleOAuth2callback(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws IOException {
        String errorCode = request.getParameter("error");
        if (errorCode != null) {
            LOG.info("failure in login");
            return "login";
        }
        String returnUrl = request.getParameter(RETURN_URL);
        String authCode = request.getParameter(AUTH_CODE);
        try {
             GoogleUserDetails user = oauthService.authenticateWithGoogleOverOAuth2(authCode);
        // create a user if required. Initiate the session for this user.
        } catch (Throwable t) {
            LOG.info("failure in login", t);

            return "login";
        }
    }
Service:- 
public class GoogleOAuth2Service {
    private static final Logger LOG = LoggerFactory.getLogger(GoogleOAuth2Service.class);

    private String userInfoUrl="https://www.googleapis.com/oauth2/v2/userinfo";
    private String authUrl="https://accounts.google.com/o/oauth2/v2/auth";
    private String tokenUrl="https://www.googleapis.com/oauth2/v4/token";
    private String redirectUri="http://googleoauthdemo.com/googleOAuth2callback";
    private String clientId="Client_Id";
    private String clientSecret="Client_Secret_Key";
    public String getOAuthURL() {
          StringBuilder oauthUrl = new StringBuilder().append(authUrl).append("?client_id=").append(clientId)
                .append("&response_type=code")
                .append("&scope=openid%20email+https://www.googleapis.com/auth/userinfo.profile")
                .append("&redirect_uri=" + redirectUri);
        return oauthUrl.toString();
    }
   
    public GoogleUserDetails authenticateWithGoogleOverOAuth2(String authCode) throws IOException {
        String accessToken = getOAuthToken(authCode);
        GoogleUserDetails googleUserDetails =
ERRORgetUserDetailsAccessToken(accessToken);
        return googleUserDetails;
    }

    public String getOAuthToken(String code) throws IOException {
        ImmutableMap<String, String> requestParameters = ImmutableMap.<String, String> builder().put("code", code)
                .put("client_id", clientId).put("client_secret", clientSecret).put("redirect_uri", redirectUri)
                .put("grant_type", "authorization_code").build();

       String body = _sendPostRequest(tokenUrl, requestParameters);
        Map<String, String> postResponse = jsonConverter.convertJsonToMap(body);
        return postResponse.get("access_token");
    }

    public GoogleUserDetails getUserDetailsAccessToken(String accessToken) throws IOException {
        LOG.trace("Fetching User Details from Google using access Token: {}", accessToken);
        String userDetailsAsJson = _sendGetRequest(
                new StringBuilder(userInfoUrl).append("?access_token=").append(accessToken).toString());
        LOG.debug("user info {}", userDetailsAsJson);

        Map<String, String> userDetailsAsMap = jsonConverter.convertJsonToMap(userDetailsAsJson);
        return GoogleUserDetails.buildFromMap(userDetailsAsMap);
    }

      private String _sendGetRequest(String url) throws ClientProtocolException, IOException {
        return _sendHttpRequest(new HttpGet(url));
    }
       private String _sendPostRequest(String url, Map<String, String> formParameters)
            throws ClientProtocolException, IOException {
        HttpPost request = new HttpPost(url);

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        for (String key : formParameters.keySet()) {
            nvps.add(new BasicNameValuePair(key, formParameters.get(key)));
        }
        request.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
        return _sendHttpRequest(request);
    }
    private String _sendHttpRequest(HttpRequestBase request) throws ClientProtocolException, IOException {
        LOG.info("Sending Request to Google");
        HttpClient httpClient = new DefaultHttpClient();
        HttpResponse response = httpClient.execute(request);

        HttpEntity entity = response.getEntity();
        String body = EntityUtils.toString(entity);
        LOG.info("Response body>>" + body);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Expected 200 but got " + response.getStatusLine().getStatusCode() + ", with body " + body);
        }
        return body;
    }

}
 public class GoogleUserDetails {
    public static final String PROP_FAMILY_NAME = "family_name";
    public static final String PROP_GIVEN_NAME = "given_name";
    public static final String PROP_EMAIL = "email";
    private String email;
    private String firstName;
    private String lastName;
    private GoogleUserDetails() {
    }

    public static GoogleUserDetails buildFromMap(Map<String, String> userDetails) {
        GoogleUserDetails gud = new GoogleUserDetails();

        gud.setEmail(userDetails.get(PROP_EMAIL));
        gud.setFirstName(userDetails.get(PROP_GIVEN_NAME));
        gud.setLastName(userDetails.get(PROP_FAMILY_NAME));

        return gud;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
 
}