javaniceday.com

  • Home
  • AboutAbout me
  • Subscribe
  • SalesforceSalesforce related content
  • Node JSNodejs related content
  • JavaJava related content
  • Electric Vehicles
  • Autos Eléctricos
  • Estaciones de carga UTE
  • Mapa cargadores autos eléctricos en Uruguay
  • Detect if a string is a number with regex

    August 30th, 2020

    Regular expressions, commonly shortened to regex, are a powerful tool for working with text data in programming. One common task is determining whether a given string is a number. Fortunately, this is a task that can be accomplished with a relatively simple regex pattern.

    To implement this regex pattern in code, simply use a regex matching function such as JavaScript’s `test()` method, which returns true or false depending on whether the pattern matches the input string. With this simple regex pattern, you can easily detect whether a given string is a number, making it a valuable addition to your programming toolkit.

    /**
     * It's not strictly the same than isNumber()
     *
     * @param text
     * @return true if the given text  is s number
     */
    function isNumberText (text) {
        if (!text)  return false;
        // the value must be a number, including float and not empty.
        const reg = new RegExp('^-?\d+\.?\d*$');
        return reg.test(text);
    };

    You can test this regex at https://regex101.com/

    Examples

    // it will return true on these cases
    12
    "12"
    32.3
    "43.4"
    
    // false for these cases
    "22a"
    undefined
    null
    ""
    "1    2"

    Share this:

    • Click to share on X (Opens in new window) X
    • Click to share on LinkedIn (Opens in new window) LinkedIn
    • Click to share on Reddit (Opens in new window) Reddit
    • Click to email a link to a friend (Opens in new window) Email
    Like Loading…
  • Define environment variables in Tomcat

    August 30th, 2020

    Sometimes you want to change the behavior of your code without recompiling or deploying. One way to do this is by defining environment variables that you can change at any time. A typical use case is for database connection properties (username, password, port, etc).

    In your Tomcat home create this file $TOMCAT_HOME/bin/setenv.sh and define variables like this:

          
    export VAR1=my_var1_value
    export VAR2=my_var2_value
       
        

    Grant execution permission

          
    chmod 755 setenv.sh
       
        

    In Windows define variables like this:

          
    set VAR1=my_var_value
       
        

    After saving the file you must reboot Tomcat.

    In your code you get the environment variable this way:

          
    //value will be null if VAR1 does not exist
    String value = System.getenv("VAR1");
         
        
    Photo by Christian Joudrey on Unsplash

    Share this:

    • Click to share on X (Opens in new window) X
    • Click to share on LinkedIn (Opens in new window) LinkedIn
    • Click to share on Reddit (Opens in new window) Reddit
    • Click to email a link to a friend (Opens in new window) Email
    Like Loading…
  • Do you really need a mobile app?

    August 30th, 2020

    I see lots of brands advertising “Hey, download our mobile app and…” …and you will have a menu with 5 items. The most complex item probably will be a form with 3 o 4 fields and one submit button. Ah, with a success message!

    – Do you really need a mobile app?

    – Sure! I need user location and push notifications for some requirements.

    – Well, browsers have those features nowadays, so why don’t you develop a web app with a good JavaScript framework?

    I’m not a big fan of JavaScript but I must recognize its portability and that’s a good reason to begin

    The main advantage is obvious: you will code only once. Also, you will skip Google Play and App Store submission.

    Remember KISS: Keep It Simple and Stupid

    Photo by Júnior Ferreira on Unsplash

    Share this:

    • Click to share on X (Opens in new window) X
    • Click to share on LinkedIn (Opens in new window) LinkedIn
    • Click to share on Reddit (Opens in new window) Reddit
    • Click to email a link to a friend (Opens in new window) Email
    Like Loading…
  • How to use a GitHub repository as a dependency in Node.js

    August 30th, 2020

    Sometimes you need a dependency that is not published as a regular package at npmjs.com. Probably is the case of a private package.

    Node.js allows remote dependencies such as GitHub private repository, so let explain how to do that.

    We will need a GitHub personal token. In your GitHub account go to

    Settings–>Developer settings–>Personal access tokens.

    After that, generate a new token with the permissions you need (probably read-only).

    Your package.json will look like this:

    "dependencies": {
      "module-name": "git+https://TOKEN_FROM_GITHUB:x-oauth-basic@github.com/My-company/my-repo.git"
    }

    If you want to point to a specific branch add #your-branch at the end of the url so, /My-company/my-repo.git#your-branch

    Remember to run npm install after you save the package.json file.

    Share this:

    • Click to share on X (Opens in new window) X
    • Click to share on LinkedIn (Opens in new window) LinkedIn
    • Click to share on Reddit (Opens in new window) Reddit
    • Click to email a link to a friend (Opens in new window) Email
    Like Loading…
  • Template of Java web and Heroku

    August 29th, 2020

    I’ve worked in several projects with Java, specially Java web using Tomcat as a web container and then Glassfish as application server.

    Lastly I’m working in Java projects deployed on Heroku, an amazing platform acquired by Salesorce.

    I faced many problems configuring deployment, JPA with Tomcat, oauth Salesforce flow, etc. so I decided to gather them in a template:

    Technologies

    • Java 8
    • Maven 3
    • JSF 2.2.7 for presentation
    • Primefaces 6.1 for presentation
    • JPA 2.1
    • Hibernate 5.2.10
    • Netbeans 8.2
    • Force.com Partner API for Salesforce communication
    • GSON 2.8.0 for serializing / parsing json
    • Postgres SQL for persistence
    • Apache httpcode 4.4 for doing http requests

    Full source code:
    https://github.com/andrescanavesi/java-web-heroku-template

    Photo by Danielle MacInnes on Unsplash

    Share this:

    • Click to share on X (Opens in new window) X
    • Click to share on LinkedIn (Opens in new window) LinkedIn
    • Click to share on Reddit (Opens in new window) Reddit
    • Click to email a link to a friend (Opens in new window) Email
    Like Loading…
  • How to get all the tables in Redshift

    August 28th, 2020

    To get all tables in Amazon Redshift, you can use the following query:

    SELECT t.table_name
    FROM information_schema.tables t
    WHERE t.table_schema = 'your_schema_name'
    ORDER BY 1

    Replace 'your_schema_name' with the name of the schema you want to retrieve the tables from. This query will return a list of table names in the specified schema.

          
    
    
    
          
    

    Share this:

    • Click to share on X (Opens in new window) X
    • Click to share on LinkedIn (Opens in new window) LinkedIn
    • Click to share on Reddit (Opens in new window) Reddit
    • Click to email a link to a friend (Opens in new window) Email
    Like Loading…
  • Search columns in Postgres

    August 28th, 2020

    A simple query to search columns in different schemas

          
    SELECT t.table_schema, t.table_name
    FROM information_schema.tables t
    INNER JOIN information_schema.columns c ON c.table_name = t.table_name and c.table_schema = t.table_schema
    WHERE c.column_name = 'my_column'
    AND t.table_schema IN ('pg_catalog', 'another_schema')
    ORDER BY t.table_schema;
     
        
    Photo by Markus Winkler on Unsplash

    Share this:

    • Click to share on X (Opens in new window) X
    • Click to share on LinkedIn (Opens in new window) LinkedIn
    • Click to share on Reddit (Opens in new window) Reddit
    • Click to email a link to a friend (Opens in new window) Email
    Like Loading…
  • Improve pg-promise stack traces

    August 28th, 2020

    When you execute a query with error, we get a
    pg-promise
    internal module-specific stack trace. That’s not really helpful, right?

    What we want is to know which of our methods executed a query that failed

    To do that we just tell pg-promise that uses bluebird as a promise lib

          
    const bluebird = require('bluebird');
    bluebird.config({ longStackTraces: true });
    const pgp = require('pg-promise')({ promiseLib: bluebird });
        
    

    Important: we have to set longStackTraces to false on production environments to avoid performance issues in termos of memory and CPU usage.

    Photo by eberhard grossgasteiger on Unsplash

    Share this:

    • Click to share on X (Opens in new window) X
    • Click to share on LinkedIn (Opens in new window) LinkedIn
    • Click to share on Reddit (Opens in new window) Reddit
    • Click to email a link to a friend (Opens in new window) Email
    Like Loading…
  • Test Driven Development (TDD) in a nutshell

    August 22nd, 2020

    Every project has somewhere in the src folder a file called utils.js, Utils.java, utils.py, etc.

    A couple of days ago I was looking for a way to generate a random float number between two integer numbers. Utils.xx was a good place to put a function called getRandomNumberBetween(min,max).

    In my case I was working with Node.js, so my function was

          
    module.exports.getRandomNumberBetween = function (min, max) {
        return Math.random() * (max - min) + min;
    }
          
        

    Seems a super basic function but it hides several scenarios to test.

    • What happen if min is null
    • And max?
    • What happen if any of them is negative?
    • What happen if min is greater than max?
    • What if there are strings?

    Sometimes simple function involves more time testing than implement it

    I found this example a good way to explain what TDD is.

    Formally, TDD means Test Driven Development but in your day by day means “to write tests before your main code”. Let’s use our random function example to explain TDD steps.

    The first step is to think what I want:

    I want a method that receives two integer numbers and returns a random float number between them

    The second step is to start writing test cases

          
    describe("getRandomNumberBetween", function() {
        it("should return a random number between positive range", function(done) {
            const min = 4;
            const max = 5;
            const random = Utils.getRandomNumberBetween(min, max);
            assert.isTrue(random >= min);
            assert.isTrue(random <= max);
     
            done();
        });
     
        it("should return a random number between negative range", function(done) {
            const min = -8;
            const max = -1;
            const random = Utils.getRandomNumberBetween(min, max);
            assert.isTrue(random >= min);
            assert.isTrue(random <= max);
     
            done();
        });
     
        it("should get an error with null min", function(done) {
            const min = null;
            const max = 10;
            try {
                Utils.getRandomNumberBetween(min, max);
                assert.fail("should throw an error");
            } catch (e) {
                assert.equal(e.message, "min is empty");
            }
     
            done();
        });
     
        it("should get an error with null max", function(done) {
            const min = 10;
            const max = null;
            try {
                Utils.getRandomNumberBetween(min, max);
                assert.fail("should throw an error");
            } catch (e) {
                assert.equal(e.message, "max is empty");
            }
     
            done();
        });
     
        it("should get an error with undefined min", function(done) {
            let min;
            const max = 10;
            try {
                Utils.getRandomNumberBetween(min, max);
                assert.fail("should throw an error");
            } catch (e) {
                assert.equal(e.message, "min is empty");
            }
     
            done();
        });
     
        it("should get an error with undefined max", function(done) {
            const min = 10;
            let max;
            try {
                Utils.getRandomNumberBetween(min, max);
                assert.fail("should throw an error");
            } catch (e) {
                assert.equal(e.message, "max is empty");
            }
            done();
        });
    });
          
        

    And the last step is to write the code that makes all the tests pass

          
    /**
     *
     * @param min
     * @param max
     * @returns {number} a number between min and max
     */
    module.exports.getRandomNumberBetween = function (min, max) {
        if (this.isEmpty(min)) {
            throw Error('min is empty');
        }
        if (this.isEmpty(max)) {
            throw Error('max is empty');
        }
        if (isNaN(min)) {
            throw Error('min is Nan');
        }
        if (isNaN(max)) {
            throw Error('max is Nan');
        }
        return Math.random() * (max - min) + min;
    };
          
        

    Steps 2 and 3 are iterations that you will stop when you cover all your scenarios and all tests are green.

    Did you see? A simple one-line method triggered a big test suite!

    If you are using Node.js, I strongly recommend the package nyc to see the coverage of your source code. That package will help you a lot if you forgot to test a particular scenario.

    Photo by Markus Spiske on Unsplash

    Share this:

    • Click to share on X (Opens in new window) X
    • Click to share on LinkedIn (Opens in new window) LinkedIn
    • Click to share on Reddit (Opens in new window) Reddit
    • Click to email a link to a friend (Opens in new window) Email
    Like Loading…
  • Compress a file in Node.js

    August 22nd, 2020

    Compress a file in Node.js without extra dependencies.

          
       const zlib = require('zlib');
       const fs = require('fs');
       /**
         *
         * @param filePath the absolute path to the will to zip
         * @return {Promise} the full absolute path to the zip file
         */
        function zip(filePath) {
            return new Promise((resolve, reject) => {
                const zipFilePath = `${filePath}.zip`;
                pipeline(
                    fs.createReadStream(filePath),
                    zlib.createGzip(),
                    fs.createWriteStream(zipFilePath),
                    (err) => {
                        if (err) {
                            reject(err);
                        } else {
                            resolve(zipFilePath);
                        }
                    },
                );
            });
        }
          
        

    Photo by JJ Ying on Unsplash

    Share this:

    • Click to share on X (Opens in new window) X
    • Click to share on LinkedIn (Opens in new window) LinkedIn
    • Click to share on Reddit (Opens in new window) Reddit
    • Click to email a link to a friend (Opens in new window) Email
    Like Loading…
←Previous Page
1 … 18 19 20 21 22 … 25
Next Page→

  • LinkedIn
  • GitHub
  • WordPress

Privacy PolicyTerms of Use

Website Powered by WordPress.com.

  • Subscribe Subscribed
    • javaniceday.com
    • Already have a WordPress.com account? Log in now.
    • javaniceday.com
    • Subscribe Subscribed
    • Sign up
    • Log in
    • Report this content
    • View site in Reader
    • Manage subscriptions
    • Collapse this bar
%d