@SuppressWarnings("unchecked") public void onSaveOrUpdate(SaveOrUpdateEvent event) throws HibernateException { Object entity = event.getObject(); boolean newEntity = !event.getSession().contains(entity); if (newEntity) { if (beforeInsertCaller != null) { beforeInsertCaller.call(entity); if (event.getSession().contains(entity)) { EntityEntry entry = event.getEntry(); if (entry != null) { Object[] state = entry.getLoadedState(); synchronizePersisterState(entity, entry.getPersister(), state); } } } if (shouldTimestamp) { long time = System.currentTimeMillis(); if (dateCreatedProperty != null && newEntity) { Object now = DefaultGroovyMethods.newInstance(dateCreatedProperty.getType(), new Object[] {time}); dateCreatedProperty.setProperty(entity, now); } if (lastUpdatedProperty != null) { Object now = DefaultGroovyMethods.newInstance(lastUpdatedProperty.getType(), new Object[] {time}); lastUpdatedProperty.setProperty(entity, now); } } } }
private static Object convertConstant(Number source, ClassNode target) { if (ClassHelper.Byte_TYPE.equals(target)) { return source.byteValue(); } if (ClassHelper.Short_TYPE.equals(target)) { return source.shortValue(); } if (ClassHelper.Integer_TYPE.equals(target)) { return source.intValue(); } if (ClassHelper.Long_TYPE.equals(target)) { return source.longValue(); } if (ClassHelper.Float_TYPE.equals(target)) { return source.floatValue(); } if (ClassHelper.Double_TYPE.equals(target)) { return source.doubleValue(); } if (ClassHelper.BigInteger_TYPE.equals(target)) { return DefaultGroovyMethods.asType(source, BigInteger.class); } if (ClassHelper.BigDecimal_TYPE.equals(target)) { return DefaultGroovyMethods.asType(source, BigDecimal.class); } throw new IllegalArgumentException("Unsupported conversion"); }
public void execute() throws BuildException { List<String> packagesToDoc = new ArrayList<String>(); Path sourceDirs = new Path(getProject()); Properties properties = new Properties(); properties.setProperty("windowTitle", windowTitle); properties.setProperty("docTitle", docTitle); properties.setProperty("footer", footer); properties.setProperty("header", header); checkScopeProperties(properties); properties.setProperty("publicScope", publicScope.toString()); properties.setProperty("protectedScope", protectedScope.toString()); properties.setProperty("packageScope", packageScope.toString()); properties.setProperty("privateScope", privateScope.toString()); properties.setProperty("author", author.toString()); properties.setProperty("processScripts", processScripts.toString()); properties.setProperty("includeMainForScripts", includeMainForScripts.toString()); properties.setProperty( "overviewFile", overviewFile != null ? overviewFile.getAbsolutePath() : ""); if (sourcePath != null) { sourceDirs.addExisting(sourcePath); } parsePackages(packagesToDoc, sourceDirs); GroovyDocTool htmlTool = new GroovyDocTool( new ClasspathResourceManager(), // we're gonna get the default templates out of the dist // jar file sourcePath.list(), getDocTemplates(), getPackageTemplates(), getClassTemplates(), links, properties); try { htmlTool.add(sourceFilesToDoc); FileOutputTool output = new FileOutputTool(); htmlTool.renderToOutput( output, destDir.getCanonicalPath()); // TODO push destDir through APIs? } catch (Exception e) { e.printStackTrace(); } // try to override the default stylesheet with custom specified one if needed if (styleSheetFile != null) { try { String css = DefaultGroovyMethods.getText(styleSheetFile); File outfile = new File(destDir, "stylesheet.css"); DefaultGroovyMethods.setText(outfile, css); } catch (IOException e) { System.out.println( "Warning: Unable to copy specified stylesheet '" + styleSheetFile.getAbsolutePath() + "'. Using default stylesheet instead. Due to: " + e.getMessage()); } } }
@SuppressWarnings("unchecked") public boolean onPreUpdate(PreUpdateEvent event) { Object entity = event.getEntity(); boolean evict = false; if (preUpdateEventListener != null) { evict = preUpdateEventListener.call(entity); synchronizePersisterState(entity, event.getPersister(), event.getState()); } if (lastUpdatedProperty != null && shouldTimestamp) { Object now = DefaultGroovyMethods.newInstance( lastUpdatedProperty.getType(), new Object[] {System.currentTimeMillis()}); event .getState()[ ArrayUtils.indexOf( event.getPersister().getPropertyNames(), GrailsDomainClassProperty.LAST_UPDATED)] = now; lastUpdatedProperty.setProperty(entity, now); } if (!AbstractSavePersistentMethod.isAutoValidationDisabled(entity) && !DefaultTypeTransformation.castToBoolean( validateMethod.invoke(entity, new Object[] {validateParams}))) { evict = true; if (failOnErrorEnabled) { Errors errors = (Errors) errorsProperty.getProperty(entity); throw new ValidationException( "Validation error whilst flushing entity [" + entity.getClass().getName() + "]", errors); } } return evict; }
public FreeplaneScriptBaseClass() { super(); nodeMetaClass = InvokerHelper.getMetaClass(Proxy.NodeRO.class); // Groovy rocks! DefaultGroovyMethods.mixin(Number.class, NodeArithmeticsCategory.class); initBinding(); }
/** * Attempts to compile the given InputStream into a Groovy script using the given name * * @param in The InputStream to read the Groovy code from * @param name The name of the class to use * @param pageName The page name * @param metaInfo * @return The compiled java.lang.Class, which is an instance of groovy.lang.Script */ private Class<?> compileGroovyPage( InputStream in, String name, String pageName, GroovyPageMetaInfo metaInfo) { GroovyClassLoader groovyClassLoader = findOrInitGroovyClassLoader(); // Compile the script into an object Class<?> scriptClass; try { scriptClass = groovyClassLoader.parseClass(DefaultGroovyMethods.getText(in), name); } catch (CompilationFailedException e) { LOG.error("Compilation error compiling GSP [" + name + "]:" + e.getMessage(), e); int lineNumber = GrailsExceptionResolver.extractLineNumber(e); final int[] lineMappings = metaInfo.getLineNumbers(); if (lineNumber > 0 && lineNumber < lineMappings.length) { lineNumber = lineMappings[lineNumber - 1]; } throw new GroovyPagesException( "Could not parse script [" + name + "]: " + e.getMessage(), e, lineNumber, pageName); } catch (IOException e) { throw new GroovyPagesException( "IO exception parsing script [" + name + "]: " + e.getMessage(), e); } return scriptClass; }
/** * Get a document field raw value or list of raw values. * * <pre><code> * assert document.title = "Big bad wolf" * assert document.keyword[0] == "wolf" * assert document.keyword[1] == "red hook" * </code></pre> * * @param document the document * @param fieldName the field name * @return a raw value or a list of raw values if the field is multivalued */ public static Object get(Document document, String fieldName) { @SuppressWarnings("unchecked") List<Field> fields = (List<Field>) DefaultGroovyMethods.collect(document.getFields(fieldName)); switch (fields.size()) { case 0: if (document instanceof ScoredDocument) { List<Object> exps = new ArrayList<Object>(); for (Field f : ((ScoredDocument) document).getExpressions()) { if (f.getName().equals(fieldName)) { exps.add(getFieldRawValue(f)); } } if (exps.size() == 0) { return null; } if (exps.size() == 1) { return exps.get(0); } return exps; } return null; case 1: return getFieldRawValue(fields.get(0)); default: List<Object> exps = new ArrayList<Object>(); for (Field f : fields) { exps.add(getFieldRawValue(f)); } return exps; } }
/** * Get the value of the named property, with support for static properties in both Java and Groovy * classes (which as of Groovy JSR 1.0 RC 01 only have getters in the metaClass) * * @param name * @param type * @return The property value or null */ public Object getPropertyValue(String name, Class type) { // Handle standard java beans normal or static properties BeanWrapper ref = getReference(); Object value = null; if (ref.isReadableProperty(name)) { value = ref.getPropertyValue(name); } else { // Groovy workaround Object inst = ref.getWrappedInstance(); if (inst instanceof GroovyObject) { final Map properties = DefaultGroovyMethods.getProperties(inst); if (properties.containsKey(name)) { value = properties.get(name); } } } if (value != null && (type.isAssignableFrom(value.getClass()) || GrailsClassUtils.isMatchBetweenPrimativeAndWrapperTypes(type, value.getClass()))) { return value; } else { return null; } }
public static MethodSignature[] allDefaultPersistentMethodSignatures() { Collection<MethodSignature> signatures = new ArrayList<MethodSignature>(); for (DefaultPersistentMethods method : DefaultPersistentMethods.values()) { signatures = DefaultGroovyMethods.plus(signatures, Arrays.asList(method.getMethodSignatures())); } return signatures.toArray(new MethodSignature[signatures.size()]); }
public static List list(NodeList self) { List answer = new ArrayList(); Iterator it = DefaultGroovyMethods.iterator(self); while (it.hasNext()) { answer.add(it.next()); } return answer; }
private String[] makeCommandLine(List<String> commandLineList) { final String[] commandLine = new String[commandLineList.size()]; for (int i = 0; i < commandLine.length; ++i) { commandLine[i] = commandLineList.get(i); } log.verbose("Compilation arguments:"); log.verbose(DefaultGroovyMethods.join(commandLine, "\n")); return commandLine; }
public TestFile leftShift(Object content) { getParentFile().mkdirs(); try { DefaultGroovyMethods.leftShift(this, content); return this; } catch (IOException e) { throw new RuntimeException(String.format("Could not append to test file '%s'", this), e); } }
/** This method exists to be binary compatible with 1.7 - 1.8.6 compiled code. */ @SuppressWarnings("Unchecked") public static Object checkImmutable(String className, String fieldName, Object field) { if (field == null || field instanceof Enum || inImmutableList(field.getClass().getName())) return field; if (field instanceof Collection) return DefaultGroovyMethods.asImmutable((Collection) field); if (field.getClass().getAnnotation(MY_CLASS) != null) return field; final String typeName = field.getClass().getName(); throw new RuntimeException(createErrorMessage(className, fieldName, typeName, "constructing")); }
private static String toString(NodeList self) { StringBuffer sb = new StringBuffer(); sb.append("["); Iterator it = DefaultGroovyMethods.iterator(self); while (it.hasNext()) { if (sb.length() > 1) sb.append(", "); sb.append(it.next().toString()); } sb.append("]"); return sb.toString(); }
@Override public void row( @DelegatesTo(RowCriterion.class) @ClosureParams( value = FromString.class, options = "org.modelcatalogue.spreadsheet.query.api.RowCriterion") Closure rowCriterion) { SimpleRowCriterion criterion = new SimpleRowCriterion(); DefaultGroovyMethods.with(criterion, rowCriterion); criteria.add(criterion); }
private void initSplashScreenProvider() { ClassLoader classLoader = ApplicationClassLoader.get(); try { URL url = classLoader.getResource("META-INF/services/" + SplashScreenProvider.class.getName()); String className = DefaultGroovyMethods.getText(url).trim(); splashScreenProvider = (SplashScreenProvider) classLoader.loadClass(className).newInstance(); } catch (Exception e) { splashScreenProvider = new DefaultSplashScreenProvider(); } }
private boolean renderObject(Object object, Writer out) { boolean renderView; try { out.write(DefaultGroovyMethods.inspect(object)); renderView = false; } catch (IOException e) { throw new ControllerExecutionException( "I/O error obtaining response writer: " + e.getMessage(), e); } return renderView; }
@SuppressWarnings("rawtypes") public List evaluateMappings(Resource resource) { InputStream inputStream = null; try { inputStream = resource.getInputStream(); return evaluateMappings(classLoader.parseClass(DefaultGroovyMethods.getText(inputStream))); } catch (IOException e) { throw new UrlMappingException( "Unable to read mapping file [" + resource.getFilename() + "]: " + e.getMessage(), e); } finally { IOUtils.closeQuietly(inputStream); } }
public String toString() { List buffer = new ArrayList(); if (this.years != 0) buffer.add(this.years + " years"); if (this.months != 0) buffer.add(this.months + " months"); if (this.days != 0) buffer.add(this.days + " days"); if (this.hours != 0) buffer.add(this.hours + " hours"); if (this.minutes != 0) buffer.add(this.minutes + " minutes"); if (this.seconds != 0 || this.millis != 0) buffer.add( (seconds == 0 ? (millis < 0 ? "-0" : "0") : seconds) + "." + DefaultGroovyMethods.padLeft("" + Math.abs(millis), 3, "0") + " seconds"); if (buffer.size() != 0) { return DefaultGroovyMethods.join(buffer, ", "); } else { return "0"; } }
@SuppressWarnings({"unchecked", "rawtypes"}) private int executeScriptWithCaching(CommandLine commandLine, String scriptName, String env) { List<File> potentialScripts; List<File> allScripts = getAvailableScripts(); GantBinding binding = new GantBinding(); binding.setVariable("scriptName", scriptName); setDefaultInputStream(binding); // Now find what scripts match the one requested by the user. potentialScripts = getPotentialScripts(scriptName, allScripts); if (potentialScripts.size() == 0) { try { File aliasFile = new File(settings.getUserHome(), ".grails/.aliases"); if (aliasFile.exists()) { Properties aliasProperties = new Properties(); aliasProperties.load(new FileReader(aliasFile)); if (aliasProperties.containsKey(commandLine.getCommandName())) { String aliasValue = (String) aliasProperties.get(commandLine.getCommandName()); String[] aliasPieces = aliasValue.split(" "); String commandName = aliasPieces[0]; String correspondingScriptName = GrailsNameUtils.getNameFromScript(commandName); potentialScripts = getPotentialScripts(correspondingScriptName, allScripts); if (potentialScripts.size() > 0) { String[] additionalArgs = new String[aliasPieces.length - 1]; System.arraycopy(aliasPieces, 1, additionalArgs, 0, additionalArgs.length); insertArgumentsInFrontOfExistingArguments(commandLine, additionalArgs); } } } } catch (Exception e) { console.error(e); } } // First try to load the script from its file. If there is no // file, then attempt to load it as a pre-compiled script. If // that fails, then let the user know and then exit. if (potentialScripts.size() > 0) { potentialScripts = (List) DefaultGroovyMethods.unique(potentialScripts); final File scriptFile = potentialScripts.get(0); if (!isGrailsProject() && !isExternalScript(scriptFile)) { return handleScriptExecutedOutsideProjectError(); } return executeScriptFile(commandLine, scriptName, env, binding, scriptFile); } return attemptPrecompiledScriptExecute(commandLine, scriptName, env, binding, allScripts); }
public static Location getAt(World self, List pos) { Object p0 = DefaultGroovyMethods.getAt(pos, 0); Object p1 = DefaultGroovyMethods.getAt(pos, 1); Object p2 = DefaultGroovyMethods.getAt(pos, 2); Double x = DefaultGroovyMethods.asType(p0, double.class); Double y = DefaultGroovyMethods.asType(p1, double.class); Double z = DefaultGroovyMethods.asType(p2, double.class); return new Location(self, x, y, z); }
@NotNull @Override protected UsageInfo[] findUsages() { final List<UsageInfo> result = new ArrayList<UsageInfo>(); for (GrMemberInfo info : myMembersToMove) { final PsiMember member = info.getMember(); if (member.hasModifierProperty(PsiModifier.STATIC)) { for (PsiReference reference : ReferencesSearch.search(member)) { result.add(new UsageInfo(reference)); } } } return DefaultGroovyMethods.asType(result, UsageInfo[].class); }
public Object invokeMethod(String name, Object args) { if (args != null && args.getClass().isArray()) { args = DefaultGroovyMethods.join((Object[]) args, ","); } // // FIXME: This kinda sucks as an output format, should probably ucase name and then // warp prefix in [] and then output the args. Basically what the SimpleLog // does in JCL. // System.out.println(prefix + name + "] " + args); return null; }
private static LoggingStrategy createLoggingStrategy( AnnotationNode logAnnotation, GroovyClassLoader loader) { String annotationName = logAnnotation.getClassNode().getName(); Class annotationClass; try { annotationClass = Class.forName(annotationName, false, loader); } catch (Throwable e) { throw new RuntimeException("Could not resolve class named " + annotationName); } Method annotationMethod; try { annotationMethod = annotationClass.getDeclaredMethod("loggingStrategy", (Class[]) null); } catch (Throwable e) { throw new RuntimeException( "Could not find method named loggingStrategy on class named " + annotationName); } Object defaultValue; try { defaultValue = annotationMethod.getDefaultValue(); } catch (Throwable e) { throw new RuntimeException( "Could not find default value of method named loggingStrategy on class named " + annotationName); } if (!LoggingStrategy.class.isAssignableFrom((Class) defaultValue)) { throw new RuntimeException( "Default loggingStrategy value on class named " + annotationName + " is not a LoggingStrategy"); } try { Class<? extends LoggingStrategy> strategyClass = (Class<? extends LoggingStrategy>) defaultValue; if (AbstractLoggingStrategy.class.isAssignableFrom(strategyClass)) { return DefaultGroovyMethods.newInstance(strategyClass, new Object[] {loader}); } else { return strategyClass.newInstance(); } } catch (Exception e) { return null; } }
@SuppressWarnings({"unchecked", "rawtypes"}) private int executeScriptWithCaching(CommandLine commandLine, String scriptName, String env) { List<Resource> potentialScripts; List<Resource> allScripts = getAvailableScripts(); GantBinding binding = new GantBinding(); binding.setVariable("scriptName", scriptName); setDefaultInputStream(binding); // Now find what scripts match the one requested by the user. boolean exactMatchFound = false; potentialScripts = new ArrayList<Resource>(); for (Resource scriptPath : allScripts) { String scriptFileName = scriptPath .getFilename() .substring(0, scriptPath.getFilename().length() - 7); // trim .groovy extension if (scriptFileName.endsWith("_")) { scriptsAllowedOutsideOfProject.add(scriptPath); scriptFileName = scriptFileName.substring(0, scriptFileName.length() - 1); } if (scriptFileName.equals(scriptName)) { potentialScripts.add(scriptPath); exactMatchFound = true; continue; } if (!exactMatchFound && ScriptNameResolver.resolvesTo(scriptName, scriptFileName)) { potentialScripts.add(scriptPath); } } // First try to load the script from its file. If there is no // file, then attempt to load it as a pre-compiled script. If // that fails, then let the user know and then exit. if (potentialScripts.size() > 0) { potentialScripts = (List) DefaultGroovyMethods.unique(potentialScripts); final Resource scriptFile = potentialScripts.get(0); if (!isGrailsProject() && !isExternalScript(scriptFile)) { return handleScriptExecutedOutsideProjectError(); } return executeScriptFile(commandLine, scriptName, env, binding, scriptFile); } return attemptPrecompiledScriptExecute(commandLine, scriptName, env, binding, allScripts); }
@SuppressWarnings("Unchecked") public static Object checkImmutable(Class<?> clazz, String fieldName, Object field) { Immutable immutable = (Immutable) clazz.getAnnotation(MY_CLASS); List<Class> knownImmutableClasses = new ArrayList<Class>(); if (immutable != null && immutable.knownImmutableClasses().length > 0) { knownImmutableClasses = Arrays.asList(immutable.knownImmutableClasses()); } if (field == null || field instanceof Enum || inImmutableList(field.getClass().getName()) || knownImmutableClasses.contains(field.getClass())) return field; if (field instanceof Collection) return DefaultGroovyMethods.asImmutable((Collection) field); if (field.getClass().getAnnotation(MY_CLASS) != null) return field; final String typeName = field.getClass().getName(); throw new RuntimeException( createErrorMessage(clazz.getName(), fieldName, typeName, "constructing")); }
@Override public <T> T getProperty(String key, Class<T> targetType, T defaultValue) { Object originalValue = configMap.get(key); if (originalValue == null && key.contains(".")) { originalValue = configMap.navigate(key.split("\\.")); if (originalValue != null) { try { configMap.put(key, originalValue); } catch (Exception e) { // ignore } } } if (originalValue != null) { T value = conversionService.convert(originalValue, targetType); return DefaultGroovyMethods.asBoolean(value) ? value : defaultValue; } return defaultValue; }
/** * This method overrides method invocation to create beans for each method name that takes a class * argument. */ public Object invokeMethod(String name, Object arg) { Object[] args = (Object[]) arg; if ("beans".equals(name) && args.length == 1 && args[0] instanceof Closure) { return beans((Closure) args[0]); } else if ("ref".equals(name)) { String refName; if (args[0] == null) throw new IllegalArgumentException( "Argument to ref() is not a valid bean or was not found"); if (args[0] instanceof RuntimeBeanReference) { refName = ((RuntimeBeanReference) args[0]).getBeanName(); } else { refName = args[0].toString(); } boolean parentRef = false; if (args.length > 1) { if (args[1] instanceof Boolean) { parentRef = (Boolean) args[1]; } } return new RuntimeBeanReference(refName, parentRef); } else if (this.namespaces.containsKey(name) && args.length > 0 && args[0] instanceof Closure) { GroovyDynamicElementReader reader = createDynamicElementReader(name); reader.invokeMethod("doCall", args); } else if (args.length > 0 && args[0] instanceof Closure) { // abstract bean definition return invokeBeanDefiningMethod(name, args); } else if (args.length > 0 && (args[0] instanceof Class || args[0] instanceof RuntimeBeanReference || args[0] instanceof Map)) { return invokeBeanDefiningMethod(name, args); } else if (args.length > 1 && args[args.length - 1] instanceof Closure) { return invokeBeanDefiningMethod(name, args); } MetaClass mc = DefaultGroovyMethods.getMetaClass(getRegistry()); if (!mc.respondsTo(getRegistry(), name, args).isEmpty()) { return mc.invokeMethod(getRegistry(), name, args); } return this; }
@SuppressWarnings("unchecked") public GroovyObject proxy(Map<Object, Object> map, Object... constructorArgs) { if (constructorArgs == null && cachedNoArgConstructor != null) { // if there isn't any argument, we can make invocation faster using the cached constructor try { return (GroovyObject) cachedNoArgConstructor.newInstance(map); } catch (InstantiationException e) { throw new GroovyRuntimeException(e); } catch (IllegalAccessException e) { throw new GroovyRuntimeException(e); } catch (InvocationTargetException e) { throw new GroovyRuntimeException(e); } } if (constructorArgs == null) constructorArgs = EMPTY_ARGS; Object[] values = new Object[constructorArgs.length + 1]; System.arraycopy(constructorArgs, 0, values, 0, constructorArgs.length); values[values.length - 1] = map; return DefaultGroovyMethods.<GroovyObject>newInstance(cachedClass, values); }
@Override public void doWithWebDescriptor(final Element webXml) { if (!pluginBean.isReadableProperty(DO_WITH_WEB_DESCRIPTOR)) { return; } final Closure c = (Closure) plugin.getProperty(DO_WITH_WEB_DESCRIPTOR); c.setResolveStrategy(Closure.DELEGATE_FIRST); c.setDelegate(this); DefaultGroovyMethods.use( this, DOMCategory.class, new Closure<Object>(this) { private static final long serialVersionUID = 1; @Override public Object call(Object... args) { return c.call(webXml); } }); }