List of usage examples for java.lang String join
public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
From source file:com.spankingrpgs.scarletmoon.loader.CharacterLoader.java
/** * Verifies that all the data that should be in the JSON is there. * * @param characterData The data to be verified * * @throws IllegalArgumentException if some of the data is missing. *//*from w w w .j a v a 2 s .co m*/ private void verifyData(JsonNode characterData) { List<String> missingFields = new ArrayList<>(); if (characterData.get(NAME) == null) { missingFields.add(NAME); } if (characterData.get(PRINTED_NAME) == null) { missingFields.add(PRINTED_NAME); } if (characterData.get(DESCRIPTION) == null) { missingFields.add(DESCRIPTION); } if (characterData.get(GENDER) == null) { missingFields.add(GENDER); } if (characterData.get(ATTACK_RANGES) == null) { missingFields.add(ATTACK_RANGES); } if (characterData.get(PRIMARY_STATISTICS) == null) { missingFields.add(PRIMARY_STATISTICS); } if (characterData.get(EXPERIENCE) == null) { missingFields.add(EXPERIENCE); } if (characterData.get(APPEARANCE) == null) { missingFields.add(APPEARANCE); } if (characterData.get(EQUIPMENT) == null) { missingFields.add(EQUIPMENT); } if (!missingFields.isEmpty()) { String msg = String.format("Character %s is missing the fields:\n%s", characterData, String.join("\n", missingFields)); LOG.log(Level.SEVERE, msg); throw new IllegalArgumentException(msg); } }
From source file:gov.pnnl.goss.gridappsd.service.ServiceManagerImpl.java
@Override public String startServiceForSimultion(String serviceId, String runtimeOptions, Map<String, Object> simulationContext) { String instanceId = serviceId + "-" + new Date().getTime(); // get execution path ServiceInfo serviceInfo = services.get(serviceId); if (serviceInfo == null) { //TODO: publish error on status topic throw new RuntimeException("Service not found: " + serviceId); }//from w w w . j av a2 s . c o m // are multiple allowed? if not check to see if it is already running, if it is then fail if (!serviceInfo.isMultiple_instances() && listRunningServices(serviceId).size() > 0) { throw new RuntimeException( "Service is already running and multiple instances are not allowed: " + serviceId); } File serviceDirectory = new File( getServiceConfigDirectory().getAbsolutePath() + File.separator + serviceId); ProcessBuilder processServiceBuilder = new ProcessBuilder(); Process process = null; List<String> commands = new ArrayList<String>(); Map<String, String> envVars = processServiceBuilder.environment(); //set environment variables List<EnvironmentVariable> envVarList = serviceInfo.getEnvironmentVariables(); for (EnvironmentVariable envVar : envVarList) { String value = envVar.getEnvValue(); //Right now this depends on having the simulationContext set, so don't try it if the simulation context is null if (simulationContext != null) { if (value.contains("(")) { String[] replaceValue = StringUtils.substringsBetween(envVar.getEnvValue(), "(", ")"); for (String args : replaceValue) { value = value.replace("(" + args + ")", simulationContext.get(args).toString()); } } } envVars.put(envVar.getEnvName(), value); } //add executation command commands.add(serviceInfo.getExecution_path()); //Check if static args contain any replacement values List<String> staticArgsList = serviceInfo.getStatic_args(); for (String staticArg : staticArgsList) { if (staticArg != null) { //Right now this depends on having the simulationContext set, so don't try it if the simulation context is null if (simulationContext != null) { if (staticArg.contains("(")) { String[] replaceArgs = StringUtils.substringsBetween(staticArg, "(", ")"); for (String args : replaceArgs) { staticArg = staticArg.replace("(" + args + ")", simulationContext.get(args).toString()); } } } commands.add(staticArg); } } if (runtimeOptions != null) { commands.add(runtimeOptions); } try { if (serviceInfo.getType().equals(ServiceType.PYTHON)) { commands.add(0, "python"); processServiceBuilder.command(commands); if (serviceDirectory.exists()) processServiceBuilder.directory(serviceDirectory); processServiceBuilder.redirectErrorStream(true); processServiceBuilder.redirectOutput(); logManager.log( new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(), "Starting service with command " + String.join(" ", commands), LogLevel.DEBUG, ProcessStatus.RUNNING, true), GridAppsDConstants.topic_simulationLog + simulationId); process = processServiceBuilder.start(); } else if (serviceInfo.getType().equals(ServiceType.EXE)) { processServiceBuilder.command(commands); if (serviceDirectory.exists()) processServiceBuilder.directory(serviceDirectory); processServiceBuilder.redirectErrorStream(true); processServiceBuilder.redirectOutput(); logManager.log( new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(), "Starting service with command " + String.join(" ", commands), LogLevel.DEBUG, ProcessStatus.RUNNING, true), GridAppsDConstants.topic_simulationLog + simulationId); process = processServiceBuilder.start(); } else if (serviceInfo.getType().equals(ServiceType.JAVA)) { commands.add(0, "java -jar"); processServiceBuilder.command(commands); if (serviceDirectory.exists()) processServiceBuilder.directory(serviceDirectory); processServiceBuilder.redirectErrorStream(true); processServiceBuilder.redirectOutput(); logManager.log( new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(), "Starting service with command " + String.join(" ", commands), LogLevel.DEBUG, ProcessStatus.RUNNING, true), GridAppsDConstants.topic_simulationLog + simulationId); process = processServiceBuilder.start(); } else if (serviceInfo.getType().equals(ServiceType.WEB)) { } else { throw new RuntimeException("Type not recognized " + serviceInfo.getType()); } } catch (IOException e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); String sStackTrace = sw.toString(); // stack trace as a string System.out.println(sStackTrace); StringBuilder commandString = new StringBuilder(); for (String s : commands) { commandString.append(s); commandString.append(" "); } logManager.log( new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(), "Error running command + " + commandString, LogLevel.ERROR, ProcessStatus.ERROR, true), GridAppsDConstants.topic_simulationLog + simulationId); logManager.log( new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(), sStackTrace, LogLevel.ERROR, ProcessStatus.ERROR, true), GridAppsDConstants.topic_simulationLog + simulationId); } //create serviceinstance object ServiceInstance serviceInstance = new ServiceInstance(instanceId, serviceInfo, runtimeOptions, simulationId, process); serviceInstance.setService_info(serviceInfo); //add to service instances map serviceInstances.put(instanceId, serviceInstance); return instanceId; }
From source file:net.sf.jabref.openoffice.OOBibBase.java
/** * This method inserts a cite marker in the text for the given BibEntry, * and may refresh the bibliography./*from w w w . j ava 2s . co m*/ * @param entries The entries to cite. * @param database The database the entry belongs to. * @param style The bibliography style we are using. * @param inParenthesis Indicates whether it is an in-text citation or a citation in parenthesis. * This is not relevant if numbered citations are used. * @param withText Indicates whether this should be a normal citation (true) or an empty * (invisible) citation (false). * @param sync Indicates whether the reference list should be refreshed. * @throws Exception */ public void insertEntry(List<BibEntry> entries, BibDatabase database, List<BibDatabase> allBases, OOBibStyle style, boolean inParenthesis, boolean withText, String pageInfo, boolean sync) throws Exception { try { XTextViewCursor xViewCursor = xViewCursorSupplier.getViewCursor(); if (entries.size() > 1) { if (style.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL)) { entries.sort(yearAuthorTitleComparator); } else { entries.sort(entryComparator); } } String keyString = String.join(",", entries.stream().map(entry -> entry.getCiteKey()).collect(Collectors.toList())); // Insert bookmark: String bName = getUniqueReferenceMarkName(keyString, withText ? inParenthesis ? OOBibBase.AUTHORYEAR_PAR : OOBibBase.AUTHORYEAR_INTEXT : OOBibBase.INVISIBLE_CIT); // If we should store metadata for page info, do that now: if (pageInfo != null) { LOGGER.info("Storing page info: " + pageInfo); setCustomProperty(bName, pageInfo); } xViewCursor.getText().insertString(xViewCursor, " ", false); if (style.isFormatCitations()) { XPropertySet xCursorProps = UnoRuntime.queryInterface(XPropertySet.class, xViewCursor); String charStyle = style.getCitationCharacterFormat(); try { xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); } catch (UnknownPropertyException | PropertyVetoException | IllegalArgumentException | WrappedTargetException ex) { // Setting the character format failed, so we throw an exception that // will result in an error message for the user. Before that, // delete the space we inserted: xViewCursor.goLeft((short) 1, true); xViewCursor.setString(""); throw new UndefinedCharacterFormatException(charStyle); } } xViewCursor.goLeft((short) 1, false); Map<BibEntry, BibDatabase> databaseMap = new HashMap<>(); for (BibEntry entry : entries) { databaseMap.put(entry, database); } String citeText = style.isNumberEntries() ? "-" : style.getCitationMarker(entries, databaseMap, inParenthesis, null, null); insertReferenceMark(bName, citeText, xViewCursor, withText, style); xViewCursor.collapseToEnd(); xViewCursor.goRight((short) 1, false); XTextRange position = xViewCursor.getEnd(); if (sync) { // To account for numbering and for uniqiefiers, we must refresh the cite markers: updateSortedReferenceMarks(); refreshCiteMarkers(allBases, style); // Insert it at the current position: rebuildBibTextSection(allBases, style); } // Go back to the relevant position: xViewCursor.gotoRange(position, false); } catch (DisposedException ex) { // We need to catch this one here because the OpenOfficePanel class is // loaded before connection, and therefore cannot directly reference // or catch a DisposedException (which is in a OO jar file). throw new ConnectionLostException(ex.getMessage()); } }
From source file:net.yacy.grid.io.index.YaCyQuery.java
private QueryBuilder parse(String q, int timezoneOffset) { // detect usage of OR ORconnective usage. Because of the preparse step we will have only OR or only AND here. q = q.replaceAll(" AND ", " "); // AND is default boolean ORconnective = q.indexOf(" OR ") >= 0; q = q.replaceAll(" OR ", " "); // if we know that all terms are OR, we remove that and apply it later. Because we splitted into OR groups it is right to use OR here only // tokenize the query Set<String> qe = new LinkedHashSet<String>(); Matcher m = tokenizerPattern.matcher(q); while (m.find()) qe.add(m.group(1));//from w w w . j av a2s . c o m // twitter search syntax: // term1 term2 term3 - all three terms shall appear // "term1 term2 term3" - exact match of all terms // term1 OR term2 OR term3 - any of the three terms shall appear // from:user - tweets posted from that user // to:user - tweets posted to that user // @user - tweets which mention that user // near:"location" within:xmi - tweets that are near that location // #hashtag - tweets containing the given hashtag // since:2015-04-01 until:2015-04-03 - tweets within given time range // additional constraints: // /image /audio /video /place - restrict to tweets which have attached images, audio, video or place ArrayList<String> text_positive_match = new ArrayList<>(); ArrayList<String> text_negative_match = new ArrayList<>(); ArrayList<String> text_positive_filter = new ArrayList<>(); ArrayList<String> text_negative_filter = new ArrayList<>(); Multimap<String, String> modifier = HashMultimap.create(); Set<String> constraints_positive = new HashSet<>(); Set<String> constraints_negative = new HashSet<>(); for (String t : qe) { if (t.length() == 0) continue; if (t.startsWith("/")) { constraints_positive.add(t.substring(1)); continue; } else if (t.startsWith("-/")) { constraints_negative.add(t.substring(2)); continue; } else if (t.indexOf(':') > 0) { int p = t.indexOf(':'); String name = t.substring(0, p).toLowerCase(); String value = t.substring(p + 1); if (value.indexOf('|') > 0) { String[] values = value.split("\\|"); for (String v : values) { modifier.put(name, v); } } else { modifier.put(name, value); } continue; } else { // patch characters that will confuse elasticsearch or have a different meaning boolean negative = t.startsWith("-"); if (negative) t = t.substring(1); if (t.length() == 0) continue; if ((t.charAt(0) == dq && t.charAt(t.length() - 1) == dq) || (t.charAt(0) == sq && t.charAt(t.length() - 1) == sq)) { t = t.substring(1, t.length() - 1); if (negative) { text_negative_filter.add(t); this.negativeBag.add(t); } else { text_positive_filter.add(t); this.positiveBag.add(t); } } else if (t.indexOf('-') > 0) { // this must be handled like a quoted string without the minus t = t.replace('-', space); if (negative) { text_negative_filter.add(t); this.negativeBag.add(t); } else { text_positive_filter.add(t); this.positiveBag.add(t); } } else { if (negative) { text_negative_match.add(t); this.negativeBag.add(t); } else { text_positive_match.add(t); this.positiveBag.add(t); } } continue; } } // construct a ranking if (modifier.containsKey("boost")) { this.boosts.patchWithModifier(modifier.get("boost").iterator().next()); } // compose query for text List<QueryBuilder> queries = new ArrayList<>(); // fuzzy matching if (!text_positive_match.isEmpty()) queries.add(simpleQueryBuilder(String.join(" ", text_positive_match), ORconnective, boosts)); if (!text_negative_match.isEmpty()) queries.add(QueryBuilders.boolQuery() .mustNot(simpleQueryBuilder(String.join(" ", text_negative_match), ORconnective, boosts))); // exact matching for (String text : text_positive_filter) { queries.add(exactMatchQueryBuilder(text, this.boosts)); } for (String text : text_negative_filter) { queries.add(QueryBuilders.boolQuery().mustNot(exactMatchQueryBuilder(text, this.boosts))); } // apply modifiers Collection<String> values; modifier_handling: for (String[] modifierType : modifierTypes) { String modifier_name = modifierType[0]; String index_name = modifierType[1]; if ((values = modifier.get(modifier_name)).size() > 0) { if (modifier_name.equals("yacy")) { values.forEach(y -> this.yacyModifiers.add(y)); continue modifier_handling; } if (modifier_name.equals("site") && values.size() == 1) { String host = values.iterator().next(); if (host.startsWith("www.")) values.add(host.substring(4)); else values.add("www." + host); } queries.add(QueryBuilders.constantScoreQuery(QueryBuilders.termsQuery(index_name, values))); continue modifier_handling; } if ((values = modifier.get("-" + modifier_name)).size() > 0) { if (modifier_name.equals("site") && values.size() == 1) { String host = values.iterator().next(); if (host.startsWith("www.")) values.add(host.substring(4)); else values.add("www." + host); } queries.add(QueryBuilders.boolQuery() .mustNot(QueryBuilders.constantScoreQuery(QueryBuilders.termsQuery(index_name, values)))); continue modifier_handling; } } if (modifier.containsKey("collection") && (this.collections == null || this.collections.length == 0)) { Collection<String> c = modifier.get("collection"); this.collections = c.toArray(new String[c.size()]); } if (modifier.containsKey("daterange")) { String dr = modifier.get("daterange").iterator().next(); if (dr.length() > 0) { String from_to[] = dr.endsWith("..") ? new String[] { dr.substring(0, dr.length() - 2), "" } : dr.startsWith("..") ? new String[] { "", dr.substring(2) } : dr.split("\\.\\."); if (from_to.length == 2) { if (from_to[0] != null && from_to[0].length() > 0) try { modifier.put("since", DateParser.dayDateFormat .format(DateParser.parse(from_to[0], timezoneOffset).getTime())); } catch (ParseException e) { } if (from_to[1] != null && from_to[1].length() > 0) try { modifier.put("until", DateParser.dayDateFormat .format(DateParser.parse(from_to[1], timezoneOffset).getTime())); } catch (ParseException e) { } } } } if (modifier.containsKey("since")) try { Calendar since = DateParser.parse(modifier.get("since").iterator().next(), timezoneOffset); this.since = since.getTime(); RangeQueryBuilder rangeQuery = QueryBuilders .rangeQuery(WebMapping.last_modified.getMapping().name()) .from(DateParser.formatGSAFS(this.since)); if (modifier.containsKey("until")) { Calendar until = DateParser.parse(modifier.get("until").iterator().next(), timezoneOffset); if (until.get(Calendar.HOUR) == 0 && until.get(Calendar.MINUTE) == 0) { // until must be the day which is included in results. // To get the result within the same day, we must add one day. until.add(Calendar.DATE, 1); } this.until = until.getTime(); rangeQuery.to(DateParser.formatGSAFS(this.until)); } else { this.until = new Date(Long.MAX_VALUE); } queries.add(rangeQuery); } catch (ParseException e) { } else if (modifier.containsKey("until")) try { Calendar until = DateParser.parse(modifier.get("until").iterator().next(), timezoneOffset); if (until.get(Calendar.HOUR) == 0 && until.get(Calendar.MINUTE) == 0) { // until must be the day which is included in results. // To get the result within the same day, we must add one day. until.add(Calendar.DATE, 1); } this.until = until.getTime(); RangeQueryBuilder rangeQuery = QueryBuilders .rangeQuery(WebMapping.last_modified.getMapping().name()) .to(DateParser.formatGSAFS(this.until)); queries.add(rangeQuery); } catch (ParseException e) { } // now combine queries with OR or AND operator // simple case where we have one query only if (queries.size() == 1) { return queries.iterator().next(); } BoolQueryBuilder b = QueryBuilders.boolQuery(); for (QueryBuilder filter : queries) { if (ORconnective) b.should(filter); else b.must(filter); } if (ORconnective) b.minimumShouldMatch(1); return b; }
From source file:com.github.lukaszbudnik.dqueue.QueueClientImpl.java
private String createTableIfNotExists(String operation, String filterNames, Map<String, ?> filters) { String tableName = cassandraTablePrefix + "_" + filterNames; if (cassandraCreateTables && cacheCreatedTables.getIfPresent(filterNames) == null) { String columns = ""; String columnsAndTypes = ""; if (!filters.isEmpty()) { columns += String.join(", ", filters.keySet()) + ", "; for (String filter : filters.keySet()) { TypeCodec typeCodec = CodecRegistry.DEFAULT_INSTANCE.codecFor(filters.get(filter)); DataType.Name cqlType = typeCodec.getCqlType().getName(); columnsAndTypes += filter + " " + cqlType.name() + ", "; }/*from w w w .j ava 2 s .com*/ } String createTable = "create table if not exists " + cassandraKeyspace + "." + tableName + " ( key varchar, " + columnsAndTypes + " contents blob, start_time timeuuid, primary key (key, " + columns + " start_time) ) "; String createTableMetricName = "dqueue." + operation + "." + filterNames + ".cassandraCreateTable.timer"; executeAndMeasureTime(() -> session.execute(createTable), createTableMetricName); cacheCreatedTables.put(filterNames, Boolean.TRUE); } return tableName; }
From source file:com.example.dlp.RiskAnalysis.java
private static void calculateLDiversity(String projectId, String datasetId, String tableId, String sensitiveAttribute, List<String> quasiIds) throws Exception { // [START dlp_l_diversity] /**//from w ww . j av a2s . co m * Calculate l-diversity for an attribute relative to quasi-identifiers in a BigQuery table. * @param projectId The Google Cloud Platform project ID to run the API call under. * @param datasetId The BigQuery dataset to analyze. * @param tableId The BigQuery table to analyze. * @param sensitiveAttribute The name of the attribute to compare the quasi-ID against * @param quasiIds A set of column names that form a composite key ('quasi-identifiers'). */ // instantiate a client try (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) { // projectId = process.env.GCLOUD_PROJECT; // datasetId = "my_dataset"; // tableId = "my_table"; // sensitiveAttribute = "name"; // quasiIds = [{ columnName: "age" }, { columnName: "city" }]; FieldId sensitiveAttributeField = FieldId.newBuilder().setColumnName(sensitiveAttribute).build(); List<FieldId> quasiIdFields = quasiIds.stream() .map(columnName -> FieldId.newBuilder().setColumnName(columnName).build()) .collect(Collectors.toList()); LDiversityConfig ldiversityConfig = LDiversityConfig.newBuilder().addAllQuasiIds(quasiIdFields) .setSensitiveAttribute(sensitiveAttributeField).build(); BigQueryTable bigQueryTable = BigQueryTable.newBuilder().setProjectId(projectId).setDatasetId(datasetId) .setTableId(tableId).build(); PrivacyMetric privacyMetric = PrivacyMetric.newBuilder().setLDiversityConfig(ldiversityConfig).build(); AnalyzeDataSourceRiskRequest request = AnalyzeDataSourceRiskRequest.newBuilder() .setPrivacyMetric(privacyMetric).setSourceTable(bigQueryTable).build(); // asynchronously submit a risk analysis operation OperationFuture<RiskAnalysisOperationResult, RiskAnalysisOperationMetadata, Operation> responseFuture = dlpServiceClient .analyzeDataSourceRiskAsync(request); // ... // block on response RiskAnalysisOperationResult response = responseFuture.get(); LDiversityHistogramBucket results = response.getLDiversityResult() .getSensitiveValueFrequencyHistogramBuckets(0); for (LDiversityEquivalenceClass bucket : results.getBucketValuesList()) { List<String> quasiIdValues = bucket.getQuasiIdsValuesList().stream().map(v -> v.toString()) .collect(Collectors.toList()); System.out.println("\tQuasi-ID values: " + String.join(", ", quasiIdValues)); System.out.println("\tClass size: " + bucket.getEquivalenceClassSize()); for (ValueFrequency valueFrequency : bucket.getTopSensitiveValuesList()) { System.out.println("\t\tSensitive value " + valueFrequency.getValue().toString() + " occurs " + valueFrequency.getCount() + " time(s)."); } } } catch (Exception e) { System.out.println("Error in lDiversityAnalysis: " + e.getMessage()); } // [END dlp_l_diversity] }
From source file:org.elasticsearch.client.RequestConverters.java
static Request clearCache(ClearIndicesCacheRequest clearIndicesCacheRequest) { String[] indices = clearIndicesCacheRequest.indices() == null ? Strings.EMPTY_ARRAY : clearIndicesCacheRequest.indices(); Request request = new Request(HttpPost.METHOD_NAME, endpoint(indices, "_cache/clear")); Params parameters = new Params(request); parameters.withIndicesOptions(clearIndicesCacheRequest.indicesOptions()); parameters.putParam("query", Boolean.toString(clearIndicesCacheRequest.queryCache())); parameters.putParam("fielddata", Boolean.toString(clearIndicesCacheRequest.fieldDataCache())); parameters.putParam("request", Boolean.toString(clearIndicesCacheRequest.requestCache())); parameters.putParam("fields", String.join(",", clearIndicesCacheRequest.fields())); return request; }
From source file:com.spotify.styx.cli.Main.java
private void backfillList() throws IOException, ExecutionException, InterruptedException { String uri = apiUrl("backfills"); final List<String> queries = new ArrayList<>(); if (namespace.getBoolean(parser.backfillListShowAll.getDest())) { queries.add("showAll=true"); }// w ww. j a va 2 s . com final String component = namespace.getString(parser.backfillListComponent.getDest()); if (component != null) { queries.add("component=" + URLEncoder.encode(component, UTF_8)); } final String workflow = namespace.getString(parser.backfillListWorkflow.getDest()); if (workflow != null) { queries.add("workflow=" + URLEncoder.encode(workflow, UTF_8)); } if (!queries.isEmpty()) { uri += "?" + String.join("&", queries); } final ByteString response = send(Request.forUri(uri)); final BackfillsPayload backfills = deserialize(response, BackfillsPayload.class); cliOutput.printBackfills(backfills.backfills()); }
From source file:org.openlmis.fulfillment.service.PermissionServiceTest.java
private void expectException(String... rightNames) { exception.expect(MissingPermissionException.class); exception.expect(hasProperty("params", arrayContaining(String.join(", ", rightNames)))); exception.expectMessage(PERMISSIONS_MISSING); }
From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.security.KubernetesV2Credentials.java
private <T> T runAndRecordMetrics(String action, List<KubernetesKind> kinds, String namespace, Supplier<T> op) { T result = null;/*from ww w . j a v a 2 s . co m*/ Throwable failure = null; KubectlException apiException = null; long startTime = clock.monotonicTime(); try { result = op.get(); } catch (KubectlException e) { apiException = e; } catch (Exception e) { failure = e; } finally { Map<String, String> tags = new HashMap<>(); tags.put("action", action); if (kinds.size() == 1) { tags.put("kind", kinds.get(0).toString()); } else { tags.put("kinds", String.join(",", kinds.stream().map(KubernetesKind::toString).collect(Collectors.toList()))); } tags.put("account", accountName); tags.put("namespace", StringUtils.isEmpty(namespace) ? "none" : namespace); if (failure == null) { tags.put("success", "true"); } else { tags.put("success", "false"); tags.put("reason", failure.getClass().getSimpleName() + ": " + failure.getMessage()); } registry.timer(registry.createId("kubernetes.api", tags)).record(clock.monotonicTime() - startTime, TimeUnit.NANOSECONDS); if (failure != null) { throw new KubectlJobExecutor.KubectlException( "Failure running " + action + " on " + kinds + ": " + failure.getMessage(), failure); } else if (apiException != null) { throw apiException; } else { return result; } } }