Esempio n. 1
0
 public static boolean hasJavaLangImportConflict(String fqName, PsiJavaFile file) {
   final String shortName = ClassUtil.extractClassName(fqName);
   final String packageName = ClassUtil.extractPackageName(fqName);
   if (HardcodedMethodConstants.JAVA_LANG.equals(packageName)) {
     return false;
   }
   final Project project = file.getProject();
   final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
   final PsiPackage javaLangPackage = psiFacade.findPackage(HardcodedMethodConstants.JAVA_LANG);
   if (javaLangPackage == null) {
     return false;
   }
   return javaLangPackage.containsClassNamed(shortName);
 }
Esempio n. 2
0
 public static boolean hasDefaultImportConflict(String fqName, PsiJavaFile file) {
   final String shortName = ClassUtil.extractClassName(fqName);
   final String packageName = ClassUtil.extractPackageName(fqName);
   final String filePackageName = file.getPackageName();
   if (filePackageName.equals(packageName)) {
     return false;
   }
   final Project project = file.getProject();
   final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
   final PsiPackage filePackage = psiFacade.findPackage(filePackageName);
   if (filePackage == null) {
     return false;
   }
   return filePackage.containsClassNamed(shortName);
 }
  protected BeanPropertyWriter _constructVirtualProperty(
      JsonAppend.Prop prop, MapperConfig<?> config, AnnotatedClass ac) {
    PropertyMetadata metadata =
        prop.required() ? PropertyMetadata.STD_REQUIRED : PropertyMetadata.STD_OPTIONAL;
    PropertyName propName = _propertyName(prop.name(), prop.namespace());
    JavaType type = config.constructType(prop.type());
    // now, then, we need a placeholder for member (no real Field/Method):
    AnnotatedMember member =
        new VirtualAnnotatedMember(
            ac, ac.getRawType(), propName.getSimpleName(), type.getRawClass());
    // and with that and property definition
    SimpleBeanPropertyDefinition propDef =
        SimpleBeanPropertyDefinition.construct(config, member, propName, metadata, prop.include());

    Class<?> implClass = prop.value();

    HandlerInstantiator hi = config.getHandlerInstantiator();
    VirtualBeanPropertyWriter bpw =
        (hi == null) ? null : hi.virtualPropertyWriterInstance(config, implClass);
    if (bpw == null) {
      bpw =
          (VirtualBeanPropertyWriter)
              ClassUtil.createInstance(implClass, config.canOverrideAccessModifiers());
    }

    // one more thing: give it necessary contextual information
    return bpw.withConfig(config, ac, propDef, type);
  }
Esempio n. 4
0
  /**
   * Initialize the backend systems, the log handler and the restrictor. A subclass can tune this
   * step by overriding {@link #createRestrictor(String)} and {@link
   * #createLogHandler(ServletConfig, boolean)}
   *
   * @param pServletConfig servlet configuration
   */
  @Override
  public void init(ServletConfig pServletConfig) throws ServletException {
    super.init(pServletConfig);

    Configuration config = initConfig(pServletConfig);

    // Create a log handler early in the lifecycle, but not too early
    String logHandlerClass = config.get(ConfigKey.LOGHANDLER_CLASS);
    logHandler =
        logHandlerClass != null
            ? (LogHandler) ClassUtil.newInstance(logHandlerClass)
            : createLogHandler(pServletConfig, Boolean.valueOf(config.get(ConfigKey.DEBUG)));

    // Different HTTP request handlers
    httpGetHandler = newGetHttpRequestHandler();
    httpPostHandler = newPostHttpRequestHandler();

    if (restrictor == null) {
      restrictor =
          createRestrictor(NetworkUtil.replaceExpression(config.get(ConfigKey.POLICY_LOCATION)));
    } else {
      logHandler.info("Using custom access restriction provided by " + restrictor);
    }
    configMimeType = config.get(ConfigKey.MIME_TYPE);
    backendManager = new BackendManager(config, logHandler, restrictor);
    requestHandler = new HttpRequestHandler(config, backendManager, logHandler);

    initDiscoveryMulticast(config);
  }
Esempio n. 5
0
 public static <T> Constructor<T> findConstructor(Class<T> cls, boolean canFixAccess)
     throws IllegalArgumentException {
   try {
     Constructor<T> ctor = cls.getDeclaredConstructor();
     if (canFixAccess) {
       checkAndFixAccess(ctor);
     } else {
       // Has to be public...
       if (!Modifier.isPublic(ctor.getModifiers())) {
         throw new IllegalArgumentException(
             "Default constructor for "
                 + cls.getName()
                 + " is not accessible (non-public?): not allowed to try modify access via Reflection: can not instantiate type");
       }
     }
     return ctor;
   } catch (NoSuchMethodException e) {;
   } catch (Exception e) {
     ClassUtil.unwrapAndThrowAsIAE(
         e,
         "Failed to find default constructor of class "
             + cls.getName()
             + ", problem: "
             + e.getMessage());
   }
   return null;
 }
Esempio n. 6
0
 /**
  * @param strict if strict is true this method checks if the conflicting class which is imported
  *     is actually used in the file. If it isn't the on demand import can be overridden with an
  *     exact import for the fqName without breaking stuff.
  */
 private static boolean hasOnDemandImportConflict(
     @NotNull String fqName, @NotNull PsiJavaFile file, boolean strict) {
   final PsiImportList imports = file.getImportList();
   if (imports == null) {
     return false;
   }
   final PsiImportStatement[] importStatements = imports.getImportStatements();
   final String shortName = ClassUtil.extractClassName(fqName);
   final String packageName = ClassUtil.extractPackageName(fqName);
   for (final PsiImportStatement importStatement : importStatements) {
     if (!importStatement.isOnDemand()) {
       continue;
     }
     final PsiJavaCodeReferenceElement importReference = importStatement.getImportReference();
     if (importReference == null) {
       continue;
     }
     final String packageText = importReference.getText();
     if (packageText.equals(packageName)) {
       continue;
     }
     final PsiElement element = importReference.resolve();
     if (!(element instanceof PsiPackage)) {
       continue;
     }
     final PsiPackage aPackage = (PsiPackage) element;
     if (!strict && aPackage.containsClassNamed(shortName)) {
       return true;
     } else {
       final PsiClass[] classes = aPackage.findClassByShortName(shortName, file.getResolveScope());
       for (final PsiClass aClass : classes) {
         final String qualifiedClassName = aClass.getQualifiedName();
         if (qualifiedClassName == null || fqName.equals(qualifiedClassName)) {
           continue;
         }
         return containsConflictingReference(file, qualifiedClassName);
       }
     }
   }
   return hasJavaLangImportConflict(fqName, file);
 }
 private Analyzer getLuceneAnalyzer() throws ProviderException {
   try {
     Class clazz = ClassUtil.findClass("", m_analyzerClass);
     Constructor constructor = clazz.getConstructor(Version.LUCENE_36.getClass());
     Analyzer analyzer = (Analyzer) constructor.newInstance(Version.LUCENE_36);
     return analyzer;
   } catch (Exception e) {
     String msg = "Could not get LuceneAnalyzer class " + m_analyzerClass + ", reason: ";
     log.error(msg, e);
     throw new ProviderException(msg + e);
   }
 }
Esempio n. 8
0
 /**
  * ImportUtils currently checks all inner classes, even those that are contained in inner classes
  * themselves, because it doesn't know the location of the original fully qualified reference. It
  * should really only check if the containing class of the fully qualified reference has any
  * conflicting inner classes.
  */
 private static boolean containsConflictingInnerClass(String fqName, PsiClass aClass) {
   final String shortName = ClassUtil.extractClassName(fqName);
   if (shortName.equals(aClass.getName()) && !fqName.equals(aClass.getQualifiedName())) {
     return true;
   }
   final PsiClass[] classes = aClass.getInnerClasses();
   for (PsiClass innerClass : classes) {
     if (containsConflictingInnerClass(fqName, innerClass)) {
       return true;
     }
   }
   return false;
 }
Esempio n. 9
0
 public static boolean nameCanBeImported(@NotNull String fqName, @NotNull PsiElement context) {
   final PsiClass containingClass = PsiTreeUtil.getParentOfType(context, PsiClass.class);
   if (containingClass != null) {
     if (fqName.equals(containingClass.getQualifiedName())) {
       return true;
     }
     final String shortName = ClassUtil.extractClassName(fqName);
     final PsiClass[] innerClasses = containingClass.getAllInnerClasses();
     for (PsiClass innerClass : innerClasses) {
       if (innerClass.hasModifierProperty(PsiModifier.PRIVATE)) {
         continue;
       }
       if (innerClass.hasModifierProperty(PsiModifier.PACKAGE_LOCAL)) {
         if (!ClassUtils.inSamePackage(innerClass, containingClass)) {
           continue;
         }
       }
       final String className = innerClass.getName();
       if (shortName.equals(className)) {
         return false;
       }
     }
     PsiField field = containingClass.findFieldByName(shortName, false);
     if (field != null) {
       return false;
     }
     field = containingClass.findFieldByName(shortName, true);
     if (field != null
         && PsiUtil.isAccessible(containingClass.getProject(), field, containingClass, null)) {
       return false;
     }
   }
   final PsiJavaFile file = PsiTreeUtil.getParentOfType(context, PsiJavaFile.class);
   if (file == null) {
     return false;
   }
   if (hasExactImportConflict(fqName, file)) {
     return false;
   }
   if (hasOnDemandImportConflict(fqName, file, true)) {
     return false;
   }
   if (containsConflictingReference(file, fqName)) {
     return false;
   }
   if (containsConflictingClass(fqName, file)) {
     return false;
   }
   return !containsConflictingClassName(fqName, file);
 }
Esempio n. 10
0
 /**
  * Method that can be called to try to create an instantiate of specified type. Instantiation is
  * done using default no-argument constructor.
  *
  * @param canFixAccess Whether it is possible to try to change access rights of the default
  *     constructor (in case it is not publicly accessible) or not.
  * @throws IllegalArgumentException If instantiation fails for any reason; except for cases where
  *     constructor throws an unchecked exception (which will be passed as is)
  */
 public static <T> T createInstance(Class<T> cls, boolean canFixAccess)
     throws IllegalArgumentException {
   Constructor<T> ctor = findConstructor(cls, canFixAccess);
   if (ctor == null) {
     throw new IllegalArgumentException(
         "Class " + cls.getName() + " has no default (no arg) constructor");
   }
   try {
     return ctor.newInstance();
   } catch (Exception e) {
     ClassUtil.unwrapAndThrowAsIAE(
         e, "Failed to instantiate class " + cls.getName() + ", problem: " + e.getMessage());
     return null;
   }
 }
 @Nullable
 public static PsiMethod findPsiMethod(PsiManager manager, String externalName) {
   final int spaceIdx = externalName.indexOf(' ');
   final String className = externalName.substring(0, spaceIdx);
   final PsiClass psiClass = ClassUtil.findPsiClass(manager, className);
   if (psiClass == null) return null;
   try {
     PsiElementFactory factory =
         JavaPsiFacade.getInstance(psiClass.getProject()).getElementFactory();
     String methodSignature = externalName.substring(spaceIdx + 1);
     PsiMethod patternMethod = factory.createMethodFromText(methodSignature, psiClass);
     return psiClass.findMethodBySignature(patternMethod, false);
   } catch (IncorrectOperationException e) {
     // Do nothing. Returning null is acceptable in this case.
     return null;
   }
 }
Esempio n. 12
0
 public static void addImportIfNeeded(@NotNull PsiClass aClass, @NotNull PsiElement context) {
   final PsiFile file = context.getContainingFile();
   if (!(file instanceof PsiJavaFile)) {
     return;
   }
   final PsiJavaFile javaFile = (PsiJavaFile) file;
   final PsiClass outerClass = aClass.getContainingClass();
   if (outerClass == null) {
     if (PsiTreeUtil.isAncestor(javaFile, aClass, true)) {
       return;
     }
   } else if (PsiTreeUtil.isAncestor(outerClass, context, true)) {
     final PsiElement brace = outerClass.getLBrace();
     if (brace != null && brace.getTextOffset() < context.getTextOffset()) {
       return;
     }
   }
   final String qualifiedName = aClass.getQualifiedName();
   if (qualifiedName == null) {
     return;
   }
   final PsiImportList importList = javaFile.getImportList();
   if (importList == null) {
     return;
   }
   final String containingPackageName = javaFile.getPackageName();
   @NonNls final String packageName = ClassUtil.extractPackageName(qualifiedName);
   if (containingPackageName.equals(packageName)
       || importList.findSingleClassImportStatement(qualifiedName) != null) {
     return;
   }
   if (importList.findOnDemandImportStatement(packageName) != null
       && !hasDefaultImportConflict(qualifiedName, javaFile)
       && !hasOnDemandImportConflict(qualifiedName, javaFile)) {
     return;
   }
   final Project project = importList.getProject();
   final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
   final PsiElementFactory elementFactory = psiFacade.getElementFactory();
   final PsiImportStatement importStatement = elementFactory.createImportStatement(aClass);
   importList.add(importStatement);
 }
 protected Class<?> _classIfExplicit(Class<?> cls) {
   if (cls == null || ClassUtil.isBogusClass(cls)) {
     return null;
   }
   return cls;
 }
Esempio n. 14
0
 private ConflictingClassReferenceVisitor(String fullyQualifiedName) {
   name = ClassUtil.extractClassName(fullyQualifiedName);
   this.fullyQualifiedName = fullyQualifiedName;
 }
Esempio n. 15
0
  public QSAdminGUI(QSAdminMain qsadminMain, JFrame parentFrame) {
    this.parentFrame = parentFrame;
    Container cp = this;
    qsadminMain.setGUI(this);
    cp.setLayout(new BorderLayout(5, 5));
    headerPanel = new HeaderPanel(qsadminMain, parentFrame);
    mainCommandPanel = new MainCommandPanel(qsadminMain);
    cmdConsole = new CmdConsole(qsadminMain);
    propertiePanel = new PropertiePanel(qsadminMain);

    if (headerPanel == null
        || mainCommandPanel == null
        || cmdConsole == null
        || propertiePanel == null) {
      throw new RuntimeException("Loading of one of gui component failed.");
    }

    headerPanel.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
    cp.add(headerPanel, BorderLayout.NORTH);
    JScrollPane propertieScrollPane = new JScrollPane(propertiePanel);
    // JScrollPane commandScrollPane = new JScrollPane(mainCommandPanel);
    JSplitPane splitPane =
        new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, mainCommandPanel, cmdConsole);
    splitPane.setOneTouchExpandable(false);
    splitPane.setDividerLocation(250);
    // splitPane.setDividerLocation(0.70);

    tabbedPane = new JTabbedPane(JTabbedPane.TOP);
    tabbedPane.addTab("Main", ball, splitPane, "Main Commands");
    tabbedPane.addTab("Get/Set", ball, propertieScrollPane, "Properties Panel");

    QSAdminPluginConfig qsAdminPluginConfig = null;
    PluginPanel pluginPanel = null;
    // -- start of loadPlugins
    try {
      File xmlFile = null;
      ClassLoader classLoader = null;
      Class mainClass = null;

      File file = new File(pluginDir);
      File dirs[] = null;

      if (file.canRead()) dirs = file.listFiles(new DirFileList());

      for (int i = 0; dirs != null && i < dirs.length; i++) {
        xmlFile = new File(dirs[i].getAbsolutePath() + File.separator + "plugin.xml");
        if (xmlFile.canRead()) {
          qsAdminPluginConfig = PluginConfigReader.read(xmlFile);
          if (qsAdminPluginConfig.getActive().equals("yes")
              && qsAdminPluginConfig.getType().equals("javax.swing.JPanel")) {
            classLoader = ClassUtil.getClassLoaderFromJars(dirs[i].getAbsolutePath());
            mainClass = classLoader.loadClass(qsAdminPluginConfig.getMainClass());
            logger.fine("Got PluginMainClass " + mainClass);
            pluginPanel = (PluginPanel) mainClass.newInstance();
            if (JPanel.class.isInstance(pluginPanel) == true) {
              logger.info("Loading plugin : " + qsAdminPluginConfig.getName());
              pluginPanelMap.put("" + (2 + i), pluginPanel);
              plugins.add(pluginPanel);
              tabbedPane.addTab(
                  qsAdminPluginConfig.getName(),
                  ball,
                  (JPanel) pluginPanel,
                  qsAdminPluginConfig.getDesc());
              pluginPanel.setQSAdminMain(qsadminMain);
              pluginPanel.init();
            }
          } else {
            logger.info(
                "Plugin "
                    + dirs[i]
                    + " is disabled so skipping "
                    + qsAdminPluginConfig.getActive()
                    + ":"
                    + qsAdminPluginConfig.getType());
          }
        } else {
          logger.info("No plugin configuration found in " + xmlFile + " so skipping");
        }
      }
    } catch (Exception e) {
      logger.warning("Error loading plugin : " + e);
      logger.fine("StackTrace:\n" + MyString.getStackTrace(e));
    }
    // -- end of loadPlugins

    tabbedPane.addChangeListener(
        new ChangeListener() {
          int selected = -1;
          int oldSelected = -1;

          public void stateChanged(ChangeEvent e) {
            // if plugin
            selected = tabbedPane.getSelectedIndex();
            if (selected >= 2) {
              ((PluginPanel) pluginPanelMap.get("" + selected)).activated();
            }
            if (oldSelected >= 2) {
              ((PluginPanel) pluginPanelMap.get("" + oldSelected)).deactivated();
            }
            oldSelected = selected;
          }
        });

    // tabbedPane.setBorder(BorderFactory.createEmptyBorder(0,5,5,5));
    cp.add(tabbedPane, BorderLayout.CENTER);

    buildMenu();
  }
Esempio n. 16
0
  /**
   * @param args
   * @throws Exception
   */
  @SuppressWarnings("unchecked")
  public void process(String[] args, String... required) throws Exception {
    final boolean debug = LOG.isDebugEnabled();

    if (debug) LOG.debug("Processing " + args.length + " parameters...");
    final Pattern p = Pattern.compile("=");
    for (int i = 0, cnt = args.length; i < cnt; i++) {
      final String arg = args[i];
      final String[] parts = p.split(arg, 2);
      if (parts[0].startsWith("-")) parts[0] = parts[0].substring(1);

      if (parts.length == 1) {
        if (parts[0].startsWith("${") == false) this.opt_params.add(parts[0]);
        continue;
      } else if (parts[0].equalsIgnoreCase("tag")) {
        continue;
      } else if (parts[1].startsWith("${") || parts[0].startsWith("#")) {
        continue;
      }
      if (debug) LOG.debug(String.format("%-35s = %s", parts[0], parts[1]));

      // DesignerHints Override
      if (parts[0].startsWith(PARAM_DESIGNER_HINTS_PREFIX)) {
        String param = parts[0].replace(PARAM_DESIGNER_HINTS_PREFIX, "").toLowerCase();
        try {
          Field f = DesignerHints.class.getField(param);
          this.hints_params.put(f.getName(), parts[1]);
          if (debug) LOG.debug(String.format("DesignerHints.%s = %s", param, parts[1]));
        } catch (NoSuchFieldException ex) {
          throw new Exception("Unknown DesignerHints parameter: " + param, ex);
        }

      }
      // HStoreConf Parameter
      else if (HStoreConf.isConfParameter(parts[0])) {
        this.conf_params.put(parts[0].toLowerCase(), parts[1]);
      }
      // ArgumentsParser Parameter
      else if (PARAMS.contains(parts[0].toLowerCase())) {
        this.params.put(parts[0].toLowerCase(), parts[1]);
      }
      // Invalid!
      else {
        String suggestions = "";
        i = 0;
        String end = CollectionUtil.last(parts[0].split("\\."));
        for (String param : PARAMS) {
          String param_end = CollectionUtil.last(param.split("\\."));
          if (param.startsWith(parts[0])
              || (end != null && param.endsWith(end))
              || (end != null && param_end != null && param_end.startsWith(end))) {
            if (suggestions.isEmpty()) suggestions = ". Possible Matches:";
            suggestions += String.format("\n [%02d] %s", ++i, param);
          }
        } // FOR
        throw new Exception("Unknown parameter '" + parts[0] + "'" + suggestions);
      }
    } // FOR

    // -------------------------------------------------------
    // CATALOGS
    // -------------------------------------------------------

    // Text File
    if (this.params.containsKey(PARAM_CATALOG)) {
      String path = this.params.get(PARAM_CATALOG);
      if (debug) LOG.debug("Loading catalog from file '" + path + "'");
      Catalog catalog = CatalogUtil.loadCatalog(path);
      if (catalog == null)
        throw new Exception("Failed to load catalog object from file '" + path + "'");
      this.updateCatalog(catalog, new File(path));
    }
    // Jar File
    else if (this.params.containsKey(PARAM_CATALOG_JAR)) {
      String path = this.params.get(PARAM_CATALOG_JAR);
      this.params.put(PARAM_CATALOG, path);
      File jar_file = new File(path);
      Catalog catalog = CatalogUtil.loadCatalogFromJar(path);
      if (catalog == null)
        throw new Exception("Failed to load catalog object from jar file '" + path + "'");
      if (debug) LOG.debug("Loaded catalog from jar file '" + path + "'");
      this.updateCatalog(catalog, jar_file);

      if (!this.params.containsKey(PARAM_CATALOG_TYPE)) {
        String jar_name = jar_file.getName();
        int jar_idx = jar_name.lastIndexOf(".jar");
        if (jar_idx != -1) {
          ProjectType type = ProjectType.get(jar_name.substring(0, jar_idx));
          if (type != null) {
            if (debug) LOG.debug("Set catalog type '" + type + "' from catalog jar file name");
            this.catalog_type = type;
            this.params.put(PARAM_CATALOG_TYPE, this.catalog_type.toString());
          }
        }
      }
    }
    // Schema File
    else if (this.params.containsKey(PARAM_CATALOG_SCHEMA)) {
      String path = this.params.get(PARAM_CATALOG_SCHEMA);
      Catalog catalog = CompilerUtil.compileCatalog(path);
      if (catalog == null) throw new Exception("Failed to load schema from '" + path + "'");
      if (debug) LOG.debug("Loaded catalog from schema file '" + path + "'");
      this.updateCatalog(catalog, new File(path));
    }

    // Catalog Type
    if (this.params.containsKey(PARAM_CATALOG_TYPE)) {
      String catalog_type = this.params.get(PARAM_CATALOG_TYPE);
      ProjectType type = ProjectType.get(catalog_type);
      if (type == null) {
        throw new Exception("Unknown catalog type '" + catalog_type + "'");
      }
      this.catalog_type = type;
    }

    // Update Cluster Configuration
    if (this.params.containsKey(ArgumentsParser.PARAM_CATALOG_HOSTS)) {
      ClusterConfiguration cc =
          new ClusterConfiguration(this.getParam(ArgumentsParser.PARAM_CATALOG_HOSTS));
      this.updateCatalog(FixCatalog.addHostInfo(this.catalog, cc), null);
    }

    // Check the requirements after loading the catalog, because some of the
    // above parameters will set the catalog one
    if (required != null && required.length > 0) this.require(required);

    // -------------------------------------------------------
    // PHYSICAL DESIGN COMPONENTS
    // -------------------------------------------------------
    if (this.params.containsKey(PARAM_PARTITION_PLAN)) {
      assert (this.catalog_db != null);
      File path = new File(this.params.get(PARAM_PARTITION_PLAN));
      boolean ignoreMissing =
          this.getBooleanParam(ArgumentsParser.PARAM_PARTITION_PLAN_IGNORE_MISSING, false);
      if (path.exists() || (path.exists() == false && ignoreMissing == false)) {
        if (debug) LOG.debug("Loading in partition plan from '" + path + "'");
        this.pplan = new PartitionPlan();
        this.pplan.load(path.getAbsolutePath(), this.catalog_db);

        // Apply!
        if (this.params.containsKey(PARAM_PARTITION_PLAN_APPLY)
            && this.getBooleanParam(PARAM_PARTITION_PLAN_APPLY)) {
          boolean secondaryIndexes =
              this.getBooleanParam(PARAM_PARTITION_PLAN_NO_SECONDARY, false) == false;
          LOG.info(
              String.format(
                  "Applying PartitionPlan '%s' to catalog [enableSecondary=%s]",
                  path.getName(), secondaryIndexes));
          this.pplan.apply(this.catalog_db, secondaryIndexes);
        }
      }
    }

    // -------------------------------------------------------
    // DESIGNER COMPONENTS
    // -------------------------------------------------------

    if (this.params.containsKey(PARAM_DESIGNER_THREADS)) {
      this.max_concurrent = Integer.valueOf(this.params.get(PARAM_DESIGNER_THREADS));
    }
    if (this.params.containsKey(PARAM_DESIGNER_INTERVALS)) {
      this.num_intervals = Integer.valueOf(this.params.get(PARAM_DESIGNER_INTERVALS));
    }
    if (this.params.containsKey(PARAM_DESIGNER_HINTS)) {
      String path = this.params.get(PARAM_DESIGNER_HINTS);
      if (debug)
        LOG.debug(
            "Loading in designer hints from '"
                + path
                + "'.\nForced Values:\n"
                + StringUtil.formatMaps(this.hints_params));
      this.designer_hints.load(path, catalog_db, this.hints_params);
    }
    if (this.params.containsKey(PARAM_DESIGNER_CHECKPOINT)) {
      this.designer_checkpoint = new File(this.params.get(PARAM_DESIGNER_CHECKPOINT));
    }

    String designer_attributes[] = {
      PARAM_DESIGNER_PARTITIONER,
      PARAM_DESIGNER_MAPPER,
      PARAM_DESIGNER_INDEXER,
      PARAM_DESIGNER_COSTMODEL
    };
    ClassLoader loader = ClassLoader.getSystemClassLoader();
    for (String key : designer_attributes) {
      if (this.params.containsKey(key)) {
        String target_name = this.params.get(key);
        Class<?> target_class = loader.loadClass(target_name);
        assert (target_class != null);
        if (debug) LOG.debug("Set " + key + " class to " + target_class.getName());

        if (key.equals(PARAM_DESIGNER_PARTITIONER)) {
          this.partitioner_class = (Class<? extends AbstractPartitioner>) target_class;
        } else if (key.equals(PARAM_DESIGNER_MAPPER)) {
          this.mapper_class = (Class<? extends AbstractMapper>) target_class;
        } else if (key.equals(PARAM_DESIGNER_INDEXER)) {
          this.indexer_class = (Class<? extends AbstractIndexSelector>) target_class;
        } else if (key.equals(PARAM_DESIGNER_COSTMODEL)) {
          this.costmodel_class = (Class<? extends AbstractCostModel>) target_class;

          // Special Case: TimeIntervalCostModel
          if (target_name.endsWith(TimeIntervalCostModel.class.getSimpleName())) {
            this.costmodel =
                new TimeIntervalCostModel<SingleSitedCostModel>(
                    this.catalog_db, SingleSitedCostModel.class, this.num_intervals);
          } else {
            this.costmodel =
                ClassUtil.newInstance(
                    this.costmodel_class,
                    new Object[] {this.catalog_db},
                    new Class[] {Database.class});
          }
        } else {
          assert (false) : "Invalid key '" + key + "'";
        }
      }
    } // FOR

    // -------------------------------------------------------
    // TRANSACTION ESTIMATION COMPONENTS
    // -------------------------------------------------------
    if (this.params.containsKey(PARAM_MAPPINGS)) {
      assert (this.catalog_db != null);
      File path = new File(this.params.get(PARAM_MAPPINGS));
      if (path.exists()) {
        this.param_mappings.load(path.getAbsolutePath(), this.catalog_db);
      } else {
        LOG.warn("The ParameterMappings file '" + path + "' does not exist");
      }
    }
    if (this.params.containsKey(PARAM_MARKOV_THRESHOLDS_VALUE)) {
      assert (this.catalog_db != null);
      float defaultValue = this.getDoubleParam(PARAM_MARKOV_THRESHOLDS_VALUE).floatValue();
      this.thresholds = new EstimationThresholds(defaultValue);
      this.params.put(PARAM_MARKOV_THRESHOLDS, this.thresholds.toString());
      LOG.debug("CREATED THRESHOLDS: " + this.thresholds);

    } else if (this.params.containsKey(PARAM_MARKOV_THRESHOLDS)) {
      assert (this.catalog_db != null);
      this.thresholds = new EstimationThresholds();
      File path = new File(this.params.get(PARAM_MARKOV_THRESHOLDS));
      if (path.exists()) {
        this.thresholds.load(path.getAbsolutePath(), this.catalog_db);
      } else {
        LOG.warn("The estimation thresholds file '" + path + "' does not exist");
      }
      LOG.debug("LOADED THRESHOLDS: " + this.thresholds);
    }

    // -------------------------------------------------------
    // HASHER
    // -------------------------------------------------------
    if (this.catalog != null) {
      if (this.params.containsKey(PARAM_HASHER_CLASS)) {
        String hasherClassName = this.params.get(PARAM_HASHER_CLASS);
        this.hasher_class = (Class<? extends AbstractHasher>) loader.loadClass(hasherClassName);
      }
      Constructor<? extends AbstractHasher> constructor =
          this.hasher_class.getConstructor(new Class[] {Database.class, Integer.class});
      int num_partitions = CatalogUtil.getNumberOfPartitions(this.catalog_db);
      this.hasher = constructor.newInstance(new Object[] {this.catalog_db, num_partitions});
      if (!(this.hasher instanceof DefaultHasher))
        LOG.debug("Loaded hasher " + this.hasher.getClass());

      if (this.params.containsKey(PARAM_HASHER_PROFILE)) {
        this.hasher.load(this.params.get(PARAM_HASHER_PROFILE), null);
      }
    }

    // -------------------------------------------------------
    // SAMPLE WORKLOAD TRACE
    // -------------------------------------------------------
    this.loadWorkload();
  }
 /**
  * Helper method to use for locating Class for given name. Should be used instead of basic <code>
  * Class.forName(className);</code> as it can try using contextual class loader, or use
  * platform-specific workarounds (like on Android, GAE).
  */
 public Class<?> findClass(String className) throws ClassNotFoundException {
   // By default, delegate to ClassUtil: can be overridden with custom handling
   return ClassUtil.findClass(className);
 }
 protected String determineClassName(Object instance) {
   return ClassUtil.getClassDescription(instance);
 }
Esempio n. 19
0
  protected void addDeclaration(SimpleNode decl, SimpleNode other, boolean added) {
    dubaj.tr.Ace.log("decl: " + decl);

    if (decl instanceof ASTClassOrInterfaceBodyDeclaration) {
      decl = TypeDeclarationUtil.getDeclaration((ASTClassOrInterfaceBodyDeclaration) decl);
    }

    if (decl instanceof ASTMethodDeclaration) {
      ASTMethodDeclaration method = (ASTMethodDeclaration) decl;
      String fullName = MethodUtil.getFullName(method);
      addDeclaration(
          added,
          METHOD_ADDED,
          METHOD_REMOVED,
          fullName,
          other,
          method,
          Relatorio.TipoDeclaracao.Metodo);
      if (added) {
        Relatorio.getMudancaClasse().incrementarMudancasMetodo(new MudancaMetodoAdicao(method));
      } else {
        Relatorio.getMudancaClasse().incrementarMudancasMetodo(new MudancaMetodoRemocao(method));
      }

    } else if (decl instanceof ASTFieldDeclaration) {
      ASTFieldDeclaration field = (ASTFieldDeclaration) decl;
      String names = FieldUtil.getNames(field);
      addDeclaration(
          added,
          FIELD_ADDED,
          FIELD_REMOVED,
          names,
          other,
          field,
          Relatorio.TipoDeclaracao.Atributo);

      if (added) {
        Relatorio.getMudancaClasse().incrementarMudancasAtributo();
      } else {
        Relatorio.getMudancaClasse().incrementarMudancasAtributo();
      }

    } else if (decl instanceof ASTConstructorDeclaration) {
      ASTConstructorDeclaration ctor = (ASTConstructorDeclaration) decl;
      String fullName = CtorUtil.getFullName(ctor);
      addDeclaration(
          added,
          CONSTRUCTOR_ADDED,
          CONSTRUCTOR_REMOVED,
          fullName,
          other,
          ctor,
          Relatorio.TipoDeclaracao.Construtor);
    } else if (decl instanceof ASTClassOrInterfaceDeclaration) {
      ASTClassOrInterfaceDeclaration coid = (ASTClassOrInterfaceDeclaration) decl;
      String name = ClassUtil.getName(coid).image;
      String addMsg = null;
      String remMsg = null;
      if (coid.isInterface()) {
        addMsg = INNER_INTERFACE_ADDED;
        remMsg = INNER_INTERFACE_REMOVED;
      } else {
        addMsg = INNER_CLASS_ADDED;
        remMsg = INNER_CLASS_REMOVED;
      }
      addDeclaration(
          added, addMsg, remMsg, name, other, coid, Relatorio.TipoDeclaracao.DeclaracaoClasse);
    } else if (decl == null) {
      // nothing.
    } else {
      dubaj.tr.Ace.stack(dubaj.tr.Ace.REVERSE, "WTF? decl: " + decl);
    }
  }