Java Code Examples for org.apache.commons.lang3.text.StrSubstitutor#replace()

The following examples show how to use org.apache.commons.lang3.text.StrSubstitutor#replace() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LogAction.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public ActionState execute(ActionContext context) {
   String message = this.message;
   if(message == null) {
      message = context.getVariable(VAR_MESSAGE, String.class);
   }
   
   Logger logger = context.logger();
   if(message == null) {
      logger.warn("Unable to retrieve log message from context [{}]", context);
   }
   else if(logger.isInfoEnabled()) {
      String logMessage = StrSubstitutor.replace(message, context.getVariables());
      logger.info(logMessage);
   }
   return ActionState.IDLE;
}
 
Example 2
Source File: LogAction.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(ActionContext context) {
   String message = this.message;
   if(message == null) {
      message = context.getVariable(VAR_MESSAGE, String.class);
   }
   
   Logger logger = context.logger();
   if(message == null) {
      logger.warn("Unable to retrieve log message from context [{}]", context);
   }
   else if(logger.isInfoEnabled()) {
      String logMessage = StrSubstitutor.replace(message, context.getVariables());
      logger.info(logMessage);
   }
}
 
Example 3
Source File: CypherUtil.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
String substituteRelationships(String query, final Multimap<String, Object> valueMap) {
  StrSubstitutor substitutor = new StrSubstitutor(new StrLookup<String>() {
    @Override
    public String lookup(String key) {
      Collection<String> resolvedRelationshipTypes =
          transform(valueMap.get(key), new Function<Object, String>() {
            @Override
            public String apply(Object input) {
              if (input.toString().matches(".*(\\s).*")) {
                throw new IllegalArgumentException(
                    "Cypher relationship templates must not contain spaces");
              }
              return curieUtil.getIri(input.toString()).orElse(input.toString());
            }

          });
      return on("|").join(resolvedRelationshipTypes);
    }
  });
  return substitutor.replace(query);
}
 
Example 4
Source File: ServerInterceptor.java    From careconnect-reference-implementation with Apache License 2.0 6 votes vote down vote up
@Override
public boolean incomingRequestPostProcessed(RequestDetails theRequestDetails, HttpServletRequest theRequest, HttpServletResponse theResponse) throws AuthenticationException {
    log.trace("incomingRequestPostProcessed "+theRequest.getMethod());
    Enumeration<String> headers = theRequest.getHeaderNames();
    while (headers.hasMoreElements()) {
        String header = headers.nextElement();
        log.debug("Header  = "+ header + "="+ theRequest.getHeader(header));
    }
    // Perform any string substitutions from the message format
    StrLookup<?> lookup = new MyLookup(theRequest, theRequestDetails);
    StrSubstitutor subs = new StrSubstitutor(lookup, "${", "}", '\\');

    // Actually log the line
    String myMessageFormat = "httpVerb[${requestVerb}] Source[${remoteAddr}] Operation[${operationType} ${idOrResourceName}] UA[${requestHeader.user-agent}] Params[${requestParameters}] RequestId[${requestHeader.x-request-id}] ForwardedFor[${requestHeader.x-forwarded-for}] ForwardedHost[${requestHeader.x-forwarded-host}] CorrelationId[] ProcessingTime[]  ResponseCode[]";

    String line = subs.replace(myMessageFormat);
    log.info(line);

    return true;
}
 
Example 5
Source File: BoxRemoteAssetUpgradeOperation.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Updates the given field to add the new element if needed
 * @param descriptor the item descriptor
 * @param item the field item
 * @param profileId the profile id
 * @param fieldName the field name
 * @return true if any field was updated
 * @throws XPathExpressionException if there is an error evaluating a XPath selector
 */
protected boolean updateField(Document descriptor, Node item, String profileId, String fieldName)
    throws XPathExpressionException {
    String fileId = (String) select(item, itemIdXpath, XPathConstants.STRING);
    String fileName = (String) select(item, itemNameXpath, XPathConstants.STRING);

    if((Boolean) select(item, urlElementName, XPathConstants.BOOLEAN)) {
        logger.info("Field {0}/{1} already has a {2} element, it will not be updated",
            fieldName, fileId, urlElementName);
    } else {
        Map<String, String> values = new HashMap<>();
        values.put(PLACEHOLDER_PROFILE, profileId);
        values.put(PLACEHOLDER_ID, fileId);
        values.put(PLACEHOLDER_EXTENSION, FilenameUtils.getExtension(fileName));

        String urlValue = StrSubstitutor.replace(urlTemplate, values);
        logger.debug("Adding url element for field {0}/{1} with value {2}",
            fieldName, fileId, urlValue);

        Element urlNode = descriptor.createElement(urlElementName);
        urlNode.setTextContent(urlValue);
        item.appendChild(urlNode);

        return true;
    }

    return false;
}
 
Example 6
Source File: NamedArgumentInterpolator.java    From arbiter with Apache License 2.0 5 votes vote down vote up
/**
 * Performs variable interpolation using the named arguments from an Action on a single String
 *
 * @param input The string possibly containing keys to be interpolated
 * @param namedArgs The key/value pairs used for interpolation
 * @param defaultArgs Default values for the named args, used if an interpolation key has no value given
 *
 * @return A copy of input with variable interpolation performed
 */
public static String interpolate(String input, final Map<String, String> namedArgs, final Map<String, String> defaultArgs) {
    if (namedArgs == null || input == null) {
        return input;
    }

    final Map<String, String> interpolationArgs = createFinalInterpolationMap(namedArgs, defaultArgs);

    return StrSubstitutor.replace(input, interpolationArgs, PREFIX, SUFFIX);
}
 
Example 7
Source File: ConfigUtils.java    From mr4c with Apache License 2.0 5 votes vote down vote up
public static String applyProperties(String template, Properties props, boolean checkAll) {
	Properties trimmed = CollectionUtils.toTrimmedProperties(props);
	String result = StrSubstitutor.replace(template, trimmed);
	if ( checkAll ) {
		Set<String> missing = extractVariables(result);
		if ( !missing.isEmpty() ) {
			throw new IllegalStateException("No values found for parameters [" + missing + "]");
		}
	}
	return result;
}
 
Example 8
Source File: ConfiguredDiffSource.java    From mr4c with Apache License 2.0 5 votes vote down vote up
private DatasetSource createOutputSource(DatasetConfig config, DiffOutput output) throws IOException {
	Map<String,String> props = new HashMap<String,String>();
	props.put(m_diffConfig.getDiffParam(), output.toString());
	ConfigSerializer ser = SerializerFactories.getSerializerFactory("application/json").createConfigSerializer(); // assume json config for now
	ser = new ParameterizedConfigSerializer(ser);
	StringWriter sw = new StringWriter();
	ser.serializeDatasetConfig(config, sw);
	String json = StrSubstitutor.replace(sw.toString(), props, "!(", ")");
	Reader reader = new StringReader(json);
	config = ser.deserializeDatasetConfig(reader);
	return DatasetSources.getDatasetSource(config);
}
 
Example 9
Source File: LDAPIdentityValidator.java    From apiman with Apache License 2.0 5 votes vote down vote up
/**
 * Formats the configured DN by replacing any properties it finds.
 * @param dnPattern
 * @param username
 * @param request
 */
private String formatDn(String dnPattern, String username, ApiRequest request) {
    Map<String, String> valuesMap = request.getHeaders().toMap();
    valuesMap.put("username", username); //$NON-NLS-1$
    StrSubstitutor sub = new StrSubstitutor(valuesMap);
    return sub.replace(dnPattern);
}
 
Example 10
Source File: AlarmClockService.java    From AlarmOn with Apache License 2.0 4 votes vote down vote up
private void refreshNotification() {
    String resolvedString = getString(R.string.no_pending_alarms);

    AlarmTime nextTime = pendingAlarms.nextAlarmTime();

    if (nextTime != null) {
        Map<String, String> values = new HashMap<>();

        values.put("t", nextTime.localizedString(getApplicationContext()));

        values.put("c", nextTime.timeUntilString(getApplicationContext()));

        String templateString = AppSettings.getNotificationTemplate(
                getApplicationContext());

        StrSubstitutor sub = new StrSubstitutor(values);

        resolvedString = sub.replace(templateString);
    }

  // Make the notification launch the UI Activity when clicked.
  final Intent notificationIntent = new Intent(this, ActivityAlarmClock.class);
  final PendingIntent launch = PendingIntent.getActivity(this, 0,
      notificationIntent, 0);

  Context c = getApplicationContext();

    NotificationCompat.Builder builder = new NotificationCompat.Builder(
            getApplicationContext());

    String notificationTitle = getString(R.string.app_name);

    if (pendingAlarms.nextAlarmId() != AlarmClockServiceBinder.NO_ALARM_ID) {
        DbAccessor db = new DbAccessor(getApplicationContext());

        AlarmInfo alarmInfo = db.readAlarmInfo(pendingAlarms.nextAlarmId());

        if (alarmInfo != null) {
            notificationTitle = alarmInfo.getName() != null && !alarmInfo.getName().isEmpty()
                    ? alarmInfo.getName()
                    : getString(R.string.app_name);
        }

        db.closeConnections();
    }

    Notification notification = builder
            .setContentIntent(launch)
            .setSmallIcon(R.drawable.ic_stat_notify_alarm)
            .setContentTitle(notificationTitle)
            .setContentText(resolvedString)
            .setColor(ContextCompat.getColor(getApplicationContext(),
                    R.color.notification_color))
            .build();
    notification.flags |= Notification.FLAG_ONGOING_EVENT;

  final NotificationManager manager =
    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  if (pendingAlarms.size() > 0 && AppSettings.displayNotificationIcon(c)) {
    manager.notify(NOTIFICATION_BAR_ID, notification);
  } else {
    manager.cancel(NOTIFICATION_BAR_ID);
  }

  setSystemAlarmStringOnLockScreen(getApplicationContext(), nextTime);
}
 
Example 11
Source File: ESMetricsAccessor.java    From apiman with Apache License 2.0 4 votes vote down vote up
/**
 * @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 apiId,
        String version, DateTime from, DateTime to) {
    ResponseStatsPerPlanBean rval = new ResponseStatsPerPlanBean();

    try {
        String query =
                "{" +
                "    \"query\": {" +
                "        \"bool\": {" +
                "            \"filter\": [{" +
                "                \"term\": {" +
                "                    \"apiOrgId\": \"${apiOrgId}\"" +
                "                }" +
                "            }, {" +
                "                \"term\": {" +
                "                    \"apiId\": \"${apiId}\"" +
                "                }" +
                "            }, {" +
                "                \"term\": {" +
                "                    \"apiVersion\": \"${apiVersion}\"" +
                "                }" +
                "            }, {" +
                "                \"range\": {" +
                "                    \"requestStart\": {" +
                "                        \"gte\": \"${from}\"," +
                "                        \"lte\": \"${to}\"" +
                "                    }" +
                "                }" +
                "            }]" +
                "        }" +
                "    }," +
                "    \"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("apiOrgId", organizationId.replace('"', '_'));
        params.put("apiId", apiId.replace('"', '_'));
        params.put("apiVersion", 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) {
                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;
}
 
Example 12
Source File: StrFormat.java    From ig-json-parser with MIT License 4 votes vote down vote up
String format() {
  return StrSubstitutor.replace(mFormatString, mInternalMap);
}
 
Example 13
Source File: ESMetricsAccessor.java    From apiman with Apache License 2.0 4 votes vote down vote up
/**
 * @see io.apiman.manager.api.core.IMetricsAccessor#getClientUsagePerApi(java.lang.String, java.lang.String, java.lang.String, org.joda.time.DateTime, org.joda.time.DateTime)
 */
@Override
@SuppressWarnings("nls")
public ClientUsagePerApiBean getClientUsagePerApi(String organizationId, String clientId,
        String version, DateTime from, DateTime to) {
    ClientUsagePerApiBean rval = new ClientUsagePerApiBean();

    try {
        String query =
                "{" +
                "    \"query\": {" +
                "        \"bool\": {" +
                "            \"filter\": [{" +
                "                    \"term\": {" +
                "                        \"clientOrgId\": \"${clientOrgId}\"" +
                "                    }" +
                "                }," +
                "                {" +
                "                    \"term\": {" +
                "                        \"clientId\": \"${clientId}\"" +
                "                    }" +
                "                }," +
                "                {" +
                "                    \"term\": {" +
                "                        \"clientVersion\": \"${clientVersion}\"" +
                "                    }" +
                "                }," +
                "                {" +
                "                    \"range\": {" +
                "                        \"requestStart\": {" +
                "                            \"gte\": \"${from}\"," +
                "                            \"lte\": \"${to}\"" +
                "                        }" +
                "                    }" +
                "                }" +
                "            ]" +
                "        }" +
                "    }," +
                "    \"size\": 0," +
                "    \"aggs\": {" +
                "        \"usage_by_api\": {" +
                "            \"terms\": {" +
                "                \"field\": \"apiId\"" +
                "            }" +
                "        }" +
                "    }" +
                "}";

        Map<String, String> params = new HashMap<>();
        params.put("from", formatDate(from));
        params.put("to", formatDate(to));
        params.put("clientOrgId", organizationId.replace('"', '_'));
        params.put("clientId", clientId.replace('"', '_'));
        params.put("clientVersion", 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("usage_by_api", ApimanTermsAggregation.class); //$NON-NLS-1$
        if (aggregation != null) {
            List<ApimanTermsAggregation.Entry> buckets = aggregation.getBuckets();
            for (ApimanTermsAggregation.Entry entry : buckets) {
                rval.getData().put(entry.getKey(), entry.getCount());
            }
        }
    } catch (IOException e) {
        log.error(e);
    }

    return rval;

}
 
Example 14
Source File: QuotaAlertManagerImpl.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
@Override
public void sendQuotaAlert(DeferredQuotaEmail emailToBeSent) {
    final AccountVO account = emailToBeSent.getAccount();
    final BigDecimal balance = emailToBeSent.getQuotaBalance();
    final BigDecimal usage = emailToBeSent.getQuotaUsage();
    final QuotaConfig.QuotaEmailTemplateTypes emailType = emailToBeSent.getEmailTemplateType();

    final List<QuotaEmailTemplatesVO> emailTemplates = _quotaEmailTemplateDao.listAllQuotaEmailTemplates(emailType.toString());
    if (emailTemplates != null && emailTemplates.get(0) != null) {
        final QuotaEmailTemplatesVO emailTemplate = emailTemplates.get(0);

        final DomainVO accountDomain = _domainDao.findByIdIncludingRemoved(account.getDomainId());
        final List<UserVO> usersInAccount = _userDao.listByAccount(account.getId());

        String userNames = "";
        final List<String> emailRecipients = new ArrayList<String>();
        for (UserVO user : usersInAccount) {
            userNames += String.format("%s <%s>,", user.getUsername(), user.getEmail());
            emailRecipients.add(user.getEmail());
        }
        if (userNames.endsWith(",")) {
            userNames = userNames.substring(0, userNames.length() - 1);
        }

        final Map<String, String> optionMap = new HashMap<String, String>();
        optionMap.put("accountName", account.getAccountName());
        optionMap.put("accountID", account.getUuid());
        optionMap.put("accountUsers", userNames);
        optionMap.put("domainName", accountDomain.getName());
        optionMap.put("domainID", accountDomain.getUuid());
        optionMap.put("quotaBalance", QuotaConfig.QuotaCurrencySymbol.value() + " " + balance.toString());
        if (emailType == QuotaEmailTemplateTypes.QUOTA_STATEMENT) {
            optionMap.put("quotaUsage", QuotaConfig.QuotaCurrencySymbol.value() + " " + usage.toString());
        }

        if (s_logger.isDebugEnabled()) {
            s_logger.debug("accountName" + account.getAccountName() + "accountID" + account.getUuid() + "accountUsers" + userNames + "domainName" + accountDomain.getName() + "domainID"
                    + accountDomain.getUuid());
        }

        final StrSubstitutor templateEngine = new StrSubstitutor(optionMap);
        final String subject = templateEngine.replace(emailTemplate.getTemplateSubject());
        final String body = templateEngine.replace(emailTemplate.getTemplateBody());
        try {
            _emailQuotaAlert.sendQuotaAlert(emailRecipients, subject, body);
            emailToBeSent.sentSuccessfully(_quotaAcc);
        } catch (Exception e) {
            s_logger.error(String.format("Unable to send quota alert email (subject=%s; body=%s) to account %s (%s) recipients (%s) due to error (%s)", subject, body, account.getAccountName(),
                    account.getUuid(), emailRecipients, e));
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Exception", e);
            }
        }
    } else {
        s_logger.error(String.format("No quota email template found for type %s, cannot send quota alert email to account %s(%s)", emailType, account.getAccountName(), account.getUuid()));
    }
}
 
Example 15
Source File: ResourceUtils.java    From incubator-pinot with Apache License 2.0 4 votes vote down vote up
/**
 * Generates the external links (if any) for a given anomaly.
 *
 * @param mergedAnomaly anomaly dto
 * @param metricDAO metric config dao
 * @param datasetDAO dataset config dao
 * @return map of external urls, keyed by link label
 */
public static Map<String, String> getExternalURLs(MergedAnomalyResultDTO mergedAnomaly, MetricConfigManager metricDAO, DatasetConfigManager datasetDAO) {
  String metric = mergedAnomaly.getMetric();
  String dataset = mergedAnomaly.getCollection();

  MetricConfigDTO metricConfigDTO = metricDAO.findByMetricAndDataset(metric, dataset);
  if (metricConfigDTO == null) {
    throw new IllegalArgumentException(String.format("Could not resolve metric '%s'", metric));
  }

  DatasetConfigDTO datasetConfigDTO = datasetDAO.findByDataset(metricConfigDTO.getDataset());
  if (datasetConfigDTO == null) {
    throw new IllegalArgumentException(String.format("Could not resolve dataset '%s'", dataset));
  }

  Map<String, String> urlTemplates = metricConfigDTO.getExtSourceLinkInfo();
  if (MapUtils.isEmpty(urlTemplates)) {
    return Collections.emptyMap();
  }

  // Construct context for substituting the keywords in URL template
  Map<String, String> context = new HashMap<>();
  populatePreAggregation(datasetConfigDTO, context);

  // context for each pair of dimension name and value
  if (MapUtils.isNotEmpty(mergedAnomaly.getDimensions())) {
    for (Map.Entry<String, String> entry : mergedAnomaly.getDimensions().entrySet()) {
      putEncoded(context, entry);
    }
  }

  Map<String, String> output = new HashMap<>();
  Map<String, String> externalLinkTimeGranularity = metricConfigDTO.getExtSourceLinkTimeGranularity();
  for (Map.Entry<String, String> externalLinkEntry : urlTemplates.entrySet()) {
    String sourceName = externalLinkEntry.getKey();
    String urlTemplate = externalLinkEntry.getValue();

    if (sourceName == null || urlTemplate == null) {
      continue;
    }

    putExternalLinkTimeContext(mergedAnomaly.getStartTime(), mergedAnomaly.getEndTime(), sourceName, context, externalLinkTimeGranularity);

    StrSubstitutor strSubstitutor = new StrSubstitutor(context);
    String result = strSubstitutor.replace(urlTemplate);

    if (PATTERN_UNMATCHED.matcher(result).find()) {
      LOG.warn("Could not create valid pattern for anomaly '{}'. Skipping.", mergedAnomaly);
      continue;
    }

    output.put(sourceName, result);
  }

  return output;
}
 
Example 16
Source File: ESMetricsAccessor.java    From apiman with Apache License 2.0 4 votes vote down vote up
/**
 * @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 apiId,
        String version, DateTime from, DateTime to) {
    ResponseStatsSummaryBean rval = new ResponseStatsSummaryBean();

    try {
        String query =
                "{" +
                "    \"query\": {" +
                "        \"bool\": {" +
                "            \"filter\": [{" +
                "                \"term\": {" +
                "                    \"apiOrgId\": \"${apiOrgId}\"" +
                "                }" +
                "            }, {" +
                "                \"term\": {" +
                "                    \"apiId\": \"${apiId}\"" +
                "                }" +
                "            }, {" +
                "                \"term\": {" +
                "                    \"apiVersion\": \"${apiVersion}\"" +
                "                }" +
                "            }, {" +
                "                \"range\": {" +
                "                    \"requestStart\": {" +
                "                        \"gte\": \"${from}\"," +
                "                        \"lte\": \"${to}\"" +
                "                    }" +
                "                }" +
                "            }]" +
                "        }" +
                "    }," +
                "    \"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("apiOrgId", organizationId.replace('"', '_'));
        params.put("apiId", apiId.replace('"', '_'));
        params.put("apiVersion", 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;
}
 
Example 17
Source File: MessageUtils.java    From sonar-gerrit-plugin with Apache License 2.0 3 votes vote down vote up
/**
 * Build a string based on an original string and the replacement by
 * settings and map values
 *
 * @param originalMessage      the original string
 * @param settings             the settings
 * @param additionalProperties the additional values
 * @return the built message
 */
private static String substituteProperties(String originalMessage, Settings settings,
                                           Map<String, Object> additionalProperties) {
    if (additionalProperties.isEmpty()) {
        return StrSubstitutor.replace(originalMessage, settings.getProperties());
    }
    additionalProperties.putAll(settings.getProperties());
    return StrSubstitutor.replace(originalMessage, additionalProperties);
}
 
Example 18
Source File: StringHelper.java    From Albianj2 with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * 通过具名参数的方式来格式化
 * @param template
 * @param values
 * @code
 * String template = "Welcome to {theWorld}. My name is {myName}.";
 * Map<String, String> values = new HashMap<>();
 * values.put("theWorld", "Stackoverflow");
 * values.put("myName", "Thanos");
 * @return
 */
public static String formatTemplate(String template, Map<String, Object> values) {
    return StrSubstitutor.replace(template, values, "{", "}");
}
 
Example 19
Source File: BeanUtil.java    From apiman-cli with Apache License 2.0 2 votes vote down vote up
/**
 * Replace the placeholders in the given input String.
 *
 * @param original     the input String, containing placeholders in the form <code>Example ${placeholder} text.</code>
 * @param replacements the Map of placeholders and their values
 * @return the {@code original} string with {@code replacements}
 */
public static String resolvePlaceholders(String original, Map<String, String> replacements) {
    return StrSubstitutor.replace(original, replacements);
}
 
Example 20
Source File: StringUtil.java    From feilong-core with Apache License 2.0 2 votes vote down vote up
/**
 * 使用给定的字符串 <code>templateString</code> 作为模板,解析匹配的变量 .
 * 
 * <h3>示例:</h3>
 * 
 * <blockquote>
 * 
 * <pre class="code">
 * String template = "/home/webuser/expressdelivery/${yearMonth}/${expressDeliveryType}/vipQuery_${fileName}.log";
 * Date date = now();
 * 
 * Map{@code <String, String>} valuesMap = newHashMap();
 * valuesMap.put("yearMonth", DateUtil.toString(date, DatePattern.YEAR_AND_MONTH));
 * valuesMap.put("expressDeliveryType", "sf");
 * valuesMap.put("fileName", DateUtil.toString(date, DatePattern.TIMESTAMP));
 * LOGGER.debug(StringUtil.replace(template, valuesMap));
 * </pre>
 * 
 * <b>返回:</b>
 * 
 * <pre class="code">
 * /home/webuser/expressdelivery/2016-06/sf/vipQuery_20160608214846.log
 * </pre>
 * 
 * </blockquote>
 * 
 * <p>
 * <span style="color:red">注意:此方法只能替换字符串,而不能像el表达式一样使用对象属性之类的来替换</span>
 * </p>
 * 
 * <h3>比如:</h3>
 * 
 * <blockquote>
 * 
 * <pre class="code">
 * Map{@code <String, Object>} valuesMap = newHashMap();
 * valuesMap.put("today", DateUtil.toString(now(), COMMON_DATE));
 * valuesMap.put("user", new User(1L));
 * LOGGER.debug(StringUtil.replace("${today}${today1}${user.id}${user}", valuesMap) + "");
 * </pre>
 * 
 * <b>返回:</b>
 * 
 * <pre class="code">
 * 2016-07-16${today1}${user.id}com.feilong.test.User@16f9a31
 * </pre>
 * 
 * </blockquote>
 *
 * @param <V>
 *            the value type
 * @param templateString
 *            the template string
 * @param valuesMap
 *            the values map
 * @return 如果 <code>templateString</code> 是 <code>StringUtils.isEmpty(templateString)</code>,返回 {@link StringUtils#EMPTY}<br>
 *         如果 <code>valuesMap</code> 是null或者empty,原样返回 <code>templateString</code><br>
 * @see org.apache.commons.lang3.text.StrSubstitutor#replace(String)
 * @see org.apache.commons.lang3.text.StrSubstitutor#replace(Object, Map)
 * @since 1.1.1
 */
public static <V> String replace(CharSequence templateString,Map<String, V> valuesMap){
    return StringUtils.isEmpty(templateString) ? EMPTY : StrSubstitutor.replace(templateString, valuesMap);
}