Exemplo n.º 1
0
  public static String getDataUsingKey(String data) {
    String message = "";
    JsonParser parser = new JsonParser();
    JsonObject jObj = (JsonObject) parser.parse(data);
    for (Map.Entry<String, JsonElement> e : jObj.entrySet()) {
      LoggerUtils.log(e.getKey());
      LoggerUtils.log(e.getValue().toString());
      JsonElement values = e.getValue();
      JsonArray jsonArray = values.getAsJsonArray();

      message = message + e.getKey() + ":";
      for (int i = 0; i < jsonArray.size(); i++) {
        message = message + jsonArray.get(i).getAsString();
      }
      message = message + "\n";
    }
    return message;
  }
  @Test
  public void testFromSpecWithGUI() {
    LoggerUtils.createGlobalConsoleLogger();

    Lawn lawn = new Lawn(5, 5);

    String cmds1 = "GAGAGAGAA";
    AutomaticLawnMower mower1 =
        new AutomaticLawnMower(
            lawn, new Point(1, 2), CardinalDirection.North, parseCommands(cmds1));
    LawnGUIUtils.setupGUI(lawn, mower1, 500);
    mower1.run();
    TestCase.assertEquals(new Lawn.Point(1, 3), mower1.getPoint());
    TestCase.assertEquals(CardinalDirection.North, mower1.getDirection());

    String cmds2 = "AADAADADDA";
    AutomaticLawnMower mower2 =
        new AutomaticLawnMower(lawn, new Point(3, 3), CardinalDirection.Est, parseCommands(cmds2));
    LawnGUIUtils.setupGUI(lawn, mower2, 500);
    mower2.run();
    TestCase.assertEquals(new Lawn.Point(5, 1), mower2.getPoint());
    TestCase.assertEquals(CardinalDirection.Est, mower2.getDirection());
  }
public class DaoUtils {

  private static Logger logger = LoggerUtils.getLogger("DaoUtils");

  /**
   * Add by linjy on 2015-12-25
   *
   * @param rsm 结果集元素组
   * @return 封装好的 key 字段名 value 值
   */
  public static List<Map<String, String>> getResultMap(ResultSet rs) {
    List<Map<String, String>> resultList = new ArrayList<Map<String, String>>();
    List<String> columName = new ArrayList<String>();
    try {
      ResultSetMetaData rsm = rs.getMetaData();
      for (int i = 1; i <= rsm.getColumnCount(); i++) {
        columName.add(rsm.getColumnName(i));
      }
      while (rs.next()) {
        Map<String, String> resuleMap = new HashMap<String, String>();
        for (String name : columName) {
          resuleMap.put(name.toLowerCase(), rs.getString(name));
        }
        resultList.add(resuleMap);
      }
    } catch (Exception e) {
      e.printStackTrace();
      logger.info("封装多条数据为key 字段名	value 值 出错,出错原因:" + e.getMessage());
    } finally {
      DaoUtils.closeResultSet(rs);
    }

    return resultList;
  }

  public static void closeConn(Connection conn) {
    if (null != conn) {
      try {
        conn.close();
      } catch (SQLException e) {
        e.printStackTrace();
        logger.error("关闭Hive连接失败,失败原因为:" + e.getMessage());
      }
    }
  }

  public static void closeStatement(Statement stmt) {
    if (null != stmt) {
      try {
        stmt.close();
      } catch (SQLException e) {
        e.printStackTrace();
        logger.error("关闭Hive Statement失败,失败原因为:" + e.getMessage());
      }
    }
  }

  public static void closeResultSet(ResultSet rs) {
    if (null != rs) {
      try {
        rs.close();
      } catch (SQLException e) {
        e.printStackTrace();
        logger.error("关闭Hive ResultSet失败,失败原因为:" + e.getMessage());
      }
    }
  }
}
  @SuppressForbidden(reason = "C2 integration (File API)")
  @Override
  protected void doStart() throws ElasticsearchException {
    try {
      Settings.Builder builder = Settings.builder();
      Path pluginConfigPath = environment.configFile().resolve(ClusteringPlugin.PLUGIN_NAME);

      if (!Files.isDirectory(pluginConfigPath)) {
        Path srcConfig = Paths.get("src/main/config");
        if (Files.isDirectory(srcConfig)) {
          // Allow running from within the IDE.
          pluginConfigPath = srcConfig;
        } else {
          throw new ElasticsearchException("Config folder missing: " + pluginConfigPath);
        }
      } else {
        logger.info("Configuration files at: {}", pluginConfigPath.toAbsolutePath());
      }

      for (String configName :
          new String[] {"config.yml", "config.yaml", "config.json", "config.properties"}) {
        try {
          Path resolved = pluginConfigPath.resolve(configName);
          if (resolved != null && Files.exists(resolved)) {
            builder.loadFromPath(resolved);
          }
        } catch (NoClassDefFoundError e) {
          logger.warn("Could not parse: {}", e, configName);
        }
      }
      Settings c2Settings = builder.build();

      // Parse suite descriptors with loggers turned off (shut them up a bit).
      final Path suitePath = pluginConfigPath.resolve(c2Settings.get(DEFAULT_SUITE_PROPERTY_NAME));
      if (!Files.isRegularFile(suitePath)) {
        throw new ElasticsearchException(
            "Could not find algorithm suite: " + suitePath.toAbsolutePath().normalize());
      }

      final ResourceLookup suiteLookup =
          new ResourceLookup(new DirLocator(suitePath.getParent().toFile()));
      final IResource suiteResource = suiteLookup.getFirst(suitePath.getFileName().toString());

      final List<String> failed = Lists.newArrayList();
      final ProcessingComponentSuite suite =
          LoggerUtils.quietCall(
              new Callable<ProcessingComponentSuite>() {
                public ProcessingComponentSuite call() throws Exception {
                  ProcessingComponentSuite suite =
                      ProcessingComponentSuite.deserialize(suiteResource, suiteLookup);
                  for (ProcessingComponentDescriptor desc : suite.removeUnavailableComponents()) {
                    failed.add(desc.getId());
                    if (isNoClassDefFound(desc.getInitializationFailure())) {
                      logger.debug("Algorithm not available on classpath: {}", desc.getId());
                    } else {
                      logger.warn(
                          "Algorithm initialization failed: {}",
                          desc.getInitializationFailure(),
                          desc.getId());
                    }
                  }
                  return suite;
                }
              },
              Logger.getLogger(ProcessingComponentDescriptor.class),
              Logger.getLogger(ReflectionUtils.class));

      algorithms = Lists.newArrayList();
      for (ProcessingComponentDescriptor descriptor : suite.getAlgorithms()) {
        algorithms.add(descriptor.getId());
      }
      algorithms = Collections.unmodifiableList(algorithms);

      if (!algorithms.isEmpty()) {
        logger.info("Available clustering components: {}", Joiner.on(", ").join(algorithms));
      }
      if (!failed.isEmpty()) {
        logger.info("Unavailable clustering components: {}", Joiner.on(", ").join(failed));
      }

      final Path resourcesPath =
          pluginConfigPath
              .resolve(c2Settings.get(DEFAULT_RESOURCES_PROPERTY_NAME, "."))
              .toAbsolutePath()
              .normalize();

      logger.info("Lexical resources dir: {}", resourcesPath);

      final ResourceLookup resourceLookup =
          new ResourceLookup(
              new DirLocator(resourcesPath.toFile()),
              new ClassLoaderLocator(ControllerSingleton.class.getClassLoader()));

      // Change the default resource lookup to include the configured location.
      Map<String, Object> c2SettingsAsMap = Maps.newHashMap();
      DefaultLexicalDataFactoryDescriptor.attributeBuilder(c2SettingsAsMap)
          .resourceLookup(resourceLookup);
      c2SettingsAsMap.putAll(c2Settings.getAsMap());

      // Set up the license for Lingo3G, if it's available.
      Path lingo3gLicense = scanForLingo3GLicense(environment, pluginConfigPath);
      if (lingo3gLicense != null && Files.isReadable(lingo3gLicense)) {
        c2SettingsAsMap.put("license", new FileResource(lingo3gLicense.toFile()));
      } else if (algorithms.contains("lingo3g")) {
        logger.warn(
            "Lingo3G is on classpath, but no licenses have been found. Check out the documentation.");
      }

      // Create component pool.
      Integer poolSize = c2Settings.getAsInt(DEFAULT_COMPONENT_SIZE_PROPERTY_NAME, 0);
      if (poolSize > 0) {
        controller = ControllerFactory.createPooling(poolSize);
      } else {
        controller = ControllerFactory.createPooling();
      }
      controller.init(c2SettingsAsMap, suite.getComponentConfigurations());
    } catch (Exception e) {
      throw new ElasticsearchException("Could not start Carrot2 controller.", e);
    }

    if (algorithms == null || algorithms.isEmpty()) {
      throw new ElasticsearchException(
          "No registered/ available clustering algorithms? Check the logs, it's odd.");
    }
  }