public void testImageInsideCollection() throws Exception { execute("CRUD.new"); execute("Collection.new", "viewObject=xava_view_section0_ingredients"); execute("ImageEditor.changeImage", "newImageProperty=image"); assertNoErrors(); assertAction("LoadImage.loadImage"); String imageUrl = System.getProperty("user.dir") + "/test-images/cake.gif"; setFileValue("newImage", imageUrl); execute("LoadImage.loadImage"); assertNoErrors(); HtmlPage page = (HtmlPage) getWebClient().getCurrentWindow().getEnclosedPage(); URL url = page.getWebResponse().getRequestSettings().getUrl(); String urlPrefix = url.getProtocol() + "://" + url.getHost() + ":" + url.getPort(); HtmlImage image = (HtmlImage) page.getElementsByName(decorateId("image")).get(0); String imageURL = null; if (image.getSrcAttribute().startsWith("/")) { imageURL = urlPrefix + image.getSrcAttribute(); } else { String urlBase = Strings.noLastToken(url.getPath(), "/"); imageURL = urlPrefix + urlBase + image.getSrcAttribute(); } WebResponse response = getWebClient().getPage(imageURL).getWebResponse(); assertTrue("Image not obtained", response.getContentAsString().length() > 0); assertEquals("Result is not an image", "image", response.getContentType()); }
private static void createDefaultMetaModules(MetaApplication app) { for (String className : AnnotatedClassParser.getManagedClassNames()) { if (className.endsWith(".GalleryImage") || className.endsWith(".AttachedFile")) continue; if (isEmbeddable(className)) continue; app.getMetaModule(Strings.lastToken(className, ".")); } }
public void setCondition(String condition) { if (condition != null && condition.toLowerCase().indexOf("year(curdate())") >= 0) { Calendar cal = Calendar.getInstance(); cal.setTime(new java.util.Date()); condition = Strings.change(condition, "year(curdate())", String.valueOf(cal.get(Calendar.YEAR))); } this.condition = condition; }
private String getHQLCondition(boolean order) throws XavaException { StringBuffer sb = new StringBuffer("from "); sb.append(getMetaModel().getName()); sb.append(" as o"); if (!Is.emptyString(this.condition)) { sb.append(" where "); String condition = transformAggregateProperties(getCondition()); condition = Strings.change(condition, getArgumentsToHQL()); sb.append(Strings.change(condition, getTokensToChangeDollarsAndNL())); } if (order && !Is.emptyString(this.order)) { sb.append(" order by "); sb.append( Strings.change( transformAggregateProperties(this.order), getTokensToChangeDollarsAndNL())); } return sb.toString(); }
protected Tab getTab() throws XavaException { if (tab == null) { String tabObject = Is.emptyString(collection) ? "xava_tab" : Tab.COLLECTION_PREFIX + Strings.change(collection, ".", "_"); tab = (Tab) getContext().get(getRequest(), tabObject); if (tab.getCollectionView() != null) { tab.getCollectionView().refreshCollections(); } } return tab; }
public String changePropertiesByCMPAttributes(String source) throws XavaException { StringBuffer r = new StringBuffer(source); int i = r.toString().indexOf("${"); int f = 0; while (i >= 0) { f = r.toString().indexOf("}", i + 2); if (f < 0) break; String property = r.substring(i + 2, f); String cmpAttribute = null; if (property.indexOf('.') >= 0) { cmpAttribute = "o._" + Strings.firstUpper(Strings.change(property, ".", "_")); } else { MetaProperty metaProperty = getMetaModel().getMetaProperty(property); if (metaProperty.getMapping().hasConverter()) { cmpAttribute = "o._" + Strings.firstUpper(property); } else { cmpAttribute = "o." + property; } } r.replace(i, f + 1, cmpAttribute); i = r.toString().indexOf("${"); } return r.toString(); }
public String getEJBQLCondition() throws XavaException { StringBuffer sb = new StringBuffer("SELECT OBJECT(o) FROM "); sb.append(getMetaModel().getName()); sb.append(" o"); if (!Is.emptyString(this.condition)) { sb.append(" WHERE "); String attributesCondition = getMetaModel().getMapping().changePropertiesByCMPAttributes(this.condition); sb.append(Strings.change(attributesCondition, getArgumentsJBoss11ToEJBQL())); } if (!Is.emptyString(this.order)) { sb.append(" ORDER BY "); sb.append(getMetaModel().getMapping().changePropertiesByCMPAttributes(this.order)); } return sb.toString(); }
public void testChangeImage() throws Exception { addImage(); HtmlPage page = (HtmlPage) getWebClient().getCurrentWindow().getEnclosedPage(); URL url = page.getWebResponse().getRequestSettings().getUrl(); String urlPrefix = url.getProtocol() + "://" + url.getHost() + ":" + url.getPort(); HtmlImage image = (HtmlImage) page.getElementsByName(decorateId("photo")).get(0); String imageURL = null; if (image.getSrcAttribute().startsWith("/")) { imageURL = urlPrefix + image.getSrcAttribute(); } else { String urlBase = Strings.noLastToken(url.getPath(), "/"); imageURL = urlPrefix + urlBase + image.getSrcAttribute(); } WebResponse response = getWebClient().getPage(imageURL).getWebResponse(); assertTrue("Image not obtained", response.getContentAsString().length() > 0); assertEquals("Result is not an image", "image", response.getContentType()); }
private void loadDatabaseMetadata() { if (!databaseMetadataLoaded) { String componentName = "UNKNOWN"; Connection con = null; try { componentName = getMetaComponent().getName(); con = DataSourceConnectionProvider.getByComponent(componentName).getConnection(); DatabaseMetaData metaData = con.getMetaData(); supportsSchemasInDataManipulation = metaData.supportsSchemasInDataManipulation(); Collection timeDateFunctions = Strings.toCollection(metaData.getTimeDateFunctions().toUpperCase()); // // another solution instead of the use of 'if' would be to use a xml with // the information of the functions from each BBDD if ("DB2 UDB for AS/400".equals(metaData.getDatabaseProductName()) || "Oracle".equals(metaData.getDatabaseProductName()) || "PostgresSQL".equals(metaData.getDatabaseProductName())) { supportsTranslateFunction = true; } if ("Oracle".equals(metaData.getDatabaseProductName()) || "PostgreSQL".equals(metaData.getDatabaseProductName())) { supportsYearFunction = supportsMonthFunction = false; } else { supportsYearFunction = timeDateFunctions.contains("YEAR"); supportsMonthFunction = timeDateFunctions.contains("MONTH"); } databaseMetadataLoaded = true; } catch (Exception ex) { log.warn(XavaResources.getString("load_database_metadata_warning")); } finally { try { if (con != null) { con.close(); } } catch (SQLException e) { log.warn(XavaResources.getString("close_connection_warning")); } } } }
private String changePropertiesByColumns(String source, boolean qualified) throws XavaException { StringBuffer r = new StringBuffer(source); int i = r.toString().indexOf("${"); int f = 0; while (i >= 0) { f = r.toString().indexOf("}", i + 2); if (f < 0) break; String property = r.substring(i + 2, f); String column = "0"; // thus it remained if it is calculated if (!getMetaModel().isCalculated(property)) { column = Strings.isModelName(property) ? getTable(property) : qualified ? getQualifiedColumn(property) : getColumn(property); } r.replace(i, f + 1, column); i = r.toString().indexOf("${"); } return r.toString(); }
public void testDeleteImage() throws Exception { addImage(); execute("ImageEditor.deleteImage", "newImageProperty=photo"); assertNoErrors(); HtmlPage page = (HtmlPage) getWebClient().getCurrentWindow().getEnclosedPage(); URL url = page.getWebResponse().getRequestSettings().getUrl(); String urlPrefix = url.getProtocol() + "://" + url.getHost() + ":" + url.getPort(); HtmlImage image = (HtmlImage) page.getElementsByName(decorateId("photo")).get(0); String imageURL = null; if (image.getSrcAttribute().startsWith("/")) { imageURL = urlPrefix + image.getSrcAttribute(); } else { String urlBase = Strings.noLastToken(url.getPath(), "/"); imageURL = urlPrefix + urlBase + image.getSrcAttribute(); } WebResponse response = getWebClient().getPage(imageURL).getWebResponse(); assertTrue("Image obtained", response.getContentAsString().length() == 0); }
private String createSelect() throws XavaException { if (hasBaseCondition()) { String baseCondition = getBaseCondition(); if (baseCondition.trim().toUpperCase().startsWith("SELECT ")) { return baseCondition; } } // basic select StringBuffer select = new StringBuffer("select "); Iterator itProperties = getPropertiesNames().iterator(); while (itProperties.hasNext()) { String property = (String) itProperties.next(); if (Strings.isModelName(property)) select.append("0"); // the property is a table name not column name else { select.append("${"); select.append(property); select.append('}'); } if (itProperties.hasNext()) select.append(", "); } Iterator itHiddenProperties = getHiddenPropertiesNames().iterator(); while (itHiddenProperties.hasNext()) { select.append(", "); select.append("${"); select.append(itHiddenProperties.next()); select.append('}'); } select.append(" from ${"); select.append(getModelName()); select.append('}'); select.append(' '); if (hasBaseCondition()) { select.append(" where "); select.append(getBaseCondition()); } return select.toString(); }
private String getTableColumn(String modelProperty, boolean qualifyReferenceMappingColumn) throws XavaException { PropertyMapping propertyMapping = (PropertyMapping) propertyMappings.get(modelProperty); if (propertyMapping == null) { int idx = modelProperty.indexOf('.'); if (idx >= 0) { String referenceName = modelProperty.substring(0, idx); String propertyName = modelProperty.substring(idx + 1); if (getMetaModel().getMetaReference(referenceName).isAggregate() && !Strings.firstUpper(referenceName).equals(getMetaModel().getContainerModelName())) { propertyMapping = (PropertyMapping) propertyMappings.get(referenceName + "_" + propertyName); if (propertyMapping == null) { int idx2 = propertyName.indexOf('.'); if (idx2 >= 0) { String referenceName2 = propertyName.substring(0, idx2); String propertyName2 = propertyName.substring(idx2 + 1); return getTableColumn( referenceName + "_" + referenceName2 + "." + propertyName2, qualifyReferenceMappingColumn); } else { throw new ElementNotFoundException( "property_mapping_not_found", referenceName + "_" + propertyName, getModelName()); } } return propertyMapping.getColumn(); } ReferenceMapping referenceMapping = getReferenceMapping(referenceName); if (referenceMapping.hasColumnForReferencedModelProperty(propertyName)) { if (qualifyReferenceMappingColumn) { return getTableToQualifyColumn() + "." + referenceMapping.getColumnForReferencedModelProperty(propertyName); } else { return referenceMapping.getColumnForReferencedModelProperty(propertyName); } } else { ModelMapping referencedMapping = referenceMapping.getReferencedMapping(); String tableName = referencedMapping.getTableToQualifyColumn(); boolean secondLevel = propertyName.indexOf('.') >= 0; String columnName = referencedMapping.getTableColumn(propertyName, secondLevel); boolean hasFormula = referencedMapping.getPropertyMapping(propertyName).hasFormula(); if (qualifyReferenceMappingColumn && !secondLevel && !hasFormula) { return tableName + "." + columnName; } else if (hasFormula) { String formula = referencedMapping.getPropertyMapping(propertyName).getFormula(); referencePropertyWithFormula = true; return qualifyFormulaWithReferenceName( formula, referencedMapping.getModelName(), modelProperty); } else { return columnName; } } } throw new ElementNotFoundException( "property_mapping_not_found", modelProperty, getModelName()); } if (propertyMapping.hasFormula()) return propertyMapping.getFormula(); return propertyMapping.getColumn(); }
public Object parse(HttpServletRequest request, String string) throws Exception { if (Is.emptyString(string)) return null; string = Strings.change(string, " ", ""); // In order to work with Polish return new BigDecimal(getFormat().parse(string).toString()).setScale(2); }
/** Determines if the property orderProperty was defined for the object. */ @SuppressWarnings({"unchecked", "rawtypes"}) private void parseOrderDefined() { orderDefined = false; OrderBy orderBy = null; if (Is.empty(orderProperty)) { try { Field collectionField = parentClass.getDeclaredField(collectionName); if (collectionField.isAnnotationPresent(OrderBy.class)) { orderBy = collectionField.getAnnotation(OrderBy.class); } } catch (SecurityException e) { log.error(e); } catch (NoSuchFieldException e) { log.debug(e.getMessage()); } if (orderBy == null) { Method collectionMethod = null; try { collectionMethod = parentClass.getDeclaredMethod( "get" + Strings.firstUpper(collectionName), new Class[] {}); } catch (Exception e) { log.debug(e); } if (collectionMethod == null) { try { collectionMethod = parentClass.getDeclaredMethod( "is" + Strings.firstUpper(collectionName), new Class[] {}); } catch (Exception e) { log.debug(e); } } if (collectionMethod != null && collectionMethod.isAnnotationPresent(OrderBy.class)) { orderBy = collectionMethod.getAnnotation(OrderBy.class); } } if (orderBy != null) { String[] fieldNames = orderBy.value().split(","); if (fieldNames.length > 0) { orderProperty = fieldNames[fieldNames.length - 1].trim(); } } } if (!Is.empty(orderProperty)) { try { Object itemObject = nodeClass.newInstance(); Class propertyType = PropertyUtils.getPropertyType(itemObject, orderProperty); if (propertyType.isAssignableFrom(Integer.class)) { orderDefined = true; } } catch (IllegalAccessException e) { log.error(e); } catch (InvocationTargetException e) { log.error(e); } catch (NoSuchMethodException e) { log.error(e); } catch (Exception e) { log.error(e); } } }
String getCMPAttributeForColumn(String column) throws XavaException { PropertyMapping mapping = getMappingForColumn(column); if (!mapping.hasConverter()) return Strings.change(mapping.getProperty(), ".", "_"); return "_" + Strings.change(Strings.firstUpper(mapping.getProperty()), ".", "_"); }
public MetaViewAction(String action) throws XavaException { this.action = action; setTypeName("java.lang.String"); setName("__ACTION__" + Strings.change(this.action, ".", "_")); setStereotype("__ACTION__"); }
public String getArguments() { arguments = Strings.change(arguments, "String", "java.lang.String"); arguments = Strings.change(arguments, "java.lang.java.lang.String", "java.lang.String"); return arguments; }
/** This method generates the output given a context and output stream */ public boolean generate(XPathContext context, ProgramWriter out) { try { String collectionName = Strings.firstUpper(collection.getName()); if (ejb) { out.print(" \n\t/**\n\t * @ejb:interface-method\n\t */"); } out.print(" \n\tpublic java.util.Collection get"); out.print(collectionName); out.print("() {"); if (ejb) { out.print( " \n\t\tboolean cmtActivated = false;\n\t\tif (!org.openxava.hibernate.XHibernate.isCmt()) {\n\t\t\torg.openxava.hibernate.XHibernate.setCmt(true);\n\t\t\tcmtActivated = true;\n\t\t}"); } out.print(" \n\t\ttry {"); MetaCalculator calculator = collection.getMetaCalculator(); String calculatorClass = calculator.getClassName(); out.print(" \t\t\n\t\t\t"); out.print(calculatorClass); out.print(" "); out.print(collection.getName()); out.print("Calculator= ("); out.print(calculatorClass); out.print(")\n\t\t\t\tgetMetaModel().getMetaCollection(\""); out.print(collection.getName()); out.print("\").getMetaCalculator().createCalculator();"); Iterator itSets = calculator.getMetaSetsWithoutValue().iterator(); while (itSets.hasNext()) { MetaSet set = (MetaSet) itSets.next(); String propertyNameInCalculator = Strings.firstUpper(set.getPropertyName()); String propertyNameFrom = set.getPropertyNameFrom(); MetaProperty p = metaModel.getMetaProperty(propertyNameFrom); if (propertyNameFrom.indexOf('.') >= 0) { if (p.isKey() || p.getMetaModel() instanceof MetaAggregate) { propertyNameFrom = Strings.firstUpper(Strings.change(propertyNameFrom, ".", "_")); } else { StringTokenizer st = new StringTokenizer(propertyNameFrom, "."); String ref = st.nextToken(); String pro = st.nextToken(); propertyNameFrom = Strings.firstUpper(ref) + "().get" + Strings.firstUpper(pro); } } else { propertyNameFrom = Strings.firstUpper(propertyNameFrom); } String getPropertyFrom = "boolean".equals(p.getTypeName()) ? "is" : "get"; String value = set.getValue(); if (set.hasValue()) { out.print(" \n\t\t\t"); out.print(collection.getName()); out.print("Calculator.set"); out.print(propertyNameInCalculator); out.print("(\""); out.print(value); out.print("\");"); } else { out.print(" \t\n\t\t\t"); out.print(collection.getName()); out.print("Calculator.set"); out.print(propertyNameInCalculator); out.print("("); out.print(getPropertyFrom); out.print(propertyNameFrom); out.print("());"); } } // else/sets if (IModelCalculator.class.isAssignableFrom(Class.forName(calculatorClass))) { out.print(" \n\t\t\t\t"); out.print(collection.getName()); out.print("Calculator.setModel(this);"); } if (IEntityCalculator.class.isAssignableFrom(Class.forName(calculatorClass))) { out.print(" \n\t\t\t\t"); out.print(collection.getName()); out.print("Calculator.setEntity(this);"); } if (IJDBCCalculator.class.isAssignableFrom(Class.forName(calculatorClass))) { out.print(" \n\t\t\t\t"); out.print(collection.getName()); out.print("Calculator.setConnectionProvider(getPortableContext());"); } String calculateValueSentence = collection.getName() + "Calculator.calculate()"; out.print(" \n\t\t\treturn "); out.print(Generators.generateCast("java.util.Collection", calculateValueSentence)); out.print( ";\n\t\t}\n\t\tcatch (Exception ex) {\n\t\t\tex.printStackTrace();\n\t\t\tthrow new "); out.print(getException()); out.print("(XavaResources.getString(\"generator.calculate_value_error\", \""); out.print(collection.getName()); out.print("\", \""); out.print(metaModel.getName()); out.print("\", ex.getLocalizedMessage()));\n\t\t}"); if (ejb) { out.print( " \n\t\tfinally {\n\t\t\tif (cmtActivated) {\n\t\t\t\torg.openxava.hibernate.XHibernate.setCmt(false);\n\t\t\t}\n\t\t}"); } out.print(" \t\t\t\t\n\t}"); } catch (Exception e) { System.out.println("Exception: " + e.getMessage()); e.printStackTrace(); return false; } return true; }
public String getColumnName(int c) { return labelAsHeader ? getMetaProperty(c).getLabel(locale) : Strings.change(getMetaProperty(c).getQualifiedName(), ".", "_"); }