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 protected static final ObjectMapper mapper = new ObjectMapper(); 035 036 /** 037 * Parses the json. 038 * 039 * @param json the json 040 * @return the json node 041 */ 042 protected static JsonNode parseJson(String json) { 043 try { 044 return mapper.readValue(json, JsonNode.class); 045 } catch (IOException e) { 046 Logger.getLogger(QmpCommand.class.getName()).log(Level.SEVERE, e, 047 () -> "Cannot initialize class: " + e.getMessage()); 048 return null; 049 } 050 } 051 052 /** 053 * Returns the Json to be sent to the Qemu process. 054 * 055 * @return the json node 056 */ 057 public abstract JsonNode toJson(); 058 059 /** 060 * Returns the string representation. 061 * 062 * @return the string 063 * @throws JsonProcessingException the JSON processing exception 064 */ 065 public String asText() throws JsonProcessingException { 066 return mapper.writeValueAsString(toJson()); 067 } 068 069 /** 070 * Calls {@link #asText()} but suppresses the 071 * {@link JsonProcessingException}. 072 * 073 * @return the string 074 */ 075 @Override 076 public String toString() { 077 try { 078 return asText(); 079 } catch (JsonProcessingException e) { 080 return "(no string representation)"; 081 } 082 } 083 084}