org.apache.commons.lang3.text.StrSubstitutor Java Examples

The following examples show how to use org.apache.commons.lang3.text.StrSubstitutor. 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: AbstractRepairStep.java    From repairnator with MIT License 6 votes vote down vote up
protected void createPullRequest(String baseBranch,String newBranch) throws IOException, GitAPIException, URISyntaxException {
    GitHub github = RepairnatorConfig.getInstance().getGithub();

    GHRepository originalRepository = github.getRepository(this.getInspector().getRepoSlug());
    GHRepository ghForkedRepo = originalRepository.fork();

    String base = baseBranch;
    String head = ghForkedRepo.getOwnerName() + ":" + newBranch;

    System.out.println("base: " + base + " head:" + head);
    String travisURL = this.getInspector().getBuggyBuild() == null ? "" : Utils.getTravisUrl(this.getInspector().getBuggyBuild().getId(), this.getInspector().getRepoSlug());
    Map<String, String> values = new HashMap<String, String>();
    values.put("travisURL", travisURL);
    values.put("tools", String.join(",", this.getConfig().getRepairTools()));
    values.put("slug", this.getInspector().getRepoSlug());

    if (prText == null) {
        StrSubstitutor sub = new StrSubstitutor(values, "%(", ")");
        this.prText = sub.replace(DEFAULT_TEXT_PR);
    }

    GHPullRequest pullRequest = originalRepository.createPullRequest(prTitle, head, base, this.prText);
    String prURL = "https://github.com/" + this.getInspector().getRepoSlug() + "/pull/" + pullRequest.getNumber();
    this.getLogger().info("Pull request created on: " + prURL);
    this.getInspector().getJobStatus().addPRCreated(prURL);
}
 
Example #2
Source File: HttpUtils.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Given a url template, interpolate with keys and build the URI after adding query parameters
 *
 * <p>
 *   With url template: http://test.com/resource/(urn:${resourceId})/entities/(entity:${entityId}),
 *   keys: { "resourceId": 123, "entityId": 456 }, queryParams: { "locale": "en_US" }, the outpuT URI is:
 *   http://test.com/resource/(urn:123)/entities/(entity:456)?locale=en_US
 * </p>
 *
 * @param urlTemplate url template
 * @param keys data map to interpolate url template
 * @param queryParams query parameters added to the url
 * @return a uri
 */
public static URI buildURI(String urlTemplate, Map<String, String> keys, Map<String, String> queryParams) {
  // Compute base url
  String url = urlTemplate;
  if (keys != null && keys.size() != 0) {
    url = StrSubstitutor.replace(urlTemplate, keys);
  }

  try {
    URIBuilder uriBuilder = new URIBuilder(url);
    // Append query parameters
    if (queryParams != null && queryParams.size() != 0) {
      for (Map.Entry<String, String> entry : queryParams.entrySet()) {
        uriBuilder.addParameter(entry.getKey(), entry.getValue());
      }
    }
    return uriBuilder.build();
  } catch (URISyntaxException e) {
    throw new RuntimeException("Fail to build uri", e);
  }
}
 
Example #3
Source File: SalesforceSource.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Get the row count for a time range
 */
private int getCountForRange(TableCountProbingContext probingContext, StrSubstitutor sub,
    Map<String, String> subValues, long startTime, long endTime) {
  String startTimeStr = Utils.dateToString(new Date(startTime), SalesforceExtractor.SALESFORCE_TIMESTAMP_FORMAT);
  String endTimeStr = Utils.dateToString(new Date(endTime), SalesforceExtractor.SALESFORCE_TIMESTAMP_FORMAT);

  subValues.put("start", startTimeStr);
  subValues.put("end", endTimeStr);

  String query = sub.replace(PROBE_PARTITION_QUERY_TEMPLATE);

  log.debug("Count query: " + query);
  probingContext.probeCount++;

  JsonArray records = getRecordsForQuery(probingContext.connector, query);
  Iterator<JsonElement> elements = records.iterator();
  JsonObject element = elements.next().getAsJsonObject();

  return element.get("cnt").getAsInt();
}
 
Example #4
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 #5
Source File: ConfigurationServiceImpl.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Resource getPluginFile(String siteId, String type, String name, String filename)
    throws ContentNotFoundException {

    String basePath = servicesConfig.getPluginFolderPattern(siteId);
    if (StringUtils.isEmpty(basePath)) {
        throw new IllegalStateException(
            String.format("Site '%s' does not have an plugin folder pattern configured", siteId));
    } else if (!StringUtils.contains(basePath, PLACEHOLDER_TYPE) ||
        !StringUtils.contains(basePath, PLACEHOLDER_NAME)) {
        throw new IllegalStateException(String.format(
            "Plugin folder pattern for site '%s' does not contain all required placeholders", basePath));
    }

    Map<String, String> values = new HashMap<>();
    values.put(PLACEHOLDER_TYPE, type);
    values.put(PLACEHOLDER_NAME, name);
    basePath = StrSubstitutor.replace(basePath, values);

    String filePath = UrlUtils.concat(basePath, filename);

    return contentService.getContentAsResource(siteId, filePath);
}
 
Example #6
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 #7
Source File: ServerInterceptor.java    From careconnect-reference-implementation with Apache License 2.0 6 votes vote down vote up
@Override
public void processingCompletedNormally(ServletRequestDetails theRequestDetails) {
    // Perform any string substitutions from the message format

    StrLookup<?> lookup = new MyLookup(theRequestDetails.getServletRequest(), theRequestDetails);
    StrSubstitutor subs = new StrSubstitutor(lookup, "${", "}", '\\');

    for (String header : theRequestDetails.getServletResponse().getHeaderNames()) {
        log.debug("Header  = " + header + "=" + theRequestDetails.getServletResponse().getHeader(header));
    }

    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[${requestHeader.x-request-id}] ProcessingTime[${processingTimeMillis}]";

    String line = subs.replace(myMessageFormat);
    log.info(line+" ResponseCode["+theRequestDetails.getServletResponse().getStatus()+"]");
}
 
Example #8
Source File: HtmlUtils.java    From appstatus with Apache License 2.0 6 votes vote down vote up
public static String applyLayout(Map<String, String> valuesMap, String templateName) throws IOException {
	String templateString = "";

	if (templates.containsKey(templateName)) {
		templateString = templates.get(templateName);
	} else {
		// get the file
		InputStream inputStream = Resources.class.getResourceAsStream("/templates/" + templateName);

		// convert to string
		StringWriter writer = new StringWriter();
		IOUtils.copy(inputStream, writer, Charset.defaultCharset());
		templateString = writer.toString();
		templates.put(templateName, templateString);
	}

	// substitution & return
	StrSubstitutor sub = new StrSubstitutor(valuesMap);
	return sub.replace(templateString);
}
 
Example #9
Source File: RuleEditorWizard.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
public void onCreate(Map<String, Object> values) {
   String name = (String) values.get(CreateRuleRequest.ATTR_NAME);
   Map<String, Object> vars = new HashMap<String,Object>();
   for(String key: values.keySet()) {
      if(key.startsWith("var:")) {
         vars.put(key.substring(4), values.get(key));
      }
   }
   
   Oculus.showProgress(
      template
         .createRule(
               placeId,
               name,
               StrSubstitutor.replace(template.getTemplate(), vars),
               vars
         )
         .onFailure((e) -> result.setError(e))
         .onSuccess((r) -> result.setValue(true)),
      "Creating rule..."
   );
   
}
 
Example #10
Source File: RuleEditorWizard.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
public void onUpdate(Map<String, Object> values) {
   Map<String, Object> vars = new HashMap<String,Object>();
   for(String key: values.keySet()) {
      if(key.startsWith("var:")) {
         vars.put(key.substring(4), values.get(key));
      }
   }

   Oculus.showProgress(result, "Updating rule...");
   
   String templateId = (String) values.get(UpdateContextRequest.ATTR_TEMPLATE);
   rule.setName((String) values.get(CreateRuleRequest.ATTR_NAME));
   rule.setDescription(StrSubstitutor.replace(template.getTemplate(), vars));
   rule
      .commit()
      .onFailure((e) -> result.setError(e))
      .onSuccess((v) -> {
         rule
            .updateContext(vars, templateId)
            .onFailure((e) -> result.setError(e))
            .onSuccess((r) -> result.setValue(true))
            ;
      })
      ;
   
}
 
Example #11
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 #12
Source File: SalesforceSource.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Split a histogram bucket along the midpoint if it is larger than the bucket size limit.
 */
private void getHistogramRecursively(TableCountProbingContext probingContext, Histogram histogram, StrSubstitutor sub,
    Map<String, String> values, int count, long startEpoch, long endEpoch) {
  long midpointEpoch = startEpoch + (endEpoch - startEpoch) / 2;

  // don't split further if small, above the probe limit, or less than 1 second difference between the midpoint and start
  if (count <= probingContext.bucketSizeLimit
      || probingContext.probeCount > probingContext.probeLimit
      || (midpointEpoch - startEpoch < MIN_SPLIT_TIME_MILLIS)) {
    histogram.add(new HistogramGroup(Utils.epochToDate(startEpoch, SECONDS_FORMAT), count));
    return;
  }

  int countLeft = getCountForRange(probingContext, sub, values, startEpoch, midpointEpoch);

  getHistogramRecursively(probingContext, histogram, sub, values, countLeft, startEpoch, midpointEpoch);
  log.debug("Count {} for left partition {} to {}", countLeft, startEpoch, midpointEpoch);

  int countRight = count - countLeft;

  getHistogramRecursively(probingContext, histogram, sub, values, countRight, midpointEpoch, endEpoch);
  log.debug("Count {} for right partition {} to {}", countRight, midpointEpoch, endEpoch);
}
 
Example #13
Source File: YAMLConfigurationLoader.java    From dcos-commons with Apache License 2.0 6 votes vote down vote up
public static <T> T loadConfigFromEnv(Class<T> configurationClass, final String path)
    throws IOException
{
  LOGGER.info("Parsing configuration file from {} ", path);
  logProcessEnv();
  final Path configPath = Paths.get(path);
  final File file = configPath.toAbsolutePath().toFile();
  final ObjectMapper mapper = new ObjectMapper(new YAMLFactory());

  final StrSubstitutor sub = new StrSubstitutor(new StrLookup<Object>() {
    @Override
    public String lookup(String key) {
      return System.getenv(key);
    }
  });
  sub.setEnableSubstitutionInVariables(true);

  final String conf = sub.replace(FileUtils.readFileToString(file));
  return mapper.readValue(conf, configurationClass);
}
 
Example #14
Source File: SalesforceSource.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Get a histogram for the time range by probing to break down large buckets. Use count instead of
 * querying if it is non-negative.
 */
private Histogram getHistogramByProbing(TableCountProbingContext probingContext, int count, long startEpoch,
    long endEpoch) {
  Histogram histogram = new Histogram();

  Map<String, String> values = new HashMap<>();
  values.put("table", probingContext.entity);
  values.put("column", probingContext.watermarkColumn);
  values.put("greater", ">=");
  values.put("less", "<");
  StrSubstitutor sub = new StrSubstitutor(values);

  getHistogramRecursively(probingContext, histogram, sub, values, count, startEpoch, endEpoch);

  return histogram;
}
 
Example #15
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 #16
Source File: Routes.java    From gocd with Apache License 2.0 5 votes vote down vote up
public static String compare(String pipelineName, String fromCounter, String toCounter) {
    return StrSubstitutor.replace("/go/compare/${pipeline_name}/${from_counter}/with/${to_counter}", of(
            "pipeline_name", pipelineName,
            "from_counter", fromCounter,
            "to_counter", toCounter
    ));
}
 
Example #17
Source File: CustomFormat.java    From mr4c with Apache License 2.0 5 votes vote down vote up
/**
  * Create a CustomFormat with custom regular expressions for some variables
*/
public static CustomFormat createInstance(String pattern, Map<String,String> regexMap) {
	CustomFormat format = new CustomFormat();
	format.m_nameList = extractNames(pattern);
	format.m_nameSet = new HashSet<String>(format.m_nameList);
	format.m_pattern = pattern;
	Map<String,String> varMap = new HashMap<String,String>();
	for ( String name : format.m_nameSet ) {
		String regex = String.format("(%s)", regexMap.containsKey(name) ? regexMap.get(name) : VALUE_REGEX);
		varMap.put(name,regex);
	}
	format.m_regex = StrSubstitutor.replace(pattern,varMap);
	return format;
}
 
Example #18
Source File: StrSubstitutorEmailSubjectBuilder.java    From foxtrot with Apache License 2.0 5 votes vote down vote up
@Override
public String content(String identifier, Map<String, Object> context) {
    if(!TEMPLATES.containsKey(identifier)) {
        return "";
    }
    return StrSubstitutor.replace(TEMPLATES.get(identifier), context);
}
 
Example #19
Source File: MigrationResource.java    From ameba with MIT License 5 votes vote down vote up
/**
 * <p>repairView.</p>
 *
 * @param uuid a {@link java.lang.String} object.
 * @return a {@link java.lang.String} object.
 */
@GET
@Path("{uuid}/repair")
@Produces("text/html")
public String repairView(@PathParam("uuid") String uuid) {
    MigrationFeature.checkMigrationId(uuid);
    if (failMigrations.isEmpty()) {
        throw new NotFoundException();
    }

    //REPAIR
    Map<String, String> model = buildPageModel(MigrationType.REPAIR, uuid);
    StrSubstitutor sub = new StrSubstitutor(model);
    model.put("migrationUri", model.get("migrationUri") + "/repair");

    StringBuilder tabs = new StringBuilder();
    StringBuilder diffs = new StringBuilder();

    int i = 0;
    for (Map.Entry<String, MigrationFail> failEntry : failMigrations.entrySet()) {
        String dbName = failEntry.getKey();
        MigrationFail fail = failEntry.getValue();
        Migration migration = fail.migration;
        ScriptInfo info = migration.generate();

        tabs.append("<li i=\"").append(i).append("\" class=\"db-name\">").append(dbName).append("</li>");
        diffs.append("<div class=\"diff\"><h2>");
        diffs.append(Messages.get("view.app.database.repair.subTitle", fail.throwable.getLocalizedMessage()));
        diffs.append("</h2><pre>")
                .append(info.getApplyDdl())
                .append("</pre></div>");
        i++;
    }
    model.put("dbNames", tabs.toString());
    model.put("diffs", diffs.toString());

    return sub.replace(MIGRATION_HTML);
}
 
Example #20
Source File: Routes.java    From gocd with Apache License 2.0 5 votes vote down vote up
public static String stageDetailTab(String pipelineName,
                                    int pipelineCounter,
                                    String stageName,
                                    int stageCounter) {
    return StrSubstitutor.replace("/pipelines/${pipeline_name}/${pipeline_counter}/${stage_name}/${stage_counter}", of(
            "pipeline_name", pipelineName,
            "pipeline_counter", pipelineCounter,
            "stage_name", stageName,
            "stage_counter", stageCounter));
}
 
Example #21
Source File: Routes.java    From gocd with Apache License 2.0 5 votes vote down vote up
public static String self(String pipelineName, String pipelineCounter, String stageName, String stageCounter) {
    return StrSubstitutor.replace("/api/stages/${pipeline_name}/${pipeline_counter}/${stage_name}/${stage_counter}", of(
            "pipeline_name", pipelineName,
            "pipeline_counter", pipelineCounter,
            "stage_name", stageName,
            "stage_counter", stageCounter));
}
 
Example #22
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 #23
Source File: AbstractCassandraSchema.java    From heroic with Apache License 2.0 5 votes vote down vote up
private String loadTemplate(final String path, final Map<String, String> values)
    throws IOException {
    final String string;
    final ClassLoader loader = ManagedSetupConnection.class.getClassLoader();

    try (final InputStream is = loader.getResourceAsStream(path)) {
        if (is == null) {
            throw new IOException("No such resource: " + path);
        }

        string = CharStreams.toString(new InputStreamReader(is, Charsets.UTF_8));
    }

    return new StrSubstitutor(values, "{{", "}}").replace(string);
}
 
Example #24
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 #25
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 #26
Source File: KylinConfigExt.java    From kylin with Apache License 2.0 5 votes vote down vote up
@Override
public String getOptional(String prop, String dft) {
    String value = overrides.get(prop);
    if (value != null)
        return   StrSubstitutor.replace(value, System.getenv());
    else
        return super.getOptional(prop, dft);
}
 
Example #27
Source File: FederatedAddressConsumerKey.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public SimpleString getQueueName() {
   if (queueName == null) {
      Map<String, String> data = new HashMap<>();
      data.put("address", address.toString());
      data.put("routeType", routingType.name().toLowerCase());
      data.put("upstream", upstream.toString());
      data.put("federation", federation.toString());
      queueName = SimpleString.toSimpleString(StrSubstitutor.replace(queueNameFormat, data));
   }
   return queueName;
}
 
Example #28
Source File: SubstituteTransformRuntime.java    From streamline with Apache License 2.0 5 votes vote down vote up
private List<StreamlineEvent> substitute(StreamlineEvent input) {
    StreamlineEventImpl.Builder builder = StreamlineEventImpl.builder();
    StrSubstitutor substitutor = new StrSubstitutor(input);
    for(Map.Entry<String, Object> entry: input.entrySet()) {
        if(shouldSubstitue(entry.getKey(), entry.getValue())) {
            builder.put(entry.getKey(), substitutor.replace(entry.getValue()));
        } else {
            builder.put(entry.getKey(), entry.getValue());
        }
    }
    return Collections.<StreamlineEvent>singletonList(builder.dataSourceId(input.getDataSourceId()).build());
}
 
Example #29
Source File: JobEmailNotification.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
private String getBody() throws IOException {
    String jobID = jobState.getId().value();
    String status = jobState.getStatus().toString();
    String hostname = "UNKNOWN";
    List<TaskState> tasks = jobState.getTasks();
    String allTaskStatusesString = String.join(System.lineSeparator(),
                                               tasks.stream()
                                                    .map(task -> task.getId().getReadableName() + " (" +
                                                                 task.getId().toString() + ") Status: " +
                                                                 task.getStatus().toString())
                                                    .collect(Collectors.toList()));
    try {
        hostname = InetAddress.getLocalHost().getCanonicalHostName();
    } catch (UnknownHostException e) {
        logger.debug("Could not get hostname", e);
    }

    final Properties properties = EmailConfiguration.getConfiguration().getProperties();
    String templatePath = properties.getProperty(EmailConfiguration.TEMPLATE_PATH);
    String bodyTemplate = Files.toString(new File(PASchedulerProperties.getAbsolutePath(templatePath)),
                                         Charset.defaultCharset());

    Map<String, String> values = new HashMap<>();
    values.put("JOB_ID", jobID);
    values.put("JOB_STATUS", status);
    values.put("JOB_TASKS", allTaskStatusesString);
    values.put("HOST_NAME", hostname);

    // use of StrSubstitutor to replace email template parameters by job details
    String emailBody = StrSubstitutor.replace(bodyTemplate, values, "%", "%");

    return emailBody;
}
 
Example #30
Source File: FileUtils.java    From hazelcast-simulator with Apache License 2.0 5 votes vote down vote up
public static File newFile(String path) {
    path = path.trim();
    if (path.equals("~")) {
        path = USER_HOME;
    } else if (path.startsWith("~" + File.separator)) {
        path = USER_HOME + path.substring(1);
    }
    path = new StrSubstitutor().replace(path);

    return new File(path);
}