Exemple #1
1
 /**
  * Factory method, equivalent to a "fromXML" for step creation. Looks for a class with the same
  * name as the XML tag, with the first letter capitalized. For example, <call /> is
  * abbot.script.Call.
  */
 public static Step createStep(Resolver resolver, Element el) throws InvalidScriptException {
   String tag = el.getName();
   Map attributes = createAttributeMap(el);
   String name = tag.substring(0, 1).toUpperCase() + tag.substring(1);
   if (tag.equals(TAG_WAIT)) {
     attributes.put(TAG_WAIT, "true");
     name = "Assert";
   }
   try {
     name = "abbot.script." + name;
     Log.debug("Instantiating " + name);
     Class cls = Class.forName(name);
     try {
       // Steps with contents require access to the XML element
       Class[] argTypes = new Class[] {Resolver.class, Element.class, Map.class};
       Constructor ctor = cls.getConstructor(argTypes);
       return (Step) ctor.newInstance(new Object[] {resolver, el, attributes});
     } catch (NoSuchMethodException nsm) {
       // All steps must support this ctor
       Class[] argTypes = new Class[] {Resolver.class, Map.class};
       Constructor ctor = cls.getConstructor(argTypes);
       return (Step) ctor.newInstance(new Object[] {resolver, attributes});
     }
   } catch (ClassNotFoundException cnf) {
     String msg = Strings.get("step.unknown_tag", new Object[] {tag});
     throw new InvalidScriptException(msg);
   } catch (InvocationTargetException ite) {
     Log.warn(ite);
     throw new InvalidScriptException(ite.getTargetException().getMessage());
   } catch (Exception exc) {
     Log.warn(exc);
     throw new InvalidScriptException(exc.getMessage());
   }
 }
Exemple #2
0
  private Object getExplicitFunction(
      Scriptable scope, String name, Object javaObject, boolean isStatic) {
    Map<String, Object> ht = isStatic ? staticMembers : members;
    Object member = null;
    MemberBox methodOrCtor = findExplicitFunction(name, isStatic);

    if (methodOrCtor != null) {
      Scriptable prototype = ScriptableObject.getFunctionPrototype(scope);

      if (methodOrCtor.isCtor()) {
        NativeJavaConstructor fun = new NativeJavaConstructor(methodOrCtor);
        fun.setPrototype(prototype);
        member = fun;
        ht.put(name, fun);
      } else {
        String trueName = methodOrCtor.getName();
        member = ht.get(trueName);

        if (member instanceof NativeJavaMethod && ((NativeJavaMethod) member).methods.length > 1) {
          NativeJavaMethod fun = new NativeJavaMethod(methodOrCtor, name);
          fun.setPrototype(prototype);
          ht.put(name, fun);
          member = fun;
        }
      }
    }

    return member;
  }
  static {
    try {
      Map<String, Method> orderedMethods = new TreeMap<String, Method>();
      for (Method m : MBeanServerConnection.class.getDeclaredMethods()) {
        orderedMethods.put(m.toGenericString(), m);
      }
      Method[] methods = orderedMethods.values().toArray(new Method[orderedMethods.size()]);
      Map<String, Method> asynchMethods = new TreeMap<String, Method>();
      for (Method asynchMethod : AsynchJMXResponseListener.class.getDeclaredMethods()) {
        asynchMethods.put(asynchMethod.getName(), asynchMethod);
      }

      Map<Method, Byte> m2k = new HashMap<Method, Byte>(methods.length);
      Map<Byte, Method> k2m = new HashMap<Byte, Method>(methods.length);
      Map<Byte, Method> k2am = new HashMap<Byte, Method>(methods.length);
      for (int i = 0; i < methods.length; i++) {
        m2k.put(methods[i], (byte) i);
        k2m.put((byte) i, methods[i]);
        Method asynchMethod = asynchMethods.get(methods[i].getName() + "Response");
        if (asynchMethod == null)
          throw new RuntimeException(
              "Failed to find asynch handler for [" + methods[i].toGenericString() + "]",
              new Throwable());
        k2am.put((byte) i, asynchMethod);
      }
      methodToKey = Collections.unmodifiableMap(m2k);
      keyToMethod = Collections.unmodifiableMap(k2m);
      keyToAsynchMethod = Collections.unmodifiableMap(k2am);
    } catch (Exception ex) {
      throw new RuntimeException(ex);
    }
  }
  /**
   * @param ctx Kernal context.
   * @param cfg Ignite configuration.
   * @param providers Plugin providers.
   */
  @SuppressWarnings("TypeMayBeWeakened")
  public IgnitePluginProcessor(
      GridKernalContext ctx, IgniteConfiguration cfg, List<PluginProvider> providers) {
    super(ctx);

    ExtensionRegistryImpl registry = new ExtensionRegistryImpl();

    for (PluginProvider provider : providers) {
      GridPluginContext pluginCtx = new GridPluginContext(ctx, cfg);

      if (F.isEmpty(provider.name())) throw new IgniteException("Plugin name can not be empty.");

      if (plugins.containsKey(provider.name()))
        throw new IgniteException("Duplicated plugin name: " + provider.name());

      plugins.put(provider.name(), provider);

      pluginCtxMap.put(provider, pluginCtx);

      provider.initExtensions(pluginCtx, registry);

      if (provider.plugin() == null) throw new IgniteException("Plugin is null.");
    }

    extensions = registry.createExtensionMap();
  }
  private void generateView(
      Map<String, DesignDocument.View> views, Method me, Class<?> handledType) {
    String name = me.getName();
    if (!name.startsWith("findBy") && !name.equals("getAll")) {
      throw new ViewGenerationException(
          String.format(
              "The method: %s in %s annotated with GenerateView does not conform to the naming convention of 'findByXxxx'",
              name, me.getDeclaringClass()));
    }

    Class<?> type = resolveReturnType(me);
    if (type == null) {
      if (handledType != null) {
        type = handledType;
      } else {
        throw new ViewGenerationException(
            "Could not resolve return type for method: %s in %s",
            me.getName(), me.getDeclaringClass());
      }
    }

    String typeDiscriminator = resolveTypeDiscriminator(type);

    if (name.equals("getAll")) {
      if (typeDiscriminator.length() < 1) {
        throw new ViewGenerationException(
            String.format(
                "Cannot generate 'all' view for %s. No type discriminator could be resolved. Try annotate unique field(s) with @TypeDiscriminator",
                type.getDeclaringClass()));
      }
      views.put("all", generateAllView(typeDiscriminator));
      return;
    }

    String finderName = name.substring(6);
    String fieldName = resolveFieldName(me, finderName);
    Method getter = findMethod(type, "get" + fieldName);
    if (getter == null) {
      // try pluralis
      fieldName += "s";
      getter = findMethod(type, "get" + fieldName);
    }
    if (getter == null) {
      throw new ViewGenerationException(
          "Could not generate view for method %s. No get method found for property %s in %s",
          name, name.substring(6), type);
    }

    fieldName = firstCharToLowerCase(fieldName);

    DesignDocument.View view;
    if (isIterable(getter.getReturnType())) {
      view = generateFindByIterableView(fieldName, typeDiscriminator);
    } else {
      view = generateFindByView(fieldName, typeDiscriminator);
    }

    views.put("by_" + firstCharToLowerCase(finderName), view);
  }
 {
   cmdmap.put(
       "sz",
       new Console.Command() {
         public void run(Console cons, String[] args) {
           if (args.length == 3) {
             int w = Integer.parseInt(args[1]), h = Integer.parseInt(args[2]);
             p.setSize(w, h);
             pack();
             Utils.setprefc("wndsz", new Coord(w, h));
           } else if (args.length == 2) {
             if (args[1].equals("dyn")) {
               setResizable(true);
               Utils.setprefb("wndlock", false);
             } else if (args[1].equals("lock")) {
               setResizable(false);
               Utils.setprefb("wndlock", true);
             }
           }
         }
       });
   cmdmap.put(
       "fsmode",
       new Console.Command() {
         public void run(Console cons, String[] args) throws Exception {
           if (args.length == 3) {
             DisplayMode mode = findmode(Integer.parseInt(args[1]), Integer.parseInt(args[2]));
             if (mode == null) throw (new Exception("No such mode is available"));
             fsmode = mode;
             Utils.setprefc("fsmode", new Coord(mode.getWidth(), mode.getHeight()));
           }
         }
       });
   cmdmap.put(
       "fs",
       new Console.Command() {
         public void run(Console cons, String[] args) {
           if (args.length >= 2) {
             Runnable r;
             if (Utils.atoi(args[1]) != 0) {
               r =
                   new Runnable() {
                     public void run() {
                       setfs();
                     }
                   };
             } else {
               r =
                   new Runnable() {
                     public void run() {
                       setwnd();
                     }
                   };
             }
             getToolkit().getSystemEventQueue().invokeLater(r);
           }
         }
       });
 }
 private void addView(
     Map<String, DesignDocument.View> views, View input, Class<?> repositoryClass) {
   if (input.file().length() > 0) {
     views.put(input.name(), loadViewFromFile(views, input, repositoryClass));
   } else {
     views.put(input.name(), DesignDocument.View.of(input));
   }
 }
Exemple #8
0
 private static void initIconTypeMap() {
   ICON_TYPE_MAP = new HashMap<String, Integer>();
   ICON_TYPE_MAP.put("gtk-menu", Integer.valueOf(1));
   ICON_TYPE_MAP.put("gtk-small-toolbar", Integer.valueOf(2));
   ICON_TYPE_MAP.put("gtk-large-toolbar", Integer.valueOf(3));
   ICON_TYPE_MAP.put("gtk-button", Integer.valueOf(4));
   ICON_TYPE_MAP.put("gtk-dnd", Integer.valueOf(5));
   ICON_TYPE_MAP.put("gtk-dialog", Integer.valueOf(6));
 }
 private static <T> T registerNewArgument(Class<T> clazz, InvocationSequence invocationSequence) {
   T placeholder = (T) createPlaceholder(clazz, invocationSequence);
   PLACEHOLDER_BY_INVOCATION.put(invocationSequence, placeholder);
   if (isLimitedValues(placeholder)) {
     LIMITED_VALUE_INVOCATIONS.put(invocationSequence, invocationSequence);
   }
   bindArgument(placeholder, new Argument<T>(invocationSequence));
   return placeholder;
 }
  @Mock(reentrant = true)
  public boolean shouldRun(Filter filter, Object m) {
    testMethod = null;

    if (!coverageMap.isEmpty()) {
      if (m instanceof JUnit38ClassRunner) {
        boolean noTestsToRun =
            verifyTestMethodsInJUnit38TestClassThatShouldRun((JUnit38ClassRunner) m);

        if (noTestsToRun) {
          return false;
        }
      } else if (m instanceof FrameworkMethod) {
        testMethod = ((FrameworkMethod) m).getMethod();
        Boolean shouldRun = shouldRunTestInCurrentTestRun(Test.class, testMethod);

        if (shouldRun != null) {
          return shouldRun;
        }
      }
    }

    Boolean shouldRun = MethodReflection.invoke(it, shouldRunMethod, filter, m);

    if (testMethod != null) {
      testMethods.put(testMethod, shouldRun);
    }

    return shouldRun;
  }
 private void addTagToMethod(
     Map<String, MethodInfo> methods, String tagText, MethodTagType tagType) {
   MethodInfo mi = methods.get(methodName);
   if (mi == null) {
     mi = new MethodInfo();
     methods.put(methodName, mi);
   }
   if (tagType == MethodTagType.OMIT_FROM_UI) {
     mi.omitFromUI = true;
     return;
   }
   String[] tagParts =
       Iterables.toArray(
           Splitter.on(WHITESPACE_PATTERN)
               .trimResults()
               .omitEmptyStrings()
               .limit(2)
               .split(tagText),
           String.class);
   if (tagParts.length == 2) {
     if (tagType == MethodTagType.DESCRIPTION) {
       mi.descriptions.put(tagParts[0], tagParts[1]);
     } else {
       mi.useSchemas.put(tagParts[0], tagParts[1]);
     }
   }
 }
Exemple #12
0
  /**
   * Returns the bean property descriptor of an attribute
   *
   * @param beanClass the class that holds the attribute
   * @param propertyName the name of the property
   * @return the attribute's property descriptor
   */
  public static PropertyDescriptor getPropertyDescriptor(Class<?> beanClass, String propertyName) {
    if (beanClass == null) throw new IllegalArgumentException("beanClass is null");
    String propertyId = beanClass.getName() + '#' + propertyName;
    PropertyDescriptor result = propertyDescriptors.get(propertyId);
    if (result != null) return result;
    // descriptor is new

    int separatorIndex = propertyName.indexOf('.');
    if (separatorIndex >= 0) {
      String localProperty = propertyName.substring(0, separatorIndex);
      String remoteProperty = propertyName.substring(separatorIndex + 1);
      Class<?> localPropertyType =
          getPropertyDescriptor(beanClass, localProperty).getPropertyType();
      result = getPropertyDescriptor(localPropertyType, remoteProperty);
    } else {
      try {
        BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
        PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor descriptor : descriptors) {
          String name = descriptor.getName();
          if (name.equals(propertyName)) {
            result = descriptor;
            break;
          }
        }
      } catch (IntrospectionException e) {
        throw ExceptionMapper.configurationException(e, propertyName);
      }
    }
    propertyDescriptors.put(propertyId, result);
    return result;
  }
 protected void _addFields(Map<String, AnnotatedField> fields, Class<?> c) {
   /* First, a quick test: we only care for regular classes (not
    * interfaces, primitive types etc), except for Object.class.
    * A simple check to rule out other cases is to see if there
    * is a super class or not.
    */
   Class<?> parent = c.getSuperclass();
   if (parent != null) {
     // Let's add super-class' fields first, then ours.
     /* 21-Feb-2010, tatu: Need to handle masking: as per [JACKSON-226]
      *    we otherwise get into trouble...
      */
     _addFields(fields, parent);
     for (Field f : c.getDeclaredFields()) {
       // static fields not included, nor transient
       if (!_isIncludableField(f)) {
         continue;
       }
       /* Ok now: we can (and need) not filter out ignorable fields
        * at this point; partly because mix-ins haven't been
        * added, and partly because logic can be done when
        * determining get/settability of the field.
        */
       fields.put(f.getName(), _constructField(f));
     }
     // And then... any mix-in overrides?
     if (_mixInResolver != null) {
       Class<?> mixin = _mixInResolver.findMixInClassFor(c);
       if (mixin != null) {
         _addFieldMixIns(mixin, fields);
       }
     }
   }
 }
  /**
   * Add {@link DiscoverInfo} to our caps database.
   *
   * <p><b>Warning</b>: The specified <tt>DiscoverInfo</tt> is trusted to be valid with respect to
   * the specified <tt>Caps</tt> for performance reasons because the <tt>DiscoverInfo</tt> should
   * have already been validated in order to be used elsewhere anyway.
   *
   * @param caps the <tt>Caps<tt/> i.e. the node, the hash and the ver for which a
   *     <tt>DiscoverInfo</tt> is to be added to our caps database.
   * @param info {@link DiscoverInfo} for the specified <tt>Caps</tt>.
   */
  public static void addDiscoverInfoByCaps(Caps caps, DiscoverInfo info) {
    cleanupDiscoverInfo(info);
    /*
     * DiscoverInfo carries the node we're now associating it with a
     * specific node so we'd better keep them in sync.
     */
    info.setNode(caps.getNodeVer());

    synchronized (caps2discoverInfo) {
      DiscoverInfo oldInfo = caps2discoverInfo.put(caps, info);

      /*
       * If the specified info is a new association for the specified
       * node, remember it across application instances in order to not
       * query for it over the network.
       */
      if ((oldInfo == null) || !oldInfo.equals(info)) {
        String xml = info.getChildElementXML();

        if ((xml != null) && (xml.length() != 0)) {
          getConfigService().setProperty(getCapsPropertyName(caps), xml);
        }
      }
    }
  }
Exemple #15
0
 public void addBinding(String name, JavaType type) {
   // note: emptyMap() is unmodifiable, hence second check is needed:
   if (_bindings == null || _bindings.size() == 0) {
     _bindings = new LinkedHashMap<String, JavaType>();
   }
   _bindings.put(name, type);
 }
Exemple #16
0
  /**
   * Returns the correct implementation instance for the interface <code>type</code>. For convention
   * the implentation is named <code>InterfaceName + Impl</code>.
   *
   * @param type The interface type
   * @return The correct ModelProxy subclass (if exists), a ModelProxy instance otherwise
   * @throws MalformedModelException is the interface or the implementation are not well formed
   *     (they don't respect the conventions).
   * @throws ModelRuntimeException is any error occurs during the instantiation
   */
  protected ModelProxy createInstance(Class type) {
    Class backClass;
    if (implementations.containsKey(type)) backClass = implementations.get(type);
    else {
      /* type never seen */

      try {
        Package pkg = type.getPackage();
        String pkgN = pkg == null ? "" : pkg.getName();

        backClass = Class.forName(pkgN + tableName(type) + CommonStatic.getImplementationSuffix());

      } catch (Exception e) {
        backClass = ModelProxy.class;
      }

      Validator.validateModel(type, backClass);

      initFieldsTypes(type);
      implementations.put(type, backClass);
    }

    ModelProxy impl = null;
    try {
      impl = (ModelProxy) backClass.newInstance();
    } catch (Exception e) {
      throw new ModelRuntimeException(e.getMessage());
    }

    return impl;
  }
  /**
   * Add a record telling what entity caps node a user has.
   *
   * @param user the user (Full JID)
   * @param node the node (of the caps packet extension)
   * @param hash the hashing algorithm used to calculate <tt>ver</tt>
   * @param ver the version (of the caps packet extension)
   * @param ext the ext (of the caps packet extension)
   * @param online indicates if the user is online
   */
  private void addUserCapsNode(
      String user, String node, String hash, String ver, String ext, boolean online) {
    if ((user != null) && (node != null) && (hash != null) && (ver != null)) {
      Caps caps = userCaps.get(user);

      if ((caps == null)
          || !caps.node.equals(node)
          || !caps.hash.equals(hash)
          || !caps.ver.equals(ver)) {
        caps = new Caps(node, hash, ver, ext);

        userCaps.put(user, caps);
      } else return;

      // Fire userCapsNodeAdded.
      UserCapsNodeListener[] listeners;

      synchronized (userCapsNodeListeners) {
        listeners = userCapsNodeListeners.toArray(NO_USER_CAPS_NODE_LISTENERS);
      }
      if (listeners.length != 0) {
        String nodeVer = caps.getNodeVer();

        for (UserCapsNodeListener listener : listeners)
          listener.userCapsNodeAdded(user, nodeVer, online);
      }
    }
  }
Exemple #18
0
  /**
   * Returns a map of MBeans with ObjectName as the key and MBeanInfo value of a given domain. If
   * domain is <tt>null</tt>, all MBeans are returned. If no MBean found, an empty map is returned.
   */
  public Map<ObjectName, MBeanInfo> getMBeans(String domain) throws IOException {

    ObjectName name = null;
    if (domain != null) {
      try {
        name = new ObjectName(domain + ":*");
      } catch (MalformedObjectNameException e) {
        // should not reach here
        assert (false);
      }
    }
    Set<ObjectName> mbeans = server.queryNames(name, null);
    Map<ObjectName, MBeanInfo> result = new HashMap<ObjectName, MBeanInfo>(mbeans.size());
    Iterator<ObjectName> iterator = mbeans.iterator();
    while (iterator.hasNext()) {
      Object object = iterator.next();
      if (object instanceof ObjectName) {
        ObjectName o = (ObjectName) object;
        try {
          MBeanInfo info = server.getMBeanInfo(o);
          result.put(o, info);
        } catch (IntrospectionException e) {
          // TODO: should log the error
        } catch (InstanceNotFoundException e) {
          // TODO: should log the error
        } catch (ReflectionException e) {
          // TODO: should log the error
        }
      }
    }
    return result;
  }
 /**
  * Registers method if it: a. is public, and b. is named "convertXxx", and c. has a return type of
  * "RexNode" or a subtype d. has a 2 parameters with types ConvertletContext and SqlNode (or a
  * subtype) respectively.
  */
 private void registerNodeTypeMethod(final Method method) {
   if (!Modifier.isPublic(method.getModifiers())) {
     return;
   }
   if (!method.getName().startsWith("convert")) {
     return;
   }
   if (!RexNode.class.isAssignableFrom(method.getReturnType())) {
     return;
   }
   final Class[] parameterTypes = method.getParameterTypes();
   if (parameterTypes.length != 2) {
     return;
   }
   if (parameterTypes[0] != SqlRexContext.class) {
     return;
   }
   final Class parameterType = parameterTypes[1];
   if (!SqlNode.class.isAssignableFrom(parameterType)) {
     return;
   }
   map.put(
       parameterType,
       new SqlRexConvertlet() {
         public RexNode convertCall(SqlRexContext cx, SqlCall call) {
           try {
             return (RexNode) method.invoke(ReflectiveConvertletTable.this, cx, call);
           } catch (IllegalAccessException e) {
             throw Util.newInternal(e, "while converting " + call);
           } catch (InvocationTargetException e) {
             throw Util.newInternal(e, "while converting " + call);
           }
         }
       });
 }
 /**
  * Builds a new AgentMBeanServerConnectionFactory and returns the underlying
  * MBeanServerConnection
  *
  * @return a new MBeanServerConnection
  */
 public MBeanServerConnection build() {
   final String key = buildKey();
   MBeanServerConnection conn = INSTANCES.get(key);
   if (conn == null) {
     synchronized (INSTANCES) {
       conn = INSTANCES.get(key);
       if (conn == null) {
         conn =
             (MBeanServerConnection)
                 Proxy.newProxyInstance(
                     Thread.currentThread().getContextClassLoader(),
                     new Class[] {MBeanServerConnection.class},
                     new AgentMBeanServerConnectionFactory(this));
         INSTANCES.put(key, conn);
         channel
             .getCloseFuture()
             .addListener(
                 new ChannelFutureListener() {
                   @Override
                   public void operationComplete(ChannelFuture future) throws Exception {
                     INSTANCES.remove(key);
                   }
                 });
       }
     }
   }
   return conn;
 }
 protected void registerTypeParametersOn(TypeVariable[] typeParameters) {
   for (TypeVariable typeParameter : typeParameters) {
     contextualActualTypeParameters.put(typeParameter, boundsOf(typeParameter));
     // logger.log("For '" + typeParameter.getGenericDeclaration() + "' found type variable : { '"
     // + typeParameter + "(" + System.identityHashCode(typeParameter) + ")" + "' : '" +
     // boundsOf(typeParameter) + "' }");
   }
 }
  /**
   * This is called when JPM runs in the background to start jobs
   *
   * @throws Exception
   */
  public void daemon() throws Exception {
    Runtime.getRuntime()
        .addShutdownHook(
            new Thread("Daemon shutdown") {
              public void run() {

                for (Service service : startedByDaemon) {
                  try {
                    reporter.error("Stopping " + service);
                    service.stop();
                    reporter.error("Stopped " + service);
                  } catch (Exception e) {
                    // Ignore
                  }
                }
              }
            });
    List<ServiceData> services = getServices();
    Map<String, ServiceData> map = new HashMap<String, ServiceData>();
    for (ServiceData d : services) {
      map.put(d.name, d);
    }
    List<ServiceData> start = new ArrayList<ServiceData>();
    Set<ServiceData> set = new HashSet<ServiceData>();
    for (ServiceData sd : services) {
      checkStartup(map, start, sd, set);
    }

    if (start.isEmpty()) reporter.warning("No services to start");

    for (ServiceData sd : start) {
      try {
        Service service = getService(sd.name);
        reporter.trace("Starting " + service);
        String result = service.start();
        if (result != null) reporter.error("Started error " + result);
        else startedByDaemon.add(service);
        reporter.trace("Started " + service);
      } catch (Exception e) {
        reporter.error("Cannot start daemon %s, due to %s", sd.name, e);
      }
    }

    while (true) {
      for (Service sd : startedByDaemon) {
        try {
          if (!sd.isRunning()) {
            reporter.error("Starting due to failure " + sd);
            String result = sd.start();
            if (result != null) reporter.error("Started error " + result);
          }
        } catch (Exception e) {
          reporter.error("Cannot start daemon %s, due to %s", sd, e);
        }
      }
      Thread.sleep(10000);
    }
  }
Exemple #23
0
 /** Gets a proxy client for a given local virtual machine. */
 public static ProxyClient getProxyClient(LocalVirtualMachine lvm) throws IOException {
   final String key = getCacheKey(lvm);
   ProxyClient proxyClient = cache.get(key);
   if (proxyClient == null) {
     proxyClient = new ProxyClient(lvm);
     cache.put(key, proxyClient);
   }
   return proxyClient;
 }
  public Map<String, Revision> latest(Collection<Revision> list) {
    Map<String, Revision> programs = new HashMap<String, Library.Revision>();

    for (Revision r : list) {
      String coordinates = r.groupId + ":" + r.artifactId;
      if (r.classifier != null) coordinates += ":" + r.classifier;

      if (r.groupId.equals(Library.SHA_GROUP)) continue;

      Revision current = programs.get(coordinates);
      if (current == null) programs.put(coordinates, r);
      else {
        // who is better?
        if (compare(r, current) >= 0) programs.put(coordinates, r);
      }
    }
    return programs;
  }
Exemple #25
0
 private void addParameterInternal(String name, ParameterSetter parameterSetter) {
   if (!this.getParamNameToIdxMap().containsKey(name)) {
     throw new Sql2oException(
         "Failed to add parameter with name '"
             + name
             + "'. No parameter with that name is declared in the sql.");
   }
   parameters.put(name, parameterSetter);
 }
Exemple #26
0
 public static void testConfigurableForNonPrimitives() {
   Map<String, String> p = new HashMap<String, String>();
   C config = Configurable.createConfigurable(C.class, p);
   assertNull(config.port());
   p.put("port", "10");
   config = Configurable.createConfigurable(C.class, p);
   assertEquals(Integer.valueOf(10), config.port()); // property port is
   // not set
 }
Exemple #27
0
  /**
   * Returns the conventional table name for a {@link Model} interface.
   *
   * @param type A valid Model interface.
   * @return The conventional table name for the given interface.
   */
  protected String tableName(Class type) {

    if (tableNames.containsKey(type)) return tableNames.get(type);

    String tN = CommonStatic.tableName(type);

    tableNames.put(type, tN);
    return tN;
  }
Exemple #28
0
  /**
   * Returns the conventional field name for a getter method.
   *
   * @param m The field getter.
   * @return The field name.
   * @throws IllegalArgumentException if the method isn't a valid getter.
   */
  protected String fieldName(Method m) {

    if (fieldNames.containsKey(m)) return fieldNames.get(m);

    String name = CommonStatic.fieldName(m);

    fieldNames.put(m, name);
    return name;
  }
Exemple #29
0
 /** Convert the attributes in the given XML Element into a Map of name/value pairs. */
 protected static Map createAttributeMap(Element el) {
   Log.debug("Creating attribute map for " + el);
   Map attributes = new HashMap();
   Iterator iter = el.getAttributes().iterator();
   while (iter.hasNext()) {
     Attribute att = (Attribute) iter.next();
     attributes.put(att.getName(), att.getValue());
   }
   return attributes;
 }
Exemple #30
0
 public static void initnames() {
   if (!inited) {
     for (Factory f : dolda.jglob.Loader.get(RName.class).instances(Factory.class)) {
       synchronized (types) {
         types.put(f.getClass().getAnnotation(RName.class).value(), f);
       }
     }
     inited = true;
   }
 }