Package com.epam.llpd.greenhouse.web

Source Code of com.epam.llpd.greenhouse.web.ConfigurationHandler

package com.epam.llpd.greenhouse.web;

import com.epam.llpd.greenhouse.Greenhouse;
import com.epam.llpd.greenhouse.config.ConfigDTO;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;

/**
*
* @author Pavel_Vervenko
*/
public class ConfigurationHandler extends AbstractHandler {

    private final ConfigDTO config;
    private final ObjectMapper jsonMapper;
    private final File configFile = new File("config.json");
    private final Greenhouse box;

    public ConfigurationHandler(Greenhouse box) {
        this.jsonMapper = new ObjectMapper();
        config = readConfigFromFile();
        this.box = box;
    }

    @Override
    public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        if (target.startsWith("/saveConfig")) {
            Map map = request.getParameterMap();
            try {
                BeanUtils.populate(config, map);
                jsonMapper.writeValue(configFile, config);
                box.reloadConfig(config);
            } catch (Throwable ex) {
                Logger.getLogger(ConfigurationHandler.class.getName()).log(Level.SEVERE, null, ex);
            }
            response.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
        }
        if (target.startsWith("/getconfig")) {
            jsonMapper.writeValue(response.getWriter(), config);
            response.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
        }
    }

    public static ConfigDTO readConfigFromFile() {
        try {
            ConfigDTO readValue = (new ObjectMapper()).readValue(new File("config.json"), ConfigDTO.class);
            return readValue != null ? readValue : new ConfigDTO();
        } catch (IOException ex) {
            Logger.getLogger(ConfigurationHandler.class.getName()).log(Level.SEVERE, null, ex);
            return null;

        }
    }
}
TOP

Related Classes of com.epam.llpd.greenhouse.web.ConfigurationHandler

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.