Configure HTML/JavaScript

Tuesday, September 12, 2017

Forcing user to add license comment in Code file and preventing users to use specific words in project code

There are many use cases and projects where we want to place license in all the file as comment at the top of the file or bottom file. If one of the file missed or wrong license text is placed, it might be a problem for legal team or any legal action will dependent on this.

In this situation is really good idea to to check before you commit your code to repository that license text is there in all files. Yap! you got it, we need to place a pre-commit hook in our repository so that any file does not have that, we will not allow them to push code to repository.


pre-commit hook 

There is a great module available in npm which does all in perfect way we want. Only thing is we have to tell him what we need to do.

So the idea is to place a pre-commit hook and assign some node script before code can be commited to the repository. so install pre-commit in your project as dependencies

npm install --save-dev pre-commit

https://www.npmjs.com/package/pre-commit


Hooking the script in pre-commit

Finding license test in all files


Now it time to fine license test in all the file. The below node script will happly do that for us and will let us know which file does not have the license text

(function () {
  var fs = require('fs');
  var glob = require('glob-fs')();
  var path = require('path');
  var result = 0;
  var exclude = ['LICENSE',
    path.join('e2e', 'util', 'db-ca', 'rds-combined-ca-bundle.pem'),
    path.join('src', 'favicon.ico')];
  var files = [];
  files = glob.readdirSync('**');
  files.map((file) => {
    try {
      if (!fs.lstatSync(file).isDirectory() && file.indexOf('.json') === -1 
           && exclude.indexOf(file) === -1) {
        var data = fs.readFileSync(file, 'utf8');

        if (data.indexOf('Copyright 2017 candifood contributors') === -1) {
          console.log('Please add License text in coment in the file ' + file);
          result = 1;
        }
      }
    } catch (e) {
      console.log('Error:', e.stack);
    }
  });
  process.exit(result);
})();




Now this script can be executed by node to find the license text in all file. 
Now its time to hook it in the pre-commit.

Hooking the script in pre-commit

To hook the script in pre commit we need to create a script in package.json and tell
the pre-commit to use that before pre-commit.
{
  "name": "project-name",
  "version": 1.0.0",
  "license": "Apache 2.0",
  "scripts": {
    "license-check": "node license-check",
  },
  "private": true,
  "dependencies": {
  },
  "devDependencies": {
    "pre-commit": "1.2.2",
  },
  "pre-commit": [
    "license-check"
  ]
}

Thats all! When we commit the code the pre-commit will call the node script 
and it will stop if any file there is no license test.


Check if company confidential information is placed in code

Now its time to check if any specific company information is there in the code in same pre hook.
So we will add another hook in the pre-commit and to check that.
So the new package.json will be
{
  "name": "project-name",
  "version": 1.0.0",
  "license": "Apache 2.0",
  "scripts": {
    "license-check": "node license-check",
    "license-check": "node prevent-secret",
}, "private": true, "dependencies": { }, "devDependencies": { "pre-commit": "1.2.2", }, "pre-commit": [ "license-check",
    "prevent-secret"
] }

Prevent secret code

Now the below wcript will be executed after license check in pre-commit and will tell us
if any keyword is confidential word is used in our code which may cause problem when the code will go to outside.
(function () {
  var fs = require('fs');
  var glob = require('glob-fs')();
  var path = require('path');
  var result = 0;
  var exclude = [
    'LICENSE',
    path.join('e2e', 'config', 'conf.e2e.json'),
    path.join('src', 'favicon.ico')
  ];
  var files = [];
  files = glob.readdirSync('**');

  var patternString = [
    // 'i am oeky',    // 'famous',    'secret',
    'moana'  ];

  files.map((file) => {
    try {
      if (!fs.lstatSync(file).isDirectory() && exclude.indexOf(file) === -1) {
        fs.readFileSync(file).toString().split(/\r?\n/).forEach(function(line){
          patternString.map((pattern) => {
            if (line.indexOf(pattern) !== -1) {
              console.log('' + file + ': `' + pattern + '` in line [' + line +']');
              // result = 1;            }
          });
        });
      }
    } catch (e) {
      console.log('Error:', e.stack);
    }
  });
  process.exit(result);

})();

So we all set! And its really batter then put a search query  manually and find all these words. Here we will do all them even before our code to go to repository.

if this did not solve your problem, put comment your case and I will try to resolve that.

Thursday, March 9, 2017

Upgrading from angular 2 to angular 4 (now in 4.0.0-rc.2)



Angular 4.0.0-rc.2 released:


The new version if angular will be 4.0.0 and google is already in the path to make it happen. The main reason to upgrade is angular router is ahead of normal angular which now in 2.4.9 version and the router is in 3.x.x version. To make a single version, the new angular 4 is coming

Of course, this will not be the only change in the new version!

Typescript:
Now the typescript 2.1.5 is minimum requirement for the angular 4.0.0 on wards

What might be the new changes


most probably these will be the new changes


 - Ahead of Compilation will be measure changes and it will be the default.
 - Angular cli is moved to @angular/cli and its now in rc.1 version
 - The angular cli default build will reduce the file size drastically less
 - changed most of the types from classes to interfaces


How to generate angular 4.x.x-rc.x project with cli:

You just need to pass --ng4 to tell cli to generate an angular 4 project.

the command will be  ng new appName --ng5 -style=scss

Let me know if nay question!!

Thursday, April 14, 2016

How to add request body to http Delete method


Http Methods methods:


While consuming web services, many tume we need to call http put, delete, get, post methods. While calling http het and post methods are regularly used and you need minimal configuration, put, delete, etc methods some time confuse developer.

Problem with Http Delete methods:


In case of http delete methods, we cannot send request body if your are using http client. it does not allow to do as there is no methods avaialble.

You will face this problem in case you are developing an application where you web service end point need some data in the delete methods and in clent there are no ways to do that.

Soloutions:


The solution is to extend the http post method and change the method to DELETE while sending data. One of the easiest way I would suggest is as below.

Extend the HttpPost method and change the method to DELETE as below and then create the object of HttpPost rather HttpDelete.


Monday, April 11, 2016

How to remove java 1.8 from class path and set java 1.7 in windows 10



Windows 10 degrading from java 1.8 to java 1.7


I have been developing a project which is on google app engine and java sdk 1.7. When I upgraded to windows 10 from my windows 7 machine, the by default java verion was jre 1.8 and when ever I have bed executing any task, the version miss matching was happening.

JDK:

 jdk and jre are 2 different thing. The jdk is responsible to compile your java code using javac compailer and generate .class file which contains java byte code which is executed in jvm(java virtual machine)

JRE:

jre is something which execute the class file and guve you the result. any operating system gives you jre not jdk as jre executes most of the internal java codes


How to chge default windows 10 jre version from java 1.8 to 1.7



In windw 10, the C:\Windows\System32 (c:\Windows\SysWOW64 folder if you have x64 system [Win 7 64 bits]) folder contains java.exe, javaw.exe and javaws.exe which is dafault java execution and any call path you will set for the java will not over ride it as these are highest priority in windows.To set you default path to java jre 1.7 you need to delete them. may be you can take a backup in case you want to come back to jre 1.8.then what ever class path jre and jdk is available, it will point to you java version in your machine.


Sunday, August 3, 2014

Making Http call from core java - different ways

There are many ways we make http calls to web server in many situation. We application server always receives requests in many forms and send back response in many forms.

Now a days there are a lots of framework, library available to kame http call easy to the web server like Spring, Struts, Ajax, etc.

 But if the requirement is simple and need just a simple and light weight http call to the server, you will not like to use these heavy library which comes will many extra functionality which you dont need. In this case the best way is to use the inbuild hava http functionality to get response data from the web server.

below are few example which will help you to understand batter

Using HttpConnect

conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod(method);
conn.setRequestProperty("X-DocuSign-Authentication", httpAuthHeader);
conn.setRequestProperty("Accept", "application/json");
if (method.equalsIgnoreCase("POST")) {
  conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  conn.setRequestProperty("Content-Length", Integer.toString(body.length()));
            conn.setDoOutput(true);
}


status = conn.getResponseCode(); // triggers the request
if (status != 200) { //// 200 = OK 
    errorParse(conn, status);
    return;
}

InputStream is = conn.getInputStream();

Another way is using HttpPost
  try {
   // 1. create HttpClient
   HttpClient httpclient = new DefaultHttpClient();

   // 2. make POST request to the given URL
   HttpPost httpPost = new HttpPost(authUrl);

   String json = "";

   // 3. build jsonObject
   JSONObject jsonObject = new JSONObject();
   jsonObject.accumulate("phone", "phone");

   // 4. convert JSONObject to JSON to String
   json = jsonObject.toString();

   // 5. set json to StringEntity
   StringEntity se = new StringEntity(json);

   // 6. set httpPost Entity
   httpPost.setEntity(se);

   // 7. Set some headers to inform server about the type of the
   // content
   httpPost.addHeader("Accept", "application/json");
   httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");

   // 8. Execute
   HttpResponse httpResponse = httpclient.execute(httpPost);

   // 9. receive response as inputStream
   inputStream = httpResponse.getEntity().getContent();
   String response = getResponseBody(inputStream);
   
   System.out.println(response);

  } catch (ClientProtocolException e) {
   System.out.println("ClientProtocolException : " + e.getLocalizedMessage());
  } catch (IOException e) {
   System.out.println("IOException:" + e.getLocalizedMessage());
  } catch (Exception e) {
   System.out.println("Exception:" + e.getLocalizedMessage());
  }

Thursday, January 9, 2014

Updating column 1 or column 2 with value of same column value or different column value of same table

Some time we need to change values of columns of same row of a table.

update  table_name set column1 = column2

you can also put some arithmetic calculation and update table as well. the above query will take the value of column2 and will store it in the column1 of the same row of same table.

Friday, October 25, 2013

UNIX Command file lists order by file size

below command will list all files in a folder order by file size.

ls -l | sort +4rn |awk '{print $9, $5}'