Java 类org.dom4j.dom.DOMElement 实例源码

项目:bisis-v4    文件:ErrorHandler.java   
public Document getErrorElement(String errorCode, String action){
    Document retVal=null;
    Element content=new DOMElement("error");
    Error thisError=null;
    if((thisError=(Error)errors.get(errorCode))==null){
        thisError=(Error)errors.get("Unspecified server error");
    }
    if(thisError==null){
        thisError=new Error("Unspecified server error","An unknown error","Server is unable to perform action due to unknown internal error",0); 
    }
    content.addAttribute("code",thisError.getCode());
    content.addAttribute("level",""+thisError.getLevel());
    content.addAttribute("severity",thisError.getLevelDesc());
    content.setText(thisError.getDescription());
    retVal=MessageUtil.messageSetup("bisis_response","http://www.w3.org/2001/XMLSchema-instance",respSchemaURL,action,content);
    return retVal;
}
项目:bisis-v4    文件:ErrorHandler.java   
public Document getErrorElement(String errorCode, String action, String descriptionAdd){
    Document retVal=null;
    Element content=new DOMElement("error");
    Error thisError=null;
    if((thisError=(Error)errors.get(errorCode))==null){
        thisError=(Error)errors.get("Unspecified server error");
    }
    if(thisError==null){
        thisError=new Error("Unspecified server error","An unknown error","Server is unable to perform action due to unknown internal error",0); 
    }
    content.addAttribute("code",thisError.getCode());
    content.addAttribute("level",""+thisError.getLevel());
    content.addAttribute("severity",thisError.getLevelDesc());
    content.setText(thisError.getDescription()+descriptionAdd);
    retVal=MessageUtil.messageSetup("bisis_response","http://www.w3.org/2001/XMLSchema-instance",respSchemaURL,action,content);
    return retVal;
}
项目:bisis-v4    文件:MessageUtil.java   
public static Document setHeaders(Document contentDoc,String from, String to, String convId){
Element newHeader=new DOMElement("header");
   Element retFrom=new DOMElement("from");
   retFrom.setText(from);
   newHeader.add(retFrom);
   Element retTo=new DOMElement("to");
   retTo.setText(to);
   newHeader.add(retTo);
   Element retTimestamp=new DOMElement("datestamp");
   retTimestamp.setText(""+new java.util.Date().toGMTString());
   Element convid=new DOMElement("conversation_id");
   convid.setText(convId);
   newHeader.add(convid);
   DOMElement newroot=(DOMElement)contentDoc.getRootElement();
   List<Element> els=newroot.elements();
   els.add(0, newHeader);
   return contentDoc;
  }
项目:bisis-v4    文件:MessageUtil.java   
public static Document messageSetup(String rootElement,String namespace,String schemaURL, String actionName, Element content) {
        Namespace nmsp=DOMNamespace.get("xsi",namespace);
        Document newDoc=new DOMDocument();
        Element resp=new DOMElement(rootElement);
Element action=new DOMElement("action");
action.addAttribute("name",actionName);
action.add(content);

resp.addAttribute("xsi:noNamespaceSchemaLocation",schemaURL);
resp.add(nmsp);
      resp.add(action);
newDoc.setRootElement(resp);

   return newDoc;
 }
项目:bisis-v4    文件:MessageUtils.java   
public static DOMElement createBisisHeader(String toServer, String requestedAction, String requestedParams,String convId){
    DOMElement bisisReq=new DOMElement("bisis_request");
    Namespace nmsp=DOMNamespace.get("xsi","http://www.w3.org/2001/XMLSchema-instance");
       bisisReq.addAttribute("xsi:noNamespaceSchemaLocation",MessagingEnvironment.getReqSchemaURL());
       bisisReq.add(nmsp);
       DOMElement header=new DOMElement("header");
       DOMElement from=new DOMElement("from");
       if(MessagingEnvironment.DEBUG==1)
        System.out.println("Messaging: "+MessagingEnvironment.getMyLibServer().getUrlAddress());
       from.setText(MessagingEnvironment.getMyLibServer().getUrlAddress());
       header.add(from);
       DOMElement to=new DOMElement("to");
       to.setText(toServer);
       header.add(to);
       DOMElement datestamp=new DOMElement("datestamp");
       datestamp.setText(new Date().toGMTString());
       header.add(datestamp);
       DOMElement convid=new DOMElement("conversation_id");
       convid.setText(convId);
       header.add(convid);
       bisisReq.add(header);

       DOMElement action=new DOMElement("action");
       action.setAttribute("name",requestedAction);
       DOMElement params=new DOMElement("params");
       params.setAttribute("name",requestedParams);
    return bisisReq;
}
项目:Openfire    文件:StreamManager.java   
/**
 * Attempts to enable Stream Management for the entity identified by the provided JID.
 *
 * @param namespace The namespace that defines what version of SM is to be enabled.
 * @param resume Whether the client is requesting a resumable session.
 */
private void enable( String namespace, boolean resume )
{


    boolean offerResume = allowResume();
    // Ensure that resource binding has occurred.
    if (session.getStatus() != Session.STATUS_AUTHENTICATED) {
        this.namespace = namespace;
        sendUnexpectedError();
        return;
    }

    String smId = null;

    synchronized ( this )
    {
        // Do nothing if already enabled
        if ( isEnabled() )
        {
            sendUnexpectedError();
            return;
        }
        this.namespace = namespace;

        this.resume = resume && offerResume;
        if ( this.resume ) {
            // Create SM-ID.
            smId = StringUtils.encodeBase64( session.getAddress().getResource() + "\0" + session.getStreamID().getID());
        }
    }

    // Send confirmation to the requestee.
    Element enabled = new DOMElement(QName.get("enabled", namespace));
    if (this.resume) {
        enabled.addAttribute("resume", "true");
        enabled.addAttribute( "id", smId);
    }
    session.deliverRawText(enabled.asXML());
}
项目:ph-commons    文件:DOM4JFuncTest.java   
@Test
public void testMisc2 ()
{
  final DOMDocument aXML = new DOMDocument ();
  final Node aChild = aXML.appendChild (new DOMElement ("rootElement",
                                                        new DOMNamespace ("xyz", "http://www.example.org")));
  aChild.appendChild (new DOMText ("anyText"));
  aChild.appendChild (new DOMEntityReference ("abc"));

  assertNotNull (XMLWriter.getNodeAsString (aXML));
}
项目:birt    文件:VersionUpdater.java   
/**
 * @author 
 * @param folderPath
 * @param plug_id
 * @param lastDate
 * @param dayInpast
 */
private void genVersionLog( File folderPath , 
                            String plug_id , 
                            String lastDate , 
                            int dayInpast ){
    // gen the dest file path
    String parentPath = folderPath.getAbsolutePath();
    String fileName = plug_id + "_DayInPast" + ".xml";
    String fullName = parentPath + "/" + fileName;
    File dest = new File(fullName);
    System.out.println("dest file full path:\t"+fullName);
    try{
        //genarate document factory
        DocumentFactory factory = new DocumentFactory();
        //create root element
        DOMElement rootElement = new DOMElement("plugin");
        rootElement.setAttribute("id",plug_id);
        //add child:lastdate
        DOMElement dateElement = new DOMElement("LastDate");
        dateElement.setText(lastDate);
        rootElement.add(dateElement);
        //add child:dayinpast
        DOMElement dayElement = new DOMElement("DayInPast");
        dayElement.setText( Integer.toString(dayInpast));
        rootElement.add(dayElement);
        //gen the doc
        Document doc = factory.createDocument(rootElement);

        //PrettyFormat
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter( new FileWriter(dest) , format );
        writer.write( doc );
        writer.close();

    }catch(Exception ex){
        ex.printStackTrace();
    }

}
项目:gocd    文件:StageXmlViewModel.java   
public Document toXml(XmlWriterContext writerContext) {
    DOMElement root = new DOMElement("stage");
    root.addAttribute("name", stage.getName()).addAttribute("counter", String.valueOf(stage.getCounter()));
    Document document = new DOMDocument(root);
    root.addElement("link").addAttribute("rel", "self").addAttribute("href", httpUrl(writerContext.getBaseUrl()));

    StageIdentifier stageId = stage.getIdentifier();
    root.addElement("id").addCDATA(stageId.asURN());
    String pipelineName = stageId.getPipelineName();
    root.addElement("pipeline").addAttribute("name", pipelineName)
            .addAttribute("counter", String.valueOf(stageId.getPipelineCounter()))
            .addAttribute("label", stageId.getPipelineLabel())
    .addAttribute("href", writerContext.getBaseUrl() + "/api/pipelines/" + pipelineName + "/" + stage.getPipelineId() + ".xml");

    root.addElement("updated").addText(DateUtils.formatISO8601(stage.latestTransitionDate()));

    root.addElement("result").addText(stage.getResult().toString());

    root.addElement("state").addText(stage.status());

    root.addElement("approvedBy").addCDATA(stage.getApprovedBy());

    Element jobs = root.addElement("jobs");
    for (JobInstance jobInstance : stage.getJobInstances()) {
        jobs.addElement("job").addAttribute("href", writerContext.getBaseUrl() + "/api/jobs/" + jobInstance.getId() + ".xml");
    }

    return document;
}
项目:gocd    文件:PipelineXmlViewModel.java   
public Document toXml(XmlWriterContext writerContext) throws DocumentException, IOException {
    DOMElement root = new DOMElement("pipeline");
    root.addAttribute("name", pipeline.getName()).addAttribute("counter", String.valueOf(pipeline.getCounter())).addAttribute("label", pipeline.getLabel());
    Document document = new DOMDocument(root);
    String baseUrl = writerContext.getBaseUrl();
    root.addElement("link").addAttribute("rel", "self").addAttribute("href", httpUrl(baseUrl));

    root.addElement("id").addCDATA(pipeline.getPipelineIdentifier().asURN());
    PipelineTimelineEntry pipelineAfter = pipeline.getPipelineAfter();
    if (pipelineAfter != null) {
        addTimelineLink(root, baseUrl, "insertedBefore", pipelineAfter);
    }
    PipelineTimelineEntry pipelineBefore = pipeline.getPipelineBefore();
    if (pipelineBefore != null) {
        addTimelineLink(root, baseUrl, "insertedAfter", pipelineBefore);
    }

    root.addElement("scheduleTime").addText(DateUtils.formatISO8601(pipeline.getScheduledDate()));

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

    for (MaterialRevision materialRevision : pipeline.getCurrentRevisions()) {
        populateXml(materials, materialRevision, writerContext);

    }

    Element stages = root.addElement("stages");
    for (StageInstanceModel stage : pipeline.getStageHistory()) {
        if (! (stage instanceof NullStageHistoryItem)) {
            stages.addElement("stage").addAttribute("href", StageXmlViewModel.httpUrlFor(writerContext.getBaseUrl(), stage.getId()));
        }
    }

    root.addElement("approvedBy").addCDATA(pipeline.getApprovedBy());
    return document;
}
项目:gocd    文件:JobPlanXmlViewModel.java   
public Document toXml(XmlWriterContext writerContext) throws DocumentException, IOException {
    DOMElement root = new DOMElement("scheduledJobs");
    for (WaitingJobPlan jobPlan : jobPlans) {
        DOMElement jobElement = getXmlForJobPlan(writerContext, jobPlan);
        root.add(jobElement);
    }
    DOMDocument domDocument = new DOMDocument(root);
    return domDocument;
}
项目:gocd    文件:JobPlanXmlViewModel.java   
private DOMElement getXmlForJobPlan(XmlWriterContext writerContext, WaitingJobPlan waitingJobPlan) {
    JobPlan jobPlan = waitingJobPlan.jobPlan();
    DOMElement root = new DOMElement("job");
    root.addAttribute("name", jobPlan.getName()).addAttribute("id", String.valueOf(jobPlan.getJobId()));
    root.addElement("link").addAttribute("rel", "self").addAttribute("href", httpUrlFor(writerContext.getBaseUrl(), jobPlan.getIdentifier()));
    root.addElement("buildLocator").addText(jobPlan.getIdentifier().buildLocator());
    if (!StringUtils.isBlank(waitingJobPlan.envName())) {
        root.addElement("environment").addText(waitingJobPlan.envName());
    }

    if (!jobPlan.getResources().isEmpty()) {
        DOMElement resources = new DOMElement("resources");

        for (Resource resource : jobPlan.getResources()) {
            resources.addElement("resource").addCDATA(resource.getName());
        }
        root.add(resources);
    }

    if (!jobPlan.getVariables().isEmpty()) {
        DOMElement envVars = new DOMElement("environmentVariables");
        for (EnvironmentVariable environmentVariable : jobPlan.getVariables()) {
            envVars.addElement("variable").addAttribute("name", environmentVariable.getName()).addText(environmentVariable.getDisplayValue());
        }
        root.add(envVars);
    }

    return root;
}
项目:bisis-v4    文件:PerformSearchAction.java   
/**
 * Generates XML document containing brief representation of records matching the query
 * @param hits - Array of records matching the query 
 * @return Returns XML (payload) document to be inserted into SOAP message 
 */
private Document prepareResult(Record []hits){
    Element content=new DOMElement("content");
    BriefFormatter rf=(BriefFormatter)RecordFormatterFactory.getFormatter(RecordFormatterFactory.FORMAT_BRIEF);
    content.addAttribute("count",""+0);
    int counter=0;
    UnimarcConverter conv=new UnimarcConverter();
    if(hits!=null){
        for (int i=0;i<hits.length;i++){
            Record oneHit = hits[i];
            if(oneHit!=null){
                Element recBrief=new DOMElement("record_brief");
                recBrief.addAttribute("recId",""+oneHit.getRecordID());

                //add author element
                Element author = new DOMElement("author");
                author.add(new DOMCDATA(getElementContent(rf.getAuthor(oneHit, "sr").toString(),conv)));
                recBrief.add(author);

                //add title element
                Element title = new DOMElement("title");
                title.add(new DOMCDATA(getElementContent(rf.getTitle(oneHit),conv)));
                recBrief.add(title);

                //add publisher element
                Element publisher = new DOMElement("publisher");
                publisher.add(new DOMCDATA(getElementContent(rf.getTitle(oneHit),conv)));
                recBrief.add(publisher);

                //add publication year element
                Element pubYear = new DOMElement("publication_year");
                pubYear.add(new DOMCDATA(rf.getYear(oneHit)));
                recBrief.add(pubYear);

                //add language year element
                Element language = new DOMElement("language");
                language.add(new DOMCDATA(rf.getLanguageOfOriginal(oneHit)));
                recBrief.add(language);

                //add language year element
                Element country = new DOMElement("country");
                country.add(new DOMCDATA(rf.getCountry(oneHit)));
                recBrief.add(country);
                content.add(recBrief);
                counter++;
            }else{
                if(MessagingEnvironment.DEBUG==1)
                    System.out.println("Null objekat za record");
            }
        }
        content.addAttribute("count",""+counter);
    }
    Document newDoc = MessageUtil.messageSetup("bisis_response","http://www.w3.org/2001/XMLSchema-instance",respSchemaURL,"PerformSearchResponse",content);
    return newDoc;
}
项目:buddycloud-atom-validator    文件:AtomEntry.java   
@Override
public Element getPayload() {

    Element entry = new DOMElement("entry", new org.dom4j.Namespace("",
            Atom.NS));
    entry.add(new org.dom4j.Namespace("activity", ActivityStreams.NS));

    String postType = POST_TYPE_NOTE;
    String activityVerb = ACTIVITY_VERB_POST;

    entry.addElement("id").setText(getGlobalItemId());

    String title = this.params.get("title");
    String itemContent = this.params.get("content");
    String publishedDate = Conf.formatDate(new Date());

    entry.addElement("published").setText(publishedDate);

    entry.addElement("updated").setText(publishedDate);

    Element author = entry.addElement("author");

    author.addElement("name").setText(jid.toBareJID());

    author.addElement("uri").setText(AUTHOR_URI_PREFIX + jid.toBareJID());

    author.addElement("activity:object-type").setText(AUTHOR_TYPE);

    if (this.geoloc != null) {
        entry.add(this.geoloc.createCopy());
    }

    if (this.inReplyTo != null) {
        Element reply = entry.addElement("in-reply-to");
        reply.addNamespace("", Atom.NS_THREAD);
        reply.addAttribute("ref", inReplyTo);
        postType = POST_TYPE_COMMENT;
    }

    this.geoloc = this.entry.element("geoloc");

    if (null != meta) {
        entry.add(meta.createCopy());
    }

    if (null != media) {
        entry.add(media.createCopy());
    }

    if (null != targetId) {
        GlobalItemIDImpl globalTargetId = new GlobalItemIDImpl(new JID(
                channelServerDomain), node, targetId);
        Element target = entry.addElement("activity:target");
        target.addElement("id").setText(globalTargetId.toString());
        target.addElement("activity:object-type").setText("post");
    }

    if (itemRating > 0) {
        entry.addNamespace("review", ActivityStreams.NS_REVIEW);
        String rating = String.format("%d.0", itemRating);
        entry.addElement("review:rating").setText(rating);
        title = "Rating";
        itemContent = "rating:" + rating;
        activityVerb = ACTIVITY_VERB_RATED;
    }

    entry.addElement("title").setText(title);

    Element content = entry.addElement("content");
    content.setText(itemContent);
    content.addAttribute("type", this.params.get("content-type"));

    entry.addElement("activity:verb").setText(activityVerb);
    Element activityObject = entry.addElement("activity:object");
    activityObject.addElement("activity:object-type").setText(postType);

    return entry;
}
项目:Openfire    文件:Xep227ExporterTest.java   
@Override
public Element getVCard(String username) {
  logger.finest("getVCard");
  return new DOMElement("VCARD");
}
项目:gocd    文件:PipelineXmlViewModel.java   
private void addTimelineLink(DOMElement root, String baseUrl, final String rel, final PipelineTimelineEntry entry) {
    root.addElement("link").addAttribute("rel", rel).addAttribute("href", httpUrlForPipeline(baseUrl, entry.getId(), pipeline.getName()));
}
项目:gocd    文件:JobXmlViewModel.java   
public Document toXml(XmlWriterContext writerContext) throws DocumentException, IOException {
    DOMElement root = new DOMElement("job");
    root.addAttribute("name", jobInstance.getName());
    Document document = new DOMDocument(root);
    root.addElement("link").addAttribute("rel", "self").addAttribute("href", httpUrl(writerContext.getBaseUrl()));

    JobIdentifier identifier = jobInstance.getIdentifier();
    root.addElement("id").addCDATA(identifier.asURN());
    String pipelineName = identifier.getPipelineName();
    StageIdentifier stageId = identifier.getStageIdentifier();

    root.addElement("pipeline").addAttribute("name", pipelineName)
            .addAttribute("counter", String.valueOf(stageId.getPipelineCounter()))
            .addAttribute("label", stageId.getPipelineLabel());

    root.addElement("stage").addAttribute("name", stageId.getStageName()).addAttribute("counter", stageId.getStageCounter()).addAttribute("href", StageXmlViewModel.httpUrlFor(
            writerContext.getBaseUrl(),
            jobInstance.getStageId()));

    root.addElement("result").addText(jobInstance.getResult().toString());

    root.addElement("state").addText(jobInstance.getState().toString());

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

    for (Property property : writerContext.propertiesForJob(jobInstance.getId())) {
        properties.addElement("property").addAttribute("name", property.getKey()).addCDATA(property.getValue());
    }

    root.addElement("agent").addAttribute("uuid", jobInstance.getAgentUuid());

    root.addComment("artifacts of type `file` will not be shown. See https://github.com/gocd/gocd/pull/2875");
    Element artifacts = root.addElement("artifacts");
    artifacts.addAttribute("baseUri", writerContext.artifactBaseUrl(identifier)).addAttribute("pathFromArtifactRoot", writerContext.artifactRootPath(identifier));

    JobPlan jobPlan = writerContext.planFor(identifier);
    for (ArtifactPlan artifactPlan : jobPlan.getArtifactPlansOfType(ArtifactType.unit)) {
        artifacts.addElement("artifact").addAttribute("src", artifactPlan.getSrc()).addAttribute("dest", artifactPlan.getDest()).addAttribute("type", artifactPlan.getArtifactType().toString());
    }

    // Retain the top level elements for backward-compatibility
    root.addComment("resources are now intentionally left blank. See https://github.com/gocd/gocd/pull/2875");
    root.addElement("resources");
    root.addComment("environmentvariables are now intentionally left blank. See https://github.com/gocd/gocd/pull/2875");
    root.addElement("environmentvariables");

    return document;
}
项目:windup    文件:Help.java   
public static void save(Furnace furnace) throws IOException
{
    Document doc = new DOMDocument(new DOMElement(HELP));
    Iterable<ConfigurationOption> windupOptions = WindupConfiguration.getWindupConfigurationOptions(furnace);
    for (ConfigurationOption option : windupOptions)
    {
        Element optionElement = new DOMElement(OPTION);
        optionElement.addAttribute(NAME, option.getName());

        Element descriptionElement = new DOMElement(DESCRIPTION);
        descriptionElement.setText(option.getDescription());
        optionElement.add(descriptionElement);

        // Type
        Element typeElement = new DOMElement(TYPE);
        typeElement.setText(option.getType().getSimpleName());
        optionElement.add(typeElement);

        // UI Type
        Element uiTypeElement = new DOMElement(UI_TYPE);
        uiTypeElement.setText(option.getUIType().name());
        optionElement.add(uiTypeElement);

        // Available Options
        Element availableOptionsElement = new DOMElement(AVAILABLE_OPTIONS);
        for (Object availableValueObject : option.getAvailableValues())
        {
            if (availableValueObject == null)
                continue;

            Element availableOption = new DOMElement(AVAILABLE_OPTION);
            availableOption.setText(String.valueOf(availableValueObject));
            availableOptionsElement.add(availableOption);
        }
        if (!availableOptionsElement.elements().isEmpty())
            optionElement.add(availableOptionsElement);

        // Is it required?
        Element required = new DOMElement(REQUIRED);
        required.setText(Boolean.toString(option.isRequired()));
        optionElement.add(required);

        doc.getRootElement().add(optionElement);
    }

    try (FileWriter writer = new FileWriter(getDefaultFile()))
    {
        doc.write(writer);
    }
}