Example #1
0
  private void checkCompoundIds(Class<?> javaClass) throws IOException {
    String javaClassName = javaClass.getCanonicalName();
    PsiClass psiClass =
        myJavaPsiFacade.findClass(
            javaClassName, GlobalSearchScope.moduleWithLibrariesScope(myModule));
    assertNotNull(psiClass);

    for (java.lang.reflect.Method javaMethod : javaClass.getDeclaredMethods()) {
      Method method =
          new Method(
              Type.getType(javaClass).getInternalName(),
              javaMethod.getName(),
              Type.getMethodDescriptor(javaMethod));
      boolean noKey = javaMethod.getAnnotation(ExpectNoPsiKey.class) != null;
      PsiMethod psiMethod = psiClass.findMethodsByName(javaMethod.getName(), false)[0];
      checkCompoundId(method, psiMethod, noKey);
    }

    for (Constructor<?> constructor : javaClass.getDeclaredConstructors()) {
      Method method =
          new Method(
              Type.getType(javaClass).getInternalName(),
              "<init>",
              Type.getConstructorDescriptor(constructor));
      boolean noKey = constructor.getAnnotation(ExpectNoPsiKey.class) != null;
      PsiMethod[] constructors = psiClass.getConstructors();
      PsiMethod psiMethod = constructors[0];
      checkCompoundId(method, psiMethod, noKey);
    }
  }
Example #2
0
  @Override
  public Type typecheck(SymTab s) {
    Type varType = preDot.typecheck(s); // this must be a class type
    // if it's another type throw an error
    if (varType.getType() == "int" || varType.getType() == "bool" || varType.getType() == "empty") {
      throw new Error(
          line
              + ":"
              + column
              + " error: "
              + "used non-class variabe like a class (bad field access)");
    }

    classType = varType.getType();

    /* Currently postDot is an ArrExpr that is kinda broken. Take example FieldExpr a.var, a:Point, var:int[]
     * postDot currently has name as an IDExpr with name "var", but "var" isn't a variable
     * Construct a new ArrExpr with postDot's accesses but prepend the classname, and typecheck it
     */
    ArrExpr real =
        new ArrExpr(
            new IDExpr(varType.getType() + "." + postDot.getName().getName(), line, column),
            postDot.getAccesses(),
            postDot.getLine(),
            postDot.getColumn());

    // if this typechecks, the full FieldExpr is good
    type = real.typecheck(s);
    return type;
  }
Example #3
0
 /**
  * Returns an OEnchantment object for a given enchantment type. Notice this isnt the enchantment
  * data, but the enchantment description.
  *
  * @return Returns the OEnchantment object for a given enchantment type
  */
 public static OEnchantment getEnchantment(Type type) {
   if (type != null) {
     if (type.getType() >= 0 && type.getType() < OEnchantment.b.length) {
       OEnchantment enchantmentType = OEnchantment.b[type.getType()];
       if (enchantmentType != null) {
         return enchantmentType;
       }
     }
   }
   return null;
 }
Example #4
0
  @SuppressWarnings("unchecked")
  protected void onMethodEnter() {
    try {
      Class wd = Wustendorf.class;
      if (hook == HOOK_LIGHT_OVERRIDE
          || hook == HOOK_LIGHT_DISPLAY
          || hook == HOOK_LIGHT_OVERRIDE_CACHE
          || hook == HOOK_LIGHT_DISPLAY_CACHE) {
        /* We're writing this code:
        int override = wustendorf.Wustendorf.overrideSkyLight(this, par2, par3, par4);
        if (override != -1) {
            return override;
        }
        */
        loadThis(); // this

        if (hook == HOOK_LIGHT_OVERRIDE_CACHE || hook == HOOK_LIGHT_DISPLAY_CACHE) {
          getField(
              Type.getType("L%conf:OBF_CHUNK_CACHE%;"),
              "%conf:OBF_CHUNK_CACHE_WORLD%",
              Type.getType("L%conf:OBF_WORLD%;"));
        }
        loadArgs(0, 3); // our own arguments 1-3

        // Ask Wustendorf if it has an override.
        String world = "%conf:OBF_WORLD%";
        if (hook == HOOK_LIGHT_OVERRIDE || hook == HOOK_LIGHT_OVERRIDE_CACHE) {
          invokeStatic(Type.getType(wd), new Method("overrideLight", "(L" + world + ";III)I"));
        } else { // if (hook == HOOK_LIGHT_DISPLAY) {
          invokeStatic(
              Type.getType(wd), new Method("overrideLightDisplay", "(L" + world + ";III)I"));
        }

        dup(); // Duplicate the return value.
        Label keep_going = new Label();
        visitJumpInsn(Opcodes.IFLT, keep_going); // If the override set
        returnValue(); // Use it.
        visitLabel(keep_going); // Otherwise, keep going
        pop(); // (and nix the copy)
      } else if (hook == HOOK_CONSIDER_KILL) {
        /* We're writing this code:
        wustendorf.Wustendorf.considerKillingCritter(this);
        */
        loadThis(); // this

        String entityliving = "%conf:OBF_ENTITY_LIVING%";
        invokeStatic(
            Type.getType(wd), new Method("considerKillingCritter", "(L" + entityliving + ";)V"));
      }
    } catch (Exception e) {
      System.out.println("Wustendorf: HOOK FAILED!");
      e.printStackTrace();
    }
  }
  // the overload of type Object for Groovy coercions:  public void setFoo(Object foo)
  private void createTypeConvertingSetter(
      ClassVisitor visitor, Type generatedType, ModelProperty<?> property) {
    if (!property.isWritable() || !(property.getSchema() instanceof ScalarValueSchema)) {
      return;
    }

    Class<?> propertyClass = property.getType().getConcreteClass();
    Type propertyType = Type.getType(propertyClass);
    Class<?> boxedClass =
        propertyClass.isPrimitive() ? BOXED_TYPES.get(propertyClass) : propertyClass;
    Type boxedType = Type.getType(boxedClass);

    Method setter = property.getSetter().getMethod();
    MethodVisitor methodVisitor =
        declareMethod(
            visitor,
            setter.getName(),
            SET_OBJECT_PROPERTY_DESCRIPTOR,
            SET_OBJECT_PROPERTY_DESCRIPTOR);

    putThisOnStack(methodVisitor);
    putTypeConverterFieldValueOnStack(methodVisitor, generatedType);

    // Object converted = $typeConverter.convert(foo, Float.class, false);
    methodVisitor.visitVarInsn(ALOAD, 1); // put var #1 ('foo') on the stack
    methodVisitor.visitLdcInsn(boxedType); // push the constant Class onto the stack
    methodVisitor.visitInsn(
        propertyClass.isPrimitive()
            ? ICONST_1
            : ICONST_0); // push int 1 or 0 (interpreted as true or false) onto the stack
    methodVisitor.visitMethodInsn(
        INVOKEINTERFACE,
        TYPE_CONVERTER_TYPE.getInternalName(),
        "convert",
        COERCE_TO_SCALAR_DESCRIPTOR,
        true);
    methodVisitor.visitTypeInsn(CHECKCAST, boxedType.getInternalName());

    if (propertyClass.isPrimitive()) {
      unboxType(methodVisitor, propertyClass);
    }

    // invoke the typed setter, popping 'this' and 'converted' from the stack
    methodVisitor.visitMethodInsn(
        INVOKEVIRTUAL,
        generatedType.getInternalName(),
        setter.getName(),
        Type.getMethodDescriptor(Type.VOID_TYPE, propertyType),
        false);
    finishVisitingMethod(methodVisitor);
  }
  /** Creates a <tt>BloatContext</tt> that loads classes from a given CLASSPATH. */
  static BloatContext makeContext(final String classpath, final String outputDirName) {
    final ClassFileLoader loader = new ClassFileLoader();
    if (classpath != null) {
      loader.prependClassPath(classpath);
    }

    // if(TRACE) {
    // loader.setVerbose(true);
    // }

    BloatBenchmark.tr("  Creating a BloatContext for CLASSPATH: " + loader.getClassPath());

    if (outputDirName != null) {
      loader.setOutputDir(new File(outputDirName));
    }
    final BloatContext context = new CachingBloatContext(loader, BloatBenchmark.CLASSES, true);

    // Always ignore the sun packages and the opj stuff for
    // interprocedural stuff
    if (!BloatBenchmark.SUN) {
      context.addIgnorePackage("sun");
    }

    context.addIgnorePackage("java.lang.ref");
    context.addIgnorePackage("org.opj.system");

    if (BloatBenchmark.USE1_1) {
      // Toba can't deal with java.lang.Character
      context.addIgnoreClass(Type.getType("Ljava/lang/Character;"));
    }

    return (context);
  }
  protected void injectGetByIndex(
      ClassWriter classWriter, String targetClassName, List<Field> fields) {
    MethodVisitor methodVisitor =
        classWriter.visitMethod(
            ACC_PUBLIC,
            "get",
            "(Ljava/lang/Object;I)Ljava/lang/Object;",
            null,
            new String[] {getInternalName(ILLEGAL_ACCESS_EXCEPTION.getCanonicalName())});

    Boxer boxer = new Boxer(methodVisitor);

    methodVisitor.visitCode();
    methodVisitor.visitVarInsn(ILOAD, 2);

    int maxStack = 6;

    Label[] labels = new Label[fields.size()];
    Label errorLabel = new Label();

    for (int i = 0; i < fields.size(); i++) {
      labels[i] = new Label();
    }

    methodVisitor.visitTableSwitchInsn(0, labels.length - 1, errorLabel, labels);

    if (!fields.isEmpty()) {
      maxStack--;

      for (int i = 0; i < fields.size(); i++) {
        Field field = fields.get(i);
        Class<?> type = field.getType();
        String fieldDescriptor = Type.getDescriptor(type);

        methodVisitor.visitLabel(labels[i]);

        if (i == 0) methodVisitor.visitFrame(F_APPEND, 1, new Object[] {targetClassName}, 0, null);
        else methodVisitor.visitFrame(F_SAME, 0, null, 0, null);

        if (isPublic(field)) {
          methodVisitor.visitVarInsn(ALOAD, 1);
          methodVisitor.visitTypeInsn(CHECKCAST, targetClassName);
          methodVisitor.visitFieldInsn(GETFIELD, targetClassName, field.getName(), fieldDescriptor);

          boxer.box(Type.getType(type));
        } else {
          injectReflectiveGetter(methodVisitor);
        }

        methodVisitor.visitInsn(ARETURN);
      }

      methodVisitor.visitLabel(errorLabel);
      methodVisitor.visitFrame(F_SAME, 0, null, 0, null);
    }

    injectException(methodVisitor, IllegalAccessException.class);
    methodVisitor.visitMaxs(maxStack, 3);
    methodVisitor.visitEnd();
  }
  private void writeSetter(ClassVisitor visitor, Type generatedType, ModelProperty<?> property) {
    WeaklyTypeReferencingMethod<?, Void> weakSetter = property.getSetter();
    // There is no setter for this property
    if (weakSetter == null) {
      return;
    }

    String propertyName = property.getName();
    Class<?> propertyClass = property.getType().getConcreteClass();
    Type propertyType = Type.getType(propertyClass);
    Label calledOutsideOfConstructor = new Label();

    Method setter = weakSetter.getMethod();

    // the regular typed setter
    String methodDescriptor = Type.getMethodDescriptor(Type.VOID_TYPE, propertyType);
    MethodVisitor methodVisitor =
        declareMethod(
            visitor, setter.getName(), methodDescriptor, AsmClassGeneratorUtils.signature(setter));

    putCanCallSettersFieldValueOnStack(methodVisitor, generatedType);
    jumpToLabelIfStackEvaluatesToTrue(methodVisitor, calledOutsideOfConstructor);
    throwExceptionBecauseCalledOnItself(methodVisitor);

    methodVisitor.visitLabel(calledOutsideOfConstructor);
    putStateFieldValueOnStack(methodVisitor, generatedType);
    putConstantOnStack(methodVisitor, propertyName);
    putFirstMethodArgumentOnStack(methodVisitor, propertyType);
    if (propertyClass.isPrimitive()) {
      boxType(methodVisitor, propertyClass);
    }
    invokeStateSetMethod(methodVisitor);

    finishVisitingMethod(methodVisitor);
  }
  private void writeConstructor(
      ClassVisitor visitor,
      Type generatedType,
      Type superclassType,
      StructSchema<?> delegateSchema) {
    String constructorDescriptor;
    Type delegateType;
    if (delegateSchema == null) {
      delegateType = null;
      constructorDescriptor = NO_DELEGATE_CONSTRUCTOR_DESCRIPTOR;
    } else {
      delegateType = Type.getType(delegateSchema.getType().getConcreteClass());
      constructorDescriptor =
          Type.getMethodDescriptor(
              Type.VOID_TYPE, MODEL_ELEMENT_STATE_TYPE, TYPE_CONVERTER_TYPE, delegateType);
    }
    MethodVisitor constructorVisitor =
        declareMethod(visitor, CONSTRUCTOR_NAME, constructorDescriptor, CONCRETE_SIGNATURE);

    invokeSuperConstructor(constructorVisitor, superclassType);
    assignStateField(constructorVisitor, generatedType);
    assignTypeConverterField(constructorVisitor, generatedType);
    if (delegateType != null) {
      assignDelegateField(constructorVisitor, generatedType, delegateType);
    }
    setCanCallSettersField(constructorVisitor, generatedType, true);
    finishVisitingMethod(constructorVisitor);
  }
Example #10
0
 /**
  * Creates a block of specified type and specified x, y and z
  *
  * @param type Type of block
  * @param x
  * @param y
  * @param z
  * @param data
  */
 public Block(Type type, int x, int y, int z, int data) {
   this.type = type.getType();
   blockType = type;
   this.x = x;
   this.y = y;
   this.z = z;
   this.data = data;
 }
    public AnnotationTextCollector(@Nullable String desc, AnnotationResultCallback callback) {
      super(Opcodes.ASM4);
      myCallback = callback;

      myDesc = desc;
      if (desc != null) {
        myBuilder.append('@').append(getTypeText(Type.getType(desc)));
      }
    }
Example #12
0
 /** Symbolically executes the corresponding Java Virtual Machine instruction. */
 public void visitATHROW(ATHROW o) {
   Type t = stack().pop();
   stack().clear();
   if (t.equals(Type.NULL)) {
     stack().push(Type.getType("Ljava/lang/NullPointerException;"));
   } else {
     stack().push(t);
   }
 }
  private void hit(
      Subject targetSubject, Attack attack, double damageModifier, boolean criticalHit) {
    double typeModifier = attack.getAttackModifier(targetSubject);
    double STAB = 1;
    if (attack.getType().is(type.getType())) {
      STAB = 1.5;
    }
    double randNumber = dice.nextInt(151) / 1000 + 0.85;
    boolean superEffective = false;
    boolean notEffective = false;
    if (typeModifier == 2.0) {
      superEffective = true;
    } else if (typeModifier == 0.5) {
      notEffective = true;
    }
    int offence = 1;
    int defence = 1;

    offence = (attack.isPracticalAttack()) ? getPracticalOffence() : getTheoreticalOffence();
    defence =
        (attack.isPracticalDefence())
            ? targetSubject.getPracticalDefence()
            : targetSubject.getTheoreticalDefence();

    int damage =
        (int)
            Math.floor(
                ((2 * level + 10)
                            * attack.getDamage()
                            * offence
                            * damageAndHpMultiplier
                            / 250
                            / defence
                        + 2)
                    * damageModifier
                    * randNumber
                    * STAB
                    * typeModifier);

    String combatText =
        String.format("%s bruker %s! (%d skade)", nickname, attack.getName(), damage);

    if (criticalHit) {
      combatText += " (kritisk treff!)";
    }
    if (superEffective) {
      combatText += " (kjempeeffektivt!)";
    } else if (notEffective) {
      combatText += " (ikke så veldig effektivt!)";
    }

    DisplayText.add(nickname, combatText);

    targetSubject.takeDamage(damage);
  }
 private void writeManagedTypeStaticField(
     Type generatedType, Class<?> managedTypeClass, MethodVisitor constructorVisitor) {
   constructorVisitor.visitLdcInsn(Type.getType(managedTypeClass));
   constructorVisitor.visitMethodInsn(
       INVOKESTATIC, MODELTYPE_INTERNAL_NAME, "of", MODELTYPE_OF_METHOD_DESCRIPTOR, false);
   constructorVisitor.visitFieldInsn(
       PUTSTATIC,
       generatedType.getInternalName(),
       MANAGED_TYPE_FIELD_NAME,
       Type.getDescriptor(ModelType.class));
 }
Example #15
0
  /**
   * Instantiate from existing field.
   *
   * @param field Field object
   * @param cp constant pool (must contain the same entries as the field's constant pool)
   */
  public FieldGen(Field field, ConstantPoolGen cp) {
    this(field.getAccessFlags(), Type.getType(field.getSignature()), field.getName(), cp);

    Attribute[] attrs = field.getAttributes();

    for (int i = 0; i < attrs.length; i++) {
      if (attrs[i] instanceof ConstantValue)
        setValue(((ConstantValue) attrs[i]).getConstantValueIndex());
      else addAttribute(attrs[i]);
    }
  }
 private void writeDelegatedMethod(
     ClassVisitor visitor, Type generatedType, Type delegateType, Method method) {
   MethodVisitor methodVisitor =
       declareMethod(
           visitor,
           method.getName(),
           Type.getMethodDescriptor(method),
           AsmClassGeneratorUtils.signature(method));
   invokeDelegateMethod(methodVisitor, generatedType, delegateType, method);
   Class<?> returnType = method.getReturnType();
   finishVisitingMethod(methodVisitor, returnCode(Type.getType(returnType)));
 }
 @NotNull
 private static TypeInfo fieldTypeViaDescription(@NotNull String desc) {
   Type type = Type.getType(desc);
   final int dim = type.getSort() == Type.ARRAY ? type.getDimensions() : 0;
   if (dim > 0) {
     type = type.getElementType();
   }
   return new TypeInfo(
       getTypeText(type),
       (byte) dim,
       false,
       Collections.<PsiAnnotationStub>emptyList()); // todo read annos from .class file
 }
 // add assert startup code
 private void initAssertions(MethodVisitor mv) {
   mv.visitLdcInsn(Type.getType("L" + myClassName + ";"));
   mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Class", "desiredAssertionStatus", "()Z", false);
   Label l0 = new Label();
   mv.visitJumpInsn(IFNE, l0);
   mv.visitInsn(ICONST_1);
   Label l1 = new Label();
   mv.visitJumpInsn(GOTO, l1);
   mv.visitLabel(l0);
   mv.visitInsn(ICONST_0);
   mv.visitLabel(l1);
   mv.visitFieldInsn(PUTSTATIC, myClassName, ASSERTIONS_DISABLED_NAME, "Z");
 }
Example #19
0
  private static void checkLeakingParameters(Class<?> jClass) throws IOException {
    final HashMap<Method, boolean[]> map = new HashMap<Method, boolean[]>();

    // collecting leakedParameters
    final ClassReader classReader =
        new ClassReader(
            new FileInputStream(
                jClass.getResource("/" + jClass.getName().replace('.', '/') + ".class").getFile()));
    classReader.accept(
        new ClassVisitor(Opcodes.ASM5) {
          @Override
          public MethodVisitor visitMethod(
              int access, String name, String desc, String signature, String[] exceptions) {
            final MethodNode node =
                new MethodNode(Opcodes.ASM5, access, name, desc, signature, exceptions);
            final Method method = new Method(classReader.getClassName(), name, desc);
            return new MethodVisitor(Opcodes.ASM5, node) {
              @Override
              public void visitEnd() {
                super.visitEnd();
                try {
                  map.put(
                      method,
                      LeakingParameters.build(classReader.getClassName(), node, false).parameters);
                } catch (AnalyzerException ignore) {
                }
              }
            };
          }
        },
        ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);

    for (java.lang.reflect.Method jMethod : jClass.getDeclaredMethods()) {
      Method method =
          new Method(
              Type.getType(jClass).getInternalName(),
              jMethod.getName(),
              Type.getMethodDescriptor(jMethod));
      Annotation[][] annotations = jMethod.getParameterAnnotations();
      for (int i = 0; i < annotations.length; i++) {
        boolean isLeaking = false;
        Annotation[] parameterAnnotations = annotations[i];
        for (Annotation parameterAnnotation : parameterAnnotations) {
          if (parameterAnnotation.annotationType() == ExpectLeaking.class) {
            isLeaking = true;
          }
        }
        assertEquals(method.toString() + " #" + i, isLeaking, map.get(method)[i]);
      }
    }
  }
 private void invokeDelegateMethod(
     MethodVisitor methodVisitor, Type generatedType, Type delegateType, Method method) {
   putDelegateFieldValueOnStack(methodVisitor, generatedType, delegateType);
   Class<?>[] parameterTypes = method.getParameterTypes();
   for (int paramNo = 0; paramNo < parameterTypes.length; paramNo++) {
     putMethodArgumentOnStack(methodVisitor, Type.getType(parameterTypes[paramNo]), paramNo + 1);
   }
   methodVisitor.visitMethodInsn(
       INVOKEVIRTUAL,
       delegateType.getInternalName(),
       method.getName(),
       Type.getMethodDescriptor(method),
       false);
 }
Example #21
0
 public static void exportProducts(
     String fileName,
     List<Product> productList,
     Map<Type, List<Category>> typeMap,
     List<Procurement> procurementList) {
   logger.info("Export product to excel");
   ExcelGenerator generator = new ExcelGenerator(fileName);
   List<String[]> headerList = new ArrayList<>();
   List<String> sheetNames = new ArrayList<>();
   for (Type type : typeMap.keySet()) {
     sheetNames.add(type.getType());
     headerList.add(new String[] {"名字", "描述", "大类", "小类", "采购价", "系数", "销售价", "单位"});
   }
   List<List<String[]>> contents = new ArrayList<>();
   for (Type type : typeMap.keySet()) {
     List<Category> categoryList = typeMap.get(type);
     List<String[]> content = new ArrayList<>();
     for (Category category : categoryList) {
       List<Product> subProductList = getProductListByCategory(productList, category);
       for (Product product : subProductList) {
         Procurement procurement = getProcurement(procurementList, product.getId());
         double procprice = product.getPrice();
         double procindex = 1.0;
         if (procurement != null) {
           procprice = procurement.getProcprice();
           procindex = procurement.getProcindex();
         }
         content.add(
             new String[] {
               product.getName(),
               product.getDescription(),
               product.getType().getType(),
               product.getCategory().getCategory(),
               String.valueOf(procprice),
               String.valueOf(procindex),
               product.getPrice().toString(),
               product.getUnit()
             });
       }
     }
     contents.add(content);
   }
   try {
     generator.generate(sheetNames, headerList, contents);
   } catch (IOException e) {
     e.printStackTrace();
     return;
   }
 }
  private void writeToString(
      ClassVisitor visitor,
      Type generatedType,
      Class<?> viewClass,
      StructSchema<?> delegateSchema) {
    Method toStringMethod = getToStringMethod(viewClass);

    if (toStringMethod != null && !toStringMethod.getDeclaringClass().equals(Object.class)) {
      writeNonAbstractMethodWrapper(visitor, generatedType, viewClass, toStringMethod);
    } else if (delegateSchema != null && delegateSchema.hasProperty("displayName")) {
      writeDelegatingToString(
          visitor, generatedType, Type.getType(delegateSchema.getType().getConcreteClass()));
    } else {
      writeDefaultToString(visitor, generatedType);
    }
  }
  protected List<Board> exportBoards() {
    if (!this.running) return null;

    // get user configured column names and sql
    String colId = (String) this.properties.get(PROPKEY_BOARD_ID);
    String colCat = (String) this.properties.get(PROPKEY_BOARD_CAT);
    String colLevel = (String) this.properties.get(PROPKEY_BOARD_LEVEL);
    String colParent = (String) this.properties.get(PROPKEY_BOARD_PARENT);
    String colParentType = (String) this.properties.get(PROPKEY_BOARD_PARENTTYPE);
    String colName = (String) this.properties.get(PROPKEY_BOARD_NAME);
    String colDesc = (String) this.properties.get(PROPKEY_BOARD_DESC);
    String table = (String) this.properties.get(PROPKEY_BOARD_TABLE);
    String rawSql = (String) this.properties.get(PROPKEY_BOARD_SQL);
    // update sql to reflect user configured column names
    String sql = rawSql.replaceAll("\\Q{" + PROPKEY_BOARD_ID + "}\\E", colId);
    sql = sql.replaceAll("\\Q{" + PROPKEY_BOARD_CAT + "}\\E", colCat);
    sql = sql.replaceAll("\\Q{" + PROPKEY_BOARD_LEVEL + "}\\E", colLevel);
    sql = sql.replaceAll("\\Q{" + PROPKEY_BOARD_PARENT + "}\\E", colParent);
    sql = sql.replaceAll("\\Q{" + PROPKEY_BOARD_PARENTTYPE + "}\\E", colParentType);
    sql = sql.replaceAll("\\Q{" + PROPKEY_BOARD_NAME + "}\\E", colName);
    sql = sql.replaceAll("\\Q{" + PROPKEY_BOARD_DESC + "}\\E", colDesc);
    sql = sql.replaceAll("\\Q{" + PROPKEY_BOARD_TABLE + "}\\E", table);

    Vector<Board> boards = new Vector<Board>();

    ResultSet data = null;
    try {
      data = sql(sql);
      while (data.next()) { // get each category
        Board board = new Board();
        board.id = data.getString(colId);
        board.category = data.getString(colCat);
        board.level = data.getString(colLevel);
        board.parent = data.getString(colParent);
        board.parenttype = Type.getType(data.getString(colParentType));
        board.name = encode(data.getBytes(colName));
        board.description = encode(data.getBytes(colDesc));
        boards.add(board);
      }
    } catch (SQLException e) {
      log.error("Could not export Boards with sql: " + sql);
      e.printStackTrace();
      return null;
    }
    return boards;
  }
  private void writeDelegateMethods(
      final ClassVisitor visitor,
      final Type generatedType,
      StructSchema<?> delegateSchema,
      Set<Class<?>> typesToDelegate) {
    Class<?> delegateClass = delegateSchema.getType().getConcreteClass();
    Type delegateType = Type.getType(delegateClass);
    Map<Equivalence.Wrapper<Method>, Map<Class<?>, Method>> methodsToDelegate = Maps.newHashMap();
    for (Class<?> typeToDelegate : typesToDelegate) {
      for (Method methodToDelegate : typeToDelegate.getMethods()) {
        if (ModelSchemaUtils.isIgnoredMethod(methodToDelegate)) {
          continue;
        }
        Equivalence.Wrapper<Method> methodKey = METHOD_EQUIVALENCE.wrap(methodToDelegate);
        Map<Class<?>, Method> methodsByReturnType = methodsToDelegate.get(methodKey);
        if (methodsByReturnType == null) {
          methodsByReturnType = Maps.newHashMap();
          methodsToDelegate.put(methodKey, methodsByReturnType);
        }
        methodsByReturnType.put(methodToDelegate.getReturnType(), methodToDelegate);
      }
    }
    Set<Equivalence.Wrapper<Method>> delegateMethodKeys =
        ImmutableSet.copyOf(
            Iterables.transform(
                Arrays.asList(delegateClass.getMethods()),
                new Function<Method, Equivalence.Wrapper<Method>>() {
                  @Override
                  public Equivalence.Wrapper<Method> apply(Method method) {
                    return METHOD_EQUIVALENCE.wrap(method);
                  }
                }));
    for (Map.Entry<Equivalence.Wrapper<Method>, Map<Class<?>, Method>> entry :
        methodsToDelegate.entrySet()) {
      Equivalence.Wrapper<Method> methodKey = entry.getKey();
      if (!delegateMethodKeys.contains(methodKey)) {
        continue;
      }

      Map<Class<?>, Method> methodsByReturnType = entry.getValue();
      for (Method methodToDelegate : methodsByReturnType.values()) {
        writeDelegatedMethod(visitor, generatedType, delegateType, methodToDelegate);
      }
    }
  }
Example #25
0
 public static void main(String[] args) {
   Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
   (new MatsimPopulationReader(scenario)).parse(args[0]);
   Population population = null;
   switch (Type.getType(args[1])) {
     case ID:
       population = getPopulationTypesId(scenario, args);
       break;
     case TRANSIT_LINE:
       population = getPopulationTypesTransitLine(scenario, args);
       break;
     case SOCIAL:
       population = getPopulationTypesSocial(scenario, args);
       break;
   }
   (new MatsimNetworkReader(scenario.getNetwork())).readFile(args[2]);
   (new PopulationWriter(population)).write(args[3]);
 }
      private String getMethodDescr(final Object value) {
        if (value instanceof Type) {
          return "()Ljava/lang/Class;";
        }

        final String name = Type.getType(value.getClass()).getInternalName();

        if (name.equals("java/lang/Integer")) {
          return "()I;";
        }

        if (name.equals("java/lang/Short")) {
          return "()S;";
        }

        if (name.equals("java/lang/Long")) {
          return "()J;";
        }

        if (name.equals("java/lang/Byte")) {
          return "()B;";
        }

        if (name.equals("java/lang/Char")) {
          return "()C;";
        }

        if (name.equals("java/lang/Boolean")) {
          return "()Z;";
        }

        if (name.equals("java/lang/Float")) {
          return "()F;";
        }

        if (name.equals("java/lang/Double")) {
          return "()D;";
        }

        final String s = "()L" + name + ";";

        return s;
      }
Example #27
0
 @RequestMapping(value = "/type_map", method = RequestMethod.GET)
 public @ResponseBody JSONArray getTypeMap() {
   JSONArray jsonArray = new JSONArray();
   Map<Type, List<Category>> typeMap = productService.getTypeMap();
   for (Type key : typeMap.keySet()) {
     List<Category> categoryList = typeMap.get(key);
     JSONArray categoryJsonArray = new JSONArray();
     for (Category category : categoryList) {
       JSONObject jsonObject = new JSONObject();
       jsonObject.put("key", category.getCategory());
       jsonObject.put("value", category.toString());
       categoryJsonArray.add(jsonObject);
     }
     JSONObject jsonObject = new JSONObject();
     jsonObject.put("name", key.getType());
     jsonObject.put("value", key.toString());
     jsonObject.put("list", categoryJsonArray);
     jsonArray.add(jsonObject);
   }
   return jsonArray;
 }
 private void unboxType(MethodVisitor methodVisitor, Class<?> primitiveClass) {
   // Float f = (Float) tmp
   // f==null?0:f.floatValue()
   Class<?> boxedType = BOXED_TYPES.get(primitiveClass);
   Type primitiveType = Type.getType(primitiveClass);
   methodVisitor.visitTypeInsn(CHECKCAST, Type.getInternalName(boxedType));
   methodVisitor.visitInsn(DUP);
   Label exit = new Label();
   Label elseValue = new Label();
   methodVisitor.visitJumpInsn(IFNONNULL, elseValue);
   methodVisitor.visitInsn(POP);
   pushDefaultValue(methodVisitor, primitiveClass);
   methodVisitor.visitJumpInsn(GOTO, exit);
   methodVisitor.visitLabel(elseValue);
   methodVisitor.visitMethodInsn(
       INVOKEVIRTUAL,
       Type.getInternalName(boxedType),
       primitiveClass.getSimpleName() + "Value",
       Type.getMethodDescriptor(primitiveType),
       false);
   methodVisitor.visitLabel(exit);
 }
  private void writeGetters(ClassVisitor visitor, Type generatedType, ModelProperty<?> property) {
    Class<?> propertyClass = property.getType().getConcreteClass();
    Type propertyType = Type.getType(propertyClass);
    Set<String> processedNames = Sets.newHashSet();
    for (WeaklyTypeReferencingMethod<?, ?> weakGetter : property.getGetters()) {
      Method getter = weakGetter.getMethod();
      if (!processedNames.add(getter.getName())) {
        continue;
      }
      MethodVisitor methodVisitor =
          declareMethod(
              visitor,
              getter.getName(),
              Type.getMethodDescriptor(propertyType),
              AsmClassGeneratorUtils.signature(getter));

      putStateFieldValueOnStack(methodVisitor, generatedType);
      putConstantOnStack(methodVisitor, property.getName());
      invokeStateGetMethod(methodVisitor);
      castFirstStackElement(methodVisitor, propertyClass);
      finishVisitingMethod(methodVisitor, returnCode(propertyType));
    }
  }
 @Override
 public void visitInvokeDynamicInsn(String name, String desc, Handle bsm, Object... bsmArgs) {
   if (bsm.getOwner().equals(LambdaNaming.LAMBDA_METAFACTORY)) {
     backportLambda(name, Type.getType(desc), bsm, bsmArgs);
   } else {
     super.visitInvokeDynamicInsn(name, desc, bsm, bsmArgs);
   }
 }