HwRestClientUtils.java 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. * Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
  3. */
  4. package com.bowintek.practice.util;
  5. import org.apache.logging.log4j.LogManager;
  6. import org.apache.logging.log4j.Logger;
  7. import org.elasticsearch.client.RequestOptions;
  8. import org.elasticsearch.client.RestHighLevelClient;
  9. import org.elasticsearch.client.indices.GetIndexRequest;
  10. import org.elasticsearch.hwclient.HwRestClient;
  11. import java.io.File;
  12. import java.io.IOException;
  13. /**
  14. * 客户端工具
  15. *
  16. * @since 2020-09-30
  17. */
  18. public class HwRestClientUtils {
  19. private static final Logger LOG = LogManager.getLogger(HwRestClientUtils.class);
  20. /**
  21. * 配置文件路径位置
  22. */
  23. private static final int CONFIG_PATH_ARGUMENT_INDEX = 0;
  24. /**
  25. * 获取HwRestClient
  26. *
  27. * @param args 配置参数
  28. * @return HwRestClient
  29. */
  30. public static HwRestClient getHwRestClient(String[] args) {
  31. HwRestClient hwRestClient;
  32. if (args == null
  33. || args.length < 1
  34. || args[CONFIG_PATH_ARGUMENT_INDEX] == null
  35. || args[CONFIG_PATH_ARGUMENT_INDEX].isEmpty()) {
  36. hwRestClient = new HwRestClient();
  37. } else {
  38. String configPath = args[CONFIG_PATH_ARGUMENT_INDEX];
  39. File configFile = new File(configPath);
  40. if (configFile.exists()) {
  41. if (configFile.isDirectory()) {
  42. hwRestClient = new HwRestClient(configPath);
  43. } else {
  44. try {
  45. hwRestClient =
  46. new HwRestClient(
  47. configFile
  48. .getCanonicalPath()
  49. .substring(
  50. 0,
  51. configFile.getCanonicalPath().lastIndexOf(File.separator) + 1),
  52. configFile.getName());
  53. } catch (IOException e) {
  54. hwRestClient = new HwRestClient();
  55. }
  56. }
  57. } else {
  58. hwRestClient = new HwRestClient();
  59. }
  60. }
  61. return hwRestClient;
  62. }
  63. /**
  64. * high level 客户端,判断索引是否存在
  65. *
  66. * @param highLevelClient high level 客户端
  67. * @return 索引是否存在
  68. */
  69. public static boolean isExistIndexForHighLevel(RestHighLevelClient highLevelClient, String indexName) {
  70. GetIndexRequest isExistsRequest = new GetIndexRequest(indexName);
  71. try {
  72. return highLevelClient.indices().exists(isExistsRequest, RequestOptions.DEFAULT);
  73. } catch (IOException e) {
  74. LOG.error("Judge index exist {} failed", indexName, e);
  75. }
  76. return false;
  77. }
  78. }