Powered By Blogger

Tuesday, November 23, 2010

UploadFileServlet

/*
* Copyright (C) 2005-2010 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see . */
package org.alfresco.web.app.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.util.TempFileProvider;
import org.alfresco.web.app.Application;
import org.alfresco.web.bean.ErrorBean;
import org.alfresco.web.bean.FileUploadBean;
import org.alfresco.web.config.ClientConfigElement;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.RequestContext;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.extensions.config.ConfigService;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
* Servlet that takes a file uploaded via a browser and represents it as an
* UploadFileBean in the session
*
* @author gavinc
*/
public class UploadFileServlet extends BaseServlet
{
private static final long serialVersionUID = -5482538466491052875L;
private static final Log logger = LogFactory.getLog(UploadFileServlet.class);

private ConfigService configService;


/**
* @see javax.servlet.GenericServlet#init()
*/
@Override
public void init(ServletConfig sc) throws ServletException
{
super.init(sc);

WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(sc.getServletContext());
this.configService = (ConfigService)ctx.getBean("webClientConfigService");
}

/**
* @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@SuppressWarnings("unchecked")
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String uploadId = null;
String returnPage = null;
final RequestContext requestContext = new ServletRequestContext(request);
boolean isMultipart = ServletFileUpload.isMultipartContent(requestContext);

try
{
AuthenticationStatus status = servletAuthenticate(request, response);
if (status == AuthenticationStatus.Failure)
{
return;
}

if (!isMultipart)
{
throw new AlfrescoRuntimeException("This servlet can only be used to handle file upload requests, make" +
"sure you have set the enctype attribute on your form to multipart/form-data");
}

if (logger.isDebugEnabled())
logger.debug("Uploading servlet servicing...");

FacesContext context = FacesContext.getCurrentInstance();
Map session = context.getExternalContext().getSessionMap();
ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());

// ensure that the encoding is handled correctly
upload.setHeaderEncoding("UTF-8");

List fileItems = upload.parseRequest(request);

FileUploadBean bean = new FileUploadBean();
for (FileItem item : fileItems)
{
if(item.isFormField())
{
if (item.getFieldName().equalsIgnoreCase("return-page"))
{
returnPage = item.getString();
}
else if (item.getFieldName().equalsIgnoreCase("upload-id"))
{
uploadId = item.getString();
}
}
else
{
String filename = item.getName();
if (filename != null && filename.length() != 0)
{
if (logger.isDebugEnabled())
{
logger.debug("Processing uploaded file: " + filename);
}

// ADB-41: Ignore non-existent files i.e. 0 byte streams.
if (allowZeroByteFiles() == true || item.getSize() > 0)
{
// workaround a bug in IE where the full path is returned
// IE is only available for Windows so only check for the Windows path separator
filename = FilenameUtils.getName(filename);
final File tempFile = TempFileProvider.createTempFile("alfresco", ".upload");
item.write(tempFile);
bean.setFile(tempFile);
bean.setFileName(filename);
bean.setFilePath(tempFile.getAbsolutePath());
if (logger.isDebugEnabled())
{
logger.debug("Temp file: " + tempFile.getAbsolutePath() +
" size " + tempFile.length() +
" bytes created from upload filename: " + filename);
}
}
else
{
if (logger.isWarnEnabled())
logger.warn("Ignored file '" + filename + "' as there was no content, this is either " +
"caused by uploading an empty file or a file path that does not exist on the client.");
}
}
}
}

session.put(FileUploadBean.getKey(uploadId), bean);

if (bean.getFile() == null && uploadId != null && logger.isWarnEnabled())
{
logger.warn("no file uploaded for upload id: " + uploadId);
}

if (returnPage == null || returnPage.length() == 0)
{
throw new AlfrescoRuntimeException("return-page parameter has not been supplied");
}

if (returnPage.startsWith("javascript:"))
{
returnPage = returnPage.substring("javascript:".length());
// finally redirect
if (logger.isDebugEnabled())
{
logger.debug("Sending back javascript response " + returnPage);
}
response.setContentType(MimetypeMap.MIMETYPE_HTML);
response.setCharacterEncoding("utf-8");
final PrintWriter out = response.getWriter();
out.println("");
out.close();
}
else
{
// finally redirect
if (logger.isDebugEnabled())
logger.debug("redirecting to: " + returnPage);

response.sendRedirect(returnPage);
}

if (logger.isDebugEnabled())
logger.debug("upload complete");
}
catch (Throwable error)
{
handleUploadException(request, response, error, returnPage);
}
}

private void handleUploadException(HttpServletRequest request, HttpServletResponse response, Throwable error, String returnPage)
{
try
{
HttpSession session = request.getSession(true);
ErrorBean errorBean = (ErrorBean) session.getAttribute(ErrorBean.ERROR_BEAN_NAME);
if (errorBean == null)
{
errorBean = new ErrorBean();
session.setAttribute(ErrorBean.ERROR_BEAN_NAME, errorBean);
}
errorBean.setLastError(error);
errorBean.setReturnPage(returnPage);
}
catch (Throwable e)
{
logger.error("Error while handling upload Exception", e);
}
try
{
String errorPage = Application.getErrorPage(getServletContext());

if (logger.isDebugEnabled())
{
logger.debug("An error has occurred. Sending back response for redirecting to error page: " + errorPage);
}

response.setContentType(MimetypeMap.MIMETYPE_HTML);
response.setCharacterEncoding("utf-8");
final PrintWriter out = response.getWriter();
out.println(" ");
out.close();
}
catch (Exception e)
{
logger.error("Error while handling upload Exception", e);
}
}


private boolean allowZeroByteFiles()
{
ClientConfigElement clientConfig = (ClientConfigElement)configService.getGlobalConfig().getConfigElement(
ClientConfigElement.CONFIG_ELEMENT_ID);
return clientConfig.isZeroByteFileUploads();
}
}

UploadContentServlet

/*
* Copyright (C) 2005-2010 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see .
*/
package org.alfresco.web.app.servlet;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.StringTokenizer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.alfresco.model.ContentModel;
import org.alfresco.repo.content.encoding.ContentCharsetFinder;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.ContentService;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.MimetypeService;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.security.AccessStatus;
import org.alfresco.service.cmr.security.PermissionService;
import org.alfresco.service.namespace.QName;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
* Servlet responsible for streaming content directly into the repository from the PUT request.
* The appropriate mimetype is calculated based on filename extension.
*


* The URL to the servlet should be generated thus:
*

/alfresco/upload/workspace/SpacesStore/0000-0000-0000-0000/myfile.pdf

* or
*
/alfresco/upload/myfile.pdf

*


* If the store and node id are specified in the URL then the content provided will be streamed onto the node
* using an updating writer, updating the content property value accordingly.
*


* If only the file name is specified the content will be streamed into the content store and the content data
* will be returned in the reposonse. This can then be used to update the value of a content property manually.
* Any used content will be cleared up in the usual manner.
*


* By default, the download assumes that the content is on the
* {@link org.alfresco.model.ContentModel#PROP_CONTENT content property}.

* To set the content of a specific model property, use a 'property' arg, providing the qualified name of the property.
*


* Like most Alfresco servlets, the URL may be followed by a valid 'ticket' argument for authentication:
* ?ticket=1234567890
*


* Guest access is currently disabled for this servlet.
*
* @author Roy Wetherall
*/
public class UploadContentServlet extends BaseServlet
{
/** Serial version UID */
private static final long serialVersionUID = 1055960980867420355L;

/** Logger */
private static Log logger = LogFactory.getLog(UploadContentServlet.class);

/** Default mime type */
protected static final String MIMETYPE_OCTET_STREAM = "application/octet-stream";

/** Argument properties */
protected static final String ARG_PROPERTY = "property";
protected static final String ARG_MIMETYPE = "mimetype";
protected static final String ARG_ENCODING = "encoding";

/**
* @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();

t.nextToken(); // skip servlet name

// 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();

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();
}

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);
}

// 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 and encoding
writer.setMimetype(mimetype);
writer.setEncoding(encoding);

// 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");
}
}
}

Monday, November 22, 2010

File upload Alfresco




File Upload




// node reference of the folder where you want to upload , you can get it from alfresco webclient by view details action



















Sunday, November 7, 2010

Alfresco CIFS with LDAP

LDAP and CIFS: If you configure Alfresco to authenticate against LDAP
and have a requirement to use CIFS, realize that the passwords in your
LDAP directory must be either clear text or MD4, otherwise, CIFS won't
work.