001/*
002 * VM-Operator
003 * Copyright (C) 2023 Michael N. Lipp
004 * 
005 * This program is free software: you can redistribute it and/or modify
006 * it under the terms of the GNU Affero General Public License as
007 * published by the Free Software Foundation, either version 3 of the
008 * License, or (at your option) any later version.
009 *
010 * This program is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
013 * GNU Affero General Public License for more details.
014 *
015 * You should have received a copy of the GNU Affero General Public License
016 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
017 */
018
019package org.jdrupes.vmoperator.runner.qemu.commands;
020
021import com.fasterxml.jackson.core.JsonProcessingException;
022import com.fasterxml.jackson.databind.JsonNode;
023import com.fasterxml.jackson.databind.ObjectMapper;
024import java.io.IOException;
025import java.util.logging.Level;
026import java.util.logging.Logger;
027
028/**
029 * The Class QmpCommand.
030 */
031public abstract class QmpCommand {
032
033    @SuppressWarnings({ "PMD.FieldNamingConventions",
034        "PMD.VariableNamingConventions" })
035    protected static final ObjectMapper mapper = new ObjectMapper();
036
037    /**
038     * Parses the json.
039     *
040     * @param json the json
041     * @return the json node
042     */
043    protected static JsonNode parseJson(String json) {
044        try {
045            return mapper.readValue(json, JsonNode.class);
046        } catch (IOException e) {
047            Logger.getLogger(QmpCommand.class.getName()).log(Level.SEVERE, e,
048                () -> "Cannot initialize class: " + e.getMessage());
049            return null;
050        }
051    }
052
053    /**
054     * Returns the Json to be sent to the Qemu process.
055     *
056     * @return the json node
057     */
058    public abstract JsonNode toJson();
059
060    /**
061     * Returns the string representation.
062     *
063     * @return the string
064     * @throws JsonProcessingException the JSON processing exception
065     */
066    public String asText() throws JsonProcessingException {
067        return mapper.writeValueAsString(toJson());
068    }
069
070    /**
071     * Calls {@link #asText()} but suppresses the 
072     * {@link JsonProcessingException}.
073     *
074     * @return the string
075     */
076    @Override
077    public String toString() {
078        try {
079            return asText();
080        } catch (JsonProcessingException e) {
081            return "(no string representation)";
082        }
083    }
084
085}