Пример #1
0
  /** Read the config file */
  private void setupConfig() {

    if (this.config == null)
      this.config =
          new NoCheatConfiguration(
              new File(NoCheatConfiguration.configFile),
              new File(NoCheatConfiguration.descriptionsFile));
    else
      this.config.config(
          new File(NoCheatConfiguration.configFile),
          new File(NoCheatConfiguration.descriptionsFile));

    config.setupFileLogger();

    try {
      this.chatLevel = config.getLogLevelValue("logging.logtochat");
      this.ircLevel = config.getLogLevelValue("logging.logtoirc");
      this.consoleLevel = config.getLogLevelValue("logging.logtoconsole");
      this.ircTag = config.getStringValue("logging.logtoirctag");
      this.useNewPermissionSystem = this.config.getBooleanValue("newpermsystem");
      this.showStartupMessages = this.config.getBooleanValue("showinfomessages");
    } catch (ConfigurationException e) {
      e.printStackTrace();
      this.setEnabled(false);
    }
  }
  public static void main(String[] args) {
    try {
      String oldConfigName;

      ClassLoader loader = Converter.class.getClassLoader();
      URL scpurl = loader.getResource(PREVIOUS_CONF_FILE);
      if (scpurl == null) scpurl = loader.getResource("storage-conf.xml");

      if (scpurl != null) oldConfigName = scpurl.getFile();
      else throw new ConfigurationException("Error finding previous configuration file.");
      System.out.println("Found previous configuration: " + oldConfigName);
      loadPreviousConfig(oldConfigName);

      System.out.println("Creating new configuration cassandra.yaml");
      dumpConfig("cassandra.yaml");
    } catch (IOException e) {
      System.out.println("Error creating new configuration file.");
      System.out.println(e.getMessage());
      e.printStackTrace();
    } catch (ConfigurationException e) {
      System.out.println("There was an error during config conversion.");
      System.out.println(e.getMessage());
      e.printStackTrace();
    }
  }
Пример #3
0
  @Test
  public void testVarAccess() {
    Configuration config = Configuration.instance();
    try {
      config.load();
    } catch (ConfigurationException e1) {
      e1.printStackTrace();
      fail();
    }
    BSFManager bsfManager = new BSFManager();
    BSFEngine engine = null;
    try {
      engine = bsfManager.loadScriptingEngine("BeanShell");
    } catch (BSFException e) {
      e.printStackTrace();
      fail(e.getMessage());
    }
    assertNotNull(engine);

    try {
      // ObjectRegistry registry = bsfManager.getObjectRegistry();
      // registry.register("mmm", new Integer(3));
      // engine.exec("source", 1, 1, "print( mmm );");
      engine.exec("source", 1, 1, "mmm = 1000;");
      engine.exec("source", 1, 1, "print( mmm );");
    } catch (BSFException e) {
      e.printStackTrace();
      fail(e.getMessage());
    }

    engine.terminate();
  }
Пример #4
0
 /**
  * This is the starting point of the compiler.
  *
  * @param args Command line arguments to control the compiler
  */
 public static void main(String[] args) {
   try {
     run(args);
   } catch (FileNotFoundException e) {
     System.err.println("FILE NOT FOUND: " + e.getLocalizedMessage());
     System.exit(FILE_NOT_FOUND_ERROR);
   } catch (ParseException e) {
     System.err.println("PARSE ERROR: " + e.getLocalizedMessage());
     System.exit(PARSE_ERROR);
   } catch (ShadowException e) {
     System.err.println("ERROR IN FILE: " + e.getLocalizedMessage());
     e.printStackTrace();
     System.exit(TYPE_CHECK_ERROR);
   } catch (IOException e) {
     System.err.println("FILE DEPENDENCY ERROR: " + e.getLocalizedMessage());
     e.printStackTrace();
     System.exit(TYPE_CHECK_ERROR);
   } catch (org.apache.commons.cli.ParseException e) {
     System.err.println("COMMAND LINE ERROR: " + e.getLocalizedMessage());
     Arguments.printHelp();
     System.exit(COMMAND_LINE_ERROR);
   } catch (ConfigurationException e) {
     System.err.println("CONFIGURATION ERROR: " + e.getLocalizedMessage());
     Arguments.printHelp();
     System.exit(CONFIGURATION_ERROR);
   } catch (TypeCheckException e) {
     System.err.println("TYPE CHECK ERROR: " + e.getLocalizedMessage());
     System.exit(TYPE_CHECK_ERROR);
   } catch (CompileException e) {
     System.err.println("COMPILATION ERROR: " + e.getLocalizedMessage());
     System.exit(COMPILE_ERROR);
   }
 }
  public void testInvalid() {
    EPServiceProvider epService = getEngineInitialized(null, null, null);

    // can add the same nested type twice
    epService
        .getEPAdministrator()
        .getConfiguration()
        .addEventType("ABC", new String[] {"p0"}, new Class[] {int.class});
    epService
        .getEPAdministrator()
        .getConfiguration()
        .addEventType("ABC", new String[] {"p0"}, new Class[] {int.class});
    try {
      // changing the definition however stops the compatibility
      epService
          .getEPAdministrator()
          .getConfiguration()
          .addEventType("ABC", new String[] {"p0"}, new Class[] {long.class});
      fail();
    } catch (ConfigurationException ex) {
      assertEquals(
          "Event type named 'ABC' has already been declared with differing column name or type information: Type by name 'ABC' in property 'p0' expected class java.lang.Integer but receives class java.lang.Long",
          ex.getMessage());
    }

    tryInvalid(
        epService,
        new String[] {"a"},
        new Object[] {new SupportBean()},
        "Nestable type configuration encountered an unexpected property type of 'SupportBean' for property 'a', expected java.lang.Class or java.util.Map or the name of a previously-declared Map or ObjectArray type");
  }
Пример #6
0
 private void tryInvalidConfig(
     String name, ConfigurationRevisionEventType config, String message) {
   try {
     epService.getEPAdministrator().getConfiguration().addRevisionEventType(name, config);
     fail();
   } catch (ConfigurationException ex) {
     assertEquals(message, ex.getMessage());
   }
 }
 @Test
 @Override
 public void store() throws ResourceException {
   assertNotNull(configuration);
   try {
     configuration.store();
     fail();
   } catch (ConfigurationException ce) {
     assertEquals("config.readonly.store", ce.getCode());
   }
 }
Пример #8
0
 @Test
 public void checkSomeProperties() {
   try {
     Configuration.instance().load();
   } catch (ConfigurationException e) {
     e.printStackTrace();
     fail();
   }
   assertEquals(-1, Configuration.instance().getHistoryDepth());
   assertEquals(1, Configuration.instance().getInteger("tangara.level"));
 }
Пример #9
0
 @Test
 public void testLoad() {
   Configuration config = Configuration.instance();
   try {
     config.load();
   } catch (ConfigurationException e) {
     e.printStackTrace();
     fail();
   }
   assertTrue(BSFManager.isLanguageRegistered("BeanShell"));
 }
Пример #10
0
 public void testNoImplicitBindingIsCreatedForAnnotatedKeys() {
   try {
     Guice.createInjector().getInstance(Key.get(I.class, Names.named("i")));
     fail();
   } catch (ConfigurationException expected) {
     Asserts.assertContains(
         expected.getMessage(),
         "1) No implementation for " + I.class.getName(),
         "annotated with @" + Named.class.getName() + "(value=i) was bound.",
         "while locating " + I.class.getName(),
         " annotated with @" + Named.class.getName() + "(value=i)");
   }
 }
Пример #11
0
 @SuppressWarnings("unchecked")
 private void assertFailure(Injector injector, Class clazz) {
   try {
     injector.getBinding(clazz);
     fail("Shouldn't have been able to get binding of: " + clazz);
   } catch (ConfigurationException expected) {
     List<Object> sources = Iterables.getOnlyElement(expected.getErrorMessages()).getSources();
     // Assert that the first item in the sources if the key for the class we're looking up,
     // ensuring that each lookup is "new".
     assertEquals(Key.get(clazz).toString(), sources.get(0).toString());
     // Assert that the last item in each lookup contains the InvalidInterface class
     Asserts.assertContains(
         sources.get(sources.size() - 1).toString(), Key.get(InvalidInterface.class).toString());
   }
 }
  public void testObjectArrayInheritanceInitTime() {
    Configuration configuration = SupportConfigFactory.getConfiguration();

    configuration.addEventType("RootEvent", new String[] {"base"}, new Object[] {String.class});
    configuration.addEventType("Sub1Event", new String[] {"sub1"}, new Object[] {String.class});
    configuration.addEventType("Sub2Event", new String[] {"sub2"}, new Object[] {String.class});
    configuration.addEventType("SubAEvent", new String[] {"suba"}, new Object[] {String.class});
    configuration.addEventType("SubBEvent", new String[] {"subb"}, new Object[] {String.class});

    configuration.addObjectArraySuperType("Sub1Event", "RootEvent");
    configuration.addObjectArraySuperType("Sub2Event", "RootEvent");
    configuration.addObjectArraySuperType("SubAEvent", "Sub1Event");
    configuration.addObjectArraySuperType("SubBEvent", "SubAEvent");

    try {
      configuration.addObjectArraySuperType("SubBEvent", "Sub2Event");
      fail();
    } catch (ConfigurationException ex) {
      assertEquals("Object-array event types may not have multiple supertypes", ex.getMessage());
    }

    EPServiceProvider epService = EPServiceProviderManager.getDefaultProvider(configuration);
    epService.initialize();
    if (InstrumentationHelper.ENABLED) {
      InstrumentationHelper.startTest(epService, this.getClass(), getName());
    }

    EPAssertionUtil.assertEqualsExactOrder(
        new Object[] {
          new EventPropertyDescriptor(
              "base", String.class, null, false, false, false, false, false),
          new EventPropertyDescriptor(
              "sub1", String.class, null, false, false, false, false, false),
          new EventPropertyDescriptor(
              "suba", String.class, null, false, false, false, false, false),
        },
        ((EPServiceProviderSPI) epService)
            .getEventAdapterService()
            .getExistsTypeByName("SubAEvent")
            .getPropertyDescriptors());

    runObjectArrInheritanceAssertion(epService);

    if (InstrumentationHelper.ENABLED) {
      InstrumentationHelper.endTest();
    }
  }
Пример #13
0
  /**
   * Startups the RESTHeart server
   *
   * @param confFilePath the path of the configuration file
   */
  public static void startup(final Path confFilePath) {
    try {
      configuration = FileUtils.getConfiguration(confFilePath, false);
    } catch (ConfigurationException ex) {
      if (RESTHEART_VERSION != null) {
        LOGGER.info(
            ansi().fg(RED).bold().a("RESTHeart").reset().toString() + " version {}",
            RESTHEART_VERSION);
      }

      LOGGER.error(ex.getMessage() + ", exiting...", ex);
      stopServer(false);
      System.exit(-1);
    }

    startServer(false);
  }
Пример #14
0
  public void addClusterSettings(ClusterSettings settings) {
    if (settings.isDefault()) {
      for (Iterator it = clusterSettings.values().iterator(); it.hasNext(); ) {
        ClusterSettings cs = (ClusterSettings) it.next();

        if (cs.isDefault()) {
          ConfigurationException cx = new ConfigurationException();
          cx.setMessage(10214, new Object[] {settings.getClusterName(), cs.getClusterName()});
          throw cx;
        }
      }
    }
    if (clusterSettings.containsKey(settings.getClusterName())) {
      ConfigurationException cx = new ConfigurationException();
      cx.setMessage(10206, new Object[] {settings.getClusterName()});
      throw cx;
    }
    clusterSettings.put(settings.getClusterName(), settings);
  }
Пример #15
0
 @Test
 public void testSysPropConf() {
   Configuration cfg = Configuration.instance();
   try {
     cfg.load();
   } catch (ConfigurationException e) {
     e.printStackTrace();
     fail();
   }
   assertNull(cfg.getProperty("name1"));
   System.setProperty(Configuration.CONF_SYS_P, "src/test/data/conf2.properties");
   Configuration cfg2 = Configuration.instance();
   try {
     cfg2.load();
   } catch (ConfigurationException e) {
     e.printStackTrace();
     fail();
   }
   assertEquals("value1", cfg2.getProperty("name1"));
   System.getProperties().remove("tangara.configuration");
 }
  public static Object execute(File artemisHome, File artemisInstance, String... args)
      throws Exception {
    try {
      return internalExecute(artemisHome, artemisInstance, args);
    } catch (ConfigurationException configException) {
      System.err.println(configException.getMessage());
      System.out.println();
      System.out.println(
          "Configuration should be specified as 'scheme:location'. Default configuration is 'xml:${ARTEMIS_INSTANCE}/etc/bootstrap.xml'");
      return configException;
    } catch (CLIException cliException) {
      System.err.println(cliException.getMessage());
      return cliException;
    } catch (RuntimeException re) {
      System.err.println(re.getMessage());
      System.out.println();

      Cli<Action> parser = builder(null).build();

      parser.parse("help").execute(ActionContext.system());
      return re;
    }
  }
Пример #17
0
  @Test
  public void testEval() {
    Configuration config = Configuration.instance();
    try {
      config.load();
    } catch (ConfigurationException ex) {
      ex.printStackTrace();
      fail();
    }
    BSFManager bsfManager = new BSFManager();

    Integer i = new Integer(5);
    try {
      bsfManager.declareBean("i", i, Integer.class);
    } catch (BSFException e) {
      e.printStackTrace();
      fail(e.getMessage());
    }

    BSFEngine engine = null;
    try {
      engine = bsfManager.loadScriptingEngine("BeanShell");
    } catch (BSFException e) {
      e.printStackTrace();
      fail(e.getMessage());
    }
    assertNotNull(engine);

    Integer j = new Integer(7);
    try {
      bsfManager.declareBean("j", j, Integer.class);
    } catch (BSFException e) {
      e.printStackTrace();
      fail(e.getMessage());
    }

    try {
      engine.exec("source", 1, 1, "a=3;\nprint(a);");
      engine.exec("source", 1, 1, "a=a+1;\nprint(a);");
    } catch (BSFException e) {
      e.printStackTrace();
      fail(e.getMessage());
    }

    try {
      engine.exec("source", 1, 1, "print(\"i=\"+i);");
      engine.exec("source", 1, 1, "j=j*10; print(\"j=\"+j);");
    } catch (BSFException e) {
      e.printStackTrace();
      fail(e.getMessage());
    }

    // BSFDeclaredBean toto = new BSFDeclaredBean();
    // toto.beannew BSFDeclaredBean("i", i, Integer.class);
    ObjectRegistry registry = bsfManager.getObjectRegistry();
    Object jValue = registry.lookup("j");
    if (jValue != null) {
      System.out.println("j-value = " + jValue.toString());
    }
    registry.register("k", new Integer(1000));
    Object kValue = registry.lookup("k");
    assertNotNull(kValue);
    System.out.println("k=" + kValue.toString());
    try {
      engine.exec("source", 1, 1, "print(\"k=\"+k);");
    } catch (BSFException e) {
      e.printStackTrace();
      fail(e.getMessage());
    }
    try {
      bsfManager.declareBean("k", kValue, Integer.class);
    } catch (BSFException e) {
      e.printStackTrace();
      fail(e.getMessage());
    }
    try {
      engine.exec("source", 1, 1, "print(\"k=\"+k);");
    } catch (BSFException e) {
      e.printStackTrace();
      fail(e.getMessage());
    }

    engine.terminate();
  }
Пример #18
0
  /**
   * main method
   *
   * @param args command line arguments
   */
  public static void main(final String[] args) {
    CONF_FILE_PATH = FileUtils.getConfigurationFilePath(args);

    try {
      // read configuration silently, to avoid logging before initializing the logger
      configuration = FileUtils.getConfiguration(args, true);
    } catch (ConfigurationException ex) {
      LOGGER.info("Starting " + ansi().fg(RED).bold().a("RESTHeart").reset().toString());

      if (RESTHEART_VERSION != null) {
        LOGGER.info("version {}", RESTHEART_VERSION);
      }

      LOGGER.error(ex.getMessage() + ", exiting...", ex);
      stopServer(false);
      System.exit(-1);
    }

    if (!hasForkOption(args)) {
      startServer(false);
    } else {
      if (OSChecker.isWindows()) {
        LOGGER.info("Starting " + ansi().fg(RED).bold().a("RESTHeart").reset().toString());

        if (RESTHEART_VERSION != null) {
          LOGGER.info("version {}", RESTHEART_VERSION);
        }

        LOGGER.error("Fork is not supported on Windows");

        LOGGER.info(ansi().fg(GREEN).bold().a("RESTHeart stopped").reset().toString());

        System.exit(-1);
      }

      // RHDaemon only works on POSIX OSes
      final boolean isPosix =
          FileSystems.getDefault().supportedFileAttributeViews().contains("posix");

      if (!isPosix) {
        LOGGER.info("Unable to fork process, " + "this is only supported on POSIX compliant OSes");

        stopServer(false);
        System.exit(-1);
      }

      RHDaemon d = new RHDaemon();

      if (d.isDaemonized()) {
        try {
          d.init();
          LOGGER.info("Forked process: {}", LIBC.getpid());
          initLogging(args, d);
        } catch (Throwable t) {
          LOGGER.error("Error staring forked process", t);
          stopServer(false, false);
          System.exit(-1);
        }

        startServer(true);
      } else {
        initLogging(args, d);

        try {
          LOGGER.info("Starting " + ansi().fg(RED).bold().a("RESTHeart").reset().toString());

          if (RESTHEART_VERSION != null) {
            LOGGER.info("version {}", RESTHEART_VERSION);
          }

          logLoggingConfiguration(true);

          d.daemonize();
        } catch (Throwable t) {
          LOGGER.error("Error forking", t);
          stopServer(false, false);
          System.exit(-1);
        }
      }
    }
  }
Пример #19
0
  public void testAddRemoveType() {
    epService = EPServiceProviderManager.getProvider("TestSchemaXML", getConfig(false));
    epService.initialize();
    updateListener = new SupportUpdateListener();
    ConfigurationOperations configOps = epService.getEPAdministrator().getConfiguration();

    // test remove type with statement used (no force)
    configOps.addEventType("MyXMLEvent", getConfigTestType("p01", false));
    EPStatement stmt =
        epService.getEPAdministrator().createEPL("select p01 from MyXMLEvent", "stmtOne");
    EPAssertionUtil.assertEqualsExactOrder(
        configOps.getEventTypeNameUsedBy("MyXMLEvent").toArray(), new String[] {"stmtOne"});

    try {
      configOps.removeEventType("MyXMLEvent", false);
    } catch (ConfigurationException ex) {
      assertTrue(ex.getMessage().contains("MyXMLEvent"));
    }

    // destroy statement and type
    stmt.destroy();
    assertTrue(configOps.getEventTypeNameUsedBy("MyXMLEvent").isEmpty());
    assertTrue(configOps.isEventTypeExists("MyXMLEvent"));
    assertTrue(configOps.removeEventType("MyXMLEvent", false));
    assertFalse(configOps.removeEventType("MyXMLEvent", false)); // try double-remove
    assertFalse(configOps.isEventTypeExists("MyXMLEvent"));
    try {
      epService.getEPAdministrator().createEPL("select p01 from MyXMLEvent");
      fail();
    } catch (EPException ex) {
      // expected
    }

    // add back the type
    configOps.addEventType("MyXMLEvent", getConfigTestType("p20", false));
    assertTrue(configOps.isEventTypeExists("MyXMLEvent"));
    assertTrue(configOps.getEventTypeNameUsedBy("MyXMLEvent").isEmpty());

    // compile
    epService.getEPAdministrator().createEPL("select p20 from MyXMLEvent", "stmtTwo");
    EPAssertionUtil.assertEqualsExactOrder(
        configOps.getEventTypeNameUsedBy("MyXMLEvent").toArray(), new String[] {"stmtTwo"});
    try {
      epService.getEPAdministrator().createEPL("select p01 from MyXMLEvent");
      fail();
    } catch (EPException ex) {
      // expected
    }

    // remove with force
    try {
      configOps.removeEventType("MyXMLEvent", false);
    } catch (ConfigurationException ex) {
      assertTrue(ex.getMessage().contains("MyXMLEvent"));
    }
    assertTrue(configOps.removeEventType("MyXMLEvent", true));
    assertFalse(configOps.isEventTypeExists("MyXMLEvent"));
    assertTrue(configOps.getEventTypeNameUsedBy("MyXMLEvent").isEmpty());

    // add back the type
    configOps.addEventType("MyXMLEvent", getConfigTestType("p03", false));
    assertTrue(configOps.isEventTypeExists("MyXMLEvent"));

    // compile
    epService.getEPAdministrator().createEPL("select p03 from MyXMLEvent");
    try {
      epService.getEPAdministrator().createEPL("select p20 from MyXMLEvent");
      fail();
    } catch (EPException ex) {
      // expected
    }
  }
  private void runObjectArrInheritanceAssertion(EPServiceProvider epService) {
    SupportUpdateListener listeners[] = new SupportUpdateListener[5];
    String[] statements = {
      "select base as vbase, sub1? as v1, sub2? as v2, suba? as va, subb? as vb from RootEvent", // 0
      "select base as vbase, sub1 as v1, sub2? as v2, suba? as va, subb? as vb from Sub1Event", // 1
      "select base as vbase, sub1? as v1, sub2 as v2, suba? as va, subb? as vb from Sub2Event", // 2
      "select base as vbase, sub1 as v1, sub2? as v2, suba as va, subb? as vb from SubAEvent", // 3
      "select base as vbase, sub1? as v1, sub2? as v2, suba? as va, subb as vb from SubBEvent" // 4
    };
    for (int i = 0; i < statements.length; i++) {
      EPStatement statement = epService.getEPAdministrator().createEPL(statements[i]);
      listeners[i] = new SupportUpdateListener();
      statement.addListener(listeners[i]);
    }
    String[] fields = "vbase,v1,v2,va,vb".split(",");

    EventType type = epService.getEPAdministrator().getConfiguration().getEventType("SubAEvent");
    assertEquals("base", type.getPropertyDescriptors()[0].getPropertyName());
    assertEquals("sub1", type.getPropertyDescriptors()[1].getPropertyName());
    assertEquals("suba", type.getPropertyDescriptors()[2].getPropertyName());
    assertEquals(3, type.getPropertyDescriptors().length);

    type = epService.getEPAdministrator().getConfiguration().getEventType("SubBEvent");
    assertEquals("[base, sub1, suba, subb]", Arrays.toString(type.getPropertyNames()));
    assertEquals(4, type.getPropertyDescriptors().length);

    type = epService.getEPAdministrator().getConfiguration().getEventType("Sub1Event");
    assertEquals("[base, sub1]", Arrays.toString(type.getPropertyNames()));
    assertEquals(2, type.getPropertyDescriptors().length);

    type = epService.getEPAdministrator().getConfiguration().getEventType("Sub2Event");
    assertEquals("[base, sub2]", Arrays.toString(type.getPropertyNames()));
    assertEquals(2, type.getPropertyDescriptors().length);

    epService
        .getEPRuntime()
        .sendEvent(new Object[] {"a", "b", "x"}, "SubAEvent"); // base, sub1, suba
    EPAssertionUtil.assertProps(
        listeners[0].assertOneGetNewAndReset(), fields, new Object[] {"a", "b", null, "x", null});
    assertFalse(listeners[2].isInvoked() || listeners[4].isInvoked());
    EPAssertionUtil.assertProps(
        listeners[1].assertOneGetNewAndReset(), fields, new Object[] {"a", "b", null, "x", null});
    EPAssertionUtil.assertProps(
        listeners[3].assertOneGetNewAndReset(), fields, new Object[] {"a", "b", null, "x", null});

    epService.getEPRuntime().sendEvent(new Object[] {"f1", "f2", "f4"}, "SubAEvent");
    EPAssertionUtil.assertProps(
        listeners[0].assertOneGetNewAndReset(),
        fields,
        new Object[] {"f1", "f2", null, "f4", null});
    assertFalse(listeners[2].isInvoked() || listeners[4].isInvoked());
    EPAssertionUtil.assertProps(
        listeners[1].assertOneGetNewAndReset(),
        fields,
        new Object[] {"f1", "f2", null, "f4", null});
    EPAssertionUtil.assertProps(
        listeners[3].assertOneGetNewAndReset(),
        fields,
        new Object[] {"f1", "f2", null, "f4", null});

    epService.getEPRuntime().sendEvent(new Object[] {"XBASE", "X1", "X2", "XY"}, "SubBEvent");
    Object[] values = new Object[] {"XBASE", "X1", null, "X2", "XY"};
    EPAssertionUtil.assertProps(listeners[0].assertOneGetNewAndReset(), fields, values);
    assertFalse(listeners[2].isInvoked());
    EPAssertionUtil.assertProps(listeners[1].assertOneGetNewAndReset(), fields, values);
    EPAssertionUtil.assertProps(listeners[3].assertOneGetNewAndReset(), fields, values);
    EPAssertionUtil.assertProps(listeners[4].assertOneGetNewAndReset(), fields, values);

    epService.getEPRuntime().sendEvent(new Object[] {"YBASE", "Y1"}, "Sub1Event");
    values = new Object[] {"YBASE", "Y1", null, null, null};
    EPAssertionUtil.assertProps(listeners[0].assertOneGetNewAndReset(), fields, values);
    assertFalse(listeners[2].isInvoked() || listeners[3].isInvoked() || listeners[4].isInvoked());
    EPAssertionUtil.assertProps(listeners[1].assertOneGetNewAndReset(), fields, values);

    epService.getEPRuntime().sendEvent(new Object[] {"YBASE", "Y2"}, "Sub2Event");
    values = new Object[] {"YBASE", null, "Y2", null, null};
    EPAssertionUtil.assertProps(listeners[0].assertOneGetNewAndReset(), fields, values);
    assertFalse(listeners[1].isInvoked() || listeners[3].isInvoked() || listeners[4].isInvoked());
    EPAssertionUtil.assertProps(listeners[2].assertOneGetNewAndReset(), fields, values);

    epService.getEPRuntime().sendEvent(new Object[] {"ZBASE"}, "RootEvent");
    values = new Object[] {"ZBASE", null, null, null, null};
    EPAssertionUtil.assertProps(listeners[0].assertOneGetNewAndReset(), fields, values);
    assertFalse(
        listeners[1].isInvoked()
            || listeners[2].isInvoked()
            || listeners[3].isInvoked()
            || listeners[4].isInvoked());

    // try property not available
    try {
      epService.getEPAdministrator().createEPL("select suba from Sub1Event");
      fail();
    } catch (EPStatementException ex) {
      assertEquals(
          "Error starting statement: Failed to validate select-clause expression 'suba': Property named 'suba' is not valid in any stream (did you mean 'sub1'?) [select suba from Sub1Event]",
          ex.getMessage());
    }

    // try supertype not exists
    try {
      epService
          .getEPAdministrator()
          .getConfiguration()
          .addEventType("Sub1Event", makeMap(""), new String[] {"doodle"});
      fail();
    } catch (ConfigurationException ex) {
      assertEquals("Supertype by name 'doodle' could not be found", ex.getMessage());
    }
  }
  public void testObjectArrayTypeUpdate() {
    Configuration configuration = SupportConfigFactory.getConfiguration();
    configuration
        .getEngineDefaults()
        .getEventMeta()
        .setDefaultEventRepresentation(Configuration.EventRepresentation.OBJECTARRAY);

    String[] names = {"base1", "base2"};
    Object[] types = {String.class, makeMap(new Object[][] {{"n1", int.class}})};
    configuration.addEventType("MyOAEvent", names, types);

    EPServiceProvider epService = EPServiceProviderManager.getDefaultProvider(configuration);
    epService.initialize();
    if (InstrumentationHelper.ENABLED) {
      InstrumentationHelper.startTest(epService, this.getClass(), getName());
    }

    EPStatement statementOne =
        epService
            .getEPAdministrator()
            .createEPL(
                "select base1 as v1, base2.n1 as v2, base3? as v3, base2.n2? as v4 from MyOAEvent");
    assertEquals(Object[].class, statementOne.getEventType().getUnderlyingType());
    EPStatement statementOneSelectAll =
        epService.getEPAdministrator().createEPL("select * from MyOAEvent");
    assertEquals(
        "[base1, base2]", Arrays.toString(statementOneSelectAll.getEventType().getPropertyNames()));
    SupportUpdateListener listenerOne = new SupportUpdateListener();
    statementOne.addListener(listenerOne);
    String[] fields = "v1,v2,v3,v4".split(",");

    epService
        .getEPRuntime()
        .sendEvent(new Object[] {"abc", makeMap(new Object[][] {{"n1", 10}}), ""}, "MyOAEvent");
    EPAssertionUtil.assertProps(
        listenerOne.assertOneGetNewAndReset(), fields, new Object[] {"abc", 10, null, null});

    // update type
    String[] namesNew = {"base3", "base2"};
    Object[] typesNew = new Object[] {Long.class, makeMap(new Object[][] {{"n2", String.class}})};
    epService
        .getEPAdministrator()
        .getConfiguration()
        .updateObjectArrayEventType("MyOAEvent", namesNew, typesNew);

    EPStatement statementTwo =
        epService
            .getEPAdministrator()
            .createEPL(
                "select base1 as v1, base2.n1 as v2, base3 as v3, base2.n2 as v4 from MyOAEvent");
    EPStatement statementTwoSelectAll =
        epService.getEPAdministrator().createEPL("select * from MyOAEvent");
    SupportUpdateListener listenerTwo = new SupportUpdateListener();
    statementTwo.addListener(listenerTwo);

    epService
        .getEPRuntime()
        .sendEvent(
            new Object[] {"def", makeMap(new Object[][] {{"n1", 9}, {"n2", "xyz"}}), 20L},
            "MyOAEvent");
    EPAssertionUtil.assertProps(
        listenerOne.assertOneGetNewAndReset(), fields, new Object[] {"def", 9, 20L, "xyz"});
    EPAssertionUtil.assertProps(
        listenerTwo.assertOneGetNewAndReset(), fields, new Object[] {"def", 9, 20L, "xyz"});

    // assert event type
    assertEquals(
        "[base1, base2, base3]",
        Arrays.toString(statementOneSelectAll.getEventType().getPropertyNames()));
    assertEquals(
        "[base1, base2, base3]",
        Arrays.toString(statementTwoSelectAll.getEventType().getPropertyNames()));

    EPAssertionUtil.assertEqualsAnyOrder(
        new Object[] {
          new EventPropertyDescriptor("base3", Long.class, null, false, false, false, false, false),
          new EventPropertyDescriptor("base2", Map.class, null, false, false, false, true, false),
          new EventPropertyDescriptor(
              "base1", String.class, null, false, false, false, false, false),
        },
        statementTwoSelectAll.getEventType().getPropertyDescriptors());

    try {
      epService
          .getEPAdministrator()
          .getConfiguration()
          .updateObjectArrayEventType("dummy", new String[0], new Object[0]);
      fail();
    } catch (ConfigurationException ex) {
      assertEquals(
          "Error updating Object-array event type: Event type named 'dummy' has not been declared",
          ex.getMessage());
    }

    epService
        .getEPAdministrator()
        .getConfiguration()
        .addEventType("SupportBean", SupportBean.class);
    try {
      epService
          .getEPAdministrator()
          .getConfiguration()
          .updateObjectArrayEventType("SupportBean", new String[0], new Object[0]);
      fail();
    } catch (ConfigurationException ex) {
      assertEquals(
          "Error updating Object-array event type: Event type by name 'SupportBean' is not an Object-array event type",
          ex.getMessage());
    }

    if (InstrumentationHelper.ENABLED) {
      InstrumentationHelper.endTest();
    }
  }
Пример #22
0
  public static void main(String[] args) throws CloneNotSupportedException {

    // Parameters for the configuration
    Algo algo = Algo.NRJ;
    Type type = Type.SECOND; // 2 methods if Algo.NRJ chosen

    int nbMachines = 10;
    int nbVms = 15;
    int sumOnOff = 50;
    int nbTry = 1;
    int maxOfExp = 1;
    // /////////////////////////////////////////////

    int indexNBofExp;
    int configPower;
    List<Long> times = new ArrayList<Long>();
    long t0, t1 = System.currentTimeMillis();

    for (indexNBofExp = 1; indexNBofExp <= maxOfExp; indexNBofExp++) {
      try {
        configLogger(nbVms, nbMachines, algo.toString());
      } catch (IOException e) {
        e.printStackTrace();
      }

      log2("\n\n#################################");
      log2("######### Experiments " + indexNBofExp + " #########");
      log2("#################################");

      PhysVirtConfiguration conf = new PhysVirtConfiguration();
      try {
        conf.makeConfiguration(algo.toString(), type.toString(), nbMachines, nbVms);
      } catch (ConfigurationException e1) {
        e1.printStackTrace();
      }

      for (int i = 0; i < nbTry; i++) {

        if (i != 0) {
          log2("\n\n#################################");
          log2("######### Loops " + (i + 1) + " ###############");
          log2("#################################");
        }

        switch (algo) {
          case NRJ:
            if (i == 0) {
              configPower = conf.initPower(type.toString());
              log2("\nSolution without constraint :\n ");
              log2(conf.print(false));
              log2(conf.print(true));
              log2(conf.show(false));
              log2("\n\nWelcome to the constraint world ...");
              log2("\n\n#################################");
              log2("######### Loops " + (i + 1) + " ###############");
              log2("#################################");
              if (SPREAD) {
                // initialize enemies
                for (vmsToSpread vts : vmsToSpread.values()) {
                  for (VM vm : conf.getVms()) {
                    if (vm.getName().equals(vts.name())) {
                      conf.addEnemies(vm);
                    }
                  }
                }
              }
            } else {
              configPower = conf.getComputePower();
            }
            conf.clearMachines();
            NRJConstraint nconstraint = new NRJConstraint(conf, SPREAD);
            t0 = System.currentTimeMillis();
            nconstraint.newModel(configPower, type.toString());
            t1 = System.currentTimeMillis();
            log2(conf.print(false));
            log2(conf.print(true));
            log2(conf.show(false));
            if (conf.isSatisfied()) {
              System.out.println("\nSatisfied");
            } else {
              System.err.println("\nNot satisfied");
            }
            times.add(t1 - t0);
            break;

          case PRIORITY:
            PriorityConstraint pconstraint = new PriorityConstraint(conf);
            if (i == 0) {
              log2("\nSolution without constraint :\n ");
              log2(conf.show(false));
              log2("\n\nWelcome to the constraint world ... ");
              log2("\n\n#################################");
              log2("######### Loops " + (i + 1) + " ###############");
              log2("#################################");
            }
            t0 = System.currentTimeMillis();
            pconstraint.newModel(sumOnOff);
            t1 = System.currentTimeMillis();
            log2(conf.show(true));
            times.add(t1 - t0);
            break;
          default:
            break;
        }

        log2("\nComputation time: " + times.get(times.size() - 1));
        // Solving times
        if (times.size() > 0) {
          log2("Solving times: " + times);
          long mean = 0;
          for (Long l : times) {
            mean += l;
          }
          log2("Mean: " + mean / times.size());
        }
      }
    }
  }