auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public static FileReaderWriterFactory createFileReaderWriterFactory(String className) throws Exception { <END> Class<?> clazz = Class.forName(className); if (!FileReaderWriterFactory.class.isAssignableFrom(clazz)) { throw new IllegalArgumentException(String.format("The class '%s' is not assignable to '%s'.", className, FileReaderWriterFactory.class.getName())); } return (FileReaderWriterFactory) clazz.newInstance(); }</code><technical_language>private refactor tests invoke indirectly createFile*()</technical_language>

Target:
private static FileReaderWriterFactory createFileReaderWriterFactory(String className) throws Exception { Class<?> clazz = Class.forName(className); if (!FileReaderWriterFactory.class.isAssignableFrom(clazz)) { throw new IllegalArgumentException(String.format("The class '%s' is not assignable to '%s'.", className, FileReaderWriterFactory.class.getName())); } return (FileReaderWriterFactory) clazz.newInstance(); }
Source:
<code>private void start(boolean daemon) { if (daemon == Thread.currentThread().isDaemon()) { server.start(); } else { FutureTask<Void> startTask = new FutureTask<Void>(new Runnable() { @Override public void run() { server.start(); } }, null); CustomThreadFactory.defaultThreadFactory(daemon).newThread(startTask).start(); try { startTask.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (ExecutionException e) { Throwable cause = e.getCause(); if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } else if (cause instanceof Error) { throw (Error)cause; <START> } else throw new RuntimeException("Unexpected exception on starting HttpSever", cause); <END> } } }</code><technical_language>class is HTTPServer</technical_language>

Target:
private void start(boolean daemon) { if (daemon == Thread.currentThread().isDaemon()) { server.start(); } else { FutureTask<Void> startTask = new FutureTask<Void>(new Runnable() { @Override public void run() { server.start(); } }, null); DaemonThreadFactory.defaultThreadFactory(daemon).newThread(startTask).start(); try { startTask.get(); } catch (ExecutionException e) { throw new RuntimeException("Unexpected exception on starting HTTPSever", e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }
Source:
<code>public int compareTo(GpxImageEntry image) { <START> MapillaryAbstractImage img = (MapillaryAbstractImage) image; <END> if (this.getSequence() == img.getSequence()) { MapillarySequence seq = this.getSequence(); return compare(seq.getImages().indexOf(this), seq.getImages().indexOf(image)); } int compareSeq = compare(this.getSequence().getCapturedAt(), img.getSequence().getCapturedAt()); if (compareSeq == 0) { int compareTime = super.compareTo(image); if (compareTime == 0) { return hashCode() - image.hashCode(); } return compareTime; } return compareSeq; }</code><technical_language>check image is a MapillaryAbstractImage cast it. in mind GpxImageEntry (a root class of MapillaryAbstractImage) others, (eventually) addon/addition core GpxImageEntry's plugins</technical_language>

Target:
public int compareTo(GpxImageEntry image) { if(image instanceof MapillaryAbstractImage) { MapillaryAbstractImage img = (MapillaryAbstractImage) image; if (this.getSequence() == img.getSequence()) { MapillarySequence seq = this.getSequence(); return compare(seq.getImages().indexOf(this), seq.getImages().indexOf(image)); } int compareSeq = compare(this.getSequence().getCapturedAt(), img.getSequence().getCapturedAt()); if (compareSeq != 0) { return compareSeq; } } int compareTime = super.compareTo(image); if (compareTime == 0) { return hashCode() - image.hashCode(); } return compareTime; }
Source:
<code>public static long estimatedSizeInBytes(Object object) { if (object == null) { return 1; } Class<?> javaType = object.getClass(); if (javaType == Long.class) { return Long.BYTES; } else if (javaType == Double.class) { return Double.BYTES; } else if (javaType == Boolean.class) { return 1; } else if (object instanceof Block) { <START> return ((Block) object).getSizeInBytes(); <END> } else if (object instanceof Slice) { return ((Slice) object).getRetainedSize(); } return Integer.MAX_VALUE; }</code><technical_language>get retained size</technical_language>

Target:
public static long estimatedSizeInBytes(Object object) { if (object == null) { return 1; } Class<?> javaType = object.getClass(); if (javaType == Long.class) { return Long.BYTES; } else if (javaType == Double.class) { return Double.BYTES; } else if (javaType == Boolean.class) { return 1; } else if (object instanceof Block) { return ((Block) object).getSizeInBytes(); } else if (object instanceof Slice) { return ((Slice) object).length(); } return Integer.MAX_VALUE; }
Source:
<code>public Map<VdcParameter, Object> getParamsMap() { Map<VdcParameter, Object> copy = new HashMap<VdcParameter, Object>(); for (Entry<VdcParameter, Object> entry : paramsMap.entrySet()) { copy.put(entry.getKey(), entry.getValue()); } return copy; <START> } <END></code><technical_language>support Clonable interface call clone map</technical_language>

Target:
public Map<VdcParameter, Object> getParamsMap() { return (Map<VdcParameter, Object>) ((HashMap)paramsMap).clone(); }
Source:
<code>public int addResourceToAllServices(GrillSessionHandle sessionid, String type, String path) { int numAdded = 0; boolean error = false; for (GrillService service : GrillServices.get().getGrillServices()) { try { service.addResource(sessionid, type, path); numAdded++; } catch (GrillException e) { <START> LOG.error("Failed to add resource in service:" + service, e); <END> error = true; break; } } if (!error) { getSession(sessionid).addResource(type, path); } return numAdded; }</code><technical_language>Add resource path type log</technical_language>

Target:
public int addResourceToAllServices(GrillSessionHandle sessionid, String type, String path) { int numAdded = 0; boolean error = false; for (GrillService service : GrillServices.get().getGrillServices()) { try { service.addResource(sessionid, type, path); numAdded++; } catch (GrillException e) { LOG.error("Failed to add resource type:" + type + " path:" + path + " in service:" + service, e); error = true; break; } } if (!error) { getSession(sessionid).addResource(type, path); } return numAdded; }
Source:
<code>@Override public boolean canHandleRequest(@NonNull Request data) { final Uri uri = data.uri; if (uri == null) { return false; <START> } <END> return (SCHEME_CONTENT.equals(uri.getScheme()) && ContactsContract.Contacts.CONTENT_URI.getHost().equals(uri.getHost()) && matcher.match(data.uri) != UriMatcher.NO_MATCH); }</code><technical_language>Merge return uri != null && .</technical_language>

Target:
@Override public boolean canHandleRequest(@NonNull Request data) { final Uri uri = data.uri; return uri != null && SCHEME_CONTENT.equals(uri.getScheme()) && ContactsContract.Contacts.CONTENT_URI.getHost().equals(uri.getHost()) && matcher.match(data.uri) != UriMatcher.NO_MATCH; }
Source:
<code>public String getAttributeValue(String name) { for (int i = 0; i < reader.getAttributeCount(); i++) { String attrName = reader.getAttributeLocalName(i); if (attrName.equals(name)) { return reader.getAttributeValue(i); } } <START> return null; <END> }</code><technical_language>I underlying XMLStream reader a 'getAttributeValue' method. receives namespace name of attribute. If pass 'null' name of attribute return of attribute, is need: <LINK_0></technical_language>

Target:
public String getAttributeValue(String name) { return reader.getAttributeValue(null, name); }
Source:
<code>private ListenableFuture<Duration> announce() { final ListenableFuture<Duration> future = announcementClient.announce(ImmutableSet.copyOf(announcements.values())); Futures.addCallback(future, new FutureCallback<Duration>() { @Override public void onSuccess(Duration duration) { errorBackOff.success(); failed.set(null); nextAnnouncementTime.set(System.nanoTime() + duration.roundTo(NANOSECONDS)); duration = new Duration(duration.toMillis() * 0.8, MILLISECONDS); scheduleNextAnnouncement(duration); } @Override public void onFailure(Throwable t) { Duration duration = errorBackOff.failed(t); failed.set(t); <START> scheduleNextAnnouncement(duration); <END> } }, executor); return future; }</code><technical_language>logging failure jmx-counter, good</technical_language>

Target:
private ListenableFuture<Duration> announce() { final ListenableFuture<Duration> future = announcementClient.announce(getServiceAnnouncements()); Futures.addCallback(future, new FutureCallback<Duration>() { @Override public void onSuccess(Duration duration) { errorBackOff.success(); failed.set(null); nextAnnouncementTime.set(System.nanoTime() + duration.roundTo(NANOSECONDS)); duration = new Duration(duration.toMillis() * 0.8, MILLISECONDS); scheduleNextAnnouncement(duration); } @Override public void onFailure(Throwable t) { Duration duration = errorBackOff.failed(t); failed.set(t); scheduleNextAnnouncement(duration); } }, executor); return future; }
Source:
<code>public void theRequestForAFirmwareUpgradeIsReceived() throws Throwable { PROPERTIES_MAP.put(Keys.KEY_DEVICE_IDENTIFICATION_E_LABEL, this.deviceId.getDeviceIdE()); PROPERTIES_MAP.put(Keys.KEY_ORGANIZATION_IDENTIFICATION, this.organisationId.getOrganisationId()); <START> PROPERTIES_MAP.put(ENDPOINT_LABEL, this.serviceEndpoint.getServiceEndpoint()); <END> this.requestRunner(TestStepStatus.OK, PROPERTIES_MAP, TEST_CASE_NAME_REQUEST, TEST_CASE_XML, TEST_SUITE_XML); }</code><technical_language>Service endpoint property is set in a parent class, this removed</technical_language>

Target:
public void theRequestForAFirmwareUpgradeIsReceived() throws Throwable { PROPERTIES_MAP.put(Keys.KEY_DEVICE_IDENTIFICATION_E_LABEL, this.deviceId.getDeviceIdE()); PROPERTIES_MAP.put(Keys.KEY_ORGANIZATION_IDENTIFICATION, this.organisationId.getOrganisationId()); this.requestRunner(TestStepStatus.OK, PROPERTIES_MAP, TEST_CASE_NAME_REQUEST, TEST_CASE_XML, TEST_SUITE_XML); }
Source:
<code>public void describe(StreamApplicationDescriptor appDescriptor) { KafkaSystemDescriptor kafkaSystemDescriptor = new KafkaSystemDescriptor("kafka").withConsumerZkConnect(KAFKA_CONSUMER_ZK_CONNECT) .withProducerBootstrapServers(KAFKA_PRODUCER_BOOTSTRAP_SERVERS) .withDefaultStreamConfigs(KAFKA_DEFAULT_STREAM_CONFIGS); KafkaInputDescriptor<PageView> pageViewInputDescriptor = kafkaSystemDescriptor.getInputDescriptor(INPUT_PAGEVIEW_STREAM_ID, new JsonSerdeV2<>(PageView.class)); GenericSystemDescriptor azureBlobSystemDescriptor = new GenericSystemDescriptor(OUTPUT_SYSTEM, "org.apache.samza.system.azureblob.AzureBlobSystemFactory"); GenericOutputDescriptor<PageViewAvroRecord> azureBlobOuputDescriptor = azureBlobSystemDescriptor.getOutputDescriptor(OUTPUT_STREAM, new NoOpSerde<>()); appDescriptor.withDefaultSystem(kafkaSystemDescriptor); MessageStream<PageView> pageViewInput = appDescriptor.getInputStream(pageViewInputDescriptor); OutputStream<PageViewAvroRecord> pageViewAvroRecordOutputStream = appDescriptor.getOutputStream(azureBlobOuputDescriptor); pageViewInput .map((message) -> { <START> System.out.println("Sending: "); System.out.println("Received PageViewEvent with pageId: " + message.pageId); <END> return PageViewAvroRecord.buildPageViewRecord(message); }) .sendTo(pageViewAvroRecordOutputStream); }</code><technical_language>Consider a logger for this</technical_language>

Target:
public void describe(StreamApplicationDescriptor appDescriptor) { KafkaSystemDescriptor kafkaSystemDescriptor = new KafkaSystemDescriptor("kafka").withConsumerZkConnect(KAFKA_CONSUMER_ZK_CONNECT) .withProducerBootstrapServers(KAFKA_PRODUCER_BOOTSTRAP_SERVERS) .withDefaultStreamConfigs(KAFKA_DEFAULT_STREAM_CONFIGS); KafkaInputDescriptor<PageView> pageViewInputDescriptor = kafkaSystemDescriptor.getInputDescriptor(INPUT_PAGEVIEW_STREAM_ID, new JsonSerdeV2<>(PageView.class)); GenericSystemDescriptor azureBlobSystemDescriptor = new GenericSystemDescriptor(OUTPUT_SYSTEM, "org.apache.samza.system.azureblob.AzureBlobSystemFactory"); GenericOutputDescriptor<PageViewAvroRecord> azureBlobOuputDescriptor = azureBlobSystemDescriptor.getOutputDescriptor(OUTPUT_STREAM, new NoOpSerde<>()); appDescriptor.withDefaultSystem(kafkaSystemDescriptor); MessageStream<PageView> pageViewInput = appDescriptor.getInputStream(pageViewInputDescriptor); OutputStream<PageViewAvroRecord> pageViewAvroRecordOutputStream = appDescriptor.getOutputStream(azureBlobOuputDescriptor); pageViewInput .map((message) -> { LOG.info("Sending: Received PageViewEvent with pageId: " + message.pageId); return PageViewAvroRecord.buildPageViewRecord(message); }) .sendTo(pageViewAvroRecordOutputStream); }
Source:
<code>public void testSpecificBuildSelector() throws Exception { FreeStyleProject other = createArtifactProject(), p = rule.createFreeStyleProject(); ParameterDefinition paramDef = new StringParameterDefinition("FOO","foo"); ParametersDefinitionProperty paramsDef = new ParametersDefinitionProperty(paramDef); other.addProperty(paramsDef); <START> CopyArtifactPermissionProperty cpp=new CopyArtifactPermissionProperty("/"+p.getName()); <END> other.addProperty(cpp); SpecificBuildSelector sbs = new SpecificBuildSelector("1"); assertEquals("1", sbs.getBuildNumber()); p.getBuildersList().add(CopyArtifactUtil.createCopyArtifact(other.getName(), null, sbs, "*.txt", "", false, false, true)); rule.assertBuildStatusSuccess(other.scheduleBuild2(0, new UserCause(), new ParametersAction(new StringParameterValue("FOO", "buildone"))).get()); rule.assertBuildStatusSuccess(other.scheduleBuild2(0, new UserCause())); FreeStyleBuild b = p.scheduleBuild2(0, new UserCause()).get(); rule.assertBuildStatusSuccess(b); assertFile(true, "foo.txt", b); assertFile(true, "buildone.txt", b); assertFile(false, "subdir/subfoo.txt", b); }</code><technical_language>(about white spaces =) [the Jenkins project follow code styles strictly|<LINK_0>], I highly recommend follow a some consistent code style</technical_language>

Target:
public void testSpecificBuildSelector() throws Exception { FreeStyleProject other = createArtifactProject(), p = rule.createFreeStyleProject(); ParameterDefinition paramDef = new StringParameterDefinition("FOO", "foo"); ParametersDefinitionProperty paramsDef = new ParametersDefinitionProperty(paramDef); other.addProperty(paramsDef); SpecificBuildSelector sbs = new SpecificBuildSelector("1"); assertEquals("1", sbs.getBuildNumber()); p.getBuildersList().add(CopyArtifactUtil.createCopyArtifact(other.getName(), null, sbs, "*.txt", "", false, false, true)); rule.assertBuildStatusSuccess(other.scheduleBuild2(0, new UserCause(), new ParametersAction(new StringParameterValue("FOO", "buildone"))).get()); rule.assertBuildStatusSuccess(other.scheduleBuild2(0, new UserCause())); FreeStyleBuild b = p.scheduleBuild2(0, new UserCause()).get(); rule.assertBuildStatusSuccess(b); assertFile(true, "foo.txt", b); assertFile(true, "buildone.txt", b); assertFile(false, "subdir/subfoo.txt", b); }
Source:
<code>public void onAllRequiredCapabilitiesAvailable() { DataHolder.getInstance().getBundleContext().registerService(WebSocketServerSC.class, this, null); <START> LOGGER.info("All required capabilities are available"); <END> }</code><technical_language>Is necessary this info log</technical_language>

Target:
public void onAllRequiredCapabilitiesAvailable() { DataHolder.getInstance().getBundleContext().registerService(WebSocketServerSC.class, this, null); log.info("All required capabilities are available"); }
Source:
<code><START> public void removeIf(Predicate<T> predicate) { <END> for (int i = start; i < start + size; i++) { T a = (T) data[i]; if (predicate.test(a)) { toRemove.remove(a); dataAsSet.remove(a); data[i] = data[start + --size]; i--; } } }</code><technical_language>handle removing element exist in list? pretty breaks size isEmpty. If want handle things, crash in cases (PlayerCubeMap that). for other strange cases adding twice</technical_language>

Target:
public void removeIf(Predicate<T> predicate) { for (int i = start; i < start + size; i++) { T a = (T) data[i]; if (predicate.test(a)) { toRemove.add(a); } } }
Source:
<code>public Set<String> getStoredReposWithAlias() { return repoIO.getStoredRepos().stream().map(repoId -> { RepoAliasMap repoAliasMap = RepoAliasMap.getInstance(); if (repoAliasMap.hasAlias(repoId)) { return repoAliasMap.getAlias(repoId); } else { return repoId; <START> } <END> }).collect(Collectors.toSet()); }</code><technical_language>ternary operator ? :</technical_language>

Target:
public Set<String> getStoredReposWithAlias() { return repoIO.getStoredRepos().stream().map(repoId -> { RepoConfig repoConfig = prefs.getRepoConfig(); return repoConfig.hasRepoAlias(repoId) ? repoConfig.getRepoAlias(repoId) : repoId; }).collect(Collectors.toSet()); }
Source:
<code>public String getTitle() { final HitPolicy hitPolicy = hitPolicySupplier.get(); final BuiltinAggregator builtinAggregator = builtinAggregatorSupplier.get(); final StringBuilder sb = new StringBuilder(hitPolicy.value().substring(0, 1).toUpperCase()); if (HitPolicy.COLLECT == hitPolicy) { if (builtinAggregator != null) { <START> switch (builtinAggregator) { <END> case COUNT: sb.append("#"); break; case MAX: sb.append(">"); break; case MIN: sb.append("<"); break; case SUM: sb.append("+"); } } } return sb.toString(); }</code><technical_language>I shorten code if store aggregator characters in BuiltinAggregator enum</technical_language>

Target:
public String getTitle() { final HitPolicy hitPolicy = hitPolicySupplier.get(); final BuiltinAggregator builtinAggregator = builtinAggregatorSupplier.get(); final StringBuilder sb = new StringBuilder(hitPolicy.value().substring(0, 1).toUpperCase()); if (HitPolicy.COLLECT == hitPolicy) { if (builtinAggregator != null) { sb.append(builtinAggregator.getCode()); } } return sb.toString(); }
Source:
<code>protected List<String> getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { List<String> options = new ArrayList<>(); if (args.length == 1 && user.isAuthorized("essentials.kit.reset")) { return getPlayers(server, user); <START> } else if (args.length == 2) { <END> for (String kitName : ess.getKits().getKits().getKeys(false)) { if (!user.isAuthorized("essentials.kits." + kitName)) { continue; } options.add(kitName); } return options; } return Collections.emptyList(); }</code><technical_language>Missing essentials.kit.reset permission check</technical_language>

Target:
protected List<String> getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) { List<String> options = new ArrayList<>(); if (args.length == 1 && user.isAuthorized("essentials.kit.reset")) { return getPlayers(server, user); } else if (args.length == 2 && user.isAuthorized("essentials.kit.reset")) { for (String kitName : ess.getKits().getKits().getKeys(false)) { if (!user.isAuthorized("essentials.kits." + kitName)) { continue; } options.add(kitName); } return options; } return options; }
Source:
<code>private String readXMLDecl(Reader input) throws IOException { BufferedReader reader = new BufferedReader(input); <START> String xmlDecl = new String(); <END> String line = null; StringBuilder stringBuilder = new StringBuilder(); while (xmlDecl.length() < 100 && ((line = reader.readLine()) != null)) { stringBuilder.append(line); if (line.indexOf(XML_DECL_END) != -1) { return stringBuilder.toString().substring(0, xmlDecl.indexOf(XML_DECL_END) + XML_DECL_END.length()); } } return xmlDecl; }</code><technical_language>new String() is generally useless replaced "" - in this case I variable removed completely</technical_language>

Target:
private String readXMLDecl(Reader input) throws IOException { BufferedReader reader = new BufferedReader(input); String line = null; StringBuilder stringBuilder = new StringBuilder(100); while (stringBuilder.length() < 100 && ((line = reader.readLine()) != null)) { stringBuilder.append(line); if (line.indexOf(XML_DECL_END) != -1) { String resultString = stringBuilder.toString(); return resultString.substring(0, resultString.indexOf(XML_DECL_END) + XML_DECL_END.length()); } } return stringBuilder.toString(); }
Source:
<code>public ValidationResult supportedFirewallTypeForClusterVersion() { return ValidationResult .failWith( EngineMessage.UNSUPPORTED_FIREWALL_TYPE_FOR_CLUSTER_VERSION, <START> ReplacementUtils.createSetVariableString("$clusterVersion", <END> cluster.getCompatibilityVersion()), ReplacementUtils.createSetVariableString("$firewallType", cluster.getFirewallType()) ) .when(cluster.getCompatibilityVersion().lessOrEquals(Version.v3_6) && FirewallType.FIREWALLD.equals(cluster.getFirewallType())); }</code><technical_language>$ sign included in property name</technical_language>

Target:
public ValidationResult supportedFirewallTypeForClusterVersion() { return ValidationResult .failWith( EngineMessage.UNSUPPORTED_FIREWALL_TYPE_FOR_CLUSTER_VERSION, ReplacementUtils.createSetVariableString("clusterVersion", cluster.getCompatibilityVersion()), ReplacementUtils.createSetVariableString("firewallType", cluster.getFirewallType()) ) .when(cluster.getCompatibilityVersion().lessOrEquals(Version.v3_6) && FirewallType.FIREWALLD.equals(cluster.getFirewallType())); }
Source:
<code>protected void run(String[] args) throws Exception { LOG.info("Running 'run' command."); final Options commandOptions = CliFrontendParser.getRunCommandOptions(); final CommandLine commandLine = getCommandLine(commandOptions, args, true); final ProgramOptions programOptions = ProgramOptions.create(commandLine); if (commandLine.hasOption(HELP_OPTION.getOpt())) { CliFrontendParser.printHelpForRun(customCommandLines); return; } <START> programOptions.validate(); <END> final PackagedProgram program; try { LOG.info("Building program from JAR file"); program = buildProgram(programOptions); } catch (FileNotFoundException e) { throw new CliArgsException("Could not build the program from JAR file: " + e.getMessage(), e); } final List<URL> jobJars = program.getJobJarAndDependencies(); final Configuration effectiveConfiguration = getEffectiveConfiguration(commandLine, programOptions, jobJars); LOG.debug("Effective executor configuration: {}", effectiveConfiguration); try { executeProgram(effectiveConfiguration, program); } finally { program.deleteExtractedLibraries(); } }</code><technical_language>validate removed executed in buildProgram</technical_language>

Target:
protected void run(String[] args) throws Exception { LOG.info("Running 'run' command."); final Options commandOptions = CliFrontendParser.getRunCommandOptions(); final CommandLine commandLine = getCommandLine(commandOptions, args, true); final ProgramOptions programOptions = ProgramOptions.create(commandLine); if (commandLine.hasOption(HELP_OPTION.getOpt())) { CliFrontendParser.printHelpForRun(customCommandLines); return; } final PackagedProgram program; try { LOG.info("Building program from JAR file"); program = buildProgram(programOptions); } catch (FileNotFoundException e) { throw new CliArgsException("Could not build the program from JAR file: " + e.getMessage(), e); } final List<URL> jobJars = program.getJobJarAndDependencies(); final Configuration effectiveConfiguration = getEffectiveConfiguration(commandLine, programOptions, jobJars); LOG.debug("Effective executor configuration: {}", effectiveConfiguration); try { executeProgram(effectiveConfiguration, program); } finally { program.deleteExtractedLibraries(); } }
Source:
<code>public RecordReader<NullWritable, NullWritable> getRecordReader(InputSplit inputSplit, JobConf jobConf, Reporter reporter) { <START> return null; <END> }</code><technical_language>throw UnsupportedOperationException()</technical_language>

Target:
public RecordReader<NullWritable, NullWritable> getRecordReader(InputSplit inputSplit, JobConf jobConf, Reporter reporter) { throw new UnsupportedOperationException(); }
Source:
<code>public boolean beginTrackingIfPossible(Application application) { if (mAutomaticTracker == null) { AutomaticTracker automaticTracker = AutomaticTracker.newInstance(application, this ); if (automaticTracker != null) { automaticTracker.register(); mAutomaticTracker = automaticTracker; return true; } } <START> return false; <END> }</code><technical_language>is worth a call LogUtil.i() here</technical_language>

Target:
public boolean beginTrackingIfPossible(Application application) { if (mAutomaticTracker == null) { AutomaticTracker automaticTracker = AutomaticTracker.newInstanceIfPossible(application, this ); if (automaticTracker != null) { automaticTracker.register(); mAutomaticTracker = automaticTracker; return true; } } return false; }
Source:
<code>protected final void processAnnotationOnClass(MethodMetadata data, Class<?> targetType) { if (Arrays.stream(targetType.getAnnotations()) .anyMatch(annotation -> classAnnotationProcessors.stream() <START> .anyMatch(processor -> processor.test(annotation)))) { <END> Arrays.stream(targetType.getAnnotations()) .forEach(annotation -> classAnnotationProcessors.stream() .filter(processor -> processor.test(annotation)) .forEach(processor -> processor.process(annotation, data))); } else { if (targetType.getAnnotations().length == 0) { data.addWarning(String.format( "Class %s has no annotations, it may affect contract %s", targetType.getSimpleName(), getClass().getSimpleName())); } else { data.addWarning(String.format( "Class %s has annotations %s that are not used by contract %s", targetType.getSimpleName(), Arrays.stream(targetType.getAnnotations()) .map(annotation -> annotation.annotationType() .getSimpleName()) .collect(Collectors.toList()), getClass().getSimpleName())); } } }</code><technical_language>want move this test a function call getApplicableAnnotationProcessors() intention clearer this more readable</technical_language>

Target:
protected final void processAnnotationOnClass(MethodMetadata data, Class<?> targetType) { final List<GuardedAnnotationProcessor> processors = Arrays.stream(targetType.getAnnotations()) .flatMap(annotation -> classAnnotationProcessors.stream() .filter(processor -> processor.test(annotation))) .collect(Collectors.toList()); if (!processors.isEmpty()) { Arrays.stream(targetType.getAnnotations()) .forEach(annotation -> processors.stream() .filter(processor -> processor.test(annotation)) .forEach(processor -> processor.process(annotation, data))); } else { if (targetType.getAnnotations().length == 0) { data.addWarning(String.format( "Class %s has no annotations, it may affect contract %s", targetType.getSimpleName(), getClass().getSimpleName())); } else { data.addWarning(String.format( "Class %s has annotations %s that are not used by contract %s", targetType.getSimpleName(), Arrays.stream(targetType.getAnnotations()) .map(annotation -> annotation.annotationType() .getSimpleName()) .collect(Collectors.toList()), getClass().getSimpleName())); } } }
Source:
<code>public void testMismatch() throws Exception { ConstructorBean bean = db.getSharedHandle().createQuery("SELECT i, '7' FROM bean").mapTo(ConstructorBean.class).findOnly(); assertEquals("3", bean.s); <START> assertEquals(2, bean.i); <END> }</code><technical_language>asserts unreachable</technical_language>

Target:
public void testMismatch() throws Exception { db.getSharedHandle().createQuery("SELECT i, '7' FROM bean").mapTo(ConstructorBean.class).findOnly(); }
Source:
<code>public void loginRegisterTestWithMultipleAccounts() throws Exception { TokensApi unAuthenticatedTokensApi = new TokensApi(getWebClient(false, "n/a")); createAccount1(unAuthenticatedTokensApi); createAccount2(unAuthenticatedTokensApi); registerAndLinkUnavailableTokens(unAuthenticatedTokensApi); UsersApi mainUsersApi = new UsersApi(getWebClient(true, GOOGLE_ACCOUNT_USERNAME1)); io.swagger.client.model.User user = mainUsersApi.changeUsername(CUSTOM_USERNAME2); Assert.assertEquals(CUSTOM_USERNAME2, user.getUsername()); registerAndLinkUnavailableTokens(unAuthenticatedTokensApi); mockGitHub(CUSTOM_USERNAME1); mockGoogleHelper(GOOGLE_ACCOUNT_USERNAME1); io.swagger.client.model.Token token = unAuthenticatedTokensApi.addGoogleToken(satellizerJSON); <START> Assert.assertEquals(100l, (long)token.getUserId()); <END> io.swagger.client.model.Token fakeGitHubCode = unAuthenticatedTokensApi.addToken(satellizerJSON); Assert.assertEquals(100l, (long)fakeGitHubCode.getUserId()); }</code><technical_language>ID is easily breakable accident. If checking token is valid, re-retrieving database fine</technical_language>

Target:
public void loginRegisterTestWithMultipleAccounts() throws Exception { TokensApi unAuthenticatedTokensApi = new TokensApi(getWebClient(false, "n/a")); createAccount1(unAuthenticatedTokensApi); createAccount2(unAuthenticatedTokensApi); registerAndLinkUnavailableTokens(unAuthenticatedTokensApi); UsersApi mainUsersApi = new UsersApi(getWebClient(true, GOOGLE_ACCOUNT_USERNAME1)); io.swagger.client.model.User user = mainUsersApi.changeUsername(CUSTOM_USERNAME2); Assert.assertEquals(CUSTOM_USERNAME2, user.getUsername()); registerAndLinkUnavailableTokens(unAuthenticatedTokensApi); mockGitHub(CUSTOM_USERNAME1); mockGoogleHelper(GOOGLE_ACCOUNT_USERNAME1); io.swagger.client.model.Token token = unAuthenticatedTokensApi.addGoogleToken(satellizerJSON); Assert.assertEquals(CUSTOM_USERNAME2, token.getUsername()); Assert.assertEquals(TokenType.DOCKSTORE.toString(), token.getTokenSource()); io.swagger.client.model.Token fakeGitHubCode = unAuthenticatedTokensApi.addToken(satellizerJSON); Assert.assertEquals(CUSTOM_USERNAME2, fakeGitHubCode.getUsername()); Assert.assertEquals(TokenType.DOCKSTORE.toString(), fakeGitHubCode.getTokenSource()); }
Source:
<code>public int hashCode() { <START> return name.hashCode() ^ parameterType.hashCode(); <END> }</code><technical_language>For consistency, this objects hash in Ds3Type (parser module), as: return Objects.hash(getName(), getParameterType())</technical_language>

Target:
public int hashCode() { return Objects.hashCode(getName(), getParameterType(), getTypeModifier(), getParameterPointerType(), isRequired()); }
Source:
<code>public Set<Variable> variables() { final Set<Variable> result = new HashSet<Variable>(); this.accept(new AbstractVisitor<Void, Void>(null) { @Override <START> public Void visit(Variable node, Void _) { <END> result.add(node); return null; } }); return result; }</code><technical_language>"Void _" in this context? (Is Java 7 new in Java 8?)</technical_language>

Target:
public Set<Variable> variables() { final Set<Variable> result = new HashSet<Variable>(); new BasicVisitor(null) { @Override public Void visit(Variable node, Void _) { result.add(node); return null; } }.visitNode(this); return result; }
Source:
<code>private List<MetacardType> getFilteredMetacardTypes() { <START> if (!whitelistedMetacardTypes.isEmpty()) { <END> return metacardTypes .stream() .filter(metacardType -> whitelistedMetacardTypes.contains(metacardType.getName())) .collect(Collectors.toList()); } return metacardTypes; }</code><technical_language>need this check if whitelistedMetacardTypes is empty filter out ultimately return</technical_language>

Target:
private List<MetacardType> getFilteredMetacardTypes() { if (!whiteListedMetacardTypes.isEmpty()) { return metacardTypes .stream() .filter(metacardType -> whiteListedMetacardTypes.contains(metacardType.getName())) .collect(Collectors.toList()); } return metacardTypes; }
Source:
<code>public void setUp() { MockitoAnnotations.initMocks(this); TmcSettingsHolder.set(settings); langs = spy(new TaskExecutorImpl()); TmcLangsHolder.set(langs); TmcSettingsHolder.set(settings); Exercise ex = new Exercise("Osa02_01.WilliamLovelace", "Example"); command = new SubmitAdaptiveExerciseToSkillifier(mockObserver, ex, factory); arithFuncsTempDir = TestUtils.getProject(this.getClass(), "arith_funcs"); when(mockExercise.getExerciseDirectory(any(Path.class))).thenReturn(arithFuncsTempDir); when(settings.getLocale()).thenReturn(new Locale("FI")); Optional<String> mockToken = Optional.of("testToken"); settings.setToken(mockToken); <START> when(factory.getSkillifierUrl(anyString())).thenReturn(URI.create("www.someurl.com")); <END> }</code><technical_language>Prefer "www.example.com" reserved RFC2606. ".test" TLD is fine similarly reserved</technical_language>

Target:
public void setUp() { MockitoAnnotations.initMocks(this); TmcSettingsHolder.set(settings); langs = spy(new TaskExecutorImpl()); TmcLangsHolder.set(langs); TmcSettingsHolder.set(settings); Exercise ex = new Exercise("Osa02_01.WilliamLovelace", "Example"); command = new SubmitAdaptiveExerciseToSkillifier(mockObserver, ex, factory); arithFuncsTempDir = TestUtils.getProject(this.getClass(), "arith_funcs"); when(mockExercise.getExerciseDirectory(any(Path.class))).thenReturn(arithFuncsTempDir); when(settings.getLocale()).thenReturn(new Locale("FI")); Optional<String> mockToken = Optional.of("testToken"); settings.setToken(mockToken); when(factory.getSkillifierUrl(anyString())).thenReturn(URI.create("www.example.com")); }
Source:
<code>protected void onInit() throws ServletException { Saver<AuthenticationResult> authenticationResultSaver = getConfig().getInstance(AUTHENTICATION_RESULT_SAVER); MessageSource messageSource = getConfig().getInstance(MESSAGE_SOURCE); <START> LoginController controller = new LoginController( <END> getConfig().getLoginControllerConfig(), getConfig().getForgotPasswordControllerConfig().getUri(), getConfig().getVerifyControllerConfig().getUri(), getConfig().getRegisterControllerConfig().getUri(), getConfig().getLogoutControllerConfig().getUri(), getConfig().getVerifyControllerConfig().isEnable(), authenticationResultSaver, new LoginErrorModelFactory(messageSource)); setController(controller); super.onInit(); }</code><technical_language>is builder pattern feedback dev of is mandatory is optional coding/compile time instead wait run app for asserts place biting configuring controllers before. I builder pattern a lot of params in constructor bother me. In register branch working I reduce a couple of params. improve this while keeping benefits of constructor</technical_language>

Target:
protected void onInit() throws ServletException { MessageSource messageSource = getConfig().getInstance(MESSAGE_SOURCE); LoginController controller = new LoginController(getConfig(), new LoginErrorModelFactory(messageSource)); setController(controller); super.onInit(); }
Source:
<code>public IdentityProvider buildAndCreate(Client client) { IdentityProvider createdIdp = client.createIdentityProvider(client.instantiate(IdentityProvider.class) .setType(IdentityProvider.TypeEnum.GOOGLE) .setName(name) .setProtocol(client.instantiate(Protocol.class) .setType(protocolType) .setScopes(scopes) .setCredentials(client.instantiate(IdentityProviderCredentials.class) .setClient(client.instantiate(IdentityProviderCredentialsClient.class) .setClientId(clientId) .setClientSecret(clientSecret)))) .setPolicy(client.instantiate(IdentityProviderPolicy.class) .setProvisioning(client.instantiate(Provisioning.class) .setAction(Provisioning.ActionEnum.AUTO) .setProfileMaster(isProfileMaster) .setGroups(client.instantiate(ProvisioningGroups.class) .setAction(ProvisioningGroups.ActionEnum.NONE)) .setConditions(client.instantiate(ProvisioningConditions.class) .setDeprovisioned(client.instantiate(ProvisioningDeprovisionedCondition.class) .setAction(ProvisioningDeprovisionedCondition.ActionEnum.NONE)) .setSuspended(client.instantiate(ProvisioningSuspendedCondition.class) .setAction(ProvisioningSuspendedCondition.ActionEnum.NONE)))) .setAccountLink(client.instantiate(PolicyAccountLink.class) .setFilter(null) .setAction(PolicyAccountLink.ActionEnum.AUTO)) .setSubject(client.instantiate(PolicySubject.class) .setUserNameTemplate(client.instantiate(PolicyUserNameTemplate.class) .setTemplate(userNameTemplate)) .setMatchType(policySubjectMatchType)) <START> .setMaxClockSkew(maxClockSkew))); <END> return createdIdp; }</code><technical_language>wow, is this object like</technical_language>

Target:
public IdentityProvider buildAndCreate(Client client) { return client.createIdentityProvider(client.instantiate(IdentityProvider.class) .setType(IdentityProvider.TypeEnum.GOOGLE) .setName(name) .setProtocol(client.instantiate(Protocol.class) .setType(Protocol.TypeEnum.OIDC) .setScopes(scopes) .setCredentials(client.instantiate(IdentityProviderCredentials.class) .setClient(client.instantiate(IdentityProviderCredentialsClient.class) .setClientId(clientId) .setClientSecret(clientSecret)))) .setPolicy(client.instantiate(IdentityProviderPolicy.class) .setProvisioning(client.instantiate(Provisioning.class) .setAction(Provisioning.ActionEnum.AUTO) .setProfileMaster(isProfileMaster) .setGroups(client.instantiate(ProvisioningGroups.class) .setAction(ProvisioningGroups.ActionEnum.NONE)) .setConditions(client.instantiate(ProvisioningConditions.class) .setDeprovisioned(client.instantiate(ProvisioningDeprovisionedCondition.class) .setAction(ProvisioningDeprovisionedCondition.ActionEnum.NONE)) .setSuspended(client.instantiate(ProvisioningSuspendedCondition.class) .setAction(ProvisioningSuspendedCondition.ActionEnum.NONE)))) .setAccountLink(client.instantiate(PolicyAccountLink.class) .setFilter(null) .setAction(PolicyAccountLink.ActionEnum.AUTO)) .setSubject(client.instantiate(PolicySubject.class) .setUserNameTemplate(client.instantiate(PolicyUserNameTemplate.class) .setTemplate(userName)) .setMatchType(matchType)) .setMaxClockSkew(maxClockSkew))); }
Source:
<code>public boolean equals(Object o) { if (this == o) { return true; } if (o == null) { return false; } if (getClass() != o.getClass()) { return false; } VariantEntityRepositoryFilter o1 = (VariantEntityRepositoryFilter) o; return (this.field.equals(o1.field) && <START> Objects.equals(this.value, o1.value) && <END> Objects.equals(this.operator, o1.operator)); }</code><technical_language>this.value.equals(o1.value), Objects.equals method issues</technical_language>

Target:
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof VariantEntityRepositoryFilter)) { return false; } VariantEntityRepositoryFilter<?> that = (VariantEntityRepositoryFilter<?>) o; if (!field.equals(that.field)) { return false; } if (!value.equals(that.value)) { return false; } return operator == that.operator; }
Source:
<code><START> private String getConfigMethodType(ITestResult iTestResult) { <END> if (iTestResult.getMethod().isBeforeSuiteConfiguration()){ return "@BeforeSuite"; } if (iTestResult.getMethod().isBeforeTestConfiguration()) { return "@BeforeTest"; } if (iTestResult.getMethod().isBeforeClassConfiguration()) { return "@BeforeClass"; } if (iTestResult.getMethod().isBeforeMethodConfiguration()) { return "@BeforeMethod"; } if (iTestResult.getMethod().isAfterSuiteConfiguration()){ return "@AfterSuite"; } if (iTestResult.getMethod().isAfterTestConfiguration()) { return "@AfterTest"; } if (iTestResult.getMethod().isAfterClassConfiguration()) { return "@AfterClass"; } if (iTestResult.getMethod().isAfterMethodConfiguration()) { return "@AfterMethod"; } return ""; }</code><technical_language>I test for method type</technical_language>

Target:
private ConfigMethodType getConfigMethodType(ITestResult iTestResult) { if (iTestResult.getMethod().isBeforeSuiteConfiguration()){ return ConfigMethodType.BeforeSuite; } if (iTestResult.getMethod().isBeforeTestConfiguration()) { return ConfigMethodType.BeforeTest; } if (iTestResult.getMethod().isBeforeClassConfiguration()) { return ConfigMethodType.BeforeClass; } if (iTestResult.getMethod().isBeforeGroupsConfiguration()) { return ConfigMethodType.BeforeGroups; } if (iTestResult.getMethod().isBeforeMethodConfiguration()) { return ConfigMethodType.BeforeMethod; } if (iTestResult.getMethod().isAfterSuiteConfiguration()){ return ConfigMethodType.AfterSuite; } if (iTestResult.getMethod().isAfterTestConfiguration()) { return ConfigMethodType.AfterTest; } if (iTestResult.getMethod().isAfterClassConfiguration()) { return ConfigMethodType.AfterClass; } if (iTestResult.getMethod().isAfterGroupsConfiguration()) { return ConfigMethodType.AfterGroups; } if (iTestResult.getMethod().isAfterMethodConfiguration()) { return ConfigMethodType.AfterMethod; } return null; }
Source:
<code>void receivedInAppMessageJson(@NonNull JSONArray json) throws JSONException { OneSignalPrefs.saveString(OneSignalPrefs.PREFS_ONESIGNAL, OneSignalPrefs.PREFS_OS_CACHED_IAMS, json.toString()); ArrayList<OSInAppMessage> newMessages = processInAppMessageJson(json); <START> List<OSInAppMessage> updatedRedisplayMessages = inAppMessageRepository.updateInAppMessage(newMessages, redisplayInAppMessages); <END> if (redisplayInAppMessages.size() != updatedRedisplayMessages.size()) { redisplayInAppMessages = updatedRedisplayMessages; } setMessages(newMessages); }</code><technical_language>source of newMessages is driven results on_session network call . results on_session is drive backend if player fits Segments defined there. this means IAM fall in out of Segment multiple times result in on_session either. reset display stats noted delete local records a long period of time safe all. set this 6 months safe</technical_language>

Target:
void receivedInAppMessageJson(@NonNull JSONArray json) throws JSONException { OneSignalPrefs.saveString(OneSignalPrefs.PREFS_ONESIGNAL, OneSignalPrefs.PREFS_OS_CACHED_IAMS, json.toString()); resetRedisplayMessagesBySession(); processInAppMessageJson(json); deleteOldRedisplayedInAppMessages(); }
Source:
<code>public String toString() { <START> return jobId + "|" + goal; <END> }</code><technical_language>Do want include deployUser in toString() method</technical_language>

Target:
public String toString() { return Objects.toStringHelper(this) .add("jobId", jobId) .add("goal", goal) .add("deployerUser", deployerUser) .toString(); }
Source:
<code>public List<Section> processResult(ApiResult result) throws Throwable { if (result.asObject().has("error")) { JSONObject errorJSON = result.asObject().optJSONObject("error"); throw new SectionsFetchException(errorJSON.optString("code"), errorJSON.optString("info")); } JSONArray sectionsJSON = result.asObject().optJSONObject("mobileview").optJSONArray("sections"); ArrayList<Section> sections = new ArrayList<Section>(); <START> if (sectionsJSON != null) { <END> for (int i = 0; i < sectionsJSON.length(); i++) { Section newSection = new Section(sectionsJSON.getJSONObject(i)); sections.add(newSection); } } if (WikipediaApp.isWikipediaZeroDevmodeOn()) { Utils.processHeadersForZero(app, result); } return sections; }</code><technical_language>Sure, do like: throw new ApiException(new JSONException("FIXME: server returned 0 sections error."));</technical_language>

Target:
public List<Section> processResult(ApiResult result) throws Throwable { if (result.asObject().has("error")) { JSONObject errorJSON = result.asObject().optJSONObject("error"); throw new SectionsFetchException(errorJSON.optString("code"), errorJSON.optString("info")); } JSONArray sectionsJSON = result.asObject().optJSONObject("mobileview").optJSONArray("sections"); ArrayList<Section> sections = new ArrayList<Section>(); if (sectionsJSON == null) { throw new ApiException(new JSONException("FIXME: server returned 0 sections with no error.")); } for (int i = 0; i < sectionsJSON.length(); i++) { Section newSection = new Section(sectionsJSON.getJSONObject(i)); sections.add(newSection); } if (WikipediaApp.isWikipediaZeroDevmodeOn()) { Utils.processHeadersForZero(app, result); } return sections; }
Source:
<code>public void testOpenAndCloseConcurrency() { SWTBotUtils.createProject(TRACE_PROJECT_NAME); File fTestFile = new File(CtfTmfTestTraceUtils.getTrace(CTF_TRACE).getPath()); CtfTmfTestTraceUtils.dispose(CTF_TRACE); String path = fTestFile.getAbsolutePath(); assertNotNull(fTestFile); assumeTrue(fTestFile.exists()); final MultiStatus status = new MultiStatus("lttn2.kernel.ui.swtbot.tests", IStatus.OK, null, null); IJobManager mgr = Job.getJobManager(); JobChangeAdapter changeListener = new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { Job job = event.getJob(); String jobNamePrefix = NLS.bind(Messages.TmfAbstractAnalysisModule_RunningAnalysis, ""); if ((job.getName().startsWith(jobNamePrefix)) && (job.getResult().getSeverity() == IStatus.ERROR)) { status.add(job.getResult()); } } }; mgr.addJobChangeListener(changeListener); <START> for (int i = 0; i < 5; i++) { SWTBotUtils.openTrace(TRACE_PROJECT_NAME, path, TRACE_TYPE, false); SWTBotUtils.openTrace(TRACE_PROJECT_NAME, path, TRACE_TYPE, false); SWTBotUtils.openTrace(TRACE_PROJECT_NAME, path, TRACE_TYPE, false); SWTBotUtils.openTrace(TRACE_PROJECT_NAME, path, TRACE_TYPE, false); SWTBotUtils.openTrace(TRACE_PROJECT_NAME, path, TRACE_TYPE, false); SWTBotUtils.delay(50); <END> workbenchbot.closeAllEditors(); if (!status.isOK()) { SWTBotUtils.deleteProject(TRACE_PROJECT_NAME, workbenchbot); fail(handleErrorStatus(status)); } } SWTBotUtils.deleteProject(TRACE_PROJECT_NAME, workbenchbot); }</code><technical_language>goal is stress test trace opening. I change 10 iteration reduce delay 500. test teake 5sec instead of 10sec</technical_language>

Target:
public void testOpenAndCloseConcurrency() { SWTBotUtils.createProject(TRACE_PROJECT_NAME); File fTestFile = new File(CtfTmfTestTraceUtils.getTrace(CTF_TRACE).getPath()); CtfTmfTestTraceUtils.dispose(CTF_TRACE); String path = fTestFile.getAbsolutePath(); assertNotNull(fTestFile); assumeTrue(fTestFile.exists()); final MultiStatus status = new MultiStatus("lttn2.kernel.ui.swtbot.tests", IStatus.OK, null, null); IJobManager mgr = Job.getJobManager(); JobChangeAdapter changeListener = new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { Job job = event.getJob(); String jobNamePrefix = NLS.bind(Messages.TmfAbstractAnalysisModule_RunningAnalysis, ""); if ((job.getName().startsWith(jobNamePrefix)) && (job.getResult().getSeverity() == IStatus.ERROR)) { status.add(job.getResult()); } } }; mgr.addJobChangeListener(changeListener); for (int i = 0; i < 10; i++) { SWTBotUtils.openTrace(TRACE_PROJECT_NAME, path, TRACE_TYPE, false); SWTBotUtils.openTrace(TRACE_PROJECT_NAME, path, TRACE_TYPE, false); SWTBotUtils.openTrace(TRACE_PROJECT_NAME, path, TRACE_TYPE, false); SWTBotUtils.openTrace(TRACE_PROJECT_NAME, path, TRACE_TYPE, false); SWTBotUtils.openTrace(TRACE_PROJECT_NAME, path, TRACE_TYPE, false); SWTBotUtils.delay(1000); workbenchbot.closeAllEditors(); if (!status.isOK()) { SWTBotUtils.deleteProject(TRACE_PROJECT_NAME, workbenchbot); fail(handleErrorStatus(status)); } } SWTBotUtils.deleteProject(TRACE_PROJECT_NAME, workbenchbot); }
Source:
<code>private boolean clientHasPermission(EntityRef callingClient, String requiredPermission) { PermissionManager permissionManager = CoreRegistry.get(PermissionManager.class); boolean hasPermission = true; <START> if (permissionManager != null && requiredPermission != null && !requiredPermission.isEmpty()) { <END> hasPermission = false; ClientComponent clientComponent = callingClient.getComponent(ClientComponent.class); if (clientComponent != null) { EntityRef character = clientComponent.character; if (permissionManager.hasPermission(character, requiredPermission)) { hasPermission = true; } } } return hasPermission; }</code><technical_language>Suggest of Preconditions check parameters state. silently work null, fail open (return true null)</technical_language>

Target:
private boolean clientHasPermission(EntityRef callingClient, String requiredPermission) { Preconditions.checkNotNull(callingClient, "The calling client must not be null!"); PermissionManager permissionManager = CoreRegistry.get(PermissionManager.class); boolean hasPermission = true; if (permissionManager != null && requiredPermission != null && !requiredPermission.isEmpty()) { hasPermission = false; ClientComponent clientComponent = callingClient.getComponent(ClientComponent.class); EntityRef character = clientComponent.character; if (permissionManager.hasPermission(character, requiredPermission)) { hasPermission = true; } } return hasPermission; }