/**
* LibreSource
* Copyright (C) 2004-2008 Artenum SARL / INRIA
* http://www.libresource.org - contact@artenum.com
*
* This file is part of the LibreSource software,
* which can be used and distributed under license conditions.
* The license conditions are provided in the LICENSE.TXT file
* at the root path of the packaging that enclose this file.
* More information can be found at
* - http://dev.libresource.org/home/license
*
* Initial authors :
*
* Guillaume Bort / INRIA
* Francois Charoy / Universite Nancy 2
* Julien Forest / Artenum
* Claude Godart / Universite Henry Poincare
* Florent Jouille / INRIA
* Sebastien Jourdain / INRIA / Artenum
* Yves Lerumeur / Artenum
* Pascal Molli / Universite Henry Poincare
* Gerald Oster / INRIA
* Mariarosa Penzi / Artenum
* Gerard Sookahet / Artenum
* Raphael Tani / INRIA
*
* Contributors :
*
* Stephane Bagnier / Artenum
* Amadou Dia / Artenum-IUP Blois
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
package org.libresource;
import org.libresource.kernel.KernelConstants;
import org.libresource.kernel.interfaces.KernelService;
import org.libresource.search.LibresourceIndexableContent;
import org.libresource.search.LibresourceResourceDocument;
import org.libresource.search.LibresourceSearch;
import java.lang.reflect.Method;
import java.net.URI;
import java.security.Principal;
import java.security.acl.Group;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import java.util.Properties;
import java.util.Vector;
import javax.jms.Message;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.mail.Session;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import javax.security.auth.callback.CallbackHandler;
import javax.sql.DataSource;
/**
* LibreSource
*
* @author <a href="mailto:bort@loria.fr">Guillaume Bort</a> - <a
* href="http://www.inria.fr">INRIA Lorraine</a>
*/
public class Libresource {
public final static String ID_REGEXP = "[^A-Za-z0-9-_]+";
private final static String SERVER_NAME = "libresource.server";
private final static String SERVER_NAME_JONAS = "jonas";
private final static String SERVER_NAME_JBOSS = "jboss";
static private Context jndi;
static private Hashtable homesCache = new Hashtable();
static private Hashtable proxy = new Hashtable();
static private Hashtable references = new Hashtable();
private static Topic eventsTopic;
private static Topic indexationTopic;
private static TopicConnectionFactory connectionFactory;
private static DataSource dataSource;
private static SimpleDateFormat dateFormater;
//
private static Properties lsConfig;
static private Context getJndiContext() throws NamingException {
if (jndi == null) {
jndi = new InitialContext();
}
return jndi;
}
static public LibresourceResourceLocal findResource(LibresourceResourceIdentifier resourceIdentifier)
throws LibresourceException {
try {
if (references.get(resourceIdentifier.serialize()) != null) {
return (LibresourceResourceLocal) references.get(resourceIdentifier.serialize());
}
String jndiName = LibresourceNamingConvention.getJndiNameForResource(resourceIdentifier.getService(), resourceIdentifier.getResourceType());
if (homesCache.get(jndiName) == null) {
LibresourceResourceLocalHome resourceLocalHome = (LibresourceResourceLocalHome) getJndiContext().lookup(jndiName);
homesCache.put(jndiName, resourceLocalHome);
}
LibresourceResourceLocalHome resourceLocalHome = (LibresourceResourceLocalHome) homesCache.get(jndiName);
Class[] types = { Class.forName("java.lang.String") };
Object[] params = { resourceIdentifier.getResourceId() };
Method method = resourceLocalHome.getClass().getMethod("findByPrimaryKey", types);
LibresourceResourceLocal resourceLocal = (LibresourceResourceLocal) method.invoke(resourceLocalHome, params);
references.put(resourceIdentifier.serialize(), resourceLocal);
return resourceLocal;
} catch (NamingException e) {
throw new LibresourceException("Can't find resource " + resourceIdentifier, e);
} catch (Exception e) {
throw new LibresourceException("Can't find resource " + resourceIdentifier, e);
}
}
static public LibresourceResourceLocal findResource(LibresourceResourceIdentifier resourceIdentifier, Class localInterfaceType)
throws LibresourceException {
checkType(resourceIdentifier, localInterfaceType);
return findResource(resourceIdentifier);
}
static public String[] listAvailablesPermissions(LibresourceResourceIdentifier resourceIdentifier)
throws LibresourceException {
try {
if (resourceIdentifier == null) {
return null;
}
return getService(resourceIdentifier.getService()).listAvailablesPermissions(resourceIdentifier);
} catch (Exception e) {
throw new LibresourceException(e);
}
}
static public String[] listAvailablesEvents(LibresourceResourceIdentifier resourceIdentifier)
throws LibresourceException {
try {
if (resourceIdentifier == null) {
return null;
}
return getService(resourceIdentifier.getService()).listAvailablesEvents(resourceIdentifier);
} catch (Exception e) {
throw new LibresourceException(e);
}
}
static public String getShortName(URI uri) throws LibresourceException {
try {
return ((KernelService) getService(KernelConstants.SERVICE)).getShortName(uri);
// return getShortName(((KernelService)
// getService("Kernel")).systemLookup(uri));
} catch (Exception e) {
throw new LibresourceException(e);
}
}
static public LibresourceService getService(String serviceName)
throws LibresourceException {
try {
if (proxy.get(serviceName) != null) {
return (LibresourceService) proxy.get(serviceName);
}
String jndiName = LibresourceNamingConvention.getJndiNameForService(serviceName);
if (homesCache.get(jndiName) == null) {
homesCache.put(jndiName, getJndiContext().lookup(jndiName));
}
LibresourceServiceHome libresourceServiceHome;
Object homeStub = homesCache.get(jndiName);
libresourceServiceHome = (LibresourceServiceHome) PortableRemoteObject.narrow(homeStub, LibresourceServiceHome.class);
LibresourceService libresourceService = libresourceServiceHome.create();
proxy.put(serviceName, libresourceService);
return libresourceService;
} catch (NamingException e) {
throw new LibresourceException("Can't find service " + serviceName, e);
} catch (Exception e) {
throw new LibresourceException("Can't create service " + serviceName, e);
}
}
static public void checkType(LibresourceResourceIdentifier resourceIdentifier, Class localInterface)
throws LibresourceException {
if (!LibresourceResourceLocal.class.isAssignableFrom(localInterface)) {
throw new LibresourceException(localInterface + " is not of type LibresourceResourceLocal");
}
try {
if (!resourceIdentifier.getService().equals(localInterface.getField("LIBRESOURCE_RESOURCE_SERVICE").get(null)) ||
!resourceIdentifier.getResourceType().equals(localInterface.getField("LIBRESOURCE_RESOURCE_TYPE").get(null))) {
throw new LibresourceException("Resource [" + resourceIdentifier + "] is not of type " +
localInterface.getField("LIBRESOURCE_RESOURCE_SERVICE").get(null) + "/" + localInterface.getField("LIBRESOURCE_RESOURCE_TYPE").get(null));
}
} catch (LibresourceException e) {
throw e;
} catch (Exception e) {
e.printStackTrace();
throw new LibresourceException("ERROR : " + e);
}
}
static public String[] listServices() throws LibresourceException {
try {
NamingEnumeration enumeration = getJndiContext().list("");
Vector result = new Vector();
while (enumeration.hasMoreElements()) {
String service = LibresourceNamingConvention.extractServiceName(((NameClassPair) enumeration.next()).getName());
if (service != null) {
result.add(service);
}
}
String[] resultS = new String[result.size()];
for (int i = 0; i < result.size(); i++) {
resultS[i] = (String) result.get(i);
}
return resultS;
} catch (Exception e) {
throw new LibresourceException("Can't list services", e);
}
}
static public void throwEvent(LibresourceEvent event)
throws LibresourceException {
try {
TopicConnectionFactory factory = getConnectionFactory();
Topic topic = getEventsTopic();
TopicConnection topicConnection = factory.createTopicConnection();
TopicSession topicSession = topicConnection.createTopicSession(true, javax.jms.Session.AUTO_ACKNOWLEDGE);
TopicPublisher topicPublisher = topicSession.createPublisher(topic);
Message message = topicSession.createMessage();
event.toMessage(message);
topicPublisher.publish(message);
topicPublisher.close();
topicSession.close();
topicConnection.close();
} catch (Exception e) {
}
}
static public void index(URI uri) throws LibresourceException {
try {
TopicConnectionFactory factory = getConnectionFactory();
Topic topic = getIndexationTopic();
TopicConnection topicConnection = factory.createTopicConnection();
TopicSession topicSession = topicConnection.createTopicSession(true, javax.jms.Session.AUTO_ACKNOWLEDGE);
TopicPublisher topicPublisher = topicSession.createPublisher(topic);
Message message = topicSession.createMessage();
message.setStringProperty("action", "index");
message.setStringProperty("uri", uri.toString());
topicPublisher.publish(message);
topicPublisher.close();
topicSession.close();
topicConnection.close();
} catch (Exception e) {
throw new LibresourceException("Error in index", e);
}
}
static public void removeFromIndex(URI uri) throws LibresourceException {
try {
TopicConnectionFactory factory = getConnectionFactory();
Topic topic = getIndexationTopic();
TopicConnection topicConnection = factory.createTopicConnection();
TopicSession topicSession = topicConnection.createTopicSession(true, javax.jms.Session.AUTO_ACKNOWLEDGE);
TopicPublisher topicPublisher = topicSession.createPublisher(topic);
Message message = topicSession.createMessage();
message.setStringProperty("action", "delete");
message.setStringProperty("uri", uri.toString());
topicPublisher.publish(message);
topicPublisher.close();
topicSession.close();
topicConnection.close();
} catch (Exception e) {
throw new LibresourceException("Error in removeFromIndex", e);
}
}
public static Topic getEventsTopic() throws NamingException {
if (eventsTopic == null) {
eventsTopic = (Topic) new InitialContext().lookup(getLibresourceConfiguration("event.topic.lookup"));
}
return eventsTopic;
}
public static Topic getIndexationTopic() throws NamingException {
if (indexationTopic == null) {
indexationTopic = (Topic) new InitialContext().lookup(getLibresourceConfiguration("indexation.topic.lookup"));
}
return indexationTopic;
}
public static TopicConnectionFactory getConnectionFactory()
throws NamingException {
if (connectionFactory == null) {
connectionFactory = (TopicConnectionFactory) new InitialContext().lookup(getLibresourceConfiguration("topic.connection.factory"));
}
return connectionFactory;
}
public static DataSource getDatasource() throws NamingException {
if (dataSource == null) {
dataSource = (DataSource) new InitialContext().lookup(getLibresourceConfiguration("libresource.datasource"));
}
return dataSource;
}
public static String formatDate(Date date) {
if (dateFormater == null) {
dateFormater = new SimpleDateFormat("dd-MM-yy HH:mm:ss");
}
if (date == null) {
return dateFormater.format(new Date());
}
return dateFormater.format(date);
}
public static Date parseDate(String date) throws ParseException {
if (dateFormater == null) {
dateFormater = new SimpleDateFormat("dd-MM-yy HH:mm:ss");
}
if ((date == null) || (date.trim().length() == 0)) {
return new Date();
}
try {
return dateFormater.parse(date);
} catch (Exception e) {
System.out.println("Impossible de parser la date: " + date);
return new Date();
}
}
public static String getLibresourceConfiguration(String key) {
if (lsConfig == null) {
synchronized (Libresource.class) {
if (lsConfig == null) {
try {
// Try for Jonas first
lsConfig = ((Session) PortableRemoteObject.narrow(new InitialContext().lookup("libresourceConfig"), Session.class)).getProperties();
} catch (Exception eJonas) {
try {
// Try for JBoss
lsConfig = ((Session) PortableRemoteObject.narrow(new InitialContext().lookup("java:/libresourceConfig"), Session.class)).getProperties();
} catch (Exception eJBoss) {
throw new RuntimeException("Unable to load the LibreSource configuration file.");
}
}
}
}
}
return lsConfig.getProperty(key);
}
public static URI getAbsoluteURI(URI contextUri, String uriToTransform)
throws Exception {
uriToTransform = uriToTransform.trim();
URI workingURI = new URI(uriToTransform).normalize();
String query = workingURI.getQuery();
String path = null;
if ((contextUri == null) || ((uriToTransform.length() != 0) && uriToTransform.startsWith("/"))) {
path = new URI(uriToTransform).normalize().getPath();
} else {
path = new URI(contextUri.getPath() + "/" + uriToTransform).normalize().getPath();
}
if (path.endsWith("/")) {
path = path.substring(0, path.length() - 1);
}
if (query != null) {
return new URI(path + "?" + query);
}
return new URI(path);
}
public static String convertStringToId(String name) {
return name.replaceAll(ID_REGEXP, "_");
}
public static CallbackHandler buildCallBackHandler(String login, String password) {
CallbackHandler result = null;
try {
if (getLibresourceConfiguration(SERVER_NAME).equals(SERVER_NAME_JONAS)) {
result = (CallbackHandler) Class.forName("org.objectweb.jonas.security.auth.callback.NoInputCallbackHandler")
.getConstructor(new Class[] { String.class, String.class }).newInstance(new Object[] { login, password });
} else { // if
// (getLibresourceConfiguration("libresource.server").equals("jboss"))
// {
result = (CallbackHandler) Class.forName("org.jboss.security.auth.callback.AppCallbackHandler")
.getConstructor(new Class[] { String.class, char[].class }).newInstance(new Object[] {
login, password.toCharArray()
});
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static Principal buildPrincipal(String principal) {
Principal result = null;
try {
if (getLibresourceConfiguration(SERVER_NAME).equals(SERVER_NAME_JONAS)) {
result = (Principal) Class.forName("org.objectweb.jonas.security.auth.JPrincipal").getConstructor(new Class[] { String.class }).newInstance(new Object[] {
principal
});
} else { // if
// (getLibresourceConfiguration("libresource.server").equals("jboss"))
// {
result = (Principal) Class.forName("org.jboss.security.NestablePrincipal").getConstructor(new Class[] { String.class }).newInstance(new Object[] {
principal
});
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static Group buildGroup(String role) {
Group result = null;
try {
if (getLibresourceConfiguration(SERVER_NAME).equals(SERVER_NAME_JONAS)) {
result = (Group) Class.forName("org.objectweb.jonas.security.auth.JGroup").getConstructor(new Class[] { String.class }).newInstance(new Object[] {
role
});
} else { // if
// (getLibresourceConfiguration("libresource.server").equals("jboss"))
// {
result = (Group) Class.forName("org.jboss.security.NestableGroup").getConstructor(new Class[] { String.class }).newInstance(new Object[] { role });
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
|