Mostly used android coding

You're android developer - beginner or pro doesn't matter because below any of 13 android code you'll use in your most of project.So read it and bookmark it for faster development in Android.
Mostly used android coding, Commonly, Frequently and Daily used Android coding

How to Disable Home Button

@Override  
public void onAttachedToWindow()  
{    
    this.getWindow().setType(WindowManager.  
      LayoutParams.TYPE_KEYGUARD_DIALOG);       
    super.onAttachedToWindow();    
}  

How to Disable Back Button

@Override  
public boolean onKeyDown(int keyCode, KeyEvent event) {  
    return false;  
} 

How to Disable Soft Keypad

final EditText txtName = (EditText) findViewById(R.id.txtName);  
txtName.setInputType(InputType.TYPE_NULL);  

How to Make Static Rotation/orientation in Android

//if you want to lock screen for always Portrait mode  
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);  
                             or  
//if you want to lock screen for always Landscape mode  
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

How to Disable screen Rotation/orientation in Android (better way is java code)

//put this code in Manifest file, activity tag  
android:screenOrientation="nosensor"
android:configChanges="keyboardHidden|orientation|screenSize"

/* or even you can do it by programmatically -- just put  
Configuration code in onResume method before calling super  
like this */
@Override  
protected void onResume() {  
    int currentOrientation = getResources().getConfiguration()  
                               .orientation;  
    if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE)   
    {  
        setRequestedOrientation(ActivityInfo  
                    .SCREEN_ORIENTATION_SENSOR_LANDSCAPE);  
    }  
    else {  
        setRequestedOrientation(ActivityInfo  
                    .SCREEN_ORIENTATION_SENSOR_PORTRAIT);  
    }  
    super.onResume();  
}  

How to Disable Title Bar and Make Full Screen View

//1. put this line to manifest file in Application tag  
android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"
  
//2. put below code in your activity onCreate method  
  
//to disable notification bar (Top Bar)  
        requestWindowFeature(Window.FEATURE_NO_TITLE);          
                           
          
        //to set full screen view  
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,  
                     WindowManager.LayoutParams.FLAG_FULLSCREEN);  
          
        //make sure code should be before calling below method  
        setContentView(R.layout.main);  

How to Create Alert Dialog Box in Android

AlertDialog.Builder builder = new AlertDialog.Builder(this);  
builder.setMessage("App has been started..")  
       .setCancelable(false)  
       .setTitle("Alert Box")             
       .setNegativeButton("OK", new DialogInterface.OnClickListener() {  
           public void onClick(DialogInterface dialog, int id) {  
                dialog.cancel();  
           }  
       });  
AlertDialog alert = builder.create();  
alert.show();  

How to Create Toast message in Android

Toast.makeText(getApplicationContext(), "I am splash message..",   
  Toast.LENGTH_LONG).show();  

How to create Progress Dialog in Android

ProgressDialog dialog = ProgressDialog.show(this, "",  "Loading. Please wait...", true);  

Load Home Screen Programmatically in Android
Intent startMain = new Intent(Intent.ACTION_MAIN);  
startMain.addCategory(Intent.CATEGORY_HOME);  
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
startActivity(startMain)  

Start/Load Activity from Activity
//put this code where you want to load another Activity  
Intent intent = new Intent(FirstActivty.this, SecondActivity.class);  
  
//below 2 lines (Flags) are optional  
// 1. if set, it will clear the back stack  
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  
  
// 2. If set, this activity will become the start of a new task  
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  
startActivity(intent);  

Make a Phone Call

String mobileNo = "+9189000000";  
String uri = "tel:" + mobileNo.trim() ;  
Intent intent = new Intent(Intent.ACTION_CALL);  
intent.setData(Uri.parse(uri));  
startActivity(intent);  
  
//add permission to Manifest file  
<uses-permission android:name="android.permission.CALL_PHONE">  
</uses-permission>  

How to check WiFi is Connected or Not

public void chekcWifiConnectDisconnect() {  
  ConnectivityManager connManager = (ConnectivityManager)   
    getSystemService(CONNECTIVITY_SERVICE);  
  NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);  
  
  if (mWifi.isConnected()) {  
   Log.v("Debug", "Wifi is connectd..");     
  } else {  
   Log.v("Debug", "Wifi is not connectd..");     
  }  
  
} 

//dont forget to put Wifi permission in manifest file   
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission> 

 If you've any other code which you use frequently in your coding then comment me. I'll add in this list.

Run website on Offline mode Using UpUp Javascript Framework

It's time to start thinking offline first

Mobile First has become the de-facto standard for building modern sites. But in a world where everyone is mobile, an always-on connection isn't something we can rely on. It's time to start thinking Offline First.
upup javascript framework, javascript framework, offline script, tiny script


This tutorial will show you how to add offline functionality to your site in under 10 minutes. When you're done, your visitors will no longer be greeted with an error screen when they visit your site with no connection... Instead you'll be able to control the content and experience they get.

Let's get started

We'll start with a simple site, and add the offline features to it:
<html>
<head>
  <meta charset="UTF-8">
  <title>Lonely Globe Advisor</title>
</head>
<body>
  <h1>Top Hotels in Rome</h1>
  <ol>
    <li>Villa Domus - Via Piacenza 9, Rome, Italy</li>
    <li>Hotel Trivelli - Piazza Barberini 11, Rome, Italy</li>
  </ol>
</body>
</html>
Our sample site, Lonely Globe Advisor, offers visitors a list of the top hotels in Rome, with user ratings and an address.


But what happens if our user just landed in Rome and doesn't have a local data plan?
Well, he'll be out of luck.
Adding Basic Offline Content
We can control the experience our users get when they are offline with 2 simple steps:

Include the UpUp script in our page.

Define the content we'd like the user to see when he is offline.
<html>
<head>
  <meta charset="UTF-8">
  <title>Lonely Globe Advisor</title>
</head>
<body>
  <h1>Top Hotels in Rome</h1>
  <ol>
    <li>Villa Domus - Via Piacenza 9, Rome, Italy</li>
    <li>Hotel Trivelli - Piazza Barberini 11, Rome, Italy</li>
  </ol>
  <script src="/upup.min.js"></script>
  <script>
    UpUp.start({
      'content': '<html><body><h1>Top Hotels in Rome</h1><p>Villa Domus</p><p>Hotel Trivelli</p></body></html>'
    });
  </script>
</body>
</html>
In the code above we simply told UpUp to display some simple HTML the next time a user can't access our site.

Download demo Project

With just this tiny bit of code, we've added an offline experience for our site, and allowed our users to see the best hotels in Rome… even when they can't access the web.

How Does It Work?

UpUp uses ServiceWorkers to determine when network requests fail. A ServiceWorker is a special script that runs in the browser in the background, and can see the status of network requests.

When the user first visits your site, UpUp registers a ServiceWorker with your browser, and gives it a list of files to cache for later.

The next time the user visits your site, the ServiceWorker listens for network errors. If a network request fails, and the ServiceWorker finds that file in the cache, it will return that file, as if it came from the network.

Creating a rich offline experience

While this is already quite impressive, it still doesn't look anything like our online version. Let's improve the offline version with more content and our design.

We'll begin by moving our offline content to a separate file. This will make it much easier to update and maintain, and we'll no longer have to include the entire content of the offline site on every page.
<html>
<head>
  <meta charset="UTF-8">
  <title>Lonely Globe Advisor</title>
</head>
<body>
  <h1>Top Hotels in Rome</h1>
  <ol>
    <li>Villa Domus - Via Piacenza 9, Rome, Italy</li>
    <li>Hotel Trivelli - Piazza Barberini 11, Rome, Italy</li>
  </ol>
  <script src="/upup.min.js"></script>
  <script>
    UpUp.start({
      'content-url': 'offline.html'
    });
  </script>
</body>
</html>
Now the content our users see when they are offline, is the contents of offline.html. This is just a simple HTML file, no different than any other page on our site.

Our offline.html file contains two css files: bootstrap.min.css and offline.css. Let's make sure these are cached and available to our users when they are offline:
<html>
<head>
  <meta charset="UTF-8">
  <title>Lonely Globe Advisor</title>
</head>
<body>
  <h1>Top Hotels in Rome</h1>
  <ol>
    <li>Villa Domus - Via Piacenza 9, Rome, Italy</li>
    <li>Hotel Trivelli - Piazza Barberini 11, Rome, Italy</li>
  </ol>
  <script src="/upup.min.js"></script>
  <script>
    UpUp.start({
      'content-url': 'offline.html',
      'assets': ['css/bootstrap.min.css', 'css/offline.css']
    });
  </script>
</body>
</html>

Where Should I Place My Files?

For security reasons, the browser only lets UpUp's ServiceWorker see network requests within its scope.

The scope that the ServiceWorker can affect is determined by where you placed upup.min.js and upup.sw.min.js. For example, if you place it on https://yoursite.com/js/upup.sw.min.js, UpUp will only be able to show your offline content when users try to look at the /js/ directory.

This is why it is important to place both files on the same server as your content, and not in a subdirectory. This should idealy be in the root of your site (e.g. https://yoursite.com/upup.min.js).

Getting fancy

With just one command and two settings, we can create rich offline experiences for our users. These can be as simple as the examples above, or as robust as a full single page application using frameworks like AngularJS, with content customized for each user, videos and even files the user can access while offline.
<script src="/upup.min.js"></script>
<script>
  UpUp.start({
    'content-url': 'schedule.html?user=joe', // show this when the user is offline
    'assets': [                 // define additional assets needed while offline:
      'img/logo.png',           // such as images,
      'css/offline.css',        // custom stylesheets,
      'schedule.json?user=joe', // dynamic requests with data per user,
      'js/angular.min.js',      // javascript libraries and frameworks,
      'mov/intro.mp4',          // videos,
      'contacts.pdf'            // and more.
    ]
  });
</script>

HTTPS Only

To preserve the user's security and privacy, ServiceWorkers can only detect requests over a secure connection.

During development you can use UpUp through localhost or file (e.g. both http://localhost/ and file:///Users/tal/index.html are ok), but to deploy it to production you'll need to have HTTPS set up on your server.

This is a requirement for many new web technologies, and SSL certificates go for as little as $5, so don't let that stop you… progress is coming.

Browser Support

UpUp plays nicely with all browsers, progressively enhancing browsers that support Service Workers, while leaving users with older browsers unaffected.

UpUp currently supports Chrome 40+, Opera 27+ and Firefox 41+. If your users are using a different browser, they simply won't notice anything different.

AngularJS LazyTube directive

It is AngularJs directive which is Lightweight, responsive, lazy loaded YouTube videos  that degrades gracefully.

This AngularJS directive replaces any heavy iframes or links with a image preview that loads the player only on click. Useful when performance and page size is important or for sites with many embeded youtube videos.

For a simple example page with 10 videos, lazytube will reduce loadtime by 7x and memory usage by 2-3x.

Link

<a ob-lazytube href="http://www.youtube.com/watch?v=J---aiyznGQ">Keyboard cat</a>

Default iframe

<iframe ob-lazytube width="480" height="360" src="//www.youtube.com/embed/J---aiyznGQ" frameborder="0" allowfullscreen></iframe>

ID based

<div ob-lazytube="J---aiyznGQ">Keyboard cat</div>

Dowload Demo Example

Player Configuration

Defaults

Any default options sent to YouTube can be changed by modifying the obYoutubeConfig. Read more about which parameters you can use with the player.
angular.module('myApp', ['oblador.lazytube']).
  run(function(obLazytubeConfig) {
    //Change default player size
    obLazytubeConfig.width = 800;
    obLazytubeConfig.height = 600;

    //Disable related videos
    obLazytubeConfig.urlParams.rel = 0;

    //Disable responsive player
    obLazytubeConfig.responsive = false;
  }
);

Per instance

To acheive the same thing but to only a specific player, just add the parameters as attributes.
<a ob-lazytube href="http://www.youtube.com/watch?v=J---aiyznGQ" rel="0">Keyboard cat</a>

Responsiveness

Placeholders and the player is responsive by default. Don't forget to add width and height arguments if the aspect ratio is not 16:9.

To disable the responsiveness either add the no-responsive attribute or change the defaults as outlined above.
<a ob-lazytube no-responsive href="http://www.youtube.com/watch?v=J---aiyznGQ">Keyboard cat</a>

Custom placeholder image (instead of Youtube autogen. thumbnail)

Use your own placeholder image from your server.
<a ob-lazytube href="http://www.youtube.com/watch?v=J---aiyznGQ" ob-placeholder="images/myVideo.png">Keyboard cat</a>
<a ob-lazytube href="http://www.youtube.com/watch?v=J---aiyznGQ" ob-placeholder="{{data.myImageFile}}">Keyboard cat</a>

How to Scan Uploaded File using VirusTotal Java Library

VirusTotal is a free service that analyzes suspicious files and URLs and facilitates the quick detection of viruses, worms, trojans, and all kinds of malware.

This is project is a VirusTotal public API version 2.0 implementation in Java.


Requirements


  • JDK 1.5 or higher version

Getting started


  • Clone project from GIT repo

https://github.com/dasnicdev/virustotal.git

  • OR Download the project as a zip file and extract

https://github.com/dasnicdev/virustotal/archive/master.zip

How to use API

Sample codes

Scan a given file
public void scanFile() {
        try {
            VirusTotalConfig.getConfigInstance().setVirusTotalAPIKey("APIKEY");
            VirustotalPublicV2 virusTotalRef = new VirustotalPublicV2Impl();

            ScanInfo scanInformation = virusTotalRef.scanFile(new File("/Users/kdesilva/Desktop/eicar.com.txt"));

            System.out.println("___SCAN INFORMATION___");
            System.out.println("MD5 :\t" + scanInformation.getMd5());
            System.out.println("Perma Link :\t" + scanInformation.getPermalink());
            System.out.println("Resource :\t" + scanInformation.getResource());
            System.out.println("Scan Date :\t" + scanInformation.getScanDate());
            System.out.println("Scan Id :\t" + scanInformation.getScanId());
            System.out.println("SHA1 :\t" + scanInformation.getSha1());
            System.out.println("SHA256 :\t" + scanInformation.getSha256());
            System.out.println("Verbose Msg :\t" + scanInformation.getVerboseMessage());
            System.out.println("Response Code :\t" + scanInformation.getResponseCode());
            System.out.println("done.");
        } catch (APIKeyNotFoundException ex) {
            System.err.println("API Key not found! " + ex.getMessage());
        } catch (UnsupportedEncodingException ex) {
            System.err.println("Unsupported Encoding Format!" + ex.getMessage());
        } catch (UnauthorizedAccessException ex) {
            System.err.println("Invalid API Key " + ex.getMessage());
        } catch (Exception ex) {
            System.err.println("Something Bad Happened! " + ex.getMessage());
        }
    }
Get File Scan Report
    public void getFileScanReport() {
        try {
            VirusTotalConfig.getConfigInstance().setVirusTotalAPIKey("APIKEY");
            VirustotalPublicV2 virusTotalRef = new VirustotalPublicV2Impl();

            String resource="275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f";
            FileScanReport report = virusTotalRef.getScanReport(resource);

            System.out.println("MD5 :\t" + report.getMd5());
            System.out.println("Perma link :\t" + report.getPermalink());
            System.out.println("Resourve :\t" + report.getResource());
            System.out.println("Scan Date :\t" + report.getScanDate());
            System.out.println("Scan Id :\t" + report.getScanId());
            System.out.println("SHA1 :\t" + report.getSha1());
            System.out.println("SHA256 :\t" + report.getSha256());
            System.out.println("Verbose Msg :\t" + report.getVerboseMessage());
            System.out.println("Response Code :\t" + report.getResponseCode());
            System.out.println("Positives :\t" + report.getPositives());
            System.out.println("Total :\t" + report.getTotal());

            HashMap<String, VirusScanInfo> scans = report.getScans();
            for (String key : scans.keySet()) {
                VirusScanInfo virusInfo = scans.get(key);
                System.out.println("Scanner : " + key);
                System.out.println("\t\t Resut : " + virusInfo.getResult());
                System.out.println("\t\t Update : " + virusInfo.getUpdate());
                System.out.println("\t\t Version :" + virusInfo.getVersion());
            }

        } catch (APIKeyNotFoundException ex) {
            System.err.println("API Key not found! " + ex.getMessage());
        } catch (UnsupportedEncodingException ex) {
            System.err.println("Unsupported Encoding Format!" + ex.getMessage());
        } catch (UnauthorizedAccessException ex) {
            System.err.println("Invalid API Key " + ex.getMessage());
        } catch (Exception ex) {
            System.err.println("Something Bad Happened! " + ex.getMessage());
        }
    }
Scan URL
  public void scanUrl() {
        try {
            VirusTotalConfig.getConfigInstance().setVirusTotalAPIKey("APIKEY");
            VirustotalPublicV2 virusTotalRef = new VirustotalPublicV2Impl();

            String urls[] = {"www.google.lk", "www.yahoo.com"};
            ScanInfo[] scanInfoArr = virusTotalRef.scanUrls(urls);

            for (ScanInfo scanInformation : scanInfoArr) {
                System.out.println("___SCAN INFORMATION___");
                System.out.println("MD5 :\t" + scanInformation.getMd5());
                System.out.println("Perma Link :\t" + scanInformation.getPermalink());
                System.out.println("Resource :\t" + scanInformation.getResource());
                System.out.println("Scan Date :\t" + scanInformation.getScanDate());
                System.out.println("Scan Id :\t" + scanInformation.getScanId());
                System.out.println("SHA1 :\t" + scanInformation.getSha1());
                System.out.println("SHA256 :\t" + scanInformation.getSha256());
                System.out.println("Verbose Msg :\t" + scanInformation.getVerboseMessage());
                System.out.println("Response Code :\t" + scanInformation.getResponseCode());
                System.out.println("done.");
            }

        } catch (APIKeyNotFoundException ex) {
            System.err.println("API Key not found! " + ex.getMessage());
        } catch (UnsupportedEncodingException ex) {
            System.err.println("Unsupported Encoding Format!" + ex.getMessage());
        } catch (UnauthorizedAccessException ex) {
            System.err.println("Invalid API Key " + ex.getMessage());
        } catch (Exception ex) {
            System.err.println("Something Bad Happened! " + ex.getMessage());
        }
    }
Get URL Report
    public void getUrlReport(){
        try {
            VirusTotalConfig.getConfigInstance().setVirusTotalAPIKey("APIKEY");
            VirustotalPublicV2 virusTotalRef = new VirustotalPublicV2Impl();

            String urls[] = {"mahamegha.com","mahamegha.info"};
            FileScanReport[] reports = virusTotalRef.getUrlScanReport(urls, false);

            for (FileScanReport report : reports) {
                if(report.getResponse_code()==0){
                    continue;
                }
                System.out.println("MD5 :\t" + report.getMd5());
                System.out.println("Perma link :\t" + report.getPermalink());
                System.out.println("Resourve :\t" + report.getResource());
                System.out.println("Scan Date :\t" + report.getScanDate());
                System.out.println("Scan Id :\t" + report.getScanId());
                System.out.println("SHA1 :\t" + report.getSha1());
                System.out.println("SHA256 :\t" + report.getSha256());
                System.out.println("Verbose Msg :\t" + report.getVerboseMessage());
                System.out.println("Response Code :\t" + report.getResponseCode());
                System.out.println("Positives :\t" + report.getPositives());
                System.out.println("Total :\t" + report.getTotal());

                HashMap<String, VirusScanInfo> scans = report.getScans();
                for (String key : scans.keySet()) {
                    VirusScanInfo virusInfo = scans.get(key);
                    System.out.println("Scanner : " + key);
                    System.out.println("\t\t Resut : " + virusInfo.getResult());
                    System.out.println("\t\t Update : " + virusInfo.getUpdate());
                    System.out.println("\t\t Version :" + virusInfo.getVersion());
                }
            }

        } catch (APIKeyNotFoundException ex) {
            System.err.println("API Key not found! " + ex.getMessage());
        } catch (UnsupportedEncodingException ex) {
            System.err.println("Unsupported Encoding Format!" + ex.getMessage());
        } catch (UnauthorizedAccessException ex) {
            System.err.println("Invalid API Key " + ex.getMessage());
        } catch (Exception ex) {
            System.err.println("Something Bad Happened! " + ex.getMessage());
        }
    }
Get IP Address Report
    public void getIPReport {
        try {
            VirusTotalConfig.getConfigInstance().setVirusTotalAPIKey("APIKEY");
            VirustotalPublicV2 virusTotalRef = new VirustotalPublicV2Impl();

            IPAddressReport report = virusTotalRef.getIPAddresReport("69.195.124.58");

            System.out.println("___IP Rport__");

            Sample[] communicatingSamples = report.getDetectedCommunicatingSamples();
            if (communicatingSamples != null) {
                System.out.println("Communicating Samples");
                for (Sample sample : communicatingSamples) {
                    System.out.println("SHA256 : " + sample.getSha256());
                    System.out.println("Date : " + sample.getDate());
                    System.out.println("Positives : " + sample.getPositives());
                    System.out.println("Total : " + sample.getTotal());
                }
            }

            Sample[] detectedDownloadedSamples = report.getDetectedDownloadedSamples();
            if (detectedDownloadedSamples != null) {
                System.out.println("Detected Downloaded Samples");
                for (Sample sample : detectedDownloadedSamples) {
                    System.out.println("SHA256 : " + sample.getSha256());
                    System.out.println("Date : " + sample.getDate());
                    System.out.println("Positives : " + sample.getPositives());
                    System.out.println("Total : " + sample.getTotal());
                }
            }

            URL[] urls = report.getDetectedUrls();
            if (urls != null) {
                System.out.println("Detected URLs");
                for (URL url : urls) {
                    System.out.println("URL : " + url.getUrl());
                    System.out.println("Positives : " + url.getPositives());
                    System.out.println("Total : " + url.getTotal());
                    System.out.println("Scan Date" + url.getScanDate());
                }
            }

            IPAddressResolution[] resolutions = report.getResolutions();
            if (resolutions != null) {
                System.out.println("Resolutions");
                for (IPAddressResolution resolution : resolutions) {
                    System.out.println("Host Name : " + resolution.getHostName());
                    System.out.println("Last Resolved : " + resolution.getLastResolved());
                }
            }

            Sample[] unDetectedDownloadedSamples = report.getUndetectedDownloadedSamples();
            if (unDetectedDownloadedSamples != null) {
                System.out.println("Undetected Downloaded Samples");
                for (Sample sample : unDetectedDownloadedSamples) {
                    System.out.println("SHA256 : " + sample.getSha256());
                    System.out.println("Date : " + sample.getDate());
                    System.out.println("Positives : " + sample.getPositives());
                    System.out.println("Total : " + sample.getTotal());
                }
            }

            Sample[] unDetectedCommunicatingSamples = report.getUndetectedDownloadedSamples();
            if (unDetectedCommunicatingSamples != null) {
                System.out.println("Undetected Communicating Samples");
                for (Sample sample : unDetectedCommunicatingSamples) {
                    System.out.println("SHA256 : " + sample.getSha256());
                    System.out.println("Date : " + sample.getDate());
                    System.out.println("Positives : " + sample.getPositives());
                    System.out.println("Total : " + sample.getTotal());
                }
            }

            System.out.println("Response Code : " + report.getResponseCode());
            System.out.println("Verbose Message : " + report.getVerboseMessage());



        } catch (APIKeyNotFoundException ex) {
            System.err.println("API Key not found! " + ex.getMessage());
        } catch (UnsupportedEncodingException ex) {
            System.err.println("Unsupported Encoding Format!" + ex.getMessage());
        } catch (UnauthorizedAccessException ex) {
            System.err.println("Invalid API Key " + ex.getMessage());
        } catch (Exception ex) {
            System.err.println("Something Bad Happened! " + ex.getMessage());
        }
    }
Get Domain Report
 public void getDomainReport() {
        try {
            VirusTotalConfig.getConfigInstance().setVirusTotalAPIKey("APIKEY");
            VirustotalPublicV2 virusTotalRef = new VirustotalPublicV2Impl();

            DomainReport report = virusTotalRef.getDomainReport("www.ntt62.com");
            System.out.println("___Domain Rport__");

            Sample[] communicatingSamples = report.getDetectedCommunicatingSamples();
            if (communicatingSamples != null) {
                System.out.println("Communicating Samples");
                for (Sample sample : communicatingSamples) {
                    System.out.println("SHA256 : " + sample.getSha256());
                    System.out.println("Date : " + sample.getDate());
                    System.out.println("Positives : " + sample.getPositives());
                    System.out.println("Total : " + sample.getTotal());
                }
            }

            Sample[] detectedDownloadedSamples = report.getDetectedDownloadedSamples();
            if (detectedDownloadedSamples != null) {
                System.out.println("Detected Downloaded Samples");
                for (Sample sample : detectedDownloadedSamples) {
                    System.out.println("SHA256 : " + sample.getSha256());
                    System.out.println("Date : " + sample.getDate());
                    System.out.println("Positives : " + sample.getPositives());
                    System.out.println("Total : " + sample.getTotal());
                }
            }

            URL[] urls = report.getDetectedUrls();
            if (urls != null) {
                System.out.println("Detected URLs");
                for (URL url : urls) {
                    System.out.println("URL : " + url.getUrl());
                    System.out.println("Positives : " + url.getPositives());
                    System.out.println("Total : " + url.getTotal());
                    System.out.println("Scan Date" + url.getScan_date());
                }
            }

            IPAddressResolution[] resolutions = report.getResolutions();
            if (resolutions != null) {
                System.out.println("Resolutions");
                for (Resolution resolution : resolutions) {
                    System.out.println("Host Name : " + resolution.getHostName());
                    System.out.println("Last Resolved : " + resolution.getLastResolved());
                }
            }

            Sample[] unDetectedDownloadedSamples = report.getUndetectedDownloadedSamples();
            if (unDetectedDownloadedSamples != null) {
                System.out.println("Undetected Downloaded Samples");
                for (Sample sample : unDetectedDownloadedSamples) {
                    System.out.println("SHA256 : " + sample.getSha256());
                    System.out.println("Date : " + sample.getDate());
                    System.out.println("Positives : " + sample.getPositives());
                    System.out.println("Total : " + sample.getTotal());
                }
            }

            Sample[] unDetectedCommunicatingSamples = report.getUndetectedCommunicatingSamples();
            if (unDetectedCommunicatingSamples != null) {
                System.out.println("Undetected Communicating Samples");
                for (Sample sample : unDetectedCommunicatingSamples) {
                    System.out.println("SHA256 : " + sample.getSha256());
                    System.out.println("Date : " + sample.getDate());
                    System.out.println("Positives : " + sample.getPositives());
                    System.out.println("Total : " + sample.getTotal());
                }
            }

            System.out.println("Response Code : " + report.getResponseCode());
            System.out.println("Verbose Message : " + report.getVerboseMessage());



        } catch (APIKeyNotFoundException ex) {
            System.err.println("API Key not found! " + ex.getMessage());
        } catch (UnsupportedEncodingException ex) {
            System.err.println("Unsupported Encoding Format!" + ex.getMessage());
        } catch (UnauthorizedAccessException ex) {
            System.err.println("Invalid API Key " + ex.getMessage());
        } catch (Exception ex) {
            System.err.println("Something Bad Happened! " + ex.getMessage());
        }
    }
Posting Comments
    public void addComment(){
        try {
            VirusTotalConfig.getConfigInstance().setVirusTotalAPIKey("APIKEY");
            VirustotalPublicV2 virusTotalRef = new VirustotalPublicV2Impl();

            String resource = "275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f";
            String comment = "Eicar file! considered a goodware";
            GeneralResponse gRespo = virusTotalRef.makeAComment(resource, comment);

            System.out.println("Response Code : " + gRespo.getResponseCode());
            System.out.println("Verbose Message : " + gRespo.getVerboseMessage());

        } catch (APIKeyNotFoundException ex) {
            System.err.println("API Key not found! " + ex.getMessage());
        } catch (UnsupportedEncodingException ex) {
            System.err.println("Unsupported Encoding Format!" + ex.getMessage());
        } catch (UnauthorizedAccessException ex) {
            System.err.println("Invalid API Key " + ex.getMessage());
        } catch (Exception ex) {
            System.err.println("Something Bad Happened! " + ex.getMessage());
        }
    }

Get Data From Database Using AngularJS in JSP

My first program with Angular JS in JSP and this is simply awesome, Blast your page without reloading, do anything just anything with MVC.

First thing you need to do is download angular.min.js from AngularJS official website by Google.
https://angularjs.org/
Either you can download the angular.min.js file and save it in your root directory or you can also use the link like this
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js" />.


I have created one webpage with client side AngularJS and at server side using JSP to retrieve data from Oracle 12c Release 1 database.
You can check AngularJS with StrutsStruts2 AngularJS Example Application
I have used two tables employee_master consisting of columns emp_code, emp_name and employee_salary consisting of gross_pay and calculated field tot_pay. So here is the code given below, the main script written within the same page, but you can write it in a different script file.

index.jsp

<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script>
// JS code 
myApp = angular.module('myApp',[]);
<%@ page import = "java.sql.*" %> 
<% 
 Class.forName("oracle.jdbc.driver.OracleDriver");
 Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:@192.168.0.109:1521:orcl","HR","HR");
 Statement stmt = conn.createStatement();
 String sql="select a.emp_code,ProperCase(a.emp_name) emp_name,to_char(to_date(b.pay_month_year,'mm/rrrr'),'Month RRRR') pay_month_year,b.gross_pay, " + 
    "sum(b.gross_pay) over (partition by b.pay_month_Year) tot_pay " +
    "from employee_master a inner join employee_salary b on b.emp_id = a.emp_id and b.pay_month_year='01/2009' and a.emp_grade='S'";
 ResultSet rs = stmt.executeQuery(sql);
 try
 {
  if(rs!=null)
  {
%> 
// JS code 
myApp.controller('empCtl',function($scope) 
   {
    $scope.empData = [
<%
    rs.next();
    while(true)
    {
%> 
     {"emp_code":"<%=rs.getString("emp_code")%>","emp_name":"<%=rs.getString("emp_name")%>","pay_month_year":"<%=rs.getString("pay_month_year")%>","gross_pay":"<%=rs.getString("gross_pay")%>","tot_pay":"<%=rs.getString("tot_pay")%>"}
   
     <%if(rs.next()) {%> , <% } else break;
    }
   } 
  }
 catch(SQLException e) 
 {
  e.printStackTrace();
 }
 stmt.close();
 rs.close();
 conn.close();
 stmt=null;
 rs=null;
 conn=null;
%>
         ];
 $scope.sortField='emp_name';
 $scope.reverse=true;
}); 
</script>
</head>
<body ng-controller="empCtl">
 Search: <input ng-model="query" type="text" />
<table border=1 cellpadding=5>
 <tr>
  <th><a href="" ng-click="sortField = 'emp_code'; reverse=!reverse">Emp Code</a></th>
  <th><a href="" ng-click="sortField = 'emp_name' reverse=!reverse">Emp Name</a></th>
  <th>Month Year</th><th>Gross Pay</th><th>Tot Pay</th></tr> 
  <tr ng-repeat="emp in empData | filter:query | orderBy:sortField:reverse">
  
  <td>{{emp.emp_code}}</td>
  <td>{{emp.emp_name}}</td>
  <td>{{emp.pay_month_year}}</td>
  <td>{{emp.gross_pay}}</td>
  <td>{{emp.tot_pay}}</td> 
 </tr>
</table>
</body>
</html>