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
  • How to send a pushengage notification with node-fetch

    January 15th, 2022

    Context

    Sending push notifications from pushengage.com dashboard is pretty easy but what about f we want to automate some process in our web site? For instance, let say we want to send a push notification every time you create a blog post

    The code

          
    
      const baseUrl = 'https://api.pushengage.com/apiv1/notifications';
      const params = {
        title: '[notification title here]',
        message: '[notification message here]',
        url: '[notification url here]',
        imageUrl: '[your image url here]',
      };
      const requestParams = `notification_type=draft&notification_title=${params.title}&notification_message=${params.message}&notification_url=${params.url}&image_url=${params.imageUrl}`;
      const url = baseUrl;
      const res = await fetch(url,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            api_key: [your_api_key_here],
          },
          body: requestParams,
        });
      const body = await res.text();
      console.info(res.status);
      console.info(body);
    
          
        
    Note: have in mind we are sending the notification as a draft: notification_type=draft. Once ready, remove that parameter to send the real notification

    Output

    The first console log will print 200 status code and the second one the operation result as json

          
    200
    {"success":true,"notification_id":13623215772}
          
        

    Photo by Andres Canavesi 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…
  • redis delete all keys

    January 14th, 2022

    Delete all the keys by a given prefix in a Redis cluster.

    Let’s ping our Redis instance

       
    redis-cli -h myhost.com -p 6379 ping
       
    

    Set some keys

       
    redis-cli -h myhost.com -p 6379 SET dev1 "val1"
    redis-cli -h myhost.com -p 6379 SET dev2 "val2"
    redis-cli -h myhost.com -p 6379 SET dev3 "val3"
       
    

    Get one key

       
    redis-cli -h myhost.com -p 6379 KEYS dev1 
       
    

    Delete one key

       
    redis-cli -h myhost.com -p 6379 DEL dev1 
       
    

    Now let’s go with our massive deletion algorithm but before making any deletion let’s test the algorithm without making changes.

       
    for key in `echo 'KEYS dev*' | redis-cli -c -h myhost.com -p 6379 | awk '{print $1}'`
      do echo KEYS $key
    done | redis-cli -c -h myhost.com -p 6379
       
    

    And then when you are sure, go ahead with the deletion

       
    for key in `echo 'KEYS dev*' | redis-cli -c -h myhost.com -p 6379 | awk '{print $1}'`
      do echo DEL $key
    done | redis-cli -c -h myhost.com -p 6379
       
    

    In case you are not using a cluster just remove the -c options from redis-cli

    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…
  • Salesforce rest api download ContentVersion

    January 14th, 2022

    The Salesforce REST API can be used to download a single file from the ContentVersion object. First, you will need to obtain a session id from the API. This will provide you with an auth token that you can use to make the request for the file. Fortunately, the library jsforce will do all that work for us

    Let’s see an example about how to download a ContentVersion file through the Salesforce rest API

    In the following code, we are going to download a Salesforce File (ContentVersion) that we already know that it is an image file (.png). If you don’t know the file type you will need to run an extra call to get that information and generate the file name accordingly with its extension.

    The endpoint that gets the body of the file (binary) it’s /services/data/v51.0/sobjects/ContentVersion/{recordId}/VersionData

    const jsforce = require('jsforce');
    const https = require('https');
    const fs = require('fs');
    const conn = new jsforce.Connection();
    const userName = '*******';
    const password = '*******';
    const securityToken = '*********';
    const fileId = '0684W00000BzWohQAF';
    const fullFileName = '/Users/andrescanavesi/sf.png';
    
    conn.login(userName, password+securityToken, function(err, res) {
        if (err) { return console.error(err); }
    
        console.log(conn.accessToken);
        console.log(conn.instanceUrl);
        // logged in user property
        console.log("User ID: " + res.id);
        console.log("Org ID: " + res.organizationId);
    
        downloadFile(conn);
    
    });
    
    function downloadFile(conn) {
    
        const options = {
            hostname: 'myinstance-dev-ed.my.salesforce.com',
            port: 443,
            path: '/services/data/v51.0/sobjects/ContentVersion/'+fileId+'/VersionData',
            method: 'GET',
            headers: {
                'Content-Type': 'application/octet-stream',
                'Authorization': 'OAuth '+conn.accessToken
            }
        }
    
        https.get(options, (resp) => {
            let data = '';
    
            // A chunk of data has been received.
            resp.on('data', (chunk) => {
                console.log('chunk');
                data += chunk;
    
                fs.appendFile(fullFileName, chunk, function (err) {
                    if (err) throw err;
                    console.log('chunk updated');
                });
    
            });
    
            // The whole response has been received. Print out the result.
            resp.on('end', () => {
                console.log('data downloaded');
            });
    
        }).on("error", (err) => {
            console.log("Error: " + err.message);
        });
    }

    In the above code we use a native module https for Node.js to make the request. Of course you can use any other module such as axios or node-fetch

    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 generate a random string in Apex

    January 14th, 2022

    Random strings are sequences of characters that are generated without any specific pattern or order. They are commonly used in various applications and programming languages for purposes such as generating random passwords, unique identifiers, session tokens, or test data.

    Random strings are typically generated using random number generators and a set of characters. The length of the string can be determined based on the requirements of the specific use case.

    Random strings can be useful in applications that require unique identifiers or random data. However, it’s important to note that the randomness of generated strings depends on the quality of the random number generator used.

    In Salesforce Apex, you can generate a random string using the following code:

          
    private static String generateRandomString(Integer len) {
            final String chars = 'xaxPmno2IDdEwLzbtEvhv6oG1RDT6xQJX3MvF4amaDQ9TUvHgJfdbodlllPTnnuw';
            String randStr = '';
            while (randStr.length() < len) {
                Integer idx = Math.mod(Math.abs(Crypto.getRandomInteger()), chars.length());
                randStr += chars.substring(idx, idx+1);
            }
            return randStr;
        }
          
        

    You can call this function by passing in the desired length of the string, like this:

    String randomString = generateRandomString(10);

    Related posts

    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…
  • jsonplaceholder – free and unlimited json API placeholder

    January 5th, 2022

    What is a placeholder API

    Frandom is a JSON Placeholder fake REST API that is mainly used for prototyping and testing. The primary use of Frandom is to fake a server, sharing the code, and many such REST API uses are associated with it.

    • You don’t need sign up so you can start using it right away
    • No configuration required. Just make requests like you do for any other API
    • It’s compatible with any frontend framework you use suh as React, Vue.js or Angular
    Access to https://www.javaniceday.com/frandom and see how to use it. it’s pretty easy!

    Why mocking a backend service

    Sometimes you need a quick prototype just to validate a new product or a new feature so you don’t need to worry about implementing a real backend but at the same time you want to make sure you can replace those calls to the API placeholder later.

    Photo by Andres Canavesi 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…
  • Frandom API placeholder

    December 22nd, 2021

    Frandom it’s an Rest API to return random data in JSON format. It’s 100% public at this moment and does not require API key to use it.

    Access to https://www.javaniceday.com/frandom

    List all available endpoints

          
    fetch('https://www.javaniceday.com/frandom/api/')
        .then((response) => response.json())
        .then((json) => console.log(json));
          
        

    Output

          
    {
        companies: [
            {
                endpoint: "/frandom/api/companies",
                description: "Companies from US"
            },
            {
                endpoint: "/frandom/api/companies?countryCode=mx&quantity=5",
                description: "Companies from MX"
            }
        ],
        persons: [
            {
                endpoint: "/frandom/api/persons",
                description: "A person from US"
            },
            {
                endpoint: "/frandom/api/persons?countryCode=mx&quantity=5",
                description: "A person from MX"
            }
        ],
        numbers: [
            {
                endpoint: "/frandom/api/numbers",
                description: "A person from US"
            },
            {
                endpoint: "/frandom/api/numbers?min=0&max=700&quantity=5",
                description: "Random numbers between two numbers"
            }
        ]
    }
          
        

    Get companies

          
    fetch('https://www.javaniceday.com/frandom/api/companies')
        .then((response) => response.json())
        .then((json) => console.log(json));
          
        

    Output

          
    [
        {
            code: "us",
            name: "Caroll",
            type: "Inc",
            displayName: "Caroll Inc"
        },
        {
            code: "us",
            name: "Caroll",
            type: "Inc",
            displayName: "Caroll Inc"
        },
        {
            code: "us",
            name: "Bartell",
            type: "Capital",
            displayName: "Bartell Capital"
        },
        {
            code: "us",
            name: "Mertz",
            type: "",
            displayName: "Mertz "
        }
    
    ]
          
        
    See more endpoints and documentation at https://www.javaniceday.com/frandom

    Photo by Austin Chan 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…
  • What is Node.js and what is the Event Loop

    December 3rd, 2021

    What is Node.js?

    Node.js (also known as just Node) is a JavaScript runtime environment to run server-side web applications without using a web browser. It uses an asynchronous, event-driven model which makes a really fast engine using single-threaded for async processing.
    Node.js provides simplicity in development because of its non-blocking I/O and even-based model results in short response time and concurrent processing, unlike other frameworks where developers have to use thread management.
    Node.js uses the V8 that provides the runtime environment in which JavaScript executes.

    Node.js is a javascript runtime that makes it possible for us to write back-end of applications.

    Some facts about Node.js

    • The node package manager (NPM) provides access to hundres of thousands of resuable packages.
    • There’s a huge community that maintains Node.js and third party packages
    • Node.js is portable. It is available on Microsoft Windows, MacOS, Linux and many others OS
    • Node.js is a single-threaded but it can support concurrency via the concept of event and callbacks.
    • Node.j uses the Observer pattern.

    What is the Event Loop in Node.js

    The Event Loop is what allows Node.js to perform non-blocking I/O operations despite the fact that is single-threaded.
    Whenever a task gets completed, the Event Loop fires the corresponding event which signals the event-listener function to execute.
    It is used to handle all the I/O operations in an asynchronous manner without blocking the main thread.

    Whatever is async is managed by Event Loop using a queue and listener.

    Node.js event loop
    Image credits: https://dev.to/

    So when an async function needs to be executed, the main thread sends it to a different thread allowing V8 to keep executing the main code. Event Loop involves different phases with specific tasks such as timers, pending callbacks, idle or prepare, poll, check, close callbacks with different FIFO queues. Also in between iterations it checks for async I/O or timers and shuts down cleanly if there aren’t any.

    So for example, if some network call needs to happen it will be scheduled in the event loop instead of the main thread (single thread). And if there are multiple such I/O calls each one will be queued accordingly to be executed separately (other than the main thread).

    Thus even though we have single-threaded, I/O operations are handled in a non-blocking way.

    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…
  • Bye bye FindBugs. Hello SpotBugs

    November 30th, 2021

    I used to use FindBugs plugin in my Java projects to detect and learn about issues and potential issues in my source code.

    Even FindBugs is no longer maintained we have an alternative called SpotBugs.

    It requires Maven version 3.1.1 to be executed

    Is not so different to use, just add the plugin like any other plugin in your pom.xml file:

          
    
    <plugin>
      <groupId>com.github.spotbugs</groupId>
      <artifactId>spotbugs-maven-plugin</artifactId>
      <version>3.1.11</version>
      <executions>
        <execution>
          <goals>
            <goal>check</goal>
            <goal>gui</goal>
            <goal>help</goal>
            <goal>spotbugs</goal>
          </goals>
          <id>check</id>
        </execution>
      </executions>
      <configuration>
        <foo>bar</foo>
      </configuration>
    </plugin>
    
       
        

    And then execute:

          
    mvn spotbugs:check
       
        

    After checking our code we may display our bugs in a friendly manner

          
    mvn spotbugs:gui
       
        

    Example of a detected issue when we forget to close streams:

    Method may fail to close stream

    The method creates an IO stream object, does not assign it to any fields, pass it to other methods that might close it, or return it, and does not appear to close the stream on all paths out of the method. This may result in a file descriptor leak. It is generally a good idea to use a finally block to ensure that streams are closed.

    Tip: normally we don’t want to execute SpotBugs every time we compile our project so let’s create a profile to skip it
          
    <profile>
      <id>default</id>
      <properties>
        <spotbugs.skip>true</spotbugs.skip>
      </properties>
      <activation>
        <activeByDefault>true</activeByDefault>
      </activation>
    </profile>
    
       
        

    And let’s create a profile to execute it:

          
    <profile>
      <id>runSpotBugs</id>
      <properties>
        <spotbugs.skip>false</spotbugs.skip>
      </properties>
    </profile>
    
       
        

    And execute like this:

          
    mvn clean install -PrunSpotBugs
       
        

    Photo by Bud Helisson 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…
  • Conflict executing request: Connector profile: xxxxxx is associated with one or more flows

    November 23rd, 2021

    Error

    Conflict executing request: Connector profile: xxxxxx is associated with one or more flows. If you still want to delete it, then make delete request with forceDelete flag as true. Some of the associated flows are: [flow1, flow2,…]

    Run this from terminal (replace the xxxxx):

    aws appflow delete-connector-profile –connector-profile-name xxxxxxx –force-delete

    Some others useful commands

    aws appflow describe-flow –flow-name xxxxxxx

    aws appflow list-flows

    aws appflow describe-connectors –connector-types Salesforce

    Photo by JC Gellidon 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…
  • Invalid request provided: AWS::AppFlow::FlowCreate – Salesforce integration

    November 19th, 2021

    AWS AppFlow is a fully managed integration service offered by Amazon Web Services (AWS). It allows you to securely transfer data between different software-as-a-service (SaaS) applications and AWS services. With AWS AppFlow, you can easily automate the flow of data without the need for custom code or complex integrations.

    AWS AppFlow supports a wide range of popular applications, including Salesforce,, and more. It provides a visual interface that allows you to configure and manage data transfers, making it simpler to set up and maintain integrations.

    We could see this error when deploying a stack in AWS that contains an App Flow block. If we are doing through Cloudformation it’s possible we have added a new mapping to a field that doesn’t exist in Salesforce.

    Let see an example of error

    In this case, Field1__c and Field2__c are being mapped in App Flow but those do not exist in Salesforce or at least App Flow doesn’t have permissions to access them.

    Resource handler returned message: “Invalid request provided: AWS::AppFlow::FlowCreate Flow

    request failed:
    
    [
    
    Task Validation Error: The following connector fields are not
    
    supported: [Field1__c, Field2__c]
    
    The task sourceConnectorType is FILTERING and the task operator is PROJECTION,
    Task Validation Error:
    
    The following connector fields are not supported: [Field1__c]
    
    The task sourceConnectorType is MAPPING and the task operator is NO_OP,
    
    Task Validation Error: The following connector fields are not supported:
    
    [Field2__c] The task sourceConnectorType is MAPPING and the task operator is NO_OP
    
    ]
    
    (Service: Appflow, Status Code: 400, Request ID: xxxxxx-xxxx-xxxxx-xxxxx-xxxxxxx,
    Extended Request ID: null)" (RequestToken: xxxxxx-xxxxxx-xxxxxx-xxxxxx-xxxxxxxx,
    HandlerErrorCode: InvalidRequest)

    Verification checklist

    • Make sure the field exists
    • Make sure you don’t have a typo in the field name
    • Make sure the user used for the OAuth connection has necessary permissions. You could check Field-Level security or an existing permission set
    • Try to recreate the connection and deactivate/activate the App Flow

    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 … 11 12 13 14 15 … 25
Next Page→

  • LinkedIn
  • GitHub
  • WordPress

Privacy PolicyTerms of Use

Website Powered by WordPress.com.

 

Loading Comments...
 

    • 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