Example usage for org.dom4j Document addElement

List of usage examples for org.dom4j Document addElement

Introduction

In this page you can find the example usage for org.dom4j Document addElement.

Prototype

Element addElement(String name);

Source Link

Document

Adds a new Element node with the given name to this branch and returns a reference to the new node.

Usage

From source file:com.taobao.osceola.demo.acount.persist.service.impl.AccountPersistServiceImpl.java

License:Open Source License

private Document readDocument() throws AccountPersistException {
    File dataFile = new File(file);
    if (!dataFile.exists()) {
        dataFile.getParentFile().mkdirs();
        Document doc = DocumentFactory.getInstance().createDocument();
        Element rootEle = doc.addElement(ELEMENT_ROOT);
        rootEle.addElement(ELEMENT_ACCOUNTS);
        writeDocment(doc);//  w  ww.j  a v  a2 s  . com
    }

    try {
        return reader.read(new File(file));
    } catch (DocumentException e) {
        throw new AccountPersistException("", e);
    }
}

From source file:com.tmount.util.FileUtils.java

License:Open Source License

 /**
 * ?/*from  w  ww . j a  va  2s .  c  om*/
 * @param fileName ??
 */
private static void initFile(String fileName){
      
   Document document = DocumentHelper.createDocument();
   Element root = document.addElement("auth");
   Element billdata = root.addElement("balance");
   billdata.setText("100");
   OutputFormat format = OutputFormat.createPrettyPrint();
   format.setEncoding("GBK");
   XMLWriter writer;
   try {
      writer = new XMLWriter(new FileWriter(new File(
            fileName)), format);
      writer.write(document); // 
      writer.close();
   } catch (IOException e) {
      log.info(" *** IOException *** ",e);
   }
      
}

From source file:com.uletian.ultcrm.business.service.CustomerInfoSyncService.java

public void notifycationDataChange(Customer customer) {
    StringWriter writer = new StringWriter();
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding("UTF-8");
    Document doc = DocumentHelper.createDocument();

    Namespace namespace = new Namespace("ns0", "http://crm/91jpfw.cn");
    Element root = doc.addElement(new QName("customer", namespace));
    root.addElement(new QName("action")).addText(action.BINDING_TEL.toString());
    root.addElement(new QName("sourceSys")).addText("ULTCRM");
    root.addElement(new QName("ultcrmid")).addText(customer.getId().toString());
    root.addElement(new QName("crmid")).addText(customer.getSyncid() == null ? "" : customer.getSyncid());
    String name = null;//  ww  w  .  j  a va2 s. c o m
    if (customer.getName() == null || "".equals(customer.getName())) {
        name = customer.getNickname();
    } else {
        name = customer.getName();
    }
    root.addElement(new QName("name")).addText(name);
    root.addElement(new QName("sexy")).addText(customer.getSex() == null ? "" : customer.getSex());
    root.addElement(new QName("telephone")).addText(customer.getPhone() == null ? "" : customer.getPhone());
    root.addElement(new QName("country")).addText(customer.getCountry() == null ? "" : customer.getCountry());
    root.addElement(new QName("province"))
            .addText(customer.getProvince() == null ? "" : customer.getProvince());
    root.addElement(new QName("city")).addText(customer.getCity() == null ? "" : customer.getCity());
    root.addElement(new QName("address")).addText(customer.getAddress() == null ? "" : customer.getAddress());
    root.addElement(new QName("postcode"))
            .addText(customer.getPostcode() == null ? "" : customer.getPostcode());
    Element techsElement = root.addElement(new QName("techs"));
    List<Tech> techs = customer.getTechs();
    if (techs != null && techs.size() > 0) {
        for (int i = 0; i < techs.size(); i++) {
            Tech tech = techs.get(i);
            Element techElement = techsElement.addElement("tech");

            techElement.addElement(new QName("crmtechid"))
                    .addText(tech.getCrmTechId() == null ? "" : tech.getCrmTechId());
            techElement.addElement(new QName("code")).addText(tech.getTechModel().getCode());
            techElement.addElement(new QName("techlevelno"))
                    .addText(tech.getTechlevelno() == null ? "" : tech.getTechlevelno());
            techElement.addElement(new QName("techerno"))
                    .addText(tech.getTecherno() == null ? "" : tech.getTecherno());
            techElement.addElement(new QName("techname"))
                    .addText(tech.getTechname() == null ? "" : tech.getTechname());
            techElement.addElement(new QName("coursetime"))
                    .addText(tech.getCoursetime() == null ? "" : tech.getCoursetime());
            String trainExpireDate = "";
            if (tech.getTrainExpireDate() != null) {
                trainExpireDate = sdf.format(tech.getTrainExpireDate());
            }
            techElement.addElement(new QName("trainExpireDate")).addText(trainExpireDate);
            techElement.addElement(new QName("trainCompany"))
                    .addText(tech.getTrainCompany() == null ? "" : tech.getTrainCompany());
            techElement.addElement(new QName("courseCode"))
                    .addText(tech.getCourseCode() == null ? "" : tech.getCourseCode());
            techElement.addElement(new QName("techColor"))
                    .addText(tech.getColor() == null ? "" : tech.getColor());
            String registerDate = "";
            if (tech.getRegisterDate() != null) {
                registerDate = sdf.format(tech.getRegisterDate());
            }
            techElement.addElement(new QName("registerDate")).addText(registerDate);
            techElement.addElement(new QName("courseLicense"))
                    .addText(tech.getCourseLicense() == null ? "" : tech.getCourseLicense());
            String checkExpireDate = "";
            if (tech.getCheckExpireDate() != null) {
                checkExpireDate = sdf.format(tech.getCheckExpireDate());
            }
            techElement.addElement(new QName("checkExpireDate")).addText(checkExpireDate);
            techElement.addElement(new QName("memberLevel"))
                    .addText(tech.getMemberLevel() == null ? "" : tech.getMemberLevel());

            // ? by xiecheng 2015-11-19
            techElement.addElement(new QName("nextMaintCoursetime"))
                    .addText(StringUtils.isNoneBlank(tech.getNextMaintCoursetime())
                            ? tech.getNextMaintCoursetime()
                            : "");

            String nextMaintDate = "";
            if (tech.getNextMaintDate() != null) {
                nextMaintDate = sdf.format(tech.getNextMaintDate());
            }
            techElement.addElement(new QName("nextMaintDate")).addText(nextMaintDate);

            String lastConsumeDate = "";
            if (tech.getLastConsumeDate() != null) {
                lastConsumeDate = sdf.format(tech.getLastConsumeDate());
            }
            techElement.addElement(new QName("lastConsumeDate")).addText(lastConsumeDate);

        }
    }
    XMLWriter xmlwriter = new XMLWriter(writer, format);
    try {
        xmlwriter.write(doc);
    } catch (IOException e) {
    }
    customerInfoMessageService.sendMessage(writer.toString());

}

From source file:com.userweave.domain.util.xml.InvoiceCreator.java

License:Open Source License

/**
 * Create XML Representation of Invoice of given Study
 * @param study/*from   w  w  w.  j a va2s. c  om*/
 * @return
 */
public String toXML(Study study) {

    DecimalFormat df_us = (DecimalFormat) DecimalFormat.getInstance(Locale.US);
    df_us.applyPattern("#0.00");

    DecimalFormat df_de = (DecimalFormat) DecimalFormat.getInstance(Locale.GERMAN);
    df_de.applyPattern("#0.00");

    Document document = DocumentHelper.createDocument();
    Element invoice = document.addElement("invoice");

    Element receipient = invoice.addElement("receipient");

    Element details = invoice.addElement("details");

    if (study.getOwner().getCompany() != null) {
        receipient.addElement("company").addText(study.getOwner().getCompany());
    } else {
        receipient.addElement("company").addText("");
    }

    receipient.addElement("surname").addText(study.getOwner().getSurname());

    receipient.addElement("forename").addText(study.getOwner().getForename());

    Element address = receipient.addElement("address");
    if (study.getOwner().getAddress() != null) {
        address.addElement("street").addText(study.getOwner().getAddress().getStreet());
        address.addElement("housenumber").addText(study.getOwner().getAddress().getHouseNumber());
        address.addElement("postcode").addText(study.getOwner().getAddress().getPostcode());
        address.addElement("city").addText(study.getOwner().getAddress().getCity());
        address.addElement("country").addText(study.getOwner().getAddress().getCountry().getName());
    }

    details.addElement("number").addText(study.getConsideration().getInvoice().getNumber());

    DateTime invoiceDate = study.getConsideration().getDate();
    DateTimeFormatter dateDTF = DateTimeFormat.longDate();
    DateTimeFormatter usFmt = dateDTF.withLocale(Locale.US);
    String dateString = invoiceDate.toString(usFmt);

    if (evaluateReceipient(study) == Receipient.GERMAN_ALL) {
        DateTimeFormatter deFmt = dateDTF.withLocale(Locale.GERMAN);
        dateString = invoiceDate.toString(deFmt);
    }

    details.addElement("date").addText(dateString);

    details.addElement("currency").addText(study.getConsideration().getCurrency().getCurrencyCode());

    Double gross = study.getConsideration().getGrossAmount();
    if (study.getConsideration().getGrossAmount() != null) {

        String grossString = df_us.format(study.getConsideration().getGrossAmount());

        if (evaluateReceipient(study) == Receipient.GERMAN_ALL) {
            grossString = df_de.format(study.getConsideration().getGrossAmount());
        }

        details.addElement("gross").addText(grossString);
    } else {
        details.addElement("gross").addText(new Integer(0).toString());
    }

    if (study.getConsideration().getInvoice().getPurchaseTaxPercent() != null
            && study.getConsideration().getInvoice().getPurchaseTaxPercent() > 0d) {

        String netString = df_us.format(study.getConsideration().getInvoice().getNetAmount());
        if (evaluateReceipient(study) == Receipient.GERMAN_ALL) {
            netString = df_de.format(study.getConsideration().getInvoice().getNetAmount());
        }
        details.addElement("net").addText(netString);

        Double tax = new Double(study.getConsideration().getGrossAmount()
                - study.getConsideration().getInvoice().getNetAmount());
        tax = Math.round(tax * 100.) / 100.;
        String taxString = df_us.format(tax);
        if (evaluateReceipient(study) == Receipient.GERMAN_ALL) {
            netString = df_de.format(tax);
        }
        details.addElement("tax").addText(taxString);

        String taxRateString = df_us.format(study.getConsideration().getInvoice().getPurchaseTaxPercent());
        if (evaluateReceipient(study) == Receipient.GERMAN_ALL) {
            netString = df_de.format(study.getConsideration().getInvoice().getPurchaseTaxPercent());
        }
        details.addElement("taxrate").addText(taxRateString);
    } else {
        details.addElement("net").addText(new Integer(0).toString());
        details.addElement("tax").addText(new Integer(0).toString());

        details.addElement("taxrate")
                .addText(study.getConsideration().getInvoice().getPurchaseTaxPercent().toString());
    }

    return document.asXML();
}

From source file:com.vmware.o11n.plugin.powershell.remote.impl.winrm.ClientState.java

License:Open Source License

private Document getRequestDocument(Action action, ResourceURI resourceURI, OptionSet optionSet, String shelId,
        Element bodyContent) {/*  w  w w  . java  2  s  .c o  m*/
    Document doc = DocumentHelper.createDocument();
    final Element envelope = doc.addElement(QName.get("Envelope", Namespaces.NS_SOAP_ENV));
    envelope.add(getHeader(action, resourceURI, optionSet, shelId));

    final Element body = envelope.addElement(QName.get("Body", Namespaces.NS_SOAP_ENV));

    if (bodyContent != null)
        body.add(bodyContent);

    return doc;
}

From source file:com.weibo.datasys.crawler.impl.crawlUnit.fetcher.wxcs.WXCSFetcher.java

License:Open Source License

@Override
protected void configPostReq(SeedData seedData, DownRequest req) {
    Document doc = DocumentHelper.createDocument();
    doc.setXMLEncoding("utf-8");
    // /*w w  w  . ja  v  a2 s.c  om*/
    Element root = doc.addElement("root");
    // transactionid
    root.addElement("transactionid").addText("");
    // timestamp
    root.addElement("timestamp").addText(sdf.format(new Date()));
    // msgname
    String msgname = seedData.getExtendField(POST_FIELD_PREFIX + "msgname");
    msgname = StringUtils.nullToEmpty(msgname);
    root.addElement("msgname").addText(msgname);
    // result
    root.addElement("result").addText("");
    // resultdesc
    root.addElement("resultdesc").addText("");
    // body
    Element body = root.addElement("body");
    // dircode ?, root
    String dircode = seedData.getExtendField(POST_FIELD_PREFIX + "dircode");
    dircode = StringUtils.nullToEmpty(dircode);
    body.addElement("dircode").addText(dircode);
    // areacode ???
    String areacode = seedData.getExtendField(POST_FIELD_PREFIX + "areacode");
    areacode = StringUtils.nullToEmpty(areacode);
    body.addElement("areacode").addText(areacode);
    // nodeversion ??
    String nodeversion = seedData.getExtendField(POST_FIELD_PREFIX + "nodeversion");
    nodeversion = StringUtils.nullToEmpty(nodeversion);
    body.addElement("nodeversion").addText(nodeversion);
    // depth ?[0..10]?10
    // ?0?????
    // ?>0????
    String depth = seedData.getExtendField(POST_FIELD_PREFIX + "depth");
    depth = StringUtils.nullToEmpty(depth);
    body.addElement("depth").addText(depth);
    // returenres ???
    // 0
    // 1?
    // ?
    String returenres = seedData.getExtendField(POST_FIELD_PREFIX + "returenres");
    if (StringUtils.isEmptyString(returenres)) {
        returenres = "1";
    }
    body.addElement("returenres").addText(returenres);

    req.setContentType("text/xml");
    req.setPostString(doc.asXML());
}

From source file:com.yahoo.validatar.report.junit.JUnitFormatter.java

License:Apache License

/**
 * {@inheritDoc}//from www . j a v a 2 s.  c o  m
 * Writes out the report for the given testSuites in the JUnit XML format.
 */
@Override
public void writeReport(List<TestSuite> testSuites) throws IOException {
    Document document = DocumentHelper.createDocument();

    Element testSuitesRoot = document.addElement("testsuites");

    // Output for each test suite
    for (TestSuite testSuite : testSuites) {
        Element testSuiteRoot = testSuitesRoot.addElement("testsuite")
                .addAttribute("tests", Integer.toString(testSuite.queries.size() + testSuite.tests.size()))
                .addAttribute("name", testSuite.name);

        for (Query query : testSuite.queries) {
            Element queryNode = testSuiteRoot.addElement("testcase").addAttribute("name", query.name);
            if (query.failed()) {
                String failureMessage = StringUtils.join(query.getMessages(), ", ");
                queryNode.addElement("failed").addText(failureMessage);
            }
        }
        for (Test test : testSuite.tests) {
            Element testNode = testSuiteRoot.addElement("testcase").addAttribute("name", test.name);
            if (test.failed()) {
                String failedAsserts = StringUtils.join(test.getMessages(), ", ");
                String failureMessage = "Description: " + test.description + ";\n" + "Failed asserts: "
                        + failedAsserts + "\n";
                testNode.addElement("failed").addText(failureMessage);
            }
        }
    }

    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter(new FileWriter(outputFile), format);
    writer.write(document);
    writer.close();
}

From source file:com.yinghua.translation.rest.PhoneResourceRESTService.java

License:Apache License

/**
 * /*from  ww  w .  jav a2s.c o m*/
 * 
 * @param params
 * @return
 */
@POST
@Path("/weixinNotify")
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public String weixinNotify(String params) {
    String req = null;
    Document reqDoc = DocumentHelper.createDocument();
    Element reqRoot = reqDoc.addElement("xml");
    Element reqCode = reqRoot.addElement("return_code");
    try {
        Document doc = DocumentHelper.parseText(params);
        Element root = doc.getRootElement();
        Element returnCode = root.element("return_code");
        if ("SUCCESS".equals(returnCode.getText())) {
            String orderNo = root.elementText("out_trade_no");
            MemberOrder order = memberOrderBean.findByOrderNo(orderNo);
            if (order != null && "SUCCESS".equals(root.elementText("result_code"))) {
                if (order.getState() != OrderStatus.FINISHED) {//????
                    order.setState(OrderStatus.FINISHED);
                    if (System.currentTimeMillis() >= order.getServiceTime().getTime()) {
                        Account account = accountBean.findByMemberNo(order.getMemberNumber());
                        int addCall = order.getSurplusCallDuration() + account.getSurplusCallDuration();
                        account.setSurplusCallDuration(addCall);
                        accountBean.updateAccount(account);
                        order.setUseState(OrderUseStatus.USING);
                    }
                    memberOrderBean.updateOrder(order);
                    System.out.println("orderNo:" + order.getOrderNo() + "|orderState:" + order.getState()
                            + "|orderUseState:" + order.getUseState());
                }
            } else {
                System.out.println("??");
            }

            PayWeixinLog pwl = new PayWeixinLog();
            pwl.setAppid(root.elementText("appid"));
            pwl.setMchId(root.elementText("mch_id"));
            if (root.element("device_info") != null)
                pwl.setDeviceInfo(root.elementText("device_info"));
            pwl.setNonceStr(root.elementText("nonce_str"));
            pwl.setSign(root.elementText("sign"));
            pwl.setResultCode(root.elementText("result_code"));
            if (root.element("err_code") != null)
                pwl.setErrCode(root.elementText("err_code"));
            if (root.element("err_code_des") != null)
                pwl.setErrCodeDes(root.elementText("err_code_des"));
            pwl.setOpenid(root.elementText("openid"));
            if (root.element("is_subscribe") != null)
                pwl.setIsSubscribe(root.elementText("is_subscribe"));
            pwl.setTradeType(root.elementText("trade_type"));
            pwl.setBankType(root.elementText("bank_type"));
            pwl.setTotalFee(Integer.parseInt(root.elementText("total_fee")));
            if (root.element("fee_type") != null)
                pwl.setFeeType(root.elementText("fee_type"));
            if (root.element("cash_fee") != null)
                pwl.setCashFee(Integer.parseInt(root.elementText("cash_fee")));
            if (root.element("cash_fee_type") != null)
                pwl.setCashFeeType(root.elementText("cash_fee_type"));
            pwl.setTransationId(root.elementText("transation_id"));
            pwl.setOutTradeNo(root.elementText("out_trade_no"));
            if (root.element("attach") != null)
                pwl.setAttach(root.elementText("attach"));
            pwl.setTimeEnd(root.elementText("time_end"));
            payWeixinLogBean.createPayWeixinLog(pwl);

            reqCode.setText("SUCCESS");
        } else {
            reqCode.setText("FAIL");
            Element returnMsg = root.element("return_msg");
            returnMsg.setText(root.elementText("retrun_msg"));
        }
    } catch (Exception e) {
        e.printStackTrace();
        reqCode.setText("FAIL");
        Element reqMsg = reqRoot.addElement("return_msg");
        reqMsg.setText("");
    }
    req = reqDoc.asXML();
    return req;
}

From source file:com.zimbra.cs.account.accesscontrol.RightManager.java

License:Open Source License

/**
 * generates two files in the output directory
 *
 * {right}-expanded.xml: the root combo right fully expanded
 * {right}-ui.xml: all UI covered by the root combo right
 *
 * @param outputDir//from  www  . ja v a  2 s  .  c  o m
 * @throws ServiceException
 * @throws IOException
 */
private void genAdminDocs(String outputDir) throws ServiceException, IOException {
    if (!outputDir.endsWith("/")) {
        outputDir = outputDir + "/";
    }

    List<AdminRight> rootRights = ImmutableList.of(Admin.R_adminConsoleRights);

    for (AdminRight right : rootRights) {
        Multimap<UI, Right> uiMap = TreeMultimap.create();

        /*
         * output the rights XML.  This XML has the root combo right expanded
         * down to each atom(preset or attrs) right
         */
        Document document = DocumentHelper.createDocument();

        Element rightsRoot = document.addElement(E_ROOT);
        genAdminDocByRight(rightsRoot, right, uiMap);
        writeXML(outputDir + right.getName() + "-expanded.xml", document);

        /*
         * output the UI XML.  This XML contains one entry for each UI, sorted by
         * the description of the UI.
         */
        document = DocumentHelper.createDocument();
        Element uiRoot = document.addElement(E_ROOT);
        genAdminDocByUI(uiRoot, uiMap);
        writeXML(outputDir + right.getName() + "-ui.xml", document);
    }

}

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);/* ww w.j ava  2s  .c om*/
        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();
    }
}