Java Examples for org.codehaus.groovy.runtime.DefaultGroovyMethods

The following java examples will help you to understand the usage of org.codehaus.groovy.runtime.DefaultGroovyMethods. These source code samples are taken from different open source projects.

Example 1
Project: intellij-community-master  File: CustomMembersGenerator.java View source code
@SuppressWarnings("UnusedDeclaration")
@Nullable
public Object methodMissing(String name, Object args) {
    final Object[] newArgs = constructNewArgs((Object[]) args);
    // Get other DSL methods from extensions
    for (GdslMembersProvider provider : PROVIDERS) {
        final List<MetaMethod> variants = DefaultGroovyMethods.getMetaClass(provider).respondsTo(provider, name, newArgs);
        if (variants.size() == 1) {
            return InvokerHelper.invokeMethod(provider, name, newArgs);
        }
    }
    return null;
}
Example 2
Project: groovy-core-master  File: StaticTypeCheckingVisitor.java View source code
/**
     * A special method handling the "withTrait" call for which the type checker knows more than
     * what the type signature is able to tell. If "withTrait" is detected, then a new class node
     * is created representing the list of trait interfaces.
     *
     * @param directMethodCallCandidate a method selected by the type checker
     * @param receiver the receiver of the method call
     *@param args the arguments of the method call
     * @param returnType the original return type, as inferred by the type checker   @return fixed return type if the selected method is {@link org.codehaus.groovy.runtime.DefaultGroovyMethods#withTraits(Object, Class[]) withTraits}
     */
private ClassNode adjustWithTraits(final MethodNode directMethodCallCandidate, final ClassNode receiver, final ClassNode[] args, final ClassNode returnType) {
    if (directMethodCallCandidate instanceof ExtensionMethodNode) {
        ExtensionMethodNode emn = (ExtensionMethodNode) directMethodCallCandidate;
        if ("withTraits".equals(emn.getName()) && "DefaultGroovyMethods".equals(emn.getExtensionMethodNode().getDeclaringClass().getNameWithoutPackage())) {
            List<ClassNode> nodes = new LinkedList<ClassNode>();
            Collections.addAll(nodes, receiver.getInterfaces());
            for (ClassNode arg : args) {
                if (isClassClassNodeWrappingConcreteType(arg)) {
                    nodes.add(arg.getGenericsTypes()[0].getType());
                } else {
                    nodes.add(arg);
                }
            }
            return new LowestUpperBoundClassNode(returnType.getName() + "Composed", OBJECT_TYPE, nodes.toArray(new ClassNode[nodes.size()]));
        }
    }
    return returnType;
}
Example 3
Project: groovy-master  File: StaticTypeCheckingVisitor.java View source code
/**
     * A special method handling the "withTrait" call for which the type checker knows more than
     * what the type signature is able to tell. If "withTrait" is detected, then a new class node
     * is created representing the list of trait interfaces.
     *
     * @param directMethodCallCandidate a method selected by the type checker
     * @param receiver the receiver of the method call
     *@param args the arguments of the method call
     * @param returnType the original return type, as inferred by the type checker   @return fixed return type if the selected method is {@link org.codehaus.groovy.runtime.DefaultGroovyMethods#withTraits(Object, Class[]) withTraits}
     */
private static ClassNode adjustWithTraits(final MethodNode directMethodCallCandidate, final ClassNode receiver, final ClassNode[] args, final ClassNode returnType) {
    if (directMethodCallCandidate instanceof ExtensionMethodNode) {
        ExtensionMethodNode emn = (ExtensionMethodNode) directMethodCallCandidate;
        if ("withTraits".equals(emn.getName()) && "DefaultGroovyMethods".equals(emn.getExtensionMethodNode().getDeclaringClass().getNameWithoutPackage())) {
            List<ClassNode> nodes = new LinkedList<ClassNode>();
            Collections.addAll(nodes, receiver.getInterfaces());
            for (ClassNode arg : args) {
                if (isClassClassNodeWrappingConcreteType(arg)) {
                    nodes.add(arg.getGenericsTypes()[0].getType());
                } else {
                    nodes.add(arg);
                }
            }
            return new LowestUpperBoundClassNode(returnType.getName() + "Composed", OBJECT_TYPE, nodes.toArray(new ClassNode[nodes.size()]));
        }
    }
    return returnType;
}
Example 4
Project: discobot-master  File: MetaClassImpl.java View source code
private void connectMultimethods(List superClasses, CachedClass firstGroovyClass) {
    superClasses = DefaultGroovyMethods.reverse(superClasses);
    MetaMethodIndex.Header last = null;
    for (Iterator iter = superClasses.iterator(); iter.hasNext(); ) {
        CachedClass c = (CachedClass) iter.next();
        MetaMethodIndex.Header methodIndex = metaMethodIndex.getHeader(c.getTheClass());
        // It saves us a lot of space and some noticeable time
        if (last != null)
            metaMethodIndex.copyNonPrivateNonNewMetaMethods(last, methodIndex);
        last = methodIndex;
        if (c == firstGroovyClass)
            break;
    }
}
Example 5
Project: ratpack-master  File: CompiledTextTemplate.java View source code
void execute(Map<String, ?> model, ByteBuf buffer, NestedRenderer nestedRenderer) {
    @SuppressWarnings("unchecked") Map<String, Object> modelTyped = (Map<String, Object>) model;
    TextTemplateModel templateModel = new MapBackedTextTemplateModel(modelTyped);
    DefaultTextTemplateScript script = DefaultGroovyMethods.newInstance(templateClass, new Object[] { templateModel, buffer, nestedRenderer });
    try {
        script.run();
    } catch (Exception e) {
        if (e instanceof InvalidTemplateException) {
            throw (InvalidTemplateException) e;
        } else {
            throw new InvalidTemplateException(templateName, "template execution failed", e);
        }
    }
}
Example 6
Project: grails-core-master  File: BeanBuilder.java View source code
/**
     * Overrides method invocation to create beans for each method name that takes a class argument.
     */
@Override
public Object invokeMethod(String name, Object arg) {
    Object[] args = (Object[]) arg;
    if (CREATE_APPCTX.equals(name)) {
        return createApplicationContext();
    }
    if (REGISTER_BEANS.equals(name) && args.length == 1 && args[0] instanceof GenericApplicationContext) {
        registerBeans((GenericApplicationContext) args[0]);
        return null;
    }
    if (BEANS.equals(name) && args.length == 1 && args[0] instanceof Closure) {
        return beans((Closure<?>) args[0]);
    }
    if (REF.equals(name)) {
        String refName;
        Assert.notNull(args[0], "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);
    }
    if (namespaceHandlers.containsKey(name) && args.length > 0 && (args[0] instanceof Closure)) {
        createDynamicElementReader(name, true).invokeMethod("doCall", args);
        return this;
    }
    if (args.length > 0 && args[0] instanceof Closure) {
        // abstract bean definition
        return invokeBeanDefiningMethod(name, args);
    }
    if (args.length > 0 && args[0] instanceof Class || args.length > 0 && args[0] instanceof RuntimeBeanReference || args.length > 0 && args[0] instanceof Map) {
        return invokeBeanDefiningMethod(name, args);
    }
    if (args.length > 1 && args[args.length - 1] instanceof Closure) {
        return invokeBeanDefiningMethod(name, args);
    }
    ApplicationContext ctx = springConfig.getUnrefreshedApplicationContext();
    MetaClass mc = DefaultGroovyMethods.getMetaClass(ctx);
    if (!mc.respondsTo(ctx, name, args).isEmpty()) {
        return mc.invokeMethod(ctx, name, args);
    }
    return this;
}
Example 7
Project: grails-master  File: BeanBuilder.java View source code
/**
     * Overrides method invocation to create beans for each method name that takes a class argument.
     */
@Override
public Object invokeMethod(String name, Object arg) {
    Object[] args = (Object[]) arg;
    if (CREATE_APPCTX.equals(name)) {
        return createApplicationContext();
    }
    if (REGISTER_BEANS.equals(name) && args.length == 1 && args[0] instanceof GenericApplicationContext) {
        registerBeans((GenericApplicationContext) args[0]);
        return null;
    }
    if (BEANS.equals(name) && args.length == 1 && args[0] instanceof Closure) {
        return beans((Closure<?>) args[0]);
    }
    if (REF.equals(name)) {
        String refName;
        Assert.notNull(args[0], "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);
    }
    if (namespaceHandlers.containsKey(name) && args.length > 0 && (args[0] instanceof Closure)) {
        createDynamicElementReader(name, true).invokeMethod("doCall", args);
        return this;
    }
    if (args.length > 0 && args[0] instanceof Closure) {
        // abstract bean definition
        return invokeBeanDefiningMethod(name, args);
    }
    if (args.length > 0 && args[0] instanceof Class || args.length > 0 && args[0] instanceof RuntimeBeanReference || args.length > 0 && args[0] instanceof Map) {
        return invokeBeanDefiningMethod(name, args);
    }
    if (args.length > 1 && args[args.length - 1] instanceof Closure) {
        return invokeBeanDefiningMethod(name, args);
    }
    ApplicationContext ctx = springConfig.getUnrefreshedApplicationContext();
    MetaClass mc = DefaultGroovyMethods.getMetaClass(ctx);
    if (!mc.respondsTo(ctx, name, args).isEmpty()) {
        return mc.invokeMethod(ctx, name, args);
    }
    return this;
}
Example 8
Project: groovy-eclipse-master  File: StaticTypeCheckingSupport.java View source code
/**
         * Returns a map which contains, as the key, the name of a class. The value
         * consists of a list of MethodNode, one for each default groovy method found
         * which is applicable for this class.
         * @return
         * @param modules
         */
private static Map<String, List<MethodNode>> getDGMMethods(List<ExtensionModule> modules) {
    Set<Class> instanceExtClasses = new LinkedHashSet<Class>();
    Set<Class> staticExtClasses = new LinkedHashSet<Class>();
    for (ExtensionModule module : modules) {
        if (module instanceof MetaInfExtensionModule) {
            MetaInfExtensionModule extensionModule = (MetaInfExtensionModule) module;
            instanceExtClasses.addAll(extensionModule.getInstanceMethodsExtensionClasses());
            staticExtClasses.addAll(extensionModule.getStaticMethodsExtensionClasses());
        }
    }
    Map<String, List<MethodNode>> methods = new HashMap<String, List<MethodNode>>();
    Collections.addAll(instanceExtClasses, DefaultGroovyMethods.DGM_LIKE_CLASSES);
    Collections.addAll(instanceExtClasses, DefaultGroovyMethods.additionals);
    staticExtClasses.add(DefaultGroovyStaticMethods.class);
    instanceExtClasses.add(ObjectArrayStaticTypesHelper.class);
    scanClassesForDGMMethods(methods, staticExtClasses, true);
    scanClassesForDGMMethods(methods, instanceExtClasses, false);
    return methods;
}
Example 9
Project: tspec-master  File: Scenario.java View source code
public void run() {
    System.out.println(name);
    if (given != null && given.getBody() != null) {
        given.getBody().setDelegate(this);
        given.getBody().setResolveStrategy(Closure.DELEGATE_FIRST);
        given.getBody().call();
        System.out.print("    �ำหนดให้ " + given.getName());
    } else {
        System.out.println("    ไม่มี�ารระบุประโยค '�ำหนดให้'");
    }
    if (when != null && when.getBody() != null) {
        when.getBody().setDelegate(this);
        when.getBody().setResolveStrategy(Closure.DELEGATE_FIRST);
        when.getBody().call();
        System.out.println(" �ละเมื่อ" + when.getName());
    } else {
        System.out.println("    ไม่มี�ารระบุประโยค 'เมื่อ'");
    }
    if (thenClauses.size() > 0) {
        for (final Then then : thenClauses) {
            if (then.getBody() != null) {
                then.init(this);
                then.getBody().setDelegate(this);
                then.getBody().setResolveStrategy(Closure.DELEGATE_FIRST);
                DefaultGroovyMethods.use(this, ShouldCategory.class, then.getBody());
                System.out.print("    " + then.getLabel() + then.getName());
                System.out.println(" / ผ่าน");
            } else {
                System.out.print("    " + then.getLabel() + then.getName());
                System.out.println(" / ไม่ผ่าน");
            }
        }
    }
    System.out.println("จบ สถาน�ารณ์");
}
Example 10
Project: dumpling-master  File: GroovyInterpretterConfig.java View source code
/**
     * Decorate Dumpling API with groovy extensions.
     */
public void setupDecorateMethods(ClassLoader cl) {
    synchronized (STAR_IMPORTS) {
        if (DECORATED)
            return;
        GroovyShell shell = new GroovyShell(cl, new Binding(), getCompilerConfiguration());
        try {
            shell.run("import org.codehaus.groovy.runtime.DefaultGroovyMethods;" + "def mc = ThreadSet.metaClass;" + "mc.asImmutable << { -> delegate };" + "mc.toSet << { -> delegate };" + "mc.grep << { Object filter -> delegate.derive(DefaultGroovyMethods.grep(delegate.threadsAsSet, filter)) };" + "mc.grep << { -> delegate.derive(delegate.threadsAsSet.grep()) };" + "mc.findAll << { Closure closure -> delegate.derive(DefaultGroovyMethods.findAll((Object) delegate.threadsAsSet, closure)) };" + "mc.findAll << { -> delegate.derive(delegate.threadsAsSet.findAll()) };" + "mc.intersect << { rhs -> if (!delegate.getProcessRuntime().equals(rhs.getProcessRuntime())) throw new IllegalArgumentException('Unable to intersect ThreadSets bound to different ProcessRuntimes'); return delegate.derive(DefaultGroovyMethods.intersect(delegate.threadsAsSet, rhs.threadsAsSet)) };" + "mc.plus << { rhs -> if (!delegate.getProcessRuntime().equals(rhs.getProcessRuntime())) throw new IllegalArgumentException('Unable to merge ThreadSets bound to different ProcessRuntimes'); return delegate.derive(DefaultGroovyMethods.plus(delegate.threadsAsSet, rhs.threadsAsSet)) };", "dumpling-metaclass-setup", Arrays.asList());
        } catch (Exception ex) {
            AssertionError err = new AssertionError("Unable to decorate object model");
            err.initCause(ex);
            throw err;
        }
        DECORATED = true;
    }
}
Example 11
Project: gradle-jnaerator-plugin-master  File: JNAeratorTask.java View source code
@TaskAction
public void run() {
    List<String> args = new ArrayList<String>();
    args.add(JNAeratorCommandLineArgs.OptionDef.CurrentLibrary.clSwitch);
    args.add(getLibraryName());
    args.add(JNAeratorCommandLineArgs.OptionDef.CurrentPackage.clSwitch);
    args.add(getPackageName());
    for (File file : getHeaderFiles()) args.add(file.getAbsolutePath());
    args.add(JNAeratorCommandLineArgs.OptionDef.OutputMode.clSwitch);
    args.add(JNAeratorConfig.OutputMode.Directory.name());
    args.add(JNAeratorCommandLineArgs.OptionDef.Runtime.clSwitch);
    args.add(getRuntimeMode().name());
    args.add(JNAeratorCommandLineArgs.OptionDef.OutputDir.clSwitch);
    // String outputPath = getPackageName().replace('.', File.separatorChar);
    // File outputDir = new File(getOutputDir(), outputPath);
    args.add(getOutputDir().getAbsolutePath());
    args.add(JNAeratorCommandLineArgs.OptionDef.ForceOverwrite.clSwitch);
    // args.add(JNAeratorCommandLineArgs.OptionDef.Verbose.clSwitch);
    args.add("-v");
    for (String d : define) args.add("-D" + d);
    for (String u : undefine) args.add("-U" + u);
    args.addAll(getExtraArgs());
    DefaultGroovyMethods.deleteDir(outputDir);
    outputDir.mkdirs();
    getLogger().info("Invoking jnaerator " + args);
    JNAerator.main(args.toArray(new String[args.size()]));
}
Example 12
Project: gradle-master  File: CompositeFileTreeTest.java View source code
@Test
public void visitsEachTreeWithClosure() {
    final Closure visitor = TestUtil.TEST_CLOSURE;
    final FileVisitor closureAsVisitor = DefaultGroovyMethods.asType(visitor, FileVisitor.class);
    context.checking(new Expectations() {

        {
            oneOf(source1).visit(closureAsVisitor);
            oneOf(source2).visit(closureAsVisitor);
        }
    });
    tree.visit(visitor);
}
Example 13
Project: gradle-velocity-plugin-master  File: VelocityTask.java View source code
@Override
public void visitFile(FileVisitDetails fvd) {
    try {
        File outputFile = fvd.getRelativePath().getFile(outputDir);
        if (getLogger().isDebugEnabled())
            getLogger().debug("Preprocessing " + fvd.getFile() + " -> " + outputFile);
        VelocityContext context = new VelocityContext();
        Map<String, Object> contextValues = getContextValues();
        if (contextValues != null)
            for (Map.Entry<String, Object> e : contextValues.entrySet()) context.put(e.getKey(), e.getValue());
        context.put("project", getProject());
        context.put("package", DefaultGroovyMethods.join(fvd.getRelativePath().getParent().getSegments(), "."));
        context.put("class", fvd.getRelativePath().getLastName().replaceFirst("\\.java$", ""));
        FileReader reader = new FileReader(fvd.getFile());
        try {
            outputFile.getParentFile().mkdirs();
            FileWriter writer = new FileWriter(outputFile);
            try {
                engine.evaluate(context, writer, fvd.getRelativePath().toString(), reader);
            } finally {
                writer.close();
            }
        } finally {
            reader.close();
        }
    } catch (IOException e) {
        throw new GradleException("Failed to process " + fvd, e);
    }
}
Example 14
Project: intellij-plugins-master  File: CustomWorldContributor.java View source code
@Nullable
private static GrClosableBlock getClosureArg(@NotNull GrMethodCall methodCall) {
    final GrClosableBlock[] closures = methodCall.getClosureArguments();
    if (closures.length == 1)
        return closures[0];
    if (closures.length > 1)
        return null;
    final GrExpression[] args = methodCall.getExpressionArguments();
    if (args.length == 0)
        return null;
    final GrExpression last = DefaultGroovyMethods.last(args);
    if (last instanceof GrClosableBlock) {
        return (GrClosableBlock) last;
    }
    return null;
}
Example 15
Project: remote-control-master  File: ClosureCommandGenerator.java View source code
/**
     * Gets the class definition bytes for the given closure class.
     */
protected byte[] getClassBytes(final Class<? extends Closure> closureClass) {
    String classFileName = getClassFileName(closureClass);
    URL classFileResource = classLoader.getResource(classFileName);
    if (classFileResource == null) {
        throw new IllegalStateException("Could not find class file for class " + String.valueOf(closureClass));
    }
    try {
        return DefaultGroovyMethods.getBytes(classFileResource);
    } catch (IOException e) {
        throw new UnexpectedIOException("reading class files", e);
    }
}
Example 16
Project: Pipeline-master  File: SerializationTest.java View source code
@Override
public void evaluate() throws Throwable {
    // TODO pending https://github.com/jenkinsci/script-security-plugin/pull/96
    ScriptApproval.get().approveSignature("staticMethod org.codehaus.groovy.runtime.DefaultGroovyMethods plus java.util.List java.lang.Object");
    p = jenkins().createProject(WorkflowJob.class, "demo");
    p.setDefinition(new CpsFlowDefinition("def arr = []; arr += 'one'; arr += 'two'\n" + "for (int i = 0; i < arr.size(); i++) {def elt = arr[i]; echo \"running C-style loop on ${elt}\"; semaphore \"C-${elt}\"}\n" + "for (def elt : arr) {echo \"running new-style loop on ${elt}\"; semaphore \"new-${elt}\"}", true));
    startBuilding();
    SemaphoreStep.waitForStart("C-one/1", b);
    story.j.waitForMessage("running C-style loop on one", b);
}
Example 17
Project: ADRApp-master  File: GroovySupport.java View source code
/**
   * Mix all the static methods of the given class into their
   * respective types.
   * @param classToMix a category class.
   */
protected void mixinGlobally(Class<?> classToMix) {
    // find the set of types into which it needs to be mixed.
    // this means the types of the first argument of each
    // static method in the class.
    Set<Class<?>> typesToMixInto = new HashSet<Class<?>>();
    for (Method method : classToMix.getMethods()) {
        if (Modifier.isStatic(method.getModifiers()) && method.getDeclaringClass() == classToMix && method.getParameterTypes().length > 0) {
            typesToMixInto.add(method.getParameterTypes()[0]);
        }
    }
    for (Class<?> clazz : typesToMixInto) {
        DefaultGroovyMethods.mixin(clazz, classToMix);
    }
}
Example 18
Project: GATEinSpring-master  File: GroovySupport.java View source code
/**
   * Mix all the static methods of the given class into their
   * respective types.
   * @param classToMix a category class.
   */
protected void mixinGlobally(Class<?> classToMix) {
    // find the set of types into which it needs to be mixed.
    // this means the types of the first argument of each
    // static method in the class.
    Set<Class<?>> typesToMixInto = new HashSet<Class<?>>();
    for (Method method : classToMix.getMethods()) {
        if (Modifier.isStatic(method.getModifiers()) && method.getDeclaringClass() == classToMix && method.getParameterTypes().length > 0) {
            typesToMixInto.add(method.getParameterTypes()[0]);
        }
    }
    for (Class<?> clazz : typesToMixInto) {
        DefaultGroovyMethods.mixin(clazz, classToMix);
    }
}
Example 19
Project: griffon-master  File: Xml2Groovy.java View source code
private void walkXml(IndentPrinter printer, NodeChild node) {
    printer.printIndent();
    printer.print(node.name());
    if (!node.attributes().isEmpty()) {
        printer.print("(");
        List<String> attrs = new ArrayList<>();
        for (Object o : node.attributes().entrySet()) {
            Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o;
            attrs.add(entry.getKey() + ": " + entry.getValue());
        }
        printer.print(DefaultGroovyMethods.join((Iterable) attrs, ", "));
        printer.print(")");
    }
    if (node.children().size() > 0) {
        printer.println(" {");
        printer.incrementIndent();
        for (Iterator<?> iter = node.childNodes(); iter.hasNext(); ) {
            Object child = iter.next();
            if (child instanceof NodeChild) {
                walkXml(printer, (NodeChild) child);
            } else if (child instanceof Node) {
                walkXml(printer, (Node) child);
            }
        }
        printer.decrementIndent();
        printer.printIndent();
        printer.println("}");
    } else if (!node.attributes().isEmpty()) {
        printer.println("");
    } else {
        printer.println("()");
    }
}
Example 20
Project: groovypp-master  File: BinaryExpressionTransformer.java View source code
public void compile(MethodVisitor mv) {
    l1.visit(mv);
    box(l1.getType(), mv);
    cast(TypeUtil.wrapSafely(l1.getType()), TypeUtil.wrapSafely(mathType), mv);
    if (ClassHelper.isPrimitiveType(mathType))
        unbox(mathType, mv);
    r1.visit(mv);
    box(r1.getType(), mv);
    cast(TypeUtil.wrapSafely(r1.getType()), TypeUtil.wrapSafely(mathType), mv);
    if (ClassHelper.isPrimitiveType(mathType))
        unbox(mathType, mv);
    if (mathType == ClassHelper.int_TYPE) {
        switch(op) {
            case Types.COMPARE_EQUAL:
                mv.visitJumpInsn(onTrue ? IF_ICMPEQ : IF_ICMPNE, label);
                break;
            case Types.COMPARE_NOT_EQUAL:
                mv.visitJumpInsn(onTrue ? IF_ICMPNE : IF_ICMPEQ, label);
                break;
            case Types.COMPARE_LESS_THAN:
                mv.visitJumpInsn(onTrue ? IF_ICMPLT : IF_ICMPGE, label);
                break;
            case Types.COMPARE_LESS_THAN_EQUAL:
                mv.visitJumpInsn(onTrue ? IF_ICMPLE : IF_ICMPGT, label);
                break;
            case Types.COMPARE_GREATER_THAN:
                mv.visitJumpInsn(onTrue ? IF_ICMPGT : IF_ICMPLE, label);
                break;
            case Types.COMPARE_GREATER_THAN_EQUAL:
                mv.visitJumpInsn(onTrue ? IF_ICMPGE : IF_ICMPLT, label);
                break;
            default:
                throw new IllegalStateException();
        }
    } else if (mathType == ClassHelper.double_TYPE) {
        mv.visitMethodInsn(INVOKESTATIC, "java/lang/Double", "compare", "(DD)I");
        intCmp(op, onTrue, mv, label);
    } else if (mathType == ClassHelper.long_TYPE) {
        mv.visitInsn(LCMP);
        intCmp(op, onTrue, mv, label);
    } else if (mathType == ClassHelper.BigInteger_TYPE) {
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/math/BigInteger", "compareTo", "(Ljava/math/BigInteger;)I");
        intCmp(op, onTrue, mv, label);
    } else if (mathType == ClassHelper.BigDecimal_TYPE) {
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/math/BigDecimal", "compareTo", "(Ljava/math/BigDecimal;)I");
        intCmp(op, onTrue, mv, label);
    } else {
        mv.visitMethodInsn(INVOKESTATIC, "org/codehaus/groovy/runtime/DefaultGroovyMethods", "compareTo", "(Ljava/lang/Number;Ljava/lang/Number;)I");
        intCmp(op, onTrue, mv, label);
    }
}
Example 21
Project: moxie-master  File: GroovyEngine.java View source code
private void prepareGroovyScript(MxGroovy task, String txt) throws IOException {
    String[] args = task.getCommandLine().getCommandline();
    // Temporary file - delete on exit, create (assured unique name).
    File tempFile = FileUtils.getFileUtils().createTempFile(PREFIX, SUFFIX, null, true, true);
    String[] commandline = new String[args.length + 1];
    DefaultGroovyMethods.write(tempFile, txt);
    commandline[0] = tempFile.getCanonicalPath();
    System.arraycopy(args, 0, commandline, 1, args.length);
    task.clearArgs();
    for (String arg : commandline) {
        Commandline.Argument argument = task.createArg();
        argument.setValue(arg);
    }
}
Example 22
Project: json-parsers-benchmark-master  File: MyJsonOutput.java View source code
/**
     * Simply rewritten to Java with minor changes.
     */
public static String toJson(Object object) {
    if (object == null) {
        return JsonBlock.NULL.symbol;
    } else if (object instanceof GString) {
        return new StringBuilder().append(JsonBlock.DQUOTE.symbol).append(StringEscapeUtils.escapeJava(((GString) object).toString())).append(JsonBlock.DQUOTE.symbol).toString();
    } else if (object instanceof String) {
        return new StringBuilder().append(JsonBlock.DQUOTE.symbol).append(StringEscapeUtils.escapeJava((String) object)).append(JsonBlock.DQUOTE.symbol).toString();
    } else if (object instanceof java.lang.Boolean) {
        return object.toString();
    } else if (object instanceof Number) {
        if ((object.getClass() == Double.class && (((Double) object).isInfinite() || ((Double) object).isNaN())) || (object.getClass() == Float.class && (((Float) object).isInfinite() || ((Float) object).isNaN()))) {
            throw new JsonException("Number " + object + " can't be serialized as JSON: infinite or NaN are not allowed in JSON.");
        }
        return object.toString();
    } else if (object instanceof Date) {
        return new StringBuilder().append(JsonBlock.DQUOTE.symbol).append(dateFormatter.get().format(object)).append(JsonBlock.DQUOTE.symbol).toString();
    } else if (object instanceof Calendar) {
        return new StringBuilder().append(JsonBlock.DQUOTE.symbol).append(dateFormatter.get().format(((Calendar) object).getTime())).append(JsonBlock.DQUOTE.symbol).toString();
    } else if (object instanceof Collection) {
        Collection<?> collection = (Collection<?>) object;
        StringBuilder sb = new StringBuilder(JsonBlock.START_LIST.symbol);
        Iterator<?> iterator = collection.iterator();
        if (iterator.hasNext()) {
            Object it = iterator.next();
            sb.append(toJson(it));
            while (iterator.hasNext()) {
                it = iterator.next();
                sb.append(JsonBlock.COMMA.symbol);
                sb.append(toJson(it));
            }
        }
        sb.append(JsonBlock.END_LIST.symbol);
        return sb.toString();
    } else if (object instanceof Iterator) {
        Iterator<?> iterator = (Iterator<?>) object;
        StringBuilder sb = new StringBuilder(JsonBlock.START_LIST.symbol);
        if (iterator.hasNext()) {
            Object it = iterator.next();
            sb.append(toJson(it));
            while (iterator.hasNext()) {
                it = iterator.next();
                sb.append(JsonBlock.COMMA.symbol);
                sb.append(toJson(it));
            }
        }
        sb.append(JsonBlock.END_LIST.symbol);
        return sb.toString();
    } else if (object instanceof Map) {
        StringBuilder sb = new StringBuilder(JsonBlock.START_OBJECT.symbol);
        Map<?, ?> m = (Map<?, ?>) object;
        if (!m.isEmpty()) {
            boolean firstItem = true;
            for (Entry<?, ?> entry : m.entrySet()) {
                if (entry.getKey() == null) {
                    throw new IllegalArgumentException("Maps with null keys can\'t be converted to JSON");
                }
                if (!firstItem) {
                    sb.append(JsonBlock.COMMA.symbol);
                } else {
                    firstItem = false;
                }
                sb.append(JsonBlock.DQUOTE.symbol).append(entry.getKey().toString()).append(JsonBlock.DQUOTE.symbol).append(JsonBlock.COLON.symbol).append(toJson(entry.getValue()));
            }
        } else {
            sb.append(JsonBlock.COLON.symbol);
        }
        return sb.append(JsonBlock.END_OBJECT.symbol).toString();
    } else if (object instanceof URL || object instanceof UUID || object instanceof Character) {
        return new StringBuilder().append(JsonBlock.DQUOTE.symbol).append(object.toString()).append(JsonBlock.DQUOTE.symbol).toString();
    } else if (object instanceof Closure) {
        return toJson(JsonDelegate.cloneDelegateAndGetContent((Closure<?>) object));
    } else if (object instanceof Expando) {
        return toJson(((Expando) object).getProperties());
    } else if (object instanceof Enumeration) {
        Enumeration<?> enumeration = (Enumeration<?>) object;
        StringBuilder sb = new StringBuilder().append(JsonBlock.START_LIST.symbol);
        if (enumeration.hasMoreElements()) {
            Object it = enumeration.nextElement();
            sb.append(toJson(it));
            while (enumeration.hasMoreElements()) {
                it = enumeration.nextElement();
                sb.append(JsonBlock.COMMA.symbol);
                sb.append(toJson(it));
            }
        }
        sb.append(JsonBlock.END_LIST.symbol);
        return sb.toString();
    } else if (object.getClass().isArray()) {
        StringBuilder sb = new StringBuilder().append(JsonBlock.START_LIST.symbol);
        boolean firstItem = true;
        if (object instanceof Object[]) {
            Object[] arr = (Object[]) object;
            for (Object it : arr) {
                if (!firstItem) {
                    sb.append(JsonBlock.COMMA.symbol);
                } else {
                    firstItem = false;
                }
                sb.append(toJson(it));
            }
        } else if (object instanceof byte[]) {
            byte[] arr = (byte[]) object;
            for (byte it : arr) {
                if (!firstItem) {
                    sb.append(JsonBlock.COMMA.symbol);
                } else {
                    firstItem = false;
                }
                sb.append(it);
            }
        } else if (object instanceof char[]) {
            char[] arr = (char[]) object;
            for (char it : arr) {
                if (!firstItem) {
                    sb.append(JsonBlock.COMMA.symbol);
                } else {
                    firstItem = false;
                }
                sb.append(JsonBlock.DQUOTE.symbol).append(it).append(JsonBlock.DQUOTE.symbol);
            }
        } else if (object instanceof boolean[]) {
            boolean[] arr = (boolean[]) object;
            for (boolean it : arr) {
                if (!firstItem) {
                    sb.append(JsonBlock.COMMA.symbol);
                } else {
                    firstItem = false;
                }
                sb.append(Boolean.toString(it));
            }
        } else if (object instanceof int[]) {
            int[] arr = (int[]) object;
            for (int it : arr) {
                if (!firstItem) {
                    sb.append(JsonBlock.COMMA.symbol);
                } else {
                    firstItem = false;
                }
                sb.append(it);
            }
        } else if (object instanceof long[]) {
            long[] arr = (long[]) object;
            for (long it : arr) {
                if (!firstItem) {
                    sb.append(JsonBlock.COMMA.symbol);
                } else {
                    firstItem = false;
                }
                sb.append(it);
            }
        } else if (object instanceof double[]) {
            double[] arr = (double[]) object;
            for (double it : arr) {
                if (!firstItem) {
                    sb.append(JsonBlock.COMMA.symbol);
                } else {
                    firstItem = false;
                }
                sb.append(it);
            }
        } else if (object instanceof float[]) {
            float[] arr = (float[]) object;
            for (float it : arr) {
                if (!firstItem) {
                    sb.append(JsonBlock.COMMA.symbol);
                } else {
                    firstItem = false;
                }
                sb.append(it);
            }
        }
        sb.append(JsonBlock.END_LIST.symbol);
        return sb.toString();
    } else if (object instanceof Enum) {
        return new StringBuilder().append(JsonBlock.DQUOTE.symbol).append(((Enum<?>) object).name()).append(JsonBlock.DQUOTE.symbol).toString();
    } else {
        Map<?, ?> properties = DefaultGroovyMethods.getProperties(object);
        properties.remove("class");
        properties.remove("declaringClass");
        properties.remove("metaClass");
        return toJson(properties);
    }
}
Example 23
Project: atlas-master  File: AtlasConfigurationHelper.java View source code
public void createBuilderAfterEvaluate() throws Exception {
    AndroidBuilder androidBuilder = appPluginHook.getAndroidBuilder();
    if (null == androidBuilder) {
        return;
    }
    AndroidBuilder atlasBuilder = new AtlasBuilder(project.equals(project.getRootProject()) ? project.getName() : project.getPath(), creator, new GradleProcessExecutor(project), new GradleJavaProcessExecutor(project), DefaultGroovyMethods.asType(ReflectUtils.getField(androidBuilder, "mErrorReporter"), ErrorReporter.class), LoggerWrapper.getLogger(AtlasBuilder.class), DefaultGroovyMethods.asType(ReflectUtils.getField(androidBuilder, "mVerboseExec"), Boolean.class));
    ((AtlasBuilder) atlasBuilder).setDefaultBuilder(androidBuilder);
    ((AtlasBuilder) atlasBuilder).setAtlasExtension(atlasExtension);
    AtlasBuildContext.androidBuilderMap.put(project, (AtlasBuilder) (atlasBuilder));
}
Example 24
Project: Dogmatic-mvc-master  File: GroovyScriptEngine.java View source code
/**
     * Get the class of the scriptName in question, so that you can instantiate
     * Groovy objects with caching and reloading.
     *
     * @param scriptName resource name pointing to the script
     * @return the loaded scriptName as a compiled class
     * @throws ResourceException if there is a problem accessing the script
     * @throws groovy.util.ScriptException if there is a problem parsing the script
     */
public Class loadScriptByName(String scriptName) throws ResourceException, ScriptException {
    URLConnection conn = rc.getResourceConnection(scriptName);
    String path = conn.getURL().getPath();
    ScriptCacheEntry entry = scriptCache.get(path);
    Class clazz = null;
    if (entry != null)
        clazz = entry.scriptClass;
    if (isSourceNewer(entry)) {
        try {
            String encoding = conn.getContentEncoding() != null ? conn.getContentEncoding() : "UTF-8";
            clazz = groovyLoader.parseClass(DefaultGroovyMethods.getText(conn.getInputStream(), encoding), conn.getURL().getPath());
        } catch (IOException e) {
            throw new ResourceException(e);
        }
    }
    return clazz;
}
Example 25
Project: gcontracts-master  File: ContractGroovyDoc.java View source code
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);
    if (classTemplates.size() == 0)
        throw new BuildException("Method getClassTemplates() needs to return at least a single classTemplate String!");
    GroovyDocTool htmlTool = new GroovyDocTool(createResourceManager(), sourcePath.list(), getDocTemplates(), getPackageTemplates(), getClassTemplates(), links, properties);
    try {
        htmlTool.add(sourceFilesToDoc);
        FileOutputTool output = new FileOutputTool();
        // TODO push destDir through APIs?
        htmlTool.renderToOutput(output, destDir.getCanonicalPath());
    } 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());
        }
    }
}
Example 26
Project: httpbuilder-master  File: HTTPBuilder.java View source code
/**
     * <p>This is the default <code>response.success</code> handler.  It will be
     * executed if the response is not handled by a status-code-specific handler
     * (i.e. <code>response.'200'= {..}</code>) and no generic 'success' handler
     * is given (i.e. <code>response.success = {..}</code>.)  This handler simply
     * returns the parsed data from the response body.  In most cases you will
     * probably want to define a <code>response.success = {...}</code> handler
     * from the request closure, which will replace the response handler defined
     * by this method.  </p>
     *
     * <h4>Note for parsers that return streaming content:</h4>
     * <p>For responses parsed as {@link ParserRegistry#parseStream(HttpResponse)
     * BINARY} or {@link ParserRegistry#parseText(HttpResponse) TEXT}, the
     * parser will return streaming content -- an <code>InputStream</code> or
     * <code>Reader</code>.  In these cases, this handler will buffer the the
     * response content before the network connection is closed.  </p>
     *
     * <p>In practice, a user-supplied response handler closure is
     * <i>designed</i> to handle streaming content so it can be read directly from
     * the response stream without buffering, which will be much more efficient.
     * Therefore, it is recommended that request method variants be used which
     * explicitly accept a response handler closure in these cases.</p>
     *
     * @param resp HTTP response
     * @param parsedData parsed data as resolved from this instance's {@link ParserRegistry}
     * @return the parsed data object (whatever the parser returns).
     * @throws ResponseParseException if there is an error buffering a streaming
     *   response.
     */
protected Object defaultSuccessHandler(HttpResponseDecorator resp, Object parsedData) throws ResponseParseException {
    try {
        //If response is streaming, buffer it in a byte array:
        if (parsedData instanceof InputStream) {
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            DefaultGroovyMethods.leftShift(buffer, (InputStream) parsedData);
            parsedData = new ByteArrayInputStream(buffer.toByteArray());
        } else if (parsedData instanceof Reader) {
            StringWriter buffer = new StringWriter();
            DefaultGroovyMethods.leftShift(buffer, (Reader) parsedData);
            parsedData = new StringReader(buffer.toString());
        } else if (parsedData instanceof Closeable)
            log.warn("Parsed data is streaming, but will be accessible after " + "the network connection is closed.  Use at your own risk!");
        return parsedData;
    } catch (IOException ex) {
        throw new ResponseParseException(resp, ex);
    }
}
Example 27
Project: hudson-2.x-master  File: BeanBuilder.java View source code
/**
	 * This method is invoked by Groovy when a method that's not defined in Java is invoked.
     * We use that as a syntax for bean definition. 
	 */
public Object methodMissing(String name, Object arg) {
    Object[] args = (Object[]) arg;
    if (args.length == 0)
        throw new MissingMethodException(name, getClass(), args);
    if (args[0] instanceof Closure) {
        // abstract bean definition
        return invokeBeanDefiningMethod(name, args);
    } else if (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);
    }
    WebApplicationContext ctx = springConfig.getUnrefreshedApplicationContext();
    MetaClass mc = DefaultGroovyMethods.getMetaClass(ctx);
    if (!mc.respondsTo(ctx, name, args).isEmpty()) {
        return mc.invokeMethod(ctx, name, args);
    }
    return this;
}
Example 28
Project: hudson-main-master  File: BeanBuilder.java View source code
/**
	 * This method is invoked by Groovy when a method that's not defined in Java is invoked.
     * We use that as a syntax for bean definition. 
	 */
public Object methodMissing(String name, Object arg) {
    Object[] args = (Object[]) arg;
    if (args.length == 0)
        throw new MissingMethodException(name, getClass(), args);
    if (args[0] instanceof Closure) {
        // abstract bean definition
        return invokeBeanDefiningMethod(name, args);
    } else if (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);
    }
    WebApplicationContext ctx = springConfig.getUnrefreshedApplicationContext();
    MetaClass mc = DefaultGroovyMethods.getMetaClass(ctx);
    if (!mc.respondsTo(ctx, name, args).isEmpty()) {
        return mc.invokeMethod(ctx, name, args);
    }
    return this;
}
Example 29
Project: jenkins-master  File: BeanBuilder.java View source code
/**
	 * This method is invoked by Groovy when a method that's not defined in Java is invoked.
     * We use that as a syntax for bean definition. 
	 */
public Object methodMissing(String name, Object arg) {
    Object[] args = (Object[]) arg;
    if (args.length == 0)
        throw new MissingMethodException(name, getClass(), args);
    if (args[0] instanceof Closure) {
        // abstract bean definition
        return invokeBeanDefiningMethod(name, args);
    } else if (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);
    }
    WebApplicationContext ctx = springConfig.getUnrefreshedApplicationContext();
    MetaClass mc = DefaultGroovyMethods.getMetaClass(ctx);
    if (!mc.respondsTo(ctx, name, args).isEmpty()) {
        return mc.invokeMethod(ctx, name, args);
    }
    return this;
}
Example 30
Project: rest-assured-master  File: HTTPBuilder.java View source code
/**
     * <p>This is the default <code>response.success</code> handler.  It will be
     * executed if the response is not handled by a status-code-specific handler
     * (i.e. <code>response.'200'= {..}</code>) and no generic 'success' handler
     * is given (i.e. <code>response.success = {..}</code>.)  This handler simply
     * returns the parsed data from the response body.  In most cases you will
     * probably want to define a <code>response.success = {...}</code> handler
     * from the request closure, which will replace the response handler defined
     * by this method.  </p>
     * <p>
     * <p>In practice, a user-supplied response handler closure is
     * <i>designed</i> to handle streaming content so it can be read directly from
     * the response stream without buffering, which will be much more efficient.
     * Therefore, it is recommended that request method variants be used which
     * explicitly accept a response handler closure in these cases.</p>
     *
     * @param resp       HTTP response
     * @param parsedData parsed data as resolved from this instance's {@link HttpResponseContentTypeFinder}
     * @return the parsed data object (whatever the parser returns).
     * @throws ResponseParseException if there is an error buffering a streaming
     *                                response.
     */
protected Object defaultSuccessHandler(HttpResponseDecorator resp, Object parsedData) throws ResponseParseException {
    try {
        //If response is streaming, buffer it in a byte array:
        if (parsedData instanceof InputStream) {
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            DefaultGroovyMethods.leftShift(buffer, (InputStream) parsedData);
            parsedData = new ByteArrayInputStream(buffer.toByteArray());
        } else if (parsedData instanceof Reader) {
            StringWriter buffer = new StringWriter();
            DefaultGroovyMethods.leftShift(buffer, (Reader) parsedData);
            parsedData = new StringReader(buffer.toString());
        } else if (parsedData instanceof Closeable)
            log.debug("Parsed data is streaming, but will be accessible after " + "the network connection is closed.  Use at your own risk!");
        return parsedData;
    } catch (IOException ex) {
        throw new ResponseParseException(resp, ex);
    }
}
Example 31
Project: JPS-master  File: ProjectWrapper.java View source code
BuildStatus iterativeCompile(final ModuleChunk chunk, final Set<StringCache.S> sources, final Set<StringCache.S> outdated, final Set<StringCache.S> removed, final Flags flags) {
    final Collection<StringCache.S> filesToCompile = DefaultGroovyMethods.intersect(affectedFiles, sources);
    final Set<StringCache.S> safeFiles = new HashSet<StringCache.S>();
    if (outdated != null) {
        for (StringCache.S s : outdated) {
            assert (s != null);
        }
        filesToCompile.addAll(outdated);
        for (StringCache.S f : outdated) {
            if (f.value.endsWith(".form")) {
                final StringCache.S sourceFileName = dependencyMapping.getJavaByForm(f);
                if (sourceFileName != null && !filesToCompile.contains(sourceFileName)) {
                    safeFiles.add(sourceFileName);
                    filesToCompile.add(sourceFileName);
                }
            } else if (f.value.endsWith(".java")) {
                final StringCache.S formFileName = dependencyMapping.getFormByJava(f);
                if (formFileName != null) {
                    filesToCompile.add(formFileName);
                }
            }
        }
    }
    filesToCompile.removeAll(compiledFiles);
    if (!filesToCompile.isEmpty() || removed != null) {
        final Set<StringCache.S> outputFiles = new HashSet<StringCache.S>();
        for (StringCache.S f : filesToCompile) {
            final Set<ClassRepr> classes = dependencyMapping.getClasses(f);
            if (classes != null)
                for (ClassRepr cr : classes) {
                    outputFiles.add(cr.fileName);
                }
        }
        if (removed != null) {
            for (StringCache.S f : removed) {
                final Set<ClassRepr> classes = dependencyMapping.getClasses(f);
                if (classes != null) {
                    for (ClassRepr cr : classes) {
                        outputFiles.add(cr.fileName);
                    }
                }
            }
        }
        if (!outputFiles.isEmpty()) {
            new Logger(flags) {

                @Override
                public void log(PrintStream stream) {
                    stream.println("Cleaning output files:");
                    logFilePaths(stream, outputFiles);
                    stream.println("End of files");
                }
            }.log();
            builder.clearChunk(chunk, outputFiles, ProjectWrapper.this);
        }
        final Mappings delta = new Mappings(ProjectWrapper.this);
        final Callbacks.Backend deltaBackend = delta.getCallback();
        new Logger(flags) {

            @Override
            public void log(PrintStream stream) {
                stream.println("Compiling files:");
                logFilePaths(stream, filesToCompile);
                stream.println("End of files");
            }
        }.log();
        boolean buildException = false;
        try {
            builder.buildChunk(chunk, flags.tests(), filesToCompile, deltaBackend, ProjectWrapper.this);
        } catch (Exception e) {
            e.printStackTrace();
            buildException = true;
        }
        if (!buildException) {
            compiledFiles.addAll(filesToCompile);
            affectedFiles.removeAll(filesToCompile);
            delta.compensateRemovedContent(filesToCompile);
            final boolean incremental = dependencyMapping.differentiate(delta, removed, compiledFiles, affectedFiles, safeFiles);
            dependencyMapping.integrate(delta, removed);
            if (!incremental) {
                affectedFiles.addAll(sources);
                affectedFiles.removeAll(compiledFiles);
                final BuildStatus result = iterativeCompile(chunk, sources, null, null, flags);
                if (result == BuildStatus.FAILURE) {
                    return result;
                }
                return BuildStatus.CONSERVATIVE;
            }
            return iterativeCompile(chunk, sources, null, null, flags);
        } else {
            return BuildStatus.FAILURE;
        }
    } else {
        for (Module m : chunk.getElements()) {
            Reporter.reportBuildSuccess(m, flags.tests());
        }
    }
    return BuildStatus.INCREMENTAL;
}
Example 32
Project: spring-framework-master  File: GroovyBeanDefinitionReader.java View source code
// INTERNAL HANDLING OF GROOVY CLOSURES AND PROPERTIES
/**
	 * 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;
}
Example 33
Project: Gorm-master  File: GrailsDomainBinder.java View source code
protected void bindCollectionSecondPass(ToMany property, InFlightMetadataCollector mappings, Map<?, ?> persistentClasses, Collection collection, String sessionFactoryBeanName) {
    PersistentClass associatedClass = null;
    if (LOG.isDebugEnabled())
        LOG.debug("Mapping collection: " + collection.getRole() + " -> " + collection.getCollectionTable().getName());
    PropertyConfig propConfig = getPropertyConfig(property);
    PersistentEntity referenced = property.getAssociatedEntity();
    if (propConfig != null && StringUtils.hasText(propConfig.getSort())) {
        if (!property.isBidirectional() && (property instanceof org.grails.datastore.mapping.model.types.OneToMany)) {
            throw new DatastoreConfigurationException("Default sort for associations [" + property.getOwner().getName() + "->" + property.getName() + "] are not supported with unidirectional one to many relationships.");
        }
        if (referenced != null) {
            PersistentProperty propertyToSortBy = referenced.getPropertyByName(propConfig.getSort());
            String associatedClassName = property.getAssociatedEntity().getName();
            associatedClass = (PersistentClass) persistentClasses.get(associatedClassName);
            if (associatedClass != null) {
                collection.setOrderBy(buildOrderByClause(propertyToSortBy.getName(), associatedClass, collection.getRole(), propConfig.getOrder() != null ? propConfig.getOrder() : "asc"));
            }
        }
    }
    // Configure one-to-many
    if (collection.isOneToMany()) {
        Mapping m = getRootMapping(referenced);
        boolean tablePerSubclass = m != null && !m.getTablePerHierarchy();
        if (referenced != null && !referenced.isRoot() && !tablePerSubclass) {
            Mapping rootMapping = getRootMapping(referenced);
            String discriminatorColumnName = RootClass.DEFAULT_DISCRIMINATOR_COLUMN_NAME;
            if (rootMapping != null) {
                DiscriminatorConfig discriminatorConfig = rootMapping.getDiscriminator();
                if (discriminatorConfig != null) {
                    final ColumnConfig discriminatorColumn = discriminatorConfig.getColumn();
                    if (discriminatorColumn != null) {
                        discriminatorColumnName = discriminatorColumn.getName();
                    }
                    if (discriminatorConfig.getFormula() != null) {
                        discriminatorColumnName = discriminatorConfig.getFormula();
                    }
                }
            }
            //NOTE: this will build the set for the in clause if it has sublcasses
            Set<String> discSet = buildDiscriminatorSet((HibernatePersistentEntity) referenced);
            String inclause = DefaultGroovyMethods.join(discSet, ",");
            collection.setWhere(discriminatorColumnName + " in (" + inclause + ")");
        }
        OneToMany oneToMany = (OneToMany) collection.getElement();
        String associatedClassName = oneToMany.getReferencedEntityName();
        associatedClass = (PersistentClass) persistentClasses.get(associatedClassName);
        // if there is no persistent class for the association throw exception
        if (associatedClass == null) {
            throw new MappingException("Association references unmapped class: " + oneToMany.getReferencedEntityName());
        }
        oneToMany.setAssociatedClass(associatedClass);
        if (shouldBindCollectionWithForeignKey(property)) {
            collection.setCollectionTable(associatedClass.getTable());
        }
        bindCollectionForPropertyConfig(collection, propConfig);
    }
    if (referenced != null && referenced.isMultiTenant()) {
        String filterCondition = getMultiTenantFilterCondition(sessionFactoryBeanName, referenced);
        if (filterCondition != null) {
            collection.addFilter(GormProperties.TENANT_IDENTITY, filterCondition, true, Collections.<String, String>emptyMap(), Collections.<String, String>emptyMap());
        }
    }
    if (isSorted(property)) {
        collection.setSorted(true);
    }
    // setup the primary key references
    DependantValue key = createPrimaryKeyValue(mappings, property, collection, persistentClasses);
    // link a bidirectional relationship
    if (property.isBidirectional()) {
        Association otherSide = property.getInverseSide();
        if ((otherSide instanceof org.grails.datastore.mapping.model.types.ToOne) && shouldBindCollectionWithForeignKey(property)) {
            linkBidirectionalOneToMany(collection, associatedClass, key, otherSide);
        } else if ((otherSide instanceof ManyToMany) || Map.class.isAssignableFrom(property.getType())) {
            bindDependentKeyValue(property, key, mappings, sessionFactoryBeanName);
        }
    } else {
        if (hasJoinKeyMapping(propConfig)) {
            bindSimpleValue("long", key, false, propConfig.getJoinTable().getKey().getName(), mappings);
        } else {
            bindDependentKeyValue(property, key, mappings, sessionFactoryBeanName);
        }
    }
    collection.setKey(key);
    // get cache config
    if (propConfig != null) {
        CacheConfig cacheConfig = propConfig.getCache();
        if (cacheConfig != null) {
            collection.setCacheConcurrencyStrategy(cacheConfig.getUsage());
        }
    }
    // if we have a many-to-many
    final boolean isManyToMany = property instanceof ManyToMany;
    if (isManyToMany || isBidirectionalOneToManyMap(property)) {
        PersistentProperty otherSide = property.getInverseSide();
        if (property.isBidirectional()) {
            if (LOG.isDebugEnabled())
                LOG.debug("[GrailsDomainBinder] Mapping other side " + otherSide.getOwner().getName() + "." + otherSide.getName() + " -> " + collection.getCollectionTable().getName() + " as ManyToOne");
            ManyToOne element = new ManyToOne(mappings, collection.getCollectionTable());
            bindManyToMany((Association) otherSide, element, mappings, sessionFactoryBeanName);
            collection.setElement(element);
            bindCollectionForPropertyConfig(collection, propConfig);
            if (property.isCircular()) {
                collection.setInverse(false);
            }
        } else {
        // TODO support unidirectional many-to-many
        }
    } else if (shouldCollectionBindWithJoinColumn(property)) {
        bindCollectionWithJoinTable(property, mappings, collection, propConfig, sessionFactoryBeanName);
    } else if (isUnidirectionalOneToMany(property)) {
        // for non-inverse one-to-many, with a not-null fk, add a backref!
        // there are problems with list and map mappings and join columns relating to duplicate key constraints
        // TODO change this when HHH-1268 is resolved
        bindUnidirectionalOneToMany((org.grails.datastore.mapping.model.types.OneToMany) property, mappings, collection);
    }
}
Example 34
Project: Desktop-master  File: NodeArithmeticsCategory.java View source code
public static Number power(final Number self, final Proxy.Node node) {
    return DefaultGroovyMethods.power(self, node.getTo().getNum0());
}
Example 35
Project: Docear-master  File: NodeArithmeticsCategory.java View source code
public static Number power(final Number self, final Proxy.Node node) {
    return DefaultGroovyMethods.power(self, node.getTo().getNum0());
}
Example 36
Project: spock-master  File: UseInterceptor.java View source code
public void intercept(final IMethodInvocation invocation) throws Throwable {
    DefaultGroovyMethods.use(null, categories, new Closure<Void>(invocation.getInstance(), invocation.getInstance()) {

        public Void doCall(Object[] args) throws Throwable {
            invocation.proceed();
            return null;
        }
    });
}
Example 37
Project: cucumber-jvm-master  File: GroovyBackend.java View source code
private boolean isScript(Script script) {
    return DefaultGroovyMethods.asBoolean(script.getMetaClass().respondsTo(script, "main"));
}
Example 38
Project: gradle-car-plugin-master  File: DefaultManifestMergeSpec.java View source code
public ManifestMergeSpec eachEntry(Closure mergeAction) {
    return eachEntry((Action<? super ManifestMergeDetails>) DefaultGroovyMethods.asType(mergeAction, Action.class));
}
Example 39
Project: gradle-msbuild-plugin-master  File: DefaultManifestMergeSpec.java View source code
public ManifestMergeSpec eachEntry(Closure mergeAction) {
    return eachEntry((Action<? super ManifestMergeDetails>) DefaultGroovyMethods.asType(mergeAction, Action.class));
}
Example 40
Project: live-plugin-master  File: LivePluginAppComponent.java View source code
private static boolean isGroovyOnClasspath() {
    return IDEUtil.isOnClasspath("org.codehaus.groovy.runtime.DefaultGroovyMethods");
}
Example 41
Project: filebot-master  File: ScriptShellMethods.java View source code
public static File getAt(File self, Range<?> range) {
    return new File(DefaultGroovyMethods.getAt(FileUtilities.listPath(self), range).stream().map(File::getName).collect(joining(File.separator)));
}
Example 42
Project: groovy-sql-stream-extension-master  File: StreamingResultSet.java View source code
/**
     * Finds the first element matching the given Closure predicate.
     * The result is equivalent to {@code findAll} operation followed by {@code head}.
     *
     * @param p   the Closure that must evaluate to {@code true} for element to be taken
     * @return the first element matching the Closure predicate
     */
public Object find(Closure<Boolean> p) throws SQLException {
    if (values != null)
        return DefaultGroovyMethods.find(values, p);
    return terminate(new Find(p), null);
}