Example usage for org.w3c.dom Document setXmlStandalone

List of usage examples for org.w3c.dom Document setXmlStandalone

Introduction

In this page you can find the example usage for org.w3c.dom Document setXmlStandalone.

Prototype

public void setXmlStandalone(boolean xmlStandalone) throws DOMException;

Source Link

Document

An attribute specifying, as part of the <a href='http://www.w3.org/TR/2004/REC-xml-20040204#NT-XMLDecl'>XML declaration</a>, whether this document is standalone.

Usage

From source file:com.connectsdk.service.DLNAService.java

protected String getMessageXml(String serviceURN, String method, String instanceId,
        Map<String, String> params) {
    try {/* w ww.ja v  a2 s.c o m*/
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.newDocument();
        doc.setXmlStandalone(true);
        doc.setXmlVersion("1.0");

        Element root = doc.createElement("s:Envelope");
        Element bodyElement = doc.createElement("s:Body");
        Element methodElement = doc.createElementNS(serviceURN, "u:" + method);
        Element instanceElement = doc.createElement("InstanceID");

        root.setAttribute("s:encodingStyle", "http://schemas.xmlsoap.org/soap/encoding/");
        root.setAttribute("xmlns:s", "http://schemas.xmlsoap.org/soap/envelope/");

        doc.appendChild(root);
        root.appendChild(bodyElement);
        bodyElement.appendChild(methodElement);
        if (instanceId != null) {
            instanceElement.setTextContent(instanceId);
            methodElement.appendChild(instanceElement);
        }

        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                Element element = doc.createElement(key);
                element.setTextContent(value);
                methodElement.appendChild(element);
            }
        }
        return xmlToString(doc, true);
    } catch (Exception e) {
        return null;
    }
}

From source file:jef.tools.XMLUtils.java

/**
 * XML//from  ww  w  .  j ava 2  s .  c  o  m
 * 
 * @param in
 *            ?
 * @param charSet
 *            ?
 * @param ignorComment
 *            
 * @return Document. DOM
 * @throws SAXException
 *             ?
 * @throws IOException
 *             
 */
public static Document loadDocument(InputStream in, String charSet, boolean ignorComments,
        boolean namespaceAware) throws SAXException, IOException {
    DocumentBuilder db = REUSABLE_BUILDER.get().getDocumentBuilder(ignorComments, namespaceAware);
    InputSource is = null;
    // ????charset
    if (charSet == null) {// ?200???
        byte[] buf = new byte[200];
        PushbackInputStream pin = new PushbackInputStream(in, 200);
        in = pin;
        int len = pin.read(buf);
        if (len > 0) {
            pin.unread(buf, 0, len);
            charSet = getCharsetInXml(buf, len);
        }
    }
    if (charSet != null) {
        is = new InputSource(new XmlFixedReader(new InputStreamReader(in, charSet)));
        is.setEncoding(charSet);
    } else { // ?
        Reader reader = new InputStreamReader(in, "UTF-8");// XML???Reader??Reader?XML?
        is = new InputSource(new XmlFixedReader(reader));
    }
    Document doc = db.parse(is);
    doc.setXmlStandalone(true);// True???standalone="no"
    return doc;

}

From source file:jef.tools.XMLUtils.java

/**
 * XML// w w  w .j a va  2 s  .co  m
 * 
 * @return XML
 */
public static Document newDocument() {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.newDocument();
        document.setXmlStandalone(true);
        return document;
    } catch (ParserConfigurationException e) {
        LogUtil.exception(e);
        return null;
    }
}

From source file:vmTools.java

public String createVmXml(String jsonString, String server) {
    String ret = "";

    ArrayList<String> ide = new ArrayList<String>();
    ide.add("hda");
    ide.add("hdb");
    ide.add("hdc");
    ide.add("hdd");
    ide.add("hde");
    ide.add("hdf");
    ArrayList<String> scsi = new ArrayList<String>();
    scsi.add("sda");
    scsi.add("sdb");
    scsi.add("sdc");
    scsi.add("sdd");
    scsi.add("sde");
    scsi.add("sdf");

    try {// w  w w .j av  a 2  s .c  om
        JSONObject jo = new JSONObject(jsonString);
        // A JSONArray is an ordered sequence of values. Its external form is a 
        // string wrapped in square brackets with commas between the values.
        // Get the JSONObject value associated with the search result key.
        String varName = jo.get("name").toString();

        String domainType = jo.get("domain_type").toString();
        String varMem = jo.get("memory").toString();
        String varCpu = jo.get("vcpu").toString();
        String varArch = jo.get("arch").toString();

        // Get the JSONArray value associated with the Result key
        JSONArray diskArray = jo.getJSONArray("diskList");
        JSONArray nicArray = jo.getJSONArray("nicList");

        // Cration d'un nouveau DOM
        DocumentBuilderFactory fabrique = DocumentBuilderFactory.newInstance();
        DocumentBuilder constructeur = fabrique.newDocumentBuilder();
        Document document = constructeur.newDocument();

        // Proprits du DOM
        document.setXmlStandalone(true);

        // Cration de l'arborescence du DOM
        Element domain = document.createElement("domain");
        document.appendChild(domain);
        domain.setAttribute("type", domainType);

        //racine.appendChild(document.createComment("Commentaire sous la racine"));
        Element name = document.createElement("name");
        domain.appendChild(name);
        name.setTextContent(varName);

        UUID varuid = UUID.randomUUID();
        Element uid = document.createElement("uuid");
        domain.appendChild(uid);
        uid.setTextContent(varuid.toString());

        Element memory = document.createElement("memory");
        domain.appendChild(memory);
        memory.setTextContent(varMem);

        Element currentMemory = document.createElement("currentMemory");
        domain.appendChild(currentMemory);
        currentMemory.setTextContent(varMem);

        Element vcpu = document.createElement("vcpu");
        domain.appendChild(vcpu);
        vcpu.setTextContent(varCpu);
        //<os>
        Element os = document.createElement("os");
        domain.appendChild(os);
        Element type = document.createElement("type");
        os.appendChild(type);
        type.setAttribute("arch", varArch);
        type.setAttribute("machine", jo.get("machine").toString());
        type.setTextContent(jo.get("machine_type").toString());

        JSONArray bootArray = jo.getJSONArray("bootList");
        int count = bootArray.length();
        for (int i = 0; i < count; i++) {
            JSONObject bootDev = bootArray.getJSONObject(i);
            Element boot = document.createElement("boot");
            os.appendChild(boot);
            boot.setAttribute("dev", bootDev.get("dev").toString());
        }

        Element bootmenu = document.createElement("bootmenu");
        os.appendChild(bootmenu);
        bootmenu.setAttribute("enable", jo.get("bootMenu").toString());
        //</os>
        //<features>
        Element features = document.createElement("features");
        domain.appendChild(features);
        JSONArray featureArray = jo.getJSONArray("features");
        int featureCount = featureArray.length();
        for (int i = 0; i < featureCount; i++) {
            JSONObject jasonFeature = featureArray.getJSONObject(i);
            String newFeature = jasonFeature.get("opt").toString();
            Element elFeature = document.createElement(newFeature);
            features.appendChild(elFeature);
        }
        //</features>
        Element clock = document.createElement("clock");
        domain.appendChild(clock);
        // Clock settings
        clock.setAttribute("offset", jo.get("clock_offset").toString());
        JSONArray timerArray = jo.getJSONArray("timers");
        for (int i = 0; i < timerArray.length(); i++) {
            JSONObject jsonTimer = timerArray.getJSONObject(i);
            Element elTimer = document.createElement("timer");
            clock.appendChild(elTimer);
            elTimer.setAttribute("name", jsonTimer.get("name").toString());
            elTimer.setAttribute("present", jsonTimer.get("present").toString());
            elTimer.setAttribute("tickpolicy", jsonTimer.get("tickpolicy").toString());
        }

        Element poweroff = document.createElement("on_poweroff");
        domain.appendChild(poweroff);
        poweroff.setTextContent(jo.get("on_poweroff").toString());
        Element reboot = document.createElement("on_reboot");
        domain.appendChild(reboot);
        reboot.setTextContent(jo.get("on_reboot").toString());
        Element crash = document.createElement("on_crash");
        domain.appendChild(crash);
        crash.setTextContent(jo.get("on_crash").toString());
        //<devices>
        Element devices = document.createElement("devices");
        domain.appendChild(devices);
        String varEmulator = jo.get("emulator").toString();
        Element emulator = document.createElement("emulator");
        devices.appendChild(emulator);
        emulator.setTextContent(varEmulator);

        int resultCount = diskArray.length();
        for (int i = 0; i < resultCount; i++) {
            Element disk = document.createElement("disk");
            devices.appendChild(disk);
            JSONObject newDisk = diskArray.getJSONObject(i);
            String diskType = newDisk.get("type").toString();
            Element driver = document.createElement("driver");
            Element target = document.createElement("target");
            disk.appendChild(driver);
            disk.appendChild(target);
            if (diskType.equals("file")) {
                Element source = document.createElement("source");
                disk.appendChild(source);
                source.setAttribute("file", newDisk.get("source").toString());
                driver.setAttribute("cache", "none");
            }

            disk.setAttribute("type", diskType);
            disk.setAttribute("device", newDisk.get("device").toString());
            driver.setAttribute("type", newDisk.get("format").toString());
            driver.setAttribute("name", newDisk.get("driver").toString());

            //String diskDev = ide.get(0);
            //ide.remove(0);
            String diskDev = newDisk.get("bus").toString();
            String diskBus = "";
            if (diskDev.indexOf("hd") > -1) {
                diskBus = "ide";
            } else if (diskDev.indexOf("sd") > -1) {
                diskBus = "scsi";
            } else if (diskDev.indexOf("vd") > -1) {
                diskBus = "virtio";
            }

            target.setAttribute("dev", diskDev);
            target.setAttribute("bus", diskBus);

        }

        resultCount = nicArray.length();
        for (int i = 0; i < resultCount; i++) {
            JSONObject newNic = nicArray.getJSONObject(i);
            String macaddr = newNic.get("mac").toString().toLowerCase();
            if (macaddr.indexOf("automatic") > -1) {
                Random rand = new Random();
                macaddr = "52:54:00";
                String hexa = Integer.toHexString(rand.nextInt(255));
                macaddr += ":" + hexa;
                hexa = Integer.toHexString(rand.nextInt(255));
                macaddr += ":" + hexa;
                hexa = Integer.toHexString(rand.nextInt(255));
                macaddr += ":" + hexa;
            }

            Element netIf = document.createElement("interface");
            devices.appendChild(netIf);
            Element netSource = document.createElement("source");
            Element netDevice = document.createElement("model");
            Element netMac = document.createElement("mac");
            netIf.appendChild(netSource);
            netIf.appendChild(netDevice);
            netIf.appendChild(netMac);
            netIf.setAttribute("type", "network");
            netSource.setAttribute("network", newNic.get("bridge").toString());
            String portgroup = newNic.get("portgroup").toString();
            if (!portgroup.equals("")) {
                netSource.setAttribute("portgroup", portgroup);
            }
            netDevice.setAttribute("type", newNic.get("device").toString());
            netMac.setAttribute("address", macaddr);
        }

        JSONArray serialArray = jo.getJSONArray("serial");
        count = serialArray.length();
        for (int i = 0; i < count; i++) {
            JSONObject serialDev = serialArray.getJSONObject(i);
            Element serial = document.createElement("serial");
            devices.appendChild(serial);
            serial.setAttribute("type", serialDev.get("type").toString());
            Element target = document.createElement("target");
            serial.appendChild(target);
            target.setAttribute("port", serialDev.get("port").toString());
        }

        JSONArray consoleArray = jo.getJSONArray("console");
        count = consoleArray.length();
        for (int i = 0; i < count; i++) {
            JSONObject consoleDev = consoleArray.getJSONObject(i);
            Element console = document.createElement("console");
            devices.appendChild(console);
            console.setAttribute("type", "pty");
            Element target = document.createElement("target");
            console.appendChild(target);
            target.setAttribute("port", consoleDev.get("port").toString());
            target.setAttribute("type", consoleDev.get("type").toString());
        }

        JSONArray inputArray = jo.getJSONArray("input");
        count = inputArray.length();
        for (int i = 0; i < count; i++) {
            JSONObject inputDev = inputArray.getJSONObject(i);
            Element input = document.createElement("input");
            devices.appendChild(input);
            input.setAttribute("type", inputDev.get("type").toString());
            input.setAttribute("bus", inputDev.get("bus").toString());
        }

        JSONArray graphicsArray = jo.getJSONArray("graphics");
        count = graphicsArray.length();
        for (int i = 0; i < count; i++) {
            JSONObject graphicsDev = graphicsArray.getJSONObject(i);
            Element graphics = document.createElement("graphics");
            devices.appendChild(graphics);
            graphics.setAttribute("type", graphicsDev.get("type").toString());
            graphics.setAttribute("port", graphicsDev.get("port").toString());
            graphics.setAttribute("autoport", graphicsDev.get("autoport").toString());
            graphics.setAttribute("listen", graphicsDev.get("listen").toString());
            graphics.setAttribute("keymap", graphicsDev.get("keymap").toString());
        }

        JSONArray soundArray = jo.getJSONArray("sound");
        count = soundArray.length();
        for (int i = 0; i < count; i++) {
            JSONObject soundDev = soundArray.getJSONObject(i);
            Element sound = document.createElement("sound");
            devices.appendChild(sound);
            sound.setAttribute("model", soundDev.get("model").toString());
        }
        //sound.setAttribute("model", "ac97");

        JSONArray videoArray = jo.getJSONArray("video");
        count = videoArray.length();
        for (int i = 0; i < count; i++) {
            JSONObject videoDev = videoArray.getJSONObject(i);
            Element video = document.createElement("video");
            devices.appendChild(video);
            Element model = document.createElement("model");
            video.appendChild(model);
            model.setAttribute("model", videoDev.get("type").toString());
            model.setAttribute("model", videoDev.get("vram").toString());
            model.setAttribute("model", videoDev.get("heads").toString());
        }

        //write the content into xml file
        this.makeRelativeDirs("/" + server + "/vm/configs/" + varName);
        String pathToXml = RuntimeAccess.getInstance().getSession().getServletContext()
                .getRealPath("resources/data/" + server + "/vm/configs/" + varName + "/" + varName + ".xml");
        File xmlOutput = new File(pathToXml);

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

        DOMSource source = new DOMSource(document);
        StreamResult result = new StreamResult(xmlOutput);
        transformer.transform(source, result);

        StringWriter stw = new StringWriter();
        transformer.transform(source, new StreamResult(stw));
        ret = stw.toString();

    } catch (Exception e) {
        log(ERROR, "create xml file has failed", e);
        return e.toString();
    }
    return ret;
}

From source file:com.portfolio.rest.RestServicePortfolio.java

@Path("/credential/group/{portfolio-id}")
@GET// w w  w. j a v a  2  s. com
@Produces(MediaType.APPLICATION_XML)
public String getUserGroupByPortfolio(@CookieParam("user") String user, @CookieParam("credential") String token,
        @QueryParam("group") int groupId, @PathParam("portfolio-id") String portfolioUuid,
        @Context ServletConfig sc, @Context HttpServletRequest httpServletRequest) {
    HttpSession session = httpServletRequest.getSession(true);
    UserInfo ui = checkCredential(httpServletRequest, user, token, null);

    try {
        String xmlGroups = dataProvider.getUserGroupByPortfolio(portfolioUuid, ui.userId);
        logRestRequest(httpServletRequest, "", xmlGroups, Status.OK.getStatusCode());

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = null;
        Document document = null;
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        document = documentBuilder.newDocument();
        document.setXmlStandalone(true);
        Document doc = documentBuilder.parse(new ByteArrayInputStream(xmlGroups.getBytes("UTF-8")));
        NodeList groups = doc.getElementsByTagName("group");
        if (groups.getLength() == 1) {
            Node groupnode = groups.item(0);
            String gid = groupnode.getAttributes().getNamedItem("id").getNodeValue();
            if (gid != null) {
                //               ui.groupId = Integer.parseInt(gid);
                //               session.setAttribute("gid", ui.groupId);
            }
        } else if (groups.getLength() == 0) // Pas de groupe, on rend invalide le choix
        {
            //            ui.groupId = -1;
            //            session.setAttribute("gid", ui.groupId);
        }

        return xmlGroups;
    } catch (Exception ex) {
        ex.printStackTrace();
        logRestRequest(httpServletRequest, "", ex.getMessage() + "\n\n" + javaUtils.getCompleteStackTrace(ex),
                Status.INTERNAL_SERVER_ERROR.getStatusCode());

        throw new RestWebApplicationException(Status.INTERNAL_SERVER_ERROR, ex.getMessage());
    } finally {
        dataProvider.disconnect();
    }
}

From source file:com.portfolio.data.provider.MysqlAdminProvider.java

@Override
public Object getNode(MimeType outMimeType, String nodeUuid, boolean withChildren, int userId, int groupId,
        String label) throws SQLException, TransformerFactoryConfigurationError, ParserConfigurationException,
        UnsupportedEncodingException, DOMException, SAXException, IOException, TransformerException {
    StringBuffer nodexml = new StringBuffer();

    NodeRight nodeRight = credential.getNodeRight(userId, groupId, nodeUuid, label);

    if (!nodeRight.read)
        return nodexml;

    if (outMimeType.getSubType().equals("xml")) {
        ResultSet result = getNodePerLevel(nodeUuid, userId, groupId);

        /// Prparation du XML que l'on va renvoyer
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = null;
        Document document = null;
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        document = documentBuilder.newDocument();
        document.setXmlStandalone(true);

        HashMap<String, Node> resolve = new HashMap<String, Node>();
        /// Node -> parent
        ArrayList<Object[]> entries = new ArrayList<Object[]>();

        processQuery(result, resolve, entries, document, documentBuilder);
        result.close();/*from  ww  w.jav  a  2 s. c  o  m*/

        for (int i = 0; i < entries.size(); ++i) {
            Object[] obj = entries.get(i);
            Node node = (Node) obj[0];
            String childsId = (String) obj[1];

            String[] tok = childsId.split(",");
            for (int j = 0; j < tok.length; ++j) {
                String id = tok[j];
                Node child = resolve.get(id);
                if (child != null)
                    node.appendChild(child);
            }
        }

        Node root = resolve.get(nodeUuid);
        Node node = document.createElement("node");
        node.appendChild(root);
        document.appendChild(node);

        StringWriter stw = new StringWriter();
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
        serializer.transform(new DOMSource(document), new StreamResult(stw));
        nodexml.append(stw.toString());

        //        StringBuffer sb = getNodeXmlOutput(nodeUuid,withChildren,null,userId, groupId, label,true);
        //          StringBuffer sb = getLinearNodeXml(nodeUuid,withChildren,null,userId, groupId, label,true);

        //        sb.insert(0, "<node>");
        //        sb.append("</node>");
        return nodexml;
    } else if (outMimeType.getSubType().equals("json"))
        return "{" + getNodeJsonOutput(nodeUuid, withChildren, null, userId, groupId, label, true) + "}";
    else
        return null;
}

From source file:com.portfolio.data.provider.MysqlAdminProvider.java

@Override
public Object getPortfolio(MimeType outMimeType, String portfolioUuid, int userId, int groupId, String label,
        String resource, String files) throws Exception {
    String rootNodeUuid = getPortfolioRootNode(portfolioUuid);
    String header = "";
    String footer = "";
    NodeRight nodeRight = credential.getPortfolioRight(userId, groupId, portfolioUuid, Credential.READ);
    if (!nodeRight.read)
        return "faux";

    if (outMimeType.getSubType().equals("xml")) {
        //         header = "<portfolio xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' schemaVersion='1.0'>";
        //         footer = "</portfolio>";

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder;
        Document document = null;
        try {//from  ww w.j a v  a  2s .c om
            documentBuilder = documentBuilderFactory.newDocumentBuilder();
            document = documentBuilder.newDocument();
            document.setXmlStandalone(true);
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Element root = document.createElement("portfolio");
        root.setAttribute("id", portfolioUuid);
        root.setAttribute("code", "0");

        //// Noeuds supplmentaire pour WAD
        // Version
        Element verNode = document.createElement("version");
        Text version = document.createTextNode("3");
        verNode.appendChild(version);
        root.appendChild(verNode);
        // metadata-wad
        Element metawad = document.createElement("metadata-wad");
        metawad.setAttribute("prog", "main.jsp");
        metawad.setAttribute("owner", "N");
        root.appendChild(metawad);

        //          root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        //          root.setAttribute("schemaVersion", "1.0");
        document.appendChild(root);

        getLinearXml(portfolioUuid, rootNodeUuid, root, true, null, userId, groupId);

        StringWriter stw = new StringWriter();
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
        serializer.transform(new DOMSource(document), new StreamResult(stw));

        if (resource != null && files != null) {

            if (resource.equals("true") && files.equals("true")) {
                String adressedufichier = System.getProperty("user.dir") + "/tmp_getPortfolio_" + new Date()
                        + ".xml";
                String adresseduzip = System.getProperty("user.dir") + "/tmp_getPortfolio_" + new Date()
                        + ".zip";

                File file = null;
                PrintWriter ecrire;
                PrintWriter ecri;
                try {
                    file = new File(adressedufichier);
                    ecrire = new PrintWriter(new FileOutputStream(adressedufichier));
                    ecrire.println(stw.toString());
                    ecrire.flush();
                    ecrire.close();
                    System.out.print("fichier cree ");
                } catch (IOException ioe) {
                    System.out.print("Erreur : ");
                    ioe.printStackTrace();
                }

                try {
                    String fileName = portfolioUuid + ".zip";

                    ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(adresseduzip));
                    zip.setMethod(ZipOutputStream.DEFLATED);
                    zip.setLevel(Deflater.BEST_COMPRESSION);
                    File dataDirectories = new File(file.getName());
                    FileInputStream fis = new FileInputStream(dataDirectories);
                    byte[] bytes = new byte[fis.available()];
                    fis.read(bytes);

                    ZipEntry entry = new ZipEntry(file.getName());
                    entry.setTime(dataDirectories.lastModified());
                    zip.putNextEntry(entry);
                    zip.write(bytes);
                    zip.closeEntry();
                    fis.close();
                    //zipDirectory(dataDirectories, zip);
                    zip.close();

                    file.delete();

                    return adresseduzip;

                } catch (FileNotFoundException fileNotFound) {
                    fileNotFound.printStackTrace();

                } catch (IOException io) {

                    io.printStackTrace();
                }
            }
        }

        return stw.toString();

    } else if (outMimeType.getSubType().equals("json")) {
        header = "{\"portfolio\": { \"-xmlns:xsi\": \"http://www.w3.org/2001/XMLSchema-instance\",\"-schemaVersion\": \"1.0\",";
        footer = "}}";
    }

    return header + getNode(outMimeType, rootNodeUuid, true, userId, groupId, label).toString() + footer;
}

From source file:com.portfolio.data.provider.MysqlDataProvider.java

@Override
public Object getNode(MimeType outMimeType, String nodeUuid, boolean withChildren, int userId, int groupId,
        String label) throws SQLException, TransformerFactoryConfigurationError, ParserConfigurationException,
        UnsupportedEncodingException, DOMException, SAXException, IOException, TransformerException {
    StringBuffer nodexml = new StringBuffer();

    NodeRight nodeRight = credential.getNodeRight(userId, groupId, nodeUuid, label);

    if (!nodeRight.read) {
        userId = credential.getPublicUid();
        /// Vrifie les droits avec le compte publique (dernire chance)
        credential.getPublicRight(userId, 123, nodeUuid, "dummy");

        if (!nodeRight.read)
            return nodexml;
    }/*from   w ww.  java  2 s  .  c  om*/

    if (outMimeType.getSubType().equals("xml")) {
        ResultSet result = getNodePerLevel(nodeUuid, userId, nodeRight.groupId);

        /// Prparation du XML que l'on va renvoyer
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = null;
        Document document = null;
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        document = documentBuilder.newDocument();
        document.setXmlStandalone(true);

        HashMap<String, Node> resolve = new HashMap<String, Node>();
        /// Node -> parent
        ArrayList<Object[]> entries = new ArrayList<Object[]>();

        processQuery(result, resolve, entries, document, documentBuilder, nodeRight.groupLabel);
        result.close();

        for (int i = 0; i < entries.size(); ++i) {
            Object[] obj = entries.get(i);
            Node node = (Node) obj[0];
            String childsId = (String) obj[1];

            String[] tok = childsId.split(",");
            for (int j = 0; j < tok.length; ++j) {
                String id = tok[j];
                Node child = resolve.get(id);
                if (child != null)
                    node.appendChild(child);

            }
        }

        Node root = resolve.get(nodeUuid);
        Node node = document.createElement("node");
        node.appendChild(root);
        document.appendChild(node);

        StringWriter stw = new StringWriter();
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
        serializer.transform(new DOMSource(document), new StreamResult(stw));
        nodexml.append(stw.toString());

        //        StringBuffer sb = getNodeXmlOutput(nodeUuid,withChildren,null,userId, groupId, label,true);
        //          StringBuffer sb = getLinearNodeXml(nodeUuid,withChildren,null,userId, groupId, label,true);

        //        sb.insert(0, "<node>");
        //        sb.append("</node>");
        return nodexml;
    } else if (outMimeType.getSubType().equals("json"))
        return "{" + getNodeJsonOutput(nodeUuid, withChildren, null, userId, groupId, label, true) + "}";
    else
        return null;
}

From source file:com.portfolio.data.provider.MysqlDataProvider.java

@Override
public Object getPortfolio(MimeType outMimeType, String portfolioUuid, int userId, int groupId, String label,
        String resource, String files, int substid) throws Exception {
    String rootNodeUuid = getPortfolioRootNode(portfolioUuid);
    String header = "";
    String footer = "";
    NodeRight nodeRight = credential.getPortfolioRight(userId, groupId, portfolioUuid, Credential.READ);
    if (!nodeRight.read) {
        userId = credential.getPublicUid();
        //         NodeRight nodeRight = new NodeRight(false,false,false,false,false,false);
        /// Vrifie les droits avec le compte publique (dernire chance)
        nodeRight = credential.getPublicRight(userId, 123, rootNodeUuid, "dummy");
        if (!nodeRight.read)
            return "faux";
    }//  w  ww  .j  a va  2s .c o m

    if (outMimeType.getSubType().equals("xml")) {
        //         header = "<portfolio xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' schemaVersion='1.0'>";
        //         footer = "</portfolio>";

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder;
        Document document = null;
        try {
            documentBuilder = documentBuilderFactory.newDocumentBuilder();
            document = documentBuilder.newDocument();
            document.setXmlStandalone(true);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }

        Element root = document.createElement("portfolio");
        root.setAttribute("id", portfolioUuid);
        root.setAttribute("code", "0");

        //// Noeuds supplmentaire pour WAD
        // Version
        Element verNode = document.createElement("version");
        Text version = document.createTextNode("4");
        verNode.appendChild(version);
        root.appendChild(verNode);
        // metadata-wad
        //         Element metawad = document.createElement("metadata-wad");
        //         metawad.setAttribute("prog", "main.jsp");
        //         metawad.setAttribute("owner", "N");
        //         root.appendChild(metawad);
        int owner = credential.getOwner(userId, portfolioUuid);
        String isOwner = "N";
        if (owner == userId)
            isOwner = "Y";
        root.setAttribute("owner", isOwner);

        //          root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        //          root.setAttribute("schemaVersion", "1.0");
        document.appendChild(root);

        getLinearXml(portfolioUuid, rootNodeUuid, root, true, null, userId, nodeRight.groupId,
                nodeRight.groupLabel);

        StringWriter stw = new StringWriter();
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
        serializer.transform(new DOMSource(document), new StreamResult(stw));

        if (resource != null && files != null) {
            if (resource.equals("true") && files.equals("true")) {
                String adressedufichier = System.getProperty("user.dir") + "/tmp_getPortfolio_" + new Date()
                        + ".xml";
                String adresseduzip = System.getProperty("user.dir") + "/tmp_getPortfolio_" + new Date()
                        + ".zip";

                File file = null;
                PrintWriter ecrire;
                try {
                    file = new File(adressedufichier);
                    ecrire = new PrintWriter(new FileOutputStream(adressedufichier));
                    ecrire.println(stw.toString());
                    ecrire.flush();
                    ecrire.close();
                    System.out.print("fichier cree ");
                } catch (IOException ioe) {
                    System.out.print("Erreur : ");
                    ioe.printStackTrace();
                }

                try {
                    ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(adresseduzip));
                    zip.setMethod(ZipOutputStream.DEFLATED);
                    zip.setLevel(Deflater.BEST_COMPRESSION);
                    File dataDirectories = new File(file.getName());
                    FileInputStream fis = new FileInputStream(dataDirectories);
                    byte[] bytes = new byte[fis.available()];
                    fis.read(bytes);

                    ZipEntry entry = new ZipEntry(file.getName());
                    entry.setTime(dataDirectories.lastModified());
                    zip.putNextEntry(entry);
                    zip.write(bytes);
                    zip.closeEntry();
                    fis.close();
                    //zipDirectory(dataDirectories, zip);
                    zip.close();

                    file.delete();

                    return adresseduzip;
                } catch (FileNotFoundException fileNotFound) {
                    fileNotFound.printStackTrace();
                } catch (IOException io) {
                    io.printStackTrace();
                }
            }
        }

        return stw.toString();
    } else if (outMimeType.getSubType().equals("json")) {
        header = "{\"portfolio\": { \"-xmlns:xsi\": \"http://www.w3.org/2001/XMLSchema-instance\",\"-schemaVersion\": \"1.0\",";
        footer = "}}";
    }

    return header + getNode(outMimeType, rootNodeUuid, true, userId, groupId, label).toString() + footer;
}

From source file:org.apache.airavata.gfac.hadoop.handler.HadoopDeploymentHandler.java

private void clusterPropertiesToHadoopSiteXml(Properties props, File hadoopSiteXml)
        throws ParserConfigurationException, TransformerException {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = domFactory.newDocumentBuilder();

    Document hadoopSiteXmlDoc = documentBuilder.newDocument();

    hadoopSiteXmlDoc.setXmlVersion("1.0");
    hadoopSiteXmlDoc.setXmlStandalone(true);
    hadoopSiteXmlDoc.createProcessingInstruction("xml-stylesheet",
            "type=\"text/xsl\" href=\"configuration.xsl\"");

    Element configEle = hadoopSiteXmlDoc.createElement("configuration");

    hadoopSiteXmlDoc.appendChild(configEle);

    for (Map.Entry<Object, Object> entry : props.entrySet()) {
        addPropertyToConfiguration(entry, configEle, hadoopSiteXmlDoc);
    }//from ww  w .j  a  va2s  .  c  o m

    saveDomToFile(hadoopSiteXmlDoc, hadoopSiteXml);
}