Search This Blog

Friday, November 16, 2018

Java Dynamic Method Call with params by using reflection

package com.product.rpa.api.ws;

import java.lang.reflect.Method;

public class DynamicMethodCall
{
public String sample ()
{
return "vijay";
}

public String sampleWithParam ( String x )
{
return x + " " + x;
}

public String sampleWithMultipleParams ( String x, int i )
{
return x + " " + i;
}

public static void main ( String args[] ) throws Exception
{
DynamicMethodCall dynamicMethodCall = new DynamicMethodCall ();

// with out param
Method method = dynamicMethodCall.getClass ().getMethod ( "sample" );
String result = (String) method.invoke ( dynamicMethodCall );
System.out.println ( result );

// with param
// String parameter
Class [] paramString = new Class[1];
paramString[0] = String.class;

method = dynamicMethodCall.getClass ().getMethod ( "sampleWithParam", paramString );
result = (String) method.invoke ( dynamicMethodCall, "hi - param" );
System.out.println ( result );

// with multiple params
// String parameter
paramString = new Class[2];
paramString[0] = String.class;
paramString[1] = Integer.TYPE;

method = dynamicMethodCall.getClass ().getMethod ( "sampleWithMultipleParams", paramString );
result = (String) method.invoke ( dynamicMethodCall, "hi - ", 100 );
System.out.println ( result );

}
}

Friday, September 28, 2018

Nodejs code to convert string date to another date format.

Sample nodejs code to convert string date to another format.


date.js

var moment = require('moment');
bar ('1980-08-29', 'YYYY-MM-DD', 'DD/MM/YYYY');    //calling method

function bar(date, currentFormat, requiredFormat )
{
    var date = moment(date,currentFormat);
    var train_date = date.format(requiredFormat);
    console.log(train_date);        // 29/08/1980
    return train_date;
}
exports.bar = bar;



//npm install --save
//node date.js

Monday, September 17, 2018

NodeJS - Request Plugin for file attachment MULTIPART/FORM-DATA

package.json

{
  "name": "sample",
  "version": "1.0.0",
  "description": "",
  "main": "apicall.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "dependencies": { 
    "request": "^2.83.0" 
  }
}



apicall.js

var fs = require("fs");
var request = require("request");

var fs = require('fs');
var request = require('request');
request.post({
    url: 'https://url/upload',
    formData: {
keyName1: 'value1',
                keyName2: 'value2',               
               file: fs.createReadStream('d:/temp/30off.jpg')
    },
}, function(error, response, body) {
    console.log(body);
});


steps

npm install
node apicall.js

Tuesday, September 11, 2018

Jacoco Sonar Report - Maven

COMPILE
mvn -X clean install -Dwtpversion=2.0 eclipse:eclipse

OR Ignore Test Cases
mvn -X clean install -Dwtpversion=2.0 -Dmaven.test.skip=true eclipse:eclipse

generate report  
**************
mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent install
mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent -Dmaven.test.skip=true install

JSoup - HTML Parser for image audio video attributes

SAMPLE

package com.jsoup;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.safety.Whitelist;
import org.jsoup.select.Elements;

public class HtmlParser
{
public static String html = "<html><head><title>Sample Title</title></head>"
         + "<body>"
         + "<p>Sample Content1</p>"              
         + "<img name='pic1' id='picid1' src='test.jpg' />"  
         + "<p>Sample Content2</p>"
         + "<p>Sample Content3</p>"
         + "<img name='pic2' id='picid2' src='test2.jpg' />"
         + "<video width='320' height='240' controls>"
        + "<source id='1' src='movie.mp4' type='video/mp4'>"
        + " <source  id='2' src='movie.ogg' type='video/ogg'>"
        + "<Br/>Your browser does not support the video tag."
        + "</video>"
        + "<audio controls>"
        + "<source id='1' src='horse.ogg' type='audio/ogg'>"
        + "<source id='2' src='horse.mp3' type='audio/mpeg'>"
        + "<Br/>Your browser does not support the audio tag."
        + "</audio>"
        + "<p><a href='http://example.com/'" + " onclick='checkData()'>Link</a></p>"
         +"</body></html>";


/*output
Initial HTML: <p><a href='http://example.com/' onclick='checkData()'>Link</a></p>
Cleaned HTML: <p><a href="http://example.com/" rel="nofollow">Link</a></p>*/
public static void safeGuardHtmlSanitize ()
{
System.out.println ( "Initial HTML: " + html );
String safeHtml = Jsoup.clean ( html, Whitelist.basic () );
System.out.println ( "Cleaned HTML: " + safeHtml );
}

public static void main ( String [] args )
{

Document document = Jsoup.parse ( html );
// img with src ending .png
Elements imgs = document.select ( "img" );
for ( Element img : imgs )
{
System.out.println ( "Name: " + img.attr ( "name" ) + " id: " + img.id () + " src: " + img.attr ( "src" ) );
//to replace the value existing
img.attr ( "src", "replacedImage.jpg" ) ;
}
System.out.println ( "\n\n" );

Elements videos = document.select ( "video" );
Elements videoSrc = videos.select ( "source" );
for ( Element vSrc : videoSrc )
{
System.out.println ( " id: " + vSrc.id () + " src: " + vSrc.attr ( "src" ) + " type: " + vSrc.attr ( "type" ));
}
System.out.println ( "\n\n" );

Elements audios = document.select ( "audio" );
Elements audioSrc = audios.select ( "source" );
for ( Element aSrc : audioSrc )
{
System.out.println ( " id: " + aSrc.id () + " src: " + aSrc.attr ( "src" ) + " type: " + aSrc.attr ( "type" ));
}
System.out.println ( "\n\n" );

safeGuardHtmlSanitize();
}
}



OUTPUT

Name: pic1 id: picid1 src: test.jpg
Name: pic2 id: picid2 src: test2.jpg



 id: 1 src: movie.mp4 type: video/mp4
 id: 2 src: movie.ogg type: video/ogg



 id: 1 src: horse.ogg type: audio/ogg
 id: 2 src: horse.mp3 type: audio/mpeg



Initial HTML: Sample TitleSample Content1
Sample Content2
Sample Content3
Link
Cleaned HTML: Sample Title
Sample Content1
Sample Content2
Sample Content3


Your browser does not support the video tag.

Your browser does not support the audio tag.
Link



Thursday, April 26, 2018

Nodejs - Decrypt for AES-256-CBC with no padding.

var crypto = require ( 'crypto' );
algorithm  = 'aes-256-cbc';

function decrypt ( key, data )
{
    var sha256 = crypto.createHash ( 'sha256' );
    sha256.update ( key );

    var input      = new Buffer ( data, 'base64' ),
        iv         = Buffer.alloc(16);
        ciphertext = input,
        decipher   = crypto.createDecipheriv( algorithm, sha256.digest (), iv ),
        plaintext  = decipher.update ( ciphertext );
    plaintext += decipher.final ();

    return plaintext
};

var deCodeValue = new Buffer ( "encrypted-content-place-here", 'base64' ).toString ( 'utf-8' );
console.log(deCodeValue);
var p           = decrypt ( 'password', deCodeValue );
console.log ( p );

PHP curl to upload a FILE with POST data



$ch = curl_init();

$fname = 'd:/temp/xxx.jpg';   
//windows
$cfile = new CURLFile(realpath($fname));
//linux
//$cfile = new CURLFile(realpath($fname), 'application/octet-stream', 'filename.pdf');

$data = array('param' => 'value', 
'param2' => 'value2',
'param3' => '{"jsonkey1":"jsonvalue1","jsonkey2":"jsonvalue2"}',
'file' => $cfile
);

curl_setopt($ch, CURLOPT_URL, 'https://api-url');
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('cache-control: no-cache','Content-Type: multipart/form-data'));
//curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

$response  = curl_exec($ch);

$err = curl_error($ch);

//echo "INfo : ".implode(',',curl_getinfo($ch));

curl_close($ch);

if ($err) {
  echo "cURL Error #: " . $err;
} else {
  echo "Success : ".$response;
}

?>

Thursday, March 15, 2018

Ruby Rails Rest-Client with POST Parameters, Authorization, Headers

response = RestClient::Request.new({
      method: :post,
      url: 'https://infovijay.com,
      user: 'vijay',
      password: 'dr12345',
      payload: { key1: 'value1', key2: 'value2' },
      headers: { :accept => :json, content_type: :json }
    }).execute do |response, request, result|
      case response.code
      when 400
        [ :error, parse_json(response.to_str) ]
      when 200
        [ :success, parse_json(response.to_str) ]
      else
        fail "#{response.to_str}."
      end
    end

Thursday, March 8, 2018

How to take from Custom/Local Lib - Maven

1. create a folder
2. in maven tag specify the local path
3.  what ever the jar you kept inside the folder. just add those jar in like how u r specifying normally.
4. Maven will pick in local repo, while compile or build [ whenever it perform ]





Wednesday, March 7, 2018

PHP - Aes-256-cbc Encrypt Decrypt with IV vector


function encrypt_decrypt($action, $string) {
    $output = false;
    $encrypt_method = "aes-256-cbc";
    $secret_key = 'abcdefghi1234567890';
    $secret_iv = '';
 
// hash
    $key = hash('sha256', $secret_key);
    echo "

".$key;

    // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
    $iv = substr(hash('sha256', $secret_iv), 0, 16);
    if ( $action == 'encrypt' ) {
        $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
        $output = base64_encode($output);
    } else if( $action == 'decrypt' ) {
        $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
    }
    return $output;
}
$plain_txt = "I am vijay";
echo "

Plain Text =" .$plain_txt. "\n";
$encrypted_txt = encrypt_decrypt('encrypt', $plain_txt);
echo "

Encrypted Text = " .$encrypted_txt. "\n";

$decrypted_txt = encrypt_decrypt('decrypt', $encrypted_txt);
echo "

Decrypted Text =" .$decrypted_txt. "\n";

if ( $plain_txt === $decrypted_txt ) echo "

SUCCESS";
else echo "

FAILED";
echo "\n";

?>



Output

Plain Text =I am vijay

681448fb66d8704c7d52f6770f6087882db21c899fe48d21012a587bbe70cdd3

Encrypted Text = THRtUkJYWFUzb1NzUFRoOUw5T3Q2UT09

681448fb66d8704c7d52f6770f6087882db21c899fe48d21012a587bbe70cdd3

Decrypted Text =I am vijay

SUCCESS

PHP - Encrypt / Decrypt with out IV Vector with AES-256-CBC



const PASSWORD = 'abcdefghi1234567890';
const CIPHER_METHOD = 'AES-256-CBC';

function encrypt($str) {
    $val = openssl_encrypt($str, CIPHER_METHOD, hash('sha256', PASSWORD, true));
    return $val;    
}

function decrypt($str) {
   return openssl_decrypt($str, CIPHER_METHOD, hash('sha256', PASSWORD, true));
}

$plain_data = 'I am vijay';

$encrypted = encrypt($plain_data);
echo "Encrypted : ".$encrypted."

";


$decrypted = decrypt($encrypted);
echo "Decrypted : ".$decrypted."

";


?>


Output

: openssl_encrypt(): Using an empty Initialization Vector (iv) is potentially insecure and not recommended in D:\php\test.php >

Encrypted :
zmuNrqZ+GwtQC5B0riJoMw==

Decrypted : I am vijay


Hit Counter


View My Stats