public BufferedImage filter(BufferedImage src, Struct parameters) throws PageException { BufferedImage dst = ImageUtil.createBufferedImage(src); Object o; if ((o = parameters.removeEL(KeyImpl.init("Threshold"))) != null) setThreshold(ImageFilterUtil.toIntValue(o, "Threshold")); if ((o = parameters.removeEL(KeyImpl.init("Iterations"))) != null) setIterations(ImageFilterUtil.toIntValue(o, "Iterations")); if ((o = parameters.removeEL(KeyImpl.init("Colormap"))) != null) setColormap(ImageFilterUtil.toColormap(o, "Colormap")); if ((o = parameters.removeEL(KeyImpl.init("NewColor"))) != null) setNewColor(ImageFilterUtil.toColorRGB(o, "NewColor")); // check for arguments not supported if (parameters.size() > 0) { throw new FunctionException( ThreadLocalPageContext.get(), "ImageFilter", 3, "parameters", "the parameter" + (parameters.size() > 1 ? "s" : "") + " [" + CollectionUtil.getKeyList(parameters, ", ") + "] " + (parameters.size() > 1 ? "are" : "is") + " not allowed, only the following parameters are supported [Threshold, Iterations, Colormap, NewColor, BlackFunction]"); } return filter(src, dst); }
public BufferedImage filter(BufferedImage src, Struct parameters) throws PageException { BufferedImage dst = null; // ImageUtil.createBufferedImage(src); Object o; if ((o = parameters.removeEL(KeyImpl.init("Type"))) != null) setType(ImageFilterUtil.toString(o, "Type")); if ((o = parameters.removeEL(KeyImpl.init("EdgeAction"))) != null) setEdgeAction(ImageFilterUtil.toString(o, "EdgeAction")); if ((o = parameters.removeEL(KeyImpl.init("Interpolation"))) != null) setInterpolation(ImageFilterUtil.toString(o, "Interpolation")); // check for arguments not supported if (parameters.size() > 0) { throw new FunctionException( ThreadLocalPageContext.get(), "ImageFilter", 3, "parameters", "the parameter" + (parameters.size() > 1 ? "s" : "") + " [" + List.arrayToList(parameters.keysAsString(), ", ") + "] " + (parameters.size() > 1 ? "are" : "is") + " not allowed, only the following parameters are supported [Type, EdgeAction, Interpolation]"); } return filter(src, dst); }
public BufferedImage filter(BufferedImage src, Struct parameters) throws PageException { BufferedImage dst = ImageUtil.createBufferedImage(src); Object o; if ((o = parameters.removeEL(KeyImpl.init("Radius"))) != null) setRadius(ImageFilterUtil.toFloatValue(o, "Radius")); if ((o = parameters.removeEL(KeyImpl.init("Sides"))) != null) setSides(ImageFilterUtil.toIntValue(o, "Sides")); if ((o = parameters.removeEL(KeyImpl.init("Bloom"))) != null) setBloom(ImageFilterUtil.toFloatValue(o, "Bloom")); if ((o = parameters.removeEL(KeyImpl.init("BloomThreshold"))) != null) setBloomThreshold(ImageFilterUtil.toFloatValue(o, "BloomThreshold")); // check for arguments not supported if (parameters.size() > 0) { throw new FunctionException( ThreadLocalPageContext.get(), "ImageFilter", 3, "parameters", "the parameter" + (parameters.size() > 1 ? "s" : "") + " [" + CollectionUtil.getKeyList(parameters, ", ") + "] " + (parameters.size() > 1 ? "are" : "is") + " not allowed, only the following parameters are supported [Radius, Sides, Bloom, BloomThreshold]"); } return filter(src, dst); }
private static Struct checkTableFill(DatabaseMetaData md, String dbName, String tableName) throws SQLException, PageException { Struct rows = new CastableStruct(tableName, Struct.TYPE_LINKED); ResultSet columns = md.getColumns(dbName, null, tableName, null); // print.o(new QueryImpl(columns,"")); try { String name; Object nullable; while (columns.next()) { name = columns.getString("COLUMN_NAME"); nullable = columns.getObject("IS_NULLABLE"); rows.setEL( KeyImpl.init(name), new ColumnInfo( name, columns.getInt("DATA_TYPE"), columns.getString("TYPE_NAME"), columns.getInt("COLUMN_SIZE"), Caster.toBooleanValue(nullable))); } } finally { DBUtil.closeEL(columns); } // Table susid defined for cfc susid does not exist. return rows; }
public BufferedImage filter(BufferedImage src, Struct parameters) throws PageException { BufferedImage dst = ImageUtil.createBufferedImage(src); Object o; if ((o = parameters.removeEL(KeyImpl.init("Dimensions"))) != null) { int[] dim = ImageFilterUtil.toDimensions(o, "Dimensions"); setDimensions(dim[0], dim[1]); } // check for arguments not supported if (parameters.size() > 0) { throw new FunctionException( ThreadLocalPageContext.get(), "ImageFilter", 3, "parameters", "the parameter" + (parameters.size() > 1 ? "s" : "") + " [" + List.arrayToList(parameters.keysAsString(), ", ") + "] " + (parameters.size() > 1 ? "are" : "is") + " not allowed, only the following parameters are supported [Dimensions]"); } return filter(src, dst); }
public static void addSet(ComponentImpl comp, Property prop) { Member m = comp.getMember( ComponentImpl.ACCESS_PRIVATE, KeyImpl.init("set" + prop.getName()), true, false); if (!(m instanceof UDF)) { UDF udf = new UDFSetterProperty(comp, prop); comp.registerUDF(udf.getFunctionName(), udf); } }
private void set(DatasourceConnection dc) { if (dc != null) { datasource = dc.getDatasource(); try { DatabaseMetaData md = dc.getConnection().getMetaData(); md.getDatabaseProductName(); setAdditional(KeyImpl.init("DatabaseName"), md.getDatabaseProductName()); setAdditional(KeyImpl.init("DatabaseVersion"), md.getDatabaseProductVersion()); setAdditional(KeyImpl.init("DriverName"), md.getDriverName()); setAdditional(KeyImpl.init("DriverVersion"), md.getDriverVersion()); // setAdditional("url",md.getURL()); setAdditional(KeyConstants._Datasource, dc.getDatasource().getName()); } catch (SQLException e) { } } }
public static void addAdd(ComponentImpl comp, Property prop) { Member m = comp.getMember( ComponentImpl.ACCESS_PRIVATE, KeyImpl.init("add" + getSingularName(prop)), true, false); if (!(m instanceof UDF)) { UDF udf = new UDFAddProperty(comp, prop); comp.registerUDF(udf.getFunctionName(), udf); } }
public Struct getTableInfo(DatasourceConnection dc, String tableName, ORMEngine engine) throws PageException { Collection.Key keyTableName = KeyImpl.init(tableName); Struct columnsInfo = (Struct) tableInfo.get(keyTableName, null); if (columnsInfo != null) return columnsInfo; columnsInfo = checkTable(dc, tableName, engine); tableInfo.setEL(keyTableName, columnsInfo); return columnsInfo; }
public Collection.Key[] keys() { Set keySet = component.keySet(access); keySet.add("this"); Collection.Key[] arr = new Collection.Key[keySet.size()]; Iterator it = keySet.iterator(); int index = 0; while (it.hasNext()) { arr[index++] = KeyImpl.toKey(it.next(), null); } return arr; }
/** returns the root of this actuell Page Context */ public final class CallStackGet implements Function { private static final long serialVersionUID = -5853145189662102420L; static final Collection.Key LINE_NUMBER = KeyImpl.init("LineNumber"); public static Array call(PageContext pc) { Array arr = new ArrayImpl(); _getTagContext(pc, arr, new Exception("Stack trace"), LINE_NUMBER); return arr; } public static void _getTagContext( PageContext pc, Array tagContext, Throwable t, Collection.Key lineNumberName) { // Throwable root = t.getRootCause(); Throwable cause = t.getCause(); if (cause != null) _getTagContext(pc, tagContext, cause, lineNumberName); StackTraceElement[] traces = t.getStackTrace(); UDF[] udfs = ((PageContextImpl) pc).getUDFs(); int line = 0; String template; Struct item; StackTraceElement trace = null; String functionName, methodName; int index = udfs.length - 1; for (int i = 0; i < traces.length; i++) { trace = traces[i]; template = trace.getFileName(); if (trace.getLineNumber() <= 0 || template == null || ResourceUtil.getExtension(template, "").equals("java")) continue; methodName = trace.getMethodName(); if (methodName != null && methodName.startsWith("udfCall") && index > -1) functionName = udfs[index--].getFunctionName(); else functionName = ""; item = new StructImpl(); line = trace.getLineNumber(); item.setEL(KeyConstants._function, functionName); item.setEL(KeyConstants._template, template); item.setEL(lineNumberName, new Double(line)); tagContext.appendEL(item); } } }
public static Object call(PageContext pc, Object[] objArr) throws PageException { if (objArr.length < 3) throw new ExpressionException("invalid call of a CFML Based built in function"); // translate arguments String filename = Caster.toString((((FunctionValue) objArr[0]).getValue())); Collection.Key name = KeyImpl.toKey((((FunctionValue) objArr[1]).getValue())); boolean isweb = Caster.toBooleanValue((((FunctionValue) objArr[2]).getValue())); UDF udf = loadUDF(pc, filename, name, isweb); Struct meta = udf.getMetaData(pc); boolean caller = meta == null ? false : Caster.toBooleanValue(meta.get(CALLER, Boolean.FALSE), false); Struct namedArguments = null; Object[] arguments = null; if (objArr.length <= 3) arguments = ArrayUtil.OBJECT_EMPTY; else if (objArr[3] instanceof FunctionValue) { FunctionValue fv; namedArguments = new StructImpl(); if (caller) namedArguments.setEL(CALLER, pc.undefinedScope().duplicate(false)); for (int i = 3; i < objArr.length; i++) { fv = toFunctionValue(name, objArr[i]); namedArguments.set(fv.getName(), fv.getValue()); } } else { int offset = (caller ? 2 : 3); arguments = new Object[objArr.length - offset]; if (caller) arguments[0] = pc.undefinedScope().duplicate(false); for (int i = 3; i < objArr.length; i++) { arguments[i - offset] = toObject(name, objArr[i]); } } // load UDF // execute UDF if (namedArguments == null) { return udf.call(pc, arguments, false); } return udf.callWithNamedValues(pc, namedArguments, false); }
public static boolean call(PageContext pc, railo.runtime.type.Struct struct, String key) { return call(pc, struct, KeyImpl.init(key)); }
public class HibernateORMEngine implements ORMEngine { private static final Collection.Key INIT = KeyImpl.intern("init"); private Configuration configuration; private SessionFactory _factory; private String datasource; // private Map<String,Long> _cfcids=new HashMap<String, Long>(); // private Map<String,String> _cfcs=new HashMap<String, String>(); private Map<String, CFCInfo> cfcs = new HashMap<String, CFCInfo>(); private Struct tableInfo = new StructImpl(); private QueryPlanCache _queryPlanCache; private DataSource ds; private List<ComponentPro> arr; private Object hash; private ORMConfiguration ormConf; private NamingStrategy namingStrategy = DefaultNamingStrategy.INSTANCE; public HibernateORMEngine() {} void checkExistent(PageContext pc, Component cfc) throws ORMException { if (!cfcs.containsKey(id(HibernateCaster.getEntityName(cfc)))) throw new ORMException( this, "there is no mapping definition for component [" + cfc.getAbsName() + "]"); } /** @see railo.runtime.orm.ORMEngine#init(railo.runtime.PageContext) */ public void init(PageContext pc) throws PageException { getSessionFactory(pc, true); } /** @see railo.runtime.orm.ORMEngine#getSession(railo.runtime.PageContext) */ public ORMSession createSession(PageContext pc) throws PageException { ApplicationContextPro appContext = ((ApplicationContextPro) pc.getApplicationContext()); String dsn = appContext.getORMDatasource(); // DatasourceManager manager = pc.getDataSourceManager(); // DatasourceConnection dc=manager.getConnection(pc,dsn, null, null); DatasourceConnection dc = ((ConfigWebImpl) pc.getConfig()) .getDatasourceConnectionPool() .getDatasourceConnection(pc, pc.getConfig().getDataSource(dsn), null, null); try { return new HibernateORMSession(this, getSessionFactory(pc), dc); } catch (PageException pe) { // manager.releaseConnection(pc, dc);// connection is closed when session ends throw pe; } } QueryPlanCache getQueryPlanCache(PageContext pc) throws PageException { SessionFactory _old = _factory; SessionFactory _new = getSessionFactory(pc); if (_queryPlanCache == null || _old != _new) { _queryPlanCache = new QueryPlanCache((SessionFactoryImplementor) _new); } return _queryPlanCache; } /** @see railo.runtime.orm.ORMEngine#getSessionFactory(railo.runtime.PageContext) */ public SessionFactory getSessionFactory(PageContext pc) throws PageException { return getSessionFactory(pc, false); } public boolean reload(PageContext pc, boolean force) throws PageException { if (force) { if (_factory != null) { _factory.close(); _factory = null; configuration = null; } } else { Object h = hash((ApplicationContextPro) pc.getApplicationContext()); if (this.hash.equals(h)) return false; } getSessionFactory(pc, true); return true; } private synchronized SessionFactory getSessionFactory(PageContext pc, boolean init) throws PageException { ApplicationContextPro appContext = ((ApplicationContextPro) pc.getApplicationContext()); if (!appContext.isORMEnabled()) throw new ORMException(this, "ORM is not enabled in application.cfc/cfapplication"); this.hash = hash(appContext); // datasource String dsn = appContext.getORMDatasource(); if (StringUtil.isEmpty(dsn)) throw new ORMException(this, "missing datasource defintion in application.cfc/cfapplication"); if (!dsn.equalsIgnoreCase(datasource)) { configuration = null; if (_factory != null) _factory.close(); _factory = null; datasource = dsn.toLowerCase(); } // config ormConf = appContext.getORMConfiguration(); // List<Component> arr = null; arr = null; if (init) { if (ormConf.autogenmap()) { arr = HibernateSessionFactory.loadComponents(pc, this, ormConf); cfcs.clear(); } else throw new HibernateException(this, "orm setting autogenmap=false is not supported yet"); } // load entities if (!ArrayUtil.isEmpty(arr)) { loadNamingStrategy(ormConf); DatasourceConnectionPool pool = ((ConfigWebImpl) pc.getConfig()).getDatasourceConnectionPool(); DatasourceConnection dc = pool.getDatasourceConnection(pc, pc.getConfig().getDataSource(dsn), null, null); // DataSourceManager manager = pc.getDataSourceManager(); // DatasourceConnection dc=manager.getConnection(pc,dsn, null, null); this.ds = dc.getDatasource(); try { Iterator<ComponentPro> it = arr.iterator(); while (it.hasNext()) { createMapping(pc, it.next(), dc, ormConf); } } finally { pool.releaseDatasourceConnection(dc); // manager.releaseConnection(pc,dc); } if (arr.size() != cfcs.size()) { ComponentPro cfc; String name, lcName; Map<String, String> names = new HashMap<String, String>(); Iterator<ComponentPro> it = arr.iterator(); while (it.hasNext()) { cfc = it.next(); name = HibernateCaster.getEntityName(cfc); lcName = name.toLowerCase(); if (names.containsKey(lcName)) throw new ORMException( this, "Entity Name [" + name + "] is ambigous, [" + names.get(lcName) + "] and [" + cfc.getPageSource().getDisplayPath() + "] use the same entity name."); names.put(lcName, cfc.getPageSource().getDisplayPath()); } } } arr = null; if (configuration != null) return _factory; // MUST // cacheconfig // cacheprovider // ... String mappings = HibernateSessionFactory.createMappings(this, cfcs); DatasourceConnectionPool pool = ((ConfigWebImpl) pc.getConfig()).getDatasourceConnectionPool(); DatasourceConnection dc = pool.getDatasourceConnection(pc, pc.getConfig().getDataSource(dsn), null, null); try { configuration = HibernateSessionFactory.createConfiguration(this, mappings, dc, ormConf); } catch (Exception e) { throw Caster.toPageException(e); } finally { pool.releaseDatasourceConnection(dc); } addEventListeners(pc, configuration, ormConf, cfcs); EntityTuplizerFactory tuplizerFactory = configuration.getEntityTuplizerFactory(); // tuplizerFactory.registerDefaultTuplizerClass(EntityMode.MAP, CFCEntityTuplizer.class); // tuplizerFactory.registerDefaultTuplizerClass(EntityMode.MAP, MapEntityTuplizer.class); tuplizerFactory.registerDefaultTuplizerClass(EntityMode.MAP, AbstractEntityTuplizerImpl.class); tuplizerFactory.registerDefaultTuplizerClass(EntityMode.POJO, AbstractEntityTuplizerImpl.class); // tuplizerFactory.registerDefaultTuplizerClass(EntityMode.POJO, // AbstractEntityTuplizerImpl.class); // configuration.setEntityResolver(new CFCEntityResolver()); // configuration.setEntityNotFoundDelegate(new EntityNotFoundDelegate()); return _factory = configuration.buildSessionFactory(); } private void loadNamingStrategy(ORMConfiguration ormConf) throws PageException { String strNamingStrategy = ormConf.namingStrategy(); if (StringUtil.isEmpty(strNamingStrategy, true)) { namingStrategy = DefaultNamingStrategy.INSTANCE; } else { strNamingStrategy = strNamingStrategy.trim(); if ("default".equalsIgnoreCase(strNamingStrategy)) namingStrategy = DefaultNamingStrategy.INSTANCE; else if ("smart".equalsIgnoreCase(strNamingStrategy)) namingStrategy = SmartNamingStrategy.INSTANCE; else namingStrategy = new CFCNamingStrategy(strNamingStrategy); } } private static void addEventListeners( PageContext pc, Configuration config, ORMConfiguration ormConfig, Map<String, CFCInfo> cfcs) throws PageException { if (!ormConfig.eventHandling()) return; String eventHandler = ormConfig.eventHandler(); AllEventListener listener = null; if (!StringUtil.isEmpty(eventHandler, true)) { // try { Component c = pc.loadComponent(eventHandler.trim()); listener = new AllEventListener(c); // config.setInterceptor(listener); // }catch (PageException e) {e.printStackTrace();} } config.setInterceptor(new InterceptorImpl(listener)); EventListeners listeners = config.getEventListeners(); // post delete List<EventListener> list = merge(listener, cfcs, EventListener.POST_DELETE); listeners.setPostDeleteEventListeners(list.toArray(new PostDeleteEventListener[list.size()])); // post insert list = merge(listener, cfcs, EventListener.POST_INSERT); listeners.setPostInsertEventListeners(list.toArray(new PostInsertEventListener[list.size()])); // post update list = merge(listener, cfcs, EventListener.POST_UPDATE); listeners.setPostUpdateEventListeners(list.toArray(new PostUpdateEventListener[list.size()])); // post load list = merge(listener, cfcs, EventListener.POST_LOAD); listeners.setPostLoadEventListeners(list.toArray(new PostLoadEventListener[list.size()])); // pre delete list = merge(listener, cfcs, EventListener.PRE_DELETE); listeners.setPreDeleteEventListeners(list.toArray(new PreDeleteEventListener[list.size()])); // pre insert // list=merge(listener,cfcs,EventListener.PRE_INSERT); // listeners.setPreInsertEventListeners(list.toArray(new PreInsertEventListener[list.size()])); // pre load list = merge(listener, cfcs, EventListener.PRE_LOAD); listeners.setPreLoadEventListeners(list.toArray(new PreLoadEventListener[list.size()])); // pre update // list=merge(listener,cfcs,EventListener.PRE_UPDATE); // listeners.setPreUpdateEventListeners(list.toArray(new PreUpdateEventListener[list.size()])); } private static List<EventListener> merge( EventListener listener, Map<String, CFCInfo> cfcs, Collection.Key eventType) { List<EventListener> list = new ArrayList<EventListener>(); Iterator<Entry<String, CFCInfo>> it = cfcs.entrySet().iterator(); Entry<String, CFCInfo> entry; Component cfc; while (it.hasNext()) { entry = it.next(); cfc = entry.getValue().getCFC(); if (EventListener.hasEventType(cfc, eventType)) { if (EventListener.POST_DELETE.equals(eventType)) list.add(new PostDeleteEventListenerImpl(cfc)); if (EventListener.POST_INSERT.equals(eventType)) list.add(new PostInsertEventListenerImpl(cfc)); if (EventListener.POST_LOAD.equals(eventType)) list.add(new PostLoadEventListenerImpl(cfc)); if (EventListener.POST_UPDATE.equals(eventType)) list.add(new PostUpdateEventListenerImpl(cfc)); if (EventListener.PRE_DELETE.equals(eventType)) list.add(new PreDeleteEventListenerImpl(cfc)); if (EventListener.PRE_INSERT.equals(eventType)) list.add(new PreInsertEventListenerImpl(cfc)); if (EventListener.PRE_LOAD.equals(eventType)) list.add(new PreLoadEventListenerImpl(cfc)); if (EventListener.PRE_UPDATE.equals(eventType)) list.add(new PreUpdateEventListenerImpl(cfc)); } } // general listener if (listener != null && EventListener.hasEventType(listener.getCFC(), eventType)) list.add(listener); return list; } private Object hash(ApplicationContextPro appContext) { String hash = appContext.getORMDatasource() + ":" + appContext.getORMConfiguration().hash(); // print.ds(hash); return hash; } public void createMapping( PageContext pc, Component cfc, DatasourceConnection dc, ORMConfiguration ormConf) throws PageException { ComponentPro cfcp = ComponentUtil.toComponentPro(cfc); String id = id(HibernateCaster.getEntityName(cfcp)); CFCInfo info = cfcs.get(id); // Long modified=cfcs.get(id); String xml; long cfcCompTime = ComponentUtil.getCompileTime(pc, cfcp.getPageSource()); if (info == null || (ORMUtil.equals(info.getCFC(), cfcp))) { // && info.getModified()!=cfcCompTime StringBuilder sb = new StringBuilder(); long xmlLastMod = loadMapping(sb, ormConf, cfcp); Element root; // create maaping if (true || xmlLastMod < cfcCompTime) { // MUSTMUST configuration = null; Document doc = null; try { doc = XMLUtil.newDocument(); } catch (Throwable t) { t.printStackTrace(); } root = doc.createElement("hibernate-mapping"); doc.appendChild(root); pc.addPageSource(cfcp.getPageSource(), true); try { HBMCreator.createXMLMapping(pc, dc, cfcp, ormConf, root, this); } finally { pc.removeLastPageSource(true); } xml = XMLCaster.toString(root.getChildNodes(), true); saveMapping(ormConf, cfcp, root); } // load else { xml = sb.toString(); root = Caster.toXML(xml).getOwnerDocument().getDocumentElement(); /*print.o("1+++++++++++++++++++++++++++++++++++++++++"); print.o(xml); print.o("2+++++++++++++++++++++++++++++++++++++++++"); print.o(root); print.o("3+++++++++++++++++++++++++++++++++++++++++");*/ } cfcs.put(id, new CFCInfo(ComponentUtil.getCompileTime(pc, cfcp.getPageSource()), xml, cfcp)); } } private static void saveMapping(ORMConfiguration ormConf, Component cfc, Element hm) throws ExpressionException { if (ormConf.saveMapping()) { Resource res = ComponentUtil.toComponentPro(cfc).getPageSource().getPhyscalFile(); if (res != null) { res = res.getParentResource().getRealResource(res.getName() + ".hbm.xml"); try { IOUtil.write( res, XMLCaster.toString( hm, false, HibernateSessionFactory.HIBERNATE_3_PUBLIC_ID, HibernateSessionFactory.HIBERNATE_3_SYSTEM_ID, HibernateSessionFactory.HIBERNATE_3_ENCODING), HibernateSessionFactory.HIBERNATE_3_ENCODING, false); } catch (Exception e) { } } } } private static long loadMapping(StringBuilder sb, ORMConfiguration ormConf, Component cfc) throws ExpressionException { Resource res = ComponentUtil.toComponentPro(cfc).getPageSource().getPhyscalFile(); if (res != null) { res = res.getParentResource().getRealResource(res.getName() + ".hbm.xml"); try { sb.append(IOUtil.toString(res, "UTF-8")); return res.lastModified(); } catch (Exception e) { } } return 0; } /** @see railo.runtime.orm.ORMEngine#getMode() */ public int getMode() { // MUST impl return MODE_LAZY; } public DataSource getDataSource() { return ds; } /** @see railo.runtime.orm.ORMEngine#getLabel() */ public String getLabel() { return "Hibernate"; } public Struct getTableInfo(DatasourceConnection dc, String tableName, ORMEngine engine) throws PageException { Collection.Key keyTableName = KeyImpl.init(tableName); Struct columnsInfo = (Struct) tableInfo.get(keyTableName, null); if (columnsInfo != null) return columnsInfo; columnsInfo = checkTable(dc, tableName, engine); tableInfo.setEL(keyTableName, columnsInfo); return columnsInfo; } private static Struct checkTable(DatasourceConnection dc, String tableName, ORMEngine engine) throws PageException { String dbName = dc.getDatasource().getDatabase(); try { DatabaseMetaData md = dc.getConnection().getMetaData(); Struct rows = checkTableFill(md, dbName, tableName); if (rows.size() == 0) { String tableName2 = checkTableValidate(md, dbName, tableName); if (tableName2 != null) rows = checkTableFill(md, dbName, tableName2); } if (rows.size() == 0) { // ORMUtil.printError("there is no table with name ["+tableName+"] defined", engine); return null; } return rows; } catch (SQLException e) { throw Caster.toPageException(e); } } private static Struct checkTableFill(DatabaseMetaData md, String dbName, String tableName) throws SQLException, PageException { Struct rows = new CastableStruct(tableName, Struct.TYPE_LINKED); ResultSet columns = md.getColumns(dbName, null, tableName, null); // print.o(new QueryImpl(columns,"")); try { String name; Object nullable; while (columns.next()) { name = columns.getString("COLUMN_NAME"); nullable = columns.getObject("IS_NULLABLE"); rows.setEL( KeyImpl.init(name), new ColumnInfo( name, columns.getInt("DATA_TYPE"), columns.getString("TYPE_NAME"), columns.getInt("COLUMN_SIZE"), Caster.toBooleanValue(nullable))); } } finally { DBUtil.closeEL(columns); } // Table susid defined for cfc susid does not exist. return rows; } private static String checkTableValidate(DatabaseMetaData md, String dbName, String tableName) { ResultSet tables = null; try { tables = md.getTables(dbName, null, null, null); String name; while (tables.next()) { name = tables.getString("TABLE_NAME"); if (name.equalsIgnoreCase(tableName) && StringUtil.indexOfIgnoreCase(tables.getString("TABLE_TYPE"), "SYSTEM") == -1) return name; } } catch (Throwable t) { } finally { DBUtil.closeEL(tables); } return null; } /** @see railo.runtime.orm.ORMEngine#getConfiguration(railo.runtime.PageContext) */ public ORMConfiguration getConfiguration(PageContext pc) { ApplicationContext ac = pc.getApplicationContext(); if (!(ac instanceof ApplicationContextPro)) return null; ApplicationContextPro acp = (ApplicationContextPro) ac; if (!acp.isORMEnabled()) return null; return acp.getORMConfiguration(); } /** * @param pc * @param session * @param entityName name of the entity to get * @param unique create a unique version that can be manipulated * @param init call the nit method of the cfc or not * @return * @throws PageException */ public Component create( PageContext pc, HibernateORMSession session, String entityName, boolean unique) throws PageException { // get existing entity ComponentPro cfc = _create(pc, entityName, unique); if (cfc != null) return cfc; // reinit ORMEngine SessionFactory _old = _factory; SessionFactory _new = getSessionFactory(pc, true); if (_old != _new) { session.resetSession(_new); cfc = _create(pc, entityName, unique); if (cfc != null) return cfc; } ApplicationContextPro appContext = ((ApplicationContextPro) pc.getApplicationContext()); ORMConfiguration ormConf = appContext.getORMConfiguration(); Resource[] locations = ormConf.getCfcLocations(); throw new ORMException( "No entity (persitent component) with name [" + entityName + "] found, available entities are [" + railo.runtime.type.List.arrayToList(getEntityNames(), ", ") + "] ", "component are searched in the following directories [" + toString(locations) + "]"); } private String toString(Resource[] locations) { if (locations == null) return ""; StringBuilder sb = new StringBuilder(); for (int i = 0; i < locations.length; i++) { if (i > 0) sb.append(", "); sb.append(locations[i].getAbsolutePath()); } return sb.toString(); } private ComponentPro _create(PageContext pc, String entityName, boolean unique) throws PageException { CFCInfo info = cfcs.get(id(entityName)); if (info != null) { ComponentPro cfc = info.getCFC(); if (unique) { cfc = (ComponentPro) cfc.duplicate(false); if (cfc.contains(pc, INIT)) cfc.call(pc, "init", new Object[] {}); } return cfc; } return null; } public static String id(String id) { return id.toLowerCase().trim(); } public Component getEntityByCFCName(String cfcName, boolean unique) throws PageException { String name = cfcName; int pointIndex = cfcName.lastIndexOf('.'); if (pointIndex != -1) { name = cfcName.substring(pointIndex + 1); } else cfcName = null; ComponentPro cfc; String[] names = null; // search array (array exist when cfcs is in generation) if (arr != null) { names = new String[arr.size()]; int index = 0; Iterator<ComponentPro> it2 = arr.iterator(); while (it2.hasNext()) { cfc = it2.next(); names[index++] = cfc.getName(); if (isEntity(cfc, cfcName, name)) // if(cfc.equalTo(name)) return unique ? (Component) cfc.duplicate(false) : cfc; } } else { // search cfcs Iterator<Entry<String, CFCInfo>> it = cfcs.entrySet().iterator(); Entry<String, CFCInfo> entry; while (it.hasNext()) { entry = it.next(); cfc = entry.getValue().getCFC(); if (isEntity(cfc, cfcName, name)) // if(cfc.instanceOf(name)) return unique ? (Component) cfc.duplicate(false) : cfc; // if(name.equalsIgnoreCase(HibernateCaster.getEntityName(cfc))) // return cfc; } names = cfcs.keySet().toArray(new String[cfcs.size()]); } // search by entityname //TODO is this ok? CFCInfo info = cfcs.get(name.toLowerCase()); if (info != null) { cfc = info.getCFC(); return unique ? (Component) cfc.duplicate(false) : cfc; } throw new ORMException( this, "entity [" + name + "] " + (StringUtil.isEmpty(cfcName) ? "" : "with cfc name [" + cfcName + "] ") + "does not exist, existing entities are [" + railo.runtime.type.List.arrayToList(names, ", ") + "]"); } private boolean isEntity(ComponentPro cfc, String cfcName, String name) { if (!StringUtil.isEmpty(cfcName)) { if (cfc.equalTo(cfcName)) return true; if (cfcName.indexOf('.') != -1) { String path = cfcName.replace('.', '/') + ".cfc"; Resource[] locations = ormConf.getCfcLocations(); for (int i = 0; i < locations.length; i++) { if (locations[i].getRealResource(path).equals(cfc.getPageSource().getFile())) return true; } return false; } } if (cfc.equalTo(name)) return true; return name.equalsIgnoreCase(HibernateCaster.getEntityName(cfc)); } public Component getEntityByEntityName(String entityName, boolean unique) throws PageException { ComponentPro cfc; CFCInfo info = cfcs.get(entityName.toLowerCase()); if (info != null) { cfc = info.getCFC(); return unique ? (Component) cfc.duplicate(false) : cfc; } if (arr != null) { Iterator<ComponentPro> it2 = arr.iterator(); while (it2.hasNext()) { cfc = it2.next(); if (HibernateCaster.getEntityName(cfc).equalsIgnoreCase(entityName)) return unique ? (Component) cfc.duplicate(false) : cfc; } } throw new ORMException(this, "entity [" + entityName + "] does not exist"); } public String[] getEntityNames() { Iterator<Entry<String, CFCInfo>> it = cfcs.entrySet().iterator(); String[] names = new String[cfcs.size()]; int index = 0; while (it.hasNext()) { names[index++] = HibernateCaster.getEntityName(it.next().getValue().getCFC()); // names[index++]=it.next().getValue().getCFC().getName(); } return names; // return cfcs.keySet().toArray(new String[cfcs.size()]); } public String convertTableName(String tableName) { if (tableName == null) return null; // print.o("table:"+namingStrategy.getType()+":"+tableName+":"+namingStrategy.convertTableName(tableName)); return namingStrategy.convertTableName(tableName); } public String convertColumnName(String columnName) { if (columnName == null) return null; // print.o("column:"+namingStrategy.getType()+":"+columnName+":"+namingStrategy.convertTableName(columnName)); return namingStrategy.convertColumnName(columnName); } }
public class CFFunction { private static final Variables VAR = new VariablesImpl(); private static final Collection.Key CALLER = KeyImpl.intern("caller"); // private static Map udfs=new ReferenceMap(); public static Object call(PageContext pc, Object[] objArr) throws PageException { if (objArr.length < 3) throw new ExpressionException("invalid call of a CFML Based built in function"); // translate arguments String filename = Caster.toString((((FunctionValue) objArr[0]).getValue())); Collection.Key name = KeyImpl.toKey((((FunctionValue) objArr[1]).getValue())); boolean isweb = Caster.toBooleanValue((((FunctionValue) objArr[2]).getValue())); UDF udf = loadUDF(pc, filename, name, isweb); Struct meta = udf.getMetaData(pc); boolean caller = meta == null ? false : Caster.toBooleanValue(meta.get(CALLER, Boolean.FALSE), false); Struct namedArguments = null; Object[] arguments = null; if (objArr.length <= 3) arguments = ArrayUtil.OBJECT_EMPTY; else if (objArr[3] instanceof FunctionValue) { FunctionValue fv; namedArguments = new StructImpl(); if (caller) namedArguments.setEL(CALLER, pc.undefinedScope().duplicate(false)); for (int i = 3; i < objArr.length; i++) { fv = toFunctionValue(name, objArr[i]); namedArguments.set(fv.getName(), fv.getValue()); } } else { int offset = (caller ? 2 : 3); arguments = new Object[objArr.length - offset]; if (caller) arguments[0] = pc.undefinedScope().duplicate(false); for (int i = 3; i < objArr.length; i++) { arguments[i - offset] = toObject(name, objArr[i]); } } // load UDF // execute UDF if (namedArguments == null) { return udf.call(pc, arguments, false); } return udf.callWithNamedValues(pc, namedArguments, false); } public static synchronized UDF loadUDF( PageContext pc, String filename, Collection.Key name, boolean isweb) throws PageException { ConfigWebImpl config = (ConfigWebImpl) pc.getConfig(); String key = isweb ? name.getString() + config.getId() : name.getString(); UDF udf = config.getFromFunctionCache(key); if (udf != null) return udf; Mapping mapping = isweb ? config.getFunctionMapping() : config.getServerFunctionMapping(); PageSourceImpl ps = (PageSourceImpl) mapping.getPageSource(filename); Page p = ps.loadPage(pc, pc.getConfig()); // execute page Variables old = pc.variablesScope(); pc.setVariablesScope(VAR); boolean wasSilent = pc.setSilent(); try { p.call(pc); Object o = pc.variablesScope().get(name, null); if (o instanceof UDF) { udf = (UDF) o; config.putToFunctionCache(key, udf); return udf; } throw new ExpressionException( "there is no Function defined with name [" + name + "] in template [" + mapping.getStrPhysical() + File.separator + filename + "]"); } catch (Throwable t) { throw Caster.toPageException(t); } finally { pc.setVariablesScope(old); if (!wasSilent) pc.unsetSilent(); } } private static FunctionValue toFunctionValue(Collection.Key name, Object obj) throws ExpressionException { if (obj instanceof FunctionValue) return (FunctionValue) obj; throw new ExpressionException( "invalid argument for function " + name + ", you can not mix named and unnamed arguments"); } private static Object toObject(Collection.Key name, Object obj) throws ExpressionException { if (obj instanceof FunctionValue) throw new ExpressionException( "invalid argument for function " + name + ", you can not mix named and unnamed arguments"); return obj; } }
public Object get(String key, Object defaultValue) { return get(KeyImpl.init(key), defaultValue); }
public Object get(String key) throws PageException { return get(KeyImpl.init(key)); }
public class ModernAppListener extends AppListenerSupport { private static final Collection.Key ON_REQUEST_START = KeyImpl.intern("onRequestStart"); private static final Collection.Key ON_CFCREQUEST = KeyImpl.intern("onCFCRequest"); private static final Collection.Key ON_REQUEST = KeyImpl.intern("onRequest"); private static final Collection.Key ON_REQUEST_END = KeyImpl.intern("onRequestEnd"); private static final Collection.Key ON_ABORT = KeyImpl.intern("onAbort"); private static final Collection.Key ON_APPLICATION_START = KeyImpl.intern("onApplicationStart"); private static final Collection.Key ON_APPLICATION_END = KeyImpl.intern("onApplicationEnd"); private static final Collection.Key ON_SESSION_START = KeyImpl.intern("onSessionStart"); private static final Collection.Key ON_SESSION_END = KeyImpl.intern("onSessionEnd"); private static final Collection.Key ON_DEBUG = KeyImpl.intern("onDebug"); private static final Collection.Key ON_ERROR = KeyImpl.intern("onError"); private static final Collection.Key ON_MISSING_TEMPLATE = KeyImpl.intern("onMissingTemplate"); // private ComponentImpl app; private Map<String, ComponentAccess> apps = new HashMap<String, ComponentAccess>(); protected int mode = MODE_CURRENT2ROOT; @Override public void onRequest(PageContext pc, PageSource requestedPage, RequestListener rl) throws PageException { // on requestStart PageSource appPS = // pc.isCFCRequest()?null: AppListenerUtil.getApplicationPageSource(pc, requestedPage, Constants.APP_CFC, mode); _onRequest(pc, requestedPage, appPS, rl); } protected void _onRequest( PageContext pc, PageSource requestedPage, PageSource appPS, RequestListener rl) throws PageException { PageContextImpl pci = (PageContextImpl) pc; if (appPS != null) { String callPath = appPS.getComponentName(); ComponentAccess app = ComponentLoader.loadComponent(pci, null, appPS, callPath, false, false); // init initApplicationContext(pci, app); apps.put(pc.getApplicationContext().getName(), app); if (!pci.initApplicationContext()) return; if (rl != null) { requestedPage = rl.execute(pc, requestedPage); if (requestedPage == null) return; } String targetPage = requestedPage.getFullRealpath(); boolean doOnRequestEnd = true; // onRequestStart if (app.contains(pc, ON_REQUEST_START)) { Object rtn = call(app, pci, ON_REQUEST_START, new Object[] {targetPage}, true); if (!Caster.toBooleanValue(rtn, true)) return; } // onRequest boolean isCFC = ResourceUtil.getExtension(targetPage, "") .equalsIgnoreCase(pc.getConfig().getCFCExtension()); Object method; if (isCFC && app.contains(pc, ON_CFCREQUEST) && (method = pc.urlFormScope().get(ComponentPage.METHOD, null)) != null) { Struct url = (Struct) Duplicator.duplicate(pc.urlFormScope(), true); url.removeEL(KeyConstants._fieldnames); url.removeEL(ComponentPage.METHOD); Object args = url.get(KeyConstants._argumentCollection, null); Object returnFormat = url.removeEL(KeyConstants._returnFormat); Object queryFormat = url.removeEL(KeyConstants._queryFormat); if (args == null) { args = pc.getHttpServletRequest().getAttribute("argumentCollection"); } if (args instanceof String) { args = new JSONExpressionInterpreter().interpret(pc, (String) args); } if (args != null) { if (Decision.isCastableToStruct(args)) { Struct sct = Caster.toStruct(args, false); // Key[] keys = url.keys(); Iterator<Entry<Key, Object>> it = url.entryIterator(); Entry<Key, Object> e; while (it.hasNext()) { e = it.next(); sct.setEL(e.getKey(), e.getValue()); } args = sct; } else if (Decision.isCastableToArray(args)) { args = Caster.toArray(args); } else { Array arr = new ArrayImpl(); arr.appendEL(args); args = arr; } } else args = url; Object rtn = call( app, pci, ON_CFCREQUEST, new Object[] {requestedPage.getComponentName(), method, args}, true); if (rtn != null) { if (pc.getHttpServletRequest().getHeader("AMF-Forward") != null) { pc.variablesScope().setEL("AMF-Forward", rtn); // ThreadLocalWDDXResult.set(rtn); } else { try { pc.forceWrite( ComponentPage.convertResult( pc, app, method.toString(), returnFormat, queryFormat, rtn)); } catch (Exception e) { throw Caster.toPageException(e); } } } } // else if(!isCFC && app.contains(pc,ON_REQUEST)) {} else { // TODO impl die nicht so generisch ist try { if (!isCFC && app.contains(pc, ON_REQUEST)) call(app, pci, ON_REQUEST, new Object[] {targetPage}, false); else pci.doInclude(requestedPage); } catch (PageException pe) { if (!Abort.isSilentAbort(pe)) { if (pe instanceof MissingIncludeException) { if (((MissingIncludeException) pe).getPageSource().equals(requestedPage)) { if (app.contains(pc, ON_MISSING_TEMPLATE)) { if (!Caster.toBooleanValue( call(app, pci, ON_MISSING_TEMPLATE, new Object[] {targetPage}, true), true)) throw pe; } else throw pe; } else throw pe; } else throw pe; } else { doOnRequestEnd = false; if (app.contains(pc, ON_ABORT)) { call(app, pci, ON_ABORT, new Object[] {targetPage}, true); } } } } // onRequestEnd if (doOnRequestEnd && app.contains(pc, ON_REQUEST_END)) { call(app, pci, ON_REQUEST_END, new Object[] {targetPage}, true); } } else { apps.put(pc.getApplicationContext().getName(), null); pc.doInclude(requestedPage); } } @Override public boolean onApplicationStart(PageContext pc) throws PageException { ComponentAccess app = apps.get(pc.getApplicationContext().getName()); if (app != null && app.contains(pc, ON_APPLICATION_START)) { Object rtn = call(app, pc, ON_APPLICATION_START, ArrayUtil.OBJECT_EMPTY, true); return Caster.toBooleanValue(rtn, true); } return true; } @Override public void onApplicationEnd(CFMLFactory factory, String applicationName) throws PageException { ComponentAccess app = apps.get(applicationName); if (app == null || !app.containsKey(ON_APPLICATION_END)) return; PageContextImpl pc = (PageContextImpl) ThreadLocalPageContext.get(); boolean createPc = pc == null; try { if (createPc) pc = createPageContext(factory, app, applicationName, null, ON_APPLICATION_END); call(app, pc, ON_APPLICATION_END, new Object[] {pc.applicationScope()}, true); } finally { if (createPc && pc != null) { factory.releasePageContext(pc); } } } @Override public void onSessionStart(PageContext pc) throws PageException { ComponentAccess app = apps.get(pc.getApplicationContext().getName()); if (hasOnSessionStart(pc, app)) { call(app, pc, ON_SESSION_START, ArrayUtil.OBJECT_EMPTY, true); } } @Override public void onSessionEnd(CFMLFactory factory, String applicationName, String cfid) throws PageException { ComponentAccess app = apps.get(applicationName); if (app == null || !app.containsKey(ON_SESSION_END)) return; PageContextImpl pc = null; try { pc = createPageContext(factory, app, applicationName, cfid, ON_SESSION_END); call( app, pc, ON_SESSION_END, new Object[] {pc.sessionScope(false), pc.applicationScope()}, true); } finally { if (pc != null) { factory.releasePageContext(pc); } } } private PageContextImpl createPageContext( CFMLFactory factory, ComponentAccess app, String applicationName, String cfid, Collection.Key methodName) throws PageException { Resource root = factory.getConfig().getRootDirectory(); String path = app.getPageSource().getFullRealpath(); // Request HttpServletRequestDummy req = new HttpServletRequestDummy(root, "localhost", path, "", null, null, null, null, null); if (!StringUtil.isEmpty(cfid)) req.setCookies(new Cookie[] {new Cookie("cfid", cfid), new Cookie("cftoken", "0")}); // Response OutputStream os = DevNullOutputStream.DEV_NULL_OUTPUT_STREAM; try { Resource out = factory .getConfig() .getConfigDir() .getRealResource("output/" + methodName.getString() + ".out"); out.getParentResource().mkdirs(); os = out.getOutputStream(false); } catch (IOException e) { e.printStackTrace(); // TODO was passiert hier } HttpServletResponseDummy rsp = new HttpServletResponseDummy(os); // PageContext PageContextImpl pc = (PageContextImpl) factory.getRailoPageContext(factory.getServlet(), req, rsp, null, false, -1, false); // ApplicationContext ClassicApplicationContext ap = new ClassicApplicationContext( factory.getConfig(), applicationName, false, app == null ? null : ResourceUtil.getResource(pc, app.getPageSource(), null)); initApplicationContext(pc, app); ap.setName(applicationName); ap.setSetSessionManagement(true); // if(!ap.hasName())ap.setName("Controler") // Base pc.setBase(app.getPageSource()); return pc; } @Override public void onDebug(PageContext pc) throws PageException { if (((PageContextImpl) pc).isGatewayContext()) return; ComponentAccess app = apps.get(pc.getApplicationContext().getName()); if (app != null && app.contains(pc, ON_DEBUG)) { call(app, pc, ON_DEBUG, new Object[] {pc.getDebugger().getDebuggingData(pc)}, true); return; } try { pc.getDebugger().writeOut(pc); } catch (IOException e) { throw Caster.toPageException(e); } } @Override public void onError(PageContext pc, PageException pe) { ComponentAccess app = apps.get(pc.getApplicationContext().getName()); if (app != null && app.containsKey(ON_ERROR) && !Abort.isSilentAbort(pe)) { try { String eventName = ""; if (pe instanceof ModernAppListenerException) eventName = ((ModernAppListenerException) pe).getEventName(); if (eventName == null) eventName = ""; call(app, pc, ON_ERROR, new Object[] {pe.getCatchBlock(pc), eventName}, true); return; } catch (PageException _pe) { pe = _pe; } } pc.handlePageException(pe); } private Object call( Component app, PageContext pc, Collection.Key eventName, Object[] args, boolean catchAbort) throws PageException { try { return app.call(pc, eventName, args); } catch (PageException pe) { if (Abort.isSilentAbort(pe)) { if (catchAbort) return Boolean.FALSE; throw pe; } throw new ModernAppListenerException(pe, eventName.getString()); } } private void initApplicationContext(PageContextImpl pc, ComponentAccess app) throws PageException { // use existing app context RefBoolean throwsErrorWhileInit = new RefBooleanImpl(false); ModernApplicationContext appContext = new ModernApplicationContext(pc, app, throwsErrorWhileInit); pc.setApplicationContext(appContext); if (appContext.isORMEnabled()) { boolean hasError = throwsErrorWhileInit.toBooleanValue(); if (hasError) pc.addPageSource(app.getPageSource(), true); try { ORMUtil.resetEngine(pc, false); } finally { if (hasError) pc.removeLastPageSource(true); } } } private static Object get(ComponentAccess app, Key name, String defaultValue) { Member mem = app.getMember(Component.ACCESS_PRIVATE, name, true, false); if (mem == null) return defaultValue; return mem.getValue(); } @Override public void setMode(int mode) { this.mode = mode; } @Override public int getMode() { return mode; } @Override public String getType() { return "modern"; } @Override public boolean hasOnSessionStart(PageContext pc) { return hasOnSessionStart(pc, apps.get(pc.getApplicationContext().getName())); } private boolean hasOnSessionStart(PageContext pc, ComponentAccess app) { return app != null && app.contains(pc, ON_SESSION_START); } }
public class PropertyFactory { public static final Collection.Key SINGULAR_NAME = KeyImpl.getInstance("singularName"); public static final Key FIELD_TYPE = KeyImpl.getInstance("fieldtype"); public static void addGet(ComponentImpl comp, Property prop) { Member m = comp.getMember( ComponentImpl.ACCESS_PRIVATE, KeyImpl.init("get" + prop.getName()), true, false); if (!(m instanceof UDF)) { UDF udf = new UDFGetterProperty(comp, prop); comp.registerUDF(udf.getFunctionName(), udf); } } public static void addSet(ComponentImpl comp, Property prop) { Member m = comp.getMember( ComponentImpl.ACCESS_PRIVATE, KeyImpl.init("set" + prop.getName()), true, false); if (!(m instanceof UDF)) { UDF udf = new UDFSetterProperty(comp, prop); comp.registerUDF(udf.getFunctionName(), udf); } } public static void addHas(ComponentImpl comp, Property prop) { Member m = comp.getMember( ComponentImpl.ACCESS_PRIVATE, KeyImpl.init("has" + getSingularName(prop)), true, false); if (!(m instanceof UDF)) { UDF udf = new UDFHasProperty(comp, prop); comp.registerUDF(udf.getFunctionName(), udf); } } public static void addAdd(ComponentImpl comp, Property prop) { Member m = comp.getMember( ComponentImpl.ACCESS_PRIVATE, KeyImpl.init("add" + getSingularName(prop)), true, false); if (!(m instanceof UDF)) { UDF udf = new UDFAddProperty(comp, prop); comp.registerUDF(udf.getFunctionName(), udf); } } public static void addRemove(ComponentImpl comp, Property prop) { Member m = comp.getMember( ComponentImpl.ACCESS_PRIVATE, KeyImpl.init("remove" + getSingularName(prop)), true, false); if (!(m instanceof UDF)) { UDF udf = new UDFRemoveProperty(comp, prop); comp.registerUDF(udf.getFunctionName(), udf); } } public static String getSingularName(Property prop) { String singularName = Caster.toString(prop.getMeta().get(SINGULAR_NAME, null), null); if (!StringUtil.isEmpty(singularName)) return singularName; return prop.getName(); } public static String getType(Property prop) { String type = prop.getType(); if (StringUtil.isEmpty(type) || "any".equalsIgnoreCase(type) || "object".equalsIgnoreCase(type)) { String fieldType = Caster.toString(prop.getMeta().get(FIELD_TYPE, null), null); if ("one-to-many".equalsIgnoreCase(fieldType) || "many-to-many".equalsIgnoreCase(fieldType)) { return "array"; } return "any"; } return type; } }
/** * @see railo.runtime.type.Objects#set(railo.runtime.PageContext, java.lang.String, * java.lang.Object) */ public Object set(PageContext pc, String propertyName, Object value) throws PageException { return set(KeyImpl.init(propertyName), value); }
/** * @see railo.runtime.type.Objects#call(railo.runtime.PageContext, java.lang.String, * java.lang.Object[]) */ public Object call(PageContext pc, String key, Object[] arguments) throws PageException { return call(pc, KeyImpl.init(key), arguments); }
public final class ComponentScopeThis extends StructSupport implements ComponentScope { private ComponentImpl component; private static final int access = Component.ACCESS_PRIVATE; private static final Collection.Key THIS = KeyImpl.init("this"); /** * constructor of the class * * @param component */ public ComponentScopeThis(ComponentImpl component) { this.component = component; } /** @see railo.runtime.type.Scope#initialize(railo.runtime.PageContext) */ public void initialize(PageContext pc) {} /** @see railo.runtime.type.Scope#release() */ public void release() {} /** @see railo.runtime.type.Scope#getType() */ public int getType() { return SCOPE_VARIABLES; } /** @see railo.runtime.type.Scope#getTypeAsString() */ public String getTypeAsString() { return "variables"; } /** @see railo.runtime.type.Collection#size() */ public int size() { return component.size(access) + 1; } /** @see railo.runtime.type.Collection#keysAsString() */ public String[] keysAsString() { Set keySet = component.keySet(access); keySet.add("this"); String[] arr = new String[keySet.size()]; Iterator it = keySet.iterator(); int index = 0; while (it.hasNext()) { arr[index++] = Caster.toString(it.next(), null); } return arr; } public Collection.Key[] keys() { Set keySet = component.keySet(access); keySet.add("this"); Collection.Key[] arr = new Collection.Key[keySet.size()]; Iterator it = keySet.iterator(); int index = 0; while (it.hasNext()) { arr[index++] = KeyImpl.toKey(it.next(), null); } return arr; } /** @see railo.runtime.type.Collection#remove(railo.runtime.type.Collection.Key) */ public Object remove(Collection.Key key) throws PageException { return component.remove(key); } /** @see railo.runtime.type.Collection#removeEL(railo.runtime.type.Collection.Key) */ public Object removeEL(Collection.Key key) { return component.removeEL(key); } /** @see railo.runtime.type.Collection#clear() */ public void clear() { component.clear(); } /** @see railo.runtime.type.Collection#get(railo.runtime.type.Collection.Key) */ public Object get(Key key) throws PageException { if (key.equalsIgnoreCase(THIS)) { return component; } return component.get(access, key); } /** @see railo.runtime.type.Collection#get(railo.runtime.type.Collection.Key, java.lang.Object) */ public Object get(Collection.Key key, Object defaultValue) { if (key.equalsIgnoreCase(THIS)) { return component; } return component.get(access, key, defaultValue); } /** @see railo.runtime.type.Collection#set(railo.runtime.type.Collection.Key, java.lang.Object) */ public Object set(Collection.Key key, Object value) throws PageException { return component.set(key, value); } /** * @see railo.runtime.type.Collection#setEL(railo.runtime.type.Collection.Key, java.lang.Object) */ public Object setEL(Collection.Key key, Object value) { return component.setEL(key, value); } /** @see railo.runtime.type.Iteratorable#keyIterator() */ public Iterator keyIterator() { return component.iterator(access); } /** @see railo.runtime.type.Collection#containsKey(railo.runtime.type.Collection.Key) */ public boolean containsKey(Key key) { return get(key, null) != null; } /** @see railo.runtime.dump.Dumpable#toDumpData(railo.runtime.PageContext, int) */ public DumpData toDumpData(PageContext pageContext, int maxlevel, DumpProperties dp) { return StructUtil.toDumpTable(this, "Variable Scope (of Component)", pageContext, maxlevel, dp); /*DumpTable table = new DumpTable("#5965e4","#9999ff","#000000"); table.setTitle("Variable Scope (of Component)"); Iterator it=keyIterator(); while(it.hasNext()) { String key=Caster.toString(it.next(),""); table.appendRow(1,new SimpleDumpData(key.toString()),DumpUtil.toDumpData(get(key,null), pageContext,maxlevel,dp)); } return table;*/ } /** @see railo.runtime.op.Castable#castToString() */ public String castToString() throws PageException { return component.castToString(); } /** @see railo.runtime.type.util.StructSupport#castToString(java.lang.String) */ public String castToString(String defaultValue) { return component.castToString(defaultValue); } /** @see railo.runtime.op.Castable#castToBooleanValue() */ public boolean castToBooleanValue() throws PageException { return component.castToBooleanValue(); } /** @see railo.runtime.op.Castable#castToBoolean(java.lang.Boolean) */ public Boolean castToBoolean(Boolean defaultValue) { return component.castToBoolean(defaultValue); } /** @see railo.runtime.op.Castable#castToDoubleValue() */ public double castToDoubleValue() throws PageException { return component.castToDoubleValue(); } /** @see railo.runtime.op.Castable#castToDoubleValue(double) */ public double castToDoubleValue(double defaultValue) { return component.castToDoubleValue(defaultValue); } /** @see railo.runtime.op.Castable#castToDateTime() */ public DateTime castToDateTime() throws PageException { return component.castToDateTime(); } /** @see railo.runtime.op.Castable#castToDateTime(railo.runtime.type.dt.DateTime) */ public DateTime castToDateTime(DateTime defaultValue) { return component.castToDateTime(defaultValue); } /** * @throws PageException * @see railo.runtime.op.Castable#compare(boolean) */ public int compareTo(boolean b) throws PageException { return component.compareTo(b); } /** @see railo.runtime.op.Castable#compareTo(railo.runtime.type.dt.DateTime) */ public int compareTo(DateTime dt) throws PageException { return component.compareTo(dt); } /** @see railo.runtime.op.Castable#compareTo(double) */ public int compareTo(double d) throws PageException { return component.compareTo(d); } /** @see railo.runtime.op.Castable#compareTo(java.lang.String) */ public int compareTo(String str) throws PageException { return component.compareTo(str); } /** @see railo.runtime.type.Collection#duplicate(boolean) */ public Collection duplicate(boolean deepCopy) { StructImpl sct = new StructImpl(); StructImpl.copy(this, sct, deepCopy); return sct; // return new ComponentScopeThis((ComponentImpl) component.duplicate(deepCopy)); // return new ComponentScopeThis(component.cloneComponentImpl(deepCopy)); } /** * Returns the value of component. * * @return value component */ public ComponentPro getComponent() { return component; } /** * @see railo.runtime.type.Objects#get(railo.runtime.PageContext, java.lang.String, * java.lang.Object) */ public Object get(PageContext pc, String key, Object defaultValue) { return component.get(access, key, defaultValue); } /** * @see railo.runtime.type.Objects#get(railo.runtime.PageContext, * railo.runtime.type.Collection.Key, java.lang.Object) */ public Object get(PageContext pc, Collection.Key key, Object defaultValue) { return component.get(access, key, defaultValue); } /** @see railo.runtime.type.Objects#get(railo.runtime.PageContext, java.lang.String) */ public Object get(PageContext pc, String key) throws PageException { return component.get(access, key); } /** * @see railo.runtime.type.Objects#get(railo.runtime.PageContext, * railo.runtime.type.Collection.Key) */ public Object get(PageContext pc, Collection.Key key) throws PageException { return component.get(access, key); } /** * @see railo.runtime.type.Objects#set(railo.runtime.PageContext, java.lang.String, * java.lang.Object) */ public Object set(PageContext pc, String propertyName, Object value) throws PageException { return component.set(propertyName, value); } /** * @see railo.runtime.type.Objects#set(railo.runtime.PageContext, * railo.runtime.type.Collection.Key, java.lang.Object) */ public Object set(PageContext pc, Collection.Key propertyName, Object value) throws PageException { return component.set(propertyName, value); } /** * @see railo.runtime.type.Objects#setEL(railo.runtime.PageContext, java.lang.String, * java.lang.Object) */ public Object setEL(PageContext pc, String propertyName, Object value) { return component.setEL(propertyName, value); } /** * @see railo.runtime.type.Objects#setEL(railo.runtime.PageContext, * railo.runtime.type.Collection.Key, java.lang.Object) */ public Object setEL(PageContext pc, Collection.Key propertyName, Object value) { return component.setEL(propertyName, value); } /** * @see railo.runtime.type.Objects#call(railo.runtime.PageContext, java.lang.String, * java.lang.Object[]) */ public Object call(PageContext pc, String key, Object[] arguments) throws PageException { return call(pc, KeyImpl.init(key), arguments); } public Object call(PageContext pc, Collection.Key key, Object[] arguments) throws PageException { Member m = component.getMember(access, key, false, false); if (m != null) { if (m instanceof UDF) return ((UDF) m).call(pc, arguments, false); throw ComponentUtil.notFunction(component, key, m.getValue(), access); } throw ComponentUtil.notFunction(component, key, null, access); } /** * @see railo.runtime.type.Objects#callWithNamedValues(railo.runtime.PageContext, * java.lang.String, railo.runtime.type.Struct) */ public Object callWithNamedValues(PageContext pc, String key, Struct args) throws PageException { return callWithNamedValues(pc, KeyImpl.init(key), args); } public Object callWithNamedValues(PageContext pc, Collection.Key key, Struct args) throws PageException { Member m = component.getMember(access, key, false, false); if (m != null) { if (m instanceof UDF) return ((UDF) m).callWithNamedValues(pc, args, false); throw ComponentUtil.notFunction(component, key, m.getValue(), access); } throw ComponentUtil.notFunction(component, key, null, access); } /** @see railo.runtime.type.Objects#isInitalized() */ public boolean isInitalized() { return component.isInitalized(); } /** @see railo.runtime.ComponentScope#setComponent(railo.runtime.ComponentImpl) */ public void setComponent(ComponentImpl c) { this.component = c; } }
/** * @see railo.runtime.type.Objects#callWithNamedValues(railo.runtime.PageContext, * java.lang.String, railo.runtime.type.Struct) */ public Object callWithNamedValues(PageContext pc, String key, Struct args) throws PageException { return callWithNamedValues(pc, KeyImpl.init(key), args); }
public static Object setProperty(Node node, Collection.Key k, Object value, boolean caseSensitive) throws PageException { Document doc = (node instanceof Document) ? (Document) node : node.getOwnerDocument(); // Comment if (k.equals(XMLCOMMENT)) { removeChilds(XMLCaster.toRawNode(node), Node.COMMENT_NODE, false); node.appendChild(XMLCaster.toRawNode(XMLCaster.toComment(doc, value))); } // NS URI else if (k.equals(XMLNSURI)) { // TODO impl throw new ExpressionException("XML NS URI can't be set", "not implemented"); } // Prefix else if (k.equals(XMLNSPREFIX)) { // TODO impl throw new ExpressionException("XML NS Prefix can't be set", "not implemented"); // node.setPrefix(Caster.toString(value)); } // Root else if (k.equals(XMLROOT)) { doc.appendChild(XMLCaster.toNode(doc, value)); } // Parent else if (k.equals(XMLPARENT)) { Node parent = getParentNode(node, caseSensitive); Key name = KeyImpl.init(parent.getNodeName()); parent = getParentNode(parent, caseSensitive); if (parent == null) throw new ExpressionException( "there is no parent element, you are already on the root element"); return setProperty(parent, name, value, caseSensitive); } // Name else if (k.equals(XMLNAME)) { throw new XMLException("You can't assign a new value for the property [xmlname]"); } // Type else if (k.equals(XMLTYPE)) { throw new XMLException("You can't change type of a xml node [xmltype]"); } // value else if (k.equals(XMLVALUE)) { node.setNodeValue(Caster.toString(value)); } // Attributes else if (k.equals(XMLATTRIBUTES)) { Element parent = XMLCaster.toElement(doc, node); Attr[] attres = XMLCaster.toAttrArray(doc, value); // print.ln("=>"+value); for (int i = 0; i < attres.length; i++) { if (attres[i] != null) { parent.setAttributeNode(attres[i]); // print.ln(attres[i].getName()+"=="+attres[i].getValue()); } } } // Text else if (k.equals(XMLTEXT)) { removeChilds(XMLCaster.toRawNode(node), Node.TEXT_NODE, false); node.appendChild(XMLCaster.toRawNode(XMLCaster.toText(doc, value))); } // CData else if (k.equals(XMLCDATA)) { removeChilds(XMLCaster.toRawNode(node), Node.CDATA_SECTION_NODE, false); node.appendChild(XMLCaster.toRawNode(XMLCaster.toCDATASection(doc, value))); } // Children else if (k.equals(XMLCHILDREN)) { Node[] nodes = XMLCaster.toNodeArray(doc, value); removeChilds(XMLCaster.toRawNode(node), Node.ELEMENT_NODE, false); for (int i = 0; i < nodes.length; i++) { if (nodes[i] == node) throw new XMLException("can't assign a XML Node to himself"); if (nodes[i] != null) node.appendChild(XMLCaster.toRawNode(nodes[i])); } } else { Node child = XMLCaster.toNode(doc, value); if (!k.getString().equalsIgnoreCase(child.getNodeName())) { throw new XMLException( "if you assign a XML Element to a XMLStruct , assignment property must have same name like XML Node Name", "Property Name is " + k.getString() + " and XML Element Name is " + child.getNodeName()); } NodeList list = XMLUtil.getChildNodes(node, Node.ELEMENT_NODE); int len = list.getLength(); Node n; for (int i = 0; i < len; i++) { n = list.item(i); if (nameEqual(n, k.getString(), caseSensitive)) { node.replaceChild(XMLCaster.toRawNode(child), XMLCaster.toRawNode(n)); return value; } } node.appendChild(XMLCaster.toRawNode(child)); } return value; }
public BufferedImage filter(BufferedImage src, Struct parameters) throws PageException { BufferedImage dst = ImageUtil.createBufferedImage(src); Object o; if ((o = parameters.removeEL(KeyImpl.init("Amount"))) != null) setAmount(ImageFilterUtil.toFloatValue(o, "Amount")); if ((o = parameters.removeEL(KeyImpl.init("Exposure"))) != null) setExposure(ImageFilterUtil.toFloatValue(o, "Exposure")); if ((o = parameters.removeEL(KeyImpl.init("ColorSource"))) != null) setColorSource(ImageFilterUtil.toColorRGB(o, "ColorSource")); if ((o = parameters.removeEL(KeyImpl.init("Material"))) != null) setMaterial(ImageFilterUtil.toLightFilter$Material(o, "Material")); if ((o = parameters.removeEL(KeyImpl.init("BumpFunction"))) != null) setBumpFunction(ImageFilterUtil.toFunction2D(o, "BumpFunction")); if ((o = parameters.removeEL(KeyImpl.init("BumpHeight"))) != null) setBumpHeight(ImageFilterUtil.toFloatValue(o, "BumpHeight")); if ((o = parameters.removeEL(KeyImpl.init("BumpSoftness"))) != null) setBumpSoftness(ImageFilterUtil.toFloatValue(o, "BumpSoftness")); if ((o = parameters.removeEL(KeyImpl.init("BumpShape"))) != null) setBumpShape(ImageFilterUtil.toIntValue(o, "BumpShape")); if ((o = parameters.removeEL(KeyImpl.init("ViewDistance"))) != null) setViewDistance(ImageFilterUtil.toFloatValue(o, "ViewDistance")); if ((o = parameters.removeEL(KeyImpl.init("EnvironmentMap"))) != null) setEnvironmentMap(ImageFilterUtil.toBufferedImage(o, "EnvironmentMap")); if ((o = parameters.removeEL(KeyImpl.init("BumpSource"))) != null) setBumpSource(ImageFilterUtil.toIntValue(o, "BumpSource")); if ((o = parameters.removeEL(KeyImpl.init("DiffuseColor"))) != null) setDiffuseColor(ImageFilterUtil.toColorRGB(o, "DiffuseColor")); // check for arguments not supported if (parameters.size() > 0) { throw new FunctionException( ThreadLocalPageContext.get(), "ImageFilter", 3, "parameters", "the parameter" + (parameters.size() > 1 ? "s" : "") + " [" + CollectionUtil.getKeyList(parameters, ", ") + "] " + (parameters.size() > 1 ? "are" : "is") + " not allowed, only the following parameters are supported [Amount, Exposure, ColorSource, Material, BumpFunction, BumpHeight, BumpSoftness, BumpShape, ViewDistance, EnvironmentMap, BumpSource, DiffuseColor]"); } return filter(src, dst); }
public final class XMLUtil { public static final Collection.Key XMLCOMMENT = KeyImpl.getInstance("xmlcomment"); public static final Collection.Key XMLTEXT = KeyImpl.getInstance("xmltext"); public static final Collection.Key XMLCDATA = KeyImpl.getInstance("xmlcdata"); public static final Collection.Key XMLCHILDREN = KeyImpl.getInstance("xmlchildren"); public static final Collection.Key XMLNSURI = KeyImpl.getInstance("xmlnsuri"); public static final Collection.Key XMLNSPREFIX = KeyImpl.getInstance("xmlnsprefix"); public static final Collection.Key XMLROOT = KeyImpl.getInstance("xmlroot"); public static final Collection.Key XMLPARENT = KeyImpl.getInstance("xmlparent"); public static final Collection.Key XMLNAME = KeyImpl.getInstance("xmlname"); public static final Collection.Key XMLTYPE = KeyImpl.getInstance("xmltype"); public static final Collection.Key XMLVALUE = KeyImpl.getInstance("xmlvalue"); public static final Collection.Key XMLATTRIBUTES = KeyImpl.getInstance("xmlattributes"); /* private static final Collection.Key = KeyImpl.getInstance(); private static final Collection.Key = KeyImpl.getInstance(); private static final Collection.Key = KeyImpl.getInstance(); private static final Collection.Key = KeyImpl.getInstance(); private static final Collection.Key = KeyImpl.getInstance(); private static final Collection.Key = KeyImpl.getInstance(); */ // static DOMParser parser = new DOMParser(); private static DocumentBuilder docBuilder; // private static DocumentBuilderFactory factory; private static TransformerFactory transformerFactory; public static String unescapeXMLString(String str) { StringBuffer rtn = new StringBuffer(); int posStart = -1; int posFinish = -1; while ((posStart = str.indexOf('&', posStart)) != -1) { int last = posFinish + 1; posFinish = str.indexOf(';', posStart); if (posFinish == -1) break; rtn.append(str.substring(last, posStart)); if (posStart + 1 < posFinish) { rtn.append(unescapeXMLEntity(str.substring(posStart + 1, posFinish))); } else { rtn.append("&;"); } posStart = posFinish + 1; } rtn.append(str.substring(posFinish + 1)); return rtn.toString(); } public static String unescapeXMLString2(String str) { StringBuffer sb = new StringBuffer(); int index, last = 0, indexSemi; while ((index = str.indexOf('&', last)) != -1) { sb.append(str.substring(last, index)); indexSemi = str.indexOf(';', index + 1); if (indexSemi == -1) { sb.append('&'); last = index + 1; } else if (index + 1 == indexSemi) { sb.append("&;"); last = index + 2; } else { sb.append(unescapeXMLEntity(str.substring(index + 1, indexSemi))); last = indexSemi + 1; } } sb.append(str.substring(last)); return sb.toString(); } private static String unescapeXMLEntity(String str) { if ("lt".equals(str)) return "<"; if ("gt".equals(str)) return ">"; if ("amp".equals(str)) return "&"; if ("apos".equals(str)) return "'"; if ("quot".equals(str)) return "\""; return "&" + str + ";"; } public static String escapeXMLString(String xmlStr) { char c; StringBuffer sb = new StringBuffer(); int len = xmlStr.length(); for (int i = 0; i < len; i++) { c = xmlStr.charAt(i); if (c == '<') sb.append("<"); else if (c == '>') sb.append(">"); else if (c == '&') sb.append("&"); // else if(c=='\'') sb.append("&"); else if (c == '"') sb.append("""); // else if(c>127) sb.append("&#"+((int)c)+";"); else sb.append(c); } return sb.toString(); } /** @return returns a singelton TransformerFactory */ public static TransformerFactory getTransformerFactory() { // Saxon // if(transformerFactory==null)transformerFactory=new com.icl.saxon.TransformerFactoryImpl(); // Xalan if (transformerFactory == null) transformerFactory = new TransformerFactoryImpl(); // Trax // if(transformerFactory==null)transformerFactory=new // com.jclark.xsl.trax.TransformerFactoryImpl(); // Trax // if(transformerFactory==null)transformerFactory=new jd.xml.xslt.trax.TransformerFactoryImpl(); // Caucho // if(transformerFactory==null)transformerFactory=new Xsl(); // xsltc // if(transformerFactory==null)transformerFactory=new // org.apache.xalan.xsltc.trax.TransformerFactoryImpl(); return transformerFactory; } /** * parse XML/HTML String to a XML DOM representation * * @param xml XML InputSource * @param isHtml is a HTML or XML Object * @return parsed Document * @throws SAXException * @throws IOException * @throws ParserConfigurationException */ public static final Document parse(InputSource xml, InputSource validator, boolean isHtml) throws SAXException, IOException { if (!isHtml) { // try to load org.apache.xerces.jaxp.DocumentBuilderFactoryImpl, oracle impl sucks DocumentBuilderFactory factory = null; try { factory = new DocumentBuilderFactoryImpl(); } catch (Throwable t) { factory = DocumentBuilderFactory.newInstance(); } // print.o(factory); if (validator == null) { XMLUtil.setAttributeEL(factory, XMLConstants.NON_VALIDATING_DTD_EXTERNAL, Boolean.FALSE); XMLUtil.setAttributeEL(factory, XMLConstants.NON_VALIDATING_DTD_GRAMMAR, Boolean.FALSE); } else { XMLUtil.setAttributeEL(factory, XMLConstants.VALIDATION_SCHEMA, Boolean.TRUE); XMLUtil.setAttributeEL(factory, XMLConstants.VALIDATION_SCHEMA_FULL_CHECKING, Boolean.TRUE); } factory.setNamespaceAware(true); factory.setValidating(validator != null); try { DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(new XMLEntityResolverDefaultHandler(validator)); builder.setErrorHandler(new ThrowingErrorHandler(true, true, false)); return builder.parse(xml); } catch (ParserConfigurationException e) { throw new SAXException(e); } /*DOMParser parser = new DOMParser(); print.out("parse"); parser.setEntityResolver(new XMLEntityResolverDefaultHandler(validator)); parser.parse(xml); return parser.getDocument();*/ } XMLReader reader = new Parser(); reader.setFeature(Parser.namespacesFeature, true); reader.setFeature(Parser.namespacePrefixesFeature, true); try { Transformer transformer = TransformerFactory.newInstance().newTransformer(); DOMResult result = new DOMResult(); transformer.transform(new SAXSource(reader, xml), result); return XMLUtil.getDocument(result.getNode()); } catch (Exception e) { throw new SAXException(e); } } private static void setAttributeEL(DocumentBuilderFactory factory, String name, Object value) { try { factory.setAttribute(name, value); } catch (Throwable t) { // SystemOut.printDate("attribute ["+name+"] is not allowed for // ["+factory.getClass().getName()+"]"); } } /** * sets a node to a node (Expression Less) * * @param node * @param key * @param value * @return Object set */ public static Object setPropertyEL(Node node, Collection.Key key, Object value) { try { return setProperty(node, key, value); } catch (PageException e) { return null; } } public static Object setPropertyEL( Node node, Collection.Key key, Object value, boolean caseSensitive) { try { return setProperty(node, key, value, caseSensitive); } catch (PageException e) { return null; } } /** * sets a node to a node * * @param node * @param key * @param value * @return Object set * @throws PageException */ public static Object setProperty(Node node, Collection.Key k, Object value) throws PageException { return setProperty(node, k, value, isCaseSensitve(node)); } public static Object setProperty(Node node, Collection.Key k, Object value, boolean caseSensitive) throws PageException { Document doc = (node instanceof Document) ? (Document) node : node.getOwnerDocument(); // Comment if (k.equals(XMLCOMMENT)) { removeChilds(XMLCaster.toRawNode(node), Node.COMMENT_NODE, false); node.appendChild(XMLCaster.toRawNode(XMLCaster.toComment(doc, value))); } // NS URI else if (k.equals(XMLNSURI)) { // TODO impl throw new ExpressionException("XML NS URI can't be set", "not implemented"); } // Prefix else if (k.equals(XMLNSPREFIX)) { // TODO impl throw new ExpressionException("XML NS Prefix can't be set", "not implemented"); // node.setPrefix(Caster.toString(value)); } // Root else if (k.equals(XMLROOT)) { doc.appendChild(XMLCaster.toNode(doc, value)); } // Parent else if (k.equals(XMLPARENT)) { Node parent = getParentNode(node, caseSensitive); Key name = KeyImpl.init(parent.getNodeName()); parent = getParentNode(parent, caseSensitive); if (parent == null) throw new ExpressionException( "there is no parent element, you are already on the root element"); return setProperty(parent, name, value, caseSensitive); } // Name else if (k.equals(XMLNAME)) { throw new XMLException("You can't assign a new value for the property [xmlname]"); } // Type else if (k.equals(XMLTYPE)) { throw new XMLException("You can't change type of a xml node [xmltype]"); } // value else if (k.equals(XMLVALUE)) { node.setNodeValue(Caster.toString(value)); } // Attributes else if (k.equals(XMLATTRIBUTES)) { Element parent = XMLCaster.toElement(doc, node); Attr[] attres = XMLCaster.toAttrArray(doc, value); // print.ln("=>"+value); for (int i = 0; i < attres.length; i++) { if (attres[i] != null) { parent.setAttributeNode(attres[i]); // print.ln(attres[i].getName()+"=="+attres[i].getValue()); } } } // Text else if (k.equals(XMLTEXT)) { removeChilds(XMLCaster.toRawNode(node), Node.TEXT_NODE, false); node.appendChild(XMLCaster.toRawNode(XMLCaster.toText(doc, value))); } // CData else if (k.equals(XMLCDATA)) { removeChilds(XMLCaster.toRawNode(node), Node.CDATA_SECTION_NODE, false); node.appendChild(XMLCaster.toRawNode(XMLCaster.toCDATASection(doc, value))); } // Children else if (k.equals(XMLCHILDREN)) { Node[] nodes = XMLCaster.toNodeArray(doc, value); removeChilds(XMLCaster.toRawNode(node), Node.ELEMENT_NODE, false); for (int i = 0; i < nodes.length; i++) { if (nodes[i] == node) throw new XMLException("can't assign a XML Node to himself"); if (nodes[i] != null) node.appendChild(XMLCaster.toRawNode(nodes[i])); } } else { Node child = XMLCaster.toNode(doc, value); if (!k.getString().equalsIgnoreCase(child.getNodeName())) { throw new XMLException( "if you assign a XML Element to a XMLStruct , assignment property must have same name like XML Node Name", "Property Name is " + k.getString() + " and XML Element Name is " + child.getNodeName()); } NodeList list = XMLUtil.getChildNodes(node, Node.ELEMENT_NODE); int len = list.getLength(); Node n; for (int i = 0; i < len; i++) { n = list.item(i); if (nameEqual(n, k.getString(), caseSensitive)) { node.replaceChild(XMLCaster.toRawNode(child), XMLCaster.toRawNode(n)); return value; } } node.appendChild(XMLCaster.toRawNode(child)); } return value; } public static Object getPropertyEL(Node node, Collection.Key key) { return getPropertyEL(node, key, isCaseSensitve(node)); } /** * returns a property from a XMl Node (Expression Less) * * @param node * @param key * @param caseSensitive * @return Object matching key */ public static Object getPropertyEL(Node node, Collection.Key k, boolean caseSensitive) { try { return getProperty(node, k, caseSensitive); } catch (SAXException e) { return null; } } public static Object getProperty(Node node, Collection.Key key) throws SAXException { return getProperty(node, key, isCaseSensitve(node)); } /** * returns a property from a XMl Node * * @param node * @param key * @param caseSensitive * @return Object matching key * @throws SAXException */ public static Object getProperty(Node node, Collection.Key k, boolean caseSensitive) throws SAXException { // String lcKey=StringUtil.toLowerCase(key); if (k.getLowerString().startsWith("xml")) { // Comment if (k.equals(XMLCOMMENT)) { StringBuffer sb = new StringBuffer(); NodeList list = node.getChildNodes(); int len = list.getLength(); for (int i = 0; i < len; i++) { Node n = list.item(i); if (n instanceof Comment) { sb.append(((Comment) n).getData()); } } return sb.toString(); } // NS URI if (k.equals(XMLNSURI)) { undefinedInRoot(k, node); return param(node.getNamespaceURI(), ""); } // Prefix if (k.equals(XMLNSPREFIX)) { undefinedInRoot(k, node); return param(node.getPrefix(), ""); } // Root else if (k.equals(XMLROOT)) { Element re = getRootElement(node, caseSensitive); if (re == null) throw new SAXException( "Attribute [" + k.getString() + "] not found in XML, XML is empty"); return param(re, ""); } // Parent else if (k.equals(XMLPARENT)) { Node parent = getParentNode(node, caseSensitive); if (parent == null) { if (node.getNodeType() == Node.DOCUMENT_NODE) throw new SAXException( "Attribute [" + k.getString() + "] not found in XML, there is no parent element, you are already at the root element"); throw new SAXException( "Attribute [" + k.getString() + "] not found in XML, there is no parent element"); } return parent; } // Name else if (k.equals(XMLNAME)) { return node.getNodeName(); } // Value else if (k.equals(XMLVALUE)) { return StringUtil.toStringEmptyIfNull(node.getNodeValue()); } // type else if (k.equals(XMLTYPE)) { return getTypeAsString(node, true); } // Attributes else if (k.equals(XMLATTRIBUTES)) { NamedNodeMap attr = node.getAttributes(); if (attr == null) throw undefined(k, node); return new XMLAttributes(node.getOwnerDocument(), attr, caseSensitive); } // Text else if (k.equals(XMLTEXT)) { undefinedInRoot(k, node); StringBuffer sb = new StringBuffer(); NodeList list = node.getChildNodes(); int len = list.getLength(); for (int i = 0; i < len; i++) { Node n = list.item(i); if (n instanceof Text || n instanceof CDATASection) { sb.append(((CharacterData) n).getData()); } } return sb.toString(); } else if (k.equals(XMLCDATA)) { undefinedInRoot(k, node); StringBuffer sb = new StringBuffer(); NodeList list = node.getChildNodes(); int len = list.getLength(); for (int i = 0; i < len; i++) { Node n = list.item(i); if (n instanceof Text || n instanceof CDATASection) { sb.append(((CharacterData) n).getData()); } } return sb.toString(); } // children else if (k.equals(XMLCHILDREN)) { return new XMLNodeList(node, caseSensitive); } } if (node instanceof Document) { node = ((Document) node).getDocumentElement(); if (node == null) throw new SAXException("Attribute [" + k.getString() + "] not found in XML, XML is empty"); // if((!caseSensitive && node.getNodeName().equalsIgnoreCase(k.getString())) || (caseSensitive // && node.getNodeName().equals(k.getString()))) { if (nameEqual(node, k.getString(), caseSensitive)) { return XMLStructFactory.newInstance(node, caseSensitive); } } else if (node.getNodeType() == Node.ELEMENT_NODE && Decision.isInteger(k)) { int index = Caster.toIntValue(k, 0); int count = 0; Node parent = node.getParentNode(); String nodeName = node.getNodeName(); Element[] children = XMLUtil.getChildElementsAsArray(parent); for (int i = 0; i < children.length; i++) { if (XMLUtil.nameEqual(children[i], nodeName, caseSensitive)) count++; if (count == index) return XMLCaster.toXMLStruct(children[i], caseSensitive); } String detail; if (count == 0) detail = "there are no Elements with this name"; else if (count == 1) detail = "there is only 1 Element with this name"; else detail = "there are only " + count + " Elements with this name"; throw new SAXException( "invalid index [" + k.getString() + "] for Element with name [" + node.getNodeName() + "], " + detail); } else { List<Node> children = XMLUtil.getChildNodesAsList(node, Node.ELEMENT_NODE, caseSensitive, null); int len = children.size(); Array array = null; // new ArrayImpl(); Element el; XMLStruct sct = null, first = null; for (int i = 0; i < len; i++) { el = (Element) children.get(i); // XMLCaster.toXMLStruct(getChildNode(index),caseSensitive); if (XMLUtil.nameEqual(el, k.getString(), caseSensitive)) { sct = XMLCaster.toXMLStruct(el, caseSensitive); if (array != null) { array.appendEL(sct); } else if (first != null) { array = new ArrayImpl(); array.appendEL(first); array.appendEL(sct); } else { first = sct; } } } if (array != null) { try { return new XMLMultiElementStruct(array, false); } catch (PageException e) { } } if (first != null) return first; } throw new SAXException("Attribute [" + k.getString() + "] not found"); } private static SAXException undefined(Key key, Node node) { if (node.getNodeType() == Node.DOCUMENT_NODE) return new SAXException( "you cannot address [" + key + "] on the Document Object, to address [" + key + "] from the root Node use [{variable-name}.xmlRoot." + key + "]"); return new SAXException(key + " is undefined"); } private static void undefinedInRoot(Key key, Node node) throws SAXException { if (node.getNodeType() == Node.DOCUMENT_NODE) throw undefined(key, node); } /** * check if given name is equal to name of the element (with and without namespace) * * @param node * @param k * @param caseSensitive * @return */ public static boolean nameEqual(Node node, String name, boolean caseSensitive) { if (name == null) return false; if (caseSensitive) { return name.equals(node.getNodeName()) || name.equals(node.getLocalName()); } return name.equalsIgnoreCase(node.getNodeName()) || name.equalsIgnoreCase(node.getLocalName()); } public static boolean isCaseSensitve(Node node) { if (node instanceof XMLStruct) return ((XMLStruct) node).isCaseSensitive(); return true; } /** * removes child from a node * * @param node * @param key * @param caseSensitive * @return removed property */ public static Object removeProperty(Node node, Collection.Key k, boolean caseSensitive) { // String lcKeyx=k.getLowerString(); if (k.getLowerString().startsWith("xml")) { // Comment if (k.equals(XMLCOMMENT)) { StringBuffer sb = new StringBuffer(); NodeList list = node.getChildNodes(); int len = list.getLength(); for (int i = 0; i < len; i++) { Node n = list.item(i); if (n instanceof Comment) { sb.append(((Comment) n).getData()); node.removeChild(XMLCaster.toRawNode(n)); } } return sb.toString(); } // Text else if (k.equals(XMLTEXT)) { StringBuffer sb = new StringBuffer(); NodeList list = node.getChildNodes(); int len = list.getLength(); for (int i = 0; i < len; i++) { Node n = list.item(i); if (n instanceof Text || n instanceof CDATASection) { sb.append(((CharacterData) n).getData()); node.removeChild(XMLCaster.toRawNode(n)); } } return sb.toString(); } // children else if (k.equals(XMLCHILDREN)) { NodeList list = node.getChildNodes(); for (int i = list.getLength() - 1; i >= 0; i--) { node.removeChild(XMLCaster.toRawNode(list.item(i))); } return list; } } NodeList nodes = node.getChildNodes(); Array array = new ArrayImpl(); for (int i = nodes.getLength() - 1; i >= 0; i--) { Object o = nodes.item(i); if (o instanceof Element) { Element el = (Element) o; if (nameEqual(el, k.getString(), caseSensitive)) { array.appendEL(XMLCaster.toXMLStruct(el, caseSensitive)); node.removeChild(XMLCaster.toRawNode(el)); } } } if (array.size() > 0) { try { return new XMLMultiElementStruct(array, false); } catch (PageException e) { } } return null; } private static Object param(Object o1, Object o2) { if (o1 == null) return o2; return o1; } /** * return the root Element from a node * * @param node node to get root element from * @param caseSensitive * @return Root Element */ public static Element getRootElement(Node node, boolean caseSensitive) { Document doc = null; if (node instanceof Document) doc = (Document) node; else doc = node.getOwnerDocument(); Element el = doc.getDocumentElement(); if (el == null) return null; return (Element) XMLStructFactory.newInstance(el, caseSensitive); } public static Node getParentNode(Node node, boolean caseSensitive) { Node parent = node.getParentNode(); if (parent == null) return null; return XMLStructFactory.newInstance(parent, caseSensitive); } /** * returns a new Empty XMl Document * * @return new Document * @throws ParserConfigurationException * @throws FactoryConfigurationError */ public static Document newDocument() throws ParserConfigurationException, FactoryConfigurationError { if (docBuilder == null) { docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); } return docBuilder.newDocument(); } /** * return the Owner Document of a Node List * * @param nodeList * @return XML Document * @throws XMLException */ public static Document getDocument(NodeList nodeList) throws XMLException { if (nodeList instanceof Document) return (Document) nodeList; int len = nodeList.getLength(); for (int i = 0; i < len; i++) { Node node = nodeList.item(i); if (node != null) return node.getOwnerDocument(); } throw new XMLException("can't get Document from NodeList, in NoteList are no Nodes"); } /** * return the Owner Document of a Node * * @param node * @return XML Document */ public static Document getDocument(Node node) { if (node instanceof Document) return (Document) node; return node.getOwnerDocument(); } /** * removes all comments from a node * * @param node node to remove elements from * @param type Type Definition to remove (Constant value from class Node) * @param deep remove also in sub nodes */ private static synchronized void removeChilds(Node node, short type, boolean deep) { NodeList list = node.getChildNodes(); for (int i = list.getLength(); i >= 0; i--) { Node n = list.item(i); if (n == null) continue; else if (n.getNodeType() == type) node.removeChild(XMLCaster.toRawNode(n)); else if (deep) removeChilds(n, type, deep); } } /** * return all Children of a node by a defined type as Node List * * @param node node to get children from * @param type type of returned node * @param filter * @param caseSensitive * @return all matching child node */ public static synchronized ArrayNodeList getChildNodes(Node node, short type) { return getChildNodes(node, type, false, null); } public static synchronized int childNodesLength( Node node, short type, boolean caseSensitive, String filter) { NodeList nodes = node.getChildNodes(); int len = nodes.getLength(); Node n; int count = 0; for (int i = 0; i < len; i++) { try { n = nodes.item(i); if (n != null && n.getNodeType() == type) { if (filter == null || (caseSensitive ? filter.equals(n.getLocalName()) : filter.equalsIgnoreCase(n.getLocalName()))) count++; } } catch (Throwable t) { } } return count; } public static synchronized ArrayNodeList getChildNodes( Node node, short type, boolean caseSensitive, String filter) { ArrayNodeList rtn = new ArrayNodeList(); NodeList nodes = node.getChildNodes(); int len = nodes.getLength(); Node n; for (int i = 0; i < len; i++) { try { n = nodes.item(i); if (n != null && n.getNodeType() == type) { if (filter == null || (caseSensitive ? filter.equals(n.getLocalName()) : filter.equalsIgnoreCase(n.getLocalName()))) rtn.add(n); } } catch (Throwable t) { } } return rtn; } public static synchronized List<Node> getChildNodesAsList( Node node, short type, boolean caseSensitive, String filter) { List<Node> rtn = new ArrayList<Node>(); NodeList nodes = node.getChildNodes(); int len = nodes.getLength(); Node n; for (int i = 0; i < len; i++) { try { n = nodes.item(i); if (n != null && n.getNodeType() == type) { if (filter == null || (caseSensitive ? filter.equals(n.getLocalName()) : filter.equalsIgnoreCase(n.getLocalName()))) rtn.add(n); } } catch (Throwable t) { } } return rtn; } public static synchronized Node getChildNode( Node node, short type, boolean caseSensitive, String filter, int index) { NodeList nodes = node.getChildNodes(); int len = nodes.getLength(); Node n; int count = 0; for (int i = 0; i < len; i++) { try { n = nodes.item(i); if (n != null && n.getNodeType() == type) { if (filter == null || (caseSensitive ? filter.equals(n.getLocalName()) : filter.equalsIgnoreCase(n.getLocalName()))) { if (count == index) return n; count++; } } } catch (Throwable t) { } } return null; } /** * return all Children of a node by a defined type as Node Array * * @param node node to get children from * @param type type of returned node * @param filter * @param caseSensitive * @return all matching child node */ public static Node[] getChildNodesAsArray(Node node, short type) { ArrayNodeList nodeList = (ArrayNodeList) getChildNodes(node, type); return (Node[]) nodeList.toArray(new Node[nodeList.getLength()]); } public static Node[] getChildNodesAsArray( Node node, short type, boolean caseSensitive, String filter) { ArrayNodeList nodeList = (ArrayNodeList) getChildNodes(node, type, caseSensitive, filter); return (Node[]) nodeList.toArray(new Node[nodeList.getLength()]); } /** * return all Element Children of a node * * @param node node to get children from * @return all matching child node */ public static Element[] getChildElementsAsArray(Node node) { ArrayNodeList nodeList = (ArrayNodeList) getChildNodes(node, Node.ELEMENT_NODE); return (Element[]) nodeList.toArray(new Element[nodeList.getLength()]); } /** * transform a XML Object to a other format, with help of a XSL Stylesheet * * @param strXML XML String * @param strXSL XSL String * @return transformed Object * @throws TransformerException * @throws IOException * @throws SAXException * @throws */ public static String transform(InputSource xml, InputSource xsl) throws TransformerException, SAXException, IOException { // toInputSource(pc, xml) return transform(parse(xml, null, false), xsl); } /** * transform a XML Object to a other format, with help of a XSL Stylesheet * * @param doc XML Document Object * @param strXSL XSL String * @return transformed Object * @throws TransformerException */ public static String transform(Document doc, InputSource xsl) throws TransformerException { StringWriter sw = new StringWriter(); Transformer transformer = XMLUtil.getTransformerFactory().newTransformer(new StreamSource(xsl.getCharacterStream())); transformer.transform(new DOMSource(doc), new StreamResult(sw)); return sw.toString(); } /** * returns the Node Type As String * * @param node * @param cftype * @return */ public static String getTypeAsString(Node node, boolean cftype) { String suffix = cftype ? "" : "_NODE"; switch (node.getNodeType()) { case Node.ATTRIBUTE_NODE: return "ATTRIBUTE" + suffix; case Node.CDATA_SECTION_NODE: return "CDATA_SECTION" + suffix; case Node.COMMENT_NODE: return "COMMENT" + suffix; case Node.DOCUMENT_FRAGMENT_NODE: return "DOCUMENT_FRAGMENT" + suffix; case Node.DOCUMENT_NODE: return "DOCUMENT" + suffix; case Node.DOCUMENT_TYPE_NODE: return "DOCUMENT_TYPE" + suffix; case Node.ELEMENT_NODE: return "ELEMENT" + suffix; case Node.ENTITY_NODE: return "ENTITY" + suffix; case Node.ENTITY_REFERENCE_NODE: return "ENTITY_REFERENCE" + suffix; case Node.NOTATION_NODE: return "NOTATION" + suffix; case Node.PROCESSING_INSTRUCTION_NODE: return "PROCESSING_INSTRUCTION" + suffix; case Node.TEXT_NODE: return "TEXT" + suffix; default: return "UNKNOW" + suffix; } } public static synchronized Element getChildWithName(String name, Element el) { Element[] children = XMLUtil.getChildElementsAsArray(el); for (int i = 0; i < children.length; i++) { if (name.equalsIgnoreCase(children[i].getNodeName())) return children[i]; } return null; } public static InputSource toInputSource(Resource res) throws IOException { String str = IOUtil.toString((res), null); return new InputSource(new StringReader(str)); } public static InputSource toInputSource(PageContext pc, Object value) throws IOException, ExpressionException { if (value instanceof InputSource) { return (InputSource) value; } if (value instanceof String) { return toInputSource(pc, (String) value); } if (value instanceof StringBuffer) { return toInputSource(pc, value.toString()); } if (value instanceof Resource) { String str = IOUtil.toString(((Resource) value), null); return new InputSource(new StringReader(str)); } if (value instanceof File) { String str = IOUtil.toString(ResourceUtil.toResource(((File) value)), null); return new InputSource(new StringReader(str)); } if (value instanceof InputStream) { InputStream is = (InputStream) value; try { String str = IOUtil.toString(is, null); return new InputSource(new StringReader(str)); } finally { IOUtil.closeEL(is); } } if (value instanceof Reader) { Reader reader = (Reader) value; try { String str = IOUtil.toString(reader); return new InputSource(new StringReader(str)); } finally { IOUtil.closeEL(reader); } } if (value instanceof byte[]) { return new InputSource(new ByteArrayInputStream((byte[]) value)); } throw new ExpressionException( "cat cast object of type [" + Caster.toClassName(value) + "] to a Input for xml parser"); } public static InputSource toInputSource(PageContext pc, String xml) throws IOException, ExpressionException { return toInputSource(pc, xml, true); } public static InputSource toInputSource(PageContext pc, String xml, boolean canBePath) throws IOException, ExpressionException { // xml text xml = xml.trim(); if (!canBePath || xml.startsWith("<")) { return new InputSource(new StringReader(xml)); } // xml link pc = ThreadLocalPageContext.get(pc); Resource res = ResourceUtil.toResourceExisting(pc, xml); return toInputSource(pc, res); } public static Struct validate(InputSource xml, InputSource schema, String strSchema) throws XMLException { return new XMLValidator(schema, strSchema).validate(xml); } /** * adds a child at the first place * * @param parent * @param child */ public static void prependChild(Element parent, Element child) { Node first = parent.getFirstChild(); if (first == null) parent.appendChild(child); else { parent.insertBefore(child, first); } } public static void setFirst(Node parent, Node node) { Node first = parent.getFirstChild(); if (first != null) parent.insertBefore(node, first); else parent.appendChild(node); } }