Showing posts with label Algorithm. Show all posts
Showing posts with label Algorithm. Show all posts

Thursday, 31 August 2023

Demystifying the PageRank Algorithm: Unveiling the Magic Behind Web Search.

 In the vast ocean of information that is the internet, search engines act as our trusty guides, helping us navigate through the digital landscape to find the information we seek. At the core of these search engines lies a powerful algorithm called PageRank, which plays a crucial role in determining the relevance and order of search results. In this article, we will delve into the intricacies of the PageRank algorithm and uncover the magic that makes web search possible.

The Quest for Relevant Search Results

Before we dive into PageRank, let's understand the problem it addresses. Imagine you're searching for information on a topic using a search engine. You type in your query, hit Enter, and within a fraction of a second, a list of relevant web pages appears before you. Have you ever wondered how the search engine decides the order of these results? This is where PageRank comes into play.

The Birth of PageRank

PageRank was born in the late 1990s, developed by Larry Page and Sergey Brin, the co-founders of Google. It was initially designed as a tool to determine the importance of web pages based on their links. The fundamental idea behind PageRank is that a page's importance can be gauged by the number and quality of links pointing to it. In essence, a page with more incoming links from reputable sources is considered more valuable and relevant.

The Link-Graph: Mapping the Digital Landscape

At the heart of the PageRank algorithm is the concept of a link graph. The internet is composed of web pages interconnected through hyperlinks. The link graph is a visual representation of these connections, where nodes represent web pages and edges represent the hyperlinks between them.

The Iterative Dance of PageRank

Calculating PageRank involves an iterative process. Imagine a web surfer who starts on a random page and follows links to other pages. The probability that they will continue to navigate to another page depends on the number of outgoing links from the current page. Pages with more outgoing links have a lower probability of retaining the surfer's attention.

This concept forms the basis of PageRank's mathematical formulation. Each page is assigned an initial PageRank value, and through each iteration, the PageRank value is updated based on the incoming links from other pages. This process continues until the PageRank values converge, signaling that the algorithm has reached a stable solution.

Damping Factor and Random Surfer Model

The PageRank algorithm also considers the likelihood that the surfer might randomly jump to any page, regardless of links. This is known as the damping factor. It prevents a web surfer from getting trapped in a small subset of pages. The damping factor is usually set around 0.85, meaning there's a 15% chance of the surfer jumping to a random page.

Beyond the Basics: Handling Dead Ends and Link Manipulation

PageRank isn't without its challenges. It struggles with dead ends (pages with no outgoing links) and link manipulation (creating artificial links to boost a page's ranking). To address these issues, adaptations and improvements have been made over the years, leading to more sophisticated algorithms.

The Legacy of PageRank

PageRank was the cornerstone of Google's early success, transforming the way search engines deliver results. While it's no longer the sole algorithm driving search engines, its concepts and principles laid the foundation for more advanced ranking algorithms that consider a plethora of factors beyond just links.

Here's a simplified version of the PageRank algorithm:

1. Initialize: Assign an initial PageRank value to each page in the web graph.

2. Set a damping factor (usually around 0.85) to model the likelihood of a random jump.

3. Define the maximum number of iterations or a convergence threshold.

Repeat the following steps until convergence:

4. For each page `P` in the web graph:

   - Calculate the sum of PageRank values of pages linking to `P`. Let's call this sum `PR_in`.

   - Calculate the total number of outgoing links from page `P`. Let's call this `L`.

5. For each page `P` in the web graph:

   - Calculate the updated PageRank value using the formula:

     PR_new = (1 - damping factor) / total number of pages + damping factor * (PR_in / L)

6. Calculate the difference between the old and new PageRank values for each page.

7. Check if the differences for all pages are smaller than the convergence threshold.

   If yes, the algorithm has converged, and you can stop iterating.

8. Update the PageRank values for each page with their new values.

9. Normalize the PageRank values so that they sum up to 1 across all pages.

10. The final PageRank values represent the importance of each page in the web graph.

In Conclusion

The PageRank algorithm, once a groundbreaking innovation, has left an indelible mark on the world of search engines and information retrieval. It demonstrated the power of using the web's inherent structure to determine the relevance and importance of web pages. While search engine algorithms have evolved, PageRank's legacy continues to influence the way we navigate the digital realm, ensuring that we can always find the information we're looking for, quickly and efficiently.

Sunday, 27 August 2023

Unveiling AES-256 Encryption: Safeguarding Data with Advanced Security.

 In the realm of modern cryptography, ensuring the security of sensitive data is paramount. Advanced Encryption Standard (AES) has emerged as one of the most widely used encryption algorithms, trusted by governments, corporations, and individuals alike. Among its variants, AES-256 stands out as the strongest and most robust encryption option. In this blog, we'll delve into the workings of the AES-256 algorithm, its significance, and how it maintains data confidentiality.

Understanding AES Encryption

AES, also known as Rijndael, was established as a U.S. federal government standard in 2001. It was designed to replace its predecessor, the Data Encryption Standard (DES), which was deemed inadequate against modern threats due to its relatively short key length and algorithmic vulnerabilities.

AES operates as a symmetric encryption algorithm, meaning it employs the same key for both encryption and decryption processes. However, the security lies in the complexity of the algorithm itself, making it practically impossible for unauthorized parties to deduce the original data from the encrypted version, even with knowledge of the algorithm.

AES Key Lengths

AES comes in three standard key lengths: 128 bits, 192 bits, and 256 bits. The numbers correspond to the length of the cryptographic key used in the algorithm. AES-256, the focus of this blog, utilizes a 256-bit key length, providing an immense number of possible key combinations. This large key space contributes significantly to the algorithm's security, as it becomes computationally infeasible to launch brute-force attacks.

AES-256 Encryption Process

Key Expansion: The initial 256-bit encryption key is expanded into a set of round keys. Each round key is used in subsequent rounds of the encryption process.

Initial Round: The data is divided into blocks, typically 128 bits each. In the initial round, each byte of the block is combined with the corresponding byte of the round key through a process called "AddRoundKey."

Main Rounds: The number of main rounds depends on the key length. For AES-256, there are 14 main rounds. Each main round consists of four operations: SubBytes, ShiftRows, MixColumns, and AddRoundKey. These operations introduce confusion and diffusion, making the relationship between the key and the ciphertext highly complex.

  • SubBytes: Non-linear substitution of each byte in the block using a predefined substitution table (S-box).
  • ShiftRows: Byte rows are shifted by varying offsets to introduce diffusion.
  • MixColumns: Columns are mixed through a mathematical transformation, enhancing the algorithm's security.
  • AddRoundKey: The round key is XORed with the block's state, adding a layer of confusion.

Final Round: The final round is similar to the main rounds but lacks the MixColumns operation.

Output: After the final round, the transformed block is the encrypted ciphertext, which can be transmitted or stored securely.

Security and Strengths

AES-256's strength lies in its combination of substitution, permutation, and mixing operations, making it highly resistant to cryptanalysis. The large key size and the multiple rounds of transformation contribute to its robustness against various attacks, including brute force, differential, and linear attacks. The security of AES-256 is also underpinned by its ability to effectively dissipate statistical patterns, ensuring that even small changes in input data result in significant changes in the ciphertext.

Decryption Process

The decryption process is essentially the reverse of encryption, involving the application of inverse operations to retrieve the original plaintext from the ciphertext. The same round keys used in encryption are applied in reverse order.

Conclusion

The AES-256 algorithm represents the pinnacle of data security through its robust encryption process and utilization of a 256-bit key length. Its widespread adoption in critical applications demonstrates its effectiveness against modern cryptographic threats. Understanding the complexities of AES-256 not only underscores the importance of data protection but also highlights the intricate beauty of cryptography in the digital age.

Saturday, 5 August 2023

Demystifying QR Code Algorithm: A Deep Dive into its Inner Workings.

 QR (Quick Response) code is a widely used two-dimensional barcode that efficiently stores data and can be easily scanned using smartphones and other devices. QR codes have become ubiquitous in modern-day life, facilitating various applications like payment systems, product tracking, ticketing, and much more. In this technical blog, we will explore the intricacies of the QR code algorithm, understanding how these codes are generated and decoded.

QR Code Structure:

A QR code consists of a matrix of black and white modules (squares) arranged in a square grid. Each module represents a bit, and the entire code can store data in alphanumeric, numeric, binary, or Kanji format. QR codes come in different sizes and versions, allowing for varying amounts of data storage and error correction capabilities.

QR Code Generation Algorithm:

The QR code generation process involves several steps, including data encoding, error correction, module placement, and masking. Let's delve into each of these steps:

  1. Data Encoding: The data to be encoded is first converted into a binary format using specific character sets like alphanumeric, numeric, or byte encoding. The binary data is then divided into appropriate segments, and each segment is assigned a mode indicator, character count, and data encoding scheme.
  2. Error Correction Coding: To enhance the QR code's resilience against damage or distortion, error correction coding is applied. Reed-Solomon error correction codes are commonly used, which add redundant information to the data. The level of error correction (L, M, Q, or H) determines the number of error-correcting codewords added.
  3. QR Code Structure Generation: The QR code's version and size are determined based on the amount of data and the selected error correction level. The QR code structure is then built with required format information, version information, and mode indicators.
  4. Module Placement: The QR code modules are arranged according to a specific pattern, which involves adding the data and error correction codewords in a predetermined manner. The module placement ensures even distribution and optimal scanning performance.
  5. Masking: The QR code is susceptible to becoming difficult to scan due to patterns and symmetries in the code. To avoid this, a process called "masking" is applied, which involves choosing one of the predefined masking patterns to alter the module arrangement slightly. This process helps improve the QR code's readability.

QR Code Decoding Algorithm:

The decoding process is the reverse of the generation process. A QR code scanner first detects the QR code's position and alignment pattern. Then, it performs the following steps:

  1. Alignment Pattern Detection: The QR code scanner identifies the three alignment patterns that help establish the orientation and size of the QR code.
  2. Module Extraction: The QR code's modules are extracted from the image based on the position information obtained during alignment pattern detection.
  3. Data Decoding: The extracted modules are processed to decode the data, which involves reversing the data encoding steps. Error correction algorithms are applied to correct any errors or damage in the QR code.
  4. Version and Error Correction Level Determination: By analyzing specific patterns within the QR code, the version and error correction level are identified.
QR Code vs Barcode: Key differences:

  • Data capacity: QR codes have a much higher data capacity than barcodes. While traditional barcodes can typically store only a few dozen characters, QR codes can hold several hundred characters of data.
  • Data representation: Barcodes represent data linearly through varying widths and spacings of lines, while QR codes store data in a 2D matrix format with black and white squares.
  • Speed and accuracy: QR codes can be scanned more quickly and accurately than traditional barcodes, thanks to their 2D format and built-in error correction capabilities.
  • Usage: Barcodes are commonly used for basic product identification and inventory tracking, while QR codes are more versatile and used in a wide range of applications, including marketing, mobile apps, and digital content sharing.

Conclusion:

QR codes have revolutionized data storage and retrieval in the digital age. Understanding the QR code algorithm's intricacies helps developers create efficient and robust QR code generation and decoding systems. By grasping the core concepts of data encoding, error correction coding, module placement, masking, and decoding, you can gain a deeper appreciation for the simplicity and power of QR codes and explore innovative applications across various industries.

If you are interested in diving deeper into QR code decoding, you can check out blog post on "How to Decode QR Code from Scratch" .The blog provides valuable insights into the practical implementation of the QR code decoding algorithm. Happy reading!

Monday, 12 June 2023

Deep Dive into Machine Learning: Unraveling the Power of Deep Learning Algorithms.

 Machine learning has revolutionized various industries, enabling us to make sense of vast amounts of data and uncover valuable insights. Among the different branches of machine learning, deep learning has emerged as a powerful technique that mimics the functioning of the human brain to solve complex problems. In this blog post, we will take a deep dive into machine learning and explore the fascinating world of deep learning algorithms.

Understanding Machine Learning

Machine learning is a subset of artificial intelligence that involves the development of algorithms that allow computers to learn from data and make predictions or take actions without explicit programming. It relies on statistical models and algorithms to find patterns and make informed decisions based on the available data.

There are three main types of machine learning algorithms: supervised learning, unsupervised learning, and reinforcement learning. Supervised learning involves training a model on labeled data, where it learns to make predictions based on input-output pairs. Unsupervised learning, on the other hand, deals with unlabeled data and focuses on finding patterns or groupings within the data. Reinforcement learning involves an agent learning through interactions with an environment, receiving rewards or penalties based on its actions.

Introduction to Deep Learning

Deep learning, a subset of machine learning, is inspired by the structure and functioning of the human brain. It employs artificial neural networks with multiple layers, allowing the model to learn hierarchical representations of data. The deep neural networks consist of interconnected layers of nodes, called artificial neurons or units, which perform computations and transfer information between layers.

Deep learning has gained immense popularity and success in recent years due to several factors, including the availability of large amounts of data, advancements in computational power, and improvements in algorithm design. It has achieved remarkable breakthroughs in various domains, such as computer vision, natural language processing, speech recognition, and more.

Key Components of Deep Learning

  • Neural Networks: At the core of deep learning are artificial neural networks (ANNs), which are computational models inspired by the biological neural networks in the human brain. ANNs consist of layers of interconnected nodes, and the connections between nodes have associated weights that determine the strength of the connection.
  • Activation Functions: Activation functions introduce non-linearities into the neural network, enabling it to learn complex relationships and make non-linear predictions. Common activation functions include the sigmoid function, hyperbolic tangent function, and rectified linear unit (ReLU).
  • Backpropagation: Backpropagation is a key algorithm used to train deep neural networks. It involves calculating the gradient of the loss function with respect to the weights and biases of the network and adjusting them accordingly to minimize the loss.
  • Convolutional Neural Networks (CNNs): CNNs are a specialized type of neural network designed for processing grid-like data, such as images. They consist of convolutional layers that apply filters to the input data, followed by pooling layers that downsample the features. CNNs have achieved remarkable success in image classification, object detection, and image generation tasks.
  • Recurrent Neural Networks (RNNs): RNNs are designed to process sequential data, such as time series or natural language. They have connections that allow information to flow in cycles, enabling the network to retain information about previous inputs. RNNs are commonly used in tasks like language modeling, machine translation, and speech recognition.

Applications of Deep Learning

Deep learning has transformed various industries and has been applied to numerous domains. Here are some notable applications:

  • Computer Vision: Deep learning has revolutionized computer vision tasks, such as image classification, object detection, semantic segmentation, and image generation. Convolutional neural networks (CNNs) have achieved remarkable accuracy in tasks like image recognition and autonomous driving.
  • Natural Language Processing (NLP): Deep learning has enabled significant advancements in NLP tasks, including sentiment analysis, machine translation, text summarization, and question-answering systems. Recurrent neural networks (RNNs) and transformer models have greatly improved language understanding and generation capabilities.
  • Healthcare: Deep learning has made significant contributions to healthcare, including disease diagnosis, medical image analysis, drug discovery, and personalized medicine. It has the potential to improve patient outcomes and optimize healthcare delivery.
  • Finance: Deep learning is utilized in financial applications for fraud detection, algorithmic trading, credit scoring, and risk assessment. It can analyze large volumes of financial data and detect complex patterns that may not be easily identifiable using traditional methods.

Conclusion

Deep learning has emerged as a game-changer in the field of machine learning, unleashing its potential to solve complex problems across various domains. With its ability to automatically learn hierarchical representations from data, deep learning has achieved remarkable success in areas such as computer vision, natural language processing, healthcare, finance, and more.

As technology continues to advance and data availability increases, the applications of deep learning will only expand further. It is an exciting time for researchers, practitioners, and enthusiasts to dive deeper into the world of deep learning and unlock its incredible potential to transform the way we live, work, and interact with technology.

Thursday, 14 June 2018

HB Blog 156: Secure Communication For OkHttpClient Web-service API.

In cryptography, encryption is the process of encoding messages or information in such a way that only authorized parties can read it. We have seen this in my old blog HB Blog 41: Encryption And Decryption Process Of String. In that post we saw how to encrypt a string, lets see how to do similar process with web service for secure communication.
Here, we will use  java.security package for AES - 256 encryption and decryption during webservice call with OkHttpClient,
Refer the below link for complete sample code:-

Download Sample Code

Have a look on few code snippets,

//EncryptionUtility.java
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package com.harshalbenake.apiencryptionaes;

import android.util.Base64;
import android.util.Log;

import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * Encrypt and decrypt messages using AES 256 bit encryption that are compatible with AESCrypt-ObjC and AESCrypt Ruby.
 */
public final class EncryptionUtility {
    //AESCrypt-ObjC uses CBC and PKCS7Padding
    private static final String AES_MODE = "AES/CBC/ISO10126Padding";
    private static final String CHARSET = "UTF-8";

    /**
     * Encrypt and encode message using 256-bit AES with key generated from password.
     *
     * @param key     : secrete key
     * @param message the thing you want to encrypt assumed String UTF-8
     * @return Base64 encoded CipherText
     * @throws GeneralSecurityException if problems occur during encryption
     */
    public static String encrypt(final String key, String message, String IV)
            throws GeneralSecurityException {
        try {
            byte[] ivBytes = IV.getBytes();
            byte[] keyBytes = key.getBytes("UTF-8");

            final SecretKeySpec secreteKey = new SecretKeySpec(keyBytes, "AES");
            byte[] cipherText = encrypt(secreteKey, ivBytes, message.getBytes(CHARSET));
            String encoded = Base64.encodeToString(cipherText, Base64.NO_WRAP);

            return encoded;
        } catch (UnsupportedEncodingException e) {
            throw new GeneralSecurityException(e);
        }
    }


    /**
     * More flexible AES encrypt that doesn't encode
     *
     * @param key     AES key typically 128, 192 or 256 bit
     * @param iv      Initiation Vector
     * @param message in bytes (assumed it's already been decoded)
     * @return Encrypted cipher text (not encoded)
     * @throws GeneralSecurityException if something goes wrong during encryption
     */
    public static byte[] encrypt(final SecretKeySpec key, final byte[] iv, final byte[] message)
            throws GeneralSecurityException {
        byte[] cipherText = new byte[0];
        try {
            final Cipher cipher = Cipher.getInstance(AES_MODE);
            IvParameterSpec ivSpec = new IvParameterSpec(iv);
            cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
            cipherText = cipher.doFinal(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cipherText;
    }

    /**
     * Decrypt and decode ciphertext using 256-bit AES with key generated from password
     *
     * @param key
     * @param base64EncodedCipherText the encrpyted message encoded with base64
     * @return message in Plain text (String UTF-8)
     * @throws GeneralSecurityException if there's an issue decrypting
     */
    public static String decrypt(final String key, String base64EncodedCipherText, String IV)
            throws GeneralSecurityException {

        try {
            byte[] ivBytes = IV.getBytes();
            byte[] keyBytes = key.getBytes("UTF-8");

            final SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES");
            byte[] decodedCipherText = Base64.decode(base64EncodedCipherText, Base64.NO_WRAP);
            byte[] decryptedBytes = decrypt(secretKey, ivBytes, decodedCipherText);
            String message = new String(decryptedBytes, CHARSET);

            return message;
        } catch (UnsupportedEncodingException e) {
            throw new GeneralSecurityException(e);
        } catch (Exception e) {
            System.out.println(" Sys : " + e);
            throw new RuntimeException(e);
        }
    }


    /**
     * More flexible AES decrypt that doesn't encode
     *
     * @param key               AES key typically 128, 192 or 256 bit
     * @param iv                Initiation Vector
     * @param decodedCipherText in bytes (assumed it's already been decoded)
     * @return Decrypted message cipher text (not encoded)
     * @throws GeneralSecurityException if something goes wrong during encryption
     */
    public static byte[] decrypt(final SecretKeySpec key, final byte[] iv, final byte[] decodedCipherText)
            throws GeneralSecurityException {
        final Cipher cipher = Cipher.getInstance(AES_MODE);
        IvParameterSpec ivSpec = new IvParameterSpec(iv);
        cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
        byte[] decryptedBytes = cipher.doFinal(decodedCipherText);
        return decryptedBytes;
    }
}

//OKHTTPService.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package com.harshalbenake.apiencryptionaes;

import android.util.ArrayMap;
import android.util.Log;

import java.util.Arrays;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * This class is used fto get and post service response to server using okhttp.
 */
public class OKHTTPService {
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    public static final String mStrUrl="Url";
    public static final String mStrRequestJson="RequestJson";
    public static final String mStrRequestEncoded="RequestEncoded";
    public static final String mStrResponseEncoded="ResponseEncoded";
    public static final String mStrResponseJson="ResponseJson";


    public OKHTTPService() {
    }

    /**
     * gets Ok Http Service
     *
     * @param strUrl
     * @param strJson
     * @return
     */
    public static HashMap<String,String> requestACallToServer(String strUrl, String strJson) {
        HashMap<String,String> hashMap=new HashMap<String, String>();
        try {
            System.out.println("OkHttp get Request: " + strJson);
            String strEncodedRequest = EncryptionUtility.encrypt("YourKey",strJson, "YourKey");            System.out.println("OkHttp get EncodedRequest: " + strEncodedRequest);
            RequestBody body = RequestBody.create(JSON, strEncodedRequest);
            Request request = new Request.Builder()
                    .url(strUrl)
                    .post(body)
                    .build();
            OkHttpClient.Builder builder = new OkHttpClient.Builder().protocols(Arrays.asList(Protocol.HTTP_1_1));
            builder.connectTimeout(3, TimeUnit.MINUTES)
                    .writeTimeout(3, TimeUnit.MINUTES)
                    .readTimeout(3, TimeUnit.MINUTES);
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    Log.d("HttpLogging", message);
                }
            });
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .protocols(Arrays.asList(Protocol.HTTP_1_1))
                    .addInterceptor(logging)
                    .connectTimeout(3, TimeUnit.MINUTES)
                    .writeTimeout(3, TimeUnit.MINUTES)
                    .readTimeout(3, TimeUnit.MINUTES)
                    .build();
            Response response = okHttpClient.newCall(request).execute();
            String strEncodedResponse = response.body().string();
            System.out.println("OkHttp get EncodedResponse: " + strEncodedResponse);
            String strResponse = EncryptionUtility.decrypt("YourKey", strEncodedResponse, "YourKey");            System.out.println("OkHttp get Response: " + strResponse);
            hashMap.put(mStrUrl,strUrl);
            hashMap.put(mStrRequestJson,strJson);
            hashMap.put(mStrRequestEncoded,strEncodedRequest);
            hashMap.put(mStrResponseEncoded,strEncodedResponse);
            hashMap.put(mStrResponseJson,strResponse.replaceAll("\\r\\n", ""));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return hashMap;
    }
}

//DataService.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.harshalbenake.apiencryptionaes;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import java.util.HashMap;

/**
 * Data Service AsyncTask
 */
public class DataService extends AsyncTask<String, String, HashMap<String, String>> {
    MainActivity mContext;
    private ProgressDialog mProgressDialog;

    public DataService(MainActivity context) {
            this.mContext = context;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        if (NetworkUtility.isOnline(mContext)) {
            mProgressDialog = new ProgressDialog(mContext);
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setCancelable(false);
            mProgressDialog.setCanceledOnTouchOutside(false);
            mProgressDialog.show();
        } else {
            Toast.makeText(mContext, "Not connected to Internet", Toast.LENGTH_SHORT).show();
            cancel(true);
        }
    }

    @Override
    protected HashMap<String, String> doInBackground(String... params) {
        HashMap<String, String> hashMap=null;
        if (!isCancelled()) {
            try {
                String strUrl ="xxxURLxxx";
                String strJsonData="xxxJsonDataxxx";
                 hashMap = OKHTTPService.requestACallToServer(strUrl,strJsonData.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return hashMap;
    }

    @Override
    protected void onPostExecute(HashMap<String, String> resultMap) {
        super.onPostExecute(resultMap);
        try {
            if (mProgressDialog != null && mProgressDialog.isShowing() == true) {
                mProgressDialog.dismiss();
            }
            if(resultMap!=null && resultMap.size()>0){
                mContext.mtv_url.setText(OKHTTPService.mStrUrl+": "+resultMap.get(OKHTTPService.mStrUrl)+"\n");
                mContext.mtv_requestjson.setText(OKHTTPService.mStrRequestJson+": "+resultMap.get(OKHTTPService.mStrRequestJson)+"\n");
                mContext.mtv_requestencoded.setText(OKHTTPService.mStrRequestEncoded+": "+resultMap.get(OKHTTPService.mStrRequestEncoded)+"\n");
                mContext.mtv_responsencoded.setText(OKHTTPService.mStrResponseEncoded+": "+resultMap.get(OKHTTPService.mStrResponseEncoded)+"\n");
                mContext.mtv_responsejson.setText(OKHTTPService.mStrResponseJson+": "+resultMap.get(OKHTTPService.mStrResponseJson)+"\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Friday, 1 December 2017

HB Blog 149: Cross Platform Development.

In computing, cross-platform software (also multi-platform software or platform-independent software) is computer software that is implemented on multiple computing platforms. Cross-platform software may be divided into two types; one requires individual building or compilation for each platform that it supports, and the other one can be directly run on any platform without special preparation. Cross-platform programming is the practice of actively writing software that will work on more than one platform.
There are a number of tools which are available to help facilitate the process of cross-platform programming:
  1.     8th: A cross-platform development language, which utilizes Juce as its GUI layer. The platforms it currently supports are: Android, iOS, Windows, macOS, Linux and Raspberry Pi.
  2.     Anant Computing: A mobile application platform that works in all Indian languages, including their keyboards, which is also supports AppWallet and Native performance inside all operating systems.
  3.     Appcelerator: It helps in building native apps by deploying just a single JavaScript code base. It provides your web content in a native application, ensuring your code is not wrapped around a web container unlike few other such solutions.
  4.     AppearIQ: A framework that supports the workflow of app development and deployment in an enterprise environment. Natively developed containers present hardware features of the mobile devices or tablets through an API to HTML5 code thus facilitating the development of mobile apps that run on different platforms.
  5.     Cairo: A free software library used to provide a vector graphics-based, device-independent API. It is designed to provide primitives for 2-dimensional drawing across a number of different backends. Cairo is written in C and has bindings for many programming languages.
  6.     Cocos2d: An open source toolkit and game engine for developing 2D and simple 3D cross-platform games and applications.
  7.     Delphi: A cross platform IDE, which uses Pascal language for Development. Currently it supports Android, iOS, Windows, macOS.
  8.     Ecere SDK: A cross platform GUI & 2D/3D graphics toolkit and IDE, written in eC and with support for additional languages such as C and Python. Currently it supports Linux, FreeBSD, Windows, Android, macOS and the Web through Emscripten or Binaryen (WebAssembly)
  9.     Eclipse: An open source cross-platform development environment. Implemented in Java with a configurable architecture which supports many tools for software development. Add-ons are available for several languages, including Java and C++.
  10.     FLTK: Another open source cross platform toolkit, but more lightweight because it restricts itself to the GUI.
  11.     fpGUI: An open source widget toolkit that is completely implemented in Object Pascal. It currently supports Linux, Windows and a bit of Windows CE.
  12.     GeneXus: A Windows rapid software development solution for cross-platform application creation and deployment based on knowledge representation and supporting C#, COBOL, Java including Android and BlackBerry smart devices, Objective-C for Apple mobile devices, RPG, Ruby, Visual Basic, and Visual FoxPro.
  13.     GLBasic: A BASIC dialoect and compiler that generates C++ code. It includes cross compilers for many platforms and supports numerous platform (Windows, Mac, Linux, Android,iOS and some exotic handhelds).
  14.     GTK+: An open source widget toolkit for Unix-like systems with X11 and Microsoft Windows.
  15.     Haxe: An open source cross-platform language.
  16.     Juce: An application framework written in C++, used to write native software on numerous systems (Microsoft Windows, POSIX, macOS), with no change to the code.
  17.     Lazarus: A programming environment for the FreePascal Compiler. It supports the creation of self-standing graphical and console applications and runs on Linux, MacOSX, iOS, Android, WinCE, Windows and WEB.
  18.     Max/MSP: A visual programming language that encapsulates platform-independent code with a platform-specific runtime environment into applications for macOS and Windows.
  19.     MechDome: A cross-platform Android runtime. It allows unmodified Android apps to run natively on iOS and macOS
  20.     MonoCross: An open-source model-view-controller design pattern where the model and controller are shared cross-platform but the view is platform-specific.
  21.     Mono: An open-source cross-platform version of Microsoft .NET (a framework for applications and programming languages)
  22.     MoSync: An open-source SDK for mobile platform app development in the C++ family
  23.     Mozilla application framework: An open source platform for building macOS, Windows and Linux applications
  24.     OpenGL: A cross-platform 3D graphics library.
  25.     PhoneGap: It enables software programmers to build applications for mobile devices using CSS3, HTML5, and JavaScript instead of relying on platform-specific APIs like those in Android, iOS, or Windows Phone.
  26.     PureBasic: A proprietary cross-platform language and IDE for building macOS, Windows and Linux applications
  27.     Qt: An application framework and widget toolkit for Unix-like systems with X11, Microsoft Windows, macOS, and other systems—available under both open source and proprietary licenses.
  28.     Simple and Fast Multimedia Library: A multimedia C++ API that provides low and high level access to graphics, input, audio, etc.
  29.     Simple DirectMedia Layer: An open-source cross-platform multimedia library written in C that creates an abstraction over various platforms’ graphics, sound, and input APIs. It runs on many operating systems including Linux, Windows and macOS and is aimed at games and multimedia applications.
  30.     Smartface: A cross platform native app development tool to create mobile applications for Android and iOS, using WYSIWYG design editor with JavaScript code editor.
  31.     Tcl/Tk
  32.     Ultimate++: A C++ cross-platform rapid application development framework focused on programmers productivity. It includes a set of libraries (GUI, SQL, etc..), and an integrated development environment. It supports Windows and Unix-like OS-s. The U++ competes with popular scripting languages while preserving C/C++ runtime characteristics. It has its own integrated development environment, TheIDE, which features BLITZ-build technology to speedup C++ rebuilds up to 4 times.
  33.     Unity: Another cross-platform SDK which uses Unity Engine.
  34.     Unreal: A cross-platform SDK which uses Unreal Engine.
  35.     V-Play Engine: V-Play is a cross-platform development SDK based on the popular Qt framework. V-Play apps and games are created within Qt Creator.
  36.     WaveMaker: A Cross-platform low-code development tool to create responsive web and hybrid mobile (Android & iOS) applications.
  37.     WinDev: Integrated Development Environment for Windows, Linux, .Net and Java (also with support for Internet and Intranet)
  38.     wxWidgets: An open source widget toolkit that is also an application framework.[14] It runs on Unix-like systems with X11, Microsoft Windows and macOS. It permits applications written to use it to run on all of the systems that it supports, if the application does not use any operating system-specific programming in addition to it.
  39.     Xamrin: With a C#-shared codebase, developers can use Xamarin tools to write native Android, iOS, and Windows apps with native user interfaces and share code across multiple platforms, including Windows and macOS. 
  40.     Xojo: A RAD IDE developed by Xojo, Inc. that uses an object-oriented programming language to create desktop, web and iOS apps. Xojo makes native, compiled desktop apps for macOS, Windows, Linux and Raspberry Pi. It creates compiled web apps that can be run as standalone servers or through CGI. And it recently added the ability to create native iOS apps.

Sunday, 15 October 2017

HB Blog 146: Create Product Counter Used In Android Applications.

In programming world we have very much importance of time and delivery of the product. We need to keep building up pieces so that we can build up complete product in time.
Here, in this tutorial I will show how to create counter that we have seen in many shopping cart and online food delivery Android applications such as Flipkart, Amazon, Zomato, etc.
Refer the below link for complete sample code:-

Download Sample Code

Have a look on few code snippets,

//custom_counter.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="vertical">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:orientation="horizontal">
        <ImageView
            android:id="@+id/ib_counterminus"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_minus" />
        <EditText
            android:id="@+id/et_countervalue"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:digits="0123456789"
            android:gravity="center"
            android:imeOptions="actionDone"
            android:inputType="number"
            android:singleLine="true" />
        <ImageView
            android:id="@+id/ib_counterplus"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_plus" />
    </LinearLayout>
</LinearLayout>

//activity_main.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.harshalbenake.counterview.views.CustomCounter
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />
</RelativeLayout>

//CustomCounter.java
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package com.harshalbenake.counterview.views;

import android.content.Context;
import android.text.method.DigitsKeyListener;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.harshalbenake.counterview.R;

/**
 * This class is used for custom counter.
 */
public class CustomCounter extends LinearLayout implements View.OnClickListener,TextView.OnEditorActionListener {
    private Context mContext;
    private EditText met_countervalue;

    public interface OnConterSubmitListner {
        void onConterSubmit();
    }

    OnConterSubmitListner mOnConterSubmitListner;


    public CustomCounter(Context context) {
        super(context);
        this.mContext = context;
        initlayout();
    }

    public CustomCounter(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        initlayout();
    }

    public CustomCounter(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.mContext = context;
        initlayout();
    }

    /**
     * initialize Layout
     */
    private void initlayout() {
        View rootView = inflate(mContext, R.layout.custom_counter, this);
        met_countervalue = (EditText) rootView.findViewById(R.id.et_countervalue);
        ImageView ib_counterminus = (ImageView) rootView.findViewById(R.id.ib_counterminus);
        ImageView ib_counterplus = (ImageView) rootView.findViewById(R.id.ib_counterplus);

        ib_counterminus.setOnClickListener(this);
        ib_counterplus.setOnClickListener(this);
        met_countervalue.setOnEditorActionListener(this);

        met_countervalue.setKeyListener(DigitsKeyListener.getInstance(true,true));

    }

    @Override
    public void onClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.ib_counterminus) {
            decrementValue();
        } else if (viewId == R.id.ib_counterplus) {
            incrementValue();
        }
    }

    @Override
    public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            if (mOnConterSubmitListner != null) {
                mOnConterSubmitListner.onConterSubmit();
            }
        }
        return false;
    }

    /**
     * increments Value
     */
    private void incrementValue() {
        int counterValue = getValue();
        met_countervalue.setText(String.valueOf(counterValue + 1));
    }

    /**
     * decrements Value
     */
    private void decrementValue() {
        int counterValue = getValue();
        if (counterValue > 0) {
            met_countervalue.setText(String.valueOf(counterValue - 1));
        }
    }

    /**
     * gets Value
     */
    public int getValue() {
        String counterValue = met_countervalue.getText().toString().trim();
        if (counterValue!=null && !counterValue.equalsIgnoreCase("")) {
            return Integer.valueOf(counterValue);
        } else {
            return 0;
        }
    }

    /**
     * sets Value
     */
    public void setValue(String strValue) {
        if (strValue!=null && !strValue.equalsIgnoreCase("")) {
            met_countervalue.setText(Integer.valueOf(strValue)+"");
        }
    }

    /**
     * set On ConterSubmit Listner
     * @param onConterSubmitListner
     */
    public void setOnConterSubmitListner(OnConterSubmitListner onConterSubmitListner) {
        mOnConterSubmitListner = onConterSubmitListner;
    }
}