All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.shedhack.thread.context.handler.JsonThreadContextHandler Maven / Gradle / Ivy

There is a newer version: 2.2.0
Show newest version
package com.shedhack.thread.context.handler;

import com.google.gson.Gson;
import com.shedhack.thread.context.model.ThreadContextModel;
import com.shedhack.thread.context.model.DefaultThreadContextModel;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * Sets/Gets the thread context as a {@link com.shedhack.thread.context.model.DefaultThreadContextModel}.
 * {@link com.google.gson.Gson} is used to convert the object to a JSON string and back.
 *
 * @author imamchishty
 */
public class JsonThreadContextHandler implements ThreadContextHandler {

    private static Gson GSON = new Gson();

    private final List afterHandlers;

    public JsonThreadContextHandler() {
        this.afterHandlers = Collections.EMPTY_LIST;
    }

    public JsonThreadContextHandler(List afterHandlers) {
        this.afterHandlers = afterHandlers;
    }

    /**
     * {@inheritDoc}
     */
    public void setThreadContext(ThreadContextModel model) {

        if(model != null) {
            String converted = GSON.toJson(model);
            Thread.currentThread().setName(converted);

            // call the after setting handler
            this.afterSettingThreadContext(converted, afterHandlers);
        }
    }

    /**
     * Returns the {@link com.shedhack.thread.context.model.DefaultThreadContextModel}.
     * If for some reason the object cannot be hydrated using GSON then an null {@link java.util.Optional}
     * object is returned.
     */
    public Optional getThreadContext() {
        return convertFromString(Thread.currentThread().getName());
    }

    /**
     * {@inheritDoc}
     */
    public Optional convertFromString(String value) {
        try {
            return Optional.ofNullable(GSON.fromJson(value, DefaultThreadContextModel.class));
        }
        catch (Exception ex) {
            return Optional.empty();
        }
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy