Commit 90501d8a authored by daryl herzmann's avatar daryl herzmann

Merge pull request #171 from Redor/openfire

REST API plugin version 1.0.0
parents 9c69db39 4c2804b6
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>REST API Plugin Changelog</title>
<style type="text/css">
BODY {
font-size : 100%;
}
BODY, TD, TH {
font-family : tahoma, verdana, arial, helvetica, sans-serif;
font-size : 0.8em;
}
H2 {
font-size : 10pt;
font-weight : bold;
padding-left : 1em;
}
A:hover {
text-decoration : none;
}
H1 {
font-family : tahoma, arial, helvetica, sans-serif;
font-size : 1.4em;
font-weight: bold;
border-bottom : 1px #ccc solid;
padding-bottom : 2px;
}
TT {
font-family : courier new;
font-weight : bold;
color : #060;
}
PRE {
font-family : courier new;
font-size : 100%;
}
</style>
</head>
<body>
<h1>
REST API Plugin Changelog
</h1>
<p><b>0.1.0</b> -- November 14th, 2014</p>
<ul>
<li>Initial release of REST API Plugin with possibility to manage system properties.</li>
</ul>
</body>
</html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>REST API Plugin Changelog</title>
<style type="text/css">
BODY {
font-size : 100%;
}
BODY, TD, TH {
font-family : tahoma, verdana, arial, helvetica, sans-serif;
font-size : 0.8em;
}
H2 {
font-size : 10pt;
font-weight : bold;
padding-left : 1em;
}
A:hover {
text-decoration : none;
}
H1 {
font-family : tahoma, arial, helvetica, sans-serif;
font-size : 1.4em;
font-weight: bold;
border-bottom : 1px #ccc solid;
padding-bottom : 2px;
}
TT {
font-family : courier new;
font-weight : bold;
color : #060;
}
PRE {
font-family : courier new;
font-size : 100%;
}
</style>
</head>
<body>
<h1>
REST API Plugin Changelog
</h1>
<p><b>1.0.0</b> -- February 3rd, 2015</p>
<ul>
<li>UserService plugin and MUC Service plugin are merged to the REST API plugin.</li>
<li>Extended REST API with JSON data format.</li>
</ul>
<p><b>0.1.0</b> -- November 14th, 2014</p>
<ul>
<li>Initial release of REST API Plugin with possibility to manage system properties.</li>
</ul>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<plugin>
<class>org.jivesoftware.openfire.plugin.rest.RESTServicePlugin</class>
<name>REST API</name>
<description>Allows administration over a RESTful API.</description>
<author>Roman Soldatow</author>
<version>0.1.0</version>
<date>11/14/2014</date>
<minServerVersion>3.9.0</minServerVersion>
<adminconsole>
<tab id="tab-server">
<sidebar id="sidebar-server-settings">
<item id="rest-api" name="REST API" url="rest-api.jsp"
description="Click to manage the service that allows to configure the Openfire over a RESTFul API" />
</sidebar>
</tab>
</adminconsole>
</plugin>
<?xml version="1.0" encoding="UTF-8"?>
<plugin>
<class>org.jivesoftware.openfire.plugin.rest.RESTServicePlugin</class>
<name>REST API</name>
<description>Allows administration over a RESTful API.</description>
<author>Roman Soldatow</author>
<version>1.0.0</version>
<date>02/03/2015</date>
<minServerVersion>3.9.0</minServerVersion>
<adminconsole>
<tab id="tab-server">
<sidebar id="sidebar-server-settings">
<item id="rest-api" name="REST API" url="rest-api.jsp"
description="Click to manage the service that allows to configure the Openfire over a RESTFul API" />
</sidebar>
</tab>
</adminconsole>
</plugin>
This diff is collapsed.
package org.jivesoftware.openfire.plugin.rest;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response.Status;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.admin.AdminManager;
import org.jivesoftware.openfire.auth.AuthFactory;
import org.jivesoftware.openfire.auth.ConnectionException;
import org.jivesoftware.openfire.auth.InternalUnauthenticatedException;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerRequestFilter;
/**
* The Class AuthFilter.
*/
public class AuthFilter implements ContainerRequestFilter {
/** The log. */
private static Logger LOG = LoggerFactory.getLogger(AuthFilter.class);
/** The http request. */
@Context
private HttpServletRequest httpRequest;
/** The plugin. */
private RESTServicePlugin plugin = (RESTServicePlugin) XMPPServer.getInstance().getPluginManager()
.getPlugin("restapi");
/*
* (non-Javadoc)
*
* @see
* com.sun.jersey.spi.container.ContainerRequestFilter#filter(com.sun.jersey
* .spi.container.ContainerRequest)
*/
@Override
public ContainerRequest filter(ContainerRequest containerRequest) throws WebApplicationException {
if (!plugin.isEnabled()) {
throw new WebApplicationException(Status.FORBIDDEN);
}
if (!plugin.getAllowedIPs().isEmpty()) {
// Get client's IP address
String ipAddress = httpRequest.getHeader("x-forwarded-for");
if (ipAddress == null) {
ipAddress = httpRequest.getHeader("X_FORWARDED_FOR");
if (ipAddress == null) {
ipAddress = httpRequest.getHeader("X-Forward-For");
if (ipAddress == null) {
ipAddress = httpRequest.getRemoteAddr();
}
}
}
if (!plugin.getAllowedIPs().contains(ipAddress)) {
LOG.warn("REST API rejected service to IP address: " + ipAddress);
throw new WebApplicationException(Status.UNAUTHORIZED);
}
}
// Get the authentification passed in HTTP headers parameters
String auth = containerRequest.getHeaderValue("authorization");
if (auth == null) {
throw new WebApplicationException(Status.UNAUTHORIZED);
}
// HTTP Basic Auth or Shared Secret key
if (plugin.isHttpBasicAuth()) {
String[] usernameAndPassword = BasicAuth.decode(auth);
// If username or password fail
if (usernameAndPassword == null || usernameAndPassword.length != 2) {
throw new WebApplicationException(Status.UNAUTHORIZED);
}
boolean userAdmin = AdminManager.getInstance().isUserAdmin(usernameAndPassword[0], true);
if (!userAdmin) {
throw new WebApplicationException(Status.UNAUTHORIZED);
}
try {
AuthFactory.authenticate(usernameAndPassword[0], usernameAndPassword[1]);
} catch (UnauthorizedException e) {
LOG.warn("Wrong HTTP Basic Auth authorization", e);
throw new WebApplicationException(Status.UNAUTHORIZED);
} catch (ConnectionException e) {
throw new WebApplicationException(Status.UNAUTHORIZED);
} catch (InternalUnauthenticatedException e) {
throw new WebApplicationException(Status.UNAUTHORIZED);
}
} else {
if (!auth.equals(plugin.getSecret())) {
LOG.warn("Wrong secret key authorization. Provided key: " + auth);
throw new WebApplicationException(Status.UNAUTHORIZED);
}
}
return containerRequest;
}
}
package org.jivesoftware.openfire.plugin.rest;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response.Status;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.admin.AdminManager;
import org.jivesoftware.openfire.auth.AuthFactory;
import org.jivesoftware.openfire.auth.ConnectionException;
import org.jivesoftware.openfire.auth.InternalUnauthenticatedException;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerRequestFilter;
/**
* The Class AuthFilter.
*/
public class AuthFilter implements ContainerRequestFilter {
/** The log. */
private static Logger LOG = LoggerFactory.getLogger(AuthFilter.class);
/** The http request. */
@Context
private HttpServletRequest httpRequest;
/** The plugin. */
private RESTServicePlugin plugin = (RESTServicePlugin) XMPPServer.getInstance().getPluginManager()
.getPlugin("restapi");
/*
* (non-Javadoc)
*
* @see
* com.sun.jersey.spi.container.ContainerRequestFilter#filter(com.sun.jersey
* .spi.container.ContainerRequest)
*/
@Override
public ContainerRequest filter(ContainerRequest containerRequest) throws WebApplicationException {
if (!plugin.isEnabled()) {
throw new WebApplicationException(Status.FORBIDDEN);
}
// To be backwards compatible to userservice 1.*
if ("restapi/v1/userservice".equals(containerRequest.getPath())) {
return containerRequest;
}
if (!plugin.getAllowedIPs().isEmpty()) {
// Get client's IP address
String ipAddress = httpRequest.getHeader("x-forwarded-for");
if (ipAddress == null) {
ipAddress = httpRequest.getHeader("X_FORWARDED_FOR");
if (ipAddress == null) {
ipAddress = httpRequest.getHeader("X-Forward-For");
if (ipAddress == null) {
ipAddress = httpRequest.getRemoteAddr();
}
}
}
if (!plugin.getAllowedIPs().contains(ipAddress)) {
LOG.warn("REST API rejected service to IP address: " + ipAddress);
throw new WebApplicationException(Status.UNAUTHORIZED);
}
}
// Get the authentification passed in HTTP headers parameters
String auth = containerRequest.getHeaderValue("authorization");
if (auth == null) {
throw new WebApplicationException(Status.UNAUTHORIZED);
}
// HTTP Basic Auth or Shared Secret key
if (plugin.isHttpBasicAuth()) {
String[] usernameAndPassword = BasicAuth.decode(auth);
// If username or password fail
if (usernameAndPassword == null || usernameAndPassword.length != 2) {
throw new WebApplicationException(Status.UNAUTHORIZED);
}
boolean userAdmin = AdminManager.getInstance().isUserAdmin(usernameAndPassword[0], true);
if (!userAdmin) {
throw new WebApplicationException(Status.UNAUTHORIZED);
}
try {
AuthFactory.authenticate(usernameAndPassword[0], usernameAndPassword[1]);
} catch (UnauthorizedException e) {
LOG.warn("Wrong HTTP Basic Auth authorization", e);
throw new WebApplicationException(Status.UNAUTHORIZED);
} catch (ConnectionException e) {
throw new WebApplicationException(Status.UNAUTHORIZED);
} catch (InternalUnauthenticatedException e) {
throw new WebApplicationException(Status.UNAUTHORIZED);
}
} else {
if (!auth.equals(plugin.getSecret())) {
LOG.warn("Wrong secret key authorization. Provided key: " + auth);
throw new WebApplicationException(Status.UNAUTHORIZED);
}
}
return containerRequest;
}
}
package org.jivesoftware.openfire.plugin.rest.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.Response;
import org.jivesoftware.database.DbConnectionManager;
import org.jivesoftware.openfire.plugin.rest.exceptions.ExceptionType;
import org.jivesoftware.openfire.plugin.rest.exceptions.ServiceException;
/**
* The Class PropertyDAO.
*/
public class PropertyDAO {
/** The Constant LOAD_PROPERTY. */
private final static String LOAD_PROPERTY = "SELECT username FROM ofUserProp WHERE name=? AND propValue=?";
/** The Constant LOAD_PROPERTY_BY_KEY. */
private final static String LOAD_PROPERTY_BY_KEY = "SELECT username FROM ofUserProp WHERE name=?";
/**
* Gets the username by property key and or value.
*
* @param propertyName
* the property name
* @param propertyValue
* the property value (can be null)
* @return the username by property
* @throws ServiceException
* the service exception
*/
public static List<String> getUsernameByProperty(String propertyName, String propertyValue) throws ServiceException {
List<String> usernames = new ArrayList<String>();
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = DbConnectionManager.getConnection();
// Load property by key and value
if (propertyValue != null) {
pstmt = con.prepareStatement(LOAD_PROPERTY);
pstmt.setString(1, propertyName);
pstmt.setString(2, propertyValue);
} else {
// Load property by key
pstmt = con.prepareStatement(LOAD_PROPERTY_BY_KEY);
pstmt.setString(1, propertyName);
}
rs = pstmt.executeQuery();
while (rs.next()) {
usernames.add(rs.getString(1));
}
} catch (SQLException sqle) {
throw new ServiceException("Could not get username by property", propertyName,
ExceptionType.PROPERTY_NOT_FOUND, Response.Status.NOT_FOUND, sqle);
} finally {
DbConnectionManager.closeConnection(rs, pstmt, con);
}
return usernames;
}
}
package org.jivesoftware.openfire.plugin.rest.entity;
public final class MUCChannelType {
public static final String PUBLIC = "public";
public static final String ALL = "all";
private MUCChannelType() {
}
}
package org.jivesoftware.openfire.plugin.rest.entity;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "chatRooms")
public class MUCRoomEntities {
List<MUCRoomEntity> mucRooms;
public MUCRoomEntities() {
}
public MUCRoomEntities(List<MUCRoomEntity> mucRooms) {
this.mucRooms = mucRooms;
}
@XmlElement(name = "chatRoom")
public List<MUCRoomEntity> getMucRooms() {
return mucRooms;
}
public void setMucRooms(List<MUCRoomEntity> mucRooms) {
this.mucRooms = mucRooms;
}
}
package org.jivesoftware.openfire.plugin.rest.entity;
import java.util.Date;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement(name = "chatRoom")
@XmlType(propOrder = { "roomName", "naturalName", "description", "password", "subject", "creationDate",
"modificationDate", "maxUsers", "persistent", "publicRoom", "registrationEnabled", "canAnyoneDiscoverJID",
"canOccupantsChangeSubject", "canOccupantsInvite", "canChangeNickname", "logEnabled",
"loginRestrictedToNickname", "membersOnly", "moderated", "broadcastPresenceRoles", "owners", "admins",
"members", "outcasts" })
public class MUCRoomEntity {
private String roomName;
private String description;
private String password;
private String subject;
private String naturalName;
private int maxUsers;
private Date creationDate;
private Date modificationDate;
private boolean persistent;
private boolean publicRoom;
private boolean registrationEnabled;
private boolean canAnyoneDiscoverJID;
private boolean canOccupantsChangeSubject;
private boolean canOccupantsInvite;
private boolean canChangeNickname;
private boolean logEnabled;
private boolean loginRestrictedToNickname;
private boolean membersOnly;
private boolean moderated;
private List<String> broadcastPresenceRoles;
private List<String> owners;
private List<String> admins;
private List<String> members;
private List<String> outcasts;
public MUCRoomEntity() {
}
public MUCRoomEntity(String naturalName, String roomName, String description) {
this.naturalName = naturalName;
this.roomName = roomName;
this.description = description;
}
@XmlElement
public String getNaturalName() {
return naturalName;
}
public void setNaturalName(String naturalName) {
this.naturalName = naturalName;
}
@XmlElement
public String getRoomName() {
return roomName;
}
public void setRoomName(String roomName) {
this.roomName = roomName;
}
@XmlElement
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@XmlElement
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@XmlElement
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
@XmlElement
public int getMaxUsers() {
return maxUsers;
}
public void setMaxUsers(int maxUsers) {
this.maxUsers = maxUsers;
}
@XmlElement
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
@XmlElement
public Date getModificationDate() {
return modificationDate;
}
public void setModificationDate(Date modificationDate) {
this.modificationDate = modificationDate;
}
@XmlElement
public boolean isPersistent() {
return persistent;
}
public void setPersistent(boolean persistent) {
this.persistent = persistent;
}
@XmlElement
public boolean isPublicRoom() {
return publicRoom;
}
public void setPublicRoom(boolean publicRoom) {
this.publicRoom = publicRoom;
}
@XmlElement
public boolean isRegistrationEnabled() {
return registrationEnabled;
}
public void setRegistrationEnabled(boolean registrationEnabled) {
this.registrationEnabled = registrationEnabled;
}
@XmlElement
public boolean isCanAnyoneDiscoverJID() {
return canAnyoneDiscoverJID;
}
public void setCanAnyoneDiscoverJID(boolean canAnyoneDiscoverJID) {
this.canAnyoneDiscoverJID = canAnyoneDiscoverJID;
}
@XmlElement
public boolean isCanOccupantsChangeSubject() {
return canOccupantsChangeSubject;
}
public void setCanOccupantsChangeSubject(boolean canOccupantsChangeSubject) {
this.canOccupantsChangeSubject = canOccupantsChangeSubject;
}
@XmlElement
public boolean isCanOccupantsInvite() {
return canOccupantsInvite;
}
public void setCanOccupantsInvite(boolean canOccupantsInvite) {
this.canOccupantsInvite = canOccupantsInvite;
}
public void setBroadcastPresenceRoles(List<String> broadcastPresenceRoles) {
this.broadcastPresenceRoles = broadcastPresenceRoles;
}
@XmlElement
public boolean isCanChangeNickname() {
return canChangeNickname;
}
public void setCanChangeNickname(boolean canChangeNickname) {
this.canChangeNickname = canChangeNickname;
}
@XmlElement
public boolean isLogEnabled() {
return logEnabled;
}
public void setLogEnabled(boolean logEnabled) {
this.logEnabled = logEnabled;
}
@XmlElement
public boolean isLoginRestrictedToNickname() {
return loginRestrictedToNickname;
}
public void setLoginRestrictedToNickname(boolean loginRestrictedToNickname) {
this.loginRestrictedToNickname = loginRestrictedToNickname;
}
@XmlElement
public boolean isMembersOnly() {
return membersOnly;
}
public void setMembersOnly(boolean membersOnly) {
this.membersOnly = membersOnly;
}
@XmlElement
public boolean isModerated() {
return moderated;
}
public void setModerated(boolean moderated) {
this.moderated = moderated;
}
@XmlElement(name = "broadcastPresenceRole")
@XmlElementWrapper(name = "broadcastPresenceRoles")
public List<String> getBroadcastPresenceRoles() {
return broadcastPresenceRoles;
}
@XmlElementWrapper(name = "owners")
@XmlElement(name = "owner")
public List<String> getOwners() {
return owners;
}
public void setOwners(List<String> owners) {
this.owners = owners;
}
@XmlElementWrapper(name = "members")
@XmlElement(name = "member")
public List<String> getMembers() {
return members;
}
public void setMembers(List<String> members) {
this.members = members;
}
@XmlElementWrapper(name = "outcasts")
@XmlElement(name = "outcast")
public List<String> getOutcasts() {
return outcasts;
}
public void setOutcasts(List<String> outcasts) {
this.outcasts = outcasts;
}
@XmlElementWrapper(name = "admins")
@XmlElement(name = "admin")
public List<String> getAdmins() {
return admins;
}
public void setAdmins(List<String> admins) {
this.admins = admins;
}
}
\ No newline at end of file
package org.jivesoftware.openfire.plugin.rest.entity;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "participants")
public class ParticipantEntities {
List<ParticipantEntity> participants;
public ParticipantEntities() {
}
public ParticipantEntities(List<ParticipantEntity> participants) {
this.participants = participants;
}
@XmlElement(name = "participant")
public List<ParticipantEntity> getParticipants() {
return participants;
}
public void setParticipants(List<ParticipantEntity> participants) {
this.participants = participants;
}
}
package org.jivesoftware.openfire.plugin.rest.entity;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "participant")
public class ParticipantEntity {
private String jid;
private String role;
private String affiliation;
public ParticipantEntity() {
}
@XmlElement
public String getJid() {
return jid;
}
public void setJid(String jid) {
this.jid = jid;
}
@XmlElement
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
@XmlElement
public String getAffiliation() {
return affiliation;
}
public void setAffiliation(String affiliation) {
this.affiliation = affiliation;
}
}
\ No newline at end of file
package org.jivesoftware.openfire.plugin.rest.entity;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* The Class RosterEntities.
*/
@XmlRootElement(name = "roster")
public class RosterEntities {
/** The roster. */
List<RosterItemEntity> roster;
/**
* Instantiates a new roster entities.
*/
public RosterEntities() {
}
/**
* Instantiates a new roster entities.
*
* @param roster
* the roster
*/
public RosterEntities(List<RosterItemEntity> roster) {
this.roster = roster;
}
/**
* Gets the roster.
*
* @return the roster
*/
@XmlElement(name = "rosterItem")
public List<RosterItemEntity> getRoster() {
return roster;
}
/**
* Sets the roster.
*
* @param roster
* the new roster
*/
public void setRoster(List<RosterItemEntity> roster) {
this.roster = roster;
}
}
package org.jivesoftware.openfire.plugin.rest.entity;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* The Class RosterItemEntity.
*/
@XmlRootElement(name = "rosterItem")
@XmlType(propOrder = { "jid", "nickname", "subscriptionType", "groups" })
public class RosterItemEntity {
/** The jid. */
private String jid;
/** The nickname. */
private String nickname;
/** The subscription type. */
private int subscriptionType;
/** The groups. */
private List<String> groups;
/**
* Instantiates a new roster item entity.
*/
public RosterItemEntity() {
}
/**
* Instantiates a new roster item entity.
*
* @param jid
* the jid
* @param nickname
* the nickname
* @param subscriptionType
* the subscription type
*/
public RosterItemEntity(String jid, String nickname, int subscriptionType) {
this.jid = jid;
this.nickname = nickname;
this.subscriptionType = subscriptionType;
}
/**
* Gets the jid.
*
* @return the jid
*/
@XmlElement
public String getJid() {
return jid;
}
/**
* Sets the jid.
*
* @param jid
* the new jid
*/
public void setJid(String jid) {
this.jid = jid;
}
/**
* Gets the nickname.
*
* @return the nickname
*/
@XmlElement
public String getNickname() {
return nickname;
}
/**
* Sets the nickname.
*
* @param nickname
* the new nickname
*/
public void setNickname(String nickname) {
this.nickname = nickname;
}
/**
* Gets the subscription type.
*
* @return the subscription type
*/
@XmlElement
public int getSubscriptionType() {
return subscriptionType;
}
/**
* Sets the subscription type.
*
* @param subscriptionType
* the new subscription type
*/
public void setSubscriptionType(int subscriptionType) {
this.subscriptionType = subscriptionType;
}
/**
* Gets the groups.
*
* @return the groups
*/
@XmlElement(name = "group")
@XmlElementWrapper(name = "groups")
public List<String> getGroups() {
return groups;
}
/**
* Sets the groups.
*
* @param groups
* the new groups
*/
public void setGroups(List<String> groups) {
this.groups = groups;
}
}
package org.jivesoftware.openfire.plugin.rest.entity;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* The Class UserEntities.
*/
@XmlRootElement(name = "users")
public class UserEntities {
/** The users. */
List<UserEntity> users;
/**
* Instantiates a new user entities.
*/
public UserEntities() {
}
/**
* Instantiates a new user entities.
*
* @param users
* the users
*/
public UserEntities(List<UserEntity> users) {
this.users = users;
}
/**
* Gets the users.
*
* @return the users
*/
@XmlElement(name = "user")
public List<UserEntity> getUsers() {
return users;
}
/**
* Sets the users.
*
* @param users
* the new users
*/
public void setUsers(List<UserEntity> users) {
this.users = users;
}
}
package org.jivesoftware.openfire.plugin.rest.entity;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* The Class UserEntity.
*/
@XmlRootElement(name = "user")
@XmlType(propOrder = { "username", "name", "email", "password", "properties" })
public class UserEntity {
/** The username. */
private String username;
/** The name. */
private String name;
/** The email. */
private String email;
/** The password. */
private String password;
/** The properties. */
private List<UserProperty> properties;
/**
* Instantiates a new user entity.
*/
public UserEntity() {
}
/**
* Instantiates a new user entity.
*
* @param username
* the username
* @param name
* the name
* @param email
* the email
*/
public UserEntity(String username, String name, String email) {
this.username = username;
this.name = name;
this.email = email;
}
/**
* Gets the username.
*
* @return the username
*/
@XmlElement
public String getUsername() {
return username;
}
/**
* Sets the username.
*
* @param username
* the new username
*/
public void setUsername(String username) {
this.username = username;
}
/**
* Gets the name.
*
* @return the name
*/
@XmlElement
public String getName() {
return name;
}
/**
* Sets the name.
*
* @param name
* the new name
*/
public void setName(String name) {
this.name = name;
}
/**
* Gets the email.
*
* @return the email
*/
@XmlElement
public String getEmail() {
return email;
}
/**
* Sets the email.
*
* @param email
* the new email
*/
public void setEmail(String email) {
this.email = email;
}
/**
* Gets the password.
*
* @return the password
*/
public String getPassword() {
return password;
}
/**
* Sets the password.
*
* @param password
* the new password
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Gets the properties.
*
* @return the properties
*/
@XmlElement(name = "property")
@XmlElementWrapper(name = "properties")
public List<UserProperty> getProperties() {
return properties;
}
/**
* Sets the properties.
*
* @param properties
* the new properties
*/
public void setProperties(List<UserProperty> properties) {
this.properties = properties;
}
}
package org.jivesoftware.openfire.plugin.rest.entity;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* The Class UserGroupsEntity.
*/
@XmlRootElement(name = "groups")
public class UserGroupsEntity {
/** The group names. */
private List<String> groupNames;
/**
* Instantiates a new user groups entity.
*/
public UserGroupsEntity() {
}
/**
* Instantiates a new user groups entity.
*
* @param groupNames
* the group names
*/
public UserGroupsEntity(List<String> groupNames) {
this.groupNames = groupNames;
}
/**
* Gets the group names.
*
* @return the group names
*/
@XmlElement(name = "groupname")
public List<String> getGroupNames() {
return groupNames;
}
/**
* Sets the group names.
*
* @param groupNames
* the new group names
*/
public void setGroupNames(List<String> groupNames) {
this.groupNames = groupNames;
}
}
package org.jivesoftware.openfire.plugin.rest.entity;
import javax.xml.bind.annotation.XmlAttribute;
/**
* The Class UserProperty.
*/
public class UserProperty {
/** The key. */
private String key;
/** The value. */
private String value;
/**
* Instantiates a new user property.
*/
public UserProperty() {
}
/**
* Instantiates a new user property.
*
* @param key
* the key
* @param value
* the value
*/
public UserProperty(String key, String value) {
this.key = key;
this.value = value;
}
/**
* Gets the key.
*
* @return the key
*/
@XmlAttribute
public String getKey() {
return key;
}
/**
* Sets the key.
*
* @param key
* the new key
*/
public void setKey(String key) {
this.key = key;
}
/**
* Gets the value.
*
* @return the value
*/
@XmlAttribute
public String getValue() {
return value;
}
/**
* Sets the value.
*
* @param value
* the new value
*/
public void setValue(String value) {
this.value = value;
}
}
package org.jivesoftware.openfire.plugin.rest.exceptions;
/**
* The Class ExceptionType.
*/
public final class ExceptionType {
/** The Constant PROPERTY_NOT_FOUND. */
public static final String PROPERTY_NOT_FOUND = "PropertyNotFoundException";
/** The Constant ILLEGAL_ARGUMENT_EXCEPTION. */
public static final String ILLEGAL_ARGUMENT_EXCEPTION = "IllegalArgumentException";
/**
* Instantiates a new exception type.
*/
private ExceptionType() {
}
}
package org.jivesoftware.openfire.plugin.rest.exceptions;
/**
* The Class ExceptionType.
*/
public final class ExceptionType {
/** The Constant ILLEGAL_ARGUMENT_EXCEPTION. */
public static final String ILLEGAL_ARGUMENT_EXCEPTION = "IllegalArgumentException";
/** The Constant SHARED_GROUP_EXCEPTION. */
public static final String SHARED_GROUP_EXCEPTION = "SharedGroupException";
/** The Constant PROPERTY_NOT_FOUND. */
public static final String PROPERTY_NOT_FOUND = "PropertyNotFoundException";
/** The Constant USER_ALREADY_EXISTS_EXCEPTION. */
public static final String USER_ALREADY_EXISTS_EXCEPTION = "UserAlreadyExistsException";
/** The Constant USER_NOT_FOUND_EXCEPTION. */
public static final String USER_NOT_FOUND_EXCEPTION = "UserNotFoundException";
/** The Constant GROUP_ALREADY_EXISTS. */
public static final String GROUP_ALREADY_EXISTS = "GroupAlreadyExistsException";
/** The Constant GROUP_NOT_FOUND. */
public static final String GROUP_NOT_FOUND = "GroupNotFoundException";
/** The Constant ROOM_NOT_FOUND. */
public static final String ROOM_NOT_FOUND = "RoomNotFoundException";
/** The Constant NOT_ALLOWED. */
public static final String NOT_ALLOWED = "NotAllowedException";
/**
* Instantiates a new exception type.
*/
private ExceptionType() {
}
}
package org.jivesoftware.openfire.plugin.rest;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.jivesoftware.openfire.plugin.rest.exceptions.ErrorResponse;
import org.jivesoftware.openfire.plugin.rest.exceptions.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The Class RESTExceptionMapper.
*/
@Provider
public class RESTExceptionMapper implements ExceptionMapper<ServiceException> {
/** The log. */
private static Logger LOG = LoggerFactory.getLogger(RESTExceptionMapper.class);
/**
* Instantiates a new REST exception mapper.
*/
public RESTExceptionMapper() {
}
/*
* (non-Javadoc)
*
* @see javax.ws.rs.ext.ExceptionMapper#toResponse(java.lang.Throwable)
*/
public Response toResponse(ServiceException exception) {
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setRessource(exception.getRessource());
errorResponse.setMessage(exception.getMessage());
errorResponse.setException(exception.getException());
LOG.error(
exception.getException() + ": " + exception.getMessage() + " with ressource "
+ exception.getRessource(), exception.getException());
return Response.status(exception.getStatus()).entity(errorResponse).type(MediaType.APPLICATION_XML).build();
}
}
package org.jivesoftware.openfire.plugin.rest.exceptions;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The Class RESTExceptionMapper.
*/
@Provider
public class RESTExceptionMapper implements ExceptionMapper<ServiceException> {
/** The log. */
private static Logger LOG = LoggerFactory.getLogger(RESTExceptionMapper.class);
/**
* Instantiates a new REST exception mapper.
*/
public RESTExceptionMapper() {
}
/*
* (non-Javadoc)
*
* @see javax.ws.rs.ext.ExceptionMapper#toResponse(java.lang.Throwable)
*/
public Response toResponse(ServiceException exception) {
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setRessource(exception.getRessource());
errorResponse.setMessage(exception.getMessage());
errorResponse.setException(exception.getException());
LOG.error(
exception.getException() + ": " + exception.getMessage() + " with ressource "
+ exception.getRessource(), exception.getException());
return Response.status(exception.getStatus()).entity(errorResponse).type(MediaType.APPLICATION_XML).build();
}
}
package org.jivesoftware.openfire.plugin.rest;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import org.jivesoftware.admin.AuthCheckFilter;
import org.jivesoftware.openfire.plugin.rest.service.RestAPIService;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.jersey.spi.container.servlet.ServletContainer;
/**
* The Class JerseyWrapper.
*/
public class JerseyWrapper extends ServletContainer {
/** The Constant AUTHFILTER. */
private static final String AUTHFILTER = "org.jivesoftware.openfire.plugin.rest.AuthFilter";
/** The Constant CONTAINER_REQUEST_FILTERS. */
private static final String CONTAINER_REQUEST_FILTERS = "com.sun.jersey.spi.container.ContainerRequestFilters";
/** The Constant RESOURCE_CONFIG_CLASS_KEY. */
private static final String RESOURCE_CONFIG_CLASS_KEY = "com.sun.jersey.config.property.resourceConfigClass";
/** The Constant RESOURCE_CONFIG_CLASS. */
private static final String RESOURCE_CONFIG_CLASS = "com.sun.jersey.api.core.PackagesResourceConfig";
/** The Constant SCAN_PACKAGE_DEFAULT. */
private static final String SCAN_PACKAGE_DEFAULT = JerseyWrapper.class.getPackage().getName();
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/** The Constant SERVLET_URL. */
private static final String SERVLET_URL = "restapi/*";
/** The config. */
private static Map<String, Object> config;
/** The prc. */
private static PackagesResourceConfig prc;
static {
config = new HashMap<String, Object>();
config.put(RESOURCE_CONFIG_CLASS_KEY, RESOURCE_CONFIG_CLASS);
prc = new PackagesResourceConfig(SCAN_PACKAGE_DEFAULT);
prc.setPropertiesAndFeatures(config);
prc.getProperties().put(CONTAINER_REQUEST_FILTERS, AUTHFILTER);
prc.getClasses().add(RestAPIService.class);
prc.getClasses().add(RESTExceptionMapper.class);
}
/**
* Instantiates a new jersey wrapper.
*/
public JerseyWrapper() {
super(prc);
}
/*
* (non-Javadoc)
*
* @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
*/
@Override
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
// Exclude this servlet from requering the user to login
AuthCheckFilter.addExclude(SERVLET_URL);
}
/*
* (non-Javadoc)
*
* @see com.sun.jersey.spi.container.servlet.ServletContainer#destroy()
*/
@Override
public void destroy() {
super.destroy();
// Release the excluded URL
AuthCheckFilter.removeExclude(SERVLET_URL);
}
}
package org.jivesoftware.openfire.plugin.rest.service;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import org.jivesoftware.admin.AuthCheckFilter;
import org.jivesoftware.openfire.plugin.rest.exceptions.RESTExceptionMapper;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.jersey.spi.container.servlet.ServletContainer;
/**
* The Class JerseyWrapper.
*/
public class JerseyWrapper extends ServletContainer {
/** The Constant AUTHFILTER. */
private static final String AUTHFILTER = "org.jivesoftware.openfire.plugin.rest.AuthFilter";
/** The Constant CONTAINER_REQUEST_FILTERS. */
private static final String CONTAINER_REQUEST_FILTERS = "com.sun.jersey.spi.container.ContainerRequestFilters";
/** The Constant RESOURCE_CONFIG_CLASS_KEY. */
private static final String RESOURCE_CONFIG_CLASS_KEY = "com.sun.jersey.config.property.resourceConfigClass";
/** The Constant RESOURCE_CONFIG_CLASS. */
private static final String RESOURCE_CONFIG_CLASS = "com.sun.jersey.api.core.PackagesResourceConfig";
/** The Constant SCAN_PACKAGE_DEFAULT. */
private static final String SCAN_PACKAGE_DEFAULT = JerseyWrapper.class.getPackage().getName();
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/** The Constant SERVLET_URL. */
private static final String SERVLET_URL = "restapi/*";
/** The config. */
private static Map<String, Object> config;
/** The prc. */
private static PackagesResourceConfig prc;
static {
config = new HashMap<String, Object>();
config.put(RESOURCE_CONFIG_CLASS_KEY, RESOURCE_CONFIG_CLASS);
prc = new PackagesResourceConfig(SCAN_PACKAGE_DEFAULT);
prc.setPropertiesAndFeatures(config);
prc.getProperties().put(CONTAINER_REQUEST_FILTERS, AUTHFILTER);
prc.getClasses().add(RestAPIService.class);
prc.getClasses().add(MUCRoomService.class);
prc.getClasses().add(MUCRoomOwnersService.class);
prc.getClasses().add(MUCRoomAdminsService.class);
prc.getClasses().add(MUCRoomMembersService.class);
prc.getClasses().add(MUCRoomOutcastsService.class);
prc.getClasses().add(UserServiceLegacy.class);
prc.getClasses().add(UserService.class);
prc.getClasses().add(UserRosterService.class);
prc.getClasses().add(UserGroupService.class);
prc.getClasses().add(UserLockoutService.class);
prc.getClasses().add(RESTExceptionMapper.class);
}
/**
* Instantiates a new jersey wrapper.
*/
public JerseyWrapper() {
super(prc);
}
/*
* (non-Javadoc)
*
* @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
*/
@Override
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
// Exclude this servlet from requering the user to login
AuthCheckFilter.addExclude(SERVLET_URL);
}
/*
* (non-Javadoc)
*
* @see com.sun.jersey.spi.container.servlet.ServletContainer#destroy()
*/
@Override
public void destroy() {
super.destroy();
// Release the excluded URL
AuthCheckFilter.removeExclude(SERVLET_URL);
}
}
package org.jivesoftware.openfire.plugin.rest.service;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.jivesoftware.openfire.plugin.rest.exceptions.ServiceException;
import org.jivesoftware.openfire.plugin.rest.controller.MUCRoomController;
@Path("restapi/v1/chatrooms/{roomName}/admins")
public class MUCRoomAdminsService {
@POST
@Path("/{jid}")
public Response addMUCRoomAdmin(@DefaultValue("conference") @QueryParam("servicename") String serviceName,
@PathParam("jid") String jid, @PathParam("roomName") String roomName) throws ServiceException {
MUCRoomController.getInstance().addAdmin(serviceName, roomName, jid);
return Response.status(Status.CREATED).build();
}
@DELETE
@Path("/{jid}")
public Response deleteMUCRoomAdmin(@PathParam("jid") String jid,
@DefaultValue("conference") @QueryParam("servicename") String serviceName,
@PathParam("roomName") String roomName) throws ServiceException {
MUCRoomController.getInstance().deleteAffiliation(serviceName, roomName, jid);
return Response.status(Status.OK).build();
}
}
package org.jivesoftware.openfire.plugin.rest.service;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.jivesoftware.openfire.plugin.rest.exceptions.ServiceException;
import org.jivesoftware.openfire.plugin.rest.controller.MUCRoomController;
@Path("restapi/v1/chatrooms/{roomName}/members")
public class MUCRoomMembersService {
@POST
@Path("/{jid}")
public Response addMUCRoomMember(@DefaultValue("conference") @QueryParam("servicename") String serviceName,
@PathParam("jid") String jid, @PathParam("roomName") String roomName) throws ServiceException {
MUCRoomController.getInstance().addMember(serviceName, roomName, jid);
return Response.status(Status.CREATED).build();
}
@DELETE
@Path("/{jid}")
public Response deleteMUCRoomMember(@PathParam("jid") String jid,
@DefaultValue("conference") @QueryParam("servicename") String serviceName,
@PathParam("roomName") String roomName) throws ServiceException {
MUCRoomController.getInstance().deleteAffiliation(serviceName, roomName, jid);
return Response.status(Status.OK).build();
}
}
package org.jivesoftware.openfire.plugin.rest.service;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.jivesoftware.openfire.plugin.rest.exceptions.ServiceException;
import org.jivesoftware.openfire.plugin.rest.controller.MUCRoomController;
@Path("restapi/v1/chatrooms/{roomName}/outcasts")
public class MUCRoomOutcastsService {
@POST
@Path("/{jid}")
public Response addMUCRoomOutcast(@DefaultValue("conference") @QueryParam("servicename") String serviceName,
@PathParam("jid") String jid, @PathParam("roomName") String roomName) throws ServiceException {
MUCRoomController.getInstance().addOutcast(serviceName, roomName, jid);
return Response.status(Status.CREATED).build();
}
@DELETE
@Path("/{jid}")
public Response deleteMUCRoomOutcast(@PathParam("jid") String jid,
@DefaultValue("conference") @QueryParam("servicename") String serviceName,
@PathParam("roomName") String roomName) throws ServiceException {
MUCRoomController.getInstance().deleteAffiliation(serviceName, roomName, jid);
return Response.status(Status.OK).build();
}
}
package org.jivesoftware.openfire.plugin.rest.service;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.jivesoftware.openfire.plugin.rest.exceptions.ServiceException;
import org.jivesoftware.openfire.plugin.rest.controller.MUCRoomController;
@Path("restapi/v1/chatrooms/{roomName}/owners")
public class MUCRoomOwnersService {
@POST
@Path("/{jid}")
public Response addMUCRoomOwner(@DefaultValue("conference") @QueryParam("servicename") String serviceName,
@PathParam("jid") String jid, @PathParam("roomName") String roomName) throws ServiceException {
MUCRoomController.getInstance().addOwner(serviceName, roomName, jid);
return Response.status(Status.CREATED).build();
}
@DELETE
@Path("/{jid}")
public Response deleteMUCRoomOwner(@PathParam("jid") String jid,
@DefaultValue("conference") @QueryParam("servicename") String serviceName,
@PathParam("roomName") String roomName) throws ServiceException {
MUCRoomController.getInstance().deleteAffiliation(serviceName, roomName, jid);
return Response.status(Status.OK).build();
}
}
package org.jivesoftware.openfire.plugin.rest.service;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.jivesoftware.openfire.plugin.rest.entity.MUCChannelType;
import org.jivesoftware.openfire.plugin.rest.entity.MUCRoomEntities;
import org.jivesoftware.openfire.plugin.rest.entity.MUCRoomEntity;
import org.jivesoftware.openfire.plugin.rest.entity.ParticipantEntities;
import org.jivesoftware.openfire.plugin.rest.exceptions.ServiceException;
import org.jivesoftware.openfire.plugin.rest.controller.MUCRoomController;
@Path("restapi/v1/chatrooms")
public class MUCRoomService {
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public MUCRoomEntities getMUCRooms(@DefaultValue("conference") @QueryParam("servicename") String serviceName,
@DefaultValue(MUCChannelType.PUBLIC) @QueryParam("type") String channelType,
@QueryParam("search") String roomSearch) {
return MUCRoomController.getInstance().getChatRooms(serviceName, channelType, roomSearch);
}
@GET
@Path("/{roomName}")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public MUCRoomEntity getMUCRoomJSON2(@PathParam("roomName") String roomName,
@DefaultValue("conference") @QueryParam("servicename") String serviceName) throws ServiceException {
return MUCRoomController.getInstance().getChatRoom(roomName, serviceName);
}
@DELETE
@Path("/{roomName}")
public Response deleteMUCRoom(@PathParam("roomName") String roomName,
@DefaultValue("conference") @QueryParam("servicename") String serviceName) throws ServiceException {
MUCRoomController.getInstance().deleteChatRoom(roomName, serviceName);
return Response.status(Status.OK).build();
}
@POST
public Response createMUCRoom(@DefaultValue("conference") @QueryParam("servicename") String serviceName,
MUCRoomEntity mucRoomEntity) throws ServiceException {
MUCRoomController.getInstance().createChatRoom(serviceName, mucRoomEntity);
return Response.status(Status.CREATED).build();
}
@PUT
@Path("/{roomName}")
public Response udpateMUCRoom(@PathParam("roomName") String roomName,
@DefaultValue("conference") @QueryParam("servicename") String serviceName, MUCRoomEntity mucRoomEntity)
throws ServiceException {
MUCRoomController.getInstance().updateChatRoom(roomName, serviceName, mucRoomEntity);
return Response.status(Status.OK).build();
}
@GET
@Path("/{roomName}/participants")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public ParticipantEntities getMUCRoomParticipants(@PathParam("roomName") String roomName,
@DefaultValue("conference") @QueryParam("servicename") String serviceName) {
return MUCRoomController.getInstance().getRoomParticipants(roomName, serviceName);
}
}
package org.jivesoftware.openfire.plugin.rest.service;
import javax.annotation.PostConstruct;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.jivesoftware.openfire.plugin.rest.RESTServicePlugin;
import org.jivesoftware.openfire.plugin.rest.entity.SystemProperties;
import org.jivesoftware.openfire.plugin.rest.entity.SystemProperty;
import org.jivesoftware.openfire.plugin.rest.exceptions.ServiceException;
@Path("restapi/system/properties")
public class RestAPIService {
private RESTServicePlugin plugin;
@PostConstruct
public void init() {
plugin = RESTServicePlugin.getInstance();
}
@GET
@Produces(MediaType.APPLICATION_XML)
public SystemProperties getSystemProperties() {
return plugin.getSystemProperties();
}
@GET
@Path("/{propertyKey}")
@Produces(MediaType.APPLICATION_XML)
public SystemProperty getSystemProperty(@PathParam("propertyKey") String propertyKey) throws ServiceException {
return plugin.getSystemProperty(propertyKey);
}
@POST
public Response createSystemProperty(SystemProperty systemProperty) throws ServiceException {
plugin.createSystemProperty(systemProperty);
return Response.status(Response.Status.CREATED).build();
}
@PUT
@Path("/{propertyKey}")
public Response updateUser(@PathParam("propertyKey") String propertyKey, SystemProperty systemProperty) throws ServiceException {
plugin.updateSystemProperty(propertyKey, systemProperty);
return Response.status(Response.Status.OK).build();
}
@DELETE
@Path("/{propertyKey}")
public Response deleteUser(@PathParam("propertyKey") String propertyKey) throws ServiceException {
plugin.deleteSystemProperty(propertyKey);
return Response.status(Response.Status.OK).build();
}
}
package org.jivesoftware.openfire.plugin.rest.service;
import javax.annotation.PostConstruct;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.jivesoftware.openfire.plugin.rest.RESTServicePlugin;
import org.jivesoftware.openfire.plugin.rest.entity.SystemProperties;
import org.jivesoftware.openfire.plugin.rest.entity.SystemProperty;
import org.jivesoftware.openfire.plugin.rest.exceptions.ServiceException;
@Path("restapi/v1/system/properties")
public class RestAPIService {
private RESTServicePlugin plugin;
@PostConstruct
public void init() {
plugin = RESTServicePlugin.getInstance();
}
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public SystemProperties getSystemProperties() {
return plugin.getSystemProperties();
}
@GET
@Path("/{propertyKey}")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public SystemProperty getSystemProperty(@PathParam("propertyKey") String propertyKey) throws ServiceException {
return plugin.getSystemProperty(propertyKey);
}
@POST
public Response createSystemProperty(SystemProperty systemProperty) throws ServiceException {
plugin.createSystemProperty(systemProperty);
return Response.status(Response.Status.CREATED).build();
}
@PUT
@Path("/{propertyKey}")
public Response updateUser(@PathParam("propertyKey") String propertyKey, SystemProperty systemProperty) throws ServiceException {
plugin.updateSystemProperty(propertyKey, systemProperty);
return Response.status(Response.Status.OK).build();
}
@DELETE
@Path("/{propertyKey}")
public Response deleteUser(@PathParam("propertyKey") String propertyKey) throws ServiceException {
plugin.deleteSystemProperty(propertyKey);
return Response.status(Response.Status.OK).build();
}
}
package org.jivesoftware.openfire.plugin.rest.service;
import javax.annotation.PostConstruct;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.jivesoftware.openfire.plugin.rest.controller.UserServiceController;
import org.jivesoftware.openfire.plugin.rest.entity.UserGroupsEntity;
import org.jivesoftware.openfire.plugin.rest.exceptions.ServiceException;
@Path("restapi/v1/users/{username}/groups")
public class UserGroupService {
private UserServiceController plugin;
@PostConstruct
public void init() {
plugin = UserServiceController.getInstance();
}
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public UserGroupsEntity getUserGroups(@PathParam("username") String username) throws ServiceException {
return new UserGroupsEntity(plugin.getUserGroups(username));
}
@POST
public Response addUserToGroups(@PathParam("username") String username, UserGroupsEntity userGroupsEntity)
throws ServiceException {
plugin.addUserToGroups(username, userGroupsEntity);
return Response.status(Response.Status.CREATED).build();
}
@DELETE
public Response deleteUserFromGroups(@PathParam("username") String username, UserGroupsEntity userGroupsEntity)
throws ServiceException {
plugin.deleteUserFromGroups(username, userGroupsEntity);
return Response.status(Response.Status.OK).build();
}
}
package org.jivesoftware.openfire.plugin.rest.service;
import javax.annotation.PostConstruct;
import javax.ws.rs.DELETE;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
import org.jivesoftware.openfire.plugin.rest.controller.UserServiceController;
import org.jivesoftware.openfire.plugin.rest.exceptions.ServiceException;
@Path("restapi/v1/lockouts")
public class UserLockoutService {
private UserServiceController plugin;
@PostConstruct
public void init() {
plugin = UserServiceController.getInstance();
}
@POST
@Path("/{username}")
public Response disableUser(@PathParam("username") String username) throws ServiceException {
plugin.disableUser(username);
return Response.status(Response.Status.CREATED).build();
}
@DELETE
@Path("/{username}")
public Response enableUser(@PathParam("username") String username) throws ServiceException {
plugin.enableUser(username);
return Response.status(Response.Status.OK).build();
}
}
package org.jivesoftware.openfire.plugin.rest.service;
import javax.annotation.PostConstruct;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.jivesoftware.openfire.SharedGroupException;
import org.jivesoftware.openfire.plugin.rest.controller.UserServiceController;
import org.jivesoftware.openfire.plugin.rest.entity.RosterEntities;
import org.jivesoftware.openfire.plugin.rest.entity.RosterItemEntity;
import org.jivesoftware.openfire.plugin.rest.exceptions.ExceptionType;
import org.jivesoftware.openfire.plugin.rest.exceptions.ServiceException;
import org.jivesoftware.openfire.user.UserAlreadyExistsException;
import org.jivesoftware.openfire.user.UserNotFoundException;
@Path("restapi/v1/users/{username}/roster")
public class UserRosterService {
private static final String COULD_NOT_UPDATE_THE_ROSTER = "Could not update the roster";
private static final String COULD_NOT_CREATE_ROSTER_ITEM = "Could not create roster item";
private UserServiceController plugin;
@PostConstruct
public void init() {
plugin = UserServiceController.getInstance();
}
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public RosterEntities getUserRoster(@PathParam("username") String username) throws ServiceException {
return plugin.getRosterEntities(username);
}
@POST
public Response createRoster(@PathParam("username") String username, RosterItemEntity rosterItemEntity)
throws ServiceException {
try {
plugin.addRosterItem(username, rosterItemEntity);
} catch (UserNotFoundException e) {
throw new ServiceException(COULD_NOT_CREATE_ROSTER_ITEM, "", ExceptionType.USER_NOT_FOUND_EXCEPTION,
Response.Status.NOT_FOUND, e);
} catch (UserAlreadyExistsException e) {
throw new ServiceException(COULD_NOT_CREATE_ROSTER_ITEM, "", ExceptionType.USER_ALREADY_EXISTS_EXCEPTION,
Response.Status.BAD_REQUEST, e);
} catch (SharedGroupException e) {
throw new ServiceException(COULD_NOT_CREATE_ROSTER_ITEM, "", ExceptionType.SHARED_GROUP_EXCEPTION,
Response.Status.BAD_REQUEST, e);
}
return Response.status(Response.Status.CREATED).build();
}
@DELETE
@Path("/{rosterJid}")
public Response deleteRoster(@PathParam("username") String username, @PathParam("rosterJid") String rosterJid)
throws ServiceException {
try {
plugin.deleteRosterItem(username, rosterJid);
} catch (SharedGroupException e) {
throw new ServiceException("Could not delete the roster item", rosterJid,
ExceptionType.SHARED_GROUP_EXCEPTION, Response.Status.BAD_REQUEST, e);
}
return Response.status(Response.Status.OK).build();
}
@PUT
@Path("/{rosterJid}")
public Response updateRoster(@PathParam("username") String username, @PathParam("rosterJid") String rosterJid,
RosterItemEntity rosterItemEntity) throws ServiceException {
try {
plugin.updateRosterItem(username, rosterJid, rosterItemEntity);
} catch (UserNotFoundException e) {
throw new ServiceException(COULD_NOT_UPDATE_THE_ROSTER, rosterJid, ExceptionType.USER_NOT_FOUND_EXCEPTION,
Response.Status.NOT_FOUND, e);
} catch (SharedGroupException e) {
throw new ServiceException(COULD_NOT_UPDATE_THE_ROSTER, rosterJid, ExceptionType.SHARED_GROUP_EXCEPTION,
Response.Status.BAD_REQUEST, e);
} catch (UserAlreadyExistsException e) {
throw new ServiceException(COULD_NOT_UPDATE_THE_ROSTER, rosterJid,
ExceptionType.USER_ALREADY_EXISTS_EXCEPTION, Response.Status.BAD_REQUEST, e);
}
return Response.status(Response.Status.OK).build();
}
}
package org.jivesoftware.openfire.plugin.rest.service;
import javax.annotation.PostConstruct;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.jivesoftware.openfire.plugin.rest.controller.UserServiceController;
import org.jivesoftware.openfire.plugin.rest.entity.UserEntities;
import org.jivesoftware.openfire.plugin.rest.entity.UserEntity;
import org.jivesoftware.openfire.plugin.rest.exceptions.ServiceException;
@Path("restapi/v1/users")
public class UserService {
private UserServiceController plugin;
@PostConstruct
public void init() {
plugin = UserServiceController.getInstance();
}
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public UserEntities getUsers(@QueryParam("search") String userSearch,
@QueryParam("propertyKey") String propertyKey, @QueryParam("propertyValue") String propertyValue)
throws ServiceException {
return plugin.getUserEntities(userSearch, propertyKey, propertyValue);
}
@POST
public Response createUser(UserEntity userEntity) throws ServiceException {
plugin.createUser(userEntity);
return Response.status(Response.Status.CREATED).build();
}
@GET
@Path("/{username}")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public UserEntity getUser(@PathParam("username") String username) throws ServiceException {
return plugin.getUserEntity(username);
}
@PUT
@Path("/{username}")
public Response updateUser(@PathParam("username") String username, UserEntity userEntity) throws ServiceException {
plugin.updateUser(username, userEntity);
return Response.status(Response.Status.OK).build();
}
@DELETE
@Path("/{username}")
public Response deleteUser(@PathParam("username") String username) throws ServiceException {
plugin.deleteUser(username);
return Response.status(Response.Status.OK).build();
}
}
package org.jivesoftware.openfire.plugin.rest.service;
import gnu.inet.encoding.Stringprep;
import java.io.IOException;
import java.io.PrintWriter;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import org.apache.log4j.Logger;
import org.jivesoftware.openfire.SharedGroupException;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.plugin.rest.RESTServicePlugin;
import org.jivesoftware.openfire.plugin.rest.controller.UserServiceLegacyController;
import org.jivesoftware.openfire.user.UserAlreadyExistsException;
import org.jivesoftware.openfire.user.UserNotFoundException;
import org.xmpp.packet.JID;
@Path("restapi/v1")
public class UserServiceLegacy {
private static Logger Log = Logger.getLogger(UserServiceLegacy.class);
@Context
private HttpServletRequest request;
@Context
private HttpServletResponse response;
private RESTServicePlugin plugin;
private UserServiceLegacyController userServiceController;
@PostConstruct
public void init() {
plugin = (RESTServicePlugin) XMPPServer.getInstance().getPluginManager()
.getPlugin("restapi");
userServiceController = UserServiceLegacyController.getInstance();
}
@POST
@Path("/userservice")
public void userSerivcePostRequest() throws IOException {
userSerivceRequest();
}
@GET
@Path("/userservice")
public Response userSerivceRequest() throws IOException {
// Printwriter for writing out responses to browser
PrintWriter out = response.getWriter();
if (!plugin.getAllowedIPs().isEmpty()) {
// Get client's IP address
String ipAddress = request.getHeader("x-forwarded-for");
if (ipAddress == null) {
ipAddress = request.getHeader("X_FORWARDED_FOR");
if (ipAddress == null) {
ipAddress = request.getHeader("X-Forward-For");
if (ipAddress == null) {
ipAddress = request.getRemoteAddr();
}
}
}
if (!plugin.getAllowedIPs().contains(ipAddress)) {
Log.warn("User service rejected service to IP address: " + ipAddress);
replyError("RequestNotAuthorised", response, out);
return Response.status(200).build();
}
}
String username = request.getParameter("username");
String password = request.getParameter("password");
String name = request.getParameter("name");
String email = request.getParameter("email");
String type = request.getParameter("type");
String secret = request.getParameter("secret");
String groupNames = request.getParameter("groups");
String item_jid = request.getParameter("item_jid");
String sub = request.getParameter("subscription");
// No defaults, add, delete, update only
// type = type == null ? "image" : type;
// Check that our plugin is enabled.
if (!plugin.isEnabled()) {
Log.warn("User service plugin is disabled: " + request.getQueryString());
replyError("UserServiceDisabled", response, out);
return Response.status(200).build();
}
// Check this request is authorised
if (secret == null || !secret.equals(plugin.getSecret())) {
Log.warn("An unauthorised user service request was received: " + request.getQueryString());
replyError("RequestNotAuthorised", response, out);
return Response.status(200).build();
}
// Some checking is required on the username
if (username == null && !"grouplist".equals(type)) {
replyError("IllegalArgumentException", response, out);
return Response.status(200).build();
}
if ((type.equals("add_roster") || type.equals("update_roster") || type.equals("delete_roster"))
&& (item_jid == null || !(sub == null || sub.equals("-1") || sub.equals("0") || sub.equals("1")
|| sub.equals("2") || sub.equals("3")))) {
replyError("IllegalArgumentException", response, out);
return Response.status(200).build();
}
// Check the request type and process accordingly
try {
if ("grouplist".equals(type)) {
String message = "";
for (String groupname : userServiceController.getAllGroups()) {
message += "<groupname>" + groupname + "</groupname>";
}
replyMessage(message, response, out);
} else {
username = username.trim().toLowerCase();
username = JID.escapeNode(username);
username = Stringprep.nodeprep(username);
if ("add".equals(type)) {
userServiceController.createUser(username, password, name, email, groupNames);
replyMessage("ok", response, out);
} else if ("delete".equals(type)) {
userServiceController.deleteUser(username);
replyMessage("ok", response, out);
} else if ("enable".equals(type)) {
userServiceController.enableUser(username);
replyMessage("ok", response, out);
} else if ("disable".equals(type)) {
userServiceController.disableUser(username);
replyMessage("ok", response, out);
} else if ("update".equals(type)) {
userServiceController.updateUser(username, password, name, email, groupNames);
replyMessage("ok", response, out);
} else if ("add_roster".equals(type)) {
userServiceController.addRosterItem(username, item_jid, name, sub, groupNames);
replyMessage("ok", response, out);
} else if ("update_roster".equals(type)) {
userServiceController.updateRosterItem(username, item_jid, name, sub, groupNames);
replyMessage("ok", response, out);
} else if ("delete_roster".equals(type)) {
userServiceController.deleteRosterItem(username, item_jid);
replyMessage("ok", response, out);
} else if ("usergrouplist".equals(type)) {
String message = "";
for (String groupname : userServiceController.getUserGroups(username)) {
message += "<groupname>" + groupname + "</groupname>";
}
replyMessage(message, response, out);
} else {
Log.warn("The userService servlet received an invalid request of type: " + type);
// TODO Do something
}
}
} catch (UserAlreadyExistsException e) {
replyError("UserAlreadyExistsException", response, out);
} catch (UserNotFoundException e) {
replyError("UserNotFoundException", response, out);
} catch (IllegalArgumentException e) {
replyError("IllegalArgumentException", response, out);
} catch (SharedGroupException e) {
replyError("SharedGroupException", response, out);
} catch (Exception e) {
Log.error("Error: ", e);
replyError(e.toString(), response, out);
}
return Response.status(200).build();
}
private void replyMessage(String message, HttpServletResponse response, PrintWriter out) {
response.setContentType("text/xml");
out.println("<result>" + message + "</result>");
out.flush();
}
private void replyError(String error, HttpServletResponse response, PrintWriter out) {
response.setContentType("text/xml");
out.println("<error>" + error + "</error>");
out.flush();
}
}
package org.jivesoftware.openfire.plugin.rest.utils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.xmpp.packet.JID;
/**
* The Class MUCRoomUtils.
*/
public class MUCRoomUtils {
/**
* Instantiates a new MUC room utils.
*/
private MUCRoomUtils() {
throw new AssertionError();
}
/**
* Convert jids to string list.
*
* @param jids
* the jids
* @return the array list< string>
*/
public static List<String> convertJIDsToStringList(Collection<JID> jids) {
List<String> result = new ArrayList<String>();
for (JID jid : jids) {
result.add(jid.toBareJID());
}
return result;
}
/**
* Convert strings to jids.
*
* @param jids
* the jids
* @return the list<jid>
*/
public static List<JID> convertStringsToJIDs(List<String> jids) {
List<JID> result = new ArrayList<JID>();
for (String jidString : jids) {
result.add(new JID(jidString));
}
return result;
}
}
package org.jivesoftware.openfire.plugin.rest.utils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map.Entry;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.plugin.rest.entity.UserEntity;
import org.jivesoftware.openfire.plugin.rest.entity.UserProperty;
import org.jivesoftware.openfire.user.User;
import org.jivesoftware.openfire.user.UserAlreadyExistsException;
import org.xmpp.packet.JID;
// TODO: Auto-generated Javadoc
/**
* The Class UserUtils.
*/
public class UserUtils {
/**
* Instantiates a new user utils.
*/
private UserUtils() {
throw new AssertionError();
}
/**
* Convert users to user entities.
*
* @param users the users
* @param userSearch the user search
* @return the list
*/
public static List<UserEntity> convertUsersToUserEntities(Collection<User> users, String userSearch) {
List<UserEntity> result = new ArrayList<UserEntity>();
for (User user : users) {
if (userSearch != null) {
if (!user.getUsername().contains(userSearch)) {
continue;
}
}
result.add(convertUserToUserEntity(user));
}
return result;
}
/**
* Convert user to user entity.
*
* @param user
* the user
* @return the user entity
*/
public static UserEntity convertUserToUserEntity(User user) {
UserEntity userEntity = new UserEntity(user.getUsername(), user.getName(), user.getEmail());
List<UserProperty> userProperties = new ArrayList<UserProperty>();
for (Entry<String, String> property : user.getProperties().entrySet()) {
userProperties.add(new UserProperty(property.getKey(), property.getValue()));
}
userEntity.setProperties(userProperties);
return userEntity;
}
/**
* Checks if is valid sub type.
*
* @param subType the sub type
* @return true, if is valid sub type
* @throws UserAlreadyExistsException the user already exists exception
*/
public static void checkSubType(int subType) throws UserAlreadyExistsException {
if (!(subType >= -1 && subType <= 3)) {
throw new UserAlreadyExistsException();
}
}
/**
* Check and get jid.
*
* @param jid the jid
* @return the jid
*/
public static JID checkAndGetJID(String jid) {
if(isValidBareJid(jid)) {
return new JID(jid);
} else {
return XMPPServer.getInstance().createJID(jid, null);
}
}
/**
* Checks if is valid bare jid.
*
* @param jid the jid
* @return true, if is valid bare jid
*/
public static boolean isValidBareJid(String jid) {
final int index = jid.indexOf('@');
if (index == -1) {
return false;
} else if (jid.indexOf('@', index + 1) != -1) {
return false;
}
return true;
}
}
<?xml version='1.0' encoding='ISO-8859-1'?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<!-- Servlets -->
<servlet>
<servlet-name>JerseyWrapper</servlet-name>
<servlet-class>org.jivesoftware.openfire.plugin.rest.JerseyWrapper</servlet-class>
</servlet>
<!-- Servlet mappings -->
<servlet-mapping>
<servlet-name>JerseyWrapper</servlet-name>
<url-pattern>/system/*</url-pattern>
</servlet-mapping>
</web-app>
<?xml version='1.0' encoding='ISO-8859-1'?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<!-- Servlets -->
<servlet>
<servlet-name>JerseyWrapper</servlet-name>
<servlet-class>org.jivesoftware.openfire.plugin.rest.service.JerseyWrapper</servlet-class>
</servlet>
<!-- Servlet mappings -->
<servlet-mapping>
<servlet-name>JerseyWrapper</servlet-name>
<url-pattern>/v1/*</url-pattern>
</servlet-mapping>
</web-app>
<%@ page import="java.util.*,
org.jivesoftware.openfire.XMPPServer,
org.jivesoftware.util.*,org.jivesoftware.openfire.plugin.rest.RESTServicePlugin"
errorPage="error.jsp"
%>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jstl/fmt_rt" prefix="fmt" %>
<%-- Define Administration Bean --%>
<jsp:useBean id="admin" class="org.jivesoftware.util.WebManager" />
<c:set var="admin" value="${admin.manager}" />
<%
admin.init(request, response, session, application, out );
%>
<%
// Get parameters
boolean save = request.getParameter("save") != null;
boolean success = request.getParameter("success") != null;
String secret = ParamUtils.getParameter(request, "secret");
boolean enabled = ParamUtils.getBooleanParameter(request, "enabled");
boolean httpBasicAuth = ParamUtils.getBooleanParameter(request, "authtype");
String allowedIPs = ParamUtils.getParameter(request, "allowedIPs");
RESTServicePlugin plugin = (RESTServicePlugin) XMPPServer.getInstance().getPluginManager().getPlugin("restapi");
// Handle a save
Map errors = new HashMap();
if (save) {
if (errors.size() == 0) {
plugin.setEnabled(enabled);
plugin.setSecret(secret);
plugin.setHttpBasicAuth(httpBasicAuth);
plugin.setAllowedIPs(StringUtils.stringToCollection(allowedIPs));
response.sendRedirect("rest-api.jsp?success=true");
return;
}
}
secret = plugin.getSecret();
enabled = plugin.isEnabled();
httpBasicAuth = plugin.isHttpBasicAuth();
allowedIPs = StringUtils.collectionToString(plugin.getAllowedIPs());
%>
<html>
<head>
<title>REST API Properties</title>
<meta name="pageID" content="rest-api"/>
</head>
<body>
<p>
Use the form below to enable or disable the REST API and configure the authentication.
</p>
<% if (success) { %>
<div class="jive-success">
<table cellpadding="0" cellspacing="0" border="0">
<tbody>
<tr><td class="jive-icon"><img src="images/success-16x16.gif" width="16" height="16" border="0"></td>
<td class="jive-icon-label">
REST API properties edited successfully.
</td></tr>
</tbody>
</table>
</div><br>
<% } %>
<form action="rest-api.jsp?save" method="post">
<fieldset>
<legend>REST API</legend>
<div>
<p>
The addition, deletion and editing of Openfire system properties is not normally available outside of the admin console.
This service lets those administration tasks be performed HTTP requests to provide
simple integration with other applications.</p>
<p>The REST API can be secured with a shared secret key defined below or a with HTTP basic authentication.
Moreover, for extra security you can specify the list of IP addresses that are allowed to
use this service. An empty list means that the service can be accessed from any
location. Addresses are delimited by commas.
</p>
<ul>
<input type="radio" name="enabled" value="true" id="rb01"
<%= ((enabled) ? "checked" : "") %>>
<label for="rb01"><b>Enabled</b> - REST API requests will be processed.</label>
<br>
<input type="radio" name="enabled" value="false" id="rb02"
<%= ((!enabled) ? "checked" : "") %>>
<label for="rb02"><b>Disabled</b> - REST API requests will be ignored.</label>
<br><br>
<input type="radio" name="authtype" value="true" id="http_basic_auth" <%= ((httpBasicAuth) ? "checked" : "") %>>
<label for="http_basic_auth">HTTP basic auth - REST API authentication with Openfire admin account.</label>
<br>
<input type="radio" name="authtype" value="false" id="secretKeyAuth" <%= ((!httpBasicAuth) ? "checked" : "") %>>
<label for="secretKeyAuth">Secret key auth - REST API authentication over specified secret key.</label>
<br>
<label style="padding-left: 25px" for="text_secret">Secret key:</label>
<input type="text" name="secret" value="<%= secret %>" id="text_secret">
<br><br>
<label for="text_secret">Allowed IP Addresses:</label>
<textarea name="allowedIPs" cols="40" rows="3" wrap="virtual"><%= ((allowedIPs != null) ? allowedIPs : "") %></textarea>
</ul>
</div>
</fieldset>
<br><br>
<input type="submit" value="Save Settings">
</form>
</body>
<%@ page
import="java.util.*,
org.jivesoftware.openfire.XMPPServer,
org.jivesoftware.util.*,org.jivesoftware.openfire.plugin.rest.RESTServicePlugin"
errorPage="error.jsp"%>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jstl/fmt_rt" prefix="fmt"%>
<%-- Define Administration Bean --%>
<jsp:useBean id="admin" class="org.jivesoftware.util.WebManager" />
<c:set var="admin" value="${admin.manager}" />
<%
admin.init(request, response, session, application, out);
%>
<%
// Get parameters
boolean save = request.getParameter("save") != null;
boolean success = request.getParameter("success") != null;
String secret = ParamUtils.getParameter(request, "secret");
boolean enabled = ParamUtils.getBooleanParameter(request, "enabled");
boolean httpBasicAuth = ParamUtils.getBooleanParameter(request, "authtype");
String allowedIPs = ParamUtils.getParameter(request, "allowedIPs");
RESTServicePlugin plugin = (RESTServicePlugin) XMPPServer.getInstance().getPluginManager()
.getPlugin("restapi");
// Handle a save
Map errors = new HashMap();
if (save) {
if (errors.size() == 0) {
plugin.setEnabled(enabled);
plugin.setSecret(secret);
plugin.setHttpBasicAuth(httpBasicAuth);
plugin.setAllowedIPs(StringUtils.stringToCollection(allowedIPs));
response.sendRedirect("rest-api.jsp?success=true");
return;
}
}
secret = plugin.getSecret();
enabled = plugin.isEnabled();
httpBasicAuth = plugin.isHttpBasicAuth();
allowedIPs = StringUtils.collectionToString(plugin.getAllowedIPs());
%>
<html>
<head>
<title>REST API Properties</title>
<meta name="pageID" content="rest-api" />
</head>
<body>
<p>Use the form below to enable or disable the REST API and
configure the authentication.</p>
<%
if (success) {
%>
<div class="jive-success">
<table cellpadding="0" cellspacing="0" border="0">
<tbody>
<tr>
<td class="jive-icon"><img src="images/success-16x16.gif"
width="16" height="16" border="0"></td>
<td class="jive-icon-label">REST API properties edited
successfully.</td>
</tr>
</tbody>
</table>
</div>
<br>
<%
}
%>
<form action="rest-api.jsp?save" method="post">
<fieldset>
<legend>REST API</legend>
<div>
<p>
The REST API can be secured with a shared secret key defined below
or a with HTTP basic authentication.<br />Moreover, for extra
security you can specify the list of IP addresses that are allowed
to use this service.<br />An empty list means that the service can
be accessed from any location. Addresses are delimited by commas.
</p>
<ul>
<input type="radio" name="enabled" value="true" id="rb01"
<%=((enabled) ? "checked" : "")%>>
<label for="rb01"><b>Enabled</b> - REST API requests will
be processed.</label>
<br>
<input type="radio" name="enabled" value="false" id="rb02"
<%=((!enabled) ? "checked" : "")%>>
<label for="rb02"><b>Disabled</b> - REST API requests will
be ignored.</label>
<br>
<br>
<input type="radio" name="authtype" value="true"
id="http_basic_auth" <%=((httpBasicAuth) ? "checked" : "")%>>
<label for="http_basic_auth">HTTP basic auth - REST API
authentication with Openfire admin account.</label>
<br>
<input type="radio" name="authtype" value="false"
id="secretKeyAuth" <%=((!httpBasicAuth) ? "checked" : "")%>>
<label for="secretKeyAuth">Secret key auth - REST API
authentication over specified secret key.</label>
<br>
<label style="padding-left: 25px" for="text_secret">Secret
key:</label>
<input type="text" name="secret" value="<%=secret%>"
id="text_secret">
<br>
<br>
<label for="allowedIPs">Allowed IP Addresses:</label>
<textarea name="allowedIPs" cols="40" rows="3" wrap="virtual"><%=((allowedIPs != null) ? allowedIPs : "")%></textarea>
</ul>
<p>You can find here detailed documentation over the Openfire REST API:
<a
href="/plugin-admin.jsp?plugin=restapi&showReadme=true&decorator=none">REST
API Documentation</a>
</p>
</div>
</fieldset>
<br> <br> <input type="submit" value="Save Settings">
</form>
</body>
</html>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment