SolutionRepositoryService.java
| Index Score | ||
|---|---|---|
![]() |
![]() |
org.pentaho.ui.servlet |
![]() |
![]() |
Pentaho |
View: Reasons, Metrics, Source Code
These are the metrics that contribute to the Enerjy Score for this file, ranked by impact. So the metrics listed at the top influence the score to a greater extent that the metrics listed at the bottom.
/*
* Copyright 2006 Pentaho Corporation. All rights reserved.
* This software was developed by Pentaho Corporation and is provided under the terms
* of the Mozilla Public License, Version 1.1, or any later version. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://www.mozilla.org/MPL/MPL-1.1.txt. The Original Code is the Pentaho
* BI Platform. The Initial Developer is Pentaho Corporation.
*
* Software distributed under the Mozilla Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.
*
* @created Jul 12, 2005
* @author James Dixon, Angelo Rodriguez, Steven Barkdull
*
*/
package org.pentaho.ui.servlet;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.pentaho.core.cache.CacheManager;
import org.pentaho.core.repository.ISolutionRepository;
import org.pentaho.core.repository.SolutionRepositoryBase;
import org.pentaho.core.session.IPentahoSession;
import org.pentaho.core.solution.HttpRequestParameterProvider;
import org.pentaho.core.solution.IFileFilter;
import org.pentaho.core.solution.IParameterProvider;
import org.pentaho.core.solution.ISolutionFile;
import org.pentaho.core.solution.PermissionFilter;
import org.pentaho.core.system.PentahoSystem;
import org.pentaho.core.util.CleanXmlHelper;
import org.pentaho.messages.Messages;
import org.pentaho.messages.util.LocaleHelper;
import org.pentaho.util.StringUtil;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.pentaho.repository.dbbased.solution.RepositoryFile;
import com.pentaho.security.IPermissionMask;
import com.pentaho.security.IPermissionRecipient;
import com.pentaho.security.PentahoAccessControlException;
import com.pentaho.security.SimplePermissionMask;
import com.pentaho.security.SimpleRole;
import com.pentaho.security.SimpleUser;
import com.pentaho.security.acls.IAclSolutionFile;
import com.pentaho.security.acls.PentahoAclEntry;
public class SolutionRepositoryService extends ServletBase {
/**
*
*/
private static final long serialVersionUID = -5870073658756939643L;
private static final Log logger = LogFactory.getLog(SolutionRepositoryService.class);
/**
* contains instance of a sax parser factory. Use getSAXParserFactory() method
* to get a copy of the factory.
*/
private static final ThreadLocal<SAXParserFactory> SAX_FACTORY = new ThreadLocal<SAXParserFactory>();
private static final String RESPONSE_DOCUMENT_ENCODING = "UTF-8";
private static final String RESPONSE_DOCUMENT_VERSION_NUM = "1.0";
public Log getLogger() {
return logger;
}
public SolutionRepositoryService() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PentahoSystem.systemEntryPoint();
OutputStream outputStream = response.getOutputStream();
try {
boolean wrapWithSoap = "false".equals(request.getParameter("ajax")); //$NON-NLS-1$ //$NON-NLS-2$
String component = request.getParameter("component"); //$NON-NLS-1$
response.setContentType("text/xml"); //$NON-NLS-1$
response.setCharacterEncoding(LocaleHelper.getSystemEncoding());
IPentahoSession userSession = getPentahoSession(request);
// send the header of the message to prevent time-outs while we are working
response.setHeader("expires", "0"); //$NON-NLS-1$ //$NON-NLS-2$
dispatch(request, response, component, outputStream, userSession, wrapWithSoap);
/**
* NOTE: PLEASE DO NOT CATCH Exception, since this is the super class of RuntimeException.
* We do NOT want to catch RuntimeException, only CHECKED exceptions!
*/
} catch (IOException ex) {
commonErrorHandler( outputStream, ex );
} catch (SolutionRepositoryServiceException ex) {
commonErrorHandler( outputStream, ex );
} catch (PentahoAccessControlException ex) {
commonErrorHandler( outputStream, ex );
} finally {
PentahoSystem.systemExitPoint();
}
if (debug) {
debug(Messages.getString("HttpWebService.DEBUG_WEB_SERVICE_END")); //$NON-NLS-1$
}
}
private void commonErrorHandler( OutputStream outputStream, Exception ex ) throws IOException
{
String msg = Messages.getErrorString("SolutionRepositoryService.ERROR_0001_ERROR_DURING_SERVICE_REQUEST"); //$NON-NLS-1$;
error(msg, ex);
WebServiceUtil.writeString(outputStream, WebServiceUtil.getErrorXml(msg), false);
}
private static String[] getFilters( HttpServletRequest request )
{
String filter = request.getParameter("filter"); //$NON-NLS-1$
List<String> filters = new ArrayList<String>();
if (!StringUtils.isEmpty(filter)) {
StringTokenizer st = new StringTokenizer(filter, "*.,");
while (st.hasMoreTokens()) {
filters.add(st.nextToken());
}
}
return filters.toArray(new String[] {});
}
protected void dispatch(HttpServletRequest request, HttpServletResponse response, String component, OutputStream outputStream,
IPentahoSession userSession, boolean wrapWithSOAP) throws IOException, SolutionRepositoryServiceException, PentahoAccessControlException {
IParameterProvider parameterProvider = new HttpRequestParameterProvider(request);
if ("getSolutionRepositoryDoc".equals(component)) { //$NON-NLS-1$
String[] filters = getFilters( request );
Document doc = getSolutionRepositoryDoc(userSession, filters);
WebServiceUtil.writeDocument(outputStream, doc, wrapWithSOAP);
} else if ("createNewFolder".equals(component)) { //$NON-NLS-1$
String path = request.getParameter("path"); //$NON-NLS-1$
String name = request.getParameter("name"); //$NON-NLS-1$
String desc = request.getParameter("desc"); //$NON-NLS-1$
createFolder(userSession, path, name, desc);
WebServiceUtil.writeString(outputStream, "", wrapWithSOAP); //$NON-NLS-1$
} else if ("setAcl".equals(component)) { //$NON-NLS-1$
setAcl(parameterProvider, outputStream, userSession, wrapWithSOAP);
} else if ("getAcl".equals(component)) { //$NON-NLS-1$
getAcl(parameterProvider, outputStream, userSession, wrapWithSOAP);
} else {
throw new RuntimeException(Messages.getErrorString("HttpWebService.UNRECOGNIZED_COMPONENT_REQUEST", component)); //$NON-NLS-1$
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
private void createFolder(IPentahoSession userSession, String path, String name, String desc) throws IOException {
ISolutionRepository repository = PentahoSystem.getSolutionRepository(userSession);
File parent = new File(PentahoSystem.getApplicationContext().getSolutionPath(path));
File newFolder = new File(parent, name);
repository.createFolder(newFolder);
String defaultIndex = "<index><name>" + name + "</name><description>" + desc //$NON-NLS-1$
+ "</description><icon>reporting.png</icon><visible>true</visible><display-type>list</display-type></index>"; //$NON-NLS-1$
repository.addSolutionFile(PentahoSystem.getApplicationContext().getSolutionPath(""), path + RepositoryFile.SEPARATOR + name,
SolutionRepositoryBase.INDEX_FILENAME, defaultIndex
.getBytes(), true);
repository.reloadSolutionRepository( userSession, repository.getLoggingLevel() );
CacheManager cacheManager = PentahoSystem.getCacheManager();
if (null != cacheManager) {
cacheManager.removeFromSessionCache(userSession, repository.getRootFolder().getFileName());
}
}
private boolean acceptFilter(String name, String[] filters) {
if (filters == null || filters.length == 0) {
return true;
}
for (int i = 0; i < filters.length; i++) {
if (name.endsWith(filters[i])) {
return true;
}
}
return false;
}
private void processRepositoryFile(Element parentElement, ISolutionFile parentFile, IFileFilter permissionFilter, String[] filters) {
ISolutionFile children[] = parentFile.listFiles(permissionFilter);
for (int i = 0; children != null && i < children.length; i++) {
String name = children[i].getFileName();
if (!name.startsWith(".") && (children[i].isDirectory() || acceptFilter(name, filters))) { //$NON-NLS-1$
Element child = parentElement.addElement("file"); //$NON-NLS-1$
child.addAttribute("name", name); //$NON-NLS-1$
child.addAttribute("isDirectory", "" + children[i].isDirectory()); //$NON-NLS-1$
child.addAttribute("lastModifiedDate", "" + children[i].getLastModified()); //$NON-NLS-1$
if (children[i].isDirectory()) {
processRepositoryFile(child, children[i], permissionFilter, filters);
}
}
}
}
private Document getSolutionRepositoryDoc(IPentahoSession userSession, String[] filters) {
ISolutionRepository repository = PentahoSystem.getSolutionRepository(userSession);
PermissionFilter permissionFilter = new PermissionFilter(repository);
ISolutionFile rootFile = repository.getRootFolder();
Document document = null;
CacheManager cacheManager = PentahoSystem.getCacheManager();
if (null != cacheManager) {
document = (Document) cacheManager.getFromSessionCache(userSession, rootFile.getFileName());
if (document == null) {
document = DocumentHelper.createDocument();
Element root = document.addElement("repository");
root.addAttribute("path", rootFile.getFullPath());
processRepositoryFile(root, rootFile, permissionFilter, filters);
cacheManager.putInSessionCache(userSession, rootFile.getFileName(), document);
}
} else {
document = DocumentHelper.createDocument();
Element root = document.addElement("repository");
root.addAttribute("path", rootFile.getFullPath());
processRepositoryFile(root, rootFile, permissionFilter, filters);
}
return document;
}
private void getAcl(IParameterProvider parameterProvider, OutputStream outputStream,
IPentahoSession userSession, boolean wrapWithSOAP) throws SolutionRepositoryServiceException, IOException
{
String solution = parameterProvider.getStringParameter("solution", null); //$NON-NLS-1$
String path = parameterProvider.getStringParameter("path", null); //$NON-NLS-1$
String filename = parameterProvider.getStringParameter("filename", null); //$NON-NLS-1$
if ( StringUtil.doesPathContainParentPathSegment( solution )
|| StringUtil.doesPathContainParentPathSegment( path ) ) {
String msg = Messages.getString( "AdhocWebService.ERROR_0008_MISSING_OR_INVALID_REPORT_NAME" ); //$NON-NLS-1$
throw new SolutionRepositoryServiceException( msg );
}
ISolutionRepository repository = PentahoSystem.getSolutionRepository(userSession);
String fullPath = WebServiceUtil.buildSolutionPath( solution, path, filename );
ISolutionFile solutionFile = repository.getFileByPath( fullPath );
String strXml = null;
//ouch, i hate instanceof
if ( solutionFile instanceof IAclSolutionFile ) {
Map <IPermissionRecipient, IPermissionMask> filePermissions = repository.getPermissions((solutionFile));
String processingInstruction = CleanXmlHelper.createXmlProcessingInstruction( RESPONSE_DOCUMENT_VERSION_NUM, RESPONSE_DOCUMENT_ENCODING );
strXml = processingInstruction + getAclAsXml( filePermissions );
}
else
{
strXml = "<acl notsupported='true'/>"; //$NON-NLS-1$
}
WebServiceUtil.writeString( outputStream, strXml, false );
}
// TODO sbarkdull, this method belongs in an AclUtils class?
// turn acl into an XML representation, and return the document.
// probably belongs in the SecurityUtils class, but does this class still exist?
String getAclAsXml( Map<IPermissionRecipient, IPermissionMask> filePermissions )
{
StringBuffer sb = new StringBuffer( CleanXmlHelper.createXmlProcessingInstruction( RESPONSE_DOCUMENT_VERSION_NUM, RESPONSE_DOCUMENT_ENCODING));
sb.append( "<acl>" );
for (Map.Entry<IPermissionRecipient, IPermissionMask> filePerm : filePermissions.entrySet()) {
IPermissionRecipient permRecipient = filePerm.getKey();
if (permRecipient instanceof SimpleRole) {
sb.append( "<entry role='" + permRecipient.getName()
+ "' permissions='" + filePerm.getValue().getMask() + "'/>" );
} else {
// entry belongs to a user
sb.append( "<entry user='" + permRecipient.getName()
+ "' permissions='" + filePerm.getValue().getMask() + "'/>" );
}
}
sb.append( "</acl>" );
return sb.toString();
}
Map<IPermissionRecipient, IPermissionMask> createAclFromXml( String strXml ) throws ParserConfigurationException, SAXException, IOException
{
SAXParser parser = SolutionRepositoryService.getSAXParserFactory().newSAXParser();
Map<IPermissionRecipient, IPermissionMask> m = new HashMap<IPermissionRecipient, IPermissionMask>();
DefaultHandler h = new AclParserHandler( m );
String encoding = CleanXmlHelper.getEncoding( strXml );
InputStream is = new ByteArrayInputStream( strXml.getBytes( encoding ) );
parser.parse(is, h );
return m;
}
private class AclParserHandler extends DefaultHandler {
Map<IPermissionRecipient, IPermissionMask> acl;
public AclParserHandler( Map<IPermissionRecipient, IPermissionMask> acl )
{
this.acl = acl;
}
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
{
if ( qName.equalsIgnoreCase( "entry" ) ) {
PentahoAclEntry entry = null;
String permissions = (String)attributes.getValue("", "permissions" );
IPermissionRecipient permRecipient = null;
String user = (String)attributes.getValue("", "user" );
if (null != user) {
permRecipient = new SimpleUser(user);
} else {
permRecipient = new SimpleRole((String)attributes.getValue("", "role" ));
}
this.acl.put(permRecipient, new SimplePermissionMask(Integer.parseInt( permissions )));
}
}
}
private void setAcl(IParameterProvider parameterProvider, OutputStream outputStream,
IPentahoSession userSession, boolean wrapWithSOAP) throws SolutionRepositoryServiceException, IOException, PentahoAccessControlException
{
String solution = parameterProvider.getStringParameter("solution", null); //$NON-NLS-1$ //$NON-NLS-2$
String path = parameterProvider.getStringParameter("path", null); //$NON-NLS-1$ //$NON-NLS-2$
String filename = parameterProvider.getStringParameter("filename", null); //$NON-NLS-1$
String strAclXml = parameterProvider.getStringParameter("aclXml", null); //$NON-NLS-1$
if ( StringUtil.doesPathContainParentPathSegment( solution )
|| StringUtil.doesPathContainParentPathSegment( path ) ) {
String msg = Messages.getString( "AdhocWebService.ERROR_0008_MISSING_OR_INVALID_REPORT_NAME" ); //$NON-NLS-1$
throw new SolutionRepositoryServiceException( msg );
}
ISolutionRepository repository = PentahoSystem.getSolutionRepository(userSession);
String fullPath = WebServiceUtil.buildSolutionPath( solution, path, filename );
ISolutionFile solutionFile = repository.getFileByPath( fullPath );
//ouch, i hate instanceof
if ( solutionFile instanceof IAclSolutionFile ) {
Map<IPermissionRecipient, IPermissionMask> acl;
try {
acl = createAclFromXml( strAclXml );
// TODO sbarkdull, fix these really really lame exception msgs
} catch (ParserConfigurationException e) {
throw new SolutionRepositoryServiceException( "ParserConfigurationException", e );
} catch (SAXException e) {
throw new SolutionRepositoryServiceException( "SAXException", e );
} catch (IOException e) {
throw new SolutionRepositoryServiceException( "IOException", e );
}
repository.setPermissions(solutionFile, acl);
}
// TODO sbarkdull, what if its not instanceof
String msg = WebServiceUtil.getStatusXml( Messages.getString("AdhocWebService.ACL_UPDATE_SUCCESSFUL") ); //$NON-NLS-1$
WebServiceUtil.writeString( outputStream, msg, false );
}
/**
* Get a SAX Parser Factory
*
* NOTE: Need sax parser factory per thread for thread safety.
* See: http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/parsers/SAXParserFactory.html
* @return
*/
public static SAXParserFactory getSAXParserFactory() {
SAXParserFactory threadLocalSAXParserFactory = SAX_FACTORY.get();
if ( null == threadLocalSAXParserFactory )
{
threadLocalSAXParserFactory = SAXParserFactory.newInstance();
SAX_FACTORY.set( threadLocalSAXParserFactory );
}
return threadLocalSAXParserFactory;
}
}
The table below shows all metrics for SolutionRepositoryService.java.




