Example #1
0
 @Override
 public Type getFieldTypes() {
   if (hasFieldNames()) {
     return TypeFactory.getInstance().tupleType(fKeyType, fKeyLabel, fValueType, fValueLabel);
   } else {
     return TypeFactory.getInstance().tupleType(fKeyType, fValueType);
   }
 }
 // for [databind#1301]
 public void testJavaTypeToString() throws Exception {
   TypeFactory tf = objectMapper().getTypeFactory();
   String desc = tf.constructType(DataDefinition.class).toString();
   assertNotNull(desc);
   // could try comparing exact message, but since it's informational try looser:
   if (!desc.contains("map type")) {
     fail("Description should contain 'map type', did not: " + desc);
   }
   if (!desc.contains("recursive type")) {
     fail("Description should contain 'recursive type', did not: " + desc);
   }
 }
Example #3
0
 @Override
 public Type instantiate(Map<Type, Type> bindings) {
   if (fKeyLabel != null) {
     return TypeFactory.getInstance()
         .mapType(
             getKeyType().instantiate(bindings),
             fKeyLabel,
             getValueType().instantiate(bindings),
             fValueLabel);
   } else {
     return TypeFactory.getInstance()
         .mapType(getKeyType().instantiate(bindings), getValueType().instantiate(bindings));
   }
 }
  String getContent(String identifier) throws Exception {
    logger.trace("Searching for '{}' in cache.", identifier);
    ResourceWrapper wrapper = resources.get(identifier);

    // If not in cache yet, load it
    if (wrapper == null) {
      long start = System.currentTimeMillis();
      logger.debug("'{}' not in cache. Loading and processing...", identifier);
      String extension = FilenameUtils.getExtension(identifier);

      Type type = TypeFactory.getType(extension);
      if (type == null) {
        logger.warn("No type available for the specified resource: {}", extension);
        throw new UnknownTypeException(
            "No type available for the specified resource: " + extension);
      }

      String content = processContent(loader.loadResource(identifier), type);
      wrapper = new ResourceWrapper(identifier, type, content);
      resources.put(identifier, wrapper);
      logger.debug("Resource loaded and processed in {} ms.", System.currentTimeMillis() - start);
    } else {
      // If in cache, check last modified
      if (wrapper.getLastLoaded() < loader.lastModified(identifier)) {
        // If last loaded was before last modified, load it again
        wrapper.setContent(loader.loadResource(identifier));
      }
    }

    return wrapper.getContent();
  }
 protected JavaType parseType(MyTokenizer tokens) throws IllegalArgumentException {
   if (!tokens.hasMoreTokens()) {
     throw _problem(tokens, "Unexpected end-of-string");
   }
   Class<?> base = findClass(tokens.nextToken(), tokens);
   // either end (ok, non generic type), or generics
   if (tokens.hasMoreTokens()) {
     String token = tokens.nextToken();
     if ("<".equals(token)) {
       return _factory._fromParameterizedClass(base, parseTypes(tokens));
     }
     // can be comma that separates types, or closing '>'
     tokens.pushBack(token);
   }
   return _factory._fromClass(base, null);
 }
Example #6
0
 /** @see jaskell.compiler.JaskellVisitor#visit(ConstructorPattern) */
 public Object visit(ConstructorPattern a) {
   String cname = a.getConstructor().getName();
   /* retrieve parameter types of constructor */
   ConstructorDefinition ctor = (ConstructorDefinition) a.getConstructor().lookup(cname);
   if (ctor == null) throw new TypeError("Undefined constructor pattern  " + a);
   /* type of data constructed by constructor */
   TypeInstantiator ti = new TypeInstantiator(ctor.getDataType());
   Type rtype = ti.instance();
   Map map = ti.getMap();
   TypeSubstitution ts = new TypeSubstitution(map);
   Iterator ittypes = ctor.getParameters().iterator();
   /* retrieve type of patterns */
   Iterator it = a.getSubPatterns();
   while (it.hasNext()) {
     try {
       Pattern p = (Pattern) it.next();
       Type actual = TypeFactory.freshBinding();
       Type formal = ts.substitute((Type) ittypes.next());
       /* unify both types */
       p.setType(tu.unify(formal, actual, typeVariablesMap));
     } catch (NoSuchElementException nex) {
       throw new TypeError("Wrong number of arguments to pattern " + a);
     }
   }
   a.setType(rtype);
   return a.getType();
 }
Example #7
0
    public AddElementDialog(MapFilterModel model) {
      super(
          tufts.vue.VUE.getDialogParentAsFrame(),
          VueResources.getString("dialog.addkey.title"),
          true);
      this.model = model;
      allTypes = (Vector) TypeFactory.getAllTypes();
      keyLabel = new JLabel(VueResources.getString("nodefilter.field.label"));
      typeLabel = new JLabel(VueResources.getString("nodefilter.type.label"));
      keyEditor = new JTextField();
      typeEditor = new JComboBox(allTypes);
      keyEditor.setPreferredSize(new Dimension(80, 20));
      JPanel keyPanel = new JPanel();
      keyPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
      keyPanel.setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6));
      keyPanel.add(keyLabel);
      keyPanel.add(keyEditor);

      JPanel typePanel = new JPanel();
      typePanel.setLayout(new FlowLayout(FlowLayout.CENTER));
      typePanel.setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6));
      typePanel.add(typeLabel);
      typePanel.add(typeEditor);

      // SOUTH: southPanel(cancelButton, okButton)

      JButton okButton = new JButton(VueResources.getString("button.ok.label"));
      okButton.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              updateModelAndNotify();
              setVisible(false);
            }
          });

      JButton cancelButton = new JButton(VueResources.getString("button.cancel.lable"));
      cancelButton.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              setVisible(false);
            }
          });

      JPanel southPanel = new JPanel();
      southPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
      southPanel.add(okButton);
      southPanel.add(cancelButton);
      BoxLayout layout = new BoxLayout(getContentPane(), BoxLayout.Y_AXIS);

      getContentPane().setLayout(layout);
      getContentPane().add(keyPanel);
      getContentPane().add(typePanel);
      getContentPane().add(southPanel);
      pack();
      setLocation(NodeFilterEditor.this.getLocationOnScreen());
      setVisible(true);
    }
 private Type getType(Class<?> cl, String propertyName) throws NoSuchMethodException {
   try {
     Field field = cl.getDeclaredField(propertyName);
     return typeFactory.create(field.getType(), field.getGenericType());
   } catch (NoSuchFieldException e) {
     String getter = "get" + BeanUtils.capitalize(propertyName);
     String bgetter = "is" + BeanUtils.capitalize(propertyName);
     for (Method method : cl.getDeclaredMethods()) {
       if ((method.getName().equals(getter) || method.getName().equals(bgetter))
           && method.getParameterTypes().length == 0) {
         return typeFactory.create(method.getReturnType(), method.getGenericReturnType());
       }
     }
     if (cl.getSuperclass().equals(Object.class)) {
       throw new IllegalArgumentException(
           "No property found for " + cl.getName() + "." + propertyName);
     } else {
       return getType(cl.getSuperclass(), propertyName);
     }
   }
 }
Example #9
0
 /** @see jaskell.compiler.JaskellVisitor#visit(Application) */
 public Object visit(Application a) {
   try {
     /* get type of function */
     Expression fun = a.getFunction();
     /* get type deduced from arguments */
     LinkedList l = new LinkedList();
     Iterator it = a.getArgs().iterator();
     while (it.hasNext()) {
       Expression e = (Expression) it.next();
       l.add((Type) e.visit(this));
     }
     Type vt = TypeFactory.freshBinding();
     Type ft = Types.fun(l, vt);
     log.finer("TypeChecker => In application " + a + ", type is " + ft);
     /* apply substitution on both types */
     ft = subst.substitute(ft);
     /* try to unify function type and constructed types */
     Type t = (Type) fun.visit(this);
     log.finer("In application, function " + fun + " :: " + t);
     t = subst.substitute(t);
     log.finer("In application, trying to unify function type " + t + " with body " + ft);
     /*
      * TODO : problem with unification of constrained types
      */
     TypeApplication uni = (TypeApplication) tu.unify(t, ft, typeVariablesMap);
     /* sets type of functional expression - this allows
      * polymorphic functions to receive several types
      * in the same code */
     // fun.setType(uni);
     /* apply arguments type to compute return type */
     log.finer("Done unify application :" + uni);
     it = PrimitiveType.functionIterator(uni);
     Iterator it2 = l.iterator();
     TypeApplication ut = uni;
     while (it2.hasNext()) {
       /* type of argument */
       Type at = (Type) it2.next();
       ut = (TypeApplication) it.next();
       /* try unification */
       tu.unify(((TypeApplication) ut.getDomain()).getRange(), at, new HashMap(typeVariablesMap));
     }
     ft = subst.substitute(ft);
     fun.setType(ft);
     log.finer("Setting type of functional element [" + fun + "] to :" + ft);
     a.setType(ut.getRange());
     return ut.getRange();
   } catch (TypeError te) {
     if (te.getLineCol() == null) te.setLineCol(a.getTag("source"));
     throw te;
   }
 }
Example #10
0
 /** @see jaskell.compiler.JaskellVisitor#visit(Abstraction) */
 public Object visit(Abstraction a) {
   try {
     Type t = a.getType();
     if (t != null) return subst.substitute(t);
     log.finest("Visiting abstraction : " + a);
     Expression body = a.getBody();
     /* duplicate bindings map to assign types to variables */
     pushContext(a.getBindings());
     /* create fresh type variables as type for each bound
      * variable */
     Iterator it = namesMap.values().iterator();
     LinkedList tl = new LinkedList();
     while (it.hasNext()) {
       LocalBinding name = (LocalBinding) it.next();
       Type vt = TypeFactory.freshBinding();
       name.setType(vt);
       tl.add(vt);
     }
     Type tv = TypeFactory.freshBinding();
     /* create type with all variables for function */
     Type ft = Types.fun(tl, tv);
     log.finer("In abstraction, setting type to " + ft);
     a.setType(ft);
     /* analyze body */
     Type bt = (Type) body.visit(this);
     /* unify return type of function with type of body */
     Type ret = tu.unify(PrimitiveType.getReturnType(ft), bt, typeVariablesMap);
     TyvarSubstitution tys = new TyvarSubstitution(typeVariablesMap);
     tys.visit(a);
     log.finer("Done abstraction, setting type from " + ft + " to " + a.getType());
     popContext();
     return a.getType();
   } catch (TypeError te) {
     if (te.getLineCol() == null) te.setLineCol(a.getTag("source"));
     throw te;
   }
 }
Example #11
0
  public static Type createType(
      String baseTypeStr,
      List<Type> typeParams,
      List<Integer> valueParams,
      List<Field> fieldParams) {
    final TajoDataTypes.Type baseType;

    try {
      baseType = TajoDataTypes.Type.valueOf(baseTypeStr);
    } catch (Throwable t) {
      throw new TajoInternalError(new UnsupportedException(baseTypeStr));
    }

    return TypeFactory.create(baseType, typeParams, valueParams, fieldParams);
  }
Example #12
0
  /**
   * Wenn <code>true</code> zurueckgegeben wird ist das zeichen vor dem offset ein : und das Zeichen
   * davor kein Whitespace.
   */
  private boolean isQualifiedSymbolProposal(final IDocument doc, final int offset)
      throws BadLocationException {
    int wordOffset = skipWhitespace(doc, offset);
    String word = computePreviousWord(doc, wordOffset);

    if (word == null || word.equals("")) {
      return false;
    }

    Symbol sym = TypeFactory.createSymbol(word, null);
    if (sym.isQualified()) {
      fContextPackage = sym.getQualifier();
      fContextWord = sym.getSymbolName();
      return true;
    }
    return false;
  }
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String[] files = request.getParameterValues("file");
    if (logger.isDebugEnabled()) {
      logger.debug("Resource servlet received request to load files: {}", Arrays.toString(files));
    }

    if (files == null || files.length == 0) {
      logger.warn("No resource specified, 'file' parameter is empty.");
      response.sendError(
          HttpServletResponse.SC_BAD_REQUEST, "No resource specified, 'file' parameter is empty.");
      return;
    }

    try {
      String requestedExtension = FilenameUtils.getExtension(request.getRequestURI());
      logger.trace("Request done with extension {}", requestedExtension);

      String answer = null;
      if ("json".equals(requestedExtension)) {
        /* If extension was .json, then it will return all resources as
         * a JSON object.
         */
        response.setContentType(CONTENT_TYPE_JSON);
        answer = renderContentAsJson(files);
      } else {
        // Any other extension will set content type for the type of the first file requested
        response.setContentType(
            TypeFactory.getType(FilenameUtils.getExtension(files[0])).getContentType());
        answer = renderContentAsText(files);
      }

      logger.trace("--- Sending response to client ---\n{}", answer);
      response.getWriter().write(answer);
    } catch (ResourceNotFoundException ex) {
      response.sendError(
          HttpServletResponse.SC_NOT_FOUND, "Resource not found: " + ex.getMessage());
      logger.warn("Resource not found.", ex);
    } catch (Exception ex) {
      response.sendError(
          HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
          "Error while loading resource: " + ex.getMessage());
      logger.error("Error while loading resoruce.", ex);
    }
  }
 public HibernateDomainExporter(
     String namePrefix,
     String nameSuffix,
     File targetFolder,
     SerializerConfig serializerConfig,
     Configuration configuration) {
   this.targetFolder = targetFolder;
   this.serializerConfig = serializerConfig;
   this.configuration = configuration;
   CodegenModule module = new CodegenModule();
   module.bind(CodegenModule.PREFIX, namePrefix);
   module.bind(CodegenModule.SUFFIX, nameSuffix);
   module.bind(CodegenModule.KEYWORDS, Constants.keywords);
   this.queryTypeFactory = module.get(QueryTypeFactory.class);
   this.typeMappings = module.get(TypeMappings.class);
   this.embeddableSerializer = module.get(EmbeddableSerializer.class);
   this.entitySerializer = module.get(EntitySerializer.class);
   this.supertypeSerializer = module.get(SupertypeSerializer.class);
   typeFactory.setUnknownAsEntity(true);
 }
Example #15
0
 /** Returns the set of all supertypes (including this type). */
 public Set<Type> allSupertypes() {
   Set<Type> res = new HashSet<Type>(2);
   res.add(TypeFactory.mkOclAny());
   res.add(this);
   return res;
 }
 /**
  * Begin a new mapping for the specified type and class.
  *
  * @param aType
  * @param bType
  * @return a new ClassMapBuilder instance for the specified types
  */
 public <A, B> ClassMapBuilder<A, B> map(Type<A> aType, Class<B> bType) {
   return getNewClassMapBuilder(aType, TypeFactory.<B>valueOf(bType));
 }
 /**
  * Begin a new mapping for the specified class and type.
  *
  * @param aType
  * @param bType
  * @return a new ClassMapBuilder instance for the specified types
  */
 public <A, B> ClassMapBuilder<A, B> map(Class<A> aType, Type<B> bType) {
   return getNewClassMapBuilder(TypeFactory.<A>valueOf(aType), bType);
 }
Example #18
0
 @Test
 public void HidaBezGruppe() {
   TypeFactory typeFactory = new TypeFactory();
   Type type = typeFactory.createEntityType(HidaBezGruppe.class);
   System.out.println(type.getGenericName(true));
 }
Example #19
0
 @Override
 public Type select(int... fields) {
   return TypeFactory.getInstance().setType(getFieldTypes().select(fields));
 }
Example #20
0
 public JavaType resolveType(Class<?> cls) {
   return _typeFactory._constructType(cls, this);
 }
 public static ActivityObjectType comment() {
   return standardTypes.newType("comment");
 }
 @Override
 public Type getTypeParameters() {
   return TypeFactory.getInstance().voidType();
 }
Example #23
0
  protected void _resolveBindings(Type t) {
    if (t == null) return;

    Class<?> raw;
    if (t instanceof ParameterizedType) {
      ParameterizedType pt = (ParameterizedType) t;
      Type[] args = pt.getActualTypeArguments();
      if (args != null && args.length > 0) {
        Class<?> rawType = (Class<?>) pt.getRawType();
        TypeVariable<?>[] vars = rawType.getTypeParameters();
        if (vars.length != args.length) {
          throw new IllegalArgumentException(
              "Strange parametrized type (in class "
                  + rawType.getName()
                  + "): number of type arguments != number of type parameters ("
                  + args.length
                  + " vs "
                  + vars.length
                  + ")");
        }
        for (int i = 0, len = args.length; i < len; ++i) {
          TypeVariable<?> var = vars[i];
          String name = var.getName();
          if (_bindings == null) {
            _bindings = new LinkedHashMap<String, JavaType>();
          } else {
            /* 24-Mar-2010, tatu: Better ensure that we do not overwrite something
             *  collected earlier (since we descend towards super-classes):
             */
            if (_bindings.containsKey(name)) continue;
          }
          // first: add a placeholder to prevent infinite loops
          _addPlaceholder(name);
          // then resolve type
          _bindings.put(name, _typeFactory._constructType(args[i], this));
        }
      }
      raw = (Class<?>) pt.getRawType();
    } else if (t instanceof Class<?>) {
      raw = (Class<?>) t;
      /* [JACKSON-677]: If this is an inner class then the generics are defined on the
       * enclosing class so we have to check there as well.  We don't
       * need to call getEnclosingClass since anonymous classes declare
       * generics
       */
      _resolveBindings(raw.getDeclaringClass());
      /* 24-Mar-2010, tatu: Can not have true generics definitions, but can
       *   have lower bounds ("<T extends BeanBase>") in declaration itself
       */
      TypeVariable<?>[] vars = raw.getTypeParameters();
      if (vars != null && vars.length > 0) {
        JavaType[] typeParams = null;

        if (_contextType != null && raw.isAssignableFrom(_contextType.getRawClass())) {
          typeParams = _typeFactory.findTypeParameters(_contextType, raw);
        }

        for (int i = 0; i < vars.length; i++) {
          TypeVariable<?> var = vars[i];

          String name = var.getName();
          Type varType = var.getBounds()[0];
          if (varType != null) {
            if (_bindings == null) {
              _bindings = new LinkedHashMap<String, JavaType>();
            } else { // and no overwriting...
              if (_bindings.containsKey(name)) continue;
            }
            _addPlaceholder(name); // to prevent infinite loops

            if (typeParams != null) {
              _bindings.put(name, typeParams[i]);
            } else {
              _bindings.put(name, _typeFactory._constructType(varType, this));
            }
          }
        }
      }
    } else { // probably can't be any of these... so let's skip for now
      // if (type instanceof GenericArrayType) {
      // if (type instanceof TypeVariable<?>) {
      // if (type instanceof WildcardType) {
      return;
    }
    // but even if it's not a parameterized type, its super types may be:
    _resolveBindings(raw.getGenericSuperclass());
    for (Type intType : raw.getGenericInterfaces()) {
      _resolveBindings(intType);
    }
  }
 /** For encoding an external value as an ADT we need a representative type */
 public Type asAbstractDataType() {
   return TypeFactory.getInstance().abstractDataType(store, getName());
 }
 public static ActivityObjectType status() {
   return standardTypes.newType("status");
 }
Example #26
0
 @Override
 public Type select(String... names) {
   return TypeFactory.getInstance().setType(getFieldTypes().select(names));
 }
Example #27
0
    public AddDialog(NodeFilter model) {
      super(
          tufts.vue.VUE.getDialogParentAsFrame(),
          VueResources.getString("dialog.addkey.title"),
          true);
      this.model = model;
      allTypes = (Vector) TypeFactory.getAllTypes();
      keyLabel = new JLabel(VueResources.getString("button.key.label"));
      typeLabel = new JLabel(VueResources.getString("nodefilter.type.label"));
      operatorLabel = new JLabel(VueResources.getString("nodefilter.operator.label"));
      valueLabel = new JLabel(VueResources.getString("nodefilter.value.label"));
      keyEditor = new JComboBox(tufts.vue.VUE.getActiveMap().getMapFilterModel().getKeyVector());

      operatorEditor = new JComboBox();
      valueEditor = new JTextField();
      typeEditor = new JTextField();
      typeEditor.setEditable(false);

      keyEditor.setPreferredSize(new Dimension(80, 20));

      GridBagLayout gridbag = new GridBagLayout();
      GridBagConstraints c = new GridBagConstraints();
      c.insets = new Insets(2, 2, 2, 2);
      JPanel panel = new JPanel();
      panel.setLayout(gridbag);

      c.anchor = GridBagConstraints.EAST;
      c.gridwidth = GridBagConstraints.RELATIVE;
      gridbag.setConstraints(keyLabel, c);
      panel.add(keyLabel);

      c.anchor = GridBagConstraints.WEST;
      c.gridwidth = GridBagConstraints.REMAINDER;
      gridbag.setConstraints(keyEditor, c);
      panel.add(keyEditor);

      c.anchor = GridBagConstraints.EAST;
      c.gridwidth = GridBagConstraints.RELATIVE;
      gridbag.setConstraints(operatorLabel, c);
      panel.add(operatorLabel);

      c.anchor = GridBagConstraints.WEST;
      c.gridwidth = GridBagConstraints.REMAINDER;
      gridbag.setConstraints(operatorEditor, c);
      panel.add(operatorEditor);

      c.anchor = GridBagConstraints.EAST;
      c.gridwidth = GridBagConstraints.RELATIVE;
      gridbag.setConstraints(valueLabel, c);
      panel.add(valueLabel);

      c.anchor = GridBagConstraints.WEST;
      c.gridwidth = GridBagConstraints.REMAINDER;
      c.fill = GridBagConstraints.HORIZONTAL;
      gridbag.setConstraints(valueEditor, c);
      panel.add(valueEditor);

      c.anchor = GridBagConstraints.EAST;
      c.fill = GridBagConstraints.NONE;
      c.gridwidth = GridBagConstraints.RELATIVE;
      gridbag.setConstraints(typeLabel, c);
      panel.add(typeLabel);

      c.anchor = GridBagConstraints.WEST;
      c.gridwidth = GridBagConstraints.REMAINDER;
      c.fill = GridBagConstraints.HORIZONTAL;
      gridbag.setConstraints(typeEditor, c);
      panel.add(typeEditor);

      // SOUTH: southPanel(cancelButton, okButton)

      JButton okButton = new JButton(VueResources.getString("button.ok.label"));
      okButton.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              updateModelAndNotify();
              setVisible(false);
            }
          });

      JButton cancelButton = new JButton(VueResources.getString("button.cancel.lable"));
      cancelButton.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              setVisible(false);
            }
          });

      JPanel southPanel = new JPanel();
      southPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
      southPanel.add(okButton);
      southPanel.add(cancelButton);

      c.gridwidth = GridBagConstraints.REMAINDER;
      gridbag.setConstraints(southPanel, c);
      panel.add(southPanel);

      getContentPane().setLayout(new BorderLayout());
      getContentPane().add(panel, BorderLayout.CENTER);

      pack();
      setLocation(500, 300);
      setVisible(true);
    }
Example #28
0
 public JavaType resolveType(Type type) {
   return _typeFactory._constructType(type, this);
 }
 public static ActivityObjectType file() {
   return standardTypes.newType("file");
 }
Example #30
0
 @Override
 public Type carrier() {
   TypeFactory tf = TypeFactory.getInstance();
   return tf.setType(fKeyType.lub(fValueType));
 }