auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private DetailNode getJavadocTree(DetailAST blockComment) { return blockCommentToJavadocTree.computeIfAbsent(blockComment, <START> key -> new JavadocDetailNodeParser().parseJavadocAsDetailNode(blockComment).getTree()); <END> }</code><technical_language>I old-school, I simple return statement, is easy put break point return validate result. Extra local variable is super easy task for optimizer, improve code maintenance. @rnveach , is position this</technical_language>

Target:
private DetailNode getJavadocTree(DetailAST blockComment) { DetailNode javadocTree = blockCommentToJavadocTree.get(blockComment); if (javadocTree == null) { javadocTree = new JavadocDetailNodeParser().parseJavadocAsDetailNode(blockComment) .getTree(); blockCommentToJavadocTree.put(blockComment, javadocTree); } return javadocTree; }
Source:
<code><START> protected DirCacheEntry keep(DirCacheEntry e) { <END> DirCacheEntry newEntry = new DirCacheEntry(e.getPathString(), e.getStage()); newEntry.setFileMode(e.getFileMode()); newEntry.setObjectId(e.getObjectId()); newEntry.setLastModified(e.getLastModified()); newEntry.setLength(e.getLength()); builder.add(newEntry); return newEntry; }</code><technical_language>need change this method signature. I leave this method private</technical_language>

Target:
private DirCacheEntry keep(DirCacheEntry e) { DirCacheEntry newEntry = new DirCacheEntry(e.getPathString(), e.getStage()); newEntry.setFileMode(e.getFileMode()); newEntry.setObjectId(e.getObjectId()); newEntry.setLastModified(e.getLastModified()); newEntry.setLength(e.getLength()); builder.add(newEntry); return newEntry; }
Source:
<code>public void testRemoveValueUnequalStoreEntryCacheAccessExceptionUnequalCacheWriterEntry() throws Exception { final MockStore realStore = new MockStore(Collections.singletonMap("key", "unequalValue")); this.store = spy(realStore); doThrow(new CacheAccessException("")).when(this.store).computeIfPresent(eq("key"), getAnyBiFunction()); final MockCacheWriter realCache = new MockCacheWriter(Collections.singletonMap("key", "unequalValue")); this.cacheWriter = spy(realCache); final Ehcache<String, String> ehcache = this.getEhcache(this.cacheWriter); <START> assertFalse(ehcache.remove("key", "value")); END> verify(this.store).computeIfPresent(eq("key"), getAnyBiFunction()); verify(this.spiedResilienceStrategy) .removeFailure(eq("key"), eq("value"), any(CacheAccessException.class), eq(false)); assertThat(realCache.getEntries().get("key"), is(equalTo("unequalValue"))); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.RemoveOutcome.FAILURE)); }</code><technical_language>others, I assert return of operation</technical_language>

Target:
public void testRemoveValueUnequalStoreEntryCacheAccessExceptionUnequalCacheWriterEntry() throws Exception { final FakeStore fakeStore = new FakeStore(Collections.singletonMap("key", "unequalValue")); this.store = spy(fakeStore); doThrow(new CacheAccessException("")).when(this.store).computeIfPresent(eq("key"), getAnyBiFunction()); final FakeCacheWriter fakeWriter = new FakeCacheWriter(Collections.singletonMap("key", "unequalValue")); this.cacheWriter = spy(fakeWriter); final Ehcache<String, String> ehcache = this.getEhcache(this.cacheWriter); ehcache.remove("key", "value"); verify(this.store).computeIfPresent(eq("key"), getAnyBiFunction()); verify(this.spiedResilienceStrategy) .removeFailure(eq("key"), eq("value"), any(CacheAccessException.class), eq(false)); assertThat(fakeWriter.getEntryMap().get("key"), is(equalTo("unequalValue"))); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.RemoveOutcome.FAILURE)); }
Source:
<code>public void saveAs(File newFolder) throws IOException { File newPrimary = checkNewFoldername(newFolder); if (!newFolder.mkdirs()) { String msg = I18n.format(tr("Could not create directory \"{0}\""), newFolder.getAbsolutePath()); throw new IOException(msg); } for (SketchFile file : files) { if (file.isPrimary()) file.saveAs(newPrimary); else file.saveAs(new File(newFolder, file.getFileName())); } if (getDataFolder().exists()) { File newDataFolder = new File(newFolder, "data"); <START> if (!newDataFolder.mkdirs()) { <END> String msg = I18n.format(tr("Could not create directory \"{0}\""), newFolder.getAbsolutePath()); throw new IOException(msg); } FileUtils.copy(getDataFolder(), newDataFolder); } folder = newFolder; }</code><technical_language>check for newDataFolder.exists() bailing out? check turned if(!(newDataFolder.exists() || newDataFolder.mkdirs())) . Do drawback in this approach</technical_language>

Target:
public void saveAs(File newFolder) throws IOException { File newPrimary = checkNewFoldername(newFolder); if (!newFolder.mkdirs()) { String msg = I18n.format(tr("Could not create directory \"{0}\""), newFolder.getAbsolutePath()); throw new IOException(msg); } for (SketchFile file : files) { if (file.isPrimary()) file.saveAs(newPrimary); else file.saveAs(new File(newFolder, file.getFileName())); } if (getDataFolder().exists()) { File newDataFolder = new File(newFolder, "data"); if (!newDataFolder.exists() && !newDataFolder.mkdirs()) { String msg = I18n.format(tr("Could not create directory \"{0}\""), newFolder.getAbsolutePath()); throw new IOException(msg); } FileUtils.copy(getDataFolder(), newDataFolder); } folder = newFolder; }
Source:
<code>private AbstractRecord createRecord(XAResource xaRes, Object[] params, Xid xid) { final AbstractRecord record; <START> if (_exceptionDeferrers == null) <END> _exceptionDeferrers = new ArrayList<>(); if ((xaRes instanceof LastResourceCommitOptimisation) || ((LAST_RESOURCE_OPTIMISATION_INTERFACE != null) && LAST_RESOURCE_OPTIMISATION_INTERFACE .isInstance(xaRes))) { XAOnePhaseResource resource = new XAOnePhaseResource(xaRes, xid, params); record = new LastResourceRecord(resource); _exceptionDeferrers.add(resource); } else { XAResourceRecord xaResourceRecord = new XAResourceRecord(this, xaRes, xid, params); record = xaResourceRecord; _exceptionDeferrers.add(xaResourceRecord); } return record; }</code><technical_language>transaction is maintaining extra collection part of state. create collection point exception is thrown inspecting failedList.in BasicAction (super class of this class) ask member of failed list report deferred exceptions. I wondering interface method List<Throwable> getDeferredThrowables(); rewritten void getDeferredThrowables(List<Throwable>); resource record create a collection maintain list of throwables</technical_language>

Target:
private AbstractRecord createRecord(XAResource xaRes, Object[] params, Xid xid) { if ((xaRes instanceof LastResourceCommitOptimisation) || ((LAST_RESOURCE_OPTIMISATION_INTERFACE != null) && LAST_RESOURCE_OPTIMISATION_INTERFACE .isInstance(xaRes))) { if (xaRes instanceof ConnectableResource) { String jndiName = ((XAResourceWrapper)xaRes).getJndiName(); if (commitMarkableResourceJNDINames.contains(jndiName)) { try { return new CommitMarkableResourceRecord(this, ((ConnectableResource)xaRes), xid, _theTransaction); } catch (IllegalStateException | RollbackException | SystemException e) { tsLogger.logger.warn("Could not register synchronization for CommitMarkableResourceRecord", e); return null; } } } return new LastResourceRecord(new XAOnePhaseResource(xaRes, xid, params)); } else { return new XAResourceRecord(this, xaRes, xid, params); } }
Source:
<code>public static Optional<Offset> parse(String offset) { <START> String[] parts = offset.split("::"); <END> if (offset.equals("0")) { return Optional.empty(); } if (parts.length != 2) { try { throw new DataParserException(Errors.EXCEL_PARSER_01); } catch (DataParserException e) { e.printStackTrace(); } } String sheetName = parts[0]; int rowNum = Integer.parseInt(parts[1]); return Optional.of(new Offset(sheetName, rowNum)); }</code><technical_language>do this check split above. suggest adding a line top: if (offset == null) return Optional.empty();</technical_language>

Target:
public static Optional<Offset> parse(String offset) throws DataParserException { if (offset.equals("0")) { return Optional.empty(); } String[] parts = offset.split("::"); if (parts.length != 2) { throw new DataParserException(Errors.EXCEL_PARSER_06, offset); } String sheetName = parts[0]; int rowNum = Integer.parseInt(parts[1]); return Optional.of(new Offset(sheetName, rowNum)); }
Source:
<code>public Result execute(UIExecutionContext context) throws Exception { XMLResource formatProfileLocation = profile.getValue(); Iterable<FileResource> formatSources = sources.getValue(); List<FileResource<?>> fileResourceList = new ArrayList<>(); for (FileResource<?> fileResource : formatSources) fileResourceList.add(fileResource); <START> if (formatProfileLocation == null) <END> format(fileResourceList); else { Properties formatProfile = new Properties(); formatProfile.load(formatProfileLocation.getResourceInputStream()); format(fileResourceList, formatProfile); } return Results.success("Files Formatted Sucessfully"); }</code><technical_language>if (formatProfileLocation == null || !formatProfileLocation.exists())</technical_language>

Target:
public Result execute(UIExecutionContext context) throws Exception { XMLResource formatProfileLocation = profile.getValue(); Iterable<FileResource> formatSources = sources.getValue(); List<FileResource<?>> fileResourceList = new ArrayList<>(); if (!formatSources.iterator().hasNext()) { UISelection<Resource> us = context.getUIContext().getInitialSelection(); Resource<?> rs = us.get(); FileResource<?> fr = (FileResource) rs.reify(FileResource.class); fileResourceList.add(fr); } else for (FileResource<?> fileResource : formatSources) fileResourceList.add(fileResource); Properties formatProfile; if (formatProfileLocation == null || !formatProfileLocation.exists()) formatProfile = null; else { formatProfile = new Properties(); formatProfile.load(formatProfileLocation.getResourceInputStream()); } format(fileResourceList, formatProfile); return Results.success("Files Formatted Sucessfully"); }
Source:
<code>protected void EndSuccessfully() { VM vm = getVm(); if (vm != null) { VmHandler.UnLockVm(vm.getId()); endDiskRelatedActions(vm); if (getParameters().getCopyCollapse()) { this.endCopyCollapseOperations(vm); } else { this.endDefaultOps(vm); } setSucceeded(true); } else { setCommandShouldBeLogged(false); <START> log.warn("ExportVmCommand::EndMoveVmCommand: Vm is null - not performing full EndAction"); <END> } }</code><technical_language>is new behaviour setSucceeded true</technical_language>

Target:
protected void EndSuccessfully() { EndActionOnAllImageGroups(); VM vm = getVm(); if (vm != null) { VmHandler.UnLockVm(vm.getId()); endDiskRelatedActions(vm); if (getParameters().getCopyCollapse()) { this.endCopyCollapseOperations(vm); } else { this.endDefaultOps(vm); } } else { setCommandShouldBeLogged(false); log.warn("ExportVmCommand::EndMoveVmCommand: Vm is null - not performing full EndAction"); } setSucceeded(true); }
Source:
<code>public E remove(int index) { throw new UnsupportedOperationException("No <START> delete(int) <END> in " + this.getClass().getName()); }</code><technical_language>remove</technical_language>

Target:
public E remove(int index) { throw new UnsupportedOperationException("No remove(int) in " + this.getClass().getName()); }
Source:
<code>public B channel(Class<? extends C> channelClass) { ObjectUtil.checkNotNull(channelClass, "channelClass"); <START> return channelFactory(new ReflectiveChannelFactory<C>(channelClass)); <END> }</code><technical_language>@qeesung: merge 2 lines checkNotNull returns channelClass</technical_language>

Target:
public B channel(Class<? extends C> channelClass) { return channelFactory(new ReflectiveChannelFactory<C>( ObjectUtil.checkNotNull(channelClass, "channelClass") )); }
Source:
<code>private int getPortOffset() { ServerConfiguration carbonConfig = ServerConfiguration.getInstance(); String portOffset = System.getProperty("portOffset", carbonConfig.getFirstProperty(CARBON_CONFIG_PORT_OFFSET)); try { if ((portOffset != null)) { return Integer.parseInt(portOffset.trim()); <START> } else { <END> return CARBON_DEFAULT_PORT_OFFSET; } } catch (NumberFormatException e) { return CARBON_DEFAULT_PORT_OFFSET; } }</code><technical_language>remove this else</technical_language>

Target:
private int getPortOffset() { ServerConfiguration carbonConfig = ServerConfiguration.getInstance(); String portOffset = System.getProperty("portOffset", carbonConfig.getFirstProperty(CARBON_CONFIG_PORT_OFFSET)); try { if ((portOffset != null)) { return Integer.parseInt(portOffset.trim()); } return CARBON_DEFAULT_PORT_OFFSET; } catch (NumberFormatException e) { return CARBON_DEFAULT_PORT_OFFSET; } }
Source:
<code>public static String parseJson(String inputString, String inputSchema) throws ValidatorException, ParserException { if (inputString != null && !inputString.isEmpty() && inputSchema != null && !inputSchema.isEmpty()) { JsonObject schemaObject; JsonElement schema = parser.parse(inputSchema); if (schema.isJsonObject()) { schemaObject = schema.getAsJsonObject(); } else if (schema.isJsonPrimitive()) { boolean valid = schema.getAsBoolean(); if (valid) { return inputString; } else { ValidatorException exception = new ValidatorException("JSON schema is not valid for all elements"); logger.error("JSON schema is false, so all validations will fail", exception); <START> throw exception; <END> } } else { ValidatorException exception = new ValidatorException("Unexpected JSON schema"); logger.error("JSON schema should be an object or boolean", exception); throw exception; } return parseJson(inputString, schemaObject); } else { ParserException exception = new ParserException("Invalid inputs"); logger.error("Input json and schema should not be null", exception); throw exception; } }</code><technical_language>do log throw here? append this error message validator exception</technical_language>

Target:
public static String parseJson(String inputString, String inputSchema) throws ValidatorException, ParserException { if (StringUtils.isNotEmpty(inputString) && StringUtils.isNotEmpty(inputSchema)) { JsonObject schemaObject; JsonElement schema; try { schema = parser.parse(inputSchema); } catch (JsonSyntaxException ex) { throw new ValidatorException("Invalid JSON schema", ex); } if (schema.isJsonObject()) { if (schema.toString().replaceAll("\\s+","").equals("{}")) { return inputString; } schemaObject = schema.getAsJsonObject(); } else if (schema.isJsonPrimitive()) { boolean valid = schema.getAsBoolean(); if (valid) { return inputString; } else { throw new ValidatorException("JSON schema is false, so all validations will fail"); } } else { throw new ValidatorException("JSON schema should be an object or boolean"); } return parseJson(inputString, schemaObject); } else { throw new ParserException("Input json and schema should not be null"); } }
Source:
<code>public <T> TypeAdapter<T> getDelegateAdapter(TypeAdapterFactory skipPast, TypeToken<T> type) { <START> boolean skipPastFound = false; <END> if (!factories.contains(skipPast)) { skipPast = jsonAdapterFactory; } for (TypeAdapterFactory factory : factories) { if (!skipPastFound) { if (factory == skipPast) { skipPastFound = true; } continue; } TypeAdapter<T> candidate = factory.create(this, type); if (candidate != null) { return candidate; } } throw new IllegalArgumentException("GSON cannot serialize " + type); }</code><technical_language>this is in loop below, move if this declaration</technical_language>

Target:
public <T> TypeAdapter<T> getDelegateAdapter(TypeAdapterFactory skipPast, TypeToken<T> type) { if (!factories.contains(skipPast)) { skipPast = jsonAdapterFactory; } boolean skipPastFound = false; for (TypeAdapterFactory factory : factories) { if (!skipPastFound) { if (factory == skipPast) { skipPastFound = true; } continue; } TypeAdapter<T> candidate = factory.create(this, type); if (candidate != null) { return candidate; } } throw new IllegalArgumentException("GSON cannot serialize " + type); }
Source:
<code>private static String getVersion() { final String defaultVersion = "dev-" + System.currentTimeMillis(); final String fileName = "bigtable-hbase-version.properties"; <START> final String versionProperty = "bigtable.version"; <END> try (InputStream stream = BigtableHBaseVersion.class.getResourceAsStream(fileName)) { if (stream == null) { LOG.error("Could not load properties file %s", fileName); return defaultVersion; } Properties properties = new Properties(); properties.load(stream); String value = properties.getProperty(versionProperty); if (value == null) { LOG.error("%s not found in %s.", versionProperty, fileName); } else if (value.startsWith("$")) { LOG.info("%s property is not replaced.", versionProperty); } else { return value; } } catch (IOException e) { LOG.error("Error while trying to get user agent name from %s", e, fileName); } return defaultVersion; }</code><technical_language>bigtable-hbase.version</technical_language>

Target:
public static String getVersion() { final String defaultVersion = "dev-" + System.currentTimeMillis(); final String fileName = "bigtable-hbase-version.properties"; final String versionProperty = "bigtable-hbase.version"; try (InputStream stream = BigtableHBaseVersion.class.getResourceAsStream(fileName)) { if (stream == null) { LOG.error("Could not load properties file %s", fileName); return defaultVersion; } Properties properties = new Properties(); properties.load(stream); String value = properties.getProperty(versionProperty); if (value == null) { LOG.error("%s not found in %s.", versionProperty, fileName); } else if (value.startsWith("$")) { LOG.info("%s property is not replaced.", versionProperty); } else { return value; } } catch (IOException e) { LOG.error("Error while trying to get user agent name from %s", e, fileName); } return defaultVersion; }
Source:
<code>public Map<String, ? extends TargetState> getTargetState() throws ThingIFException{ if (this.target == null) { throw new IllegalStateException("Can not perform this action before onboarding"); } String path = MessageFormat.format("/thing-if/apps/{0}/targets/{1}/states", this.app.getAppID(), this.target.getTypedID().toString()); String url = Path.combine(this.app.getBaseUrl(), path); Map<String, String> headers = this.newHeader(); IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.GET, headers); JSONObject responseBody = this.restClient.sendRequest(request); Map retMap = new HashMap<>(); Iterator it = responseBody.keys(); while (it.hasNext()) { <START> String key = (String)it.next(); <END> try { JsonObject object = new JsonParser() .parse(responseBody.getJSONObject(key).toString()).getAsJsonObject(); retMap.put(key, this.gson.fromJson(object, this.stateTypes.get(key))); } catch (JSONException e) { throw new IllegalStateException("Unknown target state class: " + key); } } return retMap; }</code><technical_language>check key is in this.stateTypes not? if (!this.stateTypes.has(key)) { throw new UnregisteredAliasException(key, false); }</technical_language>

Target:
public Map<String, ? extends TargetState> getTargetState() throws ThingIFException{ if (this.target == null) { throw new IllegalStateException("Can not perform this action before onboarding"); } String path = MessageFormat.format("/thing-if/apps/{0}/targets/{1}/states", this.app.getAppID(), this.target.getTypedID().toString()); String url = Path.combine(this.app.getBaseUrl(), path); Map<String, String> headers = this.newHeader(); IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.GET, headers); JSONObject responseBody = this.restClient.sendRequest(request); Map retMap = new HashMap<>(); Iterator it = responseBody.keys(); while (it.hasNext()) { String key = (String)it.next(); if (!this.stateTypes.containsKey(key)) { throw new UnregisteredAliasException(key, false); } try { JsonObject object = new JsonParser() .parse(responseBody.getJSONObject(key).toString()).getAsJsonObject(); retMap.put(key, this.gson.fromJson(object, this.stateTypes.get(key))); } catch (JSONException e) { throw new ThingIFException("Unexpected exception."); } } return retMap; }
Source:
<code>public void noCall() { <START> elasticsearchClient.index( INDEX_NAME ) <END> .deleteAndCreate() .type().putMapping( "{" + "'dynamic': 'strict'," + "'properties': {" + "'myField': {" + "'type': 'text'" + "}" + "}" + "}" ); elasticsearchClientSpy.expectNext( ElasticsearchRequest.get().build(), ElasticsearchRequestAssertionMode.EXTENSIBLE ); setupHelper.withDefaultConfiguration( BACKEND_NAME ) .withBackendProperty( BACKEND_NAME, ElasticsearchBackendSpiSettings.CLIENT_FACTORY, elasticsearchClientSpy.getFactory() ) .withIndexDefaultsProperty( BACKEND_NAME, ElasticsearchIndexSettings.LIFECYCLE_STRATEGY, ElasticsearchIndexLifecycleStrategyName.NONE.getExternalRepresentation() ) .withIndex( INDEX_NAME, ctx -> { IndexSchemaElement root = ctx.getSchemaElement(); root.field( "field", f -> f.asString() ).toReference(); }, indexManager -> { } ) .setup(); elasticsearchClientSpy.verifyExpectationsMet(); }</code><technical_language>Do need this call too? test works fine it. This block generate some confusion, log shows index creation call. I if needed work this index</technical_language>

Target:
public void noCall() { elasticsearchClientSpy.expectNext( ElasticsearchRequest.get().build(), ElasticsearchRequestAssertionMode.EXTENSIBLE ); setupHelper.withDefaultConfiguration( BACKEND_NAME ) .withBackendProperty( BACKEND_NAME, ElasticsearchBackendSpiSettings.CLIENT_FACTORY, elasticsearchClientSpy.getFactory() ) .withIndexDefaultsProperty( BACKEND_NAME, ElasticsearchIndexSettings.LIFECYCLE_STRATEGY, ElasticsearchIndexLifecycleStrategyName.NONE.getExternalRepresentation() ) .withIndex( INDEX_NAME, ctx -> { IndexSchemaElement root = ctx.getSchemaElement(); root.field( "field", f -> f.asString() ).toReference(); }, indexManager -> { } ) .setup(); elasticsearchClientSpy.verifyExpectationsMet(); }
Source:
<code>public ProjectResponse getProject(String spaceName, String projectName) { <START> log.info("Getting space '{}'", spaceName); <END> return target.path("spaces/{spaceName}/projects/{projectName}") .resolveTemplate("spaceName", spaceName) .resolveTemplate("projectName", projectName) .request().get(ProjectResponse.class); }</code><technical_language>please update log message, this method get Project</technical_language>

Target:
public ProjectResponse getProject(String spaceName, String projectName) { log.info("Getting project '{}'", spaceName); return target.path("spaces/{spaceName}/projects/{projectName}") .resolveTemplate("spaceName", spaceName) .resolveTemplate("projectName", projectName) .request().get(ProjectResponse.class); }
Source:
<code>public List<Long> getAmountOfImagesForTasksWithProcessingStatusForNotTemplateProcessesForProjectIdOrderByOrdering( Integer processingStatus, Integer projectId) { return getSum( <START> "SELECT SUM(p.sortHelperImages) FROM Task AS t INNER JOIN t.process AS p INNER JOIN p.project AS pr " <END> + "WITH pr.id = " + projectId + " WHERE t.processingStatus = " + processingStatus + " GROUP BY t.title ORDER BY t.ordering"); }</code><technical_language>change query parameters other places</technical_language>

Target:
public List<Long> getAmountOfImagesForTasksWithProcessingStatusForNotTemplateProcessesForProjectIdOrderByOrdering( Integer processingStatus, Integer projectId) { Map<String, Object> parameters = new HashMap<>(); parameters.put("projectId", projectId); parameters.put("processingStatus", processingStatus); return getSum( "SELECT SUM(p.sortHelperImages) FROM Task AS t INNER JOIN t.process AS p INNER JOIN p.project AS pr " + "WITH pr.id = :projectId WHERE t.processingStatus = :processingStatus " + "GROUP BY t.title ORDER BY t.ordering", parameters); }
Source:
<code>public String getName() { if (name.matches(".*0[1-9][0-9].*")) return name.replaceFirst("0", ""); <START> else if (name.matches(".*0{2}[1-9].*")) return name.replaceAll("0", ""); <END> else return name; }</code><technical_language>do a loop a "charAt()"? Idk regex performance is in Java</technical_language>

Target:
public String getName() { name = name.replace("00", ""); if (name.contains("0")) { for (int i = name.length() - 1; i > 0; i--) { if (Character.isDigit(name.charAt(i)) && name.charAt(i - 1) == '0') { name = name.substring(0, i - 1) + name.substring(i); break; } } } return name; }
Source:
<code>protected IOReport execute(ProgressIndicator progress, IOReporter reporter) throws IOProviderConfigurationException, IOException { HaleConnectService hcs = getServiceProvider().getService(HaleConnectService.class); LocatableInputSupplier<? extends InputStream> hcSource; try { hcSource = hcs.loadProject(owner, projectId); } catch (HaleConnectException e) { <START> throw new IllegalStateException(); <END> } super.setSource(hcSource); return super.execute(progress, reporter); }</code><technical_language>add here? suggestion throw new IllegalStateException(e.getMessage(), e);</technical_language>

Target:
protected IOReport execute(ProgressIndicator progress, IOReporter reporter) throws IOProviderConfigurationException, IOException { HaleConnectService hcs = getServiceProvider().getService(HaleConnectService.class); LocatableInputSupplier<? extends InputStream> hcSource; try { hcSource = hcs.loadProject(owner, projectId); } catch (HaleConnectException e) { throw new IllegalStateException(e.getMessage(), e); } super.setSource(hcSource); return super.execute(progress, reporter); }
Source:
<code>public boolean equals(Object obj) { if (this == obj) { return true; } <START> if (obj == null || getClass() != obj.getClass()) return false; <END> UploadOptions that = (UploadOptions) obj; return ObjectsCompat.equals(bucket, that.bucket) && ObjectsCompat.equals(metadata, that.metadata) && cannedAcl == that.cannedAcl && ObjectsCompat.equals(listener, that.listener); }</code><technical_language>suggestion if (obj == null || getClass() != obj.getClass()) { return false; }</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } UploadOptions that = (UploadOptions) obj; return ObjectsCompat.equals(bucket, that.bucket) && ObjectsCompat.equals(metadata, that.metadata) && cannedAcl == that.cannedAcl && ObjectsCompat.equals(listener, that.listener); }
Source:
<code>public boolean select(Viewer viewer, Object parent, Object element) { if (element instanceof File) { File file= (File) element; if (file.isFile()) { return isArchive(file); } else if (fAcceptFolders) { return true; } else { File[] listFiles= file.listFiles(); if (listFiles != null) { for (File <START> listFile : <END> listFiles) { if (select(viewer, file, listFile)) { return true; } } } } } return false; }</code><technical_language>rename f</technical_language>

Target:
public boolean select(Viewer viewer, Object parent, Object element) { if (element instanceof File) { File file= (File) element; if (file.isFile()) { return isArchive(file); } else if (fAcceptFolders) { return true; } else { File[] listFiles= file.listFiles(); if (listFiles != null) { for (File f : listFiles) { if (select(viewer, file, f)) { return true; } } } } } return false; }
Source:
<code><START> public void add(@Nonnull Iterable<T> runItems, @Nonnull List<Queue.Item> queueItems) { <END> sort(queueItems); addInternal(IterableUtils.chainedIterable(queueItems, runItems)); }</code><technical_language>Missing @since for public API. Missing @Restricted if supposed plugins (unclear)</technical_language>

Target:
public void add(@Nonnull Iterable<T> runItems, @Nonnull List<Queue.Item> queueItems) { sort(queueItems); addInternal(Iterables.concat(queueItems, runItems)); }
Source:
<code>private static String getRawUrlUri(String rawUrl) { String uri = rawUrl; URL url; try { url = new URL(rawUrl); if ("github.com".equals(url.getHost())) { uri = "https://api." + url.getHost(); } else { String port = ""; boolean httpOk = "http".equals(url.getProtocol()) && url.getPort() == 80; boolean httpsOk = "https".equals(url.getProtocol()) && url.getPort() == 443; if (!httpOk && !httpsOk && url.getPort()!= -1){ port = ":"+url.getPort(); } uri = url.getProtocol()+"://" + url.getHost() + port + "/api/v3"; } } catch (MalformedURLException e) { <START> LOGGER.log(Level.WARNING, "Malformed repository URL {0}", rawUrl); <END> } return uri; }</code><technical_language>sense swallow this exception, thrown out of method callers is a problem? other methods in class</technical_language>

Target:
private static String getRawUrlUri(String rawUrl) { String uri = rawUrl; URL url; try { url = new URL(rawUrl); if ("github.com".equals(url.getHost())) { uri = "https://api." + url.getHost(); } else { String port = ""; boolean httpOk = "http".equals(url.getProtocol()) && url.getPort() == 80; boolean httpsOk = "https".equals(url.getProtocol()) && url.getPort() == 443; if (!httpOk && !httpsOk && url.getPort()!= -1){ port = ":"+url.getPort(); } uri = url.getProtocol()+"://" + url.getHost() + port + "/api/v3"; } } catch (MalformedURLException e) { LOGGER.log(Level.WARNING, "Malformed repository URL {0}", rawUrl); throw new IllegalArgumentException("Repository URL not valid:" + rawUrl, e); } return GitHubConfiguration.normalizeApiUri(uri); }
Source:
<code>public List<Transaction> getTransactionsByInstanceIds(final List<Integer> instanceIds, final TransactionStatus transactionStatus, final ExperimentTransactionType experimentTransactionType) { try { final Criteria criteria = this.getSession().createCriteria(Transaction.class, "transaction"); criteria.createAlias("transaction.experimentTransactions", "experimentTransaction", Criteria.INNER_JOIN); criteria.createAlias("experimentTransaction.experiment.geoLocation", "geolocation", Criteria.INNER_JOIN); criteria.add(Restrictions.eq("status", transactionStatus.getIntValue())); criteria.add(Restrictions.in("geolocation.locationId", instanceIds)); criteria.add(Restrictions.eq("experimentTransaction.type", experimentTransactionType.getId())); criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); return criteria.list(); } catch (final HibernateException e) { final String message = <START> "Error at getTransactionsByInstanceId instanceIds = " + instanceIds + ", transactionType + " <END> + transactionStatus .getValue() + ", experimentTransactionStatus=" + experimentTransactionType.getValue(); ExperimentTransactionDAO.LOG.error(message, e); throw new MiddlewareQueryException(message, e); } }</code><technical_language>correct method name is: getTransactionsByInstanceIds</technical_language>

Target:
public List<Transaction> getTransactionsByInstanceIds(final List<Integer> instanceIds, final TransactionStatus transactionStatus, final ExperimentTransactionType experimentTransactionType) { try { final Criteria criteria = this.getSession().createCriteria(Transaction.class, "transaction"); criteria.createAlias("transaction.experimentTransactions", "experimentTransaction", Criteria.INNER_JOIN); criteria.createAlias("experimentTransaction.experiment.geoLocation", "geolocation", Criteria.INNER_JOIN); criteria.add(Restrictions.eq("status", transactionStatus.getIntValue())); criteria.add(Restrictions.in("geolocation.locationId", instanceIds)); criteria.add(Restrictions.eq("experimentTransaction.type", experimentTransactionType.getId())); criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); return criteria.list(); } catch (final HibernateException e) { final String message = "Error at getTransactionsByInstanceIds instanceIds = " + instanceIds + ", transactionType + " + transactionStatus .getValue() + ", experimentTransactionStatus=" + experimentTransactionType.getValue(); ExperimentTransactionDAO.LOG.error(message, e); throw new MiddlewareQueryException(message, e); } }
Source:
<code>HostChanges(final Set<String> newHosts, final Set<String> currentHosts) { <START> this.added = ImmutableList.copyOf(Sets.difference(newHosts, currentHosts).immutableCopy()); <END> this.removed = ImmutableList.copyOf(Sets.difference(currentHosts, newHosts).immutableCopy()); }</code><technical_language>minor I leave .immutableCopy(). ImmutableList.copyOf(Sets.difference(a, b)) thing. SetView returned Sets.difference(a, b) implements Collection</technical_language>

Target:
HostChanges(final Set<String> newHosts, final Set<String> currentHosts) { this.added = ImmutableList.copyOf(Sets.difference(newHosts, currentHosts)); this.removed = ImmutableList.copyOf(Sets.difference(currentHosts, newHosts)); }
Source:
<code>public static String sanitizeFileName(String fileName) { <START> return fileName.replace(File.separator, "↗"); <END> }</code><technical_language>Is replacing separators enough? work for special characters</technical_language>

Target:
public static String sanitizeFileName(String fileName) { String encoding = System.getProperty("file.encoding", "UTF-8"); final String sha1 = DigestUtils.sha1Hex(fileName).substring(0, 6); String fnameBase = fileName.replace(File.separator, "_"); try { fnameBase = new URI(String.format("file:/%s", fnameBase)).toASCIIString().substring("file:/".length()); } catch (URISyntaxException e) { log.debug(e, "Unable to encode base name [%s]. Trying as hex of UTF-8.", fnameBase); fnameBase = javax.xml.bind.DatatypeConverter.printHexBinary(StringUtils.toUtf8(fnameBase)); } byte[] fnameBytes; do { try { fnameBytes = fnameBase.getBytes(encoding); } catch (UnsupportedEncodingException e) { log.debug(e, "Error coding [%s] in %s, defaulting to UTF-8", fnameBase, encoding); fnameBytes = StringUtils.toUtf8(fnameBase); } if (fnameBytes.length > 100) { if (fnameBase.length() > 1) { fnameBase = fnameBase.substring(0, fnameBase.length() / 2); } else { fnameBase = ""; } } } while (fnameBytes.length > 100 && !fnameBase.isEmpty()); return fnameBase + '.' + sha1; }
Source:
<code>public static void writeDeploymentToZK(ZooKeeper zk, long genId, SegmentedCatalog catalogAndDeployment, ZKCatalogStatus catalogStatus, long txnId) throws KeeperException, InterruptedException { makeCatalogHeader(catalogAndDeployment, 0, genId); String path = VoltZK.catalogbytes + "/" + 0; ByteBuffer buffer = ByteBuffer.allocate(13); <START> buffer.put((byte)ZKCatalogStatus.PENDING.ordinal()); <END> buffer.putInt(catalogAndDeployment.m_data.size()); buffer.putLong(txnId); hostLog.info("***write deployment to " + path + " " + catalogStatus); zk.create(path, buffer.array(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); for (ByteBuffer chunk : catalogAndDeployment.m_data) { zk.create(ZKUtil.joinZKPath(path, "part_"), chunk.array(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL); } if (catalogStatus == ZKCatalogStatus.COMPLETE) { buffer.position(0); buffer.put((byte)catalogStatus.ordinal()); zk.setData(path, buffer.array(), -1); } }</code><technical_language>Setting status COMPLETE if is save update</technical_language>

Target:
public static void writeDeploymentToZK(ZooKeeper zk, long genId, SegmentedCatalog catalogAndDeployment, ZKCatalogStatus catalogStatus, long txnId) throws KeeperException, InterruptedException { makeCatalogHeader(catalogAndDeployment, 0, genId); String path = VoltZK.catalogbytes + "/" + 0; ByteBuffer buffer = ByteBuffer.allocate(13); buffer.put((byte)ZKCatalogStatus.PENDING.ordinal()); buffer.putInt(catalogAndDeployment.m_data.size()); buffer.putLong(txnId); zk.create(path, buffer.array(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); for (ByteBuffer chunk : catalogAndDeployment.m_data) { zk.create(ZKUtil.joinZKPath(path, "part_"), chunk.array(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL); } if (catalogStatus == ZKCatalogStatus.COMPLETE) { buffer.position(0); buffer.put((byte)catalogStatus.ordinal()); zk.setData(path, buffer.array(), -1); } }
Source:
<code>public byte[] idBuffer() { if (contentIdFromPtr == ptr) return contentId; <START> if (state.walk != null <END> && (mode & FileMode.TYPE_MASK) != FileMode.TYPE_GITLINK) { DirCacheIterator i = state.walk.getTree(state.dirCacheTree, DirCacheIterator.class); if (i != null) { DirCacheEntry ent = i.getDirCacheEntry(); if (ent != null && compareMetadata(ent) == MetadataDiff.EQUAL) { contentIdOffset = i.idOffset(); contentIdFromPtr = ptr; return contentId = i.idBuffer(); } contentIdOffset = 0; } else { contentIdOffset = 0; } } switch (mode & FileMode.TYPE_MASK) { case FileMode.TYPE_SYMLINK: case FileMode.TYPE_FILE: contentIdFromPtr = ptr; return contentId = idBufferBlob(entries[ptr]); case FileMode.TYPE_GITLINK: contentIdFromPtr = ptr; return contentId = idSubmodule(entries[ptr]); } return zeroid; }</code><technical_language>Christian, this reminds <LINK_0> <LINK_1>, pending. This other patches similar in places in WorkingTreeIterator. combined version</technical_language>

Target:
public byte[] idBuffer() { if (contentIdFromPtr == ptr) return contentId; if (state.walk != null) { DirCacheIterator i = state.walk.getTree(state.dirCacheTree, DirCacheIterator.class); if (i != null) { DirCacheEntry ent = i.getDirCacheEntry(); if (ent != null && compareMetadata(ent) == MetadataDiff.EQUAL && ((ent.getFileMode().getBits() & FileMode.TYPE_MASK) != FileMode.TYPE_GITLINK)) { contentIdOffset = i.idOffset(); contentIdFromPtr = ptr; return contentId = i.idBuffer(); } contentIdOffset = 0; } else { contentIdOffset = 0; } } switch (mode & FileMode.TYPE_MASK) { case FileMode.TYPE_SYMLINK: case FileMode.TYPE_FILE: contentIdFromPtr = ptr; return contentId = idBufferBlob(entries[ptr]); case FileMode.TYPE_GITLINK: contentIdFromPtr = ptr; return contentId = idSubmodule(entries[ptr]); } return zeroid; }
Source:
<code>void injectAccountAndContainerForPostRequest(RestRequest restRequest) throws RestServiceException { accountAndContainerSanityCheck(restRequest); if (getHeader(restRequest.getArgs(), Headers.TARGET_ACCOUNT_NAME, false) != null || getHeader(restRequest.getArgs(), Headers.TARGET_CONTAINER_NAME, false) != null) { ensureRequiredHeadersOrThrow(restRequest, requiredAmbryHeadersForPutWithAccountAndContainerName); frontendMetrics.putWithAccountAndContainerHeaderRate.mark(); injectAccountAndContainerUsingAccountAndContainerHeaders(restRequest); } else if (frontendConfig.frontendAllowServiceIdBasedPostRequest) { ensureRequiredHeadersOrThrow(restRequest, requiredAmbryHeadersForPutWithServiceId); frontendMetrics.putWithServiceIdForAccountNameRate.mark(); <START> String serviceId = getHeader(restRequest.getArgs(), Headers.SERVICE_ID, false); <END> boolean isPrivate = isPrivate(restRequest.getArgs()); injectAccountAndContainerUsingServiceId(restRequest, serviceId, isPrivate); } else { throw new RestServiceException( "Missing either " + Headers.TARGET_ACCOUNT_NAME + " or " + Headers.TARGET_CONTAINER_NAME + " header", RestServiceErrorCode.BadRequest); } }</code><technical_language>required true here</technical_language>

Target:
void injectAccountAndContainerForPostRequest(RestRequest restRequest) throws RestServiceException { accountAndContainerSanityCheck(restRequest); if (getHeader(restRequest.getArgs(), Headers.TARGET_ACCOUNT_NAME, false) != null || getHeader(restRequest.getArgs(), Headers.TARGET_CONTAINER_NAME, false) != null) { ensureRequiredHeadersOrThrow(restRequest, requiredAmbryHeadersForPutWithAccountAndContainerName); frontendMetrics.putWithAccountAndContainerHeaderRate.mark(); injectAccountAndContainerUsingAccountAndContainerHeaders(restRequest); } else if (frontendConfig.frontendAllowServiceIdBasedPostRequest) { ensureRequiredHeadersOrThrow(restRequest, requiredAmbryHeadersForPutWithServiceId); frontendMetrics.putWithServiceIdForAccountNameRate.mark(); String serviceId = getHeader(restRequest.getArgs(), Headers.SERVICE_ID, true); boolean isPrivate = isPrivate(restRequest.getArgs()); injectAccountAndContainerUsingServiceId(restRequest, serviceId, isPrivate); } else { throw new RestServiceException( "Missing either " + Headers.TARGET_ACCOUNT_NAME + " or " + Headers.TARGET_CONTAINER_NAME + " header", RestServiceErrorCode.BadRequest); } }
Source:
<code><START> private DataStream updateDataStream(DataStream dataStream, Metadata.Builder metadata, RestoreSnapshotRequest request) { <END> String dataStreamName = dataStream.getName(); if (request.renamePattern() != null && request.renameReplacement() != null) { dataStreamName = dataStreamName.replaceAll(request.renamePattern(), request.renameReplacement()); } List<Index> updatedIndices = dataStream.getIndices().stream() .map(i -> metadata.get(renameIndex(i.getName(), request, true)).getIndex()) .collect(Collectors.toList()); return new DataStream(dataStreamName, dataStream.getTimeStampField(), updatedIndices, dataStream.getGeneration()); }</code><technical_language>write a unit test for this method, tests renaming more thoroughly</technical_language>

Target:
static DataStream updateDataStream(DataStream dataStream, Metadata.Builder metadata, RestoreSnapshotRequest request) { String dataStreamName = dataStream.getName(); if (request.renamePattern() != null && request.renameReplacement() != null) { dataStreamName = dataStreamName.replaceAll(request.renamePattern(), request.renameReplacement()); } List<Index> updatedIndices = dataStream.getIndices().stream() .map(i -> metadata.get(renameIndex(i.getName(), request, true)).getIndex()) .collect(Collectors.toList()); return new DataStream(dataStreamName, dataStream.getTimeStampField(), updatedIndices, dataStream.getGeneration()); }
Source:
<code>protected RemoteOperationResult doInBackground(Object... params) { RemoteOperationResult result; if (params!= null && params.length==2) { String url = (String)params[0]; OwnCloudCredentials credentials = (OwnCloudCredentials)params[1]; Uri uri = Uri.parse(url); OwnCloudClient client = OwnCloudClientFactory.createOwnCloudClient(uri, mContext, true); client.setCredentials(credentials); ExistenceCheckRemoteOperation operation = new ExistenceCheckRemoteOperation( REMOTE_PATH, mContext, SUCCESS_IF_ABSENT ); result = operation.execute(client); String permanentLocation = null; if (operation.wasRedirected()) { RedirectionPath redirectionPath = operation.getRedirectionPath(); permanentLocation = redirectionPath.getLastPermanentLocation(); } if (result.isSuccess()) { if (permanentLocation == null) { GetRemoteUserInfoOperation remoteUserNameOperation = new GetRemoteUserInfoOperation(); result = remoteUserNameOperation.execute(client); } else { GetRemoteUserInfoOperation remoteUserNameOperation = new GetRemoteUserInfoOperation(); OwnCloudClient redirectedClient = OwnCloudClientFactory.createOwnCloudClient( Uri.parse(AccountUtils.trimWebdavSuffix(permanentLocation)), mContext, <START> true <END> ); redirectedClient.setCredentials(credentials); result = remoteUserNameOperation.execute(redirectedClient); } } result.setLastPermanentLocation(permanentLocation); } else { result = new RemoteOperationResult(RemoteOperationResult.ResultCode.UNKNOWN_ERROR); } return result; }</code><technical_language>a good practice variables a boolean, in order explain boolean is referring</technical_language>

Target:
protected RemoteOperationResult doInBackground(Object... params) { RemoteOperationResult result; if (params!= null && params.length==2) { String url = (String)params[0]; OwnCloudCredentials credentials = (OwnCloudCredentials)params[1]; Uri uri = Uri.parse(url); OwnCloudClient client = OwnCloudClientFactory.createOwnCloudClient(uri, mContext, true); client.setCredentials(credentials); ExistenceCheckRemoteOperation operation = new ExistenceCheckRemoteOperation( REMOTE_PATH, mContext, SUCCESS_IF_ABSENT ); result = operation.execute(client); String targetUrlAfterPermanentRedirection = null; if (operation.wasRedirected()) { RedirectionPath redirectionPath = operation.getRedirectionPath(); targetUrlAfterPermanentRedirection = redirectionPath.getLastPermanentLocation(); } if (result.isSuccess()) { GetRemoteUserInfoOperation remoteUserNameOperation = new GetRemoteUserInfoOperation(); if (targetUrlAfterPermanentRedirection != null) { client = OwnCloudClientFactory.createOwnCloudClient( Uri.parse(AccountUtils.trimWebdavSuffix( targetUrlAfterPermanentRedirection )), mContext, true ); client.setCredentials(credentials); } result = remoteUserNameOperation.execute(client); } result.setLastPermanentLocation(targetUrlAfterPermanentRedirection); } else { result = new RemoteOperationResult(RemoteOperationResult.ResultCode.UNKNOWN_ERROR); } return result; }
Source:
<code><START> public InitializerCommand(ResourceSet set, final Collection<EObject> selection) { <END> super(set); this.selection = selection; }</code><technical_language>replace Collection<EObject> selection Viewpoint viewpoint)</technical_language>

Target:
public InitializerCommand(ResourceSet set, final Collection<EObject> selection) { super(set); this.viewpoint = (Viewpoint) selection.iterator().next(); }
Source:
<code>private void poisonTable(Connection connection) throws SQLException { try (Statement statement = connection.createStatement()) { if (ConnectionDbTypes.getDbType(connection).equals(DBType.ORACLE)) { <START> statement.execute(String.format("ALTER TABLE %s RENAME COLUMN last_allocated TO LEGACY_last_allocated", <END> prefixedTimestampTableName())); } else { statement.execute(String.format("ALTER TABLE %s RENAME last_allocated TO LEGACY_last_allocated", prefixedTimestampTableName())); } } }</code><technical_language>nit: constants :)</technical_language>

Target:
private void poisonTable(Connection connection) throws SQLException { try (Statement statement = connection.createStatement()) { if (ConnectionDbTypes.getDbType(connection).equals(DBType.ORACLE)) { statement.execute(String.format("ALTER TABLE %s RENAME COLUMN %s TO %s", prefixedTimestampTableName(), LAST_ALLOCATED, LEGACY_LAST_ALLOCATED)); } else { statement.execute(String.format("ALTER TABLE %s RENAME %s TO %s", prefixedTimestampTableName(), LAST_ALLOCATED, LEGACY_LAST_ALLOCATED)); } } }
Source:
<code>private ReadWriteLock getLock(long key) { <START> return locks.get((int)key%LOCK_COUNT); <END> }</code><technical_language>if key is negative</technical_language>

Target:
private ReadWriteLock getLock(long key) { return locks.get((int)Math.abs(key)%LOCK_COUNT); }
Source:
<code>public Api getAPIForSite(Site site) { HashMap<String, String> customHeaders = new HashMap<String, String>(); customHeaders.put("User-Agent", getUserAgent()); <START> String acceptLanguage = getPrimaryLanguage(); <END> Locale defaultLocale = Locale.getDefault(); String languageBase = Utils.langCodeToWikiLang(defaultLocale.getLanguage()); String country = defaultLocale.getCountry(); String langWithCountryCode = country.equals("") ? languageBase : languageBase.concat("-" + country.toLowerCase()); if (acceptLanguage.equals("zh") || languageBase.equals("zh")) { if (acceptLanguage.equals(langWithCountryCode)) { acceptLanguage = langWithCountryCode.equals(languageBase) ? acceptLanguage : acceptLanguage.concat("," + languageBase + ";q=0.9"); } else if (acceptLanguage.equals(languageBase)) { acceptLanguage = langWithCountryCode.concat("," + acceptLanguage + ";q=0.9"); } else { acceptLanguage = acceptLanguage.concat("," + langWithCountryCode + ";q=0.9"); if (!langWithCountryCode.equals(languageBase)) { acceptLanguage = acceptLanguage.concat("," + languageBase + ";q=0.8"); } } customHeaders.put("Accept-Language", acceptLanguage); } Api api = mccMncStateHandler.makeApiWithMccMncHeaderEnrichment(this, site, customHeaders); if (api != null) { return api; } String domainAndApiAndVariantKey = site.getDomain() + "-" + site.getApiDomain() + "-" + acceptLanguage; if (!apis.containsKey(domainAndApiAndVariantKey)) { apis.put(domainAndApiAndVariantKey, new Api(site.getApiDomain(), customHeaders)); } return apis.get(domainAndApiAndVariantKey); }</code><technical_language>I prefer extract determination of acceptLanguage method (starting line 162 roughly 187). This lend unit testing</technical_language>

Target:
public Api getAPIForSite(Site site) { HashMap<String, String> customHeaders = new HashMap<String, String>(); customHeaders.put("User-Agent", getUserAgent()); String acceptLanguage = getAcceptLanguage(); if (!acceptLanguage.equals(getPrimaryLanguage())) { customHeaders.put("Accept-Language", acceptLanguage); } Api api = mccMncStateHandler.makeApiWithMccMncHeaderEnrichment(this, site, customHeaders); if (api != null) { return api; } String domainAndApiAndVariantKey = site.getDomain() + "-" + site.getApiDomain() + "-" + acceptLanguage; if (!apis.containsKey(domainAndApiAndVariantKey)) { apis.put(domainAndApiAndVariantKey, new Api(site.getApiDomain(), customHeaders)); } return apis.get(domainAndApiAndVariantKey); }