/**
   * Resolves the directory to store the FST models based on the configured {@link
   * IndexConfiguration#FST_FOLDER}. Also considering the name of the SolrServer and SolrCore
   *
   * @param core
   * @param fstFolderConfig
   * @return
   */
  private File getFstDirectory(SolrCore core, String fstFolderConfig) {
    StrSubstitutor substitutor =
        new StrSubstitutor(new SolrCoreStrLookup(indexReference, core, bundleContext));
    substitutor.setEnableSubstitutionInVariables(true);
    String folderStr = substitutor.replace(fstFolderConfig);
    if (folderStr.indexOf("${") > 0) {
      folderStr = substitutor.replace(folderStr);
    }
    // convert separators to the current OS
    folderStr = FilenameUtils.separatorsToSystem(folderStr);
    File fstDir = new File(folderStr);
    if (!fstDir.isDirectory()) { // create the FST directory
      try {
        FileUtils.forceMkdir(fstDir);
      } catch (IOException e) {
        unregisterEngine(); // unregister current engine and clean up
        throw new IllegalStateException(
            "Unable to create Directory for"
                + "storing the FST files at location '"
                + fstDir
                + "'.");
      }
    }

    return fstDir;
  }
  private Set<String> getResourceNames(
      String namespaceName, Configuration config, String resourceType)
      throws MalformedURLException {
    Map<String, String> valueMap = new HashMap<String, String>();
    Azure azure = config.getAzure();
    valueMap.put("SubscriptionId", azure.getSubscriptionId());
    valueMap.put("NameSpace", namespaceName);
    valueMap.put("ResourceType", resourceType);
    StrSubstitutor strSubstitutor = new StrSubstitutor(valueMap);
    String resourceNamesUrlString = strSubstitutor.replace(RESOURCE_NAMES_URL);
    URL resourceNamesUrl = new URL(resourceNamesUrlString);

    if (logger.isDebugEnabled()) {
      logger.debug("Request resource from URL [ " + resourceNamesUrl + " ]");
    }

    InputStream inputStream =
        processGetRequest(
            resourceNamesUrl, azure.getKeyStoreLocation(), azure.getKeyStorePassword());

    XStream xstream = new XStream();
    xstream.ignoreUnknownElements();
    xstream.processAnnotations(Feed.class);
    xstream.processAnnotations(Entry.class);
    Feed feed = (Feed) xstream.fromXML(inputStream);

    Set<String> topicNames = new HashSet<String>();
    List<Entry> entries = feed.getEntries();
    if (entries != null && !entries.isEmpty()) {
      for (Entry entry : entries) {
        topicNames.add(entry.getTitle());
      }
    }
    return topicNames;
  }
Пример #3
0
  /**
   * @see io.apiman.manager.api.core.IMetricsAccessor#getResponseStatsSummary(java.lang.String,
   *     java.lang.String, java.lang.String, org.joda.time.DateTime, org.joda.time.DateTime)
   */
  @Override
  @SuppressWarnings("nls")
  public ResponseStatsSummaryBean getResponseStatsSummary(
      String organizationId, String serviceId, String version, DateTime from, DateTime to) {
    ResponseStatsSummaryBean rval = new ResponseStatsSummaryBean();

    try {
      String query =
          "{"
              + "  \"query\": {"
              + "    \"filtered\" : {"
              + "      \"query\" : {"
              + "        \"range\" : {"
              + "          \"requestStart\" : {"
              + "            \"gte\": \"${from}\","
              + "            \"lte\": \"${to}\""
              + "          }"
              + "        }"
              + "      },"
              + "      \"filter\": {"
              + "        \"and\" : ["
              + "          { \"term\" : { \"serviceOrgId\" : \"${serviceOrgId}\" } },"
              + "          { \"term\" : { \"serviceId\" : \"${serviceId}\" } },"
              + "          { \"term\" : { \"serviceVersion\" : \"${serviceVersion}\" } }"
              + "        ]"
              + "      }"
              + "    }"
              + "  },"
              + "  \"size\": 0, "
              + "  \"aggs\" : {"
              + "    \"total_failures\" : {"
              + "      \"filter\" : { \"term\": { \"failure\": true } }"
              + "    },"
              + "    \"total_errors\" : {"
              + "      \"filter\" : { \"term\": { \"error\": true } }"
              + "    }"
              + "  }"
              + "}";
      Map<String, String> params = new HashMap<>();
      params.put("from", formatDate(from));
      params.put("to", formatDate(to));
      params.put("serviceOrgId", organizationId.replace('"', '_'));
      params.put("serviceId", serviceId.replace('"', '_'));
      params.put("serviceVersion", version.replace('"', '_'));
      StrSubstitutor ss = new StrSubstitutor(params);
      query = ss.replace(query);

      Search search = new Search.Builder(query).addIndex(INDEX_NAME).addType("request").build();
      SearchResult response = getEsClient().execute(search);

      rval.setTotal(response.getTotal());
      rval.setFailures(
          response.getAggregations().getFilterAggregation("total_failures").getCount());
      rval.setErrors(response.getAggregations().getFilterAggregation("total_errors").getCount());
    } catch (IOException e) {
      log.error(e);
    }

    return rval;
  }
 @Override
 public Path nextFilePath() {
   Map<String, String> params = new HashMap<String, String>();
   params.put(FNAME_SUB_PART_INDEX, String.valueOf(index));
   params.put(FNAME_SUB_CONTEXT_ID, Integer.toString(contextId));
   StrSubstitutor sub = new StrSubstitutor(params, "%(", ")");
   index++;
   return new Path(sub.replace(getFilePath().toString()));
 }
Пример #5
0
  public String getUrl() {
    final Map<String, String> valuesMap = new HashMap();
    valuesMap.put("lang", getLang());
    valuesMap.put("uuid", getUuid());
    final StrSubstitutor sub = new StrSubstitutor(valuesMap);

    String baseUrl = getBaseUrlForView(getType().toLowerCase(), getLang());
    return sub.replace(baseUrl);
  }
Пример #6
0
  public void process(String testString, String format) {

    Map<String, String> valueMap = new HashMap<>();
    StrSubstitutor substitution = new StrSubstitutor(valueMap);

    valueMap.put("replaceString1", "first string");
    valueMap.put("replaceString2", "second string");

    String dateFormatted = formattedString(format);

    if (dateFormatted != null) {
      valueMap.put("date", dateFormatted);
      System.out.println(substitution.replace(testString));
    }
  }
Пример #7
0
  /**
   * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
   */
  public void contextInitialized(ServletContextEvent sce) {
    ServletContext context = sce.getServletContext();
    Properties boot = loadBootProperties(context);
    String contineoHome = boot.getProperty(CONTINEO_HOME);

    // replace system properties
    if (contineoHome.indexOf("$") != -1) {
      contineoHome = StrSubstitutor.replaceSystemProperties(contineoHome);
    }

    boot.setProperty(CONTINEO_HOME, initContineoHomePath(contineoHome));
    boot.setProperty(CONTINEO_APP_ROOTDIR, initRootPath(context));
    boot.setProperty(CONTINEO_APP_PLUGINSDIR, initPluginsPath(context));
    boot.setProperty(CONTINEO_APP_PLUGINREGISTRY, initPluginRegistry());

    try {
      String log4jPath = context.getRealPath("/WEB-INF/classes/log4j.xml");
      System.out.println("log4jPath = " + log4jPath);
      Log4jConfigurer.initLogging(log4jPath);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }

    saveBootProperties(boot, context);

    // Initialize plugins
    org.contineo.util.PluginRegistry.getInstance().init();
  }
  private String getStringToSign(MessageContext msgCtxt) throws Exception {
    String msg = (String) this.properties.get("string-to-sign");
    if (msg == null || msg.equals("")) {
      // by default, get the content of the message (either request or response)
      return msgCtxt.getVariable("message.content");
    }

    // replace ALL curly-braced items in the string-to-sign
    TemplateString ts = new TemplateString(msg);
    Map valuesMap = new HashMap();
    for (String s : ts.variableNames) {
      valuesMap.put(s, msgCtxt.getVariable(s));
    }
    StrSubstitutor sub = new StrSubstitutor(valuesMap);
    String resolvedString = sub.replace(ts.template);
    return resolvedString;
  }
  private static String createConfig(String rootDir) throws IOException {
    URL configURL = TestDbService.class.getResource("db-test.yaml");
    if (configURL == null) {
      throw new IllegalStateException("Could not find cassandra.yaml");
    }

    File path = FileUtils.toFile(configURL);
    String data = FileUtils.readFileToString(path, "UTF-8");

    StrSubstitutor substitutor = new StrSubstitutor(Collections.singletonMap("rootDir", rootDir));
    String contents = substitutor.replace(data);

    File configFile = File.createTempFile("db-test", ".yaml");
    configFile.deleteOnExit();

    FileUtils.writeStringToFile(configFile, contents, "UTF-8");
    return "file:" + configFile.getAbsolutePath();
  }
Пример #10
0
  private void testProperty(String propertyName, boolean containsSubstitution) {
    String propertyValue = setup.get(propertyName);
    assertTrue(propertyName + " was not found", isNotBlank(propertyValue));
    logger.info(propertyName + "=" + propertyValue);

    if (containsSubstitution) {
      Map<String, String> valuesMap = new HashMap<String, String>();
      valuesMap.put("reset_url", "test-url");
      valuesMap.put("organization_name", "test-org");
      valuesMap.put("activation_url", "test-url");
      valuesMap.put("confirmation_url", "test-url");
      valuesMap.put("user_email", "test-email");
      valuesMap.put("pin", "test-pin");
      StrSubstitutor sub = new StrSubstitutor(valuesMap);
      String resolvedString = sub.replace(propertyValue);
      assertNotSame(propertyValue, resolvedString);
    }
  }
Пример #11
0
  /**
   * Variables to be replaced in a resource file should be in the format: $variableName$ The
   * variable to replace in the file should also also match the parameter names of the method
   * calling getFileContent.
   *
   * @param filePath
   * @param params
   * @param classRelativeToResource
   * @return
   */
  public static String getFileContent(
      String filePath, ImmutableMap<String, String> params, Class classRelativeToResource) {

    StrSubstitutor strSubstitutor = new StrSubstitutor(params);

    strSubstitutor.setVariablePrefix(RESOURCE_VARIABLE_DELIMETER);
    strSubstitutor.setVariableSuffix(RESOURCE_VARIABLE_DELIMETER);
    String fileContent;

    try {
      fileContent =
          IOUtils.toString(
              classRelativeToResource.getClassLoader().getResourceAsStream(filePath), "UTF-8");
    } catch (IOException e) {
      throw new RuntimeException("Failed to read filepath: " + filePath);
    }

    return strSubstitutor.replace(fileContent);
  }
  private void getStatsFromAzure(
      Azure azure,
      String namespaceName,
      Map<String, String> valueMap,
      String resourceName,
      String resourceType) {

    valueMap.put("ResourceName", resourceName);
    StrSubstitutor strSubstitutor = new StrSubstitutor(valueMap);
    String statsUrlString = strSubstitutor.replace(STAT_URL);
    URL statsUrl = null;
    try {
      statsUrl = new URL(statsUrlString);
    } catch (MalformedURLException e) {
      logger.error("Unable to build URL from [ " + statsUrlString + " ]");
      return;
    }

    InputStream is =
        processGetRequest(statsUrl, azure.getKeyStoreLocation(), azure.getKeyStorePassword());

    XStream xstream = new XStream();
    xstream.ignoreUnknownElements();
    xstream.processAnnotations(MetricValueSetCollection.class);
    xstream.processAnnotations(MetricValueSet.class);
    xstream.processAnnotations(MetricValue.class);
    MetricValueSetCollection metricValueSetCollection =
        (MetricValueSetCollection) xstream.fromXML(is);

    if (logger.isDebugEnabled()) {
      logger.debug(
          "Response from URL [ "
              + statsUrlString
              + " ] is [ "
              + xstream.toXML(metricValueSetCollection)
              + " ]");
    }
    extractMetrics(metricValueSetCollection, namespaceName, resourceType, resourceName);
  }
  /**
   * Reads the {@link InputStream} and substitutes system properties.
   *
   * @return {@link Reader}
   */
  private static Reader loadInputStream(InputStream propertiesStream) throws IOException {
    StringBuilder buff = new StringBuilder();

    try (InputStreamReader isr = new InputStreamReader(propertiesStream, Charset.defaultCharset());
        BufferedReader reader = new BufferedReader(isr)) {
      String line;
      while ((line = reader.readLine()) != null) {
        buff.append(line).append("\n");
      }
    }

    return new StringReader(StrSubstitutor.replaceSystemProperties(buff.toString()));
  }
  public String getText(Object element) {
    String templateText = null;

    for (ConditionalTemplate ct : templates) {
      if (ct.isTemplate((EObject) element)) {
        templateText = ct.templateText;
        break;
      }
    }

    if (templateText != null && templateText.length() > 0) {
      Object[] elements = new Object[attributeMaps.length];
      for (int i = 0; i < elements.length; i++) {
        elements[i] = attributeMaps[i].get(element);
      }

      ((EMFLookUp) substr.getVariableResolver()).elements = elements;
      return substr.replace(templateText);
    }

    return "";
  }
Пример #15
0
  /**
   * Replace keystore paths and passwords variables in original configuration file with given values
   * and set ${hostname} variable from system property: node0
   *
   * @return String content
   */
  public static String propertiesReplacer(
      String originalFile,
      String keystoreFile,
      String trustStoreFile,
      String keystorePassword,
      String vaultConfig) {
    String hostname = System.getProperty("node0");

    // expand possible IPv6 address
    try {
      hostname =
          NetworkUtils.formatPossibleIpv6Address(InetAddress.getByName(hostname).getHostAddress());
    } catch (UnknownHostException ex) {
      String message = "Cannot resolve host address: " + hostname + " , error : " + ex.getMessage();
      LOGGER.error(message);
      throw new RuntimeException(ex);
    }

    final Map<String, String> map = new HashMap<String, String>();
    String content = "";
    if (vaultConfig == null) {
      map.put("vaultConfig", "");
    } else {
      map.put("vaultConfig", vaultConfig);
    }
    map.put("hostname", hostname);
    map.put("keystore", keystoreFile);
    map.put("truststore", trustStoreFile);
    map.put("password", keystorePassword);

    try {
      content =
          StrSubstitutor.replace(
              IOUtils.toString(CoreUtils.class.getResourceAsStream(originalFile), "UTF-8"), map);
    } catch (IOException ex) {
      String message =
          "Cannot find or modify configuration file "
              + originalFile
              + " , error : "
              + ex.getMessage();
      LOGGER.error(message);
      throw new RuntimeException(ex);
    }

    return content;
  }
Пример #16
0
  /**
   * Replace variables in PicketLink configurations files with given values and set ${hostname}
   * variable from system property: node0
   *
   * @param String resourceFile
   * @param String deploymentName
   * @param String bindingType
   * @return String content
   */
  public static String propertiesReplacer(
      String resourceFile, String deploymentName, String bindingType, String idpContextPath) {

    String hostname = System.getProperty("node0");

    // expand possible IPv6 address
    try {
      hostname =
          NetworkUtils.formatPossibleIpv6Address(InetAddress.getByName(hostname).getHostAddress());
    } catch (UnknownHostException ex) {
      String message = "Cannot resolve host address: " + hostname + " , error : " + ex.getMessage();
      LOGGER.error(message);
      throw new RuntimeException(ex);
    }

    final Map<String, String> map = new HashMap<String, String>();
    String content = "";
    map.put("hostname", hostname);
    map.put("deployment", deploymentName);
    map.put("bindingType", bindingType);
    map.put("idpContextPath", idpContextPath);

    try {
      content =
          StrSubstitutor.replace(
              IOUtils.toString(
                  SAML2BasicAuthenticationTestCase.class.getResourceAsStream(resourceFile),
                  "UTF-8"),
              map);
    } catch (IOException ex) {
      String message =
          "Cannot find or modify configuration file "
              + resourceFile
              + " , error : "
              + ex.getMessage();
      LOGGER.error(message);
      throw new RuntimeException(ex);
    }
    return content;
  }
Пример #17
0
  protected MendeleyResponse fetchSearchResults(
      Client client,
      SecureUserProfile userProfile,
      AccessTokenResponse accessTokenResponse,
      PartnerConfiguration partnerConfiguration)
      throws InstantiationException, IllegalAccessException, ClassNotFoundException {
    String query = PartnerConfigurationEnum.CONFIG.getQueryGenerator().toQuery(userProfile);
    Map<String, String> valuesMap = new HashMap<String, String>();
    valuesMap.put("query", URLParamEncoder.encode(query));
    String searchRequest = StrSubstitutor.replace(partnerConfiguration.searchEndpoint, valuesMap);
    MendeleyResponse jsonResponse = getJSONResponse(client, accessTokenResponse, searchRequest);

    if (jsonResponse == null || jsonResponse.getDocuments() == null)
      log.log(Level.WARNING, "Mendeley returned an empty result list");

    int numResults = 100;
    if (userProfile.numResults != null) numResults = userProfile.numResults;

    jsonResponse.limitNumDocuments(numResults);

    return jsonResponse;
  }
  // @formatter:off
  @CreateDS(
      name = "JBossDS",
      factory = org.jboss.as.test.integration.ldap.InMemoryDirectoryServiceFactory.class,
      partitions = {
        @CreatePartition(
            name = "jboss",
            suffix = "dc=jboss,dc=org",
            contextEntry =
                @ContextEntry(
                    entryLdif =
                        "dn: dc=jboss,dc=org\n"
                            + "dc: jboss\n"
                            + "objectClass: top\n"
                            + "objectClass: domain\n\n"),
            indexes = {
              @CreateIndex(attribute = "objectClass"),
              @CreateIndex(attribute = "dc"),
              @CreateIndex(attribute = "ou")
            })
      },
      additionalInterceptors = {KeyDerivationInterceptor.class})
  @CreateLdapServer(
      transports = {
        @CreateTransport(protocol = "LDAP", port = LDAP_PORT),
        @CreateTransport(protocol = "LDAPS", port = LDAPS_PORT)
      },
      certificatePassword = "******")
  @CreateKdcServer(
      primaryRealm = KERBEROS_PRIMARY_REALM,
      kdcPrincipal = "krbtgt/" + KERBEROS_PRIMARY_REALM + "@" + KERBEROS_PRIMARY_REALM,
      searchBaseDn = "dc=jboss,dc=org",
      transports = {
        @CreateTransport(protocol = "UDP", port = KERBEROS_PORT),
        @CreateTransport(protocol = "TCP", port = KERBEROS_PORT)
      })
  // @formatter:on
  public void createLdap1(ManagementClient managementClient, final String hostname)
      throws Exception, IOException, ClassNotFoundException, FileNotFoundException {
    final Map<String, String> map = new HashMap<String, String>();
    final String cannonicalHost =
        NetworkUtils.formatPossibleIpv6Address(Utils.getCannonicalHost(managementClient));
    map.put("hostname", cannonicalHost);
    map.put("realm", KERBEROS_PRIMARY_REALM);
    directoryService1 = DSAnnotationProcessor.getDirectoryService();
    final String ldifContent =
        StrSubstitutor.replace(
            IOUtils.toString(
                KerberosServerSetupTask.class.getResourceAsStream(
                    KerberosServerSetupTask.class.getSimpleName() + ".ldif"),
                "UTF-8"),
            map);
    LOGGER.info(ldifContent);

    final SchemaManager schemaManager = directoryService1.getSchemaManager();
    try {
      for (LdifEntry ldifEntry : new LdifReader(IOUtils.toInputStream(ldifContent))) {
        directoryService1
            .getAdminSession()
            .add(new DefaultEntry(schemaManager, ldifEntry.getEntry()));
      }
    } catch (Exception e) {
      e.printStackTrace();
      throw e;
    }
    final ManagedCreateLdapServer createLdapServer =
        new ManagedCreateLdapServer(
            (CreateLdapServer) AnnotationUtils.getInstance(CreateLdapServer.class));
    FileOutputStream fos = new FileOutputStream(KEYSTORE_FILE);
    IOUtils.copy(getClass().getResourceAsStream(KEYSTORE_FILENAME), fos);
    fos.close();

    createLdapServer.setKeyStore(KEYSTORE_FILE.getAbsolutePath());
    fixTransportAddress(createLdapServer, cannonicalHost);

    ldapServer1 =
        ServerAnnotationProcessor.instantiateLdapServer(createLdapServer, directoryService1);
    krbServer1 =
        KDCServerAnnotationProcessor.getKdcServer(directoryService1, KERBEROS_PORT, cannonicalHost);
    ldapServer1.start();
  }
Пример #19
0
  /**
   * @see io.apiman.manager.api.core.IMetricsAccessor#getResponseStatsPerPlan(java.lang.String,
   *     java.lang.String, java.lang.String, org.joda.time.DateTime, org.joda.time.DateTime)
   */
  @Override
  @SuppressWarnings("nls")
  public ResponseStatsPerPlanBean getResponseStatsPerPlan(
      String organizationId, String serviceId, String version, DateTime from, DateTime to) {
    ResponseStatsPerPlanBean rval = new ResponseStatsPerPlanBean();

    try {
      String query =
          "{"
              + "  \"query\": {"
              + "    \"filtered\" : {"
              + "      \"query\" : {"
              + "        \"range\" : {"
              + "          \"requestStart\" : {"
              + "            \"gte\": \"${from}\","
              + "            \"lte\": \"${to}\""
              + "          }"
              + "        }"
              + "      },"
              + "      \"filter\": {"
              + "        \"and\" : ["
              + "          { \"term\" : { \"serviceOrgId\" : \"${serviceOrgId}\" } },"
              + "          { \"term\" : { \"serviceId\" : \"${serviceId}\" } },"
              + "          { \"term\" : { \"serviceVersion\" : \"${serviceVersion}\" } }"
              + "        ]"
              + "      }"
              + "    }"
              + "  },"
              + "  \"size\": 0, "
              + "  \"aggs\" : {"
              + "      \"by_plan\" : {"
              + "        \"terms\" : {"
              + "          \"field\" : \"planId\""
              + "        },"
              + "        \"aggs\" : {"
              + "          \"total_failures\" : {"
              + "            \"filter\" : { \"term\": { \"failure\": true } }"
              + "          },"
              + "          \"total_errors\" : {"
              + "            \"filter\" : { \"term\": { \"error\": true } }"
              + "          }"
              + "        }"
              + "      }"
              + "  }"
              + "}";
      Map<String, String> params = new HashMap<>();
      params.put("from", formatDate(from));
      params.put("to", formatDate(to));
      params.put("serviceOrgId", organizationId.replace('"', '_'));
      params.put("serviceId", serviceId.replace('"', '_'));
      params.put("serviceVersion", version.replace('"', '_'));
      StrSubstitutor ss = new StrSubstitutor(params);
      query = ss.replace(query);

      Search search = new Search.Builder(query).addIndex(INDEX_NAME).addType("request").build();
      SearchResult response = getEsClient().execute(search);
      MetricAggregation aggregations = response.getAggregations();
      ApimanTermsAggregation aggregation =
          aggregations.getAggregation("by_plan", ApimanTermsAggregation.class); // $NON-NLS-1$
      if (aggregation != null) {
        List<ApimanTermsAggregation.Entry> buckets = aggregation.getBuckets();
        int counter = 0;
        for (ApimanTermsAggregation.Entry entry : buckets) {
          ResponseStatsDataPoint point = new ResponseStatsDataPoint();
          point.setTotal(entry.getCount());
          rval.addDataPoint(
              entry.getKey(),
              entry.getCount(),
              entry.getFilterAggregation("total_failures").getCount(),
              entry.getFilterAggregation("total_errors").getCount());
          counter++;
          if (counter > 10) {
            break;
          }
        }
      }
    } catch (IOException e) {
      log.error(e);
    }

    return rval;
  }
Пример #20
0
  /**
   * @see io.apiman.manager.api.core.IMetricsAccessor#getUsage(java.lang.String, java.lang.String,
   *     java.lang.String, io.apiman.manager.api.beans.metrics.HistogramIntervalType,
   *     org.joda.time.DateTime, org.joda.time.DateTime)
   */
  @SuppressWarnings("nls")
  @Override
  public UsageHistogramBean getUsage(
      String organizationId,
      String serviceId,
      String version,
      HistogramIntervalType interval,
      DateTime from,
      DateTime to) {
    UsageHistogramBean rval = new UsageHistogramBean();
    Map<String, UsageDataPoint> index =
        generateHistogramSkeleton(rval, from, to, interval, UsageDataPoint.class);

    try {
      String query =
          "{"
              + "  \"query\": {"
              + "    \"filtered\" : {"
              + "      \"query\" : {"
              + "        \"range\" : {"
              + "          \"requestStart\" : {"
              + "            \"gte\": \"${from}\","
              + "            \"lte\": \"${to}\""
              + "          }"
              + "        }"
              + "      },"
              + "      \"filter\": {"
              + "        \"and\" : ["
              + "          { \"term\" : { \"serviceOrgId\" : \"${serviceOrgId}\" } },"
              + "          { \"term\" : { \"serviceId\" : \"${serviceId}\" } },"
              + "          { \"term\" : { \"serviceVersion\" : \"${serviceVersion}\" } }"
              + "        ]"
              + "      }"
              + "    }"
              + "  },"
              + "  \"size\": 0, "
              + "  \"aggs\" : {"
              + "      \"histogram\" : {"
              + "          \"date_histogram\" : {"
              + "              \"field\" : \"requestStart\","
              + "              \"interval\" : \"${interval}\""
              + "          }"
              + "      }"
              + "  }"
              + "}";
      Map<String, String> params = new HashMap<>();
      params.put("from", formatDate(from));
      params.put("to", formatDate(to));
      params.put("serviceOrgId", organizationId.replace('"', '_'));
      params.put("serviceId", serviceId.replace('"', '_'));
      params.put("serviceVersion", version.replace('"', '_'));
      params.put("interval", interval.name());
      StrSubstitutor ss = new StrSubstitutor(params);
      query = ss.replace(query);

      Search search = new Search.Builder(query).addIndex(INDEX_NAME).addType("request").build();
      SearchResult response = getEsClient().execute(search);
      MetricAggregation aggregations = response.getAggregations();
      DateHistogramAggregation aggregation = aggregations.getDateHistogramAggregation("histogram");
      if (aggregation != null) {
        List<DateHistogram> buckets = aggregation.getBuckets();
        for (DateHistogram entry : buckets) {
          String keyAsString = entry.getTimeAsString();
          if (index.containsKey(keyAsString)) {
            index.get(keyAsString).setCount(entry.getCount());
          }
        }
      }
    } catch (IOException e) {
      log.error(e);
    }

    return rval;
  }
 protected String interpolate(String value) {
   Object result = substitutor.replace(value);
   return (result == null) ? null : result.toString();
 }
Пример #22
0
 /**
  * Performs variable substitution on the specified string, replacing variables specified like
  * ${name} with the value of the corresponding config parameter obtained from the current context
  * Config object
  *
  * @param string the string on which to perform variable substitution
  * @return a string with any variables substituted with configuration parameter values
  */
 public static String substituteConfigParameters(String string) {
   return SUBSTITUTOR.replace(string);
 }
Пример #23
0
 /**
  * Performs variable substitution on the specified string, replacing variables specified like
  * ${name} with the value of the corresponding config parameter obtained from the current context
  * Config object. This version of the method also takes an application id to qualify the
  * parameter.
  *
  * @param applicationId the application id to use for qualifying the parameter
  * @param string the string on which to perform variable substitution
  * @return a string with any variables substituted with configuration parameter values
  */
 public static String substituteConfigParameters(String applicationId, String string) {
   StrSubstitutor sub = new StrSubstitutor(new ParameterStrLookup(applicationId));
   return sub.replace(string);
 }