Thursday, July 12, 2018

Java > Convert text content to Image > Using Java Create An Image And Save To File With Transparent Background

For example, from the string Pritom K Mondal, I would like to generate this simple image:
package com.pkm;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class TextToImage {
    public static void main(String[] args) {
        String text = "Pritom K Mondal";

        BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = img.createGraphics();
        Font font = new Font("Arial", Font.PLAIN, 48);
        g2d.setFont(font);
        FontMetrics fm = g2d.getFontMetrics();
        int width = fm.stringWidth(text) + 20;
        int height = fm.getHeight();
        g2d.dispose();

        img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        g2d = img.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
        g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
        g2d.setFont(font);
        fm = g2d.getFontMetrics();
        g2d.setColor(Color.BLACK);
        g2d.drawString(text, 10, fm.getAscent());
        g2d.dispose();
        try {
            ImageIO.write(img, "png", new File("Image.png"));
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
And output is like below:


Grails on Groovy over Java > Email Address Validation Using Regex

Below is a sample code snippet to validate email address using REGEX
package com.pkm;

import java.util.regex.Pattern;

public class EmailValidationRegex {
    private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+([\\.\\+]?[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    private static Pattern _pattern = null;

    public static void main(String[] args) {
        check("pritomkucse+regex.test@gmail.com");
        check("pkm@c.commmmmmmmmmmmmmmmmmmmm");
        check("pkm@c.commmmmmmmmmmmmmmmmmmmm.");
        check("pkm.+invalid@no.valid");
    }

    static void check(String email) {
        System.out.println(email + " > " + valid(email).toString().toUpperCase());
    }

    static Boolean valid(String email) {
        return getPattern().matcher(email).matches();
    }

    static Pattern getPattern() {
        if (_pattern != null) return _pattern;
        _pattern = Pattern.compile(EMAIL_PATTERN);
        return _pattern;
    }
}

Friday, July 6, 2018

Grails on Groovy > GORM dirty checking of instance and properties > grails - tell me if anything is dirty > Checking for Dirty (Updated) Properties on a Grails Domain

GORM provides Grails developers lots of useful hooks, events, methods, and functionality, very important is domain events that inform you when domain objects are being created, updated, and deleted. Within these events, a common use-case is to determine if a particular domain property has changed, and to act accordingly.
Below is a code snippet of how you validate your domain before insert or update.
package com.pkm

class Table1 {
    Long id
    String name
    String roll

    static mapping = {
        table("table1")
    }

    static hasMany = [
            scores: Table2
    ]

    void beforeValidate(){
        println("BEFORE VALIDATE")
    }

    void beforeInsert(){
        println("BEFORE INSERT")
    }

    void beforeUpdate(){
        println("BEFORE UPDATE")
    }
}
Now, how can you get the actual value of that object? The actual value is modified and you want to get the persisted value. One “not so good” idea is to call refresh() which will load the object from the database again which might be a huge data retrieval in few cases. To solve this problem, GORM has given a simple method which will do the work for you:
Below is a example of how you can see which fields are updating in current transaction using below code snippet
void beforeUpdate(){
    println("BEFORE UPDATE")
    this.dirtyPropertyNames.each { String fieldName ->
        def oldValue = this.getPersistentValue(fieldName)
        def newValue = this.getProperty(fieldName)
        println("\t> VALUE CHANGED FOR $fieldName FROM $oldValue TO $newValue")
    }
}
The best place to check for dirty properties is usually in the beforeUpdate event. The beforeInsert and afterUpdate events may also seem like good choices at first, but they may not be depending on the use-case. Before inserting, all properties are dirty because they are new, so they haven't really changed they have just been created. After updating, none of the properties are dirty because the new values have already been persisted in your database. These events provide plenty of value if used correctly, but may not always be the best place to check for dirty domain properties.
One domain in particular that I always perform dirty property checks on is any User domains that my application requires. For instance, if a User object's password has changed, you may want to be alerted in the beforeUpdate event and encrypt the password before it is inserted into your database.
You also can check if an existing field is dirty or not using
this.isDirty("fieldname")
Be careful not to perform any saves on the domain within these events, as you will get a StackOverflowException. (The event calls .save(), restarting the whole event cycle, where .save() will be called again, and so on. This infinite loop will never end, and the exception will be raised.)
Otherhand you can check if entire session (hibernate session) is dirty or not. so below is an example how to check if whole hibernate session is dirty or not.
package com.pkm

import grails.transaction.Transactional
import org.springframework.transaction.TransactionStatus

import org.hibernate.SessionFactory
import grails.util.Holders

@Transactional
class HomeService {
    TransactionStatus transactionStatus

    void callMe() {
        Table1 table1 = Table1.first()
        table1.roll = System.currentTimeMillis().toString()
        table1.save()

        SessionFactory sessionFactory = Holders.applicationContext.getBean(SessionFactory)
        Boolean isDirty = sessionFactory.currentSession.isDirty()
        println("IS SESSION DIRTY=${isDirty.toString().capitalize()}")
    }
}