Commits

Tim Olsen  committed 6b7f611 Merge

Merge

  • Participants
  • Parent commits 6a8ba37, 942c3c5

Comments (0)

Files changed (8)

File src/main/java/org/nrg/xdat/turbine/modules/actions/XDATLoginUser.java

 import org.nrg.xdat.turbine.utils.TurbineUtils;
 import org.nrg.xft.XFTItem;
 import org.nrg.xft.schema.Wrappers.GenericWrapper.GenericWrapperElement;
+import org.postgresql.util.PSQLException;
 /**
  * @author Tim
  *
 			HttpSession session = data.getSession();
 			session.setAttribute("user",user);
             session.setAttribute("loggedin",true);
-            
+
             try{
             	doRedirect(data,context,user);
             }catch(Exception e){
 		catch (Exception e)
 		{
             log.error("",e);
-            
+
             if(username.toLowerCase().contains("script"))
             {
             	e= new Exception("Illegal username <script> usage.");
                 data.getParameters().setString("exception", e.toString());
                 return;
             }
-            
+
 				// Set Error Message and clean out the user.
+            if(e instanceof PSQLException){
+				data.setMessage("An error has occurred.  Please contact a site administrator for assistance.");
+            }else{
 				data.setMessage(e.getMessage());
+            }
 				String loginTemplate =  org.apache.turbine.Turbine.getConfiguration().getString("template.login");
 
 				if (StringUtils.isNotEmpty(loginTemplate))
 				}
 		}
 	}
-	
+
 	public void doRedirect(RunData data, Context context,XDATUser user) throws Exception{
 		String nextPage = data.getParameters().getString("nextPage","");
 		String nextAction = data.getParameters().getString("nextAction","");

File src/main/java/org/nrg/xdat/turbine/modules/actions/XMLUpload.java

                 if(!handler.assertValid()){
                 	throw handler.getErrors().get(0);
                 }
-                
+
                 //Document doc = XMLUtils.GetDOM(fi.getInputStream());
                 //item = XMLReader.TranslateDomToItem(doc,TurbineUtils.getUser(data));
                 SAXReader reader = new SAXReader(TurbineUtils.getUser(data));
                 if (XFT.VERBOSE)
                     System.out.println("Loaded XML Item:" + item.getProperName());
                 logger.info("Loaded XML Item:" + item.getProperName());
-                
+
                 ValidationResults vr = XFTValidator.Validate(item);
                 if (vr.isValid())
                 {
                     if (XFT.VERBOSE)
                         System.out.println("Validation: PASSED");
                     logger.info("Validation: PASSED");
-                	
+
                 	boolean q;
                 	boolean override;
                 	q = item.getGenericSchemaElement().isQuarantine();
                 	override = false;
-                	   
+
                 	if (allowDeletion.equalsIgnoreCase("true"))
                 	{
                     	SaveItemHelper.Save(item,TurbineUtils.getUser(data),false,q,override,true);
                 	}else{
                     	SaveItemHelper.Save(item,TurbineUtils.getUser(data),false,q,override,false);
                 	}
-                	
+
                 	if(XFT.VERBOSE)System.out.println("Item Successfully Stored.");
-                    logger.info("Item Successfully Stored.");	
-                    
+                    logger.info("Item Successfully Stored.");
+
                     DisplayItemAction dia = new DisplayItemAction();
                 	data = TurbineUtils.SetSearchProperties(data,item);
                 	dia.doPerform(data,context);
-                	
+
                 	postProcessing(item,data,context);
-                	
+
                 	return;
                 }else
                 {
 				    logger.error("",e);
                     data.setScreenTemplate("Error.vm");
                     String message = "Permissions Exception.<BR><BR>" + e.getMessage();
-                    SchemaElement se = SchemaElement.GetElement(item.getXSIType());
-                    message += "<BR><BR>Please review the security field (" + se.getElementSecurity().getSecurityFields() + ") for this data type.";
-                    message += " Verify that the data reflects a currently stored value and the user has relevant permissions for this data.";
+                    final SchemaElement se = SchemaElement.GetElement(item.getXSIType());
+                    final ElementSecurity es=se.getElementSecurity();
+                    if(es!=null && es.getSecurityFields()!=null){
+                    	message += "<BR><BR>Please review the security field (" + se.getElementSecurity().getSecurityFields() + ") for this data type.";
+                    	message += " Verify that the data reflects a currently stored value and the user has relevant permissions for this data.";
+                    }
                     data.setMessage(message);
 				}else{
 	                logger.error("",e);
             }
         }
     }
+
     public void postProcessing(XFTItem item,RunData data, Context context) throws Exception{
         SchemaElementI se = SchemaElement.GetElement(item.getXSIType());
         if (se.getGenericXFTElement().getType().getLocalPrefix().equalsIgnoreCase("xdat"))

File src/main/java/org/nrg/xdat/turbine/modules/screens/Login.java

 package org.nrg.xdat.turbine.modules.screens;
 
 import org.apache.turbine.modules.screens.VelocitySecureScreen;
+import org.apache.turbine.services.velocity.TurbineVelocity;
 import org.apache.turbine.util.RunData;
 import org.apache.velocity.context.Context;
+import org.nrg.xdat.turbine.utils.TurbineUtils;
 
 public class Login extends VelocitySecureScreen {
+
+	@Override
+	protected void doBuildTemplate(RunData data) throws Exception {
+		Context c = TurbineVelocity.getContext(data);
+        String systemName = TurbineUtils.GetSystemName();
+        c.put("turbineUtils",TurbineUtils.GetInstance());
+        c.put("systemName",systemName);
+        doBuildTemplate(data, c);
+	}
+
 	@Override
 	protected void doBuildTemplate(RunData data, Context context) throws Exception {
 		for(final Object param : data.getParameters().keySet()){
 		}
 	}
 
+
+
+
 	@Override
 	protected boolean isAuthorized(RunData arg0) throws Exception {
 		return false;

File src/main/java/org/nrg/xdat/turbine/modules/screens/Register.java

 package org.nrg.xdat.turbine.modules.screens;
 
 import org.apache.turbine.modules.screens.VelocitySecureScreen;
+import org.apache.turbine.services.velocity.TurbineVelocity;
 import org.apache.turbine.util.RunData;
 import org.apache.velocity.context.Context;
+import org.nrg.xdat.turbine.utils.TurbineUtils;
 
 public class Register extends VelocitySecureScreen {
 
+
+	@Override
+	protected void doBuildTemplate(RunData data) throws Exception {
+		Context c = TurbineVelocity.getContext(data);
+        String systemName = TurbineUtils.GetSystemName();
+        c.put("turbineUtils",TurbineUtils.GetInstance());
+        c.put("systemName",systemName);
+        doBuildTemplate(data, c);
+	}
+
 	@Override
 	protected void doBuildTemplate(RunData data, Context context) throws Exception {
 		for(final Object param : data.getParameters().keySet()){
 			final String paramS= (String)param;
-			if ((!paramS.equalsIgnoreCase("template")) 
+			if ((!paramS.equalsIgnoreCase("template"))
 					&& (!paramS.equalsIgnoreCase("action"))
 					&& (!paramS.equalsIgnoreCase("username"))
 					&& (!paramS.equalsIgnoreCase("password"))){

File src/main/java/org/nrg/xdat/turbine/utils/TurbineUtils.java

     }
     
     public String escapeHTML(String o){
-    	return StringEscapeUtils.escapeHtml(o);
+    	return (o==null)?null:StringEscapeUtils.escapeHtml(o);
+    }
+    
+    public String escapeJS(String o){
+    	return (o==null)?null:StringEscapeUtils.escapeJavaScript(o);
     }
 }
 

File src/main/java/org/nrg/xft/db/DBConfig.java

 			ds.setPassword(pass);
 			ds.setUrl(url);
 			ds.setMaxActive(maxConnections);
+			ds.setValidationQuery("SELECT NOW();");
 			dataSource = ds;
 		}
 		return dataSource.getConnection();

File src/main/java/org/nrg/xft/db/PoolDBUtils.java

 		try {
 			if (sequence != null && !sequence.equalsIgnoreCase(""))
 			{
-				st = getConnection(db).createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
+				st = getStatement(db);
 				logger.debug("QUERY:" + query);
 				st.execute(query);
 				String newQuery = "SELECT currval('"+ sequence + "') AS " + pk;
 					}
 				}
 			}else{
-				st = getConnection(db).createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
+				st = getStatement(db);
 				st.execute(query);
 				String newQuery = "SELECT currval('"+ table + "_" + pk + "_seq') AS " + pk;
 				try {
 		try {
 			if (sequence != null && !sequence.equalsIgnoreCase(""))
 			{
-				st = getConnection(db).createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
+				st = getStatement(db);
 				String newQuery = "SELECT nextval('"+ sequence + "') AS " + pk;
 				try {
 					rs = st.executeQuery(newQuery);
 					}
 				}
 			}else{
-				st = getConnection(db).createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
+				st = getStatement(db);
 				String newQuery = "SELECT nextval('"+ table + "_" + pk + "_seq') AS " + pk;
 				try {
 					rs = st.executeQuery(newQuery);
 
 		return o;
 	}
-	
-	public void sendFunctionBatch(ArrayList<String> statements,String db,String userName,int resultSetType,int resultSetConcurrency) throws SQLException, Exception{
-		if(db==null)db=PoolDBUtils.getDefaultDBName();
-	    Date start = Calendar.getInstance().getTime();
-	    try {
-            con = getConnection(db);
-            try {
-            	con.setAutoCommit(false);
 
-            	st = con.prepareCall(statements.get(0), resultSetType, resultSetConcurrency);
-            	st.clearBatch();
-            	for (String stmt:statements)
-            	{
-            	    st.addBatch(stmt);
-            	}
-
-            	st.executeBatch();
-            	
-            	logger.debug(getTimeDiff(start,Calendar.getInstance().getTime()) + " ms" + " (" + userName + "): " + StringUtils.ReplaceStr("BATCH","\n"," "));
-
-            	st.clearBatch();
-
-            	con.commit();
-            }catch (SQLException e) {
-                con.rollback();
-                logger.error(statements.toString());
-                logger.error(e.getMessage());
-               throw e.getNextException();
-			}finally{
-			    con.setAutoCommit(true);
-			}
-        } catch (DBPoolException e) {
-            logger.error("",e);
-            throw e;
-        }finally{
-		    closeConnection(null);
-		}
-	}
-	
-	public void sendBatch(ArrayList<String> statements,String db,String userName,int resultSetType,int resultSetConcurrency) throws SQLException, Exception{
+	private void sendBatchExec(ArrayList<String> statements,String db,String userName,int resultSetType,int resultSetConcurrency) throws SQLException, Exception{
 		if(db==null)db=PoolDBUtils.getDefaultDBName();
 	    Date start = Calendar.getInstance().getTime();
 	    try {
 		    closeConnection(null);
 		}
 	}
-	
+
 
 	public void sendBatch(DBItemCache cache,String db,String userName) throws SQLException, Exception
 	{
 	 */
 	public void executeNonSelectQuery(String query,String db, String userName) throws SQLException,Exception
 	{
-	    Date start = Calendar.getInstance().getTime();
-	    if(db==null)db=PoolDBUtils.getDefaultDBName();
 		try {
-			st = getConnection(db).createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
-			try {
-				st.execute(query);
-			} catch (SQLException e) {
-				if(e.getMessage().indexOf("Connection reset")>-1){
-					resetConnections();
-					st.execute(query);
-				}else{
-					throw e;
-				}
-			}
-			logger.debug(getTimeDiff(start,Calendar.getInstance().getTime()) + " ms" + " (" + userName + "): " + StringUtils.ReplaceStr(query,"\n"," "));
-
+			execute(db, query, userName);
 		}catch (SQLException e) {
 		    logger.error(query);
 		   throw e;
 	public static void ExecuteNonSelectQuery(String query,String db, String userName) throws SQLException,Exception
 	{
 		PoolDBUtils con = new PoolDBUtils();
-		
+
 		con.executeNonSelectQuery(query,db,userName);
 	}
 
 	public static void ExecuteBatch(ArrayList<String> queries,String db, String userName) throws SQLException,Exception
 	{
 		PoolDBUtils con = new PoolDBUtils();
-		
+
 		con.sendBatch(queries,db,userName, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
 	}
 
-
-	public static void ExecuteFunctionBatch(ArrayList<String> queries,String db, String userName) throws SQLException,Exception
-	{
-		PoolDBUtils con = new PoolDBUtils();
-		
-		con.sendFunctionBatch(queries,db,userName, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
-	}
-
 	public Object returnStatisticQuery(String query,String column,String db, String userName) throws SQLException,Exception
 	{
 		Object o = null;
 		ResultSet rs = null;
-		Date start = Calendar.getInstance().getTime();
 		try {
-			st = getConnection(db).createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
-			try {
-				rs = st.executeQuery(query);
-			} catch (SQLException e) {
-				if(e.getMessage().indexOf("Connection reset")>-1){
-					resetConnections();
-					rs = st.executeQuery(query);
-				}else{
-					throw e;
-				}
-			}
+			rs=executeQuery(db, query, userName);
 
 			if (rs.first())
 			{
 				o = rs.getObject(column);
 			}
 
-			logger.debug(getTimeDiff(start,Calendar.getInstance().getTime()) + " ms" + " (" + userName + "): " + StringUtils.ReplaceStr(query,"\n"," "));
-
 		} catch (SQLException e) {
 			logger.error(query);
 			throw e;
 		return con.returnStatisticQuery(query,column,db,userName);
 	}
 
-	public void resetConnections(){
+	private void resetConnections(){
 		System.out.println("WARNING: DB CONNECTION FAILURE: Resetting all DB connections!!!!!!");
 		this.con=null;
 		DBPool.GetPool().resetConnections();
 		ResultSet rs = null;
 		XFTTable results = new XFTTable();
 
-	    if(db==null)db=PoolDBUtils.getDefaultDBName();
 		try {
-			st = getConnection(db).createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
-			Date start = Calendar.getInstance().getTime();
+		    rs=executeQuery(db, query, userName);
 
-			try {
-				rs = st.executeQuery(query);
-			} catch (SQLException e) {
-				if(e.getMessage().indexOf("Connection reset")>-1){
-					resetConnections();
-					rs = st.executeQuery(query);
-				}else{
-					throw e;
-				}
-			}
-
-			logger.debug(getTimeDiff(start,Calendar.getInstance().getTime()) + " ms" + " (" + userName + "): " + StringUtils.ReplaceStr(query,"\n"," "));
-
-			String[] columns = new String[rs.getMetaData().getColumnCount()];
+			final String[] columns = new String[rs.getMetaData().getColumnCount()];
 			for (int i=1;i<=columns.length;i++)
 			{
 				columns[i-1]= rs.getMetaData().getColumnName(i);
 		{
 			try {
 				rs.close();
-			} catch (SQLException e) {
+			} catch (Throwable e) {
 				e.printStackTrace();
 			}
 		}
+		closeConnection();
+	}
+
+	private void closeConnection()
+	{
 		if (st != null)
 		{
 			try {
 				st.close();
-			} catch (SQLException e) {
+			} catch (Throwable e) {
 				e.printStackTrace();
 			}
 		}
 		{
 			try {
 				con.close();
-			} catch (SQLException e) {
+			} catch (Throwable e) {
 				e.printStackTrace();
 			}
 		}
             logger.error("",e);
         }
     }
-    
+
     public static String getDefaultDBName(){
     	DBConfig config=DBPool.GetDBConfig((String)DBPool.GetPool().getDS().keySet().toArray()[0]);
     	return config.getDbIdentifier();
 
                 CreateCache(e.getDbName(),login);
 
-                long localTime = Calendar.getInstance().getTimeInMillis();
                 itemString =(String)PoolDBUtils.ReturnStatisticQuery("SELECT contents FROM xs_item_cache WHERE elementName='" + rootElement + "' AND ids='" + ids + "';","contents",e.getDbName(),login);
                 if (itemString==null){
                     itemString =(String)PoolDBUtils.ReturnStatisticQuery(functionQuery,functionName,e.getDbName(),login);
             String ids = "";
             ArrayList keys = item.getGenericSchemaElement().getAllPrimaryKeys();
             Iterator keyIter = keys.iterator();
-            String pk = null;
             while (keyIter.hasNext())
             {
                 GenericWrapperField sf = (GenericWrapperField)keyIter.next();
         mv.setTable_name(tablename);
         mv.setSearch_sql(query);
         mv.save();
-        
+
         return mv.getSize();
     }
 
         	return mv.getData(null, offset, rowsPerPage);
         }
     }
-    
-    public static boolean HackCheck(String value) 
+
+    public static boolean HackCheck(String value)
     {
     	value=value.toUpperCase();
     	if(value.matches("<*SCRIPT"))return true;
     	if(StringContains(value,"DROP")) return true;
     	if(StringContains(value,"ALTER")) return true;
     	if(StringContains(value,"CREATE")) return true;
-    	
+
     	return false;
     }
-    
+
     public static boolean StringContains(String value, String s){
     	if(value.contains(s+' ')){
     		if(value.startsWith(s +' ')) return true;
     	}
     		return false;
     }
+
+    private Statement getStatement(String db) throws DBPoolException,SQLException{
+    	return getConnection(db).createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
+    }
+
+    private ResultSet executeQuery(String db, String query, String userName) throws SQLException, DBPoolException{
+    	ResultSet rs;
+
+    	if(db==null)db=PoolDBUtils.getDefaultDBName();
+
+		st = getStatement(db);
+		final Date start = Calendar.getInstance().getTime();
+
+		try {
+			rs = st.executeQuery(query);
+		} catch (SQLException e) {
+			if(e.getMessage().contains("Connection reset")){
+				closeConnection();
+				resetConnections();
+				st = getStatement(db);
+				rs = st.executeQuery(query);
+			}else{
+				throw e;
+			}
+		}
+
+		logger.debug(getTimeDiff(start,Calendar.getInstance().getTime()) + " ms" + " (" + userName + "): " + StringUtils.ReplaceStr(query,"\n"," "));
+
+		return rs;
+    }
+
+    private void execute(String db, String query, String userName) throws SQLException, DBPoolException{
+    	if(db==null)db=PoolDBUtils.getDefaultDBName();
+
+		st = getStatement(db);
+		final Date start = Calendar.getInstance().getTime();
+
+		try {
+			st.execute(query);
+		} catch (SQLException e) {
+			if(e.getMessage().contains("Connection reset")){
+				closeConnection();
+				resetConnections();
+				st = getStatement(db);
+				st.execute(query);
+			}else{
+				throw e;
+			}
+		}
+
+		logger.debug(getTimeDiff(start,Calendar.getInstance().getTime()) + " ms" + " (" + userName + "): " + StringUtils.ReplaceStr(query,"\n"," "));
+    }
+
+	public void sendBatch(ArrayList<String> statements,String db,String userName,int resultSetType,int resultSetConcurrency) throws SQLException, Exception{
+		try{
+			sendBatchExec(statements,db,userName,resultSetType,resultSetConcurrency);
+		}catch(SQLException e){
+			if(e.getMessage().contains("Connection reset")){
+				sendBatchExec(statements,db,userName,resultSetType,resultSetConcurrency);
+			}
+		}
+	}
 }
 

File src/main/java/org/nrg/xft/utils/SaveItemHelper.java

 
 import org.apache.log4j.Logger;
 import org.nrg.xdat.base.BaseElement;
+import org.nrg.xdat.security.XDATUser;
 import org.nrg.xft.ItemI;
+import org.nrg.xft.XFT;
+import org.nrg.xft.ItemWrapper;
+
+
 import org.nrg.xft.XFTItem;
+import org.nrg.xft.exception.InvalidPermissionException;
 import org.nrg.xft.security.UserI;
 
 public class SaveItemHelper {
 	public static SaveItemHelper getInstance(){
 		return new SaveItemHelper();
 	}
-	
+
 	protected void save(ItemI i,UserI user, boolean overrideSecurity, boolean quarantine, boolean overrideQuarantine, boolean allowItemRemoval) throws Exception {
 		if(i==null){
 			throw new NullPointerException();
 		}
-		
+
+		if(i.getItem().getGenericSchemaElement().getType().getForeignPrefix().equals(XFT.PREFIX)){
+        	if (!((XDATUser)user).checkRole("Administrator"))
+            {
+        		throw new InvalidPermissionException("Only site administrators can store core documents.");
+            }
+        }
+
 		if(i instanceof XFTItem){
 			ItemI temp=BaseElement.GetGeneratedItem(i);
 			temp.save(user, overrideSecurity, quarantine, overrideQuarantine, allowItemRemoval);
 			i.save(user,overrideSecurity,quarantine,overrideQuarantine,allowItemRemoval);
 		}
 	}
-	
+
 	protected void save(ItemI i,UserI user, boolean overrideSecurity, boolean allowItemRemoval) throws Exception {
 		if(i==null){
 			throw new NullPointerException();
 		}
-		
+
+		if(i.getItem().getGenericSchemaElement().getType().getForeignPrefix().equals(XFT.PREFIX)){
+        	if (!((XDATUser)user).checkRole("Administrator"))
+            {
+        		throw new InvalidPermissionException("Only site administrators can store core documents.");
+            }
+        }
+
 		if(i instanceof XFTItem){
 			ItemI temp=BaseElement.GetGeneratedItem(i);
 			temp.save(user, overrideSecurity, allowItemRemoval);
 			i.save(user,overrideSecurity,allowItemRemoval);
 		}
 	}
-	
+
 	public static void Save(ItemI i,UserI user, boolean overrideSecurity, boolean quarantine, boolean overrideQuarantine, boolean allowItemRemoval) throws Exception {
 		getInstance().save(i, user, overrideSecurity, quarantine, overrideQuarantine, allowItemRemoval);
 	}
-	
+
 	public static void Save(ItemI i,UserI user, boolean overrideSecurity, boolean allowItemRemoval) throws Exception {
 		getInstance().save(i, user, overrideSecurity, allowItemRemoval);
 	}