Search in sources :

Example 91 with ImmutableSet

use of org.apache.beam.vendor.calcite.v1_28_0.com.google.common.collect.ImmutableSet in project raml-module-builder by folio-org.

the class AnnotationGrabber method generateMappings.

// ^http.*?//.*?/apis/patrons/.*?/fines/.*
// ^http.*?\/\/.*?\/apis\/patrons\/?(.+?)*
// ^http.*?\/\/.*?\/apis\/([^\/]+)\/([^\/]+)(\?.*)
public static JsonObject generateMappings() throws Exception {
    /* this class is one of the drivers for the client generation
     * check if the plugin set the system property in the pom and only if
     * so generate */
    String clientGen = System.getProperty("client.generate");
    String modDescr = System.getProperty("modDescrptor.generate");
    if (clientGen != null) {
        generateClient = true;
    }
    if ("true".equals(modDescr)) {
        generateModDescrptor = true;
    }
    JsonObject globalClassMapping = new JsonObject();
    // get classes in generated package
    ClassPath classPath = ClassPath.from(Thread.currentThread().getContextClassLoader());
    ImmutableSet<ClassPath.ClassInfo> classes = classPath.getTopLevelClasses(RTFConsts.INTERFACE_PACKAGE);
    Collection<Object> classNames = Collections2.transform(classes, new Function<ClassPath.ClassInfo, Object>() {

        @Override
        public Object apply(ClassPath.ClassInfo input) {
            log.info("Mapping functions in " + input.getName() + " class to appropriate urls");
            // not needed - dont need transform function,
            return input.getName();
        // remove
        }
    });
    // loop over all the classes from the package
    classNames.forEach(val -> {
        try {
            ClientGenerator cGen = new ClientGenerator();
            // ----------------- class level annotations -----------------------//
            // -----------------------------------------------------------------//
            // will contain all mappings for a specific class in the package
            JsonObject classSpecificMapping = new JsonObject();
            // get annotations via reflection for a class
            Annotation[] annotations = Class.forName(val.toString()).getAnnotations();
            // create an entry for the class name = ex. "class":"com.sling.rest.jaxrs.resource.BibResource"
            classSpecificMapping.put(CLASS_NAME, val.toString());
            classSpecificMapping.put(INTERFACE_NAME, val.toString());
            // needed info - these are class level annotation - not method level
            for (int i = 0; i < annotations.length; i++) {
                // get the annotation type - example in jersey would we javax.ws.rs.Path
                Class<? extends Annotation> type = annotations[i].annotationType();
                // function
                for (Method method : type.getDeclaredMethods()) {
                    Object value = method.invoke(annotations[i], (Object[]) null);
                    if (type.isAssignableFrom(Path.class)) {
                        classSpecificMapping.put(CLASS_URL, "^/" + value);
                        if (generateClient) {
                            cGen.generateClassMeta(val.toString(), value);
                        }
                        if (generateModDescrptor && classSpecificMapping.getString(CLASS_URL) != null) {
                            String url = classSpecificMapping.getString(CLASS_URL).substring(2);
                            if (!url.contains("rmbtests")) {
                                MDGenerator.ProvidesEntry pe = MDGenerator.INSTANCE.new ProvidesEntry();
                                if (url.contains("_/tenant")) {
                                    url = "_tenant";
                                }
                                pe.setId(url);
                                MDGenerator.INSTANCE.addProvidesEntry(pe);
                            }
                        }
                    }
                }
            }
            // ----------------- method level annotations ------------ //
            // ------------------------------------------------------- //
            /**
             * will be used only if ModuleDescriptor generation is turned on
             * maps all http verbs to a single url
             */
            mdUrl2Verbs = new HashMap<>();
            JsonArray methodsInAPath;
            // iterate over all functions in the class
            Method[] methods = Class.forName(val.toString()).getMethods();
            for (int i = 0; i < methods.length; i++) {
                JsonObject methodObj = new JsonObject();
                JsonObject params = getParameterNames(methods[i]);
                // get annotations on the method and add all info per method to its
                // own methodObj
                Annotation[] methodAn = methods[i].getAnnotations();
                // System.out.println(methods[i].getName());
                // put the name of the function
                methodObj.put(FUNCTION_NAME, methods[i].getName());
                methodObj.put(METHOD_PARAMS, params);
                for (int j = 0; j < methodAn.length; j++) {
                    Class<? extends Annotation> type = methodAn[j].annotationType();
                    // System.out.println("Values of " + type.getName());
                    if (RTFConsts.POSSIBLE_HTTP_METHOD.contains(type.getName())) {
                        // put the method - get or post, etc..
                        methodObj.put(HTTP_METHOD, type.getName());
                    }
                    boolean replaceAccept = false;
                    if (type.isAssignableFrom(Produces.class)) {
                        // this is the accept header, right now can not send */*
                        // so if accept header equals any/ - change this to */*
                        replaceAccept = true;
                    }
                    for (Method method : type.getDeclaredMethods()) {
                        Object value = method.invoke(methodAn[j], (Object[]) null);
                        if (value.getClass().isArray()) {
                            List<Object> retList = new ArrayList<>();
                            for (int k = 0; k < Array.getLength(value); k++) {
                                if (replaceAccept) {
                                    // replace any/any with */* to allow declaring accpet */* which causes compilation issues
                                    // when declared in raml. so declare any/any in raml instead and replaced here
                                    retList.add(((String) Array.get(value, k)).replaceAll("any/any", ""));
                                } else {
                                    retList.add(Array.get(value, k));
                                }
                            }
                            // put generically things like consumes, produces as arrays
                            // since they can have multi values
                            methodObj.put(type.getName(), retList);
                        } else {
                            if (type.isAssignableFrom(Path.class)) {
                                String path = classSpecificMapping.getString(CLASS_URL) + URL_PATH_DELIMITER + value;
                                String regexPath = getRegexForPath(path);
                                // put path to function
                                methodObj.put(METHOD_URL, path);
                                // put regex path to function
                                methodObj.put(REGEX_URL, regexPath);
                            }
                        // System.out.println(" " + method.getName() + ": " + value.toString());
                        }
                    }
                }
                if (generateClient) {
                    cGen.generateMethodMeta(methodObj.getString(FUNCTION_NAME), methodObj.getJsonObject(METHOD_PARAMS), methodObj.getString(METHOD_URL), methodObj.getString(HTTP_METHOD), methodObj.getJsonArray(CONSUMES), methodObj.getJsonArray(PRODUCES));
                }
                // class
                if (methodObj.getString(METHOD_URL) == null) {
                    methodObj.put(METHOD_URL, classSpecificMapping.getString(CLASS_URL));
                    methodObj.put(REGEX_URL, getRegexForPath(classSpecificMapping.getString(CLASS_URL)));
                }
                if (generateModDescrptor) {
                    String verb = methodObj.getString(HTTP_METHOD);
                    verb = verb.substring(verb.lastIndexOf(".") + 1);
                    String rootURL4Service = classSpecificMapping.getString(CLASS_URL).substring(1);
                    /*if(mdUrl2Verbs.get(path.substring(1)) != null){
              mdUrl2Verbs.get(path.substring(1)).add(verb);
            } else {
              mdUrl2Verbs.put(path.substring(1), new JsonArray());
              mdUrl2Verbs.get(path.substring(1)).add(verb);
            }*/
                    if (mdUrl2Verbs.get(rootURL4Service) != null) {
                        mdUrl2Verbs.get(rootURL4Service).add(verb);
                    } else {
                        mdUrl2Verbs.put(rootURL4Service, new HashSet<String>());
                        mdUrl2Verbs.get(rootURL4Service).add(verb);
                    }
                }
                // this is the key - the regex path is the key to the functions
                // represented by this url
                // an array of functions which answer to this url (with get, delete,
                // post, etc... methods)
                methodsInAPath = classSpecificMapping.getJsonArray(methodObj.getString(REGEX_URL));
                if (methodsInAPath == null) {
                    methodsInAPath = new JsonArray();
                    classSpecificMapping.put(methodObj.getString(REGEX_URL), methodsInAPath);
                }
                methodsInAPath.add(methodObj);
            }
            // System.out.println( val.toString() );
            globalClassMapping.put(classSpecificMapping.getString(CLASS_URL), classSpecificMapping);
            if (generateClient) {
                cGen.generateClass(classSpecificMapping);
            }
            if (generateModDescrptor) {
                BiConsumer<String, Set<String>> biConsumer = (key, value) -> {
                    if (!key.contains("_/tenant") && !key.contains("rmbtests")) {
                        MDGenerator.RoutingEntry re = MDGenerator.INSTANCE.new RoutingEntry();
                        JsonArray ja = new JsonArray();
                        value.forEach(verb -> {
                            ja.add(verb);
                        });
                        re.setMethods(ja);
                        re.setEntryPath(key);
                        re.setLevel("30");
                        re.setType("request-response");
                        MDGenerator.INSTANCE.addRoutingEntry(re);
                    }
                };
                mdUrl2Verbs.forEach(biConsumer);
                MDGenerator.INSTANCE.generateMD();
                // this is needed when the MDGenerator is used to generate
                // partial MDs in submodules. the system variable is maintained
                // across the sub module builds and if not reset will generate a
                // partial MD for all sub modules
                System.setProperty("modDescrptor.generate", "false");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    });
    // writeMappings(globalClassMapping);
    return globalClassMapping;
}
Also used : PathParam(javax.ws.rs.PathParam) Array(java.lang.reflect.Array) Produces(javax.ws.rs.Produces) Path(javax.ws.rs.Path) HashMap(java.util.HashMap) Collections2(com.google.common.collect.Collections2) LoggerFactory(io.vertx.core.logging.LoggerFactory) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) QueryParam(javax.ws.rs.QueryParam) Parameter(java.lang.reflect.Parameter) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) DefaultValue(javax.ws.rs.DefaultValue) HeaderParam(javax.ws.rs.HeaderParam) JsonObject(io.vertx.core.json.JsonObject) ClassPath(com.google.common.reflect.ClassPath) Logger(io.vertx.core.logging.Logger) Method(java.lang.reflect.Method) Function(com.google.common.base.Function) ImmutableSet(com.google.common.collect.ImmutableSet) Collection(java.util.Collection) Set(java.util.Set) JsonArray(io.vertx.core.json.JsonArray) List(java.util.List) Annotation(java.lang.annotation.Annotation) ClassPath(com.google.common.reflect.ClassPath) HashSet(java.util.HashSet) ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) ArrayList(java.util.ArrayList) JsonObject(io.vertx.core.json.JsonObject) Method(java.lang.reflect.Method) Annotation(java.lang.annotation.Annotation) JsonArray(io.vertx.core.json.JsonArray) JsonObject(io.vertx.core.json.JsonObject)

Example 92 with ImmutableSet

use of org.apache.beam.vendor.calcite.v1_28_0.com.google.common.collect.ImmutableSet in project ForestryMC by ForestryMC.

the class ItemInventoryHabitatLocator method getErrorStates.

/* IErrorSource */
@Override
public ImmutableSet<IErrorState> getErrorStates() {
    if (!getStackInSlot(SLOT_ANALYZED).isEmpty()) {
        return ImmutableSet.of();
    }
    ImmutableSet.Builder<IErrorState> errorStates = ImmutableSet.builder();
    ItemStack specimen = getStackInSlot(SLOT_SPECIMEN);
    if (!BeeManager.beeRoot.isMember(specimen)) {
        errorStates.add(EnumErrorCode.NO_SPECIMEN);
    }
    if (!isEnergy(getStackInSlot(SLOT_ENERGY))) {
        errorStates.add(EnumErrorCode.NO_HONEY);
    }
    return errorStates.build();
}
Also used : ImmutableSet(com.google.common.collect.ImmutableSet) IErrorState(forestry.api.core.IErrorState) ItemStack(net.minecraft.item.ItemStack)

Example 93 with ImmutableSet

use of org.apache.beam.vendor.calcite.v1_28_0.com.google.common.collect.ImmutableSet in project ForestryMC by ForestryMC.

the class ItemInventorySolderingIron method getErrorStates.

@Override
public ImmutableSet<IErrorState> getErrorStates() {
    ImmutableSet.Builder<IErrorState> errorStates = ImmutableSet.builder();
    if (layouts.getCurrent() == CircuitRegistry.DUMMY_LAYOUT) {
        errorStates.add(EnumErrorCode.NO_CIRCUIT_LAYOUT);
    }
    ItemStack blankCircuitBoard = getStackInSlot(inputCircuitBoardSlot);
    if (blankCircuitBoard.isEmpty()) {
        errorStates.add(EnumErrorCode.NO_CIRCUIT_BOARD);
    } else {
        EnumCircuitBoardType type = EnumCircuitBoardType.values()[blankCircuitBoard.getItemDamage()];
        int circuitCount = 0;
        for (short i = 0; i < type.getSockets(); i++) {
            if (!getStackInSlot(ingredientSlot1 + i).isEmpty()) {
                circuitCount++;
            }
        }
        if (circuitCount != type.getSockets()) {
            errorStates.add(EnumErrorCode.CIRCUIT_MISMATCH);
        } else {
            int count = getCircuitCount();
            if (count != type.getSockets()) {
                errorStates.add(EnumErrorCode.NO_CIRCUIT_LAYOUT);
            }
        }
    }
    return errorStates.build();
}
Also used : EnumCircuitBoardType(forestry.core.circuits.EnumCircuitBoardType) ImmutableSet(com.google.common.collect.ImmutableSet) IErrorState(forestry.api.core.IErrorState) ItemStack(net.minecraft.item.ItemStack)

Example 94 with ImmutableSet

use of org.apache.beam.vendor.calcite.v1_28_0.com.google.common.collect.ImmutableSet in project vespa by vespa-engine.

the class TypeCheckers method createChecker.

// this is festooned with instance checkes before all the casting
@SuppressWarnings("unchecked")
private static OperatorTypeChecker createChecker(Operator parent, int idx, Object value) {
    if (value instanceof TypeLiteral) {
        TypeLiteral<?> lit = (TypeLiteral<?>) value;
        Class<?> raw = lit.getRawType();
        if (List.class.isAssignableFrom(raw)) {
            Preconditions.checkArgument(lit.getType() instanceof ParameterizedType, "TypeLiteral without a ParameterizedType for List");
            ParameterizedType type = (ParameterizedType) lit.getType();
            TypeLiteral<?> arg = TypeLiteral.get(type.getActualTypeArguments()[0]);
            if (OperatorNode.class.isAssignableFrom(arg.getRawType())) {
                Preconditions.checkArgument(arg.getType() instanceof ParameterizedType, "Type spec must be List<OperatorNode<?>>");
                Class<? extends Operator> optype = (Class<? extends Operator>) TypeLiteral.get(((ParameterizedType) arg.getType()).getActualTypeArguments()[0]).getRawType();
                return new OperatorNodeListTypeChecker(parent, idx, optype, ImmutableSet.<Operator>of());
            } else {
                return new JavaListTypeChecker(parent, idx, arg.getRawType());
            }
        }
        throw new IllegalArgumentException("don't know how to handle TypeLiteral " + value);
    }
    if (value instanceof Class) {
        Class<?> clazz = (Class<?>) value;
        if (Operator.class.isAssignableFrom(clazz)) {
            return new NodeTypeChecker(parent, idx, (Class<? extends Operator>) clazz, ImmutableSet.<Operator>of());
        } else {
            return new JavaTypeChecker(parent, idx, clazz);
        }
    } else if (value instanceof Operator) {
        Operator operator = (Operator) value;
        Class<? extends Operator> clazz = operator.getClass();
        Set<? extends Operator> allowed;
        if (Enum.class.isInstance(value)) {
            Class<? extends Enum> enumClazz = (Class<? extends Enum>) clazz;
            allowed = (Set<? extends Operator>) EnumSet.of(enumClazz.cast(value));
        } else {
            allowed = ImmutableSet.of(operator);
        }
        return new NodeTypeChecker(parent, idx, clazz, allowed);
    } else if (value instanceof EnumSet) {
        EnumSet<?> v = (EnumSet<?>) value;
        Enum elt = Iterables.get(v, 0);
        if (elt instanceof Operator) {
            Class<? extends Operator> opclass = (Class<? extends Operator>) elt.getClass();
            Set<? extends Operator> allowed = (Set<? extends Operator>) v;
            return new NodeTypeChecker(parent, idx, opclass, allowed);
        }
    } else if (value instanceof Set) {
        // Set<Class<?>>
        return new JavaUnionTypeChecker(parent, idx, (Set<Class<?>>) value);
    }
    throw new IllegalArgumentException("I don't know how to create a checker from " + value);
}
Also used : ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) EnumSet(java.util.EnumSet) EnumSet(java.util.EnumSet) ParameterizedType(java.lang.reflect.ParameterizedType) TypeLiteral(com.google.inject.TypeLiteral)

Example 95 with ImmutableSet

use of org.apache.beam.vendor.calcite.v1_28_0.com.google.common.collect.ImmutableSet in project BuildCraft by BuildCraft.

the class BCTransportRecipes method makeGateModifierAssembly.

private static void makeGateModifierAssembly(int multiplier, EnumGateMaterial material, EnumGateModifier modifier, IngredientStack... mods) {
    for (EnumGateLogic logic : EnumGateLogic.VALUES) {
        String name = String.format("gate-modifier-%s-%s-%s", logic, material, modifier);
        ItemStack toUpgrade = BCTransportItems.plugGate.getStack(new GateVariant(logic, material, EnumGateModifier.NO_MODIFIER));
        ItemStack output = BCTransportItems.plugGate.getStack(new GateVariant(logic, material, modifier));
        ImmutableSet<IngredientStack> input = new ImmutableSet.Builder<IngredientStack>().add(IngredientStack.of(toUpgrade)).add(mods).build();
        AssemblyRecipeRegistry.register((new AssemblyRecipeBasic(name, MjAPI.MJ * multiplier, input, output)));
    }
}
Also used : AssemblyRecipeBasic(buildcraft.api.recipes.AssemblyRecipeBasic) ImmutableSet(com.google.common.collect.ImmutableSet) GateVariant(buildcraft.transport.gate.GateVariant) ItemStack(net.minecraft.item.ItemStack) IngredientStack(buildcraft.api.recipes.IngredientStack) EnumGateLogic(buildcraft.transport.gate.EnumGateLogic)

Aggregations

ImmutableSet (com.google.common.collect.ImmutableSet)348 Set (java.util.Set)86 ImmutableList (com.google.common.collect.ImmutableList)73 Path (java.nio.file.Path)71 ImmutableMap (com.google.common.collect.ImmutableMap)69 IOException (java.io.IOException)67 Optional (java.util.Optional)65 Map (java.util.Map)63 List (java.util.List)60 BuildTarget (com.facebook.buck.model.BuildTarget)58 Test (org.junit.Test)55 HashMap (java.util.HashMap)42 Collection (java.util.Collection)34 HashSet (java.util.HashSet)33 SourcePath (com.facebook.buck.rules.SourcePath)31 ArrayList (java.util.ArrayList)31 TargetNode (com.facebook.buck.rules.TargetNode)28 BuildRule (com.facebook.buck.rules.BuildRule)26 VisibleForTesting (com.google.common.annotations.VisibleForTesting)25 ImmutableSortedSet (com.google.common.collect.ImmutableSortedSet)25