auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void run() { System.out.println("Druid version " + Initialization.class.getPackage().getImplementationVersion()); ExtensionsConfig config = Initialization.makeStartupInjector().getInstance(ExtensionsConfig.class); <START> System.out.println(""); <END> System.out.println("Registered Druid Modules"); for (DruidModule module : Initialization.getFromExtensions(config, DruidModule.class)) { String artifact = module.getClass().getPackage().getImplementationTitle(); String version = module.getClass().getPackage().getImplementationVersion(); if(artifact != null) { System.out.println( String.format( " - %s (%s-%s)", module.getClass().getCanonicalName(), module.getClass().getPackage().getImplementationTitle(), module.getClass().getPackage().getImplementationVersion() ) ); } else { System.out.println( String.format( " - %s", module.getClass().getCanonicalName() ) ); } } }</code><technical_language>a StringBuilder build want display print</technical_language>

Target:
public void run() { System.out.println(StatusResource.getStatus()); }
Source:
<code>public DistributedCacheFactory(HazelcastConnection connection, ObjectMapper mapper) { this.connection = connection; this.mapper = mapper; <START> DistributedCache.setup(connection); <END> }</code><technical_language>do this. setup cache in constructor itself. bring default setup set here. Doesnt right put in a static function in instantiable class</technical_language>

Target:
public DistributedCacheFactory(HazelcastConnection connection, ObjectMapper mapper) { this.connection = connection; this.mapper = mapper; this.connection.getHazelcastConfig().addMapConfig(getDefaultMapConfig()); }
Source:
<code>public void method_behavior_yields() { SymbolicExecutionVisitor sev = createSymbolicExecutionVisitor("src/test/resources/se/MethodYields.java"); Optional<MethodSymbol> topMethod = sev.behaviorCache.keySet().stream().filter(s -> "method".equals(s.name())).findFirst(); assertThat(topMethod.isPresent()).isTrue(); MethodBehavior mb = sev.behaviorCache.get(topMethod.get()); List<MethodYield> yields = mb.yields(); assertThat(yields).hasSize(3); List<MethodYield> trueResults = yields.stream().filter(my -> BooleanConstraint.TRUE.equals(my.result.constraint)).collect(Collectors.toList()); assertThat(trueResults).hasSize(1); <START> assertThat(trueResults.get(0).parameters[0].constraint.isNull()).isTrue(); <END> List<MethodYield> falseResults = yields.stream().filter(my -> BooleanConstraint.FALSE.equals(my.result.constraint)).collect(Collectors.toList()); assertThat(falseResults).hasSize(2); assertThat(falseResults.stream().filter(my -> !my.parameters[0].constraint.isNull()).count()).isEqualTo(2); assertThat(falseResults.stream().filter(my -> BooleanConstraint.FALSE.equals(my.parameters[1].constraint)).count()).isEqualTo(1); assertThat(falseResults.stream().filter(my -> my.parameters[1].constraint == null).count()).isEqualTo(1); }</code><technical_language>I added fact learned b</technical_language>

Target:
public void method_behavior_yields() { SymbolicExecutionVisitor sev = createSymbolicExecutionVisitor("src/test/resources/se/MethodYields.java"); Optional<MethodSymbol> topMethod = sev.behaviorCache.keySet().stream().filter(s -> "method".equals(s.name())).findFirst(); assertThat(topMethod.isPresent()).isTrue(); MethodBehavior mb = sev.behaviorCache.get(topMethod.get()); List<MethodYield> yields = mb.yields(); assertThat(yields).hasSize(3); List<MethodYield> trueResults = yields.stream().filter(my -> BooleanConstraint.TRUE.equals(my.resultConstraint)).collect(Collectors.toList()); assertThat(trueResults).hasSize(1); MethodYield trueResult = trueResults.get(0); assertThat(trueResult.parametersConstraints[0].isNull()).isTrue(); assertThat(trueResult.parametersConstraints[1]).isNull(); assertThat(trueResult.resultIndex).isEqualTo(-1); List<MethodYield> falseResults = yields.stream().filter(my -> BooleanConstraint.FALSE.equals(my.resultConstraint)).collect(Collectors.toList()); assertThat(falseResults).hasSize(2); assertThat(falseResults.stream().filter(my -> !my.parametersConstraints[0].isNull()).count()).isEqualTo(2); assertThat(falseResults.stream().filter(my -> BooleanConstraint.FALSE.equals(my.parametersConstraints[1]) && my.resultIndex == 1).count()).isEqualTo(1); assertThat(falseResults.stream().filter(my -> BooleanConstraint.TRUE.equals(my.parametersConstraints[1]) && my.resultIndex == -1).count()).isEqualTo(1); }
Source:
<code>private String parseParamsForSystemInformation(ParameterSet params, JSONObject obj) throws Exception { String subselector = "OVERVIEW"; if (params.toArray().length > 1) { return "Incorrect number of arguments to @SystemInformation (expects 1, received " + params.toArray().length + ")"; } if (params.toArray().length == 1) { Object first = params.toArray()[0]; if (!(first instanceof String)) { return "First argument to @SystemInformation must be a valid STRING selector, instead was " + first; } subselector = (String)first; <START> if (!(subselector.equalsIgnoreCase("OVERVIEW") || subselector.equalsIgnoreCase("DEPLOYMENT") || subselector.equalsIgnoreCase("LICENSE"))) { <END> return "Invalid @SystemInformation selector " + subselector; } } obj.put("subselector", subselector); obj.put("interval", false); return null; }</code><technical_language>worth a sorted set a case insensitive comparison hold list of valid selectors. private static final Set<Sting> VALID_SUBSELECTORS = ImmutableSortedSet.orderedBy(String.CASE_INSENSITIVE_ORDER).add("OVERVIEW", "DEPLOYMENT", "LICENSE").build(); ... if (!VALID_SUBSELECTORS.contains(subselector)) { ..</technical_language>

Target:
private String parseParamsForSystemInformation(ParameterSet params, JSONObject obj) throws Exception { String subselector = "OVERVIEW"; if (params.toArray().length > 1) { return "Incorrect number of arguments to @SystemInformation (expects 1, received " + params.toArray().length + ")"; } if (params.toArray().length == 1) { Object first = params.toArray()[0]; if (!(first instanceof String)) { return "First argument to @SystemInformation must be a valid STRING selector, instead was " + first; } subselector = (String)first; if (!VALID_SUBSELECTORS.contains(subselector)) { return "Invalid @SystemInformation selector " + subselector; } } obj.put("subselector", subselector); obj.put("interval", false); return null; }
Source:
<code>private boolean initVirtResources() { if (InitializeStorage()) { processFence(); processStoragePoolStatus(); runUpdateMomPolicy(getVdsGroup(), getVds()); } else { Map<String, String> customLogValues = new HashMap<>(); customLogValues.put("StoragePoolName", getStoragePoolName()); if (problematicDomains != null && !problematicDomains.isEmpty()) { <START> customLogValues.put("StorageDomainNames", StringUtils.join(Entities.objectNames(problematicDomains), ',')); <END> } setNonOperational(NonOperationalReason.STORAGE_DOMAIN_UNREACHABLE, customLogValues); return false; } return true; }</code><technical_language>consider change ', ' (with space) rebase</technical_language>

Target:
private boolean initVirtResources() { if (InitializeStorage()) { processFence(); processStoragePoolStatus(); runUpdateMomPolicy(getVdsGroup(), getVds()); } else { Map<String, String> customLogValues = new HashMap<>(); customLogValues.put("StoragePoolName", getStoragePoolName()); if (problematicDomains != null && !problematicDomains.isEmpty()) { customLogValues.put("StorageDomainNames", StringUtils.join(Entities.objectNames(problematicDomains), ", ")); } setNonOperational(NonOperationalReason.STORAGE_DOMAIN_UNREACHABLE, customLogValues); return false; } return true; }
Source:
<code>protected void onMethodInvocationFound(MethodInvocationTree isPresentMIT) { previousMITInChain(isPresentMIT) .filter(FIND_METHODS::anyMatch) .ifPresent(findMIT -> previousMITInChain(findMIT).filter(FILTER_METHODS::anyMatch) .ifPresent(filterMIT -> <START> context.reportIssue(this, identifierFromMethodInvocationChain(filterMIT), identifierFromMethodInvocationChain(isPresentMIT), <END> "Replace this \"filter()." + identifierFromMethodInvocationChain(findMIT).name() +"().isPresent()\" chain with \"anyMatch()\""))); }</code><technical_language>I reuse MethodsHelper.methodName(mit) instead of a defining a new method identifierFromMethodInvocationChain(mit)</technical_language>

Target:
protected void onMethodInvocationFound(MethodInvocationTree isPresentMIT) { previousMITInChain(isPresentMIT) .filter(FIND_METHODS::anyMatch) .ifPresent(findMIT -> previousMITInChain(findMIT).filter(FILTER_METHODS::anyMatch) .ifPresent(filterMIT -> context.reportIssue(this, MethodsHelper.methodName(filterMIT), MethodsHelper.methodName(isPresentMIT), "Replace this \"filter()." + MethodsHelper.methodName(findMIT).name() +"().isPresent()\" chain with \"anyMatch()\""))); }
Source:
<code>public void stopRecording(Client c) { if (!kHandler.isConnected() || !hasRightsToRecord(c)) { return; } kHandler.getRoom(c.getRoomId()).stopRecording(this, c); <START> Optional<StreamDesc> osd = c.getScreenStream(); <END> if (osd.isPresent()) { pauseSharing(c, osd.get().getUid()); } }</code><technical_language>I write modern syntax: c.getScreenStream().ifPresent(sd -> { if (!sd.hasActivity(Activity.SCREEN)) { pauseSharing(c, sd.getUid()); } });</technical_language>

Target:
public void stopRecording(Client c) { if (!kHandler.isConnected() || !hasRightsToRecord(c)) { return; } kHandler.getRoom(c.getRoomId()).stopRecording(this, c); c.getScreenStream().ifPresent(sd -> { if (!sd.hasActivity(Activity.SCREEN)) { pauseSharing(c, sd.getUid()); } }); }
Source:
<code>private boolean areSubscribersBehindByMax() { boolean behind = false; if (backPressureEnabled) { int count = 0; <START> for (Block curr = last; curr != null; curr = curr.prev, count++) { <END> if (count >= (MAX_COUNT_OF_INMEM_BLOCKS - 1)) { if (curr.refCount.get() != 0) { behind = true; break; } } } } return behind; }</code><technical_language>thread safe</technical_language>

Target:
public boolean areSubscribersBehindByMax() { boolean behind = false; if (backPressureEnabled) { int count = 0; synchronized (this) { Block curr = last.prev; while ((curr != null) && (++count < (MAX_COUNT_OF_INMEM_BLOCKS - 2))) { curr = curr.prev; } while (!behind && (curr != null)) { behind = (curr.refCount.get() != 0); curr = curr.prev; } } } return behind; }
Source:
<code>private void assertCommitsAfterBase(SWTBotTable table, String... commitMsgs) throws Exception { <START> TestUtil.waitForJobs(50, 5000); <END> bot.waitUntil(new DefaultCondition() { @Override public boolean test() throws Exception { return table.rowCount() >= commitMsgs.length; } @Override public String getFailureMessage() { return "CommitGraphTable did not become empty"; } }); List<Matcher<? super String>> matchers = new ArrayList<>(); matchers.add(equalTo("Initial commit")); matchers.add(startsWith("Touched at")); matchers.add(equalTo("A new file in a new folder")); for (String msg : commitMsgs) { matchers.add(equalTo(msg)); } Assert.assertThat("Expected different commits", getCommitMsgsFromUi(table), is(arrayContainingInAnyOrder(matchers))); }</code><technical_language>I do that. table enough entries is reloaded. history table loads asynchronously is notoriously difficult test, I left this in</technical_language>

Target:
private void assertCommitsAfterBase(SWTBotTable table, String... commitMsgs) throws Exception { TestUtil.waitForJobs(50, 5000); int expectedNumberOfCommits = commitMsgs.length + 3; bot.waitUntil(new DefaultCondition() { @Override public boolean test() throws Exception { return table.rowCount() == expectedNumberOfCommits; } @Override public String getFailureMessage() { return "CommitGraphTable did not get expected number of rows: " + expectedNumberOfCommits; } }); List<Matcher<? super String>> matchers = new ArrayList<>(); matchers.add(equalTo("Initial commit")); matchers.add(startsWith("Touched at")); matchers.add(equalTo("A new file in a new folder")); for (String msg : commitMsgs) { matchers.add(equalTo(msg)); } Assert.assertThat("Expected different commits", getCommitMsgsFromUi(table), is(arrayContainingInAnyOrder(matchers))); }
Source:
<code>public static void checkValid(BoundedContextName name) { checkNotNull(name); <START> checkNotEmptyOrBlank(name.getValue(), "name"); <END> }</code><technical_language>This check for null. previous expression is redundant</technical_language>

Target:
public static void checkValid(BoundedContextName name) throws IllegalArgumentException { checkNotEmptyOrBlank(name.getValue(), "name"); }
Source:
<code>public int hashCode() { int result = name != null ? name.hashCode() : 0; <START> result = 31 * result + (permissions != null ? permissions.hashCode() : 0); <END> result = 31 * result + mask; return result; }</code><technical_language>permissions null, constructor throw a NPE</technical_language>

Target:
public int hashCode() { int result = name.hashCode(); result = 31 * result + permissions.hashCode(); result = 31 * result + mask; return result; }
Source:
<code>private void updateView(final List<Project> projects) { view.clearProjects(); projects.stream().forEach(project -> { final TileWidget tileWidget = tileWidgets.get(); final POM pom = project.getPom(); <START> tileWidget.init(project.getProjectName(), <END> pom != null ? pom.getDescription() : "", String.valueOf(project.getNumberOfAssets()), view.getNumberOfAssetsMessage(13), selectCommand(project)); view.addProject(tileWidget.getView().getElement()); }); }</code><technical_language>(optinal) separate this "Project -> Element" code separate method separate concerns better: private void updateView(final List<Project> projects) { view.clearProjects(); projects.stream().forEach(project -> view.addProject(createTileWidget(project)) ); } private HTMLElement createTileWidget(Project project) { final TileWidget tileWidget = tileWidgets.get(); final POM pom = project.getPom(); tileWidget.init(project.getProjectName(), pom != null ? pom.getDescription() : "", String.valueOf(project.getNumberOfAssets()), view.getNumberOfAssetsMessage(13), selectCommand(project)); return tileWidget.getView().getElement(); }</technical_language>

Target:
private void updateView(final List<Project> projects) { view.clearProjects(); projects.stream().forEach(project -> { final TileWidget tileWidget = createProjectWidget(project); view.addProject(tileWidget.getView().getElement()); }); }
Source:
<code>protected List<MethodMatcher> getMethodInvocationMatchers() { <START> return ImmutableList.of( <END> MethodMatcher.create().typeDefinition("java.sql.DriverManager").name("getConnection").withAnyParameters() ); }</code><technical_language>Collections.singletonList is (at for meaning) in this case</technical_language>

Target:
protected List<MethodMatcher> getMethodInvocationMatchers() { return METHOD_MATCHERS; }
Source:
<code>protected void executeQueryCommand() { InstanceType instance; GetVmTemplateParameters params = getParameters(); if (params.getName() != null) { instance = vmTemplateDao.getInstanceTypeByName(params.getName(), getUserID(), getParameters().isFiltered()); } else { <START> instance = vmTemplateDao.get(getParameters().getId(), getUserID(), getParameters().isFiltered()); <END> } getQueryReturnValue().setReturnValue(instance); }</code><technical_language>vmTemplateDao.getInstanceType</technical_language>

Target:
protected void executeQueryCommand() { InstanceType instance; GetVmTemplateParameters params = getParameters(); if (params.getName() != null) { instance = vmTemplateDao.getInstanceTypeByName(params.getName(), getUserID(), getParameters().isFiltered()); } else { instance = vmTemplateDao.getInstanceType(getParameters().getId()); } getQueryReturnValue().setReturnValue(instance); }
Source:
<code>private void updateAccountElements() { TextView userNameView = (TextView)findViewById(R.id.username_text); LoginManager loginManager = App.getLoginManager(); if (loginManager.isLoggedIn()) { findViewById(R.id.have_account_text).setVisibility(View.GONE); findViewById(R.id.login_button).setVisibility(View.GONE); try { userNameView.setText(makeUserNameString(loginManager.loggedInUser.getUserName())); userNameView.setVisibility(View.VISIBLE); } catch (JSONException e) { <START> e.printStackTrace(); <END> } findViewById(R.id.logout_button).setVisibility(View.VISIBLE); } else { findViewById(R.id.have_account_text).setVisibility(View.VISIBLE); findViewById(R.id.login_button).setVisibility(View.VISIBLE); userNameView.setVisibility(View.GONE); findViewById(R.id.logout_button).setVisibility(View.GONE); } }</code><technical_language>more do is Log this message</technical_language>

Target:
private void updateAccountElements() { TextView userNameView = (TextView) findViewById(R.id.username_text); LoginManager loginManager = App.getLoginManager(); if (loginManager.isLoggedIn()) { findViewById(R.id.have_account_text).setVisibility(View.GONE); findViewById(R.id.login_button).setVisibility(View.GONE); try { userNameView.setText(makeUserNameString(loginManager.loggedInUser.getUserName())); userNameView.setVisibility(View.VISIBLE); } catch (JSONException e) { Log.e(App.LOG_TAG, "Could not get username.", e); } findViewById(R.id.logout_button).setVisibility(View.VISIBLE); } else { findViewById(R.id.have_account_text).setVisibility(View.VISIBLE); findViewById(R.id.login_button).setVisibility(View.VISIBLE); userNameView.setVisibility(View.GONE); findViewById(R.id.logout_button).setVisibility(View.GONE); } }
Source:
<code>public synchronized void start() { <START> if (isRunning.getAndSet(true) && !isClosed.getAndSet(false)) { <END> logger.info("Processor is already running"); return; } receiveMessages(); if (this.scheduledExecutor == null) { this.scheduledExecutor = Executors.newSingleThreadScheduledExecutor(); scheduledExecutor.scheduleWithFixedDelay(() -> { if (this.asyncClient.get().isConnectionClosed()) { restartMessageReceiver(); } }, SCHEDULER_INTERVAL_IN_SECONDS, SCHEDULER_INTERVAL_IN_SECONDS, TimeUnit.SECONDS); } }</code><technical_language>Do throw exception processor client continue receive if start() is called close()</technical_language>

Target:
public synchronized void start() { if (isRunning.getAndSet(true)) { logger.info("Processor is already running"); return; } if (asyncClient.get() == null) { ServiceBusReceiverAsyncClient newReceiverClient = this.receiverBuilder == null ? this.sessionReceiverBuilder.buildAsyncClientForProcessor() : this.receiverBuilder.buildAsyncClient(); asyncClient.set(newReceiverClient); } receiveMessages(); if (this.scheduledExecutor == null) { this.scheduledExecutor = Executors.newSingleThreadScheduledExecutor(); scheduledExecutor.scheduleWithFixedDelay(() -> { if (this.asyncClient.get().isConnectionClosed()) { restartMessageReceiver(); } }, SCHEDULER_INTERVAL_IN_SECONDS, SCHEDULER_INTERVAL_IN_SECONDS, TimeUnit.SECONDS); } }
Source:
<code>public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException { if (arguments.length != 1) { throw new UDFArgumentLengthException("The GetGeoDataUDF takes an array with only 1 element as argument"); } ObjectInspector arg1 = arguments[0]; if (arg1.getCategory() != Category.PRIMITIVE) { throw new UDFArgumentTypeException(0, "A string argument was expected but an argument of type " + arg1.getTypeName() + " was given."); } PrimitiveCategory primitiveCategory = ((PrimitiveObjectInspector) arg1).getPrimitiveCategory(); if (primitiveCategory != PrimitiveCategory.STRING) { throw new UDFArgumentTypeException(0, "A string argument was expected but an argument of type " + arg1.getTypeName() + " was given."); } argumentOI = arg1; <START> initialiseMaxMindGeocode(null); <END> return ObjectInspectorFactory.getStandardMapObjectInspector( PrimitiveObjectInspectorFactory.javaStringObjectInspector, PrimitiveObjectInspectorFactory.javaStringObjectInspector); }</code><technical_language>this is java overload function send unnecessary null</technical_language>

Target:
public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException { if (arguments.length != 1) { throw new UDFArgumentLengthException("The GetGeoDataUDF takes an array with only 1 element as argument"); } ObjectInspector arg1 = arguments[0]; if (arg1.getCategory() != Category.PRIMITIVE) { throw new UDFArgumentTypeException(0, "A string argument was expected but an argument of type " + arg1.getTypeName() + " was given."); } PrimitiveCategory primitiveCategory = ((PrimitiveObjectInspector) arg1).getPrimitiveCategory(); if (primitiveCategory != PrimitiveCategory.STRING) { throw new UDFArgumentTypeException(0, "A string argument was expected but an argument of type " + arg1.getTypeName() + " was given."); } argumentOI = arg1; initialiseMaxMindReader(); return ObjectInspectorFactory.getStandardMapObjectInspector( PrimitiveObjectInspectorFactory.javaStringObjectInspector, PrimitiveObjectInspectorFactory.javaStringObjectInspector); }
Source:
<code>private Type createParameterizedType(AST ast, ITypeBinding typeBinding) { if (typeBinding.isParameterizedType() && !typeBinding.isRawType()) { Type baseType= ast.newSimpleType(ASTNodeFactory.newName(ast, typeBinding.getErasure().getName())); ParameterizedType newType= ast.newParameterizedType(baseType); for (int i= 0; i < typeBinding.getTypeArguments().length; i++) { ITypeBinding typeArg= typeBinding.getTypeArguments()[i]; Type argType= createParameterizedType(ast, typeArg); newType.typeArguments().add(argType); } return newType; } else { if (!typeBinding.isTypeVariable()) { if (typeBinding.isWildcardType()) { String <START> newName= typeBinding.isUpperbound() <END> ? typeBinding.getErasure().getName() : typeBinding.getBound().getName(); WildcardType newWildcardType= ast.newWildcardType(); newWildcardType.setBound(ast.newSimpleType(ast.newSimpleName(newName)), typeBinding.isUpperbound()); return newWildcardType; } return ast.newSimpleType(ASTNodeFactory.newName(ast, typeBinding.getErasure().getName())); } return ast.newSimpleType(ast.newSimpleName(typeBinding.getName())); } }</code><technical_language>this 'String newName= typeBinding.getBound().getName()' ? docs, getBound() return upper bound null if isWildCardType() is true. I getBound() returns getErasure() isUpperbound() is true, simpler return getBound() regardless</technical_language>

Target:
private Type createParameterizedType(AST ast, ITypeBinding typeBinding) { if (typeBinding.isParameterizedType() && !typeBinding.isRawType()) { Type baseType= ast.newSimpleType(ASTNodeFactory.newName(ast, typeBinding.getErasure().getName())); ParameterizedType newType= ast.newParameterizedType(baseType); for (int i= 0; i < typeBinding.getTypeArguments().length; i++) { ITypeBinding typeArg= typeBinding.getTypeArguments()[i]; Type argType= createParameterizedType(ast, typeArg); newType.typeArguments().add(argType); } return newType; } else { if (!typeBinding.isTypeVariable()) { if (typeBinding.isWildcardType()) { String newName= typeBinding.getBound().getName(); WildcardType newWildcardType= ast.newWildcardType(); newWildcardType.setBound(ast.newSimpleType(ast.newSimpleName(newName)), typeBinding.isUpperbound()); return newWildcardType; } return ast.newSimpleType(ASTNodeFactory.newName(ast, typeBinding.getErasure().getName())); } return ast.newSimpleType(ast.newSimpleName(typeBinding.getName())); } }
Source:
<code>public void sendEmail(String receiverEmail, String subject, String message) throws MessagingException { Properties props = buildProperties(); try { Session session = Session.getDefaultInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(senderEmail,senderPassword); } }); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(senderEmail)); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiverEmail, false)); msg.setSubject(subject); msg.setText(message); msg.setSentDate(new Date()); Transport.send(msg); <START> } catch (MessagingException e) { <END> throw e; } }</code><technical_language>If exception is catched thrown try catch replace "throws MessagingException". Also, if exception is thrown Transport.send(msg) logged log level SEVERE</technical_language>

Target:
public void sendEmail(String receiverEmail, String subject, String message) throws MessagingException { Properties props = buildProperties(); Session session = Session.getDefaultInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(senderEmail, senderPassword); } }); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(senderEmail)); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiverEmail, false)); msg.setSubject(subject); msg.setText(message); msg.setSentDate(new Date()); Transport.send(msg); }
Source:
<code>protected void createFile(FileVersion reconstructedFileVersion) throws IOException { File reconstructedFileInCache; try { <START> reconstructedFileInCache = assembleFileToCache(reconstructedFileVersion); <END> } catch (NoSuchAlgorithmException | ChecksumMismatchException e) { throw new IOException(e); } moveFileToFinalLocation(reconstructedFileInCache, reconstructedFileVersion); }</code><technical_language>I generally dislike this pattern: X var; try { X = ...; } catch (..) { } move moveFileToFinalLocation try</technical_language>

Target:
protected void createFile(FileVersion reconstructedFileVersion) throws IOException { try { File reconstructedFileInCache = assembleFileToCache(reconstructedFileVersion); moveFileToFinalLocation(reconstructedFileInCache, reconstructedFileVersion); } catch (NoSuchAlgorithmException | ChecksumMismatchException e) { throw new IOException(e); } }
Source:
<code>protected void endSuccessfully() { RunVmParams runVmParams = getChildRunVmParameters(); if (runVmParams != null) { setVmId(runVmParams.getVmId()); if (getSnapshotDao().exists(getVmId(), SnapshotType.STATELESS)) { setSucceeded(Backend.getInstance().endAction(VdcActionType.RunVm, runVmParams, cloneContext().withoutLock().withoutExecutionContext()).getSucceeded()); if (!getSucceeded()) { log.warn("endSuccessfully: endAction of RunVm failed, detaching user from Vm"); detachUserFromVmFromPool(); getReturnValue().setEndActionTryAgain(false); } } <START> else { <END> log.warn("endSuccessfully: No images were created for Vm, detaching user from Vm"); detachUserFromVmFromPool(); getReturnValue().setEndActionTryAgain(false); } } else { setCommandShouldBeLogged(false); log.warn("endSuccessfully: Vm is null - not performing full endAction"); setSucceeded(true); } }</code><technical_language>issue - running vm stateful, get this else block (as stateless snapshot) detach user fine. generally speaking, i in this flow inspect result of RunVm instead of running endAction() (Example - <LINK_0></technical_language>

Target:
protected void endSuccessfully() { RunVmParams runVmParams = getChildRunVmParameters(); if (runVmParams != null) { setVmId(runVmParams.getVmId()); if (!isRunVmSucceeded()) { log.warn("endSuccessfully: RunVm failed, detaching user from VM"); detachUserFromVmFromPool(); getReturnValue().setEndActionTryAgain(false); } } else { setCommandShouldBeLogged(false); log.warn("endSuccessfully: VM is null"); } setSucceeded(true); }
Source:
<code>private Map<String, Object> serializeStackframe(StackTraceElement el, List<String> projectPackages) { Map<String, Object> map = new HashMap<>(); try { String methodName; if (el.getClassName().length() > 0) { methodName = el.getClassName() + "." + el.getMethodName(); } else { methodName = el.getMethodName(); } map.put("method", methodName); String filename = el.getFileName() == null ? "Unknown" : el.getFileName(); map.put("file", filename); map.put("lineNumber", el.getLineNumber()); if (inProject(el.getClassName(), projectPackages)) { map.put("inProject", true); } return map; } catch (Exception lineEx) { <START> return null; <END> } }</code><technical_language>Alright, thanks for looking. Class name method name null least, I wondered if some case I missed potentially testing for</technical_language>

Target:
private Map<String, Object> serializeStackframe(StackTraceElement el, List<String> projectPackages) { Map<String, Object> map = new HashMap<>(); try { String methodName; if (el.getClassName().length() > 0) { methodName = el.getClassName() + "." + el.getMethodName(); } else { methodName = el.getMethodName(); } map.put("method", methodName); String filename = el.getFileName() == null ? "Unknown" : el.getFileName(); map.put("file", filename); map.put("lineNumber", el.getLineNumber()); if (inProject(el.getClassName(), projectPackages)) { map.put("inProject", true); } return map; } catch (Exception lineEx) { Logger.warn("Failed to serialize stacktrace", lineEx); return null; } }
Source:
<code>public void drafts() throws Exception { PushOneCommit.Result r = createChange(); DraftInput in = new DraftInput(); in.line = 1; in.message = "nit: trailing <START> hitespace"; <END> in.path = FILE_NAME; DraftApi draftApi = gApi.changes() .id(r.getChangeId()) .revision(r.getCommit().name()) .createDraft(in); assertThat(draftApi .get() .message) .isEqualTo(in.message); assertThat(gApi.changes() .id(r.getChangeId()) .revision(r.getCommit().name()) .draft(draftApi.get().id) .get() .message) .isEqualTo(in.message); assertThat(gApi.changes() .id(r.getChangeId()) .revision(r.getCommit().name()) .drafts()) .hasSize(1); in.message = "good catch!"; assertThat(gApi.changes() .id(r.getChangeId()) .revision(r.getCommit().name()) .draft(draftApi.get().id) .update(in) .message) .isEqualTo(in.message); assertThat(gApi.changes() .id(r.getChangeId()) .revision(r.getCommit().name()) .draft(draftApi.get().id) .get() .author .email) .isEqualTo(admin.email); draftApi.delete(); assertThat(gApi.changes() .id(r.getChangeId()) .revision(r.getCommit().name()) .drafts()) .isEmpty(); }</code><technical_language>whitespace</technical_language>

Target:
public void drafts() throws Exception { PushOneCommit.Result r = createChange(); DraftInput in = new DraftInput(); in.line = 1; in.message = "nit: trailing whitespace"; in.path = FILE_NAME; DraftApi draftApi = gApi.changes() .id(r.getChangeId()) .revision(r.getCommit().name()) .createDraft(in); assertThat(draftApi .get() .message) .isEqualTo(in.message); assertThat(gApi.changes() .id(r.getChangeId()) .revision(r.getCommit().name()) .draft(draftApi.get().id) .get() .message) .isEqualTo(in.message); assertThat(gApi.changes() .id(r.getChangeId()) .revision(r.getCommit().name()) .drafts()) .hasSize(1); in.message = "good catch!"; assertThat(gApi.changes() .id(r.getChangeId()) .revision(r.getCommit().name()) .draft(draftApi.get().id) .update(in) .message) .isEqualTo(in.message); assertThat(gApi.changes() .id(r.getChangeId()) .revision(r.getCommit().name()) .draft(draftApi.get().id) .get() .author .email) .isEqualTo(admin.email); draftApi.delete(); assertThat(gApi.changes() .id(r.getChangeId()) .revision(r.getCommit().name()) .drafts()) .isEmpty(); }
Source:
<code>public static void writeSegmentDescriptor( final FileSystem outputFS, final DataSegment segment, final Path descriptorPath, final FileContext fileContext, final Progressable progressable ) throws IOException { final DataPusher descriptorPusher = (DataPusher) RetryProxy.create( DataPusher.class, new DataPusher() { @Override public void push() throws IOException { try { progressable.progress(); if (outputFS.exists(descriptorPath)) { if (!fileContext.delete(descriptorPath, false)) { throw new IOException(String.format("Failed to delete descriptor at [%s]", descriptorPath)); } } try (final OutputStream descriptorOut = fileContext.create( descriptorPath, EnumSet.of(CreateFlag.OVERWRITE, CreateFlag.CREATE), Options.CreateOpts.bufferSize(256 * 1024), Options.CreateOpts.createParent() )) { HadoopDruidIndexerConfig.jsonMapper.writeValue(descriptorOut, segment); descriptorOut.flush(); } } catch (RuntimeException | IOException ex) { log.info(ex, "Error in retry loop"); throw ex; } } }, <START> RetryPolicies.retryUpToMaximumCountWithFixedSleep(6, 10, TimeUnit.SECONDS) <END> ); descriptorPusher.push(); }</code><technical_language>define constants</technical_language>

Target:
public static void writeSegmentDescriptor( final FileSystem outputFS, final DataSegment segment, final Path descriptorPath, final FileContext fileContext, final Progressable progressable ) throws IOException { final DataPusher descriptorPusher = (DataPusher) RetryProxy.create( DataPusher.class, new DataPusher() { @Override public void push() throws IOException { try { progressable.progress(); if (outputFS.exists(descriptorPath)) { if (!fileContext.delete(descriptorPath, false)) { throw new IOException(String.format("Failed to delete descriptor at [%s]", descriptorPath)); } } try (final OutputStream descriptorOut = fileContext.create( descriptorPath, EnumSet.of(CreateFlag.OVERWRITE, CreateFlag.CREATE), Options.CreateOpts.bufferSize(256 * 1024), Options.CreateOpts.createParent() )) { HadoopDruidIndexerConfig.jsonMapper.writeValue(descriptorOut, segment); descriptorOut.flush(); } } catch (RuntimeException | IOException ex) { log.info(ex, "Error in retry loop"); throw ex; } } }, RetryPolicies.retryUpToMaximumCountWithFixedSleep(NUM_RETRIES, SECONDS_BETWEEN_RETRIES, TimeUnit.SECONDS) ); descriptorPusher.push(); }
Source:
<code>public URI getWebUri() { if (webUri == null) { try { webUri = new URI("http://localhost:8080"); } catch (URISyntaxException e) { throw new RuntimeException(e); } try { if (undertowSubsystem == null) { ModelNode address = new ModelNode(); address.add("subsystem", UNDERTOW); undertowSubsystem = readResource(address); } } catch (Exception e) { <START> undertowSubsystem = new ModelNode(); <END> } if (undertowSubsystem.isDefined()) { List<Property> vhosts = undertowSubsystem.get("server").asPropertyList(); ModelNode socketBinding = new ModelNode(); if (!vhosts.isEmpty()) { socketBinding = vhosts.get(0).getValue().get("http-listener", "default").get("socket-binding"); } if (socketBinding.isDefined()) { webUri = getBinding("http", socketBinding.asString()); } } } return webUri; }</code><technical_language>Possibly. for a null check. more code where/why this is used</technical_language>

Target:
public URI getWebUri() { if (webUri == null) { try { webUri = new URI("http://localhost:8080"); } catch (URISyntaxException e) { throw new RuntimeException(e); } try { if (undertowSubsystem == null) { ModelNode address = new ModelNode(); address.add("subsystem", UNDERTOW); undertowSubsystem = readResource(address); } } catch (Exception e) { logger.warn("Unable to retrieve Undertow configuration from server"); undertowSubsystem = new ModelNode(); } if (undertowSubsystem.isDefined()) { List<Property> vhosts = undertowSubsystem.get("server").asPropertyList(); ModelNode socketBinding = new ModelNode(); if (!vhosts.isEmpty()) { socketBinding = vhosts.get(0).getValue().get("http-listener", "default").get("socket-binding"); } if (socketBinding.isDefined()) { webUri = getBinding("http", socketBinding.asString()); } } } return webUri; }
Source:
<code>private boolean connectToUserSelectNetwork(int netId, int uid) { if (!mWifiConfigManager.enableNetwork(netId, true, uid)) { loge("connectToUserSelectNetwork uid " + uid + " did not have the permissions to enable=" + netId); return false; } if (!mWifiConfigManager.checkAndUpdateLastConnectUid(netId, uid)) { loge("connectToUserSelectNetwork uid " + uid + " did not have the permissions to connect=" + netId); mWifiConnectivityManager.forceConnectivityScan(); } else { mWifiConnectivityManager.setUserConnectChoice(netId); if <START> (SupplicantState.isConnecting(mWifiInfo.getSupplicantState()) <END> && mWifiInfo.getNetworkId() == netId) { logi("connectToUserSelectNetwork already connecting/connected=" + netId); } else { startConnectToNetwork(netId, SUPPLICANT_BSSID_ANY); } } return true; }</code><technical_language>This check is redundant if sanity check if netId == WifiConfiguration.INVALID_NETWORK_ID return false beginning of this method. In WifiStateMachine#handleSupplicantStateChange have: // Network id is valid start connecting if (SupplicantState.isConnecting(state)) { mWifiInfo.setNetworkId(lookupFrameworkNetworkId(stateChangeResult.networkId)); } else { mWifiInfo.setNetworkId(WifiConfiguration.INVALID_NETWORK_ID); }</technical_language>

Target:
private boolean connectToUserSelectNetwork(int netId, int uid) { if (!mWifiConfigManager.enableNetwork(netId, true, uid)) { loge("connectToUserSelectNetwork uid " + uid + " did not have the permissions to enable=" + netId); return false; } if (!mWifiConfigManager.checkAndUpdateLastConnectUid(netId, uid)) { loge("connectToUserSelectNetwork uid " + uid + " did not have the permissions to connect=" + netId); mWifiConnectivityManager.forceConnectivityScan(); } else { mWifiConnectivityManager.setUserConnectChoice(netId); if (mWifiInfo.getNetworkId() == netId) { logi("connectToUserSelectNetwork already connecting/connected=" + netId); } else { startConnectToNetwork(netId, SUPPLICANT_BSSID_ANY); } } return true; }
Source:
<code>public ListWorkflowInstanceResponse fetchWorkflowInstance( @ApiParam("Internal id for workflow instance") @PathParam("id") int id, @QueryParam("include") @ApiParam(value = INCLUDE_PARAM_DESC, allowableValues = INCLUDE_PARAM_VALUES, allowMultiple = true) String include) { <START> Collection<ListWorkflowInstanceResponse> instances = listWorkflowInstances(Arrays.asList(id), Collections.<String>emptyList(), null, null, <END> Collections.<String>emptyList(), Collections.<WorkflowInstanceStatus>emptyList(), null, null, include, 1L); if (instances.isEmpty()) { throw new NotFoundException(format("Workflow instance %s not found", id)); } return instances.iterator().next(); }</code><technical_language>static import for Arrays.asList</technical_language>

Target:
public ListWorkflowInstanceResponse fetchWorkflowInstance( @ApiParam("Internal id for workflow instance") @PathParam("id") int id, @QueryParam("include") @ApiParam(value = INCLUDE_PARAM_DESC, allowableValues = INCLUDE_PARAM_VALUES, allowMultiple = true) String include) { Collection<ListWorkflowInstanceResponse> instances = listWorkflowInstances(asList(id), Collections.<String>emptyList(), null, null, Collections.<String>emptyList(), Collections.<WorkflowInstanceStatus>emptyList(), null, null, include, 1L); if (instances.isEmpty()) { throw new NotFoundException(format("Workflow instance %s not found", id)); } return instances.iterator().next(); }
Source:
<code>public void testArrayRemoveFunctionBigint() throws Exception { Connection conn = DriverManager.getConnection(getUrl()); String tableName = initTables(conn); ResultSet rs; <START> rs = conn.createStatement().executeQuery("SELECT ARRAY_REMOVE(bigints,56) FROM " + tableName + " WHERE region_name = 'SF Bay Area'"); <END> assertTrue(rs.next()); Long[] longs = new Long[]{12l, 34l, 78l, 910l}; Array array = conn.createArrayOf("BIGINT", longs); assertEquals(array, rs.getArray(1)); assertFalse(rs.next()); }</code><technical_language>56L is in array is removed</technical_language>

Target:
public void testArrayRemoveFunctionBigint() throws Exception { ResultSet rs = conn.createStatement().executeQuery( "SELECT ARRAY_REMOVE(bigints,56),bigints FROM " + tableName + " WHERE region_name = 'SF Bay Area'"); assertTrue(rs.next()); assertEquals(conn.createArrayOf("BIGINT", new Long[] { 12l, 34l, 78l, 910l }), rs.getArray(1)); assertEquals(conn.createArrayOf("BIGINT", new Long[] { 12l, 34l, 56l, 78l, 910l }), rs.getArray(2)); assertFalse(rs.next()); }
Source:
<code>synchronized public void updateExportingLabel() { String text = lblExporting.getText(); if (text.equals(EXPORTING_DOT_ETC)) { text = "Exporting."; } else { text += "."; } lblExporting.setText(text); <START> scheduledHideExportingLabel.ifPresent(scheduledFuture -> <END> scheduledFuture.cancel(false)); scheduledHideExportingLabel = Optional.of(SCHEDULED_EXECUTOR.schedule(this::hideExporting, 5, TimeUnit.SECONDS)); }</code><technical_language>For conformity rest of code (at new parts working on), break long lines</technical_language>

Target:
synchronized public void updateExportingLabel() { String text = exportingLabel.getText(); if (text.equals(EXPORTING_DOT_ETC)) { text = "Exporting."; } else { text += "."; } exportingLabel.setText(text); scheduledHideExportingLabel.ifPresent(scheduledFuture -> scheduledFuture.cancel(false)); scheduledHideExportingLabel = Optional.of(SCHEDULED_EXECUTOR.schedule(this::hideExporting, 3, SECONDS)); }
Source:
<code>public void assertCglibProxyForGetTarget() { ElasticJob target = new TargetJob(); ProxyFactory pf = new ProxyFactory(target); pf.setProxyTargetClass(true); ElasticJob proxy = (ElasticJob) pf.getProxy(); assertTrue(AopUtils.isCglibProxy(proxy)); <START> assertEquals(AopTargetUtils.getTarget(proxy), target); <END> }</code><technical_language>For multiple parameter asserts, assertThat used</technical_language>

Target:
public void assertCglibProxyForGetTarget() { ElasticJob target = new TargetJob(); ProxyFactory pf = new ProxyFactory(target); pf.setProxyTargetClass(true); ElasticJob proxy = (ElasticJob) pf.getProxy(); assertTrue(AopUtils.isCglibProxy(proxy)); assertThat(AopTargetUtils.getTarget(proxy), is(target)); }
Source:
<code>public List<MoneyItem> moneyToItems(float amount) { <START> return moneyToItems(amount, -1); <END> }</code><technical_language>unsure -1. IMO, set a sane default limit, mark this method @Deprecated, straightforward remove</technical_language>

Target:
public List<MoneyItem> moneyToItems(float amount) { return moneyToItems(amount, 60); }
Source:
<code>private SymbolStatsEstimate buildSymbolStatistics(List<Object> values, Session session, Type type) { List<Object> nonNullValues = values.stream() .filter(Objects::nonNull) .collect(toImmutableList()); if (nonNullValues.isEmpty()) { return SymbolStatsEstimate.builder() .setLowValue(Double.NaN) .setHighValue(Double.NaN) .setNullsFraction(values.isEmpty() ? 0.0 : 1.0) .setDistinctValuesCount(0.0) .build(); } <START> else { <END> double[] valuesAsDoubles = nonNullValues.stream() .map(value -> toStatsRepresentation(metadata, session, type, value)) .filter(OptionalDouble::isPresent) .mapToDouble(OptionalDouble::getAsDouble) .toArray(); double lowValue = DoubleStream.of(valuesAsDoubles).min().orElse(Double.NEGATIVE_INFINITY); double highValue = DoubleStream.of(valuesAsDoubles).max().orElse(Double.POSITIVE_INFINITY); double valuesCount = values.size(); double nonNullValuesCount = nonNullValues.size(); long distinctValuesCount = nonNullValues.stream().distinct().count(); return SymbolStatsEstimate.builder() .setNullsFraction((valuesCount - nonNullValuesCount) / valuesCount) .setLowValue(lowValue) .setHighValue(highValue) .setDistinctValuesCount(distinctValuesCount) .build(); } }</code><technical_language>need for else</technical_language>

Target:
private SymbolStatsEstimate buildSymbolStatistics(List<Object> values, Session session, Type type) { List<Object> nonNullValues = values.stream() .filter(Objects::nonNull) .collect(toImmutableList()); if (nonNullValues.isEmpty()) { return SymbolStatsEstimate.ZERO_STATS; } double[] valuesAsDoubles = nonNullValues.stream() .map(value -> toStatsRepresentation(metadata, session, type, value)) .filter(OptionalDouble::isPresent) .mapToDouble(OptionalDouble::getAsDouble) .toArray(); double lowValue = DoubleStream.of(valuesAsDoubles).min().orElse(Double.NEGATIVE_INFINITY); double highValue = DoubleStream.of(valuesAsDoubles).max().orElse(Double.POSITIVE_INFINITY); double valuesCount = values.size(); double nonNullValuesCount = nonNullValues.size(); long distinctValuesCount = nonNullValues.stream().distinct().count(); return SymbolStatsEstimate.builder() .setNullsFraction((valuesCount - nonNullValuesCount) / valuesCount) .setLowValue(lowValue) .setHighValue(highValue) .setDistinctValuesCount(distinctValuesCount) .build(); }
Source:
<code>public void scanHttpResponseReceive(HttpMessage msg, int id, Source source) { if (msg.getResponseBody().length() == 0 || !msg.getResponseHeader().isHtml()) { return; } List<Element> links = source.getAllElements(HTMLElementName.A); for (Element link : links) { <START> if (_BLANK.equals(link.getAttributeValue(TARGET_ATTRIBUTE))) { <END> if (!NOOPENER.equals(link.getAttributeValue(REL_ATTRIBUTE))) { Alert alert = new Alert(getPluginId(), Alert.RISK_MEDIUM, Alert.CONFIDENCE_MEDIUM, getName()); alert.setDetail( getDescription(), msg.getRequestHeader().getURI().toString(), "", "", "", getSolution(), getReference(), link.toString(), 0, 0, msg); parent.raiseAlert(id, alert); return; } } } }</code><technical_language>Do care case</technical_language>

Target:
public void scanHttpResponseReceive(HttpMessage msg, int id, Source source) { if (msg.getResponseBody().length() == 0 || !msg.getResponseHeader().isHtml()) { return; } String host = msg.getRequestHeader().getHostName(); List<Context> contextList = getModel().getSession().getContextsForUrl(msg.getRequestHeader().getURI().toString()); for (Element link : source.getAllElements(HTMLElementName.A)) { if (this.isLinkFromOtherDomain(host, link.getAttributeValue("href"), contextList)) { if (this.checkElement(link, msg, id)) { return; } } } for (Element link : source.getAllElements(HTMLElementName.AREA)) { if (this.isLinkFromOtherDomain(host, link.getAttributeValue("href"), contextList)) { if (this.checkElement(link, msg, id)) { return; } } } }
Source:
<code><START> private void sortDuplicatePatients(List<Patient> patients, List<Integer> patientIds) { <END> Map<Integer, Integer> patientIdOrder = new HashMap<Integer, Integer>(); int startPos = 0; for (Integer id : patientIds) { patientIdOrder.put(id, startPos++); } class PatientIdComparator implements Comparator<Patient> { private Map<Integer, Integer> sortOrder; public PatientIdComparator(Map<Integer, Integer> sortOrder) { this.sortOrder = sortOrder; } @Override public int compare(Patient i1, Patient i2) { Integer weekdayPos1 = sortOrder.get(i1.getPatientId()); if (weekdayPos1 == null) { throw new IllegalArgumentException("Bad patient encountered: " + i1.getPatientId()); } Integer weekdayPos2 = sortOrder.get(i2.getPatientId()); if (weekdayPos2 == null) { throw new IllegalArgumentException("Bad patient encountered: " + i2.getPatientId()); } return weekdayPos1.compareTo(weekdayPos2); } } Collections.sort(patients, new PatientIdComparator(patientIdOrder)); }</code><technical_language>if do sort</technical_language>

Target:
private void sortDuplicatePatients(List<Patient> patients, List<Integer> patientIds) { Map<Integer, Integer> patientIdOrder = new HashMap<Integer, Integer>(); int startPos = 0; for (Integer id : patientIds) { patientIdOrder.put(id, startPos++); } class PatientIdComparator implements Comparator<Patient> { private Map<Integer, Integer> sortOrder; public PatientIdComparator(Map<Integer, Integer> sortOrder) { this.sortOrder = sortOrder; } @Override public int compare(Patient patient1, Patient patient2) { Integer patPos1 = sortOrder.get(patient1.getPatientId()); if (patPos1 == null) { throw new IllegalArgumentException("Bad patient encountered: " + patient1.getPatientId()); } Integer patPos2 = sortOrder.get(patient2.getPatientId()); if (patPos2 == null) { throw new IllegalArgumentException("Bad patient encountered: " + patient2.getPatientId()); } return patPos1.compareTo(patPos2); } } Collections.sort(patients, new PatientIdComparator(patientIdOrder)); }
Source:
<code>public WMSCoverageReader(WebMapServer wms, Layer layer, String style, String preferredFormat) { this.wms = wms; addLayer(layer, style); List<String> formats = wms.getCapabilities().getRequest().getGetMap().getFormats(); this.format = preferredFormat; if (!formats.contains(preferredFormat)) { LOGGER.warning(preferredFormat + " format is not supported, falling back to defaults"); <START> for (String format : formats) { <END> if ("image/png".equals(format) || "image/png24".equals(format) || "png".equals(format) || "png24".equals(format) || "image/png; mode=24bit".equals(format)) { this.format = format; break; } } } }</code><technical_language>This code is exact copy paste of code 20 lines above, avoid this :fearful:</technical_language>

Target:
public WMSCoverageReader(WebMapServer wms, Layer layer, String style, String preferredFormat) { this.wms = wms; addLayer(layer, style); List<String> formats = wms.getCapabilities().getRequest().getGetMap().getFormats(); this.format = preferredFormat; if (!formats.contains(preferredFormat)) this.format = getDefaultFormat(formats); }