Implement max timeout while returning Promise in Javascript

When you call a function which returns a Promise, it means you are making a call to an asynchronous function.

You can handle the response of an asynchronous function by using either a “then and catch blocks” or by using await.

Sometimes, asynchronous calls can take forever to send the response. It might be because of network failure or the database could be down etc. In such cases, you do not want to wait for the response for ever. You can implement timeout and return an appropriate error message to the caller thus preventing the caller from waiting for ever.

So, there are two cases that you shoud consider.

First case is the regular case. That is, when the operation is completed normally without any problem.

Second case is the exceptional case. That is, when the operation is taking more than the maximum expected time.

In the first case, you should call resolve and return the regular response.

In the second case, you should call reject and return the error message saying that the operation has timed out.

To illustrate this implementation, I will show you two examples:

The following is an example, where the resolve will be called first. This is the regular case

getName = (maxTimeout = 5000) => {

  return new Promise((resolve, reject) => {

    setTimeout(() => {

      reject({

        message: `${maxTimeout} ms timed out. Could not process the request within ${maxTimeout} ms`,

      });

    }, maxTimeout);

    setTimeout(() => resolve({ name: “Venkat Ram Taddi” }), maxTimeout – 1000);

  });

};

The following is an example, where the reject is called first. This is the exceptional case:

getName = (maxTimeout = 5000) => {

  return new Promise((resolve, reject) => {

    setTimeout(() => {

      reject({

        message: `${maxTimeout} ms timed out. Could not process the request within ${maxTimeout} ms`,

      });

    }, maxTimeout);

    setTimeout(() => resolve({ name: “Venkat Ram Taddi” }), maxTimeout + 1000);

  });

};

The following code is the caller of asynchronous function:

getName()

  .then((response) => {

    console.log(response.name);

  })

  .catch((error) => {

    console.log(error.message);

  });

Observe that passing maxTimeout while calling the asynchronous function is optional

Posted in Javascript | Tagged , | Leave a comment

LinkedHashSet – Qualities of Set and List

We know that a java.util.Set will contain unique elements. It will not allow duplicates.

We also know that a java.util.List will maintain the insertion order of added elements.

If you are looking for a collection which should have unique elements and also maintain the insertion order, then it is java.util.LinkedHashSet.

Posted in Uncategorized | Tagged , | Leave a comment

Best Security Practice for maintaining the Application properties

It is a common requirement for any application to store the properties and read them in a secured manner so that they are not exposed to to the unintended players.

Take for example, the jdbc properties required to connect to the database from your java application.

Store these properties as environment variables on your system as key value pairs.

For example,

jdbc.username=xyz

jdbc.password=abc

You can read these properties from your Java program by using System.getenv(“property.name”)

To read the property jdbc.username, you will say System.getenv(“jdbc.username”)

Posted in Uncategorized | Tagged | Leave a comment

Basic HTML5 boilerplate template

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>A Basic HTML5 Template</title>
  <meta name="description" content="A simple HTML5 Template for new projects.">
  <meta name="author" content="venkat">

  <meta property="og:title" content="A Basic HTML5 Template">
  <meta property="og:type" content="website">
  <meta property="og:url" content="https://taddivenkat.wordpress.com">
  <meta property="og:description" content="A simple HTML5 Template for new projects.">
  <meta property="og:image" content="Refer to an image here">

  <link rel="icon" href="/favicon.ico">
  <link rel="icon" href="/favicon.svg" type="image/svg+xml">
  <link rel="apple-touch-icon" href="/apple-touch-icon.png">

  <link rel="stylesheet" href="css/styles.css?v=1.0">

</head>

<body>
  <!-- your content here... -->
 
</body>
</html>

Posted in Uncategorized | Tagged | Leave a comment

Memoization

Memoization is the technique of caching repeated calculations thereby achieving a significant increase in the speed of computation.

I will take an example in illustrating this:

Here is the code to calculate fibonacci number at a given position which uses the concept of recursion:

private static BigInteger fibonacciNormal(long n) {
if (n <= 0) {
return BigInteger.ZERO;
}
if (n == 1 || n == 2) {
return BigInteger.ONE;
}
return fibonacciNormal(n-1).add(fibonacciNormal(n-2));
}

The problem with the above code is that it becomes too slow as you provide a bigger value of input n. The reason is that there are repeated calculations being done which can be avoided by caching them.
The following code uses the concept of memoization by avoiding the repeated calculations by caching the results. The performance boost is quite significant.

public static Map<Long, BigInteger> cache =

new HashMap<Long, BigInteger>();

public static BigInteger fibonacci(long n) {

if (n < 1) {

return BigInteger.valueOf(-1);

}

// Check from cache if we already computed the value

BigInteger fibonacciOfN = cache.get(n);

if (fibonacciOfN == null) {

if (n == 1) {

fibonacciOfN = BigInteger.ZERO;

} else if (n == 2) {

fibonacciOfN = BigInteger.ONE;

} else {

fibonacciOfN = fibonacci(n-1).add(fibonacci(n-2));

}

// Update the cache before returning

cache.put(n, fibonacciOfN);

return fibonacciOfN;

}

return fibonacciOfN;

}

Posted in Java, Uncategorized | Leave a comment

Event Broker Using Kafka

I have been working on Event broker application. We process messages in real time using Kafka brokers. Kafka is a distributed publish subscribe messaging service. Kafka helped us achieve scalability, fault tolerance and high throughput of more than 1 million messages per second. We selected Kafka Streams to process the messages that are stored in kafka. Kafka streams reads the message in the source topic, does processing and then writes the message into sink topic. We have a jdbc consumer which reads the data from the sink topic and then ingests it into the database.

Posted in Kafka, Uncategorized | Leave a comment

Proxy settings for maven to connect to a custom repository

We know that, by default, Maven connects to Maven Central Repository.

If you want Maven to connect to a custom repository maintained by your organization, then you can make following changes to /conf/settings.xml:

<proxy>
<id>optional</id>
<active>true</active>
<protocol>http</protocol>
<username>proxyuser</username>
<password>proxypass</password>
<host>web-proxy.corp.hpecorp.net</host>
<port>8080</port>
<!–<nonProxyHosts>web-proxy.corp.hpecorp.net</nonProxyHosts>–>
</proxy>

Posted in Maven | Tagged , | Leave a comment

Handling clob variables in plsql

If you are storing more than 4K characters in the database or more than 32K characters in pl/sql, then you are advised to use clob datatype instead of varchar2.

These functions will be very helpful in handling clob variables:

create or replace function CLOB_TO_BLOB (p_clob CLOB) return BLOB
as
l_blob blob;
l_dest_offset integer := 1;
l_source_offset integer := 1;
l_lang_context integer := DBMS_LOB.DEFAULT_LANG_CTX;
l_warning integer := DBMS_LOB.WARN_INCONVERTIBLE_CHAR;
BEGIN

DBMS_LOB.CREATETEMPORARY(l_blob, TRUE);
DBMS_LOB.CONVERTTOBLOB
(
dest_lob =>l_blob,
src_clob =>p_clob,
amount =>DBMS_LOB.LOBMAXSIZE,
dest_offset =>l_dest_offset,
src_offset =>l_source_offset,
blob_csid =>DBMS_LOB.DEFAULT_CSID,
lang_context=>l_lang_context,
warning =>l_warning
);
return l_blob;
END;

create or replace function blob_to_clob(p_blob blob) return CLOB as
l_clob clob;
l_dest_offsset integer := 1;
l_src_offsset integer := 1;
l_lang_context integer := dbms_lob.default_lang_ctx;
l_warning integer;

BEGIN

if p_blob is null then
return null;
end if;

dbms_lob.createTemporary(lob_loc => l_clob
,cache => false);

dbms_lob.converttoclob(dest_lob => l_clob
,src_blob => p_blob
,amount => dbms_lob.lobmaxsize
,dest_offset => l_dest_offsset
,src_offset => l_src_offsset
,blob_csid => dbms_lob.default_csid
,lang_context => l_lang_context
,warning => l_warning);

return l_clob;

END;

Posted in Database | Leave a comment

Rendering a flex widget in Extjs

In the head section include the following:

    extjs/ext-all.js in the script tag with type=”text/javascript” attribute

    swfobject/swfobject.js in the script tag with type=”text/javascript” attribute

    extjs/resources/css/ext-all.css in the link tag with rel=”stylesheet” type=”text/css” attributes

Ext.onReady(function () {
var win = Ext.widget(‘window’, {
title: “Inspections Widget!”,
layout: ‘fit’,
width: 700,
height: 500,
resizable: true,
items: {
xtype: ‘flash’,
url: ‘http://somedomain.com/someflashfile.swf&#8217;,
flashVars: {locale:’en’,dealerCode:’XTIMEMOTORS’,webKey:’xtimemotors’,make:’HYUNDAI’,vin:’5NPEU46FX6H146379′,day:’01/20/2015′,customerName:’DABROWSKI, AMY’,model:’SONATA’,year:’2006′}
}
});
win.show();
});

Note: You can download swfobject.js from

References:

Posted in Extjs, Flex | Leave a comment

Search for files containing a text on linux

I found this command to be very useful. Often we would like to search for a file containing a text.

$ find /path-here -type f -exec fgrep -l ‘text-to-find-here’ {} \;

Eg.

$ find /home/venkat -type f -exec fgrep -l ‘foo’ {} \;

Posted in Linux | Leave a comment