diff options
author | Jonathan Bauer | 2017-10-20 17:48:24 +0200 |
---|---|---|
committer | Jonathan Bauer | 2017-10-20 17:48:24 +0200 |
commit | 17a212b54f42c46f203abbbcea61a80d6f40df61 (patch) | |
tree | 338659b194a09c377cdce914719b741a285b7ea7 /src/main/java/org/openslx | |
parent | [VBox] improved download part (diff) | |
download | master-sync-shared-17a212b54f42c46f203abbbcea61a80d6f40df61.tar.gz master-sync-shared-17a212b54f42c46f203abbbcea61a80d6f40df61.tar.xz master-sync-shared-17a212b54f42c46f203abbbcea61a80d6f40df61.zip |
formatting & first round of cleanup
removed typeOf, use instanceof
Diffstat (limited to 'src/main/java/org/openslx')
-rw-r--r-- | src/main/java/org/openslx/util/vm/VboxConfig.java | 393 | ||||
-rw-r--r-- | src/main/java/org/openslx/util/vm/VboxMetaData.java | 163 | ||||
-rw-r--r-- | src/main/java/org/openslx/util/vm/VmMetaData.java | 159 | ||||
-rw-r--r-- | src/main/java/org/openslx/util/vm/VmwareMetaData.java | 540 |
4 files changed, 558 insertions, 697 deletions
diff --git a/src/main/java/org/openslx/util/vm/VboxConfig.java b/src/main/java/org/openslx/util/vm/VboxConfig.java index d4db21d..44a1eb0 100644 --- a/src/main/java/org/openslx/util/vm/VboxConfig.java +++ b/src/main/java/org/openslx/util/vm/VboxConfig.java @@ -21,92 +21,87 @@ import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.apache.log4j.Logger; -import org.apache.log4j.varia.StringMatchFilter; -import org.openslx.util.vm.VmwareConfig.ConfigEntry; -import org.w3c.dom.Attr; +import org.openslx.util.vm.VmMetaData.DriveBusType; +import org.openslx.util.vm.VmMetaData.HardDisk; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; -import org.openslx.util.vm.VmMetaData.DriveBusType; -import org.openslx.util.vm.VmMetaData.HardDisk; /** * @author victorm * */ -public class VboxConfig -{ - private static final Logger LOGGER = Logger.getLogger( VboxConfig.class ); +public class VboxConfig { + private static final Logger LOGGER = Logger.getLogger(VboxConfig.class); XPath xPath = XPathFactory.newInstance().newXPath(); + private static final String displayNameExpression = "/VirtualBox/Machine/@name"; + private static final String osTypeExpression = "/VirtualBox/Machine/@OSType"; + private static final String hddsExpression = "/VirtualBox/Machine/MediaRegistry/HardDisks/*"; + // a black list of sorts of tags that need to be removed from the .vbox file + private static String[] blackList = { "ExtraData", "Adapter", "GuestProperties", "LPT", "StorageController", + "FloppyImages", "DVDImages", "AttachedDevice" }; + private Document doc = null; - private String displayNameExpression = "/VirtualBox/Machine/@name"; private String displayName; - - private String osTypeExpression = "/VirtualBox/Machine/@OSType"; - private String osName = new String();; - - private String hddsExpression = "/VirtualBox/Machine/MediaRegistry/HardDisks/*"; + private String osName = new String(); private ArrayList<HardDisk> hddsArray = new ArrayList<HardDisk>();; - // a black list of sorts of tags that need to be removed from the .vbox file - private static String[] blackList = { "ExtraData", "Adapter", "GuestProperties", "LPT", "StorageController", "FloppyImages", "DVDImages", "AttachedDevice" }; - /** - * constructor with input xml file - * used to set the doc variable of this class when creating vm + * constructor with input xml file used to set the doc variable of this class + * when creating vm * - * @param file as File - the input xml File + * @param file + * as File - the input xml File * @throws IOException * @throws UnsupportedVirtualizerFormatException */ - public VboxConfig( File file ) throws IOException, UnsupportedVirtualizerFormatException - { + public VboxConfig(File file) throws IOException, UnsupportedVirtualizerFormatException { try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); - doc = dBuilder.parse( file ); + doc = dBuilder.parse(file); // TODO - does this test suffice?? - if ( !doc.getDocumentElement().getNodeName().equals( "VirtualBox" ) ) { - throw new UnsupportedVirtualizerFormatException( "not VirtualBox image format" ); + if (!doc.getDocumentElement().getNodeName().equals("VirtualBox")) { + throw new UnsupportedVirtualizerFormatException("not VirtualBox image format"); } - } catch ( ParserConfigurationException | SAXException | IOException e ) { - LOGGER.warn( "Could not parse .Vbox", e ); - throw new UnsupportedVirtualizerFormatException( "Konnte VBoxConfig nicht erstellen!" ); + } catch (ParserConfigurationException | SAXException | IOException e) { + LOGGER.warn("Could not parse .vbox", e); + throw new UnsupportedVirtualizerFormatException("Konnte VBoxConfig nicht erstellen!"); } displayName = new String(); } /** - * constructor with input string from server - * used to set the doc variable of this class when rebuilding the doc + * constructor with input string from server used to set the doc variable of + * this class when rebuilding the doc * - * @param filtered as String - sent from server + * @param filtered + * as String - sent from server * @param length * @throws IOException */ - public VboxConfig( byte[] filtered, int length ) throws IOException - { + public VboxConfig(byte[] filtered, int length) throws IOException { // TODO test this spoon try { - String filteredString = new String( filtered ); + String filteredString = new String(filtered); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); - //dbFactory.setValidating( true ); - //dbFactory.setIgnoringElementContentWhitespace( true ); + // dbFactory.setValidating( true ); + // dbFactory.setIgnoringElementContentWhitespace( true ); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); - InputSource is = new InputSource( new StringReader( filteredString ) ); - - doc = dBuilder.parse( is ); + InputSource is = new InputSource(new StringReader(filteredString)); - } catch ( ParserConfigurationException | SAXException e ) { + doc = dBuilder.parse(is); - LOGGER.warn( "Could not recreate the dom", e ); + } catch (Exception e) { + // catch everything for now... + LOGGER.warn("Could not recreate the dom", e); } } @@ -115,31 +110,29 @@ public class VboxConfig * * @return definition document */ - public Document getConfigDoc() - { + public Document getConfigDoc() { return doc; } /** * initialization function */ - public void init() - { - if ( doc.getChildNodes().item( 0 ).getNodeType() == 8 ) { - doc.removeChild( doc.getChildNodes().item( 0 ) ); + public void init() { + if (doc.getChildNodes().item(0).getNodeType() == 8) { + doc.removeChild(doc.getChildNodes().item(0)); } try { setMachineName(); setOsType(); - if ( checkForPlaceholders() ) { - LOGGER.debug( "we have placeholders" ); + if (checkForPlaceholders()) { + LOGGER.debug("we have placeholders"); return; } setHdds(); removeBlackListedTags(); addPlaceHolders(); - } catch ( XPathExpressionException e ) { - LOGGER.debug( "Konnte VBoxConfig nicht initializieren", e ); + } catch (XPathExpressionException e) { + LOGGER.debug("Konnte VBoxConfig nicht initializieren", e); return; } } @@ -149,108 +142,104 @@ public class VboxConfig * * @return true if the placeholders are present, false otherwise */ - private boolean checkForPlaceholders() - { - NodeList hdds = findANode( "HardDisk" ); - for ( int i = 0; i < hdds.getLength(); i++ ) { - Element hdd = (Element)hdds.item( i ); - if ( hdd.getAttribute( "location" ).equals( "#some_fancy_HDD_place_holder" ) ) { + private boolean checkForPlaceholders() { + NodeList hdds = findNodes("HardDisk"); + for (int i = 0; i < hdds.getLength(); i++) { + Element hdd = (Element) hdds.item(i); + if (hdd.getAttribute("location").equals("#some_fancy_HDD_place_holder")) { return true; } } return false; } - public void setMachineName() throws XPathExpressionException - { - String name = xPath.compile( displayNameExpression ).evaluate( this.doc ); - if ( !name.isEmpty() ) { + public void setMachineName() throws XPathExpressionException { + String name = xPath.compile(displayNameExpression).evaluate(this.doc); + if (!name.isEmpty()) { displayName = name; } } - public void setOsType() throws XPathExpressionException - { - String os = xPath.compile( osTypeExpression ).evaluate( this.doc ); - if ( !os.isEmpty() ) { + public void setOsType() throws XPathExpressionException { + String os = xPath.compile(osTypeExpression).evaluate(this.doc); + if (!os.isEmpty()) { osName = os; } } - public void setHdds() throws XPathExpressionException - { - XPathExpression hddsExpr = xPath.compile( hddsExpression ); - Object result = hddsExpr.evaluate( this.doc, XPathConstants.NODESET ); + public void setHdds() throws XPathExpressionException { + XPathExpression hddsExpr = xPath.compile(hddsExpression); + Object result = hddsExpr.evaluate(this.doc, XPathConstants.NODESET); // take all the hdd nodes - NodeList nodes = (NodeList)result; + NodeList nodes = (NodeList) result; // TODO find all HardDisk under HardDisks, give them to the hdds // foreach hdd in the hddnodes do: - for ( int i = 0; i < nodes.getLength(); i++ ) { + for (int i = 0; i < nodes.getLength(); i++) { // have the node // take the uuid // look under <AttachedDevice if found and do stuff with it - Element hddElement = (Element)nodes.item( i ); + Element hddElement = (Element) nodes.item(i); // read the filePath - String fileName = hddElement.getAttribute( "location" ); + String fileName = hddElement.getAttribute("location"); // take the uuid - String uuid = hddElement.getAttribute( "uuid" ); + String uuid = hddElement.getAttribute("uuid"); // do the loop the loop - // search in the xml object and give back the parent of the parent of the node that is called Image and has the given uuid - String pathToParent = givePathToStorageController( uuid ); - XPathExpression attachedDevicesExpr = xPath.compile( pathToParent ); - Object devicesResult = attachedDevicesExpr.evaluate( this.doc, XPathConstants.NODESET ); - NodeList devicesNodes = (NodeList)devicesResult; + // search in the xml object and give back the parent of the parent of the node + // that is called Image and has the given uuid + String pathToParent = givePathToStorageController(uuid); + XPathExpression attachedDevicesExpr = xPath.compile(pathToParent); + Object devicesResult = attachedDevicesExpr.evaluate(this.doc, XPathConstants.NODESET); + NodeList devicesNodes = (NodeList) devicesResult; // TODO -- ehm...should only have 1 element...what do when there are more? - if ( devicesNodes.getLength() > 1 ) { - LOGGER.error( "There can not be more HDDs with the same UUID!" ); + if (devicesNodes.getLength() > 1) { + LOGGER.error("There can not be more HDDs with the same UUID!"); return; } - Element deviceElement = (Element)devicesNodes.item( 0 ); - String controllerDevice = deviceElement.getAttribute( "type" ); - String bus = deviceElement.getAttribute( "name" ); + Element deviceElement = (Element) devicesNodes.item(0); + String controllerDevice = deviceElement.getAttribute("type"); + String bus = deviceElement.getAttribute("name"); DriveBusType busType = null; - if ( bus.equals( "IDE" ) ) { + if (bus.equals("IDE")) { busType = DriveBusType.IDE; - } else if ( bus.equals( "SCSI" ) ) { + } else if (bus.equals("SCSI")) { busType = DriveBusType.SCSI; - } else if ( bus.equals( "SATA" ) ) { + } else if (bus.equals("SATA")) { busType = DriveBusType.SATA; } // add them together - hddsArray.add( new HardDisk( controllerDevice, busType, fileName ) ); + hddsArray.add(new HardDisk(controllerDevice, busType, fileName)); } } - public void addPlaceHolders() - { + public void addPlaceHolders() { // placeholder for the location of the virtual hdd - changeAttribute( "HardDisk", "location", "#some_fancy_HDD_place_holder" ); + changeAttribute("HardDisk", "location", "#some_fancy_HDD_place_holder"); // placeholder for the memory - changeAttribute( "Memory", "RAMSize", "#some_fancy_MEMORY_place_holder" ); + changeAttribute("Memory", "RAMSize", "#some_fancy_MEMORY_place_holder"); // placeholder for the CPU - changeAttribute( "CPU", "count", "#some_fancy_CPU_place_holder" ); + changeAttribute("CPU", "count", "#some_fancy_CPU_place_holder"); // add placeholder for the uuid of the virtual harddrive. // must be added on 2 positions...in the HardDisk tag and the attachedDevice tag // first find the uuid - NodeList hdds = findANode( "HardDisk" ); - for ( int i = 0; i < hdds.getLength(); i++ ) { - Element hdd = (Element)findANode( "HardDisk" ).item( i ); - String uuid = hdd.getAttribute( "uuid" ); - hdd.setAttribute( "uuid", "#some_fancy_HDDUUID_" + i + "_placeholder" ); - NodeList images = findANode( "Image" ); + NodeList hdds = findNodes("HardDisk"); + for (int i = 0; i < hdds.getLength(); i++) { + Element hdd = (Element) findNodes("HardDisk").item(i); + String uuid = hdd.getAttribute("uuid"); + hdd.setAttribute("uuid", "#some_fancy_HDDUUID_" + i + "_placeholder"); + NodeList images = findNodes("Image"); Element image; - for ( int j = 0; j < images.getLength(); j++ ) { - if ( ( (Element)images.item( j ) ).getAttribute( "uuid" ).equals( uuid ) ) { - image = (Element)images.item( j ); - image.setAttribute( "uuid", "#some_fancy_HDDUUID_" + i + "_placeholder" ); + for (int j = 0; j < images.getLength(); j++) { + if (((Element) images.item(j)).getAttribute("uuid").equals(uuid)) { + image = (Element) images.item(j); + image.setAttribute("uuid", "#some_fancy_HDDUUID_" + i + "_placeholder"); break; } } @@ -258,46 +247,43 @@ public class VboxConfig } /** - * Function used to find a node in the document - * Function returnes a NodeList of Nodes...not just a Node...even when the wanted Node a single - * Node is - * you get a NodeList with just one element + * Function used to find a node in the document Function returns a NodeList of + * Nodes...not just a Node...even when the wanted Node a single Node is you get + * a NodeList with just one element * - * @param targetTag as String + * @param targetTag + * as String * @return nodes as NodeList */ - public NodeList findANode( String targetTag ) - { + public NodeList findNodes(String targetTag) { String path = ".//" + targetTag; - XPathExpression expr; NodeList nodes = null; try { - expr = xPath.compile( path ); - Object nodesObject = expr.evaluate( this.doc, XPathConstants.NODESET ); - nodes = (NodeList)nodesObject; - } catch ( XPathExpressionException e ) { - LOGGER.error( "Path konnte nicht gebaut werden", e ); + XPathExpression expr = xPath.compile(path); + Object nodesObject = expr.evaluate(this.doc, XPathConstants.NODESET); + nodes = (NodeList) nodesObject; + } catch (XPathExpressionException e) { + LOGGER.error("Could not compile xPath expression: " + path, e); } return nodes; } /** - * Function used to change the value of an attribute - * Use this function if you know the targetNode is unique + * Function used to change the value of an attribute Use this function if you + * know the targetNode is unique * * @param targetTag * @param attribute * @param newValue */ - public void changeAttribute( String targetTag, String attribute, String newValue ) - { - changeAttribute( targetTag, attribute, newValue, null, null ); + public void changeAttribute(String targetTag, String attribute, String newValue) { + changeAttribute(targetTag, attribute, newValue, null, null); } /** - * Function used to change the value of an attribute - * Use this function if you are not sure if the targetNode is unique - * Use refAttr and refVal to address the right node + * Function used to change the value of an attribute Use this function if you + * are not sure if the targetNode is unique Use refAttr and refVal to address + * the right node * * @param targetTag * @param targetAttr @@ -305,172 +291,167 @@ public class VboxConfig * @param refAttr * @param refVal */ - public void changeAttribute( String targetTag, String targetAttr, String newValue, String refAttr, String refVal ) - { - NodeList nodes = findANode( targetTag ); - - for ( int i = 0; i < nodes.getLength(); i++ ) { - Element element = (Element)nodes.item( i ); - if ( refAttr != null && refVal != null ) { - if ( element.getAttribute( refAttr ).equals( refVal ) ) { - element.setAttribute( targetAttr, newValue ); + public void changeAttribute(String targetTag, String targetAttr, String newValue, String refAttr, String refVal) { + + NodeList nodes = findNodes(targetTag); + for (int i = 0; i < nodes.getLength(); i++) { + Element element = (Element) nodes.item(i); + if (refAttr != null && refVal != null) { + if (element.getAttribute(refAttr).equals(refVal)) { + element.setAttribute(targetAttr, newValue); break; } } else { - if ( nodes.getLength() > 1 ) { - LOGGER.error( "Aktion würde an mehreren Knotten die Value ändern; unterbrochen!" ); + if (nodes.getLength() > 1) { + LOGGER.error("Aktion würde an mehreren Knoten die Value ändern; unterbrochen!"); return; } - element.setAttribute( targetAttr, newValue ); + element.setAttribute(targetAttr, newValue); } } } - public void addAttributeToNode( Node targetNode, String attrName, String value ) - { - if ( targetNode == null ) { - LOGGER.warn( "Knotten ist null; unterbrochen!" ); + public void addAttributeToNode(Node targetNode, String attrName, String value) { + if (targetNode == null) { return; } - ( (Element)targetNode ).setAttribute( attrName, value ); + ((Element) targetNode).setAttribute(attrName, value); } - public Node addNewNode( String nameOfParent, String nameOfnewNode, boolean oneLiner ) - { - return addNewNode( nameOfParent, nameOfnewNode, oneLiner, null, null ); + public Node addNewNode(String nameOfParent, String nameOfnewNode, boolean oneLiner) { + return addNewNode(nameOfParent, nameOfnewNode, oneLiner, null, null); } - public Node addNewNode( String nameOfParent, String nameOfnewNode, boolean oneLiner, String refAttr, String refVal ) - { + public Node addNewNode(String nameOfParent, String nameOfnewNode, boolean oneLiner, String refAttr, String refVal) { Node parent = null; - NodeList posibleParents = findANode( nameOfParent ); - if ( posibleParents.getLength() > 1 ) { - // if we have more then 1 parent we need to have an sanityArg s.t. we insert our new attribute in the right tag - if ( refAttr == null ) { - LOGGER.warn( "Aktion würde an mehreren Knotten einen neuen Knoten hinzufügen; unterbrochen!" ); + NodeList posibleParents = findNodes(nameOfParent); + if (posibleParents.getLength() > 1) { + // if we have more then 1 parent we need to have an sanityArg s.t. we insert our + // new attribute in the right tag + if (refAttr == null) { + LOGGER.warn("Aktion würde an mehreren Knoten einen neuen Knoten hinzufügen; unterbrochen!"); return null; } - for ( int i = 1; i < posibleParents.getLength(); i++ ) { - if ( ( (Element)posibleParents.item( i ) ).getAttribute( refAttr ).equals( refVal ) ) { - parent = posibleParents.item( i ); + for (int i = 1; i < posibleParents.getLength(); i++) { + if (((Element) posibleParents.item(i)).getAttribute(refAttr).equals(refVal)) { + parent = posibleParents.item(i); break; } } } else { - parent = posibleParents.item( 0 ); + parent = posibleParents.item(0); } - if ( parent == null ) { - LOGGER.warn( "Node: '" + nameOfParent + "' could not be found" ); + if (parent == null) { + LOGGER.warn("Node: '" + nameOfParent + "' could not be found"); return null; } - Element newTag = doc.createElement( nameOfnewNode ); + Element newTag = doc.createElement(nameOfnewNode); - if ( !oneLiner ) { - org.w3c.dom.Text a = doc.createTextNode( "\n" ); - newTag.appendChild( a ); + if (!oneLiner) { + org.w3c.dom.Text a = doc.createTextNode("\n"); + newTag.appendChild(a); } - parent.appendChild( newTag ); + parent.appendChild(newTag); return newTag; } - // function removes a given child and the format childNode - private void removeNode( Node node ) - { + // function removes a given child and the format childNode + private void removeNode(Node node) { Node parent = node.getParentNode(); - // this node here is usually a type3 Node used only for the formating of the vbox file + // this node here is usually a type3 Node used only for the formating of the + // vbox file Node previousSibling = node.getPreviousSibling(); - parent.removeChild( node ); + parent.removeChild(node); // HACK remove empty lines // format children have type 3 - if ( previousSibling.getNodeType() == 3 ) { + if (previousSibling.getNodeType() == 3) { // the value of these Nodes are characters String tmp = previousSibling.getNodeValue(); boolean shouldDelete = true; - for ( int foo = 0; foo < tmp.length(); foo++ ) { - if ( !Character.isWhitespace( tmp.charAt( foo ) ) ) { + for (int foo = 0; foo < tmp.length(); foo++) { + if (!Character.isWhitespace(tmp.charAt(foo))) { shouldDelete = false; break; } } - if ( shouldDelete ) - parent.removeChild( previousSibling ); + if (shouldDelete) + parent.removeChild(previousSibling); } } // cleanup part here - private void removeBlackListedTags() throws XPathExpressionException - { + private void removeBlackListedTags() throws XPathExpressionException { // iterate over the blackList - for ( String blackedTag : blackList ) { + for (String blackedTag : blackList) { String blackedExpression = ".//" + blackedTag; - XPathExpression blackedExpr = xPath.compile( blackedExpression ); + XPathExpression blackedExpr = xPath.compile(blackedExpression); - NodeList blackedNodes = (NodeList)blackedExpr.evaluate( this.doc, XPathConstants.NODESET ); - //LOGGER.debug( blackedNodes.getLength() ); - for ( int i = 0; i < blackedNodes.getLength(); i++ ) { + NodeList blackedNodes = (NodeList) blackedExpr.evaluate(this.doc, XPathConstants.NODESET); + // LOGGER.debug( blackedNodes.getLength() ); + for (int i = 0; i < blackedNodes.getLength(); i++) { // get the child node - Element child = (Element)blackedNodes.item( i ); + Element child = (Element) blackedNodes.item(i); // remove child - if ( child.getTagName().equals( "Adapter" ) && child.getAttribute( "enabled" ).equals( "true" ) ) { + if (child.getTagName().equals("Adapter") && child.getAttribute("enabled").equals("true")) { // we need to remove the children of the active network adapter - // these are the mode of network connection and disabled modes...they go together -> see wiki - if ( child.getChildNodes().item( 0 ).getNodeName().equals( "#text" ) && !child.getChildNodes().item( 1 ).getNodeName().equals( "#text" ) ) { - removeNode( child.getChildNodes().item( 1 ) ); + // these are the mode of network connection and disabled modes...they go + // together -> see wiki + if (child.getChildNodes().item(0).getNodeName().equals("#text") + && !child.getChildNodes().item(1).getNodeName().equals("#text")) { + removeNode(child.getChildNodes().item(1)); } continue; } - if ( ( child.getTagName().equals( "StorageController" ) && !child.getAttribute( "name" ).equals( "Floppy" ) ) - || ( child.getTagName().equals( "AttachedDevice" ) && child.getAttribute( "type" ).equals( "HardDisk" ) ) ) { + if ((child.getTagName().equals("StorageController") && !child.getAttribute("name").equals("Floppy")) + || (child.getTagName().equals("AttachedDevice") + && child.getAttribute("type").equals("HardDisk"))) { continue; } - // the structure of the xml Document is achieved through children nodes that are made up of just /n and spaces - // when a child node is deleted we get an empty line there the old child node used to be - removeNode( child ); + // the structure of the xml Document is achieved through children nodes that are + // made up of just /n and spaces + // when a child node is deleted we get an empty line there the old child node + // used to be + removeNode(child); } } } - private String givePathToStorageController( String uuid ) - { + private String givePathToStorageController(String uuid) { // StorageController is the parent of the parent of node with given uuid return "//Image[contains(@uuid, \'" + uuid + "\')]/../.."; } - public String getDisplayName() - { + public String getDisplayName() { return displayName; } - public String getOsName() - { + public String getOsName() { return osName; } - public ArrayList<HardDisk> getHdds() - { + public ArrayList<HardDisk> getHdds() { return hddsArray; } - public String toString() - { + public String toString() { try { StringWriter sw = new StringWriter(); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); - transformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "no" ); - transformer.setOutputProperty( OutputKeys.METHOD, "xml" ); - transformer.setOutputProperty( OutputKeys.INDENT, "yes" ); - transformer.setOutputProperty( OutputKeys.ENCODING, "UTF-8" ); + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); + transformer.setOutputProperty(OutputKeys.METHOD, "xml"); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); - transformer.transform( new DOMSource( doc ), new StreamResult( sw ) ); + transformer.transform(new DOMSource(doc), new StreamResult(sw)); return sw.toString(); - } catch ( Exception ex ) { - throw new RuntimeException( "Error converting to String", ex ); + } catch (Exception ex) { + throw new RuntimeException("Error converting to String", ex); } } diff --git a/src/main/java/org/openslx/util/vm/VboxMetaData.java b/src/main/java/org/openslx/util/vm/VboxMetaData.java index 5115248..9ea59d2 100644 --- a/src/main/java/org/openslx/util/vm/VboxMetaData.java +++ b/src/main/java/org/openslx/util/vm/VboxMetaData.java @@ -19,209 +19,186 @@ import org.apache.log4j.Logger; import org.openslx.bwlp.thrift.iface.OperatingSystem; import org.openslx.bwlp.thrift.iface.Virtualizer; -public class VboxMetaData extends VmMetaData -{ - private static final Logger LOGGER = Logger.getLogger( VboxMetaData.class ); - private static final Virtualizer virtualizer = new Virtualizer( "virtualbox", "VirtualBox" ); +public class VboxMetaData extends VmMetaData { - private final VboxConfig config; + private static final Logger LOGGER = Logger.getLogger(VboxMetaData.class); + + private static final Virtualizer virtualizer = new Virtualizer("virtualbox", "VirtualBox"); - public VboxMetaData( List<OperatingSystem> osList, File file ) throws IOException, UnsupportedVirtualizerFormatException - { - super( osList ); + private final VboxConfig config; - this.config = new VboxConfig( file ); + public VboxMetaData(List<OperatingSystem> osList, File file) + throws IOException, UnsupportedVirtualizerFormatException { + super(osList); + this.config = new VboxConfig(file); init(); } - public VboxMetaData( List<OperatingSystem> osList, byte[] vmContent, int length ) throws IOException, UnsupportedVirtualizerFormatException - { - super( osList ); - this.config = new VboxConfig( vmContent, length ); - setTypeOf(); - init(); + public VboxMetaData(List<OperatingSystem> osList, byte[] vmContent, int length) + throws IOException, UnsupportedVirtualizerFormatException { + super(osList); + this.config = new VboxConfig(vmContent, length); + init(); } - private void init() - { + private void init() { this.config.init(); - displayName = config.getDisplayName(); + setOs("virtualbox", config.getOsName()); - setOs( "virtualbox", config.getOsName() ); - - for ( HardDisk hardDisk : config.getHdds() ) { - hdds.add( hardDisk ); + for (HardDisk hardDisk : config.getHdds()) { + hdds.add(hardDisk); } + + // DEBUG Code???? mark such code please! try { - addFloppy( 0, null, true ); + addFloppy(0, null, true); WriteToFile(); - } catch ( TransformerFactoryConfigurationError | TransformerException e ) { + } catch (TransformerFactoryConfigurationError | TransformerException e) { // WriteToFile exceptions here...not important for the the LOGGER e.printStackTrace(); } } // --TODO will be needed later again - private void WriteToFile() throws TransformerFactoryConfigurationError, TransformerException - { + private void WriteToFile() throws TransformerFactoryConfigurationError, TransformerException { Transformer transformer = TransformerFactory.newInstance().newTransformer(); - StreamResult output = new StreamResult( new File( "output.xml" ) ); - Source input = new DOMSource( config.getConfigDoc() ); - transformer.transform( input, output ); + StreamResult output = new StreamResult(new File("output.xml")); + Source input = new DOMSource(config.getConfigDoc()); + transformer.transform(input, output); } @Override - public Virtualizer getVirtualizer() - { - return new Virtualizer( "virtualbox", "VirtualBox" ); + public Virtualizer getVirtualizer() { + return virtualizer; } @Override - public void enableUsb( boolean enabled ) - { + public void enableUsb(boolean enabled) { // TODO Auto-generated method stub } @Override - public void applySettingsForLocalEdit() - { + public void applySettingsForLocalEdit() { // TODO Auto-generated method stub } @Override - public byte[] getFilteredDefinitionArray() - { - return config.toString().getBytes( StandardCharsets.UTF_8 ); + public byte[] getFilteredDefinitionArray() { + return config.toString().getBytes(StandardCharsets.UTF_8); } @Override - public boolean addHddTemplate( String diskImage, String hddMode, String redoDir ) - { - config.changeAttribute( "HardDisk", "location", diskImage ); + public boolean addHddTemplate(String diskImage, String hddMode, String redoDir) { + config.changeAttribute("HardDisk", "location", diskImage); return true; } @Override - public boolean addHddTemplate( File diskImage, String hddMode, String redoDir ) - { + public boolean addHddTemplate(File diskImage, String hddMode, String redoDir) { String diskImagePath = diskImage.getName(); - config.changeAttribute( "HardDisk", "location", diskImagePath ); + config.changeAttribute("HardDisk", "location", diskImagePath); UUID newhdduuid = UUID.randomUUID(); - LOGGER.debug( newhdduuid ); + LOGGER.debug(newhdduuid); // patching the new uuid in the vbox config file here String vboxUUid = "{" + newhdduuid.toString() + "}"; - config.changeAttribute( "HardDisk", "uuid", vboxUUid ); - config.changeAttribute( "Image", "uuid", vboxUUid ); + config.changeAttribute("HardDisk", "uuid", vboxUUid); + config.changeAttribute("Image", "uuid", vboxUUid); // write the new hdd uuid in the vdi file - byte[] bytesToWrite = new byte[ 16 ]; - - int[] bytesOffset = {32, 40, 48, 56, 16, 24, 0, 8, 56, 48, 40, 32, 24, 16, 8, 0}; - + byte[] bytesToWrite = new byte[16]; + + int[] bytesOffset = { 32, 40, 48, 56, 16, 24, 0, 8, 56, 48, 40, 32, 24, 16, 8, 0 }; + int offset = 0; for (int i = 0; i < 2; i++) { Long uuidlong = null; - if ( i == 0 ) { + if (i == 0) { uuidlong = newhdduuid.getMostSignificantBits(); } else { uuidlong = newhdduuid.getLeastSignificantBits(); } - - for ( int j = 0; j < 8; j++) { + + for (int j = 0; j < 8; j++) { int index = j + offset; bytesToWrite[index] = (byte) (uuidlong >>> bytesOffset[index]); } offset = 8; } - try ( RandomAccessFile file = new RandomAccessFile( diskImage, "rw" ) ) { + try (RandomAccessFile file = new RandomAccessFile(diskImage, "rw")) { - file.seek( 392 ); - file.write( bytesToWrite, 0, 16 ); - } catch ( Exception e ) { - LOGGER.warn( "could not patch new uuid in the vdi", e ); + file.seek(392); + file.write(bytesToWrite, 0, 16); + } catch (Exception e) { + LOGGER.warn("could not patch new uuid in the vdi", e); } - - // we need a new machine uuid + + // we need a new machine uuid UUID newMachineUuid = UUID.randomUUID(); - if ( newMachineUuid.equals( newhdduuid ) ) { - LOGGER.warn( "The new Machine UUID is the same as the new HDD UUID; tying again...this vm might not start" ); + if (newMachineUuid.equals(newhdduuid)) { + LOGGER.warn("The new Machine UUID is the same as the new HDD UUID; tying again...this vm might not start"); newMachineUuid = UUID.randomUUID(); } String machineUUid = "{" + newMachineUuid.toString() + "}"; - config.changeAttribute( "Machine", "uuid", machineUUid ); + config.changeAttribute("Machine", "uuid", machineUUid); return true; } @Override - public boolean addDefaultNat() - { - config.addNewNode( "Adapter", "NAT", false ); + public boolean addDefaultNat() { + config.addNewNode("Adapter", "NAT", false); return true; } - public void reWrite() - { + public void reWrite() { try { WriteToFile(); - } catch ( TransformerFactoryConfigurationError | TransformerException e ) { + } catch (TransformerFactoryConfigurationError | TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override - public void setOs( String vendorOsId ) - { + public void setOs(String vendorOsId) { // TODO Auto-generated method stub } @Override - public boolean addDisplayName( String name ) - { - config.changeAttribute( "Machine", "name", name ); + public boolean addDisplayName(String name) { + config.changeAttribute("Machine", "name", name); return true; } @Override - public boolean addRam( int mem ) - { - config.changeAttribute( "Memory", "RAMSize", Integer.toString( mem ) ); + public boolean addRam(int mem) { + config.changeAttribute("Memory", "RAMSize", Integer.toString(mem)); return true; } @Override - public void addFloppy( int index, String image, boolean readOnly ) - { + public void addFloppy(int index, String image, boolean readOnly) { - if ( image == null ) { + if (image == null) { } else { } } @Override - public boolean addCdrom( String image ) - { + public boolean addCdrom(String image) { // TODO Auto-generated method stub return false; } @Override - public void setTypeOf() - { - typeOf = TypeOf.VBOX; - } - - @Override - public boolean addCpuCoreCount( int nrOfCores ) - { - config.changeAttribute( "CPU", "count", "1" ); + public boolean addCpuCoreCount(int nrOfCores) { + config.changeAttribute("CPU", "count", "1"); return true; } } diff --git a/src/main/java/org/openslx/util/vm/VmMetaData.java b/src/main/java/org/openslx/util/vm/VmMetaData.java index 200aef9..dc93dc9 100644 --- a/src/main/java/org/openslx/util/vm/VmMetaData.java +++ b/src/main/java/org/openslx/util/vm/VmMetaData.java @@ -13,39 +13,25 @@ import org.openslx.bwlp.thrift.iface.OperatingSystem; import org.openslx.bwlp.thrift.iface.Virtualizer; /** - * Describes a configured virtual machine. This class is parsed from a machine description, like a - * *.vmx for VMware machines. + * Describes a configured virtual machine. This class is parsed from a machine + * description, like a *.vmx for VMware machines. */ -public abstract class VmMetaData -{ - private static final Logger LOGGER = Logger.getLogger( VmMetaData.class ); +public abstract class VmMetaData { + private static final Logger LOGGER = Logger.getLogger(VmMetaData.class); /* * Helper types */ - public static enum TypeOf - { - VMX, - VBOX; + public static enum DriveBusType { + SCSI, IDE, SATA; } - public static TypeOf typeOf = null; - - public static enum DriveBusType - { - SCSI, - IDE, - SATA; - } - - public static class HardDisk - { + public static class HardDisk { public final String chipsetDriver; public final DriveBusType bus; public final String diskImage; - public HardDisk( String chipsetDriver, DriveBusType bus, String diskImage ) - { + public HardDisk(String chipsetDriver, DriveBusType bus, String diskImage) { this.chipsetDriver = chipsetDriver; this.bus = bus; this.diskImage = diskImage; @@ -70,67 +56,64 @@ public abstract class VmMetaData /** * Get operating system of this VM. */ - public OperatingSystem getOs() - { + public OperatingSystem getOs() { return os; } /** * Get all hard disks of this VM. */ - public List<HardDisk> getHdds() - { - return Collections.unmodifiableList( hdds ); + public List<HardDisk> getHdds() { + return Collections.unmodifiableList(hdds); } /** * Get display name of VM. */ - public String getDisplayName() - { + public String getDisplayName() { return displayName; } /** - * This method should return a minimal representation of the input meta data. The representation - * is platform dependent, and should be stripped of all non-essential configuration, such as - * CD/DVD/FLoppy drives, serial or parallel ports, shared folders, or anything else that could be - * considered sensible information (absolute paths containing the local user's name). + * This method should return a minimal representation of the input meta data. + * The representation is platform dependent, and should be stripped of all + * non-essential configuration, such as CD/DVD/FLoppy drives, serial or parallel + * ports, shared folders, or anything else that could be considered sensible + * information (absolute paths containing the local user's name). */ public abstract byte[] getFilteredDefinitionArray(); - public final ByteBuffer getFilteredDefinition() - { - return ByteBuffer.wrap( getFilteredDefinitionArray() ); + public final ByteBuffer getFilteredDefinition() { + return ByteBuffer.wrap(getFilteredDefinitionArray()); } /* * Methods */ - public VmMetaData( List<OperatingSystem> osList ) - { + public VmMetaData(List<OperatingSystem> osList) { this.osList = osList; } /** - * Called from subclass to set the OS. If the OS cannot be determined from the given parameters, - * it will not be set. + * Called from subclass to set the OS. If the OS cannot be determined from the + * given parameters, it will not be set. * - * @param virtId virtualizer, eg "vmware" for VMware - * @param virtOsId the os identifier used by the virtualizer, eg. windows7-64 for 64bit Windows 7 - * on VMware + * @param virtId + * virtualizer, eg "vmware" for VMware + * @param virtOsId + * the os identifier used by the virtualizer, eg. windows7-64 for + * 64bit Windows 7 on VMware */ - protected final void setOs( String virtId, String virtOsId ) - { + protected final void setOs(String virtId, String virtOsId) { OperatingSystem lazyMatch = null; - for ( OperatingSystem os : osList ) { - if ( os.getVirtualizerOsId() == null ) + for (OperatingSystem os : osList) { + if (os.getVirtualizerOsId() == null) continue; - for ( Entry<String, String> entry : os.getVirtualizerOsId().entrySet() ) { - if ( !entry.getValue().equals( virtOsId ) ) + for (Entry<String, String> entry : os.getVirtualizerOsId().entrySet()) { + if (!entry.getValue().equals(virtOsId)) continue; - if ( entry.getKey().equals( virtId ) ) { + if (entry.getKey().equals(virtId)) { this.os = os; return; } else { @@ -145,79 +128,63 @@ public abstract class VmMetaData public abstract Virtualizer getVirtualizer(); - public abstract void enableUsb( boolean enabled ); + public abstract void enableUsb(boolean enabled); /** - * Apply config options that are desired when locally editing a VM. - * for vmware, this disables automatic DPI scaling of the guest. + * Apply config options that are desired when locally editing a VM. for vmware, + * this disables automatic DPI scaling of the guest. */ public abstract void applySettingsForLocalEdit(); // meta object needed when reading vm from file - public static VmMetaData getInstance( List<OperatingSystem> osList, File file ) throws IOException - { - - VmMetaData meta = null; + public static VmMetaData getInstance(List<OperatingSystem> osList, File file) throws IOException { try { - meta = new VmwareMetaData( osList, file ); - } catch ( UnsupportedVirtualizerFormatException e ) { - LOGGER.debug( "datei war nicht .vmx; versuche mit VBox" ); - try { - meta = new VboxMetaData( osList, file ); - } catch ( UnsupportedVirtualizerFormatException ex ) { - LOGGER.debug( "datei war nicht .vbox; unterbrochen!", ex ); - // TODO ok so or throw new IOException? - } + return new VmwareMetaData(osList, file); + } catch (UnsupportedVirtualizerFormatException e) { + LOGGER.debug("Disk file not .vmdk"); } - if ( meta != null ) { - return meta; + try { + return new VboxMetaData(osList, file); + } catch (UnsupportedVirtualizerFormatException e) { + LOGGER.debug("Disk file not .vdi"); } + LOGGER.error("Unsupported disk file format!"); return null; } // meta object needed when reading from configarray - public static VmMetaData getInstance( List<OperatingSystem> osList, byte[] vmContent, int length ) throws IOException - { - - VmMetaData meta = null; + public static VmMetaData getInstance(List<OperatingSystem> osList, byte[] vmContent, int length) + throws IOException { try { - meta = new VmwareMetaData( osList, vmContent, length ); - } catch ( UnsupportedVirtualizerFormatException e ) { - LOGGER.debug( "machine Description entspricht nicht vmx format; versuche mit VBox" ); - try { - meta = new VboxMetaData( osList, vmContent, length ); - } catch ( UnsupportedVirtualizerFormatException ex ) { - LOGGER.debug( "machine Description entspricht nicht vbox format ); unterbrochen!", ex ); - } + return new VmwareMetaData(osList, vmContent, length); + } catch (UnsupportedVirtualizerFormatException e) { + LOGGER.debug("Machine description not in .vmx format.", e); } - if ( meta != null ) { - return meta; + try { + return new VboxMetaData(osList, vmContent, length); + } catch (UnsupportedVirtualizerFormatException e) { + LOGGER.debug("Machine description not in .vbox format.", e); } + LOGGER.error("Machine description has an unknown format!"); return null; } - public abstract boolean addHddTemplate( File diskImage, String hddMode, String redoDir ); + public abstract boolean addHddTemplate(File diskImage, String hddMode, String redoDir); - public abstract boolean addHddTemplate( String diskImagePath, String hddMode, String redoDir ); + public abstract boolean addHddTemplate(String diskImagePath, String hddMode, String redoDir); public abstract boolean addDefaultNat(); - public abstract void setOs( String vendorOsId ); + public abstract void setOs(String vendorOsId); - public abstract boolean addDisplayName( String name ); + public abstract boolean addDisplayName(String name); - public abstract boolean addRam( int mem ); + public abstract boolean addRam(int mem); - public abstract void addFloppy( int index, String image, boolean readOnly ); + public abstract void addFloppy(int index, String image, boolean readOnly); - public abstract boolean addCdrom( String image ); + public abstract boolean addCdrom(String image); - public abstract void setTypeOf(); + public abstract boolean addCpuCoreCount(int nrOfCores); - public abstract boolean addCpuCoreCount( int nrOfCores ); - - public TypeOf getTypeOf() - { - return typeOf; - } } diff --git a/src/main/java/org/openslx/util/vm/VmwareMetaData.java b/src/main/java/org/openslx/util/vm/VmwareMetaData.java index cdb3e46..1c84a72 100644 --- a/src/main/java/org/openslx/util/vm/VmwareMetaData.java +++ b/src/main/java/org/openslx/util/vm/VmwareMetaData.java @@ -16,14 +16,14 @@ import org.openslx.bwlp.thrift.iface.Virtualizer; import org.openslx.util.Util; import org.openslx.util.vm.VmwareConfig.ConfigEntry; -public class VmwareMetaData extends VmMetaData -{ +public class VmwareMetaData extends VmMetaData { - private static final Logger LOGGER = Logger.getLogger( VmwareMetaData.class ); + private static final Logger LOGGER = Logger.getLogger(VmwareMetaData.class); - private static final Virtualizer virtualizer = new Virtualizer( "vmware", "VMware" ); + private static final Virtualizer virtualizer = new Virtualizer("vmware", "VMware"); - private static final Pattern hddKey = Pattern.compile( "^(ide\\d|scsi\\d|sata\\d):?(\\d)?\\.(.*)", Pattern.CASE_INSENSITIVE ); + private static final Pattern hddKey = Pattern.compile("^(ide\\d|scsi\\d|sata\\d):?(\\d)?\\.(.*)", + Pattern.CASE_INSENSITIVE); // Lowercase list of allowed settings for upload (as regex) private static final Pattern[] whitelist; @@ -32,295 +32,284 @@ public class VmwareMetaData extends VmMetaData // Init static members static { - String[] list = { "^guestos", "^uuid\\.bios", "^config\\.version", "^ehci\\.", "^mks\\.enable3d", "^virtualhw\\.", "^sound\\.", "\\.pcislotnumber$", "^pcibridge", - "\\.virtualdev$", "^tools\\.syncTime$", "^time\\.synchronize", "^bios\\.bootDelay", "^rtc\\.", "^xhci\\." }; - whitelist = new Pattern[ list.length ]; - for ( int i = 0; i < list.length; ++i ) { - whitelist[i] = Pattern.compile( list[i].toLowerCase() ); + String[] list = { "^guestos", "^uuid\\.bios", "^config\\.version", "^ehci\\.", "^mks\\.enable3d", + "^virtualhw\\.", "^sound\\.", "\\.pcislotnumber$", "^pcibridge", "\\.virtualdev$", "^tools\\.syncTime$", + "^time\\.synchronize", "^bios\\.bootDelay", "^rtc\\.", "^xhci\\." }; + whitelist = new Pattern[list.length]; + for (int i = 0; i < list.length; ++i) { + whitelist[i] = Pattern.compile(list[i].toLowerCase()); } } private final Map<String, Controller> disks = new HashMap<>(); - public VmwareMetaData( List<OperatingSystem> osList, File file ) throws IOException, UnsupportedVirtualizerFormatException - { - super( osList ); - this.config = new VmwareConfig( file ); + public VmwareMetaData(List<OperatingSystem> osList, File file) + throws IOException, UnsupportedVirtualizerFormatException { + super(osList); + this.config = new VmwareConfig(file); init(); } - public VmwareMetaData( List<OperatingSystem> osList, byte[] vmxContent, int length ) throws UnsupportedVirtualizerFormatException - { - super( osList ); - this.config = new VmwareConfig( vmxContent, length ); // still unfiltered - setTypeOf(); + public VmwareMetaData(List<OperatingSystem> osList, byte[] vmxContent, int length) + throws UnsupportedVirtualizerFormatException { + super(osList); + this.config = new VmwareConfig(vmxContent, length); // still unfiltered init(); // now filtered } - private void init() - { - for ( Entry<String, ConfigEntry> entry : config.entrySet() ) { - handleLoadEntry( entry ); + private void init() { + for (Entry<String, ConfigEntry> entry : config.entrySet()) { + handleLoadEntry(entry); } // if we find this tag, we already went through the hdd's - so we're done. - if ( config.get( "#SLX_HDD_BUS" ) != null ) { + if (config.get("#SLX_HDD_BUS") != null) { return; } // Now find the HDDs and add to list - for ( Entry<String, Controller> cEntry : disks.entrySet() ) { + for (Entry<String, Controller> cEntry : disks.entrySet()) { Controller controller = cEntry.getValue(); String controllerType = cEntry.getKey(); - if ( !controller.present ) + if (!controller.present) continue; - for ( Entry<String, Device> dEntry : controller.devices.entrySet() ) { + for (Entry<String, Device> dEntry : controller.devices.entrySet()) { Device device = dEntry.getValue(); - if ( !device.present ) + if (!device.present) continue; // Not present - if ( device.deviceType != null && !device.deviceType.toLowerCase().endsWith( "disk" ) ) + if (device.deviceType != null && !device.deviceType.toLowerCase().endsWith("disk")) continue; // Not a HDD DriveBusType bus = null; - if ( controllerType.startsWith( "ide" ) ) { + if (controllerType.startsWith("ide")) { bus = DriveBusType.IDE; - } else if ( controllerType.startsWith( "scsi" ) ) { + } else if (controllerType.startsWith("scsi")) { bus = DriveBusType.SCSI; - } else if ( controllerType.startsWith( "sata" ) ) { + } else if (controllerType.startsWith("sata")) { bus = DriveBusType.SATA; } - hdds.add( new HardDisk( controller.virtualDev, bus, device.filename ) ); + hdds.add(new HardDisk(controller.virtualDev, bus, device.filename)); } } // Add HDD to cleaned vmx - if ( !hdds.isEmpty() ) { - HardDisk hdd = hdds.get( 0 ); - addFiltered( "#SLX_HDD_BUS", hdd.bus.toString() ); - if ( hdd.chipsetDriver != null ) { - addFiltered( "#SLX_HDD_CHIP", hdd.chipsetDriver ); + if (!hdds.isEmpty()) { + HardDisk hdd = hdds.get(0); + addFiltered("#SLX_HDD_BUS", hdd.bus.toString()); + if (hdd.chipsetDriver != null) { + addFiltered("#SLX_HDD_CHIP", hdd.chipsetDriver); } } } - private void addFiltered( String key, String value ) - { - config.set( key, value ).filtered( true ); + private void addFiltered(String key, String value) { + config.set(key, value).filtered(true); } - private boolean isSetAndTrue( String key ) - { - String value = config.get( key ); - return value != null && value.equalsIgnoreCase( "true" ); + private boolean isSetAndTrue(String key) { + String value = config.get(key); + return value != null && value.equalsIgnoreCase("true"); } - private void handleLoadEntry( Entry<String, ConfigEntry> entry ) - { + private void handleLoadEntry(Entry<String, ConfigEntry> entry) { String lowerKey = entry.getKey().toLowerCase(); // Cleaned vmx construction - for ( Pattern exp : whitelist ) { - if ( exp.matcher( lowerKey ).find() ) { - entry.getValue().filtered( true ); + for (Pattern exp : whitelist) { + if (exp.matcher(lowerKey).find()) { + entry.getValue().filtered(true); break; } } // // Dig Usable meta data String value = entry.getValue().getValue(); - if ( lowerKey.equals( "guestos" ) ) { - setOs( "vmware", value ); + if (lowerKey.equals("guestos")) { + setOs("vmware", value); return; } - if ( lowerKey.equals( "displayname" ) ) { + if (lowerKey.equals("displayname")) { displayName = value; return; } - Matcher hdd = hddKey.matcher( entry.getKey() ); - if ( hdd.find() ) { - handleHddEntry( hdd.group( 1 ).toLowerCase(), hdd.group( 2 ), hdd.group( 3 ), value ); + Matcher hdd = hddKey.matcher(entry.getKey()); + if (hdd.find()) { + handleHddEntry(hdd.group(1).toLowerCase(), hdd.group(2), hdd.group(3), value); } } - private void handleHddEntry( String controllerStr, String deviceStr, String property, String value ) - { - Controller controller = disks.get( controllerStr ); - if ( controller == null ) { + private void handleHddEntry(String controllerStr, String deviceStr, String property, String value) { + Controller controller = disks.get(controllerStr); + if (controller == null) { controller = new Controller(); - disks.put( controllerStr, controller ); + disks.put(controllerStr, controller); } - if ( deviceStr == null || deviceStr.isEmpty() ) { + if (deviceStr == null || deviceStr.isEmpty()) { // Controller property - if ( property.equalsIgnoreCase( "present" ) ) { - controller.present = Boolean.parseBoolean( value ); - } else if ( property.equalsIgnoreCase( "virtualDev" ) ) { + if (property.equalsIgnoreCase("present")) { + controller.present = Boolean.parseBoolean(value); + } else if (property.equalsIgnoreCase("virtualDev")) { controller.virtualDev = value; } return; } // Device property - Device device = controller.devices.get( deviceStr ); - if ( device == null ) { + Device device = controller.devices.get(deviceStr); + if (device == null) { device = new Device(); - controller.devices.put( deviceStr, device ); + controller.devices.put(deviceStr, device); } - if ( property.equalsIgnoreCase( "deviceType" ) ) { + if (property.equalsIgnoreCase("deviceType")) { device.deviceType = value; - } else if ( property.equalsIgnoreCase( "filename" ) ) { + } else if (property.equalsIgnoreCase("filename")) { device.filename = value; - } else if ( property.equalsIgnoreCase( "present" ) ) { - device.present = Boolean.parseBoolean( value ); + } else if (property.equalsIgnoreCase("present")) { + device.present = Boolean.parseBoolean(value); } } - + @Override - public boolean addHddTemplate( File diskImage, String hddMode, String redoDir) { + public boolean addHddTemplate(File diskImage, String hddMode, String redoDir) { String diskImagePath = diskImage.getName(); DriveBusType bus; try { - bus = DriveBusType.valueOf( config.get( "#SLX_HDD_BUS" ) ); - } catch ( Exception e ) { - LOGGER.warn( "Unknown bus type: " + config.get( "#SLX_HDD_BUS" ) + ". Cannot add hdd config." ); + bus = DriveBusType.valueOf(config.get("#SLX_HDD_BUS")); + } catch (Exception e) { + LOGGER.warn("Unknown bus type: " + config.get("#SLX_HDD_BUS") + ". Cannot add hdd config."); return false; } - String chipset = config.get( "#SLX_HDD_CHIP" ); + String chipset = config.get("#SLX_HDD_CHIP"); String prefix; - switch ( bus ) { + switch (bus) { case IDE: prefix = "ide0:0"; - addFiltered( "ide0.present", "TRUE" ); + addFiltered("ide0.present", "TRUE"); break; case SATA: // Cannot happen?... use lsisas1068 case SCSI: prefix = "scsi0:0"; - addFiltered( "scsi0.present", "TRUE" ); - if ( chipset != null ) { - addFiltered( "scsi0.virtualDev", chipset ); + addFiltered("scsi0.present", "TRUE"); + if (chipset != null) { + addFiltered("scsi0.virtualDev", chipset); } break; default: - LOGGER.warn( "Unknown HDD bus type: " + bus.toString() ); + LOGGER.warn("Unknown HDD bus type: " + bus.toString()); return false; } // Gen - addFiltered( prefix + ".present", "TRUE" ); - addFiltered( prefix + ".deviceType", "disk" ); - addFiltered( prefix + ".fileName", diskImagePath ); - if ( hddMode != null ) { - addFiltered( prefix + ".mode", hddMode ); - addFiltered( prefix + ".redo", "" ); - addFiltered( prefix + ".redoLogDir", redoDir ); - } - config.remove( "#SLX_HDD_BUS" ); - config.remove( "#SLX_HDD_CHIP" ); + addFiltered(prefix + ".present", "TRUE"); + addFiltered(prefix + ".deviceType", "disk"); + addFiltered(prefix + ".fileName", diskImagePath); + if (hddMode != null) { + addFiltered(prefix + ".mode", hddMode); + addFiltered(prefix + ".redo", ""); + addFiltered(prefix + ".redoLogDir", redoDir); + } + config.remove("#SLX_HDD_BUS"); + config.remove("#SLX_HDD_CHIP"); return true; } @Override - public boolean addHddTemplate( String diskImagePath, String hddMode, String redoDir ) - { + public boolean addHddTemplate(String diskImagePath, String hddMode, String redoDir) { DriveBusType bus; try { - bus = DriveBusType.valueOf( config.get( "#SLX_HDD_BUS" ) ); - } catch ( Exception e ) { - LOGGER.warn( "Unknown bus type: " + config.get( "#SLX_HDD_BUS" ) + ". Cannot add hdd config." ); + bus = DriveBusType.valueOf(config.get("#SLX_HDD_BUS")); + } catch (Exception e) { + LOGGER.warn("Unknown bus type: " + config.get("#SLX_HDD_BUS") + ". Cannot add hdd config."); return false; } - String chipset = config.get( "#SLX_HDD_CHIP" ); + String chipset = config.get("#SLX_HDD_CHIP"); String prefix; - switch ( bus ) { + switch (bus) { case IDE: prefix = "ide0:0"; - addFiltered( "ide0.present", "TRUE" ); + addFiltered("ide0.present", "TRUE"); break; case SATA: // Cannot happen?... use lsisas1068 case SCSI: prefix = "scsi0:0"; - addFiltered( "scsi0.present", "TRUE" ); - if ( chipset != null ) { - addFiltered( "scsi0.virtualDev", chipset ); + addFiltered("scsi0.present", "TRUE"); + if (chipset != null) { + addFiltered("scsi0.virtualDev", chipset); } break; default: - LOGGER.warn( "Unknown HDD bus type: " + bus.toString() ); + LOGGER.warn("Unknown HDD bus type: " + bus.toString()); return false; } // Gen - addFiltered( prefix + ".present", "TRUE" ); - addFiltered( prefix + ".deviceType", "disk" ); - addFiltered( prefix + ".fileName", diskImagePath ); - if ( hddMode != null ) { - addFiltered( prefix + ".mode", hddMode ); - addFiltered( prefix + ".redo", "" ); - addFiltered( prefix + ".redoLogDir", redoDir ); - } - config.remove( "#SLX_HDD_BUS" ); - config.remove( "#SLX_HDD_CHIP" ); + addFiltered(prefix + ".present", "TRUE"); + addFiltered(prefix + ".deviceType", "disk"); + addFiltered(prefix + ".fileName", diskImagePath); + if (hddMode != null) { + addFiltered(prefix + ".mode", hddMode); + addFiltered(prefix + ".redo", ""); + addFiltered(prefix + ".redoLogDir", redoDir); + } + config.remove("#SLX_HDD_BUS"); + config.remove("#SLX_HDD_CHIP"); return true; } - public boolean addDefaultNat() - { - addFiltered( "ethernet0.present", "TRUE" ); - addFiltered( "ethernet0.connectionType", "nat" ); + public boolean addDefaultNat() { + addFiltered("ethernet0.present", "TRUE"); + addFiltered("ethernet0.connectionType", "nat"); return true; } - public boolean addEthernet( EthernetType type ) - { + public boolean addEthernet(EthernetType type) { int index = 0; - for ( ;; ++index ) { - if ( config.get( "ethernet" + index + ".present" ) == null ) + for (;; ++index) { + if (config.get("ethernet" + index + ".present") == null) break; } - return addEthernet( index, type ); + return addEthernet(index, type); } - public boolean addEthernet( int index, EthernetType type ) - { + public boolean addEthernet(int index, EthernetType type) { String ether = "ethernet" + index; - addFiltered( ether + ".present", "TRUE" ); - addFiltered( ether + ".connectionType", "custom" ); - addFiltered( ether + ".vnet", type.vmnet ); - if ( config.get( ether + ".virtualDev" ) == null ) { - String dev = config.get( "ethernet0.virtualDev" ); - if ( dev != null ) { - addFiltered( ether + ".virtualDev", dev ); + addFiltered(ether + ".present", "TRUE"); + addFiltered(ether + ".connectionType", "custom"); + addFiltered(ether + ".vnet", type.vmnet); + if (config.get(ether + ".virtualDev") == null) { + String dev = config.get("ethernet0.virtualDev"); + if (dev != null) { + addFiltered(ether + ".virtualDev", dev); } } return true; } - public void addFloppy( int index, String image, boolean readOnly ) - { + public void addFloppy(int index, String image, boolean readOnly) { String pre = "floppy" + index; - addFiltered( pre + ".present", "TRUE" ); - if ( image == null ) { - addFiltered( pre + ".startConnected", "FALSE" ); - addFiltered( pre + ".fileType", "device" ); - config.remove( pre + ".fileName" ); - config.remove( pre + ".readonly" ); - addFiltered( pre + ".autodetect", "TRUE" ); + addFiltered(pre + ".present", "TRUE"); + if (image == null) { + addFiltered(pre + ".startConnected", "FALSE"); + addFiltered(pre + ".fileType", "device"); + config.remove(pre + ".fileName"); + config.remove(pre + ".readonly"); + addFiltered(pre + ".autodetect", "TRUE"); } else { - addFiltered( pre + ".startConnected", "TRUE" ); - addFiltered( pre + ".fileType", "file" ); - addFiltered( pre + ".fileName", image ); - addFiltered( pre + ".readonly", vmBoolean( readOnly ) ); - config.remove( pre + ".autodetect" ); - } - } - - public boolean addCdrom( String image ) - { - for ( String port : new String[] { "ide0:0", "ide0:1", "ide1:0", "ide1:1", "scsi0:1" } ) { - if ( !isSetAndTrue( port + ".present" ) ) { - addFiltered( port + ".present", "TRUE" ); - if ( image == null ) { - addFiltered( port + ".autodetect", "TRUE" ); - addFiltered( port + ".deviceType", "cdrom-raw" ); - config.remove( port + ".fileName" ); + addFiltered(pre + ".startConnected", "TRUE"); + addFiltered(pre + ".fileType", "file"); + addFiltered(pre + ".fileName", image); + addFiltered(pre + ".readonly", vmBoolean(readOnly)); + config.remove(pre + ".autodetect"); + } + } + + public boolean addCdrom(String image) { + for (String port : new String[] { "ide0:0", "ide0:1", "ide1:0", "ide1:1", "scsi0:1" }) { + if (!isSetAndTrue(port + ".present")) { + addFiltered(port + ".present", "TRUE"); + if (image == null) { + addFiltered(port + ".autodetect", "TRUE"); + addFiltered(port + ".deviceType", "cdrom-raw"); + config.remove(port + ".fileName"); } else { - config.remove( port + ".autodetect" ); - addFiltered( port + ".deviceType", "cdrom-image" ); - addFiltered( port + ".fileName", image ); + config.remove(port + ".autodetect"); + addFiltered(port + ".deviceType", "cdrom-image"); + addFiltered(port + ".fileName", image); } return true; } @@ -328,155 +317,129 @@ public class VmwareMetaData extends VmMetaData return false; } - private static String vmBoolean( boolean var ) - { - return Boolean.toString( var ).toUpperCase(); + private static String vmBoolean(boolean var) { + return Boolean.toString(var).toUpperCase(); } - private static String vmInteger( int val ) - { - return Integer.toString( val ); + private static String vmInteger(int val) { + return Integer.toString(val); } - public boolean disableSuspend() - { - addFiltered( "suspend.disabled", "TRUE" ); + public boolean disableSuspend() { + addFiltered("suspend.disabled", "TRUE"); return true; } - public boolean addDisplayName( String name ) - { - addFiltered( "displayName", name ); + public boolean addDisplayName(String name) { + addFiltered("displayName", name); return true; } - public boolean addRam( int mem ) - { - addFiltered( "memsize", Integer.toString( mem ) ); + public boolean addRam(int mem) { + addFiltered("memsize", Integer.toString(mem)); return true; } - public void setOs( String vendorOsId ) - { - addFiltered( "guestOS", vendorOsId ); - setOs( "vmware", vendorOsId ); + public void setOs(String vendorOsId) { + addFiltered("guestOS", vendorOsId); + setOs("vmware", vendorOsId); } @Override - public byte[] getFilteredDefinitionArray() - { - return config.toString( true, false ).getBytes( StandardCharsets.UTF_8 ); + public byte[] getFilteredDefinitionArray() { + return config.toString(true, false).getBytes(StandardCharsets.UTF_8); } - public byte[] getDefinitionArray() - { - return config.toString( false, false ).getBytes( StandardCharsets.UTF_8 ); + public byte[] getDefinitionArray() { + return config.toString(false, false).getBytes(StandardCharsets.UTF_8); } @Override - public Virtualizer getVirtualizer() - { + public Virtualizer getVirtualizer() { return virtualizer; } - private static class Device - { + private static class Device { public boolean present = false; public String deviceType = null; public String filename = null; @Override - public String toString() - { + public String toString() { return filename + " is " + deviceType + " (present: " + present + ")"; } } - private static class Controller - { + private static class Controller { public boolean present = true; // Seems to be implicit, seen at least for IDE... public String virtualDev = null; Map<String, Device> devices = new HashMap<>(); @Override - public String toString() - { + public String toString() { return virtualDev + " is (present: " + present + "): " + devices.toString(); } } - public static enum EthernetType - { - NAT( "vmnet1" ), - BRIDGED( "vmnet0" ), - HOST_ONLY( "vmnet2" ); + public static enum EthernetType { + NAT("vmnet1"), BRIDGED("vmnet0"), HOST_ONLY("vmnet2"); public final String vmnet; - private EthernetType( String vnet ) - { + private EthernetType(String vnet) { this.vmnet = vnet; } } @Override - public void enableUsb( boolean enabled ) - { - addFiltered( "usb.present", vmBoolean( enabled ) ); - addFiltered( "ehci.present", vmBoolean( enabled ) ); + public void enableUsb(boolean enabled) { + addFiltered("usb.present", vmBoolean(enabled)); + addFiltered("ehci.present", vmBoolean(enabled)); } @Override - public void applySettingsForLocalEdit() - { - addFiltered( "gui.applyHostDisplayScalingToGuest", "FALSE" ); + public void applySettingsForLocalEdit() { + addFiltered("gui.applyHostDisplayScalingToGuest", "FALSE"); } - public String getValue( String key ) - { - return config.get( key ); + public String getValue(String key) { + return config.get(key); } // SOUND - public static enum SoundCardType - { - NONE( false, null, "None" ), - DEFAULT( true, null, "(default)" ), - SOUND_BLASTER( true, "sb16", "Sound Blaster 16" ), - ES( true, "es1371", "ES 1371" ), - HD_AUDIO( true, "hdaudio", "Intel Integrated HD Audio" ); + public static enum SoundCardType { + NONE(false, null, "None"), DEFAULT(true, null, "(default)"), SOUND_BLASTER(true, "sb16", + "Sound Blaster 16"), ES(true, "es1371", + "ES 1371"), HD_AUDIO(true, "hdaudio", "Intel Integrated HD Audio"); public final boolean isPresent; public final String value; public final String displayName; - private SoundCardType( boolean present, String value, String dName ) - { + private SoundCardType(boolean present, String value, String dName) { this.isPresent = present; this.value = value; this.displayName = dName; } } - public void setSoundCard( SoundCardType type ) - { - addFiltered( "sound.present", vmBoolean( type.isPresent ) ); - if ( type.value != null ) { - addFiltered( "sound.virtualDev", type.value ); + public void setSoundCard(SoundCardType type) { + addFiltered("sound.present", vmBoolean(type.isPresent)); + if (type.value != null) { + addFiltered("sound.virtualDev", type.value); } else { - config.remove( "sound.virtualDev" ); + config.remove("sound.virtualDev"); } } - public SoundCardType getSoundCard() - { - if ( !isSetAndTrue( "sound.present" ) || !isSetAndTrue( "sound.autodetect" ) ) { + public SoundCardType getSoundCard() { + if (!isSetAndTrue("sound.present") || !isSetAndTrue("sound.autodetect")) { return SoundCardType.NONE; } - String current = config.get( "sound.virtualDev" ); - if ( current != null ) { - for ( SoundCardType type : SoundCardType.values() ) { - if ( current.equals( type.value ) ) { + String current = config.get("sound.virtualDev"); + if (current != null) { + for (SoundCardType type : SoundCardType.values()) { + if (current.equals(type.value)) { return type; } } @@ -485,29 +448,24 @@ public class VmwareMetaData extends VmMetaData } // 3DAcceleration - public static enum DDAcceleration - { - OFF( false, "Off" ), - ON( true, "On" ); + public static enum DDAcceleration { + OFF(false, "Off"), ON(true, "On"); public final boolean isPresent; public final String displayName; - private DDAcceleration( boolean present, String dName ) - { + private DDAcceleration(boolean present, String dName) { this.isPresent = present; this.displayName = dName; } } - public void setDDAcceleration( DDAcceleration type ) - { - addFiltered( "mks.enable3d", vmBoolean( type.isPresent ) ); + public void setDDAcceleration(DDAcceleration type) { + addFiltered("mks.enable3d", vmBoolean(type.isPresent)); } - public DDAcceleration getDDAcceleration() - { - if ( isSetAndTrue( "mks.enable3d" ) ) { + public DDAcceleration getDDAcceleration() { + if (isSetAndTrue("mks.enable3d")) { return DDAcceleration.ON; } else { return DDAcceleration.OFF; @@ -515,39 +473,33 @@ public class VmwareMetaData extends VmMetaData } // Virtual hardware version - public static enum HWVersion - { - NONE( 0, "(invalid)" ), - THREE( 3, " 3 (Workstation 4/5, Player 1)" ), - FOUR( 4, " 4 (Workstation 4/5, Player 1/2, Fusion 1)" ), - SIX( 6, " 6 (Workstation 6)" ), - SEVEN( 7, " 7 (Workstation 6.5/7, Player 3, Fusion 2/3)" ), - EIGHT( 8, " 8 (Workstation 8, Player/Fusion 4)" ), - NINE( 9, " 9 (Workstation 9, Player/Fusion 5)" ), - TEN( 10, "10 (Workstation 10, Player/Fusion 6)" ), - ELEVEN( 11, "11 (Workstation 11, Player/Fusion 7)" ), - TWELVE( 12, "12 (Workstation/Player 12, Fusion 8)" ); + public static enum HWVersion { + NONE(0, "(invalid)"), THREE(3, " 3 (Workstation 4/5, Player 1)"), FOUR(4, + " 4 (Workstation 4/5, Player 1/2, Fusion 1)"), SIX(6, " 6 (Workstation 6)"), SEVEN(7, + " 7 (Workstation 6.5/7, Player 3, Fusion 2/3)"), EIGHT(8, + " 8 (Workstation 8, Player/Fusion 4)"), NINE(9, + " 9 (Workstation 9, Player/Fusion 5)"), TEN(10, + "10 (Workstation 10, Player/Fusion 6)"), ELEVEN(11, + "11 (Workstation 11, Player/Fusion 7)"), TWELVE(12, + "12 (Workstation/Player 12, Fusion 8)"); public final int version; public final String displayName; - private HWVersion( int vers, String dName ) - { + private HWVersion(int vers, String dName) { this.version = vers; this.displayName = dName; } } - public void setHWVersion( HWVersion type ) - { - addFiltered( "virtualHW.version", vmInteger( type.version ) ); + public void setHWVersion(HWVersion type) { + addFiltered("virtualHW.version", vmInteger(type.version)); } - public HWVersion getHWVersion() - { - int currentValue = Util.parseInt( config.get( "virtualHW.version" ), -1 ); - for ( HWVersion ver : HWVersion.values() ) { - if ( currentValue == ver.version ) { + public HWVersion getHWVersion() { + int currentValue = Util.parseInt(config.get("virtualHW.version"), -1); + for (HWVersion ver : HWVersion.values()) { + if (currentValue == ver.version) { return ver; } } @@ -555,41 +507,33 @@ public class VmwareMetaData extends VmMetaData } // Virtual network adapter - public static enum EthernetDevType - { - AUTO( null, "(default)" ), - PCNET32( "vlance", "AMD PCnet32" ), - E1000( "e1000", "Intel E1000 (PCI)" ), - E1000E( "e1000e", "Intel E1000e (PCI-Express)" ), - VMXNET( "vmxnet", "VMXnet" ), - VMXNET3( "vmxnet3", "VMXnet 3" ); + public static enum EthernetDevType { + AUTO(null, "(default)"), PCNET32("vlance", "AMD PCnet32"), E1000("e1000", "Intel E1000 (PCI)"), E1000E("e1000e", + "Intel E1000e (PCI-Express)"), VMXNET("vmxnet", "VMXnet"), VMXNET3("vmxnet3", "VMXnet 3"); public final String value; public final String displayName; - private EthernetDevType( String value, String dName ) - { + private EthernetDevType(String value, String dName) { this.value = value; this.displayName = dName; } } - public void setEthernetDevType( int cardIndex, EthernetDevType type ) - { - if ( type.value != null ) { - addFiltered( "ethernet" + cardIndex + ".virtualDev", type.value ); + public void setEthernetDevType(int cardIndex, EthernetDevType type) { + if (type.value != null) { + addFiltered("ethernet" + cardIndex + ".virtualDev", type.value); } else { - config.remove( "ethernet" + cardIndex + ".virtualDev" ); + config.remove("ethernet" + cardIndex + ".virtualDev"); } } - public EthernetDevType getEthernetDevType( int cardIndex ) - { - String temp = config.get( "ethernet" + cardIndex + ".virtualDev" ); - if ( temp != null ) { + public EthernetDevType getEthernetDevType(int cardIndex) { + String temp = config.get("ethernet" + cardIndex + ".virtualDev"); + if (temp != null) { - for ( EthernetDevType type : EthernetDevType.values() ) { - if ( temp.equals( type.value ) ) { + for (EthernetDevType type : EthernetDevType.values()) { + if (temp.equals(type.value)) { return type; } } @@ -598,21 +542,13 @@ public class VmwareMetaData extends VmMetaData } @Override - public void setTypeOf() - { - typeOf = TypeOf.VMX; - } - - @Override - public void reWrite() - { + public void reWrite() { // TODO Auto-generated method stub } @Override - public boolean addCpuCoreCount( int nrOfCores ) - { + public boolean addCpuCoreCount(int nrOfCores) { // TODO Auto-generated method stub return false; } |