use of org.alfresco.service.cmr.repository.StoreRef in project acs-community-packaging by Alfresco.
the class ContextListener method contextInitialized.
/**
* @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
*/
public void contextInitialized(ServletContextEvent event) {
// make sure that the spaces store in the repository exists
this.servletContext = event.getServletContext();
WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
// If no context has been initialised, exit silently so config changes can be made
if (ctx == null) {
return;
}
ServiceRegistry registry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
TransactionService transactionService = registry.getTransactionService();
NodeService nodeService = registry.getNodeService();
SearchService searchService = registry.getSearchService();
NamespaceService namespaceService = registry.getNamespaceService();
AuthenticationContext authenticationContext = (AuthenticationContext) ctx.getBean("authenticationContext");
// repo bootstrap code for our client
UserTransaction tx = null;
NodeRef companySpaceNodeRef = null;
try {
tx = transactionService.getUserTransaction();
tx.begin();
authenticationContext.setSystemUserAsCurrentUser();
// get and setup the initial store ref and root path from config
StoreRef storeRef = Repository.getStoreRef(servletContext);
// get root path
String rootPath = Application.getRootPath(servletContext);
// Extract company space id and store it in the Application object
companySpaceNodeRef = Repository.getCompanyRoot(nodeService, searchService, namespaceService, storeRef, rootPath);
Application.setCompanyRootId(companySpaceNodeRef.getId());
// commit the transaction
tx.commit();
} catch (Throwable e) {
// rollback the transaction
try {
if (tx != null) {
tx.rollback();
}
} catch (Exception ex) {
}
logger.error("Failed to initialise ", e);
throw new AlfrescoRuntimeException("Failed to initialise ", e);
} finally {
try {
authenticationContext.clearCurrentSecurityContext();
} catch (Exception ex) {
}
}
}
use of org.alfresco.service.cmr.repository.StoreRef in project acs-community-packaging by Alfresco.
the class BaseTemplateContentServlet method processTemplateRequest.
/**
* Processes the template request using the current context i.e. no
* authentication checks are made, it is presumed they have already
* been done.
*
* @param req The HTTP request
* @param res The HTTP response
* @param redirectToLogin Flag to determine whether to redirect to the login
* page if the user does not have the correct permissions
*/
protected void processTemplateRequest(HttpServletRequest req, HttpServletResponse res, boolean redirectToLogin) throws ServletException, IOException {
Log logger = getLogger();
String uri = req.getRequestURI();
if (logger.isDebugEnabled()) {
String queryString = req.getQueryString();
logger.debug("Processing URL: " + uri + ((queryString != null && queryString.length() > 0) ? ("?" + queryString) : ""));
}
uri = uri.substring(req.getContextPath().length());
StringTokenizer t = new StringTokenizer(uri, "/");
int tokenCount = t.countTokens();
// skip servlet name
t.nextToken();
NodeRef nodeRef = null;
NodeRef templateRef = null;
try {
String contentPath = req.getParameter(ARG_CONTEXT_PATH);
if (contentPath != null && contentPath.length() != 0) {
// process the name based path to resolve the NodeRef
PathRefInfo pathInfo = resolveNamePath(getServletContext(), contentPath);
nodeRef = pathInfo.NodeRef;
} else if (tokenCount > 3) {
// get NodeRef to the content from the URL elements
StoreRef storeRef = new StoreRef(t.nextToken(), t.nextToken());
nodeRef = new NodeRef(storeRef, t.nextToken());
}
// get NodeRef to the template if supplied
String templatePath = req.getParameter(ARG_TEMPLATE_PATH);
if (templatePath != null && templatePath.length() != 0) {
// process the name based path to resolve the NodeRef
PathRefInfo pathInfo = resolveNamePath(getServletContext(), templatePath);
templateRef = pathInfo.NodeRef;
} else if (tokenCount >= 7) {
StoreRef storeRef = new StoreRef(t.nextToken(), t.nextToken());
templateRef = new NodeRef(storeRef, t.nextToken());
}
} catch (AccessDeniedException err) {
if (redirectToLogin) {
if (logger.isDebugEnabled())
logger.debug("Redirecting to login page...");
redirectToLoginPage(req, res, getServletContext());
} else {
if (logger.isDebugEnabled())
logger.debug("Returning 403 Forbidden error...");
res.sendError(HttpServletResponse.SC_FORBIDDEN);
}
return;
}
// TODO: should this default to something else?
if (nodeRef == null && templateRef != null) {
nodeRef = templateRef;
}
if (nodeRef == null) {
throw new TemplateException("Not enough elements supplied in URL or no 'path' argument specified.");
}
// get the services we need to retrieve the content
ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext());
NodeService nodeService = serviceRegistry.getNodeService();
TemplateService templateService = serviceRegistry.getTemplateService();
PermissionService permissionService = serviceRegistry.getPermissionService();
// check that the user has at least READ access on any nodes - else redirect to the login page
if (permissionService.hasPermission(nodeRef, PermissionService.READ) == AccessStatus.DENIED || (templateRef != null && permissionService.hasPermission(templateRef, PermissionService.READ) == AccessStatus.DENIED)) {
if (redirectToLogin) {
if (logger.isDebugEnabled())
logger.debug("Redirecting to login page...");
redirectToLoginPage(req, res, getServletContext());
} else {
if (logger.isDebugEnabled())
logger.debug("Returning 403 Forbidden error...");
res.sendError(HttpServletResponse.SC_FORBIDDEN);
}
return;
}
String mimetype = MIMETYPE_HTML;
if (req.getParameter(ARG_MIMETYPE) != null) {
mimetype = req.getParameter(ARG_MIMETYPE);
}
res.setContentType(mimetype);
try {
UserTransaction txn = null;
try {
txn = serviceRegistry.getTransactionService().getUserTransaction(true);
txn.begin();
// if template not supplied, then use the default against the node
if (templateRef == null) {
if (nodeService.hasAspect(nodeRef, ContentModel.ASPECT_TEMPLATABLE)) {
templateRef = (NodeRef) nodeService.getProperty(nodeRef, ContentModel.PROP_TEMPLATE);
}
if (templateRef == null) {
throw new TemplateException("Template reference not set against node or not supplied in URL.");
}
}
// create the model - put the supplied noderef in as space/document as appropriate
Map<String, Object> model = getModel(serviceRegistry, req, templateRef, nodeRef);
// to be streamed directly to the browser response stream.
try {
templateService.processTemplate(templateRef.toString(), model, res.getWriter());
// commit the transaction
txn.commit();
} catch (SocketException e) {
if (e.getMessage().contains("ClientAbortException")) {
// the client cut the connection - our mission was accomplished apart from a little error message
logger.error("Client aborted stream read:\n node: " + nodeRef + "\n template: " + templateRef);
try {
if (txn != null) {
txn.rollback();
}
} catch (Exception tex) {
}
} else {
throw e;
}
} finally {
res.getWriter().close();
}
} catch (Throwable txnErr) {
try {
if (txn != null) {
txn.rollback();
}
} catch (Exception tex) {
}
throw txnErr;
}
} catch (Throwable err) {
throw new AlfrescoRuntimeException("Error during template servlet processing: " + err.getMessage(), err);
}
}
use of org.alfresco.service.cmr.repository.StoreRef in project acs-community-packaging by Alfresco.
the class UploadContentServlet method doPut.
/**
* @see javax.servlet.http.HttpServlet#doPut(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
protected void doPut(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
if (logger.isDebugEnabled() == true) {
String queryString = req.getQueryString();
logger.debug("Authenticating request to URL: " + req.getRequestURI() + ((queryString != null && queryString.length() > 0) ? ("?" + queryString) : ""));
}
AuthenticationStatus status = servletAuthenticate(req, res, false);
if (status == AuthenticationStatus.Failure || status == AuthenticationStatus.Guest) {
res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
// Tokenise the URI
String uri = req.getRequestURI();
uri = uri.substring(req.getContextPath().length());
StringTokenizer t = new StringTokenizer(uri, "/");
int tokenCount = t.countTokens();
// skip servlet name
t.nextToken();
// get or calculate the noderef and filename to download as
NodeRef nodeRef = null;
String filename = null;
QName propertyQName = null;
if (tokenCount == 2) {
// filename is the only token
filename = t.nextToken();
} else if (tokenCount == 4 || tokenCount == 5) {
// assume 'workspace' or other NodeRef based protocol for remaining URL
// elements
StoreRef storeRef = new StoreRef(t.nextToken(), t.nextToken());
String id = t.nextToken();
// build noderef from the appropriate URL elements
nodeRef = new NodeRef(storeRef, id);
if (tokenCount == 5) {
// filename is last remaining token
filename = t.nextToken();
}
// get qualified of the property to get content from - default to
// ContentModel.PROP_CONTENT
propertyQName = ContentModel.PROP_CONTENT;
String property = req.getParameter(ARG_PROPERTY);
if (property != null && property.length() != 0) {
propertyQName = QName.createQName(property);
}
} else {
logger.debug("Upload URL did not contain all required args: " + uri);
res.sendError(HttpServletResponse.SC_EXPECTATION_FAILED);
return;
}
// get the services we need to retrieve the content
ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext());
ContentService contentService = serviceRegistry.getContentService();
PermissionService permissionService = serviceRegistry.getPermissionService();
MimetypeService mimetypeService = serviceRegistry.getMimetypeService();
NodeService nodeService = serviceRegistry.getNodeService();
InputStream is = req.getInputStream();
BufferedInputStream inputStream = new BufferedInputStream(is);
// Sort out the mimetype
String mimetype = req.getParameter(ARG_MIMETYPE);
if (mimetype == null || mimetype.length() == 0) {
mimetype = MIMETYPE_OCTET_STREAM;
if (filename != null) {
MimetypeService mimetypeMap = serviceRegistry.getMimetypeService();
int extIndex = filename.lastIndexOf('.');
if (extIndex != -1) {
String ext = filename.substring(extIndex + 1);
mimetype = mimetypeService.getMimetype(ext);
}
}
}
// Get the encoding
String encoding = req.getParameter(ARG_ENCODING);
if (encoding == null || encoding.length() == 0) {
// Get the encoding
ContentCharsetFinder charsetFinder = mimetypeService.getContentCharsetFinder();
Charset charset = charsetFinder.getCharset(inputStream, mimetype);
encoding = charset.name();
}
// Get the locale
Locale locale = I18NUtil.parseLocale(req.getParameter(ARG_LOCALE));
if (locale == null) {
locale = I18NUtil.getContentLocale();
if (nodeRef != null) {
ContentData contentData = (ContentData) nodeService.getProperty(nodeRef, propertyQName);
if (contentData != null) {
locale = contentData.getLocale();
}
}
}
if (logger.isDebugEnabled()) {
if (nodeRef != null) {
logger.debug("Found NodeRef: " + nodeRef.toString());
}
logger.debug("For property: " + propertyQName);
logger.debug("File name: " + filename);
logger.debug("Mimetype: " + mimetype);
logger.debug("Encoding: " + encoding);
logger.debug("Locale: " + locale);
}
// Check that the user has the permissions to write the content
if (permissionService.hasPermission(nodeRef, PermissionService.WRITE_CONTENT) == AccessStatus.DENIED) {
if (logger.isDebugEnabled() == true) {
logger.debug("User does not have permissions to wrtie content for NodeRef: " + nodeRef.toString());
}
if (logger.isDebugEnabled()) {
logger.debug("Returning 403 Forbidden error...");
}
res.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
// Try and get the content writer
ContentWriter writer = contentService.getWriter(nodeRef, propertyQName, true);
if (writer == null) {
if (logger.isDebugEnabled() == true) {
logger.debug("Content writer cannot be obtained for NodeRef: " + nodeRef.toString());
}
res.sendError(HttpServletResponse.SC_EXPECTATION_FAILED);
return;
}
// Set the mimetype, encoding and locale
writer.setMimetype(mimetype);
writer.setEncoding(encoding);
if (locale != null) {
writer.setLocale(locale);
}
// Stream the content into the repository
writer.putContent(inputStream);
if (logger.isDebugEnabled() == true) {
logger.debug("Content details: " + writer.getContentData().toString());
}
// Set return status
res.getWriter().write(writer.getContentData().toString());
res.flushBuffer();
if (logger.isDebugEnabled() == true) {
logger.debug("UploadContentServlet done");
}
}
use of org.alfresco.service.cmr.repository.StoreRef in project SearchServices by Alfresco.
the class AlfrescoSolrUtils method getNodeMetaData.
/**
* Get a nodes meta data.
* @param node
* @param txn
* @param acl
* @param owner
* @param ancestors
* @param createError
* @return {@link NodeMetaData}
*/
public static NodeMetaData getNodeMetaData(Node node, Transaction txn, Acl acl, String owner, Set<NodeRef> ancestors, boolean createError) {
NodeMetaData nodeMetaData = new NodeMetaData();
nodeMetaData.setId(node.getId());
nodeMetaData.setAclId(acl.getId());
nodeMetaData.setTxnId(txn.getId());
nodeMetaData.setOwner(owner);
nodeMetaData.setAspects(new HashSet<QName>());
nodeMetaData.setAncestors(ancestors);
Map<QName, PropertyValue> props = new HashMap<QName, PropertyValue>();
props.put(ContentModel.PROP_IS_INDEXED, new StringPropertyValue("true"));
props.put(ContentModel.PROP_CONTENT, new ContentPropertyValue(Locale.US, 0l, "UTF-8", "text/plain", null));
nodeMetaData.setProperties(props);
// If create createError is true then we leave out the nodeRef which will cause an error
if (!createError) {
NodeRef nodeRef = new NodeRef(new StoreRef("workspace", "SpacesStore"), createGUID());
nodeMetaData.setNodeRef(nodeRef);
}
nodeMetaData.setType(QName.createQName(TEST_NAMESPACE, "testSuperType"));
nodeMetaData.setAncestors(ancestors);
nodeMetaData.setPaths(new ArrayList<Pair<String, QName>>());
nodeMetaData.setNamePaths(new ArrayList<List<String>>());
return nodeMetaData;
}
use of org.alfresco.service.cmr.repository.StoreRef in project SearchServices by Alfresco.
the class SortCMISTest method addSortableNull.
private void addSortableNull(NodeRef folder00NodeRef, NodeRef rootNodeRef, NodeRef baseFolderNodeRef, Object baseFolderQName, Object folder00QName, Date date1, String id, int offset) throws IOException {
HashMap<QName, PropertyValue> content00Properties = new HashMap<QName, PropertyValue>();
MLTextPropertyValue desc00 = new MLTextPropertyValue();
desc00.addValue(Locale.ENGLISH, "Test null");
content00Properties.put(ContentModel.PROP_DESCRIPTION, desc00);
content00Properties.put(ContentModel.PROP_TITLE, desc00);
content00Properties.put(ContentModel.PROP_NAME, new StringPropertyValue("Test null"));
content00Properties.put(ContentModel.PROP_CREATED, new StringPropertyValue(DefaultTypeConverter.INSTANCE.convert(String.class, date1)));
NodeRef content00NodeRef = new NodeRef(new StoreRef("workspace", "SpacesStore"), createGUID());
QName content00QName = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "Test null");
ChildAssociationRef content00CAR = new ChildAssociationRef(ContentModel.ASSOC_CONTAINS, folder00NodeRef, content00QName, content00NodeRef, true, 0);
addNode(h.getCore(), dataModel, 1, 200 + offset, 1, extendedContent, new QName[] { ContentModel.ASPECT_OWNABLE, ContentModel.ASPECT_TITLED }, content00Properties, null, "andy", new ChildAssociationRef[] { content00CAR }, new NodeRef[] { baseFolderNodeRef, rootNodeRef, folder00NodeRef }, new String[] { "/" + baseFolderQName.toString() + "/" + folder00QName.toString() + "/" + content00QName.toString() }, content00NodeRef, true);
}
Aggregations