Example usage for org.dom4j.io XMLWriter XMLWriter

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

Introduction

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

Prototype

public XMLWriter(OutputFormat format) throws UnsupportedEncodingException 

Source Link

Usage

From source file:condorclient.utilities.XMLHandler.java

void setTransfer(String clusterId) {
    SAXReader saxReader = new SAXReader();
    Document document = null;/*from w  w  w  .j  a  va2s  . 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("transfer").setValue("1");
        }

    }
    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:controller.setup.Setup.java

private void updateHibernateCfgFile(String bd, String bdHost, String bdPort, String bdName, String bdUser,
        String bdUserMdp) {/*w  w w  .ja v a2 s. c  o m*/

    System.out.println(
            "------------------------------ Creation hibernate config file -----------------------------");

    try {

        URL resource = Thread.currentThread().getContextClassLoader().getResource("hibernate.cfg.xml");
        File f = new File(resource.toURI());

        SAXReader xmlReader = new SAXReader();
        Document doc = xmlReader.read(f);
        Element sessionFactory = (Element) doc.getRootElement().elements().get(0);

        if (sessionFactory.elements().size() != 0)
            for (Iterator elt = sessionFactory.elements().iterator(); elt.hasNext();)
                sessionFactory.remove((Element) elt.next());

        if (bd.equals("mysql")) {
            sessionFactory.addElement("property").addAttribute("name", "dialect")
                    .addText("org.hibernate.dialect.MySQLDialect");
            sessionFactory.addElement("property").addAttribute("name", "connection.url")
                    .addText("jdbc:mysql://" + bdHost + ":" + bdPort + "/" + bdName);
            sessionFactory.addElement("property").addAttribute("name", "connection.driver_class")
                    .addText("com.mysql.jdbc.Driver");
        } else if (bd.equals("pgsql")) {
            sessionFactory.addElement("property").addAttribute("name", "dialect")
                    .addText("org.hibernate.dialect.PostgreSQLDialect");
            sessionFactory.addElement("property").addAttribute("name", "connection.url")
                    .addText("jdbc:postgresql://" + bdHost + ":" + bdPort + "/" + bdName);
            sessionFactory.addElement("property").addAttribute("name", "connection.driver_class")
                    .addText("org.postgresql.Driver");
        } else if (bd.equals("oracle")) {
            sessionFactory.addElement("property").addAttribute("name", "dialect")
                    .addText("org.hibernate.dialect.OracleDialect");
            sessionFactory.addElement("property").addAttribute("name", "connection.url")
                    .addText("jdbc:oracle:thin:@" + bdHost + ":" + bdPort + ":" + bdName);
            sessionFactory.addElement("property").addAttribute("name", "connection.driver_class")
                    .addText("oracle.jdbc.OracleDriver");
        } else if (bd.equals("mssqlserver")) {
            sessionFactory.addElement("property").addAttribute("name", "dialect")
                    .addText("org.hibernate.dialect.SQLServerDialect");
            sessionFactory.addElement("property").addAttribute("name", "connection.url")
                    .addText("jdbc:sqlserver://" + bdHost + ":" + bdPort + ";databaseName=" + bdName + ";");
            sessionFactory.addElement("property").addAttribute("name", "connection.driver_class")
                    .addText("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        }

        sessionFactory.addElement("property").addAttribute("name", "connection.username").addText(bdUser);
        sessionFactory.addElement("property").addAttribute("name", "connection.password").addText(bdUserMdp);
        sessionFactory.addElement("property").addAttribute("name", "hbm2ddl.auto").addText("update");

        XMLWriter writer = new XMLWriter(new FileWriter(f));
        writer.write(doc);
        writer.close();

        System.out.println(
                "------------------------------ Creation hibernate config file over -----------------------------");

    }

    catch (URISyntaxException e) {
        e.printStackTrace();
    }

    catch (DocumentException e) {
        e.printStackTrace();
    }

    catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:cz.dasnet.dasik.Dasik.java

License:Open Source License

@Override
protected void onConnect() {
    log.info("Connected on " + getServer());
    auth();//  w  w w  . jav  a2  s.c o m
    if (authed) {
        requestInvites();
    }
    final Dasik bot = this;
    try {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                bot.joinChannels();
            }
        }, 1000);

        TimerTask dumpTask = new TimerTask() {

            @Override
            public void run() {
                Document document = DocumentHelper.createDocument();
                Element channelinfo = document.addElement("channelinfo");

                for (String c : activeChannels.keySet()) {
                    Element channel = channelinfo.addElement("channel");
                    Element name = channel.addElement("name");
                    name.setText(c);
                    Element size = channel.addElement("size");
                    size.setText("" + getUsers(c).length);
                }

                Element updatetime = channelinfo.addElement("updatetime");
                updatetime.setText(new Long(new Date().getTime() / 1000).toString());

                try {
                    XMLWriter writer = new XMLWriter(new FileWriter("channelinfo.xml"));
                    writer.write(document);
                    writer.close();
                } catch (IOException ex) {
                    log.error("Unable to dump channel info", ex);
                }
            }
        };

        Timer dump = new Timer("dump", true);
        dump.schedule(dumpTask, 10000, 60000);
    } catch (Exception ex) {
        this.joinChannels();
        log.error("Channel autojoin timer failed to schedule the task.", ex);
    }
}

From source file:de.fmaul.android.cmis.utils.StorageUtils.java

License:Apache License

public static void storeFeedInCache(Application app, String url, Document doc, String workspace)
        throws StorageException {
    File cacheFile = getFeedFile(app, workspace, md5(url));
    ensureOrCreatePathAndFile(cacheFile);

    try {//from   w ww. j  ava  2  s.c o  m
        XMLWriter writer = new XMLWriter(new FileOutputStream(cacheFile));
        writer.write(doc);
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:de.innovationgate.utils.WGUtils.java

License:Apache License

/**
 * Creates a directory link file pointing to a target path
 * @param parentDir The directory to contain the link file
 * @param target The target path that the directory link should point to
 * @throws IOException//from w  ww.  ja  va 2  s  .c  o m
 */
public static void createDirLink(File parentDir, String target) throws IOException {
    File link = new File(parentDir, DIRLINK_FILE);
    Document doc = DocumentFactory.getInstance().createDocument();
    Element dirlink = doc.addElement("dirlink");
    Element path = dirlink.addElement("path");
    path.addAttribute("location", target);
    XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint());
    writer.setOutputStream(new FileOutputStream(link));
    writer.write(doc);
    writer.close();
}

From source file:de.innovationgate.wga.common.beans.hdbmodel.ModelDefinition.java

License:Open Source License

public static ModelDefinition read(InputStream in) throws Exception {

    // First read XML manually and validate against the DTD provided in this OpenWGA distribution (to prevent it being loaded from the internet, which might not work, see #00003612) 
    SAXReader reader = new SAXReader();
    reader.setIncludeExternalDTDDeclarations(true);
    reader.setIncludeInternalDTDDeclarations(true);
    reader.setEntityResolver(new EntityResolver() {

        @Override//from w w  w . j  a va2s  .c  om
        public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {

            if (systemId.equals("http://doc.openwga.com/hdb-model-definition-6.0.dtd")) {
                return new InputSource(ModelDefinition.class.getClassLoader().getResourceAsStream(
                        WGUtils.getPackagePath(ModelDefinition.class) + "/hdb-model-definition-6.0.dtd"));
            } else {
                // use the default behaviour
                return null;
            }

        }

    });

    org.dom4j.Document domDoc = reader.read(in);

    // Remove doctype (we already have validated) and provide the resulting XML to the serializer
    domDoc.setDocType(null);
    StringWriter out = new StringWriter();
    XMLWriter writer = new XMLWriter(out);
    writer.write(domDoc);
    String xml = out.toString();

    return _serializer.read(ModelDefinition.class, new StringReader(xml));
}

From source file:de.innovationgate.wgpublisher.WebTMLDebugger.java

License:Open Source License

/**
 * @param request/*from   w ww  .  j ava  2s  . c o  m*/
 * @param response
 * @param session
 * @throws HttpErrorException
 * @throws IOException
 */
private void sendDebugDoc(HttpServletRequest request, HttpServletResponse response, HttpSession session)
        throws HttpErrorException, IOException {
    String urlStr = request.getParameter("url");
    String indexStr = request.getParameter("index");

    if (urlStr != null) {
        urlStr = _dispatcher.getCore().getURLEncoder().decode(urlStr);
        List<Document> debugDocuments = WGACore.getDebugDocumentsList(session);
        Document debugDoc;
        for (int idx = 0; idx < debugDocuments.size(); idx++) {
            debugDoc = (Document) debugDocuments.get(idx);
            if (debugDoc.getRootElement().attributeValue("url", "").equals(urlStr)) {
                indexStr = String.valueOf(idx);
                break;
            }
        }
    }

    if (indexStr != null) {
        int index = Integer.valueOf(indexStr).intValue();
        List<Document> debugDocuments = WGACore.getDebugDocumentsList(session);
        if (index == -1) {
            index = debugDocuments.size() - 1;
        }
        if (index >= debugDocuments.size()) {
            throw new HttpErrorException(HttpServletResponse.SC_BAD_REQUEST,
                    "Index out of range: " + index + " where maximum index is " + (debugDocuments.size() - 1),
                    null);
        } else {
            Document doc = (Document) debugDocuments.get(index);
            response.setContentType("text/xml");
            XMLWriter writer = new XMLWriter(response.getWriter());
            writer.write(doc);
        }
    } else {
        throw new HttpErrorException(HttpServletResponse.SC_BAD_REQUEST,
                "You must include either parameter index or url to address the debug document to show", null);
    }
}

From source file:de.juwimm.cms.beans.TizzitRestAPIController.java

License:Apache License

@RequestMapping(value = "/contentparsed/{vcId}/{getPUBLSVersion}", method = RequestMethod.GET)
@ResponseBody/*  w w w . ja  va  2  s.  co m*/
public String getContentParsed(@PathVariable int vcId, @PathVariable boolean getPUBLSVersion) {
    if (log.isDebugEnabled())
        log.debug("/contentparsed/" + vcId);
    String sb = null;
    try {
        sb = webSpringBean.getContent(vcId, getPUBLSVersion);
    } catch (Exception e) {
        log.warn("Error calling getContent on webservicespring");
    }

    StringWriter sw = new StringWriter();
    if (sb != null) {
        try {
            XMLReader parser = XMLReaderFactory.createXMLReader();
            XMLWriter xw = new XMLWriter(sw);
            PluginManagement pm = new PluginManagement();
            BaseContentHandler transformer = new BaseContentHandler(pm, xw, webSpringBean, vcId,
                    getPUBLSVersion);

            parser.setContentHandler(transformer);

            InputStream stream = new ByteArrayInputStream(sb.getBytes());
            InputSource inputSource = new InputSource(stream);

            long parseTime = System.currentTimeMillis();

            parser.parse(inputSource);
            parseTime = System.currentTimeMillis() - parseTime;
            log.debug("Parse time: " + parseTime + "ms");
        } catch (SAXException saxe) {
            log.warn("Error while parsing content of: " + vcId, saxe);
        } catch (IOException ioe) {
            log.warn("Error while parsing content of: " + vcId, ioe);
        }
    }
    return sw.toString().substring(38);
}

From source file:de.tu_berlin.cit.rwx4j.xmpp.whack.ExternalComponent.java

License:Open Source License

/**
 * Generates a connection with the server and tries to authenticate. If an error occurs in any
 * of the steps then a ComponentException is thrown.
 *
 * @param host          the host to connect with.
 * @param port          the port to use.
 * @param subdomain     the subdomain that this component will be handling.
 * @throws ComponentException if an error happens during the connection and authentication steps.
 *//*  w  w w . j ava2s  . c o m*/
public void connect(String host, int port, String subdomain) throws ComponentException {
    try {
        // Open a socket to the server
        this.socket = new Socket();
        socket.connect(new InetSocketAddress(host, port), manager.getConnectTimeout());
        if (manager.getServerName() != null) {
            this.domain = subdomain + "." + manager.getServerName();
        } else {
            this.domain = subdomain;
        }
        this.subdomain = subdomain;
        // Keep these variables that will be used in case a reconnection is required
        this.host = host;
        this.port = port;

        try {
            factory = XmlPullParserFactory.newInstance();
            reader = new XPPPacketReader();
            reader.setXPPFactory(factory);

            reader.getXPPParser().setInput(new InputStreamReader(socket.getInputStream(), CHARSET));

            // Get a writer for sending the open stream tag
            writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), CHARSET));
            // Open the stream.
            StringBuilder stream = new StringBuilder();
            stream.append("<stream:stream");
            stream.append(" xmlns=\"jabber:component:accept\"");
            stream.append(" xmlns:stream=\"http://etherx.jabber.org/streams\"");
            if (manager.isMultipleAllowed(subdomain)) {
                stream.append(" allowMultiple=\"true\"");
            }
            stream.append(" to=\"").append(domain).append("\">");
            writer.write(stream.toString());
            writer.flush();
            stream = null;

            // Get the answer from the server
            XmlPullParser xpp = reader.getXPPParser();
            for (int eventType = xpp.getEventType(); eventType != XmlPullParser.START_TAG;) {
                eventType = xpp.next();
            }

            // Set the streamID returned from the server
            connectionID = xpp.getAttributeValue("", "id");
            if (xpp.getAttributeValue("", "from") != null) {
                this.domain = xpp.getAttributeValue("", "from");
            }
            xmlSerializer = new XMLWriter(writer);

            // Handshake with the server
            stream = new StringBuilder();
            stream.append("<handshake>");
            stream.append(StringUtils.hash(connectionID + manager.getSecretKey(subdomain)));
            stream.append("</handshake>");
            writer.write(stream.toString());
            writer.flush();
            stream = null;

            // Get the answer from the server
            try {
                Element doc = reader.parseDocument().getRootElement();
                if ("error".equals(doc.getName())) {
                    StreamError error = new StreamError(doc);
                    // Close the connection
                    socket.close();
                    socket = null;
                    // throw the exception with the wrapped error
                    throw new ComponentException(error);
                }
                // Everything went fine
                // Start keep alive thread to send every 30 seconds of inactivity a heart beat
                keepAliveTask = new KeepAliveTask();
                TaskEngine.getInstance().scheduleAtFixedRate(keepAliveTask, 15000, 30000);

                timeoutTask = new TimeoutTask();
                TaskEngine.getInstance().scheduleAtFixedRate(timeoutTask, 2000, 2000);

            } catch (DocumentException e) {
                try {
                    socket.close();
                } catch (IOException ioe) {
                    // Do nothing
                }
                throw new ComponentException(e);
            } catch (XmlPullParserException e) {
                try {
                    socket.close();
                } catch (IOException ioe) {
                    // Do nothing
                }
                throw new ComponentException(e);
            }
        } catch (XmlPullParserException e) {
            try {
                socket.close();
            } catch (IOException ioe) {
                // Do nothing
            }
            throw new ComponentException(e);
        }
    } catch (UnknownHostException uhe) {
        try {
            if (socket != null)
                socket.close();
        } catch (IOException e) {
            // Do nothing
        }
        throw new ComponentException(uhe);
    } catch (IOException ioe) {
        try {
            if (socket != null)
                socket.close();
        } catch (IOException e) {
            // Do nothing
        }
        throw new ComponentException(ioe);
    }
}

From source file:dk.netarkivet.harvester.datamodel.H1HeritrixTemplate.java

License:Open Source License

@Override
public void writeTemplate(OutputStream os) throws IOException, ArgumentNotValid {
    XMLWriter writer;/*w w w .ja va 2 s .  c om*/
    try {
        writer = new XMLWriter(os);
        writer.write(this.template);
    } catch (UnsupportedEncodingException e) {
        String errMsg = "The encoding of this template is unsupported by this environment";
        log.error(errMsg, e);
        throw new ArgumentNotValid(errMsg, e);
    }
}