Search in sources :

Example 21 with DocumentException

use of org.dom4j.DocumentException in project Openfire by igniterealtime.

the class OfflineMessageStore method getMessages.

/**
     * Returns a Collection of all messages in the store for a user.
     * Messages may be deleted after being selected from the database depending on
     * the delete param.
     *
     * @param username the username of the user who's messages you'd like to receive.
     * @param delete true if the offline messages should be deleted.
     * @return An iterator of packets containing all offline messages.
     */
public Collection<OfflineMessage> getMessages(String username, boolean delete) {
    List<OfflineMessage> messages = new ArrayList<>();
    SAXReader xmlReader = null;
    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        // Get a sax reader from the pool
        xmlReader = xmlReaders.take();
        con = DbConnectionManager.getConnection();
        pstmt = con.prepareStatement(LOAD_OFFLINE);
        pstmt.setString(1, username);
        rs = pstmt.executeQuery();
        while (rs.next()) {
            String msgXML = rs.getString(1);
            Date creationDate = new Date(Long.parseLong(rs.getString(2).trim()));
            OfflineMessage message;
            try {
                message = new OfflineMessage(creationDate, xmlReader.read(new StringReader(msgXML)).getRootElement());
            } catch (DocumentException e) {
                // Try again after removing invalid XML chars (e.g. &#12;)
                Matcher matcher = pattern.matcher(msgXML);
                if (matcher.find()) {
                    msgXML = matcher.replaceAll("");
                }
                try {
                    message = new OfflineMessage(creationDate, xmlReader.read(new StringReader(msgXML)).getRootElement());
                } catch (DocumentException de) {
                    Log.error("Failed to route packet (offline message): " + msgXML, de);
                    // skip and process remaining offline messages
                    continue;
                }
            }
            // if there is already a delay stamp, we shouldn't add another.
            Element delaytest = message.getChildElement("delay", "urn:xmpp:delay");
            if (delaytest == null) {
                // Add a delayed delivery (XEP-0203) element to the message.
                Element delay = message.addChildElement("delay", "urn:xmpp:delay");
                delay.addAttribute("from", XMPPServer.getInstance().getServerInfo().getXMPPDomain());
                delay.addAttribute("stamp", XMPPDateTimeFormat.format(creationDate));
            }
            messages.add(message);
        }
        // messages to delete.
        if (delete && !messages.isEmpty()) {
            PreparedStatement pstmt2 = null;
            try {
                pstmt2 = con.prepareStatement(DELETE_OFFLINE);
                pstmt2.setString(1, username);
                pstmt2.executeUpdate();
                removeUsernameFromSizeCache(username);
            } catch (Exception e) {
                Log.error("Error deleting offline messages of username: " + username, e);
            } finally {
                DbConnectionManager.closeStatement(pstmt2);
            }
        }
    } catch (Exception e) {
        Log.error("Error retrieving offline messages of username: " + username, e);
    } finally {
        DbConnectionManager.closeConnection(rs, pstmt, con);
        // Return the sax reader to the pool
        if (xmlReader != null) {
            xmlReaders.add(xmlReader);
        }
    }
    return messages;
}
Also used : Matcher(java.util.regex.Matcher) SAXReader(org.dom4j.io.SAXReader) Element(org.dom4j.Element) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) DocumentException(org.dom4j.DocumentException) DocumentException(org.dom4j.DocumentException) ResultSet(java.sql.ResultSet) StringReader(java.io.StringReader)

Example 22 with DocumentException

use of org.dom4j.DocumentException in project hibernate-orm by hibernate.

the class TestDataReader method read.

public List<TestDataElement> read(String fileName) {
    if (fileName == null) {
        throw new RuntimeException("Null testsuite-suite data file specified.");
    }
    List<TestDataElement> testDataElements = new ArrayList<TestDataElement>();
    SAXReader reader = new SAXReader();
    try {
        Document document = reader.read(getInputStream(fileName));
        addDataElements(document, testDataElements);
    } catch (DocumentException e) {
        throw new RuntimeException(e);
    }
    return testDataElements;
}
Also used : SAXReader(org.dom4j.io.SAXReader) DocumentException(org.dom4j.DocumentException) ArrayList(java.util.ArrayList) Document(org.dom4j.Document)

Example 23 with DocumentException

use of org.dom4j.DocumentException in project hudson-2.x by hudson.

the class ManagedWindowsServiceLauncher method launch.

@Override
public void launch(final SlaveComputer computer, final TaskListener listener) throws IOException, InterruptedException {
    try {
        final PrintStream logger = listener.getLogger();
        final String name = determineHost(computer);
        logger.println(Messages.ManagedWindowsServiceLauncher_ConnectingTo(name));
        InetAddress host = InetAddress.getByName(name);
        try {
            Socket s = new Socket();
            s.connect(new InetSocketAddress(host, 135), 5000);
            s.close();
        } catch (IOException e) {
            logger.println("Failed to connect to port 135 of " + name + ". Is Windows firewall blocking this port? Or did you disable DCOM service?");
        // again, let it continue.
        }
        JIDefaultAuthInfoImpl auth = createAuth();
        JISession session = JISession.createSession(auth);
        session.setGlobalSocketTimeout(60000);
        SWbemServices services = WMI.connect(session, name);
        String path = computer.getNode().getRemoteFS();
        if (path.indexOf(':') == -1)
            throw new IOException("Remote file system root path of the slave needs to be absolute: " + path);
        SmbFile remoteRoot = new SmbFile("smb://" + name + "/" + path.replace('\\', '/').replace(':', '$') + "/", createSmbAuth());
        if (!remoteRoot.exists())
            remoteRoot.mkdirs();
        try {
            // does Java exist?
            logger.println("Checking if Java exists");
            WindowsRemoteProcessLauncher wrpl = new WindowsRemoteProcessLauncher(name, auth);
            Process proc = wrpl.launch("java -fullversion", "c:\\");
            proc.getOutputStream().close();
            IOUtils.copy(proc.getInputStream(), logger);
            proc.getInputStream().close();
            int exitCode = proc.waitFor();
            if (exitCode == 1) {
                // we'll get this error code if Java is not found
                //TODO enable me when JDK installer based on REST API will be ready
                logger.println("No JDK found on slave node. Please install JDK");
                throw new InterruptedException("No JDK found on slave node. Please install JDK");
            //                    logger.println("No Java found. Downloading JDK");
            //                    JDKInstaller jdki = new JDKInstaller("jdk-6u16-oth-JPR@CDS-CDS_Developer",true);
            //                    URL jdk = jdki.locate(listener, Platform.WINDOWS, CPU.i386);
            //
            //                    listener.getLogger().println("Installing JDK");
            //                    copyStreamAndClose(jdk.openStream(), new SmbFile(remoteRoot, "jdk.exe").getOutputStream());
            //
            //                    String javaDir = path + "\\jdk"; // this is where we install Java to
            //
            //                    WindowsRemoteFileSystem fs = new WindowsRemoteFileSystem(name, createSmbAuth());
            //                    fs.mkdirs(javaDir);
            //
            //                    jdki.install(new WindowsRemoteLauncher(listener,wrpl), Platform.WINDOWS,
            //                            fs, listener, javaDir ,path+"\\jdk.exe");
            }
        } catch (Exception e) {
            e.printStackTrace(listener.error("Failed to prepare Java"));
        }
        String id = WindowsSlaveInstaller.generateServiceId(path);
        Win32Service slaveService = services.getService(id);
        if (slaveService == null) {
            logger.println(Messages.ManagedWindowsServiceLauncher_InstallingSlaveService());
            if (!DotNet.isInstalled(2, 0, name, auth)) {
                // abort the launch
                logger.println(Messages.ManagedWindowsServiceLauncher_DotNetRequired());
                return;
            }
            // copy exe
            logger.println(Messages.ManagedWindowsServiceLauncher_CopyingSlaveExe());
            copyStreamAndClose(getClass().getResource("/windows-service/hudson.exe").openStream(), new SmbFile(remoteRoot, "hudson-slave.exe").getOutputStream());
            copySlaveJar(logger, remoteRoot);
            // copy hudson-slave.xml
            logger.println(Messages.ManagedWindowsServiceLauncher_CopyingSlaveXml());
            String xml = WindowsSlaveInstaller.generateSlaveXml(id, "javaw.exe", "-tcp %BASE%\\port.txt");
            copyStreamAndClose(new ByteArrayInputStream(xml.getBytes("UTF-8")), new SmbFile(remoteRoot, "hudson-slave.xml").getOutputStream());
            // install it as a service
            logger.println(Messages.ManagedWindowsServiceLauncher_RegisteringService());
            Document dom = new SAXReader().read(new StringReader(xml));
            Win32Service svc = services.Get("Win32_Service").cast(Win32Service.class);
            int r = svc.Create(id, dom.selectSingleNode("/service/name").getText() + " at " + path, path + "\\hudson-slave.exe", Win32OwnProcess, 0, "Manual", true);
            if (r != 0) {
                listener.error("Failed to create a service: " + svc.getErrorMessage(r));
                return;
            }
            slaveService = services.getService(id);
        } else {
            copySlaveJar(logger, remoteRoot);
        }
        logger.println(Messages.ManagedWindowsServiceLauncher_StartingService());
        slaveService.start();
        // wait until we see the port.txt, but don't do so forever
        logger.println(Messages.ManagedWindowsServiceLauncher_WaitingForService());
        SmbFile portFile = new SmbFile(remoteRoot, "port.txt");
        for (int i = 0; !portFile.exists(); i++) {
            if (i >= 30) {
                listener.error(Messages.ManagedWindowsServiceLauncher_ServiceDidntRespond());
                return;
            }
            Thread.sleep(1000);
        }
        int p = readSmbFile(portFile);
        // connect
        logger.println(Messages.ManagedWindowsServiceLauncher_ConnectingToPort(p));
        final Socket s = new Socket(name, p);
        // ready
        computer.setChannel(new BufferedInputStream(new SocketInputStream(s)), new BufferedOutputStream(new SocketOutputStream(s)), listener.getLogger(), new Listener() {

            @Override
            public void onClosed(Channel channel, IOException cause) {
                afterDisconnect(computer, listener);
            }
        });
    } catch (SmbException e) {
        e.printStackTrace(listener.error(e.getMessage()));
    } catch (JIException e) {
        if (e.getErrorCode() == 5)
            // access denied error
            e.printStackTrace(listener.error(Messages.ManagedWindowsServiceLauncher_AccessDenied()));
        else
            e.printStackTrace(listener.error(e.getMessage()));
    } catch (DocumentException e) {
        e.printStackTrace(listener.error(e.getMessage()));
    }
}
Also used : Listener(hudson.remoting.Channel.Listener) TaskListener(hudson.model.TaskListener) InetSocketAddress(java.net.InetSocketAddress) SAXReader(org.dom4j.io.SAXReader) Win32OwnProcess(org.jvnet.hudson.wmi.Win32Service.Win32OwnProcess) Document(org.dom4j.Document) Win32Service(org.jvnet.hudson.wmi.Win32Service) SmbException(jcifs.smb.SmbException) JISession(org.jinterop.dcom.core.JISession) BufferedInputStream(java.io.BufferedInputStream) DocumentException(org.dom4j.DocumentException) StringReader(java.io.StringReader) BufferedOutputStream(java.io.BufferedOutputStream) JIException(org.jinterop.dcom.common.JIException) PrintStream(java.io.PrintStream) SocketOutputStream(hudson.remoting.SocketOutputStream) JIDefaultAuthInfoImpl(org.jinterop.dcom.common.JIDefaultAuthInfoImpl) Channel(hudson.remoting.Channel) IOException(java.io.IOException) SocketInputStream(hudson.remoting.SocketInputStream) WindowsRemoteProcessLauncher(org.jvnet.hudson.remcom.WindowsRemoteProcessLauncher) SmbException(jcifs.smb.SmbException) DocumentException(org.dom4j.DocumentException) JIException(org.jinterop.dcom.common.JIException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) SmbFile(jcifs.smb.SmbFile) ByteArrayInputStream(java.io.ByteArrayInputStream) SWbemServices(org.jvnet.hudson.wmi.SWbemServices) InetAddress(java.net.InetAddress) Socket(java.net.Socket)

Example 24 with DocumentException

use of org.dom4j.DocumentException in project Openfire by igniterealtime.

the class ServerDialback method sendVerifyKey.

private VerifyResult sendVerifyKey(String key, StreamID streamID, String recipient, String remoteDomain, Writer writer, XMPPPacketReader reader, Socket socket, boolean skipTLS) throws IOException, XmlPullParserException, RemoteConnectionFailedException {
    final Logger log = LoggerFactory.getLogger(Log.getName() + "[Acting as Receiving Server: Verify key with AS: " + remoteDomain + " for OS: " + recipient + " (id " + streamID + ")]");
    VerifyResult result = VerifyResult.error;
    TLSStreamHandler tlsStreamHandler;
    log.debug("Send the Authoritative Server a stream header and wait for answer.");
    StringBuilder stream = new StringBuilder();
    stream.append("<stream:stream");
    stream.append(" xmlns:stream=\"http://etherx.jabber.org/streams\"");
    stream.append(" xmlns=\"jabber:server\"");
    stream.append(" xmlns:db=\"jabber:server:dialback\"");
    stream.append(" to=\"");
    stream.append(remoteDomain);
    stream.append("\"");
    stream.append(" from=\"");
    stream.append(recipient);
    stream.append("\"");
    stream.append(" version=\"1.0\">");
    writer.write(stream.toString());
    writer.flush();
    // Get the answer from the Authoritative Server
    XmlPullParser xpp = reader.getXPPParser();
    for (int eventType = xpp.getEventType(); eventType != XmlPullParser.START_TAG; ) {
        eventType = xpp.next();
    }
    // TODO there's code duplication here with LocalOutgoingServerSession.
    log.debug("Got a response.");
    if ((xpp.getAttributeValue("", "version") != null) && (xpp.getAttributeValue("", "version").equals("1.0"))) {
        log.debug("The remote server is XMPP 1.0 compliant (or at least reports to be).");
        Document doc;
        try {
            doc = reader.parseDocument();
        } catch (DocumentException e) {
            log.warn("Unable to verify key: XML Error!", e);
            return VerifyResult.error;
        }
        Element features = doc.getRootElement();
        Element starttls = features.element("starttls");
        if (!skipTLS && starttls != null) {
            writer.write("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
            writer.flush();
            try {
                doc = reader.parseDocument();
            } catch (DocumentException e) {
                log.warn("Unable to verify key: XML Error!", e);
                return VerifyResult.error;
            }
            if (!doc.getRootElement().getName().equals("proceed")) {
                log.warn("Unable to verify key: Got {} instead of proceed for starttls", doc.getRootElement().getName());
                log.debug("Like this: {}", doc.asXML());
                return VerifyResult.error;
            }
            log.debug("Negotiating TLS with AS... ");
            // Ugly hacks, apparently, copied from SocketConnection.
            final ConnectionManagerImpl connectionManager = ((ConnectionManagerImpl) XMPPServer.getInstance().getConnectionManager());
            tlsStreamHandler = new TLSStreamHandler(socket, connectionManager.getListener(ConnectionType.SOCKET_S2S, false).generateConnectionConfiguration(), true);
            // Start handshake
            tlsStreamHandler.start();
            // Use new wrapped writers
            writer = new BufferedWriter(new OutputStreamWriter(tlsStreamHandler.getOutputStream(), StandardCharsets.UTF_8));
            reader.getXPPParser().setInput(new InputStreamReader(tlsStreamHandler.getInputStream(), StandardCharsets.UTF_8));
            log.debug("Successfully negotiated TLS with AS... ");
            /// Recurses!
            return sendVerifyKey(key, streamID, recipient, remoteDomain, writer, reader, socket, skipTLS);
        }
    }
    if ("jabber:server:dialback".equals(xpp.getNamespace("db"))) {
        log.debug("Request for verification of the key and wait for response");
        StringBuilder sb = new StringBuilder();
        sb.append("<db:verify");
        sb.append(" from=\"").append(recipient).append("\"");
        sb.append(" to=\"").append(remoteDomain).append("\"");
        sb.append(" id=\"").append(streamID.getID()).append("\">");
        sb.append(key);
        sb.append("</db:verify>");
        writer.write(sb.toString());
        writer.flush();
        try {
            Element doc = reader.parseDocument().getRootElement();
            if ("db".equals(doc.getNamespacePrefix()) && "verify".equals(doc.getName())) {
                if (doc.attributeValue("id") == null || !streamID.equals(BasicStreamIDFactory.createStreamID(doc.attributeValue("id")))) {
                    // Include the invalid-id stream error condition in the response
                    writer.write(new StreamError(StreamError.Condition.invalid_id).toXML());
                    writer.flush();
                    // condition is sent to the Originating Server
                    throw new RemoteConnectionFailedException("Invalid ID");
                } else if (isHostUnknown(doc.attributeValue("to"))) {
                    // Include the host-unknown stream error condition in the response
                    writer.write(new StreamError(StreamError.Condition.host_unknown).toXML());
                    writer.flush();
                    // condition is sent to the Originating Server
                    throw new RemoteConnectionFailedException("Host unknown");
                } else if (!remoteDomain.equals(doc.attributeValue("from"))) {
                    // Include the invalid-from stream error condition in the response
                    writer.write(new StreamError(StreamError.Condition.invalid_from).toXML());
                    writer.flush();
                    // condition is sent to the Originating Server
                    throw new RemoteConnectionFailedException("Invalid From");
                } else if ("valid".equals(doc.attributeValue("type"))) {
                    log.debug("Key was VERIFIED by the Authoritative Server.");
                    result = VerifyResult.valid;
                } else if ("invalid".equals(doc.attributeValue("type"))) {
                    log.debug("Key was NOT VERIFIED by the Authoritative Server.");
                    result = VerifyResult.invalid;
                } else {
                    log.debug("Key was ERRORED by the Authoritative Server.");
                    result = VerifyResult.error;
                }
            } else {
                log.debug("db:verify answer was: " + doc.asXML());
            }
        } catch (DocumentException | RuntimeException e) {
            log.error("An error occurred while connecting to the Authoritative Server:", e);
            // sent to the Originating Server
            throw new RemoteConnectionFailedException("Error connecting to the Authoritative Server");
        }
    } else {
        // Include the invalid-namespace stream error condition in the response
        writer.write(new StreamError(StreamError.Condition.invalid_namespace).toXML());
        writer.flush();
        // sent to the Originating Server
        throw new RemoteConnectionFailedException("Invalid namespace");
    }
    return result;
}
Also used : ConnectionManagerImpl(org.jivesoftware.openfire.spi.ConnectionManagerImpl) InputStreamReader(java.io.InputStreamReader) Element(org.dom4j.Element) XmlPullParser(org.xmlpull.v1.XmlPullParser) Logger(org.slf4j.Logger) Document(org.dom4j.Document) BufferedWriter(java.io.BufferedWriter) StreamError(org.xmpp.packet.StreamError) DocumentException(org.dom4j.DocumentException) OutputStreamWriter(java.io.OutputStreamWriter)

Example 25 with DocumentException

use of org.dom4j.DocumentException in project Openfire by igniterealtime.

the class ChatTranscriptManager method formatTranscript.

/**
     * Formats a given XML Chat Transcript.
     *
     * @param transcript the XMP ChatTranscript.
     * @return the pretty-version of a transcript.
     */
public static String formatTranscript(String transcript) {
    if (transcript == null || "".equals(transcript)) {
        return "";
    }
    final SimpleDateFormat UTC_FORMAT = new SimpleDateFormat(XMPPDateTimeFormat.XMPP_DELAY_DATETIME_FORMAT);
    UTC_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
    final SimpleDateFormat formatter = new SimpleDateFormat("h:mm a");
    Document element = null;
    try {
        element = DocumentHelper.parseText(transcript);
    } catch (DocumentException e) {
        Log.error(e.getMessage(), e);
    }
    StringBuilder buf = new StringBuilder();
    String conv1 = null;
    // Add the Messages and Presences contained in the retrieved transcript element
    for (Iterator<Element> it = element.getRootElement().elementIterator(); it.hasNext(); ) {
        Element packet = it.next();
        String name = packet.getName();
        String message = "";
        String from = "";
        if ("presence".equals(name)) {
            String type = packet.attributeValue("type");
            from = new JID(packet.attributeValue("from")).getResource();
            if (type == null) {
                message = from + " has joined the room";
            } else {
                message = from + " has left the room";
            }
        } else if ("message".equals(name)) {
            from = new JID(packet.attributeValue("from")).getResource();
            message = packet.elementText("body");
            message = StringUtils.escapeHTMLTags(message);
            if (conv1 == null) {
                conv1 = from;
            }
        }
        List<Element> el = packet.elements("x");
        for (Element ele : el) {
            if ("jabber:x:delay".equals(ele.getNamespaceURI())) {
                String stamp = ele.attributeValue("stamp");
                try {
                    String formattedDate;
                    synchronized (UTC_FORMAT) {
                        Date d = UTC_FORMAT.parse(stamp);
                        formattedDate = formatter.format(d);
                    }
                    if ("presence".equals(name)) {
                        buf.append("<tr valign=\"top\"><td class=\"notification-label\" colspan=2 nowrap>[").append(formattedDate).append("] ").append(message).append("</td></tr>");
                    } else {
                        String cssClass = conv1.equals(from) ? "conversation-label1" : "conversation-label2";
                        buf.append("<tr valign=\"top\"><td width=1% class=\"" + cssClass + "\" nowrap>[").append(formattedDate).append("] ").append(from).append(":</td><td class=\"conversation-body\">").append(message).append("</td></tr>");
                    }
                } catch (ParseException e) {
                    Log.error(e.getMessage(), e);
                }
            }
        }
    }
    return buf.toString();
}
Also used : JID(org.xmpp.packet.JID) DocumentException(org.dom4j.DocumentException) Element(org.dom4j.Element) ParseException(java.text.ParseException) Document(org.dom4j.Document) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date)

Aggregations

DocumentException (org.dom4j.DocumentException)36 Document (org.dom4j.Document)20 SAXReader (org.dom4j.io.SAXReader)19 Element (org.dom4j.Element)13 IOException (java.io.IOException)8 StringReader (java.io.StringReader)8 File (java.io.File)7 ConfigException (com.zimbra.common.localconfig.ConfigException)4 ArrayList (java.util.ArrayList)4 LocalConfig (com.zimbra.common.localconfig.LocalConfig)3 ServiceException (com.zimbra.common.service.ServiceException)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3 Server (com.zimbra.cs.account.Server)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 HashMap (java.util.HashMap)2 List (java.util.List)2 XMLWriter (org.dom4j.io.XMLWriter)2 LoginCms (afip.wsaa.wsdl.LoginCms)1 NonNull (com.android.annotations.NonNull)1 DirectoryInput (com.android.build.api.transform.DirectoryInput)1