Category: Programming

  • Empty datatable in Python/Django, even if the referred query returns a non-empty set

    Hey, there! How are you doing?

    I guess you’re facing an annoying (but quite easy to solve) problem… am I right? Well, no more talk, let’s go ahead!

    I can bet that the problem is that you didn’t put the desired set of components in a context variable. But what am I talking about?

    See, in your views.py you need to have something like:

    1. Creating the Context in views.py

    @login_required
    def notifica_modelo(request, id):
        modelos = Modelo.objects.all
        notificar_clientes_modelo(id)
        context = {'modelos': modelos}
        return render(request, "pages/envia_notificacoes.html", context)
    

    In that piece of code, the method notifica_modelo stores all the Modelo objects in the variable context, which is just a dictionary containing key-value pairs.

    2. Accessing the Context in the Template

    To improve your understanding, here is the partial template envia_notificacoes.html:

    {% load static %}
    {% load bootstrap_icons %}
    
    <div class="container-lista">
        <h2>Enviar notificações</h2>
        <br>
        <table id="datatable">
            <tr>
                <th>Notificação</th>
                <th>&nbsp;</th>
                <th>&nbsp;</th>
            </tr>
            {% for modelo in modelos %}
            <tr>
                <td>{{ modelo.assunto }}</td>
                <td>
                    <a href="{% url 'exibe_modelo' modelo.id %}">
                        {% bs_icon 'search' color='blue' %}
                    </a>
                </td>
                <td>
                    <a href="{% url 'notifica_modelo' modelo.id %}">
                        {% bs_icon 'send' color='blue' %}
                    </a>
                </td>
            </tr>
            {% endfor %}
        </table>
    </div>
    
    

    By iterating through the variable modelos, the data is retrieved from the context dictionary passed from the view, and everything works smoothly.

    Final Thoughts

    See? Told you it was easy! If you have any questions or want to dive deeper, just drop a comment or message. Happy coding!

    — Igor Magalhães Oliveira

  • Creating a simple endpoint in Java and Spring Boot to authenticate using Active Directory

    Well, guys, how are you doing? Yes, I’ll be quite straightforward: I’ll show you a working code in Java using the framework Spring Boot and Windows Server Active Directory.

    Let me contextualize: you have Active Directory running in a Windows Server machine (not necessarily on the same machine as the current code) and, in order to harness the users’ authentication data from the company domain as the authentication method of a third-party software, you have to create an endpoint and make it available to the other software. You don’t need a VIEW in the MVC Architecture.

    Model class: AuthenticationRequest

    public class AuthenticationRequest {
        private String username;
        private String password;
    
        // Getters and setters
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    }
    

    RestController: AuthenticationController

    import model.AuthenticationRequest;
    import java.util.Hashtable;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.http.ResponseEntity;
    import org.springframework.http.HttpStatus;
    import javax.naming.*;
    import javax.naming.directory.*;
    
    @RestController
    public class AuthenticationController {
    
        @PostMapping("/authenticate")
        public ResponseEntity<String> authenticateUser(@RequestBody AuthenticationRequest request) {
            try {
                String username = request.getUsername();
                String password = request.getPassword();
    
                boolean isAuthenticated = authenticateWithActiveDirectory(username, password);
    
                if (isAuthenticated) {
                    return new ResponseEntity<>("User authenticated successfully", HttpStatus.OK);
                } else {
                    return new ResponseEntity<>("Authentication failed", HttpStatus.UNAUTHORIZED);
                }
            } catch (Exception e) {
                // Log the exception or handle it appropriately
                e.printStackTrace();
                return new ResponseEntity<>("Authentication failed. Erro", HttpStatus.UNAUTHORIZED);
                // return new ResponseEntity<>("An error occurred during authentication", HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }
    
        private boolean authenticateWithActiveDirectory(String username, String password) {
            String ldapURL = "ldap://192.168.0.2:389";
    
            Hashtable<String, String> env = new Hashtable<>();
            env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            env.put(Context.PROVIDER_URL, ldapURL);
            env.put(Context.SECURITY_AUTHENTICATION, "simple");
            env.put(Context.SECURITY_PRINCIPAL, username + "@intranet.company.com.br");
            env.put(Context.SECURITY_CREDENTIALS, password);
    
            try {
                DirContext context = new InitialDirContext(env);
                System.out.println("Conexão bem sucedida!");
                context.close();
                return true;
            } catch (AuthenticationException authEx) {
                System.out.println("Autenticação falhou: " + authEx.getMessage());
                return false;
            } catch (NamingException nex) {
                System.out.println("Falha ao tentar conectar com o servidor LDAP: " + nex.getMessage());
                return false;
            }
        }
    }
    

    Main Class

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class MainApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(MainApplication.class, args);
        }
    }
    

    application.properties file

    logging.level.org.springframework=INFO
    logging.level.com.example=DEBUG
    
    server.port=8444
    server.ssl.keystore=file:/C:/xampp/ssl/certificates/keystore.p12
    server.ssl.key-store-type=PKCS12
    server.ssl.key-store-password=pass
    server.ssl.key-alias=endpoint
    

    An important information is that we call this endpoint through an HTTPS POST request, so we need to generate the keystore.p12 file from the certificate provided by the certification authority. In case you don’t need to use SSL, you won’t need to worry about the last part of the previous file.

    Well… I have nothing else to say about it. It’s done! But… ah, yes! Before I go, let me remind you: please execute the Main Class and it will start your application server (like Tomcat), and your endpoint will be ready to receive and handle HTTPS requests.

    By Igor Magalhães Oliveira

  • String and StringBuider for Everybody!

    Hey! Are you one of the millions enthusiasts of String? Are you always doing something like str += “concatenate another string”?

    Pretty good! Uh… unfortunately I’m joking, but calm down. I do the diagnosis and provide you the medicines too.

    I explain: it turns out that a String object is immutable (each time you do “+=” you create another String object, with huge impact in processing time), while a StringBuilder is mutable and, because of that, far more efficient for that purpose.

    Use the String class when you need to store immutable data to be read later, like names, addresses, API endpoints, file paths… For all other cases (except multithreaded environments, where you might use StringBuffer), you’ll use StringBuilder.

    I give you some examples.

    Example 1: String concatenation

    StringBuilder message = new StringBuilder("Hello");
    message.append(" ");
    message.append("World!");
    System.out.println(message.toString());
    

    Example 2: Building dynamic strings

    StringBuilder jsonBuilder = new StringBuilder();
    jsonBuilder.append("{");
    jsonBuilder.append("\"name\": \"John\",");
    jsonBuilder.append("\"age\": 30");
    jsonBuilder.append("}");
    

    When you do a benchmarking test comparing String and StringBuilder, the results are awesome, as we see in the code below:

    int n = 10000;
    long startTime = System.nanoTime();
    long endTime;
    
    // Using String
    String result = "";
    for (int i = 0; i < n; i++) {
        result += "a";
    }
    endTime = System.nanoTime();
    long durationString = endTime - startTime;
    
    System.out.println("String concatenation took: " + durationString + " nanoseconds");
    
    // Using StringBuilder
    startTime = System.nanoTime();
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < n; i++) {
        sb.append("a");
    }
    String resultStringBuilder = sb.toString();
    endTime = System.nanoTime();
    long durationStringBuilder = endTime - startTime;
    
    System.out.println("StringBuilder concatenation took: " + durationStringBuilder + " nanoseconds");
    

    With the result as shown below:

    Well, for today it’s enough! See you soon!

    By Igor Magalhães Oliveira

  • How to enable your Redis to be seen and accept connections from everywhere

    Hello, everyone!

    The aim here is to write something as useful as fast for reading and at the end you’ll be able to access your Redis server from everywhere.

    Step 1: search the file redis.conf

    Usually, this file is under /etc/redis directory, if your system runs in a Linux OS, but you can check it using locate command (review this post):

    locate redis.conf
    

    Then, you have to edit it. If you’re using Windows you have to open it in the administrative mode in a tool like Notepad++; if you’re using Linux, you can do (inside the correct directory):

    sudo nano redis.conf
    

    Now, you’ll change the protected-mode parameter and comment the line with bind 127.0.0.1:

    In Linux, press CTRL+O (to save) and CTRL+X (to exit the nano editor), then restart Redis service:

    sudo service redis-service restart
    

    We’re done! Everything will run fine when your system tries to communicate with the Redis server.

    By Igor Magalhães Oliveira

  • Mastering Git Command Line: Boost Your Development Workflow

    Mastering Git on the command line can significantly enhance your development workflow and collaboration efficiency. Recently, Visual Studio Code (VS Code) has become a standout tool for developers, offering powerful features—including its built-in terminal, which allows seamless use of the Git Command Line Interface (CLI).

    From personal experience, I’ve transitioned away from heavier IDEs like Eclipse, NetBeans, and Android Studio since adopting VS Code. Its lightweight yet powerful environment, combined with Git integration, makes it an excellent choice for modern development.

    To help you optimize your Git workflow, here are some essential best practices:

    1. Understanding Git Basics

    Start by mastering fundamental Git commands:

    • git init – Initialize a new repository
    • git add – Stage changes
    • git commit – Save changes with a meaningful message
    • git push – Upload changes to a remote repository

    These commands form the foundation of version control, enabling efficient change tracking.

    2. Adopting Branching Strategies

    A well-structured branching strategy keeps your codebase organized. Consider:

    • Feature branching – Isolate new features in separate branches
    • GitFlow – A structured workflow for larger projects (I’ll cover this in detail soon!)

    Use commands like git branch and git checkout (or git switch) to manage branches effortlessly.

    3. Committing Frequently & Effectively

    • Commit often – Small, frequent commits make tracking changes easier.
    • Write clear messages – Follow conventions like:
    feat: Add user authentication
    fix: Resolve login page bug

    This keeps your project history clean and understandable.

    4. Resolving Merge Conflicts Like a Pro

    Conflicts are inevitable in collaborative projects. Learn to resolve them efficiently with:

    • git merge – Combine branches
    • git rebase – Rewrite commit history for a cleaner log
    • VS Code’s built-in conflict resolver for a visual approach

    5. Leveraging Terminal Shortcuts & Aliases

    Speed up your workflow with:

    • Bash/Zsh aliases – Shorten repetitive commands
    • Terminal customization – Optimize your shell for productivity

    Example alias:

    alias gs="git status"

    6. Integrating Git with VS Code

    VS Code’s Source Control panel provides a visual Git interface, allowing you to:

    • Stage & commit changes
    • View commit history
    • Manage branches without leaving the editor

    7. Embracing Collaboration Tools

    Platforms like GitHub, GitLab, and Bitbucket enhance teamwork with:

    • Pull requests – Facilitate code reviews
    • Issue tracking – Manage bugs and enhancements
    • CI/CD pipelines – Automate testing and deployment

    Final Thoughts

    By adopting these practices, you’ll maximize the power of Git CLI and VS Code, streamlining version control and collaboration. Stay curious, explore new features, and continuously refine your workflow for peak efficiency.

    Happy coding!
    — Igor Magalhães Oliveira

  • Understanding the Importance of Version Control in Programming

    Version control tools are indispensable for professional programming teams. Whether you’re collaborating with a team or working solo, integrating version control tools like Git is a fundamental practice.

    By embracing version control tools like Git, you gain a comprehensive history of your project’s development. This enables you to accurately measure future efforts, provide better estimates, and recover working code in case of errors.

    Let’s delve into the usage of Git’s command-line interface:

    • git init: Initializes an empty repository in the current folder, marking the beginning of your version control journey.
    • git branch master: Creates a new branch named “master,” representing a distinct line of development within the codebase.
    • git checkout feature_button: Allows you to switch to another branch for work, with the option to create a new branch using the “-b” parameter.
    • git add: Adds files to the staging area, preparing them for commit. Using “git add .” adds all new and modified files to the staging area.
    • git commit -m "fix: it was fixed this and that": Saves changes in the repository with an intelligible commit message summarizing the changes.
    • git log --oneline: Provides a concise summary of all commits in the repository, enhancing visibility and tracking.
    • git status: Offers insights into the current state of the repository, including the current working branch and staged files.
    • git config: Sets up essential variables for working with remote repositories, ensuring seamless collaboration. Commands like git config --global user.name "yourname" and git config --global user.email "youremail@example.com" are crucial.
    • git merge master: Integrates branches together, a common practice but one requiring careful attention due to potential conflicts.
    • git remote add origin https://github.com/imoliveira88/repositorio: Establishes connections with remote repositories.
    • git clone https://github.com/imoliveira88/repositorio.git: Clones a targeted repository into the current folder.
    • git pull https://github.com/imoliveira88/repositorio master: Fetches and merges content from the remote branch to the local current branch.
    • git push https://github.com/imoliveira88/repositorio master: Sends content from the local branch to the remote branch.

    Incorporating version control tools like Git streamlines development processes, fosters collaboration, and ensures project integrity. Stay tuned for more insights and tips on mastering version control tools. Thank you for joining us on this journey

    By Igor Magalhães Oliveira