Example usage for org.w3c.dom Element equals

List of usage examples for org.w3c.dom Element equals

Introduction

In this page you can find the example usage for org.w3c.dom Element equals.

Prototype

public boolean equals(Object obj) 

Source Link

Document

Indicates whether some other object is "equal to" this one.

Usage

From source file:com.twinsoft.convertigo.beans.core.Sequence.java

private static void traverseLevel(TreeWalker walker, Element topParent, String indent) {
    // describe current node:
    Element current = (Element) walker.getCurrentNode();
    //System.out.println(indent + "- " + ((Element) current).getTagName());

    // store elements which need to be moved
    if (topParent != null) {
        Element parent = (Element) current.getParentNode();
        if (parent != null && !topParent.equals(parent)) {
            OutputFilter outputFilter = (OutputFilter) walker.getFilter();
            outputFilter.getToAddList(topParent).add(current);
        }/*from   w w  w .j  a v a 2s . c om*/
    }

    // traverse children:
    for (Node n = walker.firstChild(); n != null; n = walker.nextSibling()) {
        traverseLevel(walker, current, indent + '\t');
    }

    // return position to the current (level up):
    walker.setCurrentNode(current);
}

From source file:it.iit.genomics.cru.structures.bridges.uniprot.UniprotkbUtils.java

private Collection<MoleculeEntry> getUniprotEntriesXML(String location, boolean waitAndRetryOnFailure)
        throws BridgesRemoteAccessException {

    String url = location + "&format=xml";

    ArrayList<MoleculeEntry> uniprotEntries = new ArrayList<>();
    try {// ww w  .  j  a  va 2  s  .  c  om
        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, Boolean.TRUE);
        HttpGet request = new HttpGet(url);

        // add request header
        request.addHeader("User-Agent", USER_AGENT);

        HttpResponse response = client.execute(request);

        if (response.getEntity().getContentLength() == 0) {
            // No result
            return uniprotEntries;
        }

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(new InputSource(response.getEntity().getContent()));

        // optional, but recommended
        // read this -
        // http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
        doc.getDocumentElement().normalize();

        // interaction structure
        NodeList entryList = doc.getElementsByTagName("entry");

        for (int i = 0; i < entryList.getLength(); i++) {

            Element entryElement = (Element) entryList.item(i);

            String dataset = entryElement.getAttribute("dataset");

            String ac = entryElement.getElementsByTagName("accession").item(0).getFirstChild().getNodeValue();

            MoleculeEntry uniprotEntry = new MoleculeEntry(ac);

            uniprotEntry.setDataset(dataset);

            // Taxid
            Element organism = (Element) entryElement.getElementsByTagName("organism").item(0);

            String organismCommonName = null;
            String organismScientificName = null;
            String organismOtherName = null;

            NodeList organismNames = organism.getElementsByTagName("name");

            for (int j = 0; j < organismNames.getLength(); j++) {

                Element reference = (Element) organismNames.item(j);
                switch (reference.getAttribute("type")) {
                case "scientific":
                    organismScientificName = reference.getTextContent();
                    break;
                case "common":
                    organismCommonName = reference.getTextContent();
                    break;
                default:
                    organismOtherName = reference.getTextContent();
                    break;
                }
            }

            if (null != organismCommonName) {
                uniprotEntry.setOrganism(organismCommonName);
            } else if (null != organismScientificName) {
                uniprotEntry.setOrganism(organismScientificName);
            } else if (null != organismOtherName) {
                uniprotEntry.setOrganism(organismOtherName);
            }

            NodeList organismReferences = organism.getElementsByTagName("dbReference");

            for (int j = 0; j < organismReferences.getLength(); j++) {
                Element reference = (Element) organismReferences.item(j);
                if (reference.hasAttribute("type") && "NCBI Taxonomy".equals(reference.getAttribute("type"))) {
                    String proteinTaxid = reference.getAttribute("id");
                    uniprotEntry.setTaxid(proteinTaxid);
                }
            }

            // GENE
            NodeList geneNames = entryElement.getElementsByTagName("gene");

            for (int j = 0; j < geneNames.getLength(); j++) {
                Element gene = (Element) geneNames.item(j);

                NodeList nameList = gene.getElementsByTagName("name");

                for (int k = 0; k < nameList.getLength(); k++) {
                    Element name = (Element) nameList.item(k);
                    uniprotEntry.addGeneName(name.getFirstChild().getNodeValue());
                }
            }

            // modified residues
            HashMap<String, ModifiedResidue> modifiedResidues = new HashMap<>();

            NodeList features = entryElement.getElementsByTagName("feature");
            for (int j = 0; j < features.getLength(); j++) {
                Element feature = (Element) features.item(j);

                if (false == entryElement.equals(feature.getParentNode())) {
                    continue;
                }

                // ensembl
                if (feature.hasAttribute("type") && "modified residue".equals(feature.getAttribute("type"))) {

                    String description = feature.getAttribute("description").split(";")[0];

                    if (false == modifiedResidues.containsKey(description)) {
                        modifiedResidues.put(description, new ModifiedResidue(description));
                    }

                    NodeList locations = feature.getElementsByTagName("location");
                    for (int k = 0; k < locations.getLength(); k++) {
                        Element loc = (Element) locations.item(k);
                        NodeList positions = loc.getElementsByTagName("position");
                        for (int l = 0; l < positions.getLength(); l++) {
                            Element position = (Element) positions.item(l);
                            modifiedResidues.get(description).addPosition(
                                    new UniprotPosition(Integer.parseInt(position.getAttribute("position"))));
                        }

                    }
                }
            }

            uniprotEntry.getModifications().addAll(modifiedResidues.values());

            // Xrefs:
            NodeList dbReferences = entryElement.getElementsByTagName("dbReference");
            for (int j = 0; j < dbReferences.getLength(); j++) {
                Element dbReference = (Element) dbReferences.item(j);

                if (false == entryElement.equals(dbReference.getParentNode())) {
                    continue;
                }

                NodeList molecules = dbReference.getElementsByTagName("molecule");

                // ensembl
                if (dbReference.hasAttribute("type") && "Ensembl".equals(dbReference.getAttribute("type"))) {

                    // transcript ID
                    String id = dbReference.getAttribute("id");

                    for (int iMolecule = 0; iMolecule < molecules.getLength(); iMolecule++) {
                        Element molecule = (Element) molecules.item(iMolecule);
                        uniprotEntry.addXrefToVarSplice(id, molecule.getAttribute("id"));
                    }

                    uniprotEntry.addEnsemblGene(id);

                    NodeList properties = dbReference.getElementsByTagName("property");

                    for (int k = 0; k < properties.getLength(); k++) {
                        Element property = (Element) properties.item(k);

                        if (property.hasAttribute("type") && "gene ID".equals(property.getAttribute("type"))) {
                            uniprotEntry.addEnsemblGene(property.getAttribute("value"));
                        }
                    }
                }

                // refseq
                if (dbReference.hasAttribute("type") && "RefSeq".equals(dbReference.getAttribute("type"))) {
                    NodeList properties = dbReference.getElementsByTagName("property");
                    for (int k = 0; k < properties.getLength(); k++) {
                        Element property = (Element) properties.item(k);
                        if (property.hasAttribute("type")
                                && "nucleotide sequence ID".equals(property.getAttribute("type"))) {

                            String id = property.getAttribute("value");
                            if (molecules.getLength() > 0) {
                                for (int iMolecule = 0; iMolecule < molecules.getLength(); iMolecule++) {
                                    Element molecule = (Element) molecules.item(iMolecule);

                                    // If refseq, add also without the version                                       
                                    uniprotEntry.addXrefToVarSplice(id, molecule.getAttribute("id"));
                                    uniprotEntry.addXrefToVarSplice(id.split("\\.")[0],
                                            molecule.getAttribute("id"));

                                }
                            } else {
                                // If refseq, add also without the version                                       
                                uniprotEntry.addXrefToVarSplice(id, ac);
                                uniprotEntry.addXrefToVarSplice(id.split("\\.")[0], ac);
                            }

                            uniprotEntry.addRefseq(id);

                        }
                    }
                }

                /* PDB chains will be imported from the webservice */
                // PDB
                if (dbReference.hasAttribute("type") && "PDB".equals(dbReference.getAttribute("type"))) {
                    NodeList properties = dbReference.getElementsByTagName("property");
                    String method = null;
                    String chains = null;

                    for (int k = 0; k < properties.getLength(); k++) {
                        Element property = (Element) properties.item(k);
                        if (property.hasAttribute("type") && "method".equals(property.getAttribute("type"))) {
                            method = property.getAttribute("value");
                        } else if (property.hasAttribute("type")
                                && "chains".equals(property.getAttribute("type"))) {
                            chains = property.getAttribute("value");
                        }
                    }

                    if (method != null && "Model".equals(method)) {
                        continue;
                    }

                    if (chains == null) {
                        continue;
                    }

                    String pdb = dbReference.getAttribute("id");

                    uniprotEntry.addPDB(pdb, method);

                    for (String chainElement : chains.split(",")) {
                        try {
                            String chainNames = chainElement.split("=")[0];
                            int start = Integer.parseInt(chainElement.split("=")[1].trim().split("-")[0]);
                            int end = Integer
                                    .parseInt(chainElement.split("=")[1].trim().split("-")[1].replace(".", ""));
                            for (String chainName : chainNames.split("/")) {
                                uniprotEntry.addChain(pdb, new ChainMapping(pdb, chainName.trim(), start, end),
                                        method);
                            }
                        } catch (ArrayIndexOutOfBoundsException aiobe) {
                            // IGBLogger.getInstance().warning(
                            // "Cannot parse chain: " + chainElement
                            // + ", skip");
                        }
                    }
                }

            }

            // Sequence
            NodeList sequenceElements = entryElement.getElementsByTagName("sequence");

            for (int j = 0; j < sequenceElements.getLength(); j++) {
                Element sequenceElement = (Element) sequenceElements.item(j);

                if (false == sequenceElement.getParentNode().equals(entryElement)) {
                    continue;
                }
                String sequence = sequenceElement.getFirstChild().getNodeValue().replaceAll("\n", "");
                uniprotEntry.setSequence(sequence);
            }

            // Diseases
            NodeList diseases = entryElement.getElementsByTagName("disease");

            for (int j = 0; j < diseases.getLength(); j++) {
                Element disease = (Element) diseases.item(j);

                NodeList nameList = disease.getElementsByTagName("name");

                for (int k = 0; k < nameList.getLength(); k++) {
                    Element name = (Element) nameList.item(k);
                    uniprotEntry.addDisease(name.getFirstChild().getNodeValue());
                }
            }

            // Get fasta for all varsplice
            String fastaQuery = "http://www.uniprot.org/uniprot/" + uniprotEntry.getUniprotAc()
                    + ".fasta?include=yes";

            try {
                //HttpClient fastaClient = new DefaultHttpClient();

                client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, Boolean.TRUE);
                HttpGet fastaRequest = new HttpGet(fastaQuery);

                // add request header
                request.addHeader("User-Agent", USER_AGENT);

                HttpResponse fastaResponse = client.execute(fastaRequest);

                if (fastaResponse.getEntity().getContentLength() == 0) {
                    continue;
                }

                InputStream is = fastaResponse.getEntity().getContent();

                try {
                    LinkedHashMap<String, ProteinSequence> fasta = FastaReaderHelper
                            .readFastaProteinSequence(is);

                    boolean mainSequence = true;

                    for (ProteinSequence seq : fasta.values()) {
                        //                            logger.info("Add sequence: " + seq.getAccession().getID() + " : " + seq.getSequenceAsString());
                        uniprotEntry.addSequence(seq.getAccession().getID(), seq.getSequenceAsString());
                        if (mainSequence) {
                            uniprotEntry.setMainIsoform(seq.getAccession().getID());
                            mainSequence = false;
                        }
                    }
                } catch (Exception e) {
                    logger.error("Cannot retrieve fasta for : " + uniprotEntry.getUniprotAc());
                }
            } catch (IOException | IllegalStateException ex) {
                logger.error(null, ex);
            }

            uniprotEntries.add(uniprotEntry);

        }

    } catch (SAXParseException se) {
        // Nothing was return
        // IGBLogger.getInstance()
        // .error("Uniprot returns empty result: " + url);
    } catch (IOException | ParserConfigurationException | IllegalStateException | SAXException | DOMException
            | NumberFormatException e) {
        if (waitAndRetryOnFailure && allowedUniprotFailures > 0) {
            try {
                allowedUniprotFailures--;
                Thread.sleep(5000);
                return getUniprotEntriesXML(location, false);
            } catch (InterruptedException e1) {
                logger.error("Fail to retrieve data from " + location);
                throw new BridgesRemoteAccessException("Fail to retrieve data from Uniprot " + location);
            }
        } else {
            logger.error("Problem with Uniprot: " + url);
            throw new BridgesRemoteAccessException("Fail to retrieve data from Uniprot " + location);
        }
    }

    for (MoleculeEntry entry : uniprotEntries) {
        addToCache(entry);
    }

    return uniprotEntries;
}

From source file:org.alfresco.web.forms.xforms.Schema2XForms.java

private void createTriggersForRepeats(final Document xformsDocument, final Element rootGroup) {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("[createTriggersForRepeats] start");

    final HashMap<String, Element> bindIdToBind = new HashMap<String, Element>();
    final NodeList binds = xformsDocument.getElementsByTagNameNS(NamespaceConstants.XFORMS_NS, "bind");
    for (int i = 0; i < binds.getLength(); i++) {
        final Element b = (Element) binds.item(i);
        bindIdToBind.put(b.getAttributeNS(null, "id"), b);
    }/* w  w  w .  j  a  va  2s. c o  m*/

    final NodeList repeats = xformsDocument.getElementsByTagNameNS(NamespaceConstants.XFORMS_NS, "repeat");
    final HashMap<Element, Element> bindToRepeat = new HashMap<Element, Element>();
    for (int i = 0; i < repeats.getLength(); i++) {
        Element r = (Element) repeats.item(i);

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("[createTriggersForRepeats] processing repeat " + r.getAttributeNS(null, "id"));

        Element bind = bindIdToBind.get(r.getAttributeNS(NamespaceConstants.XFORMS_NS, "bind"));
        bindToRepeat.put(bind, r);

        String xpath = "";

        do {
            if (xpath.length() != 0) {
                xpath = '/' + xpath;
            }

            if (LOGGER.isDebugEnabled())
                LOGGER.debug("[createTriggersForRepeats] walking bind " + bind.getAttributeNS(null, "id"));

            String s = bind.getAttributeNS(NamespaceConstants.XFORMS_NS, "nodeset");
            s = s.replaceAll("^([^\\[]+).*$", "$1");
            if (bindToRepeat.containsKey(bind) && !r.equals(bindToRepeat.get(bind))) {
                s += "[index(\'" + bindToRepeat.get(bind).getAttributeNS(null, "id") + "\')]";
            }
            xpath = s + xpath;
            bind = ((NamespaceConstants.XFORMS_PREFIX + ":bind").equals(bind.getParentNode().getNodeName())
                    ? (Element) bind.getParentNode()
                    : null);
        } while (bind != null);
        this.createTriggersForRepeat(xformsDocument, rootGroup, r.getAttributeNS(null, "id"), xpath,
                r.getAttributeNS(NamespaceConstants.XFORMS_NS, "bind"));
    }
}

From source file:org.chiba.tools.schemabuilder.AbstractSchemaFormBuilder.java

/**
 * if "createBind", a bind is created, otherwise bindId is used
 *//*ww  w. j a va  2 s .  com*/
private void addSimpleType(Document xForm, Element modelSection, Element formSection,
        XSTypeDefinition controlType, String owningElementName, XSObject owner, String pathToRoot,
        int minOccurs, int maxOccurs) {

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("addSimpleType for " + controlType.getName() + " (owningElementName=" + owningElementName
                + ")");

    // create the <xforms:bind> element and add it to the model.
    Element bindElement = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "bind");
    String bindId = this.setXFormsId(bindElement);
    bindElement.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "nodeset", pathToRoot);
    bindElement = (Element) modelSection.appendChild(bindElement);
    bindElement = startBindElement(bindElement, controlType, minOccurs, maxOccurs);

    // add a group if a repeat !
    if (owner instanceof XSElementDeclaration && maxOccurs != 1) {
        Element groupElement = createGroup(xForm, modelSection, formSection, (XSElementDeclaration) owner);
        //set content
        Element groupWrapper = groupElement;
        if (groupElement != modelSection) {
            groupWrapper = _wrapper.createGroupContentWrapper(groupElement);
        }
        formSection = groupWrapper;
    }

    //eventual repeat
    Element repeatSection = addRepeatIfNecessary(xForm, modelSection, formSection, controlType, minOccurs,
            maxOccurs, pathToRoot);

    // create the form control element
    //put a wrapper for the repeat content, but only if it is really a repeat
    Element contentWrapper = repeatSection;

    if (repeatSection != formSection) {
        //content of repeat
        contentWrapper = _wrapper.createGroupContentWrapper(repeatSection);

        //if there is a repeat -> create another bind with "."
        Element bindElement2 = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "bind");
        String bindId2 = this.setXFormsId(bindElement2);
        bindElement2.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "nodeset", ".");

        //recopy other attributes: required  and type
        // ->no, attributes shouldn't be copied
        /*String required = "required";
        String type = "type";
        if (bindElement.hasAttributeNS(XFORMS_NS, required)) {
        bindElement2.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + required,
                                    bindElement.getAttributeNS(XFORMS_NS, required));
        }
        if (bindElement.hasAttributeNS(XFORMS_NS, type)) {
        bindElement2.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + type,
                                    bindElement.getAttributeNS(XFORMS_NS, type));
        }*/

        bindElement.appendChild(bindElement2);
        bindId = bindId2;
    }

    String caption = createCaption(owningElementName);

    //Element formControl = (Element) contentWrapper.appendChild(createFormControl(xForm,caption,controlType,bindId,bindElement,minOccurs,maxOccurs));
    Element formControl = createFormControl(xForm, caption, controlType, bindId, bindElement, minOccurs,
            maxOccurs);
    Element controlWrapper = _wrapper.createControlsWrapper(formControl);
    contentWrapper.appendChild(controlWrapper);

    // if this is a repeatable then set ref to point to current element
    // not sure if this is a workaround or this is just the way XForms works...
    //
    if (!repeatSection.equals(formSection)) {
        formControl.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "ref", ".");
    }

    Element hint = createHint(xForm, owner);

    if (hint != null) {
        formControl.appendChild(hint);
    }

    //add selector if repeat
    //if (repeatSection != formSection)
    //this.addSelector(xForm, (Element) formControl.getParentNode());
    //
    // TODO: Generate help message based on datatype and restrictions
    endFormControl(formControl, controlType, minOccurs, maxOccurs);
    endBindElement(bindElement);
}

From source file:org.mule.module.xml.config.XsltTextDefinitionParser.java

protected void postProcess(ParserContext context, BeanAssembler assembler, Element element) {
    NodeList children = element.getChildNodes();
    if (0 != children.getLength()) {
        Element stylesheet = null;
        for (int i = 0; i < children.getLength(); i++) {
            if (Node.ELEMENT_NODE == children.item(i).getNodeType()) {
                assertArgument(null == stylesheet, "XSLT transformer can have at most one child element");
                stylesheet = (Element) children.item(i);
            }//from ww w .  j  a  va  2s.  c  o m
        }
        if (null != stylesheet) {
            assertArgument(STYLESHEET.equals(stylesheet.getLocalName()),
                    "XSLT transformer child element must be named " + STYLESHEET);
            assembler.extendTarget("xslt", domToString(stylesheet), false);
            // block processing by Spring
            element.removeChild(stylesheet);
        }
    }
    super.postProcess(context, assembler, element);
}

From source file:org.sakaiproject.content.impl.DbContentService.java

/**
 * Create a file system body binary for any content_resource record that has a null file_path.
 *///ww  w . jav a  2  s .c  o m
protected void convertToFile() {
    M_log.info("convertToFile");

    //final Pattern contextPattern = Pattern.compile("\\A/group/(.+?)/");

    try {
        // get a connection for the updates
        final Connection connection = m_sqlService.borrowConnection();
        boolean wasCommit = connection.getAutoCommit();
        connection.setAutoCommit(false);

        // get a connection for reading binary
        final Connection sourceConnection = m_sqlService.borrowConnection();

        final Counter count = new Counter();

        // read content_resource records that have null file path
        String sql = contentServiceSql.getResourceIdXmlSql();
        m_sqlService.dbRead(sql, null, new SqlReader() {
            public Object readSqlResultRecord(ResultSet result) {
                String id = null;
                BaseResourceEdit edit = null;

                try {
                    Object clob = result.getObject(3);
                    if (clob != null && clob instanceof byte[]) {
                        edit = new BaseResourceEdit();
                        resourceSerializer.parse(edit, (byte[]) clob);
                    }
                } catch (SQLException e) {
                    // ignore?
                    M_log.debug("convertToFile(): SqlException unable to read entity");
                    edit = null;
                } catch (EntityParseException e) {
                    M_log.warn("convertToFile(): EntityParseException unable to parse entity");
                    edit = null;
                }
                if (edit == null) {
                    try {
                        String xml = result.getString(2);
                        if (xml == null) {
                            M_log.warn("convertToFile(): null xml : ");
                            return null;
                        }

                        // read the xml
                        Document doc = Xml.readDocumentFromString(xml);
                        if (doc == null) {
                            M_log.warn("convertToFile(): null xml doc : ");
                            return null;
                        }

                        // verify the root element
                        Element root = doc.getDocumentElement();
                        if (!root.getTagName().equals("resource")) {
                            M_log.warn("convertToFile(): XML root element not resource: " + root.getTagName());
                            return null;
                        }
                        edit = new BaseResourceEdit(root);

                    } catch (SQLException e) {
                        M_log.debug("convertToFile(): SqlException problem with results");
                    }
                }

                if (edit == null) {
                    return null;
                }

                // zero length?
                if (edit.getContentLength() == 0) {
                    M_log.warn("convertToFile(): zero length body ");

                }

                id = edit.getId();

                if (id == null) {
                    return null;
                }

                // is resource body in db there?
                String sql = contentServiceSql.getResourceId2Sql();
                Object[] fields = new Object[1];
                fields[0] = id;
                List found = m_sqlService.dbRead(sourceConnection, sql, fields, null);
                if ((found == null) || (found.size() == 0)) {
                    // not found
                    M_log.warn("convertToFile(): body not found in source : " + id);
                }

                // get the creation date (or modified date, or now)
                Time created = null;
                try {
                    created = edit.getProperties().getTimeProperty(ResourceProperties.PROP_CREATION_DATE);
                } catch (Exception any) {
                    try {
                        created = edit.getProperties().getTimeProperty(ResourceProperties.PROP_MODIFIED_DATE);
                    } catch (Exception e) {
                        created = timeService.newTime();
                    }
                }

                // form the file name
                edit.setFilePath(created);

                try {
                    // read the body from the source
                    sql = contentServiceSql.getBodySql(m_resourceBodyTableName);
                    InputStream stream = m_sqlService.dbReadBinary(sql, fields, true);

                    //byte[] body = new byte[edit.m_contentLength];
                    //m_sqlService.dbReadBinary(sourceConnection, sql, fields, body);

                    // write the body to the file
                    boolean ok = ((DbStorage) m_storage).putResourceBodyFilesystem(edit, stream, m_bodyPath);
                    if (!ok) {
                        M_log.warn("convertToFile: body file failure : " + id + " file: " + edit.m_filePath);
                        return null;
                    }
                } catch (ServerOverloadException e) {
                    M_log.debug("convertToFile(): ServerOverloadException moving resource body for " + id);
                    return null;
                }

                // write resource back to db, now with file path set

                try {
                    // regenerate the serialization
                    byte[] serialization = resourceSerializer.serialize(edit);

                    Matcher contextMatcher = contextPattern.matcher(id);
                    String context = null;
                    if (contextMatcher.find()) {
                        String root = contextMatcher.group(1);
                        context = contextMatcher.group(2);
                        if (!root.equals("group/")) {
                            context = "~" + context;
                        }
                    }

                    // update the record
                    sql = contentServiceSql.getUpdateContentResource3Sql();
                    fields = new Object[6];
                    fields[0] = edit.m_filePath;
                    fields[1] = serialization;
                    fields[2] = context;
                    fields[3] = Long.valueOf(edit.m_contentLength);
                    fields[4] = edit.getResourceType();
                    fields[5] = id;

                    m_sqlService.dbWrite(connection, sql, fields);

                    // m_logger.info(" ** converted: " + id + " size: " +
                    // edit.m_contentLength);
                    count.value++;
                    if ((count.value % 1000) == 0) {
                        connection.commit();
                        M_log.info(" ** converted: " + count.value);
                    }

                    return null;
                } catch (EntityParseException e) {
                    M_log.debug("convertToFile(): EntityParseException for " + id);
                    return null;
                } catch (SQLException e) {
                    M_log.info(" ** exception converting : " + id + " : ", e);
                    return null;
                }
            }
        });

        connection.commit();

        M_log.info("convertToFile: converted resources: " + count.value);

        m_sqlService.returnConnection(sourceConnection);

        connection.setAutoCommit(wasCommit);
        m_sqlService.returnConnection(connection);
    } catch (Exception t) {
        M_log.warn("convertToFile: failed: " + t);
    }

    M_log.info("convertToFile: done");
}