log4j.rootLogger=WARN, development
log4j.logger.org.argeo=DEBUG
-log4j.logger.org.argeo.cms.internal=TRACE
-log4j.logger.org.argeo.cms.viewers=TRACE
## Appenders
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
-log4j.appender.console.layout.ConversionPattern= %-5p %d{ISO8601} %m - %c - [%t]%n
+log4j.appender.console.layout.ConversionPattern= %-5p %d{ISO8601} %m %n
log4j.appender.development=org.apache.log4j.ConsoleAppender
log4j.appender.development.layout=org.apache.log4j.PatternLayout
<groupId>org.argeo.tp.misc</groupId>
<artifactId>org.slf4j.commons.logging</artifactId>
</dependency>
+
<dependency>
<groupId>org.argeo.tp.bouncycastle</groupId>
<artifactId>bcprov</artifactId>
<groupId>org.argeo.tp.bouncycastle</groupId>
<artifactId>bcpg</artifactId>
</dependency>
+
<dependency>
<groupId>org.argeo.tp.apache</groupId>
<artifactId>org.apache.httpcomponents.httpcore</artifactId>
</dependency>
<!-- Misc Third Parties -->
- <dependency>
- <groupId>org.argeo.tp.bouncycastle</groupId>
- <artifactId>bcmail</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.bouncycastle</groupId>
- <artifactId>bcpg</artifactId>
- </dependency>
+<!-- <dependency> -->
+<!-- <groupId>org.argeo.tp.bouncycastle</groupId> -->
+<!-- <artifactId>bcmail</artifactId> -->
+<!-- </dependency> -->
+<!-- <dependency> -->
+<!-- <groupId>org.argeo.tp.bouncycastle</groupId> -->
+<!-- <artifactId>bcpg</artifactId> -->
+<!-- </dependency> -->
<dependency>
<groupId>org.argeo.tp.apache.ant</groupId>
<artifactId>org.apache.ant</artifactId>
<!-- <groupId>org.argeo.tp.misc</groupId> -->
<!-- <artifactId>org.quartz-scheduler.quartz.jobs</artifactId> -->
<!-- </dependency> -->
- <dependency>
- <groupId>org.argeo.tp.javax</groupId>
- <artifactId>javax.mail</artifactId>
- </dependency>
+<!-- <dependency> -->
+<!-- <groupId>org.argeo.tp.javax</groupId> -->
+<!-- <artifactId>javax.mail</artifactId> -->
+<!-- </dependency> -->
<!-- Nebula -->
<dependency>
<artifactId>org.eclipse.rap.nebula.jface.gridviewer</artifactId>
</dependency>
-
- <!-- Spring -->
- <dependency>
- <groupId>org.argeo.tp.spring</groupId>
- <artifactId>org.springframework.aspects</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.spring</groupId>
- <artifactId>org.springframework.context.support</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.spring</groupId>
- <artifactId>org.springframework.jdbc</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.spring</groupId>
- <artifactId>org.springframework.tx</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.spring</groupId>
- <artifactId>org.springframework.web</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.spring</groupId>
- <artifactId>org.springframework.web.servlet</artifactId>
- </dependency>
-
<!-- Eclipse Core -->
<dependency>
<groupId>org.argeo.tp.rap.e4</groupId>
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.argeo.commons</groupId>
<!-- CMS Dependencies -->
<!-- TODO: not bitronix dependent -->
- <dependency>
- <groupId>org.argeo.tp.misc</groupId>
- <artifactId>bitronix.tm</artifactId>
- </dependency>
+ <!-- <dependency> -->
+ <!-- <groupId>org.argeo.tp.misc</groupId> -->
+ <!-- <artifactId>bitronix.tm</artifactId> -->
+ <!-- </dependency> -->
<!-- <dependency> -->
<!-- <groupId>org.argeo.tp.misc</groupId> -->
<!-- <artifactId>org.joda.time</artifactId> -->
</dependency>
- <!-- TODO: remove Spring dependency -->
- <dependency>
- <groupId>org.argeo.tp.spring</groupId>
- <artifactId>org.springframework.beans</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.spring</groupId>
- <artifactId>org.springframework.core</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.javax</groupId>
- <artifactId>javax.el</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.gemini</groupId>
- <artifactId>org.eclipse.gemini.blueprint.core</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.gemini</groupId>
- <artifactId>org.eclipse.gemini.blueprint.extender</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.gemini</groupId>
- <artifactId>org.eclipse.gemini.blueprint.io</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.misc</groupId>
- <artifactId>org.aspectj.weaver</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.misc</groupId>
- <artifactId>org.aopalliance</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.spring</groupId>
- <artifactId>org.springframework.aop</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.spring</groupId>
- <artifactId>org.springframework.context</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.spring</groupId>
- <artifactId>org.springframework.expression</artifactId>
- </dependency>
- <dependency>
- <groupId>org.argeo.tp.spring</groupId>
- <artifactId>org.springframework.instrument</artifactId>
- </dependency>
-
<!-- HTTP Server -->
<dependency>
<groupId>org.argeo.tp.equinox</groupId>
<artifactId>javax.mail</artifactId>
</dependency>
+ <!-- Base Spring dependency -->
+ <dependency>
+ <groupId>org.argeo.tp.spring</groupId>
+ <artifactId>org.springframework.beans</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.argeo.tp.spring</groupId>
+ <artifactId>org.springframework.core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.argeo.tp.javax</groupId>
+ <artifactId>javax.el</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.argeo.tp.gemini</groupId>
+ <artifactId>org.eclipse.gemini.blueprint.core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.argeo.tp.gemini</groupId>
+ <artifactId>org.eclipse.gemini.blueprint.extender</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.argeo.tp.gemini</groupId>
+ <artifactId>org.eclipse.gemini.blueprint.io</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.argeo.tp.misc</groupId>
+ <artifactId>org.aspectj.weaver</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.argeo.tp.misc</groupId>
+ <artifactId>org.aopalliance</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.argeo.tp.spring</groupId>
+ <artifactId>org.springframework.aop</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.argeo.tp.spring</groupId>
+ <artifactId>org.springframework.context</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.argeo.tp.spring</groupId>
+ <artifactId>org.springframework.expression</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.argeo.tp.spring</groupId>
+ <artifactId>org.springframework.instrument</artifactId>
+ </dependency>
+
<!-- Spring -->
<dependency>
<groupId>org.argeo.tp.spring</groupId>
<implementation class="org.argeo.cms.e4.rap.CmsE4AdminApp"/>
<service>
<provide interface="org.eclipse.rap.rwt.application.ApplicationConfiguration"/>
- <property name="contextName" type="String" value="cmsXXX"/>
+ <property name="contextName" type="String" value="cms"/>
</service>
</scr:component>
Bundle-ActivationPolicy: lazy
-#Service-Component: OSGI-INF/cms-admin-rap.xml,\
+Service-Component: OSGI-INF/cms-admin-rap.xml
#OSGI-INF/cms-demo-rap.xml
-Bundle-Activator: org.argeo.cms.script.ScriptAppActivator
+#Bundle-Activator: org.argeo.cms.script.ScriptAppActivator
Import-Package: org.argeo.node,\
org.eclipse.swt,\
org.eclipse.swt.graphics,\
org.eclipse.e4.ui.workbench,\
org.eclipse.rap.rwt.client,\
-org.argeo.cms.script,\
org.eclipse.nebula.widgets.richtext;resolution:=optional,\
*
public class CmsE4AdminApp extends AbstractRapE4App {
public CmsE4AdminApp() {
- setPageTitle("CMS Admin");
+ setPageTitle("Argeo CMS DevOps");
setE4Xmi("org.argeo.cms.e4/e4xmi/cms-devops.e4xmi");
setPath("/devops");
}
org.eclipse.e4.ui.model.application.ui,\
org.eclipse.e4.ui.model.application,\
javax.jcr.nodetype,\
+org.argeo.cms,\
org.argeo.jcr.docbook,\
org.eclipse.core.commands.common,\
org.eclipse.jface.window,\
org.argeo.cms.widgets.auth,\
-org.argeo.cms.i18n,\
*
@Override
protected void extendsCredentialsBlock(Composite credentialsBlock, Locale selectedLocale,
SelectionListener loginSelectionListener) {
- Button loginButton = new Button(credentialsBlock, SWT.PUSH);
- loginButton.setText(CmsMsg.login.lead(selectedLocale));
- loginButton.setLayoutData(CmsUtils.fillWidth());
- loginButton.addSelectionListener(loginSelectionListener);
+// Button loginButton = new Button(credentialsBlock, SWT.PUSH);
+// loginButton.setText(CmsMsg.login.lead(selectedLocale));
+// loginButton.setLayoutData(CmsUtils.fillWidth());
+// loginButton.addSelectionListener(loginSelectionListener);
}
@Override
@Override
protected void extendsCredentialsBlock(Composite credentialsBlock, Locale selectedLocale,
SelectionListener loginSelectionListener) {
- Button loginButton = new Button(credentialsBlock, SWT.PUSH);
- loginButton.setText(CmsMsg.login.lead(selectedLocale));
- loginButton.setLayoutData(CmsUtils.fillWidth());
- loginButton.addSelectionListener(loginSelectionListener);
+// Button loginButton = new Button(credentialsBlock, SWT.PUSH);
+// loginButton.setText(CmsMsg.login.lead(selectedLocale));
+// loginButton.setLayoutData(CmsUtils.fillWidth());
+// loginButton.addSelectionListener(loginSelectionListener);
}
@Override
org.eclipse.core.commands
Import-Package: org.argeo.cms.auth,\
+org.argeo.cms,\
org.argeo.cms.ui,\
-org.argeo.cms.i18n,\
org.argeo.eclipse.spring,\
org.argeo.eclipse.ui.utils,\
org.eclipse.core.runtime.jobs,\
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * 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.
+ */
+package org.argeo.cms.spring;
+
+import javax.security.auth.Subject;
+import javax.security.auth.login.LoginContext;
+import javax.security.auth.login.LoginException;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.cms.CmsException;
+import org.argeo.node.NodeConstants;
+
+/** Provides base method for executing code with system authorization. */
+abstract class AbstractSystemExecution {
+ private final static Log log = LogFactory.getLog(AbstractSystemExecution.class);
+ private final Subject subject = new Subject();
+
+ /** Authenticate the calling thread */
+ protected void authenticateAsSystem() {
+ ClassLoader origClassLoader = Thread.currentThread().getContextClassLoader();
+ Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
+ try {
+ LoginContext lc = new LoginContext(NodeConstants.LOGIN_CONTEXT_DATA_ADMIN, subject);
+ lc.login();
+ } catch (LoginException e) {
+ throw new CmsException("Cannot login as system", e);
+ } finally {
+ Thread.currentThread().setContextClassLoader(origClassLoader);
+ }
+ if (log.isTraceEnabled())
+ log.trace("System authenticated");
+ }
+
+ protected void deauthenticateAsSystem() {
+ ClassLoader origClassLoader = Thread.currentThread().getContextClassLoader();
+ Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
+ try {
+ LoginContext lc = new LoginContext(NodeConstants.LOGIN_CONTEXT_DATA_ADMIN, subject);
+ lc.logout();
+ } catch (LoginException e) {
+ throw new CmsException("Cannot logout as system", e);
+ } finally {
+ Thread.currentThread().setContextClassLoader(origClassLoader);
+ }
+ }
+
+ protected Subject getSubject() {
+ return subject;
+ }
+}
--- /dev/null
+/*
+ * Copyright (C) 2007-2012 Argeo GmbH
+ *
+ * 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.
+ */
+package org.argeo.cms.spring;
+
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.security.auth.Subject;
+
+import org.eclipse.gemini.blueprint.context.DependencyInitializationAwareBeanPostProcessor;
+import org.springframework.beans.BeansException;
+import org.springframework.beans.factory.support.AbstractBeanFactory;
+import org.springframework.beans.factory.support.SecurityContextProvider;
+import org.springframework.beans.factory.support.SimpleSecurityContextProvider;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.ApplicationContextAware;
+
+/**
+ * Executes with a system authentication the instantiation and initialization
+ * methods of the application context where it has been defined.
+ */
+public class AuthenticatedApplicationContextInitialization extends
+ AbstractSystemExecution implements
+ DependencyInitializationAwareBeanPostProcessor, ApplicationContextAware {
+ /** If non empty, restricts to these beans */
+ private List<String> beanNames = new ArrayList<String>();
+
+ public Object postProcessBeforeInitialization(Object bean, String beanName)
+ throws BeansException {
+ if (beanNames.size() == 0 || beanNames.contains(beanName))
+ authenticateAsSystem();
+ return bean;
+ }
+
+ public Object postProcessAfterInitialization(Object bean, String beanName)
+ throws BeansException {
+ if (beanNames.size() == 0 || beanNames.contains(beanName))
+ deauthenticateAsSystem();
+ return bean;
+ }
+
+ public void setBeanNames(List<String> beanNames) {
+ this.beanNames = beanNames;
+ }
+
+ @Override
+ public void setApplicationContext(ApplicationContext applicationContext)
+ throws BeansException {
+ if (applicationContext.getAutowireCapableBeanFactory() instanceof AbstractBeanFactory) {
+ final AbstractBeanFactory beanFactory = ((AbstractBeanFactory) applicationContext
+ .getAutowireCapableBeanFactory());
+ // retrieve subject's access control context
+ // and set it as the bean factory security context
+ Subject.doAs(getSubject(), new PrivilegedAction<Void>() {
+ @Override
+ public Void run() {
+ SecurityContextProvider scp = new SimpleSecurityContextProvider(
+ AccessController.getContext());
+ beanFactory.setSecurityContextProvider(scp);
+ return null;
+ }
+ });
+ }
+ }
+}
--- /dev/null
+package org.argeo.cms.spring;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import javax.naming.InvalidNameException;
+import javax.naming.ldap.LdapName;
+import javax.transaction.UserTransaction;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.argeo.cms.CmsException;
+import org.osgi.service.useradmin.Role;
+import org.osgi.service.useradmin.UserAdmin;
+
+/**
+ * Register one or many roles via a user admin service. Does nothing if the role
+ * is already registered.
+ */
+public class SimpleRoleRegistration implements Runnable {
+ private final static Log log = LogFactory
+ .getLog(SimpleRoleRegistration.class);
+
+ private String role;
+ private List<String> roles = new ArrayList<String>();
+ private UserAdmin userAdmin;
+ private UserTransaction userTransaction;
+
+ @Override
+ public void run() {
+ try {
+ userTransaction.begin();
+ if (role != null && !roleExists(role))
+ newRole(toDn(role));
+
+ for (String r : roles)
+ if (!roleExists(r))
+ newRole(toDn(r));
+ userTransaction.commit();
+ } catch (Exception e) {
+ try {
+ userTransaction.rollback();
+ } catch (Exception e1) {
+ log.error("Cannot rollback", e1);
+ }
+ throw new CmsException("Cannot add roles", e);
+ }
+ }
+
+ private boolean roleExists(String role) {
+ return userAdmin.getRole(toDn(role).toString()) != null;
+ }
+
+ protected void newRole(LdapName r) {
+ userAdmin.createRole(r.toString(), Role.GROUP);
+ log.info("Added role " + r + " required by application.");
+ }
+
+ public void register(UserAdmin userAdminService, Map<?, ?> properties) {
+ this.userAdmin = userAdminService;
+ run();
+ }
+
+ protected LdapName toDn(String name) {
+ try {
+ return new LdapName("cn=" + name + ",ou=roles,ou=node");
+ } catch (InvalidNameException e) {
+ throw new CmsException("Badly formatted role name " + name, e);
+ }
+ }
+
+ public void setRole(String role) {
+ this.role = role;
+ }
+
+ public void setRoles(List<String> roles) {
+ this.roles = roles;
+ }
+
+ public void setUserAdmin(UserAdmin userAdminService) {
+ this.userAdmin = userAdminService;
+ }
+
+ public void setUserTransaction(UserTransaction userTransaction) {
+ this.userTransaction = userTransaction;
+ }
+
+}
--- /dev/null
+package org.argeo.cms.spring.osgi;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.Constants;
+
+/**
+ * Logs the name and version of an OSGi bundle based on its
+ * {@link BundleContext}.
+ */
+public class OsgiModuleLabel {
+ private final static Log log = LogFactory.getLog(OsgiModuleLabel.class);
+
+ private Bundle bundle;
+
+ public OsgiModuleLabel() {
+ }
+
+ /** Sets without logging. */
+ public OsgiModuleLabel(Bundle bundle) {
+ this.bundle = bundle;
+ }
+
+ /**
+ * Retrieved bundle from a bundle context and logs it. Typically to be set
+ * as a Spring bean.
+ */
+ public void setBundleContext(BundleContext bundleContext) {
+ this.bundle = bundleContext.getBundle();
+ log.info(msg());
+ }
+
+ public String msg() {
+ String name = bundle.getHeaders().get(Constants.BUNDLE_NAME).toString();
+ String symbolicName = bundle.getSymbolicName();
+ String version = bundle.getVersion().toString();
+ return name + " v" + version + " (" + symbolicName + ")";
+ }
+}
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
-import javax.activation.MimetypesFileTypeMap;
import javax.jcr.Binary;
import javax.jcr.Node;
import javax.jcr.Property;
/** Manages only public images so far. */
public class ImageManagerImpl implements CmsImageManager, CmsNames {
private final static Log log = LogFactory.getLog(ImageManagerImpl.class);
- private MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap();
+// private MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap();
- public Boolean load(Node node, Control control, Point preferredSize)
- throws RepositoryException {
+ public Boolean load(Node node, Control control, Point preferredSize) throws RepositoryException {
Point imageSize = getImageSize(node);
Point size;
String imgTag = null;
size = imageSize;
} else {
// no image if not completely known
- size = resizeTo(NO_IMAGE_SIZE,
- preferredSize != null ? preferredSize : imageSize);
+ size = resizeTo(NO_IMAGE_SIZE, preferredSize != null ? preferredSize : imageSize);
imgTag = CmsUtils.noImg(size);
}
} else if (constraints.x == 0 && constraints.y == 0) {
return orig;
} else if (constraints.y == 0) {// force width
- return new Point(constraints.x,
- scale(orig.y, orig.x, constraints.x));
+ return new Point(constraints.x, scale(orig.y, orig.x, constraints.x));
} else if (constraints.x == 0) {// force height
- return new Point(scale(orig.x, orig.y, constraints.y),
- constraints.y);
+ return new Point(scale(orig.x, orig.y, constraints.y), constraints.y);
}
throw new CmsException("Cannot resize " + orig + " to " + constraints);
}
private int scale(int origDimension, int otherDimension, int otherConstraint) {
- return Math.round(origDimension
- * divide(otherConstraint, otherDimension));
+ return Math.round(origDimension * divide(otherConstraint, otherDimension));
}
private float divide(int a, int b) {
}
public Point getImageSize(Node node) throws RepositoryException {
- return new Point(node.hasProperty(CMS_IMAGE_WIDTH) ? (int) node
- .getProperty(CMS_IMAGE_WIDTH).getLong() : 0,
- node.hasProperty(CMS_IMAGE_WIDTH) ? (int) node.getProperty(
- CMS_IMAGE_HEIGHT).getLong() : 0);
+ return new Point(node.hasProperty(CMS_IMAGE_WIDTH) ? (int) node.getProperty(CMS_IMAGE_WIDTH).getLong() : 0,
+ node.hasProperty(CMS_IMAGE_WIDTH) ? (int) node.getProperty(CMS_IMAGE_HEIGHT).getLong() : 0);
}
/** @return null if not available */
return getImageTag(node, getImageSize(node));
}
- private String getImageTag(Node node, Point size)
- throws RepositoryException {
+ private String getImageTag(Node node, Point size) throws RepositoryException {
StringBuilder buf = getImageTagBuilder(node, size);
if (buf == null)
return null;
/** @return null if not available */
@Override
- public StringBuilder getImageTagBuilder(Node node, Point size)
- throws RepositoryException {
- return getImageTagBuilder(node, Integer.toString(size.x),
- Integer.toString(size.y));
+ public StringBuilder getImageTagBuilder(Node node, Point size) throws RepositoryException {
+ return getImageTagBuilder(node, Integer.toString(size.x), Integer.toString(size.y));
}
/** @return null if not available */
- private StringBuilder getImageTagBuilder(Node node, String width,
- String height) throws RepositoryException {
+ private StringBuilder getImageTagBuilder(Node node, String width, String height) throws RepositoryException {
String url = getImageUrl(node);
if (url == null)
return null;
}
@Override
- public String uploadImage(Node parentNode, String fileName, InputStream in)
- throws RepositoryException {
+ public String uploadImage(Node parentNode, String fileName, InputStream in) throws RepositoryException {
InputStream inputStream = null;
try {
String previousResourceName = null;
ImageData id = new ImageData(inputStream);
fileNode.setProperty(CMS_IMAGE_WIDTH, id.width);
fileNode.setProperty(CMS_IMAGE_HEIGHT, id.height);
- fileNode.setProperty(Property.JCR_MIMETYPE,
- fileTypeMap.getContentType(fileName));
+ String mime = Files.probeContentType(Paths.get(fileName));
+ fileNode.setProperty(Property.JCR_MIMETYPE, mime);
fileNode.getSession().save();
// reset resource manager
ResourceManager resourceManager = RWT.getResourceManager();
- if (previousResourceName != null
- && resourceManager.isRegistered(previousResourceName)) {
+ if (previousResourceName != null && resourceManager.isRegistered(previousResourceName)) {
resourceManager.unregister(previousResourceName);
if (log.isDebugEnabled())
log.debug("Unregistered image " + previousResourceName);
}
return getImageUrl(fileNode);
} catch (IOException e) {
- throw new CmsException("Cannot upload image " + fileName + " in "
- + parentNode, e);
+ throw new CmsException("Cannot upload image " + fileName + " in " + parentNode, e);
} finally {
IOUtils.closeQuietly(inputStream);
}
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.argeo.cms.CmsMsg;
+import org.argeo.cms.LocaleUtils;
import org.argeo.cms.auth.HttpRequestCallback;
-import org.argeo.cms.i18n.LocaleUtils;
import org.argeo.cms.ui.CmsStyles;
import org.argeo.cms.ui.CmsView;
import org.argeo.cms.ui.internal.Activator;
passwordT.addTraverseListener(tl);
parent.setTabList(new Control[] { credentialsBlock });
credentialsBlock.setTabList(new Control[] { usernameT, passwordT });
- // credentialsBlock.setFocus();
+
+ // Button
+ Button loginButton = new Button(credentialsBlock, SWT.PUSH);
+ loginButton.setText(CmsMsg.login.lead(locale));
+ loginButton.setLayoutData(CmsUtils.fillWidth());
+ loginButton.addSelectionListener(loginSelectionListener);
extendsCredentialsBlock(credentialsBlock, locale, loginSelectionListener);
if (localeChoice != null)
import javax.security.auth.callback.LanguageCallback;
import org.argeo.cms.CmsException;
-import org.argeo.cms.i18n.LocaleUtils;
+import org.argeo.cms.LocaleUtils;
/** Choose in a list of locales. TODO: replace with {@link LanguageCallback} */
public class LocaleChoice {
org.postgresql;resolution:=optional,\
org.apache.jackrabbit.webdav.server,\
org.apache.jackrabbit.webdav.jcr,\
-org.springframework.context;resolution:=optional,\
-org.springframework.core.io;resolution:=optional,\
-org.springframework.*;resolution:=optional,\
-org.eclipse.gemini.blueprint.*;resolution:=optional\
org.apache.commons.httpclient.cookie;resolution:=optional,\
org.osgi.*;version=0.0.0,\
*
<artifactId>org.argeo.enterprise</artifactId>
<version>2.1.77-SNAPSHOT</version>
</dependency>
+ <dependency>
+ <groupId>org.argeo.commons</groupId>
+ <artifactId>org.argeo.core</artifactId>
+ <version>2.1.77-SNAPSHOT</version>
+ </dependency>
<dependency>
<groupId>org.argeo.commons</groupId>
<artifactId>org.argeo.eclipse.ui</artifactId>
package org.argeo.cms;
-import org.argeo.cms.i18n.Localized;
-
public enum CmsMsg implements Localized {
username, password, login, logout, register,
// password
--- /dev/null
+package org.argeo.cms;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+import java.util.ResourceBundle;
+
+import org.argeo.cms.auth.CurrentUser;
+
+/** Utilities simplifying the development of localization enums. */
+public class LocaleUtils {
+ public static Object local(Enum<?> en) {
+ return local(en, getCurrentLocale(), "/OSGI-INF/l10n/bundle");
+ }
+
+ public static Object local(Enum<?> en, Locale locale) {
+ return local(en, locale, "/OSGI-INF/l10n/bundle");
+ }
+
+ public static Object local(Enum<?> en, Locale locale, String resource) {
+ return local(en, locale, resource, en.getClass().getClassLoader());
+ }
+
+ public static Object local(Enum<?> en, Locale locale, String resource, ClassLoader classLoader) {
+ ResourceBundle rb = ResourceBundle.getBundle(resource, locale, classLoader);
+ return rb.getString(en.name());
+ }
+
+ public static String lead(String raw, Locale locale) {
+ return raw.substring(0, 1).toUpperCase(locale) + raw.substring(1);
+ }
+
+ public static String lead(Localized localized) {
+ return lead(localized, getCurrentLocale());
+ }
+
+ public static String lead(Localized localized, Locale locale) {
+ return lead(localized.local(locale).toString(), locale);
+ }
+
+ static Locale getCurrentLocale() {
+ return CurrentUser.locale();
+ // return UiContext.getLocale();
+ // FIXME look into Subject or settings
+ // return Locale.getDefault();
+ }
+
+ /** Returns null if argument is null. */
+ public static List<Locale> asLocaleList(Object locales) {
+ if (locales == null)
+ return null;
+ ArrayList<Locale> availableLocales = new ArrayList<Locale>();
+ String[] codes = locales.toString().split(",");
+ for (int i = 0; i < codes.length; i++) {
+ String code = codes[i];
+ // variant not supported
+ int indexUnd = code.indexOf("_");
+ Locale locale;
+ if (indexUnd > 0) {
+ String language = code.substring(0, indexUnd);
+ String country = code.substring(indexUnd + 1);
+ locale = new Locale(language, country);
+ } else {
+ locale = new Locale(code);
+ }
+ availableLocales.add(locale);
+ }
+ return availableLocales;
+ }
+}
--- /dev/null
+package org.argeo.cms;
+
+import java.text.MessageFormat;
+import java.util.Locale;
+
+/** Localized object. */
+public interface Localized {
+ /** Default assumes that this is an {@link Enum} */
+ default Object local(Locale locale) {
+ return LocaleUtils.local((Enum<?>) this, locale);
+ }
+
+ default String lead() {
+ return LocaleUtils.lead(this);
+ }
+
+ default String format(Object[] args) {
+ Locale locale = LocaleUtils.getCurrentLocale();
+ MessageFormat format = new MessageFormat(local(locale).toString(), locale);
+ return format.format(args);
+ }
+
+ default String lead(Locale locale) {
+ return LocaleUtils.lead(local(locale).toString(), locale);
+ }
+
+}
package org.argeo.cms.i18n;
-import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
-import java.util.ResourceBundle;
import org.argeo.cms.auth.CurrentUser;
-/** Utilities simplifying the development of localization enums. */
+/**
+ * Utilities simplifying the development of localization enums.
+ *
+ * @deprecated Use {@link org.argeo.cms.LocaleUtils}
+ */
+@Deprecated
public class LocaleUtils {
public static Object local(Enum<?> en) {
- return local(en, getCurrentLocale(), "/OSGI-INF/l10n/bundle");
+ return org.argeo.cms.LocaleUtils.local(en);
}
public static Object local(Enum<?> en, Locale locale) {
- return local(en, locale, "/OSGI-INF/l10n/bundle");
+ return org.argeo.cms.LocaleUtils.local(en, locale);
}
public static Object local(Enum<?> en, Locale locale, String resource) {
- return local(en, locale, resource, en.getClass().getClassLoader());
+ return org.argeo.cms.LocaleUtils.local(en, locale, resource);
}
public static Object local(Enum<?> en, Locale locale, String resource, ClassLoader classLoader) {
- ResourceBundle rb = ResourceBundle.getBundle(resource, locale, classLoader);
- return rb.getString(en.name());
+ return org.argeo.cms.LocaleUtils.local(en, locale, resource, classLoader);
}
public static String lead(String raw, Locale locale) {
- return raw.substring(0, 1).toUpperCase(locale) + raw.substring(1);
+ return org.argeo.cms.LocaleUtils.lead(raw, locale);
}
public static String lead(Localized localized) {
- return lead(localized, getCurrentLocale());
+ return org.argeo.cms.LocaleUtils.lead(localized);
}
public static String lead(Localized localized, Locale locale) {
- return lead(localized.local(locale).toString(), locale);
+ return org.argeo.cms.LocaleUtils.lead(localized, locale);
}
static Locale getCurrentLocale() {
/** Returns null if argument is null. */
public static List<Locale> asLocaleList(Object locales) {
- if (locales == null)
- return null;
- ArrayList<Locale> availableLocales = new ArrayList<Locale>();
- String[] codes = locales.toString().split(",");
- for (int i = 0; i < codes.length; i++) {
- String code = codes[i];
- // variant not supported
- int indexUnd = code.indexOf("_");
- Locale locale;
- if (indexUnd > 0) {
- String language = code.substring(0, indexUnd);
- String country = code.substring(indexUnd + 1);
- locale = new Locale(language, country);
- } else {
- locale = new Locale(code);
- }
- availableLocales.add(locale);
- }
- return availableLocales;
+ return org.argeo.cms.LocaleUtils.asLocaleList(locales);
}
}
package org.argeo.cms.i18n;
-import java.text.MessageFormat;
-import java.util.Locale;
-
-/** Localized object. */
-public interface Localized {
- /** Default assumes that this is an {@link Enum} */
- default Object local(Locale locale) {
- return LocaleUtils.local((Enum<?>) this, locale);
- }
-
- default String lead() {
- return LocaleUtils.lead(this);
- }
-
- default String format(Object[] args) {
- Locale locale = LocaleUtils.getCurrentLocale();
- MessageFormat format = new MessageFormat(local(locale).toString(), locale);
- return format.format(args);
- }
-
- default String lead(Locale locale) {
- return LocaleUtils.lead(local(locale).toString(), locale);
- }
-
+/**
+ * Localized object.
+ *
+ * @deprecated Use {@link org.argeo.cms.Localized} instead.
+ */
+@Deprecated
+public interface Localized extends org.argeo.cms.Localized {
}
RepositoryContext repositoryContext = RepositoryContext.create(repositoryConfig);
double duration = ((double) (System.currentTimeMillis() - begin)) / 1000;
- if (log.isTraceEnabled())
- log.trace(
+ if (log.isDebugEnabled())
+ log.debug(
"Created Jackrabbit repository in " + duration + " s, home: " + repositoryConfig.getHomeDir());
return repositoryContext;
userAdminSt = new ServiceTracker<>(instance.bc, UserAdmin.class, null);
userAdminSt.open();
- log.debug("Kernel bundle started");
+ if (log.isTraceEnabled())
+ log.trace("Kernel bundle started");
} catch (Throwable e) {
log.error("## FATAL: CMS activator failed", e);
}
properties.put(Constants.SERVICE_RANKING, Integer.MAX_VALUE);
LocalRepository localRepository = new LocalRepository(repository, dataModelName);
bc.registerService(Repository.class, localRepository, properties);
- if (log.isDebugEnabled())
- log.debug("Published data model " + dataModelName);
+ if (log.isTraceEnabled())
+ log.trace("Published data model " + dataModelName);
}
@Override
Object cn = reference.getProperty(NodeConstants.CN);
if (cn != null && cn.equals(NodeConstants.HOME)) {
homeRepository = (HomeRepository) bc.getService(reference);
- if (log.isDebugEnabled())
- log.debug("Home repository is available");
+ if (log.isTraceEnabled())
+ log.trace("Home repository is available");
}
return super.addingService(reference);
}
package org.argeo.cms.internal.kernel;
-import java.io.IOException;
-
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkEvent;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.launch.Framework;
package org.argeo.cms.internal.kernel;
-import static bitronix.tm.TransactionManagerServices.getTransactionManager;
-import static bitronix.tm.TransactionManagerServices.getTransactionSynchronizationRegistry;
import static java.util.Locale.ENGLISH;
-import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.file.spi.FileSystemProvider;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
-import java.util.UUID;
import javax.jcr.RepositoryFactory;
import javax.transaction.TransactionManager;
-import javax.transaction.TransactionSynchronizationRegistry;
import javax.transaction.UserTransaction;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.argeo.cms.CmsException;
-import org.argeo.cms.i18n.LocaleUtils;
+import org.argeo.cms.LocaleUtils;
import org.argeo.node.NodeConstants;
import org.argeo.node.NodeState;
import org.argeo.transaction.simple.SimpleTransactionManager;
import org.argeo.util.LangUtils;
-import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.FrameworkUtil;
-import org.osgi.framework.ServiceReference;
import org.osgi.service.cm.ManagedServiceFactory;
-import bitronix.tm.BitronixTransactionManager;
-import bitronix.tm.BitronixTransactionSynchronizationRegistry;
-import bitronix.tm.TransactionManagerServices;
-
public class CmsState implements NodeState {
private final static Log log = LogFactory.getLog(CmsState.class);
private final BundleContext bc = FrameworkUtil.getBundle(CmsState.class).getBundleContext();
if (NodeConstants.TRANSACTION_MANAGER_SIMPLE.equals(tmType)) {
initSimpleTransactionManager();
} else if (NodeConstants.TRANSACTION_MANAGER_BITRONIX.equals(tmType)) {
- initBitronixTransactionManager();
+// initBitronixTransactionManager();
+ throw new UnsupportedOperationException(
+ "Bitronix is not supported anymore, but could be again if there is enough interest.");
} else {
throw new CmsException("Usupported transaction manager type " + tmType);
}
// TODO TransactionSynchronizationRegistry
}
- private void initBitronixTransactionManager() {
- // TODO manage it in a managed service, as startup could be long
- ServiceReference<TransactionManager> existingTm = bc.getServiceReference(TransactionManager.class);
- if (existingTm != null) {
- if (log.isDebugEnabled())
- log.debug("Using provided transaction manager " + existingTm);
- return;
- }
-
- if (!TransactionManagerServices.isTransactionManagerRunning()) {
- bitronix.tm.Configuration tmConf = TransactionManagerServices.getConfiguration();
- tmConf.setServerId(UUID.randomUUID().toString());
-
- Bundle bitronixBundle = FrameworkUtil.getBundle(bitronix.tm.Configuration.class);
- File tmBaseDir = bitronixBundle.getDataFile(KernelConstants.DIR_TRANSACTIONS);
- File tmDir1 = new File(tmBaseDir, "btm1");
- tmDir1.mkdirs();
- tmConf.setLogPart1Filename(new File(tmDir1, tmDir1.getName() + ".tlog").getAbsolutePath());
- File tmDir2 = new File(tmBaseDir, "btm2");
- tmDir2.mkdirs();
- tmConf.setLogPart2Filename(new File(tmDir2, tmDir2.getName() + ".tlog").getAbsolutePath());
- }
- BitronixTransactionManager transactionManager = getTransactionManager();
- stopHooks.add(() -> transactionManager.shutdown());
- BitronixTransactionSynchronizationRegistry transactionSynchronizationRegistry = getTransactionSynchronizationRegistry();
- // register
- bc.registerService(TransactionManager.class, transactionManager, null);
- bc.registerService(UserTransaction.class, transactionManager, null);
- bc.registerService(TransactionSynchronizationRegistry.class, transactionSynchronizationRegistry, null);
- if (log.isDebugEnabled())
- log.debug("Initialised default Bitronix transaction manager");
- }
+// private void initBitronixTransactionManager() {
+// // TODO manage it in a managed service, as startup could be long
+// ServiceReference<TransactionManager> existingTm = bc.getServiceReference(TransactionManager.class);
+// if (existingTm != null) {
+// if (log.isDebugEnabled())
+// log.debug("Using provided transaction manager " + existingTm);
+// return;
+// }
+//
+// if (!TransactionManagerServices.isTransactionManagerRunning()) {
+// bitronix.tm.Configuration tmConf = TransactionManagerServices.getConfiguration();
+// tmConf.setServerId(UUID.randomUUID().toString());
+//
+// Bundle bitronixBundle = FrameworkUtil.getBundle(bitronix.tm.Configuration.class);
+// File tmBaseDir = bitronixBundle.getDataFile(KernelConstants.DIR_TRANSACTIONS);
+// File tmDir1 = new File(tmBaseDir, "btm1");
+// tmDir1.mkdirs();
+// tmConf.setLogPart1Filename(new File(tmDir1, tmDir1.getName() + ".tlog").getAbsolutePath());
+// File tmDir2 = new File(tmBaseDir, "btm2");
+// tmDir2.mkdirs();
+// tmConf.setLogPart2Filename(new File(tmDir2, tmDir2.getName() + ".tlog").getAbsolutePath());
+// }
+// BitronixTransactionManager transactionManager = getTransactionManager();
+// stopHooks.add(() -> transactionManager.shutdown());
+// BitronixTransactionSynchronizationRegistry transactionSynchronizationRegistry = getTransactionSynchronizationRegistry();
+// // register
+// bc.registerService(TransactionManager.class, transactionManager, null);
+// bc.registerService(UserTransaction.class, transactionManager, null);
+// bc.registerService(TransactionSynchronizationRegistry.class, transactionSynchronizationRegistry, null);
+// if (log.isDebugEnabled())
+// log.debug("Initialised default Bitronix transaction manager");
+// }
void shutdown() {
if (log.isDebugEnabled())
}
+ public boolean isRemote() {
+ return remote;
+ }
+
}
@Override
public void run() {
+ if (log.isTraceEnabled())
+ log.trace("Kernel thread started.");
final long periodNs = PERIOD * m;
while (running) {
long beginNs = System.nanoTime();
registerRemotingServlet(httpService, alias, repository);
if (NodeConstants.HOME.equals(alias))
registerFilesServlet(httpService, alias, repository);
- if (log.isDebugEnabled())
- log.debug("Registered servlets for repository '" + alias + "'");
+ if (log.isTraceEnabled())
+ log.trace("Registered servlets for repository '" + alias + "'");
} catch (Exception e) {
throw new CmsException("Could not register servlets for repository '" + alias + "'", e);
}
httpService.unregister(remotingPath(alias));
if (NodeConstants.HOME.equals(alias))
httpService.unregister(filesPath(alias));
- if (log.isDebugEnabled())
- log.debug("Unregistered servlets for repository '" + alias + "'");
+ if (log.isTraceEnabled())
+ log.trace("Unregistered servlets for repository '" + alias + "'");
} catch (Exception e) {
log.error("Could not unregister servlets for repository '" + alias + "'", e);
}
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
-import org.springframework.core.io.Resource;
/**
* OSGi-aware Jackrabbit repository factory which can retrieve/publish
protected void postInitialization(Repository repository, Map parameters) {
}
-
- public void setFileRepositoryConfiguration(Resource fileRepositoryConfiguration) {
- // this.fileRepositoryConfiguration = fileRepositoryConfiguration;
- }
-
}
import org.osgi.service.useradmin.UserAdmin;
import org.osgi.util.tracker.ServiceTracker;
-import bitronix.tm.BitronixTransactionManager;
-import bitronix.tm.resource.ehcache.EhCacheXAResourceProducer;
-
/**
* Aggregates multiple {@link UserDirectory} and integrates them with system
* roles.
// JTA
private final ServiceTracker<TransactionManager, TransactionManager> tmTracker;
- private final String cacheName = UserDirectory.class.getName();
+ // private final String cacheName = UserDirectory.class.getName();
// GSS API
private Path nodeKeyTab = KernelUtils.getOsgiInstancePath(KernelConstants.NODE_KEY_TAB_PATH);
if (tm == null)
throw new CmsException("A JTA transaction manager must be available.");
userDirectory.setTransactionManager(tm);
- if (tmTracker.getService() instanceof BitronixTransactionManager)
- EhCacheXAResourceProducer.registerXAResource(cacheName, userDirectory.getXaResource());
+// if (tmTracker.getService() instanceof BitronixTransactionManager)
+// EhCacheXAResourceProducer.registerXAResource(cacheName, userDirectory.getXaResource());
Object realm = userDirectory.getProperties().get(UserAdminConf.realm.name());
if (realm != null) {
}
protected void preDestroy(AbstractUserDirectory userDirectory) {
- if (tmTracker.getService() instanceof BitronixTransactionManager)
- EhCacheXAResourceProducer.unregisterXAResource(cacheName, userDirectory.getXaResource());
+// if (tmTracker.getService() instanceof BitronixTransactionManager)
+// EhCacheXAResourceProducer.unregisterXAResource(cacheName, userDirectory.getXaResource());
Object realm = userDirectory.getProperties().get(UserAdminConf.realm.name());
if (realm != null) {
import java.security.AllPermission;
import java.util.PropertyPermission;
-import javax.management.MBeanPermission;
-import javax.management.MBeanServerPermission;
-import javax.management.MBeanTrustPermission;
import javax.security.auth.AuthPermission;
import org.osgi.framework.AdminPermission;
import org.osgi.service.condpermadmin.ConditionalPermissionUpdate;
import org.osgi.service.permissionadmin.PermissionInfo;
-import bitronix.tm.BitronixTransactionManager;
-
public interface SecurityProfile {
BundleContext bc = FrameworkUtil.getBundle(SecurityProfile.class).getBundleContext();
// ConditionalPermissionInfo.ALLOW));
// Bitronix
- update.getConditionalPermissionInfos().add(permissionAdmin.newConditionalPermissionInfo(null,
- new ConditionInfo[] { new ConditionInfo(BundleLocationCondition.class.getName(),
- new String[] { locate(BitronixTransactionManager.class) }) },
- new PermissionInfo[] { new PermissionInfo(PropertyPermission.class.getName(), "bitronix.tm.*", "read"),
- new PermissionInfo(RuntimePermission.class.getName(), "getClassLoader", null),
- new PermissionInfo(MBeanServerPermission.class.getName(), "createMBeanServer", null),
- new PermissionInfo(MBeanPermission.class.getName(), "bitronix.tm.*", "registerMBean"),
- new PermissionInfo(MBeanTrustPermission.class.getName(), "register", null) },
- ConditionalPermissionInfo.ALLOW));
+// update.getConditionalPermissionInfos().add(permissionAdmin.newConditionalPermissionInfo(null,
+// new ConditionInfo[] { new ConditionInfo(BundleLocationCondition.class.getName(),
+// new String[] { locate(BitronixTransactionManager.class) }) },
+// new PermissionInfo[] { new PermissionInfo(PropertyPermission.class.getName(), "bitronix.tm.*", "read"),
+// new PermissionInfo(RuntimePermission.class.getName(), "getClassLoader", null),
+// new PermissionInfo(MBeanServerPermission.class.getName(), "createMBeanServer", null),
+// new PermissionInfo(MBeanPermission.class.getName(), "bitronix.tm.*", "registerMBean"),
+// new PermissionInfo(MBeanTrustPermission.class.getName(), "register", null) },
+// ConditionalPermissionInfo.ALLOW));
// DS
Bundle dsBundle = findBundle("org.eclipse.equinox.ds");
ConditionalPermissionInfo.ALLOW));
// Jetty
- Bundle jettyUtilBundle = findBundle("org.eclipse.equinox.http.jetty");
+ // Bundle jettyUtilBundle = findBundle("org.eclipse.equinox.http.jetty");
update.getConditionalPermissionInfos().add(permissionAdmin.newConditionalPermissionInfo(null,
new ConditionInfo[] { new ConditionInfo(BundleLocationCondition.class.getName(),
new String[] { "*/org.eclipse.jetty.*" }) },
new PermissionInfo(AdminPermission.class.getName(), "*", "*") },
ConditionalPermissionInfo.ALLOW));
Bundle luceneBundle = findBundle("org.apache.lucene");
- update.getConditionalPermissionInfos()
- .add(permissionAdmin.newConditionalPermissionInfo(null,
- new ConditionInfo[] { new ConditionInfo(BundleLocationCondition.class.getName(),
- new String[] { luceneBundle.getLocation() }) },
- new PermissionInfo[] {
- new PermissionInfo(FilePermission.class.getName(), "<<ALL FILES>>",
- "read,write,delete"),
- new PermissionInfo(PropertyPermission.class.getName(), "*", "read"),
- new PermissionInfo(AdminPermission.class.getName(), "*", "*") },
- ConditionalPermissionInfo.ALLOW));
+ update.getConditionalPermissionInfos().add(permissionAdmin.newConditionalPermissionInfo(null,
+ new ConditionInfo[] { new ConditionInfo(BundleLocationCondition.class.getName(),
+ new String[] { luceneBundle.getLocation() }) },
+ new PermissionInfo[] {
+ new PermissionInfo(FilePermission.class.getName(), "<<ALL FILES>>", "read,write,delete"),
+ new PermissionInfo(PropertyPermission.class.getName(), "*", "read"),
+ new PermissionInfo(AdminPermission.class.getName(), "*", "*") },
+ ConditionalPermissionInfo.ALLOW));
// COMMIT
update.commit();
package org.argeo.cms.security;
-import static javax.xml.bind.DatatypeConverter.printBase64Binary;
-
import java.io.IOException;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.security.MessageDigest;
+import java.util.Base64;
import java.util.zip.Checksum;
import org.argeo.cms.CmsException;
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
- public FileVisitResult visitFile(Path file,
- BasicFileAttributes attrs) throws IOException {
+ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (!Files.isDirectory(file)) {
byte[] digest = digest(file, algo);
md.update(digest);
});
byte[] digest = md.digest();
long duration = System.currentTimeMillis() - begin;
- System.out.println(printBase64Binary(digest) + " " + path
- + " (" + duration / 1000 + "s)");
+ System.out.println(printBase64Binary(digest) + " " + path + " (" + duration / 1000 + "s)");
return digest;
} else {
long begin = System.nanoTime();
long length = -1;
- try (FileChannel channel = (FileChannel) Files
- .newByteChannel(path);) {
+ try (FileChannel channel = (FileChannel) Files.newByteChannel(path);) {
length = channel.size();
long cursor = 0;
while (cursor < length) {
- long effectiveSize = Math.min(regionSize, length
- - cursor);
- MappedByteBuffer mb = channel.map(
- FileChannel.MapMode.READ_ONLY, cursor,
- effectiveSize);
+ long effectiveSize = Math.min(regionSize, length - cursor);
+ MappedByteBuffer mb = channel.map(FileChannel.MapMode.READ_ONLY, cursor, effectiveSize);
// md.update(mb);
byte[] buffer = new byte[1024];
- while (mb.hasRemaining()){
+ while (mb.hasRemaining()) {
mb.get(buffer);
md.update(buffer);
}
}
byte[] digest = md.digest();
long duration = System.nanoTime() - begin;
- System.out.println(printBase64Binary(digest) + " "
- + path.getFileName() + " (" + duration / 1000000
- + "ms, " + (length / 1024) + "kB, "
- + (length / (duration / 1000000)) * 1000
- / (1024 * 1024) + " MB/s)");
+ System.out.println(printBase64Binary(digest) + " " + path.getFileName() + " (" + duration / 1000000
+ + "ms, " + (length / 1024) + "kB, " + (length / (duration / 1000000)) * 1000 / (1024 * 1024)
+ + " MB/s)");
return digest;
}
}
long cursor = 0;
while (cursor < length) {
long effectiveSize = Math.min(regionSize, length - cursor);
- MappedByteBuffer mb = channel.map(
- FileChannel.MapMode.READ_ONLY, cursor, effectiveSize);
+ MappedByteBuffer mb = channel.map(FileChannel.MapMode.READ_ONLY, cursor, effectiveSize);
int nGet;
while (mb.hasRemaining()) {
nGet = Math.min(mb.remaining(), bufferSize);
if (args.length > 0) {
path = Paths.get(args[0]);
} else {
- path = Paths
- .get("/home/mbaudier/Downloads/torrents/CentOS-7-x86_64-DVD-1503-01/"
- + "CentOS-7-x86_64-DVD-1503-01.iso");
+ path = Paths.get("/home/mbaudier/Downloads/torrents/CentOS-7-x86_64-DVD-1503-01/"
+ + "CentOS-7-x86_64-DVD-1503-01.iso");
}
// long adler = cf.checksum(path, new Adler32());
// System.out.format("Adler=%d%n", adler);
// String sha1 = printBase64Binary(cf.digest(path, "SHA1"));
// System.out.format("SHA1=%s%n", sha1);
}
+
+ private static String printBase64Binary(byte[] arr) {
+ return Base64.getEncoder().encodeToString(arr);
+ }
}
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * 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.
- */
-package org.argeo.cms.spring;
-
-import javax.security.auth.Subject;
-import javax.security.auth.login.LoginContext;
-import javax.security.auth.login.LoginException;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.cms.CmsException;
-import org.argeo.node.NodeConstants;
-
-/** Provides base method for executing code with system authorization. */
-abstract class AbstractSystemExecution {
- private final static Log log = LogFactory.getLog(AbstractSystemExecution.class);
- private final Subject subject = new Subject();
-
- /** Authenticate the calling thread */
- protected void authenticateAsSystem() {
- ClassLoader origClassLoader = Thread.currentThread().getContextClassLoader();
- Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
- try {
- LoginContext lc = new LoginContext(NodeConstants.LOGIN_CONTEXT_DATA_ADMIN, subject);
- lc.login();
- } catch (LoginException e) {
- throw new CmsException("Cannot login as system", e);
- } finally {
- Thread.currentThread().setContextClassLoader(origClassLoader);
- }
- if (log.isTraceEnabled())
- log.trace("System authenticated");
- }
-
- protected void deauthenticateAsSystem() {
- ClassLoader origClassLoader = Thread.currentThread().getContextClassLoader();
- Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
- try {
- LoginContext lc = new LoginContext(NodeConstants.LOGIN_CONTEXT_DATA_ADMIN, subject);
- lc.logout();
- } catch (LoginException e) {
- throw new CmsException("Cannot logout as system", e);
- } finally {
- Thread.currentThread().setContextClassLoader(origClassLoader);
- }
- }
-
- protected Subject getSubject() {
- return subject;
- }
-}
+++ /dev/null
-/*
- * Copyright (C) 2007-2012 Argeo GmbH
- *
- * 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.
- */
-package org.argeo.cms.spring;
-
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.security.auth.Subject;
-
-import org.eclipse.gemini.blueprint.context.DependencyInitializationAwareBeanPostProcessor;
-import org.springframework.beans.BeansException;
-import org.springframework.beans.factory.support.AbstractBeanFactory;
-import org.springframework.beans.factory.support.SecurityContextProvider;
-import org.springframework.beans.factory.support.SimpleSecurityContextProvider;
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.ApplicationContextAware;
-
-/**
- * Executes with a system authentication the instantiation and initialization
- * methods of the application context where it has been defined.
- */
-public class AuthenticatedApplicationContextInitialization extends
- AbstractSystemExecution implements
- DependencyInitializationAwareBeanPostProcessor, ApplicationContextAware {
- /** If non empty, restricts to these beans */
- private List<String> beanNames = new ArrayList<String>();
-
- public Object postProcessBeforeInitialization(Object bean, String beanName)
- throws BeansException {
- if (beanNames.size() == 0 || beanNames.contains(beanName))
- authenticateAsSystem();
- return bean;
- }
-
- public Object postProcessAfterInitialization(Object bean, String beanName)
- throws BeansException {
- if (beanNames.size() == 0 || beanNames.contains(beanName))
- deauthenticateAsSystem();
- return bean;
- }
-
- public void setBeanNames(List<String> beanNames) {
- this.beanNames = beanNames;
- }
-
- @Override
- public void setApplicationContext(ApplicationContext applicationContext)
- throws BeansException {
- if (applicationContext.getAutowireCapableBeanFactory() instanceof AbstractBeanFactory) {
- final AbstractBeanFactory beanFactory = ((AbstractBeanFactory) applicationContext
- .getAutowireCapableBeanFactory());
- // retrieve subject's access control context
- // and set it as the bean factory security context
- Subject.doAs(getSubject(), new PrivilegedAction<Void>() {
- @Override
- public Void run() {
- SecurityContextProvider scp = new SimpleSecurityContextProvider(
- AccessController.getContext());
- beanFactory.setSecurityContextProvider(scp);
- return null;
- }
- });
- }
- }
-}
+++ /dev/null
-package org.argeo.cms.spring;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-import javax.naming.InvalidNameException;
-import javax.naming.ldap.LdapName;
-import javax.transaction.UserTransaction;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.argeo.cms.CmsException;
-import org.osgi.service.useradmin.Role;
-import org.osgi.service.useradmin.UserAdmin;
-
-/**
- * Register one or many roles via a user admin service. Does nothing if the role
- * is already registered.
- */
-public class SimpleRoleRegistration implements Runnable {
- private final static Log log = LogFactory
- .getLog(SimpleRoleRegistration.class);
-
- private String role;
- private List<String> roles = new ArrayList<String>();
- private UserAdmin userAdmin;
- private UserTransaction userTransaction;
-
- @Override
- public void run() {
- try {
- userTransaction.begin();
- if (role != null && !roleExists(role))
- newRole(toDn(role));
-
- for (String r : roles)
- if (!roleExists(r))
- newRole(toDn(r));
- userTransaction.commit();
- } catch (Exception e) {
- try {
- userTransaction.rollback();
- } catch (Exception e1) {
- log.error("Cannot rollback", e1);
- }
- throw new CmsException("Cannot add roles", e);
- }
- }
-
- private boolean roleExists(String role) {
- return userAdmin.getRole(toDn(role).toString()) != null;
- }
-
- protected void newRole(LdapName r) {
- userAdmin.createRole(r.toString(), Role.GROUP);
- log.info("Added role " + r + " required by application.");
- }
-
- public void register(UserAdmin userAdminService, Map<?, ?> properties) {
- this.userAdmin = userAdminService;
- run();
- }
-
- protected LdapName toDn(String name) {
- try {
- return new LdapName("cn=" + name + ",ou=roles,ou=node");
- } catch (InvalidNameException e) {
- throw new CmsException("Badly formatted role name " + name, e);
- }
- }
-
- public void setRole(String role) {
- this.role = role;
- }
-
- public void setRoles(List<String> roles) {
- this.roles = roles;
- }
-
- public void setUserAdmin(UserAdmin userAdminService) {
- this.userAdmin = userAdminService;
- }
-
- public void setUserTransaction(UserTransaction userTransaction) {
- this.userTransaction = userTransaction;
- }
-
-}
+++ /dev/null
-package org.argeo.cms.spring.osgi;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Constants;
-
-/**
- * Logs the name and version of an OSGi bundle based on its
- * {@link BundleContext}.
- */
-public class OsgiModuleLabel {
- private final static Log log = LogFactory.getLog(OsgiModuleLabel.class);
-
- private Bundle bundle;
-
- public OsgiModuleLabel() {
- }
-
- /** Sets without logging. */
- public OsgiModuleLabel(Bundle bundle) {
- this.bundle = bundle;
- }
-
- /**
- * Retrieved bundle from a bundle context and logs it. Typically to be set
- * as a Spring bean.
- */
- public void setBundleContext(BundleContext bundleContext) {
- this.bundle = bundleContext.getBundle();
- log.info(msg());
- }
-
- public String msg() {
- String name = bundle.getHeaders().get(Constants.BUNDLE_NAME).toString();
- String symbolicName = bundle.getSymbolicName();
- String version = bundle.getVersion().toString();
- return name + " v" + version + " (" + symbolicName + ")";
- }
-}
Fragment-Host: org.apache.jackrabbit.core
-Import-Package: org.springframework.core,\
-org.argeo.node,\
+Import-Package: org.argeo.node,\
*
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
-import javax.activation.FileTypeMap;
-import javax.activation.MimetypesFileTypeMap;
import javax.jcr.Binary;
import javax.jcr.Node;
import javax.jcr.Property;
private long position = 0;
- // private ByteBuffer toWrite;
private FileChannel fc = null;
- private static FileTypeMap fileTypeMap;
-
- static {
- try {
- fileTypeMap = new MimetypesFileTypeMap("/etc/mime.types");
- } catch (IOException e) {
- fileTypeMap = FileTypeMap.getDefaultFileTypeMap();
- }
- }
-
- public BinaryChannel(Node file) throws RepositoryException, IOException {
+ public BinaryChannel(Node file, Path path) throws RepositoryException, IOException {
this.file = file;
- // int capacity = 1024 * 1024;
- // this.toWrite = ByteBuffer.allocate(capacity);
if (file.isNodeType(NodeType.NT_FILE)) {
if (file.hasNode(Property.JCR_CONTENT)) {
Node data = file.getNode(Property.JCR_CONTENT);
data.setProperty(Property.JCR_DATA, this.binary);
// MIME type
- String mime = fileTypeMap.getContentType(file.getName());
+ String mime = Files.probeContentType(path);
+ // String mime = fileTypeMap.getContentType(file.getName());
data.setProperty(Property.JCR_MIMETYPE, mime);
data.getSession().save();
Binary newBinary = null;
try {
Session session = file.getSession();
- // byte[] arr = new byte[(int) position];
- // toWrite.flip();
- // toWrite.get(arr);
fc.position(0);
InputStream in = Channels.newInputStream(fc);
newBinary = session.getValueFactory().createBinary(in);
try {
int read;
- // int capacity = dst.capacity();
byte[] arr = dst.array();
read = binary.read(arr, position);
- // dst.put(arr, 0, read);
-
- // try {
- // byte[] arr = dst.array();
- // read = binary.read(arr, position);
- // } catch (UnsupportedOperationException e) {
- // int capacity = dst.capacity();
- // byte[] arr = new byte[capacity];
- // read = binary.read(arr, position);
- // dst.put(arr);
- // }
+
if (read != -1)
position = position + read;
return read;
public int write(ByteBuffer src) throws IOException {
int written = getFileChannel().write(src);
return written;
- // int byteCount = src.remaining();
- // if (toWrite.remaining() < byteCount)
- // throw new JcrFsException("Write buffer is full");
- // toWrite.put(src);
- // if (position < binarySize)
- // position = binarySize + byteCount;
- // else
- // position = position + byteCount;
- // return byteCount;
}
@Override
@Override
public SeekableByteChannel truncate(long size) throws IOException {
getFileChannel().truncate(size);
- // if (size != size())
- // throw new UnsupportedOperationException("Cannot truncate JCR
- // binary");
return this;
}
}
if (!node.isNodeType(NodeType.NT_FILE))
throw new UnsupportedOperationException(node + " must be a file");
- return new BinaryChannel(node);
+ return new BinaryChannel(node, path);
} catch (RepositoryException e) {
discardChanges(node);
throw new IOException("Cannot read file", e);
Import-Package: org.apache.commons.io,\
org.eclipse.core.commands,\
- org.springframework.beans.factory,\
- org.springframework.core.io.support,\
org.argeo.eclipse.ui.utils,\
!org.eclipse.core.runtime,\
!org.eclipse.ui.plugin,\