WebManager.java 12.8 KB
Newer Older
1 2 3 4 5
/**
 * $RCSfile$
 * $Revision$
 * $Date$
 *
6
 * Copyright (C) 2004-2008 Jive Software. All rights reserved.
7
 *
8 9 10 11 12 13 14 15 16 17 18
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
19 20
 */

Matt Tucker's avatar
Matt Tucker committed
21 22
package org.jivesoftware.util;

23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;

import org.jivesoftware.openfire.PresenceManager;
import org.jivesoftware.openfire.PrivateStorage;
import org.jivesoftware.openfire.SessionManager;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.XMPPServerInfo;
38 39
import org.jivesoftware.openfire.auth.AuthToken;
import org.jivesoftware.openfire.group.GroupManager;
40
import org.jivesoftware.openfire.lockout.LockOutManager;
41
import org.jivesoftware.openfire.muc.MultiUserChatManager;
42
import org.jivesoftware.openfire.roster.RosterManager;
43
import org.jivesoftware.openfire.security.SecurityAuditManager;
44 45
import org.jivesoftware.openfire.user.User;
import org.jivesoftware.openfire.user.UserManager;
46
import org.jivesoftware.util.cache.Cache;
47
import org.jivesoftware.util.cache.CacheFactory;
48 49
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Matt Tucker's avatar
Matt Tucker committed
50

51
/**
52
 * A utility bean for Openfire admin console pages.
53
 */
Matt Tucker's avatar
Matt Tucker committed
54
public class WebManager extends WebBean {
55

56 57
	private static final Logger Log = LoggerFactory.getLogger(WebManager.class);

Matt Tucker's avatar
Matt Tucker committed
58 59 60 61 62 63
    private int start = 0;
    private int range = 15;

    public WebManager() {
    }

64 65 66
    /**
     * Returns the auth token redirects to the login page if an auth token is not found.
     */
Matt Tucker's avatar
Matt Tucker committed
67
    public AuthToken getAuthToken() {
68
        return (AuthToken)session.getAttribute("jive.admin.authToken");
Matt Tucker's avatar
Matt Tucker committed
69 70
    }

71
    /**
72
     * Returns <tt>true</tt> if the Openfire container is in setup mode, <tt>false</tt> otherwise.
73
     */
Matt Tucker's avatar
Matt Tucker committed
74
    public boolean isSetupMode() {
75
        return getXMPPServer().isSetupMode();
Matt Tucker's avatar
Matt Tucker committed
76 77
    }

78 79 80
    /**
     * Returns the XMPP server object -- can get many config items from here.
     */
Matt Tucker's avatar
Matt Tucker committed
81
    public XMPPServer getXMPPServer() {
82
        final XMPPServer xmppServer = XMPPServer.getInstance();
Matt Tucker's avatar
Matt Tucker committed
83 84 85 86 87 88 89 90 91
        if (xmppServer == null) {
            // Show that the server is down
            showServerDown();
            return null;
        }
        return xmppServer;
    }

    public UserManager getUserManager() {
92
        return getXMPPServer().getUserManager();
93 94
    }

Matt Tucker's avatar
Matt Tucker committed
95 96 97 98
    public GroupManager getGroupManager() {
        return GroupManager.getInstance();
    }

99 100 101 102
    public LockOutManager getLockOutManager() {
        return LockOutManager.getInstance();
    }

103 104 105 106
    public SecurityAuditManager getSecurityAuditManager() {
        return SecurityAuditManager.getInstance();
    }

107
    public RosterManager getRosterManager() {
108
        return getXMPPServer().getRosterManager();
Matt Tucker's avatar
Matt Tucker committed
109 110
    }

111
    public PrivateStorage getPrivateStore() {
112
        return getXMPPServer().getPrivateStorage();
Matt Tucker's avatar
Matt Tucker committed
113 114 115
    }

    public PresenceManager getPresenceManager() {
116
        return getXMPPServer().getPresenceManager();
Matt Tucker's avatar
Matt Tucker committed
117 118 119
    }

    public SessionManager getSessionManager() {
120
        return getXMPPServer().getSessionManager();
Matt Tucker's avatar
Matt Tucker committed
121 122
    }

123 124
    public MultiUserChatManager getMultiUserChatManager() {
        return getXMPPServer().getMultiUserChatManager();
Matt Tucker's avatar
Matt Tucker committed
125 126 127 128 129 130
    }

    public XMPPServerInfo getServerInfo() {
        return getXMPPServer().getServerInfo();
    }

131 132 133 134 135 136 137 138 139 140
    /**
     * Logs a security event as the currently logged in user.  (convenience routine for SecurityAuditManager)
     *
     * @param summary Summary of event.
     * @param details Details of event, can be null if no details available.
     */
    public void logEvent(String summary, String details) {
        SecurityAuditManager.getInstance().logEvent(getUser().getUsername(), summary, details);
    }

141 142 143
    /**
     * Returns the page user or <tt>null</tt> if one is not found.
     */
Matt Tucker's avatar
Matt Tucker committed
144 145 146
    public User getUser() {
        User pageUser = null;
        try {
147
            pageUser = getUserManager().getUser(getAuthToken().getUsername());
Matt Tucker's avatar
Matt Tucker committed
148
        }
149 150 151
        catch (Exception ignored) {
            // Ignore.
        }
Matt Tucker's avatar
Matt Tucker committed
152 153 154
        return pageUser;
    }

155 156 157
    /**
     * Returns <tt>true</tt> if the server is in embedded mode, <tt>false</tt> otherwise.
     */
Matt Tucker's avatar
Matt Tucker committed
158 159
    public boolean isEmbedded() {
        try {
160
            ClassUtils.forName("org.jivesoftware.openfire.starter.ServerStarter");
Matt Tucker's avatar
Matt Tucker committed
161 162 163 164 165 166 167
            return true;
        }
        catch (Exception ignored) {
            return false;
        }
    }

168
    /**
169
     * Restarts the server then sleeps for 3 seconds.
170
     */
171
    public void restart() {
Matt Tucker's avatar
Matt Tucker committed
172
        try {
173
            getXMPPServer().restart();
Matt Tucker's avatar
Matt Tucker committed
174 175
        }
        catch (Exception e) {
176
            Log.error(e.getMessage(), e);
Matt Tucker's avatar
Matt Tucker committed
177 178
        }
        sleep();
179
    }
Matt Tucker's avatar
Matt Tucker committed
180

181
    /**
182
     * Stops the server then sleeps for 3 seconds.
183
     */
184
    public void stop() {
Matt Tucker's avatar
Matt Tucker committed
185
        try {
186
            getXMPPServer().stop();
Matt Tucker's avatar
Matt Tucker committed
187 188
        }
        catch (Exception e) {
189
            Log.error(e.getMessage(), e);
Matt Tucker's avatar
Matt Tucker committed
190 191
        }
        sleep();
192
    }
Matt Tucker's avatar
Matt Tucker committed
193 194 195 196 197 198 199 200 201 202 203 204 205

    public WebManager getManager() {
        return this;
    }

    public void validateService() {
        if (getPresenceManager() == null ||
                getXMPPServer() == null) {
            showServerDown();
        }
    }

    public boolean isServerRunning() {
206
        return !(getPresenceManager() == null || getXMPPServer() == null);
Matt Tucker's avatar
Matt Tucker committed
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
    }

    public void setStart(int start) {
        this.start = start;
    }

    public int getStart() {
        return start;
    }

    public void setRange(int range) {
        this.range = range;
    }

    public int getRange() {
        return range;
    }

    public int getCurrentPage() {
        return (start / range) + 1;
    }

229 230 231 232 233 234
    private void sleep() {
        // Sleep for a minute:
        try {
            Thread.sleep(3000L);
        }
        catch (Exception ignored) {
235
            // Ignore.
236 237 238
        }
    }

Derek DeMoro's avatar
Derek DeMoro committed
239
    protected void showServerDown() {
240 241 242 243 244 245 246
        try {
            response.sendRedirect("error-serverdown.jsp");
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
    }
247 248

    /**
249 250 251 252 253 254 255 256 257 258 259 260
     * Copies the contents at <CODE>src</CODE> to <CODE>dst</CODE>.
     */
    public static void copy(URL src, File dst) throws IOException {
        InputStream in = null;
        OutputStream out = null;
        try {
            in = src.openStream();
            out = new FileOutputStream(dst);
            dst.mkdirs();
            copy(in, out);
        }
        finally {
261
            try {
262 263
                if (in != null) {
                    in.close();
264
                }
265
            }
266 267 268
            catch (IOException e) {
                // Ignore.
            }
269 270 271
            try {
                if (out != null) {
                    out.close();
272 273
                }
            }
274 275 276
            catch (IOException e) {
                // Ignore.
            }
277
        }
278
    }
279

280 281 282 283 284 285 286 287 288 289 290
    /**
     * Common code for copy routines.  By convention, the streams are
     * closed in the same method in which they were opened.  Thus,
     * this method does not close the streams when the copying is done.
     */
    private static void copy(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[4096];
        while (true) {
            int bytesRead = in.read(buffer);
            if (bytesRead < 0) {
                break;
291
            }
292
            out.write(buffer, 0, bytesRead);
293
        }
294
    }
295 296 297 298 299 300 301 302 303 304 305

    /**
     * Returns the number of rows per page for the specified page for the current logged user.
     * The rows per page value is stored as a user property. The same property is being used for
     * different pages. The encoding format is the following "pageName1=value,pageName2=value".
     *
     * @param pageName     the name of the page to look up its stored value.
     * @param defaultValue the default value to return if no user value was found.
     * @return the number of rows per page for the specified page for the current logged user.
     */
    public int getRowsPerPage(String pageName, int defaultValue) {
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
        return getPageProperty(pageName, "console.rows_per_page", defaultValue);
    }

    /**
     * Sets the new number of rows per page for the specified page for the current logged user.
     * The rows per page value is stored as a user property. The same property is being used for
     * different pages. The encoding format is the following "pageName1=value,pageName2=value".
     *
     * @param pageName the name of the page to stored its new value.
     * @param newValue the new rows per page value.
     */
    public void setRowsPerPage(String pageName, int newValue) {
        setPageProperty(pageName, "console.rows_per_page", newValue);
    }

    /**
     * Returns the number of seconds between each page refresh for the specified page for the
     * current logged user. The value is stored as a user property. The same property is being
     * used for different pages. The encoding format is the following
     * "pageName1=value,pageName2=value".
     *
     * @param pageName     the name of the page to look up its stored value.
     * @param defaultValue the default value to return if no user value was found.
     * @return the number of seconds between each page refresh for the specified page for
     *         the current logged user.
     */
    public int getRefreshValue(String pageName, int defaultValue) {
        return getPageProperty(pageName, "console.refresh", defaultValue);
    }

    /**
     * Sets the number of seconds between each page refresh for the specified page for the
     * current logged user. The value is stored as a user property. The same property is being
     * used for different pages. The encoding format is the following
     * "pageName1=value,pageName2=value".
     *
     * @param pageName the name of the page to stored its new value.
     * @param newValue the new number of seconds between each page refresh.
     */
    public void setRefreshValue(String pageName, int newValue) {
        setPageProperty(pageName, "console.refresh", newValue);
    }

349
    public int getPageProperty(String pageName, String property, int defaultValue) {
350 351
        User user = getUser();
        if (user != null) {
352
            String values = user.getProperties().get(property);
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
            if (values != null) {
                StringTokenizer tokens = new StringTokenizer(values, ",=");
                while (tokens.hasMoreTokens()) {
                    String page = tokens.nextToken().trim();
                    String rows = tokens.nextToken().trim();
                    if  (pageName.equals(page)) {
                        try {
                            return Integer.parseInt(rows);
                        }
                        catch (NumberFormatException e) {
                            return defaultValue;
                        }
                    }
                }
            }
        }
        return defaultValue;
    }

372
    public void setPageProperty(String pageName, String property, int newValue) {
373 374 375
        String toStore = pageName + "=" + newValue;
        User user = getUser();
        if (user != null) {
376
            String values = user.getProperties().get(property);
377 378 379 380 381 382 383 384
            if (values != null) {
                if (values.contains(toStore)) {
                    // The new value for the page was already stored so do nothing
                    return;
                }
                else {
                    if (values.contains(pageName)) {
                        // Replace an old value for the page with the new value
385
                        int oldValue = getPageProperty(pageName, property, -1);
386
                        String toRemove = pageName + "=" + oldValue;
387
                        user.getProperties().put(property, values.replace(toRemove, toStore));
388 389 390
                    }
                    else {
                        // Append the new page-value
391
                        user.getProperties().put(property, values + "," + toStore);
392 393 394
                    }
                }
            }
395
            else {
396
                // Store the new page-value as a new user property
397
                user.getProperties().put(property, toStore);
398 399 400
            }
        }
    }
401 402

    public Cache[] getCaches() {
403 404 405
        Cache[] caches =CacheFactory.getAllCaches();
        Arrays.sort(caches, new Comparator<Cache>() {
            public int compare(Cache cache1, Cache cache2) {
406 407 408
                return cache1.getName().toLowerCase().compareTo(cache2.getName().toLowerCase());
            }
        });
409
        return caches;
410
    }
Matt Tucker's avatar
Matt Tucker committed
411
}