Example usage for org.dom4j.io XMLWriter write

List of usage examples for org.dom4j.io XMLWriter write

Introduction

In this page you can find the example usage for org.dom4j.io XMLWriter write.

Prototype

public void write(Object object) throws IOException 

Source Link

Document

Writes the given object which should be a String, a Node or a List of Nodes.

Usage

From source file:com.zimbra.cs.dav.resource.DavResource.java

License:Open Source License

protected String getPropertiesAsText(DavContext ctxt) throws IOException {
    Element e = org.dom4j.DocumentHelper.createElement(DavElements.E_PROP);
    for (ResourceProperty rp : mProps.values())
        rp.toElement(ctxt, e, false);/*www  .  j a v  a 2 s  . co m*/
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setTrimText(false);
    format.setOmitEncoding(false);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XMLWriter writer = new XMLWriter(baos, format);
    writer.write(e);
    return new String(baos.toByteArray());
}

From source file:com.zimbra.cs.dav.resource.MailItemResource.java

License:Open Source License

@Override
public void patchProperties(DavContext ctxt, java.util.Collection<Element> set,
        java.util.Collection<QName> remove) throws DavException, IOException {
    List<QName> reqProps = new ArrayList<QName>();
    for (QName n : remove) {
        mDeadProps.remove(n);/* www  .  ja  va 2  s .co m*/
        reqProps.add(n);
    }
    for (Element e : set) {
        QName name = e.getQName();
        if (name.equals(DavElements.E_DISPLAYNAME)
                && (type == MailItem.Type.FOLDER || type == MailItem.Type.MOUNTPOINT)) {
            // rename folder
            try {
                String val = e.getText();
                String uri = getUri();
                Mailbox mbox = getMailbox(ctxt);
                mbox.rename(ctxt.getOperationContext(), mId, type, val, mFolderId);
                setProperty(DavElements.P_DISPLAYNAME, val);
                UrlNamespace.addToRenamedResource(getOwner(), uri, this);
                UrlNamespace.addToRenamedResource(getOwner(), uri.substring(0, uri.length() - 1), this);
            } catch (ServiceException se) {
                ctxt.getResponseProp().addPropError(DavElements.E_DISPLAYNAME,
                        new DavException(se.getMessage(), DavProtocol.STATUS_FAILED_DEPENDENCY));
            }
            mDeadProps.remove(name);
            continue;
        } else if (name.equals(DavElements.E_CALENDAR_COLOR)
                && (type == MailItem.Type.FOLDER || type == MailItem.Type.MOUNTPOINT)) {
            // change color
            String colorStr = e.getText();
            Color color = new Color(colorStr.substring(0, 7));
            byte col = (byte) COLOR_LIST.indexOf(colorStr);
            if (col >= 0)
                color.setColor(col);
            try {
                Mailbox mbox = getMailbox(ctxt);
                mbox.setColor(ctxt.getOperationContext(), new int[] { mId }, type, color);
            } catch (ServiceException se) {
                ctxt.getResponseProp().addPropError(DavElements.E_CALENDAR_COLOR,
                        new DavException(se.getMessage(), DavProtocol.STATUS_FAILED_DEPENDENCY));
            }
            mDeadProps.remove(name);
            continue;
        } else if (name.equals(DavElements.E_SUPPORTED_CALENDAR_COMPONENT_SET)) {
            // change default view
            @SuppressWarnings("unchecked")
            List<Element> elements = e.elements(DavElements.E_COMP);
            boolean isTodo = false;
            boolean isEvent = false;
            for (Element element : elements) {
                Attribute attr = element.attribute(DavElements.P_NAME);
                if (attr != null && CalComponent.VTODO.name().equals(attr.getValue())) {
                    isTodo = true;
                } else if (attr != null && CalComponent.VEVENT.name().equals(attr.getValue())) {
                    isEvent = true;
                }
            }
            if (isEvent ^ isTodo) { // we support a calendar collection of type event or todo, not both or none.
                Type type = (isEvent) ? Type.APPOINTMENT : Type.TASK;
                try {
                    Mailbox mbox = getMailbox(ctxt);
                    mbox.setFolderDefaultView(ctxt.getOperationContext(), mId, type);
                    // Update the view for this collection. This collection may get cached if display name is modified.
                    // See UrlNamespace.addToRenamedResource()
                    if (this instanceof Collection) {
                        ((Collection) this).view = type;
                    }
                } catch (ServiceException se) {
                    ctxt.getResponseProp().addPropError(name,
                            new DavException(se.getMessage(), DavProtocol.STATUS_FAILED_DEPENDENCY));
                }
            } else {
                ctxt.getResponseProp().addPropError(name, new DavException.CannotModifyProtectedProperty(name));
            }
            continue;
        }
        mDeadProps.put(name, e);
        reqProps.add(name);
    }
    String configVal = "";
    if (mDeadProps.size() > 0) {
        org.dom4j.Document doc = org.dom4j.DocumentHelper.createDocument();
        Element top = doc.addElement(CONFIG_KEY);
        for (Map.Entry<QName, Element> entry : mDeadProps.entrySet())
            top.add(entry.getValue().detach());

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        OutputFormat format = OutputFormat.createCompactFormat();
        XMLWriter writer = new XMLWriter(out, format);
        writer.write(doc);
        configVal = new String(out.toByteArray(), "UTF-8");

        if (configVal.length() > PROP_LENGTH_LIMIT)
            for (Map.Entry<QName, Element> entry : mDeadProps.entrySet())
                ctxt.getResponseProp().addPropError(entry.getKey(),
                        new DavException("prop length exceeded", DavProtocol.STATUS_INSUFFICIENT_STORAGE));
    }
    Mailbox mbox = null;
    try {
        mbox = getMailbox(ctxt);
        mbox.lock.lock();
        Metadata data = mbox.getConfig(ctxt.getOperationContext(), CONFIG_KEY);
        if (data == null) {
            data = new Metadata();
        }
        data.put(Integer.toString(mId), configVal);
        mbox.setConfig(ctxt.getOperationContext(), CONFIG_KEY, data);
    } catch (ServiceException se) {
        for (QName qname : reqProps)
            ctxt.getResponseProp().addPropError(qname,
                    new DavException(se.getMessage(), HttpServletResponse.SC_FORBIDDEN));
    } finally {
        if (mbox != null)
            mbox.lock.release();
    }
}

From source file:com.zimbra.cs.dav.service.DavMethod.java

License:Open Source License

public HttpMethod toHttpMethod(DavContext ctxt, String targetUrl) throws IOException, DavException {
    if (ctxt.getUpload() != null && ctxt.getUpload().getSize() > 0) {
        PostMethod method = new PostMethod(targetUrl) {
            @Override/*  w  w  w  .ja  v  a2 s  .  co  m*/
            public String getName() {
                return getMethodName();
            }
        };
        RequestEntity reqEntry;
        if (ctxt.hasRequestMessage()) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            XMLWriter writer = new XMLWriter(baos);
            writer.write(ctxt.getRequestMessage());
            reqEntry = new ByteArrayRequestEntity(baos.toByteArray());
        } else { // this could be a huge upload
            reqEntry = new InputStreamRequestEntity(ctxt.getUpload().getInputStream(),
                    ctxt.getUpload().getSize());
        }
        method.setRequestEntity(reqEntry);
        return method;
    }
    return new GetMethod(targetUrl) {
        @Override
        public String getName() {
            return getMethodName();
        }
    };
}

From source file:com.zimbra.soap.util.WsdlGenerator.java

License:Open Source License

public static void writeWsdl(OutputStream xmlOut, String targetNamespace, String serviceName,
        List<WsdlInfoForNamespace> nsInfos) throws IOException {
    Document wsdlDoc = makeWsdlDoc(nsInfos, serviceName, targetNamespace);
    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter(xmlOut, format);
    writer.write(wsdlDoc);
    writer.close();//  w w  w.  j  av a2s  .c om
}

From source file:com.zuuyii.action.admin.InstallAction.java

public String save() throws URISyntaxException, IOException, DocumentException {
    if (isInstalled()) {
        return ajaxJsonErrorMessage("SHOP++?????");
    }/*from  w ww .j  a  v a  2s  .com*/
    if (StringUtils.isEmpty(databaseHost)) {
        return ajaxJsonErrorMessage("?!");
    }
    if (StringUtils.isEmpty(databasePort)) {
        return ajaxJsonErrorMessage("??!");
    }
    if (StringUtils.isEmpty(databaseUsername)) {
        return ajaxJsonErrorMessage("???!");
    }
    if (StringUtils.isEmpty(databasePassword)) {
        return ajaxJsonErrorMessage("??!");
    }
    if (StringUtils.isEmpty(databaseName)) {
        return ajaxJsonErrorMessage("???!");
    }
    if (StringUtils.isEmpty(adminUsername)) {
        return ajaxJsonErrorMessage("???!");
    }
    if (StringUtils.isEmpty(adminPassword)) {
        return ajaxJsonErrorMessage("??!");
    }
    if (StringUtils.isEmpty(installStatus)) {
        Map<String, String> jsonMap = new HashMap<String, String>();
        jsonMap.put(STATUS, "requiredCheckFinish");
        return ajaxJson(jsonMap);
    }

    String jdbcUrl = "jdbc:mysql://" + databaseHost + ":" + databasePort + "/" + databaseName
            + "?useUnicode=true&characterEncoding=UTF-8";
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    try {
        // ?
        connection = DriverManager.getConnection(jdbcUrl, databaseUsername, databasePassword);
        DatabaseMetaData databaseMetaData = connection.getMetaData();
        String[] types = { "TABLE" };
        resultSet = databaseMetaData.getTables(null, databaseName, "%", types);
        if (StringUtils.equalsIgnoreCase(installStatus, "databaseCheck")) {
            Map<String, String> jsonMap = new HashMap<String, String>();
            jsonMap.put(STATUS, "databaseCheckFinish");
            return ajaxJson(jsonMap);
        }

        // ?
        if (StringUtils.equalsIgnoreCase(installStatus, "databaseCreate")) {
            StringBuffer stringBuffer = new StringBuffer();
            BufferedReader bufferedReader = null;
            String sqlFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI()
                    .getPath() + SQL_INSTALL_FILE_NAME;
            bufferedReader = new BufferedReader(
                    new InputStreamReader(new FileInputStream(sqlFilePath), "UTF-8"));
            String line = "";
            while (null != line) {
                line = bufferedReader.readLine();
                stringBuffer.append(line);
                if (null != line && line.endsWith(";")) {
                    System.out.println("[SHOP++?]SQL: " + line);
                    preparedStatement = connection.prepareStatement(stringBuffer.toString());
                    preparedStatement.executeUpdate();
                    stringBuffer = new StringBuffer();
                }
            }
            String insertAdminSql = "INSERT INTO `Admin` VALUES ('402881862bec2a21012bec2bd8de0003','2010-10-10 0:0:0','2010-10-10 0:0:0','','admin@shopxx.net',b'1',b'0',b'0',b'0',NULL,NULL,0,NULL,'?','"
                    + DigestUtils.md5Hex(adminPassword) + "','" + adminUsername + "');";
            String insertAdminRoleSql = "INSERT INTO `Admin_Role` VALUES ('402881862bec2a21012bec2bd8de0003','402881862bec2a21012bec2b70510002');";
            preparedStatement = connection.prepareStatement(insertAdminSql);
            preparedStatement.executeUpdate();
            preparedStatement = connection.prepareStatement(insertAdminRoleSql);
            preparedStatement.executeUpdate();
        }
    } catch (SQLException e) {
        e.printStackTrace();
        return ajaxJsonErrorMessage("???!");
    } finally {
        try {
            if (resultSet != null) {
                resultSet.close();
                resultSet = null;
            }
            if (preparedStatement != null) {
                preparedStatement.close();
                preparedStatement = null;
            }
            if (connection != null) {
                connection.close();
                connection = null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // ???
    String configFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath()
            + JDBC_CONFIG_FILE_NAME;
    Properties properties = new Properties();
    properties.put("jdbc.driver", "com.mysql.jdbc.Driver");
    properties.put("jdbc.url", jdbcUrl);
    properties.put("jdbc.username", databaseUsername);
    properties.put("jdbc.password", databasePassword);
    properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
    properties.put("hibernate.show_sql", "false");
    properties.put("hibernate.format_sql", "false");
    OutputStream outputStream = new FileOutputStream(configFilePath);
    properties.store(outputStream, JDBC_CONFIG_FILE_DESCRIPTION);
    outputStream.close();

    // ??
    /*String backupWebConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath() + BACKUP_WEB_CONFIG_FILE_NAME;
    String backupApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath() + BACKUP_APPLICATION_CONTEXT_CONFIG_FILE_NAME;
    String backupCompassApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath() + BACKUP_COMPASS_APPLICATION_CONTEXT_CONFIG_FILE_NAME;
    String backupSecurityApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath() + BACKUP_SECURITY_APPLICATION_CONTEXT_CONFIG_FILE_NAME;
            
    String webConfigFilePath = new File(Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath()).getParent() + "/" + WEB_CONFIG_FILE_NAME;
    String applicationContextConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath() + APPLICATION_CONTEXT_CONFIG_FILE_NAME;
    String compassApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath() + COMPASS_APPLICATION_CONTEXT_CONFIG_FILE_NAME;
    String securityApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath() + SECURITY_APPLICATION_CONTEXT_CONFIG_FILE_NAME;
            
    FileUtils.copyFile(new File(backupWebConfigFilePath), new File(webConfigFilePath));
    FileUtils.copyFile(new File(backupApplicationContextConfigFilePath), new File(applicationContextConfigFilePath));
    FileUtils.copyFile(new File(backupCompassApplicationContextConfigFilePath), new File(compassApplicationContextConfigFilePath));
    FileUtils.copyFile(new File(backupSecurityApplicationContextConfigFilePath), new File(securityApplicationContextConfigFilePath));
    */
    // ??
    String systemConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI()
            .getPath() + SystemConfigUtil.CONFIG_FILE_NAME;
    File systemConfigFile = new File(systemConfigFilePath);
    SAXReader saxReader = new SAXReader();
    Document document = saxReader.read(systemConfigFile);
    Element rootElement = document.getRootElement();
    Element systemConfigElement = rootElement.element("systemConfig");
    Node isInstalledNode = document.selectSingleNode("/shopxx/systemConfig/isInstalled");
    if (isInstalledNode == null) {
        isInstalledNode = systemConfigElement.addElement("isInstalled");
    }
    isInstalledNode.setText("true");
    try {
        OutputFormat outputFormat = OutputFormat.createPrettyPrint();// XML?
        outputFormat.setEncoding("UTF-8");// XML?
        outputFormat.setIndent(true);// ?
        outputFormat.setIndent("   ");// TAB?
        outputFormat.setNewlines(true);// ??
        XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(systemConfigFile), outputFormat);
        xmlWriter.write(document);
        xmlWriter.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return ajaxJsonSuccessMessage("SHOP++?????");
}

From source file:condorclient.utilities.XMLHandler.java

public String createName_IdXML() {
    String strXML = null;/*  w w w .jav a2s . c o m*/
    Document document = DocumentHelper.createDocument();
    // document.
    Element root = document.addElement("root");

    Element info = root.addElement("info");

    Element job = info.addElement("job");
    job.addAttribute("name", "test");
    job.addAttribute("id", "0");

    StringWriter strWtr = new StringWriter();
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding("UTF-8");
    XMLWriter xmlWriter = new XMLWriter(strWtr, format);
    try {
        xmlWriter.write(document);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    strXML = strWtr.toString();
    //--------

    //-------
    //strXML=document.asXML();
    //------
    //-------------
    File file = new File("niInfo.xml");
    if (file.exists()) {
        file.delete();
    }
    try {
        file.createNewFile();
        XMLWriter out = new XMLWriter(new FileWriter(file));
        out.write(document);
        out.flush();
        out.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //--------------

    return strXML;
}

From source file:condorclient.utilities.XMLHandler.java

public void removeJob(String clusterId) {

    SAXReader saxReader = new SAXReader();
    Document document = null;//from w  w w .j  a v a 2s .com
    try {
        document = saxReader.read(new File("niInfo.xml"));

    } catch (DocumentException ex) {
        Logger.getLogger(XMLHandler.class.getName()).log(Level.SEVERE, null, ex);
    }

    List list = document.selectNodes("/root/info/job");//?job
    Iterator iter = list.iterator();
    Element root = document.getRootElement();
    Element info = root.element("info");
    while (iter.hasNext()) {
        Element job = (Element) iter.next();
        String id = job.attributeValue("id");
        if (id.equals(clusterId)) {

            info.remove(job);
        }

    }
    XMLWriter writer = null;
    try {
        writer = new XMLWriter(new FileWriter(new File("niInfo.xml")));
        writer.write(document);
        writer.close();
    } catch (IOException ex) {
        Logger.getLogger(XMLHandler.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:condorclient.utilities.XMLHandler.java

public void modifyJob(String name, String clusterId) {

    SAXReader saxReader = new SAXReader();
    Document document = null;/*  w w w  .j a va2  s . c  om*/
    try {
        document = saxReader.read(new File("niInfo.xml"));

    } catch (DocumentException ex) {
        Logger.getLogger(XMLHandler.class.getName()).log(Level.SEVERE, null, ex);
    }

    List list = document.selectNodes("/root/info/job");
    Iterator iter = list.iterator();

    while (iter.hasNext()) {
        Element job = (Element) iter.next();

        String id = job.attributeValue("id");
        if (id.equals(clusterId)) {
            job.attribute("name").setValue(name);
        }

    }
    XMLWriter writer = null;
    try {
        writer = new XMLWriter(new FileWriter(new File("niInfo.xml")));
        writer.write(document);
        writer.close();
    } catch (IOException ex) {
        Logger.getLogger(XMLHandler.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:condorclient.utilities.XMLHandler.java

public void addJob(String name, String clusterId, String resultpath, String expFile, String infoFile) {

    SAXReader saxReader = new SAXReader();
    Document document = null;/*from  w w w. j  a  v a2  s  .c  o  m*/
    try {
        document = saxReader.read(new File("niInfo.xml"));

    } catch (DocumentException ex) {
        Logger.getLogger(XMLHandler.class.getName()).log(Level.SEVERE, null, ex);
    }

    Element root = document.getRootElement();
    Element info = root.element("info");
    Element job = info.addElement("job");
    job.addAttribute("name", name);
    job.addAttribute("id", clusterId);
    job.addAttribute("dir", resultpath);
    job.addAttribute("transfer", "0");
    job.addAttribute("expFile", expFile);
    job.addAttribute("infoFile", infoFile);
    //  System.out.println("id:" + job.attribute("id").getValue());

    /**
     * document
     */
    XMLWriter writer = null;
    try {
        writer = new XMLWriter(new FileWriter(new File("niInfo.xml")));
        writer.write(document);
        writer.close();
    } catch (IOException ex) {
        Logger.getLogger(XMLHandler.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:condorclient.utilities.XMLHandler.java

public String createXML() {
    String strXML = null;//from  ww w  . ja va  2  s.c o m
    Document document = DocumentHelper.createDocument();
    // document.
    Element root = document.addElement("root");

    Element job = root.addElement("Job");

    Element jobDescFile = job.addElement("item");
    jobDescFile.addAttribute("about", "descfile");
    Element file_name = jobDescFile.addElement("name");
    file_name.addText("submit.txt");
    Element filer_path = jobDescFile.addElement("path");
    filer_path.addText("D:\\HTCondor\\test\\2");

    StringWriter strWtr = new StringWriter();
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding("UTF-8");
    XMLWriter xmlWriter = new XMLWriter(strWtr, format);
    try {
        xmlWriter.write(document);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    strXML = strWtr.toString();
    //--------

    //-------
    //strXML=document.asXML();
    //------
    //-------------
    File file = new File("condorclient.xml");
    if (file.exists()) {
        file.delete();
    }
    try {
        file.createNewFile();
        XMLWriter out = new XMLWriter(new FileWriter(file));
        out.write(document);
        out.flush();
        out.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //--------------

    return strXML;
}