auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>void processMsg(byte[] data, int offset, int length) { SubscriptionImpl sub; mu.lock(); try { stats.incrementInMsgs(); stats.incrementInBytes(length); sub = subs.get(parser.ps.ma.sid); if (sub == null) { return; } Message msg = new Message(parser.ps.ma, sub, data, offset, length); MsgDeliveryWorker mdw = null; if (sub instanceof AsyncSubscriptionImpl) { mdw = ((AsyncSubscriptionImpl) sub).getDeliveryWorker(); } <START> if (mdw != null) { <END> mdw.lock(); } else { sub.lock(); } try { sub.pMsgs++; if (sub.pMsgs > sub.pMsgsMax) { sub.pMsgsMax = sub.pMsgs; } sub.pBytes += (msg.getData() == null ? 0 : msg.getData().length); if (sub.pBytes > sub.pBytesMax) { sub.pBytesMax = sub.pBytes; } if ((sub.pMsgsLimit > 0 && sub.pMsgs > sub.pMsgsLimit) || (sub.pBytesLimit > 0 && sub.pBytes > sub.pBytesLimit)) { handleSlowConsumer(sub, msg); } else { if (mdw != null) { mdw.postMsg(msg); } else { if (sub.getChannel() != null) { if (sub.getChannel().add(msg)) { sub.pCond.signal(); sub.setSlowConsumer(false); } else { handleSlowConsumer(sub, msg); } } } } } finally { if (mdw != null) { mdw.unlock(); } else { sub.unlock(); } } } finally { mu.unlock(); } }</code><technical_language>Is a race mdw able obtain lock</technical_language>

Target:
void processMsg(byte[] data, int offset, int length) { SubscriptionImpl sub; mu.lock(); try { stats.incrementInMsgs(); stats.incrementInBytes(length); sub = subs.get(parser.ps.ma.sid); if (sub == null) { return; } Message msg = new Message(parser.ps.ma, sub, data, offset, length); MsgDeliveryWorker mdw = null; if (sub instanceof AsyncSubscriptionImpl) { mdw = ((AsyncSubscriptionImpl) sub).getDeliveryWorker(); } if (mdw != null) { mdw.lock(); } else { sub.lock(); } try { sub.pMsgs++; if (sub.pMsgs > sub.pMsgsMax) { sub.pMsgsMax = sub.pMsgs; } sub.pBytes += (msg.getData() == null ? 0 : msg.getData().length); if (sub.pBytes > sub.pBytesMax) { sub.pBytesMax = sub.pBytes; } if ((sub.pMsgsLimit > 0 && sub.pMsgs > sub.pMsgsLimit) || (sub.pBytesLimit > 0 && sub.pBytes > sub.pBytesLimit)) { handleSlowConsumer(sub, msg); } else { sub.setSlowConsumer(false); if (mdw != null) { mdw.postMsg(msg); } else { if (sub.getChannel() != null) { if (sub.getChannel().add(msg)) { sub.pCond.signal(); } else { handleSlowConsumer(sub, msg); } } } } } finally { if (mdw != null) { mdw.unlock(); } else { sub.unlock(); } } } finally { mu.unlock(); } }
Source:
<code>private void initializeRunId(){ <START> LOG.info("Manasa: LocalApplicationRunner: getRunId() : entered "); <END> Boolean isAppModeBatch = new ApplicationConfig(appDesc.getConfig()).getAppMode() == ApplicationConfig.ApplicationMode.BATCH; if(coordinationUtils == null || !isAppModeBatch) { return; } runIdLock = coordinationUtils.getReadWriteLock(CoordinationConstants.RUNID_LOCK_ID); runIdAccess = coordinationUtils.getDataAccess(); if(runIdAccess == null || runIdLock == null) { LOG.warn("Processor failed to create utils for run.id generation", uid); return; } try { DistributedReadWriteLock.AccessType lockAccess = runIdLock.lock(CoordinationConstants.LOCK_TIMEOUT_MS, TimeUnit.MILLISECONDS); if(lockAccess == DistributedReadWriteLock.AccessType.WRITE) { LOG.info("write lock acquired for run.id generation by Processor " + uid); runId = String.valueOf(System.currentTimeMillis()) + "-" + UUID.randomUUID().toString().substring(0, 8); LOG.info("The run id for this run is {}", runId); runIdAccess.writeData(CoordinationConstants.RUNID_PATH, runId, new LocalDistributedDataWatcher()); runIdLock.unlock(); } else if(lockAccess == DistributedReadWriteLock.AccessType.READ) { LOG.info("read lock acquired for run.id by Processor " + uid); runId = (String) runIdAccess.readData(CoordinationConstants.RUNID_PATH, new LocalDistributedDataWatcher()); runIdLock.unlock(); } else { String msg = String.format("Processor failed to get the lock for run.id", uid); throw new SamzaException(msg); } } catch (TimeoutException e) { String msg = String.format("Processor timed out waiting to acquire lock for run.id generation", uid); throw new SamzaException(msg, e); } }</code><technical_language>nit: remove "Manasa" log statements</technical_language>

Target:
private void initializeRunId() { if (!isAppModeBatch) { LOG.info("Not BATCH mode and hence not generating run id"); return; } if (!coordinationUtils.isPresent()) { LOG.warn("Coordination utils not present. Aborting run id generation. Will continue execution without a run id."); return; } try { MetadataStore metadataStore = getMetadataStore(); runIdGenerator = Optional.of(new RunIdGenerator(coordinationUtils.get(), metadataStore)); runId = runIdGenerator.flatMap(RunIdGenerator::getRunId); } catch (Exception e) { LOG.warn("Failed to generate run id. Will continue execution without a run id. Caused by {}", e); } }
Source:
<code>public void removeListener() { if (!stereotypeList.isEmpty()) { <START> if (comment != null) { <END> for (Stereotype stereotype : stereotypeList) { getDiagramEventBroker().removeNotificationListener(helper.getStereotypeCompartment(comment, stereotype), this); getDiagramEventBroker().removeNotificationListener(helper.getStereotypeBraceCompartment(comment, stereotype), this); } } } }</code><technical_language>'null !=' is preferably</technical_language>

Target:
public void removeListener() { if (!stereotypeList.isEmpty()) { if (null != comment) { for (Stereotype stereotype : stereotypeList) { getDiagramEventBroker().removeNotificationListener(helper.getStereotypeCompartment(comment, stereotype), this); getDiagramEventBroker().removeNotificationListener(helper.getStereotypeBraceCompartment(comment, stereotype), this); } } } }
Source:
<code>void testNumberOfCellsByExperimentAccession(String experimentAccession) { <START> cleanDatabaseTables(); <END> populator.setScripts(new ClassPathResource("fixtures/scxa_tsne-full.sql")); populator.execute(dataSource); Map<Integer, AtlasResource<TsvStreamer>> resource = new DataFileHub(dataFilesPath.resolve("scxa")) .getSingleCellExperimentFiles(experimentAccession).tSnePlotTsvs; Map.Entry<Integer, AtlasResource<TsvStreamer>> firstFile = resource.entrySet().iterator().next(); Stream<String[]> fileContent = firstFile.getValue().get().get(); Integer fileContentLines = Math.toIntExact(fileContent.count()); Integer numberOfcells = subject.fetchCellNumberByExperimentAccession(experimentAccession); assertThat(numberOfcells) .isEqualTo(fileContentLines-1); cleanDatabaseTables(); populateDatabaseTables(); }</code><technical_language>Is reason fixtures for tests? change @AfterAll @BeforeAll @AfterEach @BeforeEach</technical_language>

Target:
void testNumberOfCellsByExperimentAccession(String experimentAccession) { cleanDatabaseTables(); populator.setScripts(new ClassPathResource("fixtures/scxa_tsne-full.sql")); populator.execute(dataSource); Map<Integer, AtlasResource<TsvStreamer>> resource = new DataFileHub(dataFilesPath.resolve("scxa")) .getSingleCellExperimentFiles(experimentAccession).tSnePlotTsvs; Map.Entry<Integer, AtlasResource<TsvStreamer>> firstFile = resource.entrySet().iterator().next(); Stream<String[]> fileContent = firstFile.getValue().get().get(); Integer fileContentLines = Math.toIntExact(fileContent.count()); Integer numberOfcells = subject.fetchNumberOfCellsByExperimentAccession(experimentAccession); assertThat(numberOfcells) .isEqualTo(fileContentLines-1); cleanDatabaseTables(); populateDatabaseTables(); }
Source:
<code>public CachingContext(ExperimentsCache cache, Experiment.BuilderFactory builderFactory, ExecutorService executorService) { this.cache = cache; this.builderFactory = builderFactory; <START> this.executorService = executorService != null ? executorService : Executors.newSingleThreadExecutor(); <END> this.ownsExecutorService = executorService == null; this.experimentLocks = Maps.newConcurrentMap(); this.lock = new ReentrantLock(); }</code><technical_language>constructors? executor? This is obvious a caller executor is optional</technical_language>

Target:
public CachingContext(ExperimentsCache cache, Experiment.BuilderFactory builderFactory, ExecutorService executorService) { this.cache = cache; this.builderFactory = builderFactory; this.executorService = executorService != null ? executorService : Executors.newSingleThreadExecutor(); this.ownsExecutorService = executorService == null; this.experimentLocks = Maps.newConcurrentMap(); this.lock = new AtomicBoolean(false); }
Source:
<code>public void testProxyUriUnexpectedWidgetType() { <START> ItemUIRegistry itemUIRegistry = mock(ItemUIRegistry.class); <END> ModelRepository modelRepository = mock(ModelRepository.class); Sitemap sitemap = mock(Sitemap.class); Switch widget = mock(Switch.class); HttpServletRequest request = mock(HttpServletRequest.class); service.setModelRepository(modelRepository); service.setItemUIRegistry(itemUIRegistry); when(request.getParameter(eq("sitemap"))).thenReturn("testSitemap"); when(request.getParameter(eq("widgetId"))).thenReturn("testWidget"); when(modelRepository.getModel(eq("testSitemap"))).thenReturn(sitemap); when(itemUIRegistry.getWidget(eq(sitemap), eq("testWidget"))).thenReturn(widget); URI uri = service.uriFromRequest(request); assertNull(uri); }</code><technical_language>basic mocks in test setup method</technical_language>

Target:
public void testProxyUriUnexpectedWidgetType() { when(request.getParameter(eq("widgetId"))).thenReturn(SWITCH_WIDGET_ID); URI uri = service.uriFromRequest(request); assertNull(uri); }
Source:
<code>public static Slice stPoint(@SqlType(StandardTypes.DOUBLE) double x, @SqlType(StandardTypes.DOUBLE) double y) { <START> OGCGeometry geometry = getGeometry(OGCGeometry.createFromEsriGeometry(new Point(x, y), null), "ST_Point", POINT); <END> return serialize(geometry); }</code><technical_language>getGeometry call is redundant, OGCGeometry.createFromEsriGeometry(new Point(x, y), null) return other point. Perhaps, remove it</technical_language>

Target:
public static Slice stPoint(@SqlType(StandardTypes.DOUBLE) double x, @SqlType(StandardTypes.DOUBLE) double y) { OGCGeometry geometry = createFromEsriGeometry(new Point(x, y), null); return serialize(geometry); }
Source:
<code>AbstractApplication loadApplicationFromClasspathOrParse(ResourceUtils utils, GroovyClassLoader loader, String app) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { Class<?> appClass; try { log.debug("Trying to load application as class on classpath"); appClass = loader.loadClass(app, true, false); } catch (ClassNotFoundException cnfe) { <START> log.debug("Loading as class on classpath failed, now trying as .groovy file"); <END> String content = utils.getResourceAsString(app); appClass = loader.parseClass(content); } Constructor<?> constructor = appClass.getConstructor(); return (AbstractApplication) constructor.newInstance(); }</code><technical_language>app failed load</technical_language>

Target:
AbstractApplication loadApplicationFromClasspathOrParse(ResourceUtils utils, GroovyClassLoader loader, String app) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { Class<?> appClass; try { log.debug("Trying to load application as class on classpath: {}", app); appClass = loader.loadClass(app, true, false); } catch (ClassNotFoundException cnfe) { log.debug("Loading \"{}\" as class on classpath failed, now trying as .groovy source file",app); String content = utils.getResourceAsString(app); appClass = loader.parseClass(content); } Constructor<?> constructor = appClass.getConstructor(); return (AbstractApplication) constructor.newInstance(); }
Source:
<code>public final ProtoSubject message(int index) { if (messages() == null) { <START> failWithActual(fact(FactKey.ACTUAL.value, null)); <END> return ignoreCheck().about(protos()) .that(Empty.getDefaultInstance()); } int size = size(messages()); if (index >= size(messages())) { failWithActual( fact(FactKey.MESSAGE_COUNT.value, size), fact(FactKey.REQUESTED_INDEX.value, index) ); return ignoreCheck().about(protos()) .that(Empty.getDefaultInstance()); } T outerObject = Iterables.get(messages(), index); Message unpacked = AnyPacker.unpack(outerObject.getMessage()); return ProtoTruth.assertThat(unpacked); }</code><technical_language>enum values referencing enum name</technical_language>

Target:
public final ProtoSubject message(int index) { if (messages() == null) { failWithActual(fact(ACTUAL.value, null)); return ignoreCheck().about(protos()) .that(Empty.getDefaultInstance()); } int size = size(messages()); if (index >= size(messages())) { failWithActual( fact(MESSAGE_COUNT.value, size), fact(REQUESTED_INDEX.value, index) ); return ignoreCheck().about(protos()) .that(Empty.getDefaultInstance()); } T outerObject = Iterables.get(messages(), index); Message unpacked = AnyPacker.unpack(outerObject.getMessage()); return ProtoTruth.assertThat(unpacked); }
Source:
<code>void cancelFocusAndMetering() { if (mCurrentFocusMeteringAction != null) { mCurrentFocusMeteringAction.notifyAutoFocusCompleted(false); } disableAutoCancel(); if (shouldTriggerAF()) { <START> mCameraControl.cancelAfAeTriggerInternal(true, false); <END> } mAfRects = new MeteringRectangle[]{}; mAeRects = new MeteringRectangle[]{}; mAwbRects = new MeteringRectangle[]{}; mCameraControl.setIsInAfAutoMode(false); mCameraControl.updateSessionConfig(); mCurrentFocusMeteringAction = null; }</code><technical_language>Whats reason Camera2CameraControls some of AfAe specific controls. for AfAe specific methods in FocusMeteringControl? instead Camera2CameraControl generic method for sending triggers</technical_language>

Target:
void cancelFocusAndMetering() { mCameraControl.removeCaptureResultListener(mSessionListenerForFocus); if (mCurrentFocusMeteringAction != null) { mCurrentFocusMeteringAction.notifyAutoFocusCompleted(false); } disableAutoCancel(); if (shouldTriggerAF()) { mCameraControl.cancelAfAeTriggerInternal(true, false); } mAfRects = new MeteringRectangle[]{}; mAeRects = new MeteringRectangle[]{}; mAwbRects = new MeteringRectangle[]{}; mIsInAfAutoMode = false; mCameraControl.updateSessionConfig(); mCurrentFocusMeteringAction = null; }
Source:
<code>static FileBasedSystemAccessControlRules parse(byte[] json) { <START> ObjectMapper mapper = new ObjectMapperProvider().get() <END> .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); Class<FileBasedSystemAccessControlRules> javaType = FileBasedSystemAccessControlRules.class; try { return mapper.readValue(json, javaType); } catch (IOException e) { throw new IllegalArgumentException(format("Invalid JSON string for %s", javaType), e); } }</code><technical_language>JsonCodec: java return new JsonCodecFactory().jsonCodec(FileBasedSystemAccessControlRules.class).fromJson(json);</technical_language>

Target:
private static FileBasedSystemAccessControlRules parse(byte[] json) { ObjectMapper mapper = new ObjectMapperProvider().get() .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); Class<FileBasedSystemAccessControlRules> javaType = FileBasedSystemAccessControlRules.class; try { return mapper.readValue(json, javaType); } catch (IOException e) { throw new IllegalArgumentException(format("Invalid JSON string for %s", javaType), e); } }
Source:
<code>private void invoke(String... parameters) { CmdLineParser parser = new CmdLineParser(this); try { try { parser.parseArgument(parameters); if (inputFiles.isEmpty()) { throw new CmdLineException(parser, "asciidoctor: FAILED: input file missing"); } } catch (CmdLineException e) { System.err.println(e.getMessage()); parser.printUsage(System.err); System.exit(1); return; } ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(zipFile)); byte[] buf = new byte[BUFSIZ]; for (String inputFile : inputFiles) { <START> Options options = createOptions(inputFile); <END> renderInput(options, inputFile); FileInputStream f = new FileInputStream(new File(mapInFileToOutFileWithDir(inputFile))); int len; zip.putNextEntry(new ZipEntry(mapInFileToOutFile(inputFile))); while ((len = f.read(buf)) > 0) { zip.write(buf, 0, len); } f.close(); zip.closeEntry(); } zip.close(); } catch (java.io.IOException e) { System.err.println(e.getMessage()); System.exit(1); } }</code><technical_language>a temporary file, automatically $TMP: File tmp = File.createTempFile("doc", ".html"); Options options = createOptions(tmp);</technical_language>

Target:
private void invoke(String... parameters) throws IOException { CmdLineParser parser = new CmdLineParser(this); try { parser.parseArgument(parameters); if (inputFiles.isEmpty()) { throw new CmdLineException(parser, "asciidoctor: FAILED: input file missing"); } } catch (CmdLineException e) { System.err.println(e.getMessage()); parser.printUsage(System.err); System.exit(1); return; } ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(zipFile)); byte[] buf = new byte[BUFSIZ]; for (String inputFile : inputFiles) { File tmp = File.createTempFile("doc", ".html"); tmp.deleteOnExit(); Options options = createOptions(tmp); renderInput(options, inputFile); FileInputStream f = new FileInputStream(tmp); int len; zip.putNextEntry(new ZipEntry(mapInFileToOutFile(inputFile))); while ((len = f.read(buf)) > 0) { zip.write(buf, 0, len); } f.close(); zip.closeEntry(); } zip.close(); }
Source:
<code>public boolean isCompatible(String otherMimeType) { return mimeType.equalsIgnoreCase(otherMimeType) || <START> otherMimeType.startsWith(mimeType); <END> }</code><technical_language>this case insensitive if exact match, case sensitive if matching a subtype, is odd do</technical_language>

Target:
public boolean isCompatible(String otherMimeType) { return mimeType.equalsIgnoreCase(otherMimeType) || (otherMimeType != null && otherMimeType.toLowerCase().startsWith(mimeType.toLowerCase())); }
Source:
<code>protected Pair<Boolean, EngineFault> runConnectionStorageToDomain(StorageDomain storageDomain, Guid vdsId, int type, LUNs lun, Guid storagePoolId) { if (FeatureSupported.refreshLunSupported(DbFacade.getInstance() .getStoragePoolDao() .get(storagePoolId) <START> .getCompatibilityVersion())) { <END> List<StorageServerConnections> list = new ArrayList<>(); list.add(getFCPConnection()); VDSReturnValue returnValue = Backend .getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.forValue(type), new StorageServerConnectionManagementVDSParameters(vdsId, storagePoolId, StorageType.FCP, list)); boolean isSuccess = returnValue.getSucceeded(); EngineFault engineFault = null; if (!isSuccess && returnValue.getVdsError() != null) { engineFault = new EngineFault(); engineFault.setError(returnValue.getVdsError().getCode()); } return new Pair<>(isSuccess, engineFault); } else { return new Pair<>(true, null); } }</code><technical_language>In case of passed Guid.Empty pool id get a NPE here</technical_language>

Target:
protected Pair<Boolean, EngineFault> runConnectionStorageToDomain(StorageDomain storageDomain, Guid vdsId, int type, LUNs lun, Guid storagePoolId) { if(storagePoolId == null || storagePoolId.equals(Guid.Empty)){ return new Pair<>(false, null); } if (FeatureSupported.refreshLunSupported(DbFacade.getInstance() .getStoragePoolDao() .get(storagePoolId) .getCompatibilityVersion())) { VDSReturnValue returnValue = Backend .getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.forValue(type), new StorageServerConnectionManagementVDSParameters(vdsId, storagePoolId, StorageType.FCP, Arrays.asList(getFCPConnection()))); boolean isSuccess = returnValue.getSucceeded(); EngineFault engineFault = null; if (!isSuccess && returnValue.getVdsError() != null) { engineFault = new EngineFault(); engineFault.setError(returnValue.getVdsError().getCode()); } return new Pair<>(isSuccess, engineFault); } else { return new Pair<>(true, null); } }
Source:
<code>public void addColumn(Column<T, ?> column, Header<?> header) { Header<?> wrappedHeader = (columnResizingEnabled && header instanceof CheckboxHeader) <START> ? new ResizeableCheckboxHeader<T>((CheckboxHeader) header, column, this) : header; <END> super.addColumn(column, wrappedHeader); if (columnResizingEnabled) { if (emptyNoWidthColumn != null) { removeColumn(emptyNoWidthColumn); } emptyNoWidthColumn = new EmptyColumn<T>(); addColumn(emptyNoWidthColumn); } }</code><technical_language>suggest move this code separate method, for example: Header<?> maybeWrapHeader(Column<T, ?> column, Header<?> header) ... in addColumn method: super.addColumn(column, maybeWrapHeader(column, header));</technical_language>

Target:
public void addColumn(Column<T, ?> column, Header<?> header) { super.addColumn(column, wrapHeader(header, column)); if (columnResizingEnabled) { if (emptyNoWidthColumn != null) { removeColumn(emptyNoWidthColumn); } emptyNoWidthColumn = new EmptyColumn<T>(); addColumn(emptyNoWidthColumn); } }
Source:
<code>private void unlockImageInDb() { DiskImage diskImage = getDiskImage(); <START> diskImage.setImageStatus(ImageStatus.OK); <END> ImagesHandler.updateImageStatus(diskImage.getImageId(), ImageStatus.OK); }</code><technical_language>needed, next statement handles in DB, do care if status changed in instance</technical_language>

Target:
private void unlockImageInDb() { DiskImage diskImage = getDiskImage(); ImagesHandler.updateImageStatus(diskImage.getImageId(), ImageStatus.OK); }
Source:
<code>public void processSoftwareCapabilities(VDS vds) { boolean softwareCapabilitiesAreMet = true; <START> <END> if (vds.getKvmEnabled() != null && vds.getKvmEnabled().equals(false)) { softwareCapabilitiesAreMet = false; } if (!softwareCapabilitiesAreMet && vds.getStatus() != VDSStatus.NonOperational) { vdsNonOperational(vds); vds.setStatus(VDSStatus.NonOperational); } }</code><technical_language>if processSoftwareCapabilities, call methods (or a new method) this one</technical_language>

Target:
public void processSoftwareCapabilities(VDS vds) { if (vds.getKvmEnabled() != null && vds.getKvmEnabled().equals(false) && vds.getStatus() != VDSStatus.NonOperational) { vdsNonOperational(vds, NonOperationalReason.KVM_NOT_RUNNING, null); vds.setStatus(VDSStatus.NonOperational); } VDSGroup vdsGroup = DbFacade.getInstance().getVdsGroupDao().get(vds.getVdsGroupId()); if (!hostCompliesWithClusterEmulationMode(vds, vdsGroup) && vds.getStatus() != VDSStatus.NonOperational) { Map<String, String> customLogValues = new HashMap<>(); customLogValues.put("hostSupportedEmulatedMachines", vds.getSupportedEmulatedMachines()); customLogValues.put("clusterEmulatedMachines", StringUtils.isEmpty(vdsGroup.getEmulatedMachine()) ? Config.<String>GetValue(ConfigValues.ClusterEmulatedMachines, vds.getVdsGroupCompatibilityVersion().getValue()) : vdsGroup.getEmulatedMachine()); vdsNonOperational(vds, NonOperationalReason.EMULATED_MACHINES_INCOMPATIBLE_WITH_CLUSTER, customLogValues); vds.setStatus(VDSStatus.NonOperational); } }
Source:
<code>protected void setNavMenuItems() { navMenu = new NavDrawerItem[] { NavMenuItem.create(SWITCH_MODE, getResources().getString(R.string.switch_to_client), "ic_action_client_mode", false, this), <START> NavMenuItem.create(LOGOUT, getResources().getString(R.string.logout), "ic_logout", false, this) <END> }; }</code><technical_language>weird do this time. Maybe, default, include logout item. Then, in situations invalidate state, add "change mode" item. I guess implies show header if logged in, is case, right</technical_language>

Target:
protected void setNavMenuItems() { navMenu = new NavDrawerItem[] { NavMenuItem.create(SWITCH_MODE, getResources().getString(R.string.switch_to_client), "ic_action_client_mode", false, this), LogoutMenuItem.create(this) }; }
Source:
<code>public final void run() { doRun(); <START> fHasDrawnEntries = true; <END> fDirty.decrementAndGet(); }</code><technical_language>A problem this is relies zoom thread, implementation zoom list thread (could override createZoomThread() return null). Also, clear flag if completed zoom empty entry list, if entries filtered out. work if build thread done a iteration called refresh() discovered entries yet</technical_language>

Target:
public final void run() { doRun(); fDirty.decrementAndGet(); }
Source:
<code>private static void validateClause(Map<String, Object> clause) throws QueryException { List<String> validOperators = Arrays.asList(EQ, LT, GT, EXISTS, NOT, GTE, LTE, IN, MOD, SIZE); if (clause.size() == 1) { String operator = (String) clause.keySet().toArray()[0]; if (validOperators.contains(operator)) { Object clauseOperand = clause.get(operator); if (operator.equals(NOT)) { if (!(clauseOperand instanceof Map)) { <START> throw new QueryException("clauseOperand not instance of Map"); <END> } validateClause((Map) clauseOperand); } else if (operator.equals(IN)) { if (!(clauseOperand instanceof List)) { throw new QueryException("clauseOperand not instance of List"); } validateInListValues((List<Object>) clauseOperand); } else { validatePredicateValue(clauseOperand, operator); } } else { throw new QueryException(String.format(Locale.ENGLISH, "%s not a valid operator", operator)); } } else { throw new QueryException("Clause must only have one key"); } }</code><technical_language>I include clause in error message easier debug problem</technical_language>

Target:
private static void validateClause(Map<String, Object> clause) throws QueryException { List<String> validOperators = Arrays.asList(EQ, LT, GT, EXISTS, NOT, GTE, LTE, IN, MOD, SIZE); if (clause.size() == 1) { String operator = (String) clause.keySet().toArray()[0]; if (validOperators.contains(operator)) { Object clauseOperand = clause.get(operator); if (operator.equals(NOT)) { if (!(clauseOperand instanceof Map)) { throw new QueryException(String.format(Locale.ENGLISH, "clauseOperand %s is not an instance of Map", clauseOperand)); } validateClause((Map) clauseOperand); } else if (operator.equals(IN)) { if (!(clauseOperand instanceof List)) { throw new QueryException(String.format(Locale.ENGLISH, "clauseOperand %s is not an instance of List", clauseOperand)); } validateInListValues((List<Object>) clauseOperand); } else { validatePredicateValue(clauseOperand, operator); } } else { throw new QueryException(String.format(Locale.ENGLISH, "operator %s is not a valid operator", operator)); } } else { throw new QueryException(String.format(Locale.ENGLISH, "Clause %s must only have one key", clause)); } }
Source:
<code>public void setLastAccessTime(long lastAccessTime, TimeUnit unit) { <START> while (true) { <END> long read = this.lastAccessTime; if (read >= lastAccessTime) { break; } if (ACCESSTIME_UPDATER.compareAndSet(this, read, unit.convert(lastAccessTime, nativeTimeUnit()))) { break; } } }</code><technical_language>a while loop a do...while loop above</technical_language>

Target:
public void setLastAccessTime(long lastAccessTime, TimeUnit unit) { long update = unit.convert(lastAccessTime, nativeTimeUnit()); while (true) { long current = this.lastAccessTime; if (current >= update) { break; } if (ACCESSTIME_UPDATER.compareAndSet(this, current, update)) { break; } }; }
Source:
<code>private void addPreferenceChangeListener() { <START> IEclipsePreferences pref = (IEclipsePreferences) Platform.getPreferencesService().getRootNode().node(InstanceScope.SCOPE).node(ResourcesPlugin.PI_RESOURCES); <END> if (pref != null) { pref.addPreferenceChangeListener(this); fileWalkerConcurrencyLevel = pref.getInt(ResourcesPlugin.PREF_NIO2_REFRESH_FILE_WALKER_CONCURRENCY_LEVEL, PreferenceInitializer.PREF_NIO2_REFRESH_FILE_WALKER_CONCURRENCY_LEVEL_DEFAULT); } else { fileWalkerConcurrencyLevel = PreferenceInitializer.PREF_NIO2_REFRESH_FILE_WALKER_CONCURRENCY_LEVEL_DEFAULT; } }</code><technical_language>Simpler get using: IPreferencesService prefs = Platform.getPreferencesService(); fileWalkerConcurrencyLevel = prefs.getInt(ResourcesPlugin.PI_RESOURCES, ResourcesPlugin.PREF_NIO2_REFRESH_FILE_WALKER_CONCURRENCY_LEVEL, PreferenceInitializer.PREF_NIO2_REFRESH_FILE_WALKER_CONCURRENCY_LEVEL_DEFAULT, null);</technical_language>

Target:
private void addPreferenceChangeListener() { IPreferencesService preferencesService = Platform.getPreferencesService(); fileWalkerConcurrencyLevel = preferencesService.getInt(ResourcesPlugin.PI_RESOURCES, ResourcesPlugin.PREF_NIO2_REFRESH_FILE_WALKER_CONCURRENCY_LEVEL, PreferenceInitializer.PREF_NIO2_REFRESH_FILE_WALKER_CONCURRENCY_LEVEL_DEFAULT, null); }
Source:
<code>private void updateFromSourceField() { if <START> (sourceNameField.getText().contentEquals(currentSourceName)) <END> { return; } setSourceName(sourceNameField.getText()); updateWidgetEnablements(); fileSystemStructureProvider.clearVisitedDirs(); selectionGroup.setFocus(); }</code><technical_language>Please equals() allows null arguments</technical_language>

Target:
private void updateFromSourceField() { String sourceNameFieldText = sourceNameField.getText(); if (sourceNameFieldText.equals(currentSourceName)) { return; } setSourceName(sourceNameFieldText); updateWidgetEnablements(); fileSystemStructureProvider.clearVisitedDirs(); selectionGroup.setFocus(); }
Source:
<code>private void broadcastCallScreeningAppChangedIntent(String componentName, boolean isDefault) { Intent intentForNewCallScreeningApp = new Intent(TelecomManager .ACTION_DEFAULT_CALL_SCREENING_APP_CHANGED); intentForNewCallScreeningApp.putExtra(TelecomManager .EXTRA_IS_DEFAULT_CALL_SCREENING_APP, isDefault); intentForNewCallScreeningApp.putExtra(TelecomManager .EXTRA_DEFAULT_CALL_SCREENING_APP_COMPONENT_NAME, componentName); <START> intentForNewCallScreeningApp.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); <END> mContext.sendBroadcast(intentForNewCallScreeningApp); }</code><technical_language>If this explicit intent need FLAG_RECEIVE_INCLUDE_BACKGROUND. wake single receiver then. intent.setPackage(componentName.getPackageName())</technical_language>

Target:
private void broadcastCallScreeningAppChangedIntent(String componentName, boolean isDefault) { if (TextUtils.isEmpty(componentName)) { return; } ComponentName broadcastComponentName = ComponentName.unflattenFromString(componentName); if (broadcastComponentName != null) { Intent intent = new Intent(TelecomManager .ACTION_DEFAULT_CALL_SCREENING_APP_CHANGED); intent.putExtra(TelecomManager .EXTRA_IS_DEFAULT_CALL_SCREENING_APP, isDefault); intent.putExtra(TelecomManager .EXTRA_DEFAULT_CALL_SCREENING_APP_COMPONENT_NAME, componentName); intent.setPackage(broadcastComponentName.getPackageName()); mContext.sendBroadcast(intent); } }
Source:
<code>private int checkMouseDownListener(Control c) { Listener[] listeners = c.getListeners(SWT.MouseDown); List<TypedListener> typedListeners = new ArrayList<TypedListener>(); <START> for (Listener l : listeners) { <END> if (l instanceof TypedListener) { TypedListener tl = (TypedListener) l; if (tl.getEventListener() .toString() .contains("org.eclipse.mylyn.internal.reviews.ui.annotations.CommentPopupDialog")) { typedListeners.add(tl); } } } assertEquals(1, typedListeners.size()); return typedListeners.size(); }</code><technical_language>avoid 'l' identifier '1'</technical_language>

Target:
private void checkMouseDownListener(Control c) { Listener[] listeners = c.getListeners(SWT.MouseDown); List<TypedListener> typedListeners = new ArrayList<TypedListener>(); for (Listener listener : listeners) { if (listener instanceof TypedListener) { TypedListener tl = (TypedListener) listener; if (tl.getEventListener() .toString() .contains("org.eclipse.mylyn.internal.reviews.ui.annotations.CommentPopupDialog")) { typedListeners.add(tl); } } } assertEquals(1, typedListeners.size()); }
Source:
<code>public void reduce(Iterator<Edge> edges, Collector<Triad> out) throws Exception { vertices.clear(); Edge firstEdge = edges.next(); outTriad.setFirstVertex(firstEdge.getFirstVertex()); <START> vertices.add((Integer)firstEdge.getSecondVertex()); <END> while(edges.hasNext()) { Integer higherVertexId = edges.next().getSecondVertex(); for(Integer lowerVertexId : vertices) { outTriad.setSecondVertex(lowerVertexId); outTriad.setThirdVertex(higherVertexId); out.collect(outTriad); } vertices.add(higherVertexId); } }</code><technical_language>do need a cast here? I Edge.getSecondVertex() returns Integer</technical_language>

Target:
public void reduce(Iterator<Edge> edges, Collector<Triad> out) throws Exception { vertices.clear(); Edge firstEdge = edges.next(); outTriad.setFirstVertex(firstEdge.getFirstVertex()); vertices.add(firstEdge.getSecondVertex()); while(edges.hasNext()) { Integer higherVertexId = edges.next().getSecondVertex(); for(Integer lowerVertexId : vertices) { outTriad.setSecondVertex(lowerVertexId); outTriad.setThirdVertex(higherVertexId); out.collect(outTriad); } vertices.add(higherVertexId); } }
Source:
<code>protected static Collection<Story[]> createStories(String[] interopTests) throws Exception { List<Story[]> result = new ArrayList<>(); for (String interopTestName : interopTests) { List<Story> stories = HpackJsonUtil.readStories(interopTestName); if (stories.isEmpty()) { <START> throw new AssumptionViolatedException("No stories for: " + interopTestName); <END> } for (Story story : stories) { result.add(new Story[] {story}); } } return result; }</code><technical_language>past-tense of this class bothers me. AssumptionViolationException</technical_language>

Target:
protected static Collection<Story[]> createStories(String[] interopTests) throws Exception { if (interopTests.length == 0) { return Collections.singletonList(new Story[] {MISSING}); } List<Story[]> result = new ArrayList<>(); for (String interopTestName : interopTests) { List<Story> stories = HpackJsonUtil.readStories(interopTestName); for (Story story : stories) { result.add(new Story[] {story}); } } return result; }
Source:
<code><START> public void dispose() { <END> fTCPBlock.dispose(); fSerialBlock.dispose(); fConnectionStack.dispose(); fConnectionField.dispose(); }</code><technical_language>This method overrides StandardGDBDebuggerPage.dispose(). super.dispose() in dispose of widgets classes added GDBServerDebuggerPage</technical_language>

Target:
public void dispose() { fTCPBlock.dispose(); fSerialBlock.dispose(); fConnectionStack.dispose(); fConnectionField.dispose(); super.dispose(); }
Source:
<code>public static void assertNotEquals(String pattern, String current){ boolean isAssertPassed = true; pattern = encodeSpecialChars(pattern); current = encodeSpecialChars(current); try { Assert.assertNotEquals(pattern, current); PageObjectLogging.log( "assertNotEquals", "assertion passed<br/>pattern: " + pattern + "<br/>current: " + current, true ); <START> } catch(AssertionError ass) { <END> isAssertPassed = false; addVerificationFailure(ass); PageObjectLogging.log( "assertNotEquals", "assertion failed<br/>pattern: " + pattern + "<br/>current: " + current, false ); } }</code><technical_language>lets call Assertion error: error instead of ass</technical_language>

Target:
public static void assertNotEquals(String pattern, String current){ boolean isAssertPassed = true; String patternEncoded = encodeSpecialChars(pattern); String currentEncoded = encodeSpecialChars(current); try { Assert.assertNotEquals(pattern, current); } catch(AssertionError err) { isAssertPassed = false; addVerificationFailure(err); PageObjectLogging.log( "assertNotEquals", "assertion failed<br/>pattern: " + patternEncoded + "<br/>current: " + currentEncoded, false ); } PageObjectLogging.log( "assertNotEquals", "assertion passed<br/>pattern: " + patternEncoded + "<br/>current: " + currentEncoded, true ); }
Source:
<code>public void shouldAttemptMethodAndFailImmedaitelyOnException_withImmediateFailureExceptionClassThrownAndRetryEnabled() throws Throwable { final RetryableAspect retryableAspect = new RetryableAspect(); final ProceedingJoinPoint mockProceedingJoinPoint = setupSimpleProceedingJoinPointMock(); <START> final int retryMaxAttempts = 3; <END> final Retryable mockRetryable = setupMockRetryable(retryMaxAttempts, 2000); RetryableConfiguration.setRetryableEnabled(true); when(mockRetryable.failImmediatelyOn()).thenReturn(new Class[] { RetryAspectTestException.class }); when(mockProceedingJoinPoint.proceed()).thenThrow(new RetryAspectTestException()); RetryAspectTestException actualException = null; try { retryableAspect.attemptMethodAndRetryIfNeeded(mockProceedingJoinPoint, mockRetryable); } catch (final RetryAspectTestException e) { actualException = e; } verify(mockProceedingJoinPoint, atMost(1)).proceed(); assertNotNull(actualException); }</code><technical_language>above, this named maxAttempts</technical_language>

Target:
public void shouldAttemptMethodAndFailImmedaitelyOnException_withImmediateFailureExceptionClassThrownAndRetryEnabled() throws Throwable { final RetryableAspect retryableAspect = new RetryableAspect(); final ProceedingJoinPoint mockProceedingJoinPoint = setupSimpleProceedingJoinPointMock(); final int maxAttempts = 3; final Retryable mockRetryable = setupMockRetryable(maxAttempts, 2000); RetryableConfiguration.setRetryableEnabled(true); when(mockRetryable.failImmediatelyOn()).thenReturn(new Class[] { RetryAspectTestException.class }); when(mockProceedingJoinPoint.proceed()).thenThrow(new RetryAspectTestException()); RetryAspectTestException actualException = null; try { retryableAspect.attemptMethodAndRetryIfNeeded(mockProceedingJoinPoint, mockRetryable); } catch (final RetryAspectTestException e) { actualException = e; } verify(mockProceedingJoinPoint, atMost(1)).proceed(); assertNotNull(actualException); }
Source:
<code>private static boolean storedInStaticFinal(MethodInvocationTree mit) { Tree tree = mit.parent(); <START> while (!tree.is(Tree.Kind.VARIABLE, Tree.Kind.CLASS, Tree.Kind.ASSIGNMENT)) { <END> tree = tree.parent(); } if (tree.is(Tree.Kind.CLASS)) { return false; } else if (tree.is(Tree.Kind.ASSIGNMENT)) { return isConstant(((AssignmentExpressionTree) tree).variable()); } VariableTree variableTree = (VariableTree) tree; return variableTree.symbol().isStatic() && variableTree.symbol().isFinal(); }</code><technical_language>stop METHOD level well. If reach a CLASS a METHOD, ASSIGNMENT a VARIABLE, stored in a static final field. Now, want group KINDs target category for consistency (CLASS METHOD failing stop conditions, ASSIGNMENT VARIABLE allows investigate further)</technical_language>

Target:
private static boolean storedInStaticFinal(MethodInvocationTree mit) { Tree tree = mit.parent(); while (!tree.is(Tree.Kind.VARIABLE, Tree.Kind.CLASS, Tree.Kind.ASSIGNMENT, Tree.Kind.METHOD)) { tree = tree.parent(); } if (tree.is(Tree.Kind.CLASS, Tree.Kind.METHOD)) { return false; } else { return isConstant(tree); } }
Source:
<code>public void testEncode() { <START> String[][] tests = new String[][]{ <END> {"Test <code>title</code>", "Test&nbsp;&#60;code&#62;title&#60;/code&#62;"}, {"ahoj", "ahoj"}, {"<>|&\"'", "&#60;&#62;|&#38;&#34;&#39;"} }; for (String[] test : tests) { assertEquals(test[1], Util.encode(test[0])); } }</code><technical_language>if/else if cases in encode() covered, e.g. '\t' is missing</technical_language>

Target:
public void testEncode() { String[][] tests = new String[][]{ {"Test <code>title</code>", "Test&nbsp;&#60;code&#62;title&#60;/code&#62;"}, {"ahoj", "ahoj"}, {"<>|&\"'", "&#60;&#62;|&#38;&#34;&#39;"}, {"tab\ttab", "tab&nbsp;&nbsp;&nbsp;&nbsp;tab"}, {"multi\nline\t\nstring", "multi&lt;br/&gt;line&nbsp;&nbsp;&nbsp;&nbsp;&lt;br/&gt;string"} }; for (String[] test : tests) { assertEquals(test[1], Util.encode(test[0])); } }
Source:
<code>public MgfFileImportMethod(File target) { this.target = target; spectra = new LinkedList<>(); patterns = new Hashtable<>(); <START> patterns.put("PEPMASS", Pattern.compile("(?<=PEPMASS=)(\\d+\\.\\d+)")); <END> patterns.put("CHARGE", Pattern.compile("(?<=CHARGE=)(\\d+)\\+|-")); patterns.put("TITLE", Pattern.compile("(?<=TITLE=).*")); }</code><technical_language>If patterns constant, static final</technical_language>

Target:
public MgfFileImportMethod(File target) { this.target = target; }
Source:
<code>public static KeyedStateBackend<Long> createKeyedStateBackend(StateBackendType backendType) throws IOException { switch (backendType) { case HEAP: rootDir = prepareDirectory(rootDirName, null); return createHeapKeyedStateBackend(rootDir); case ROCKSDB: rootDir = prepareDirectory(rootDirName, null); return createRocksDBKeyedStateBackend(rootDir); case SINGLE_KEY: try { <START> return new SingleKeyStateBackend().createKeyedStateBackend( <END> null, null, null, new LongSerializer(), 0, null, null, null, null, Collections.emptyList(), null ); } catch (Exception e) { throw new IOException(e); } default: throw new IllegalArgumentException("Unknown backend type: " + backendType); } }</code><technical_language>in a method for other backends</technical_language>

Target:
public static KeyedStateBackend<Long> createKeyedStateBackend(StateBackendType backendType) throws IOException { switch (backendType) { case HEAP: rootDir = prepareDirectory(rootDirName, null); return createHeapKeyedStateBackend(rootDir); case ROCKSDB: rootDir = prepareDirectory(rootDirName, null); return createRocksDBKeyedStateBackend(rootDir); case BATCH_EXECUTION: return createBatchExecutionStateBackend(); default: throw new IllegalArgumentException("Unknown backend type: " + backendType); } }
Source:
<code>private void validate() { if (_clusterName == null) { throw new HelixException("The cluster name/ID cannot be null."); } if (_cloudEnabled) { if (_cloudID == null || _cloudInfoURLList == null || _cloudInfoParserClassName == null || _cloudInfoURLList.isEmpty()) { throw new HelixException( <START> "This Cloud Configuration is Invalid. The configuration must have all of the fields if enabled."); <END> } } }</code><technical_language>This confusing here. user fields</technical_language>

Target:
private void validate() { if (_cloudEnabled) { if (_cloudID == null) { throw new HelixException( "This Cloud Configuration is Invalid. The CloudID is missing from the config."); } if (_cloudProvider == null) { throw new HelixException( "This Cloud Configuration is Invalid. The Cloud Provider is missing from the config."); } else if (_cloudProvider == CloudProvider.CUSTOMIZED) { if (_cloudInfoProcessorName == null || _cloudInfoSources == null || _cloudInfoSources.size() == 0) { throw new HelixException( "This Cloud Configuration is Invalid. CUSTOMIZED provider has been chosen without defining CloudInfoProcessorName or CloudInfoSources"); } } } }
Source:
<code>public void startModule_shouldCreateDwrModulesXmlIfNotExists() throws ParserConfigurationException { Module mod = buildModuleForMessageTest(); ModuleFactory.getStartedModulesMap().put(mod.getModuleId(), mod); ServletContext servletContext = mock(ServletContext.class); String realPath = servletContext.getRealPath(""); if (realPath == null) realPath = System.getProperty("user.dir"); <START> File f = new File(realPath, "/WEB-INF/dwr-modules.xml"); <END> f.delete(); WebModuleUtil.startModule(mod, servletContext, true); assertTrue(f.exists()); ModuleFactory.getStartedModulesMap().clear(); }</code><technical_language>need get rid of slashes</technical_language>

Target:
public void startModule_shouldCreateDwrModulesXmlIfNotExists() throws ParserConfigurationException { Module mod = buildModuleForMessageTest(); ModuleFactory.getStartedModulesMap().put(mod.getModuleId(), mod); ServletContext servletContext = mock(ServletContext.class); String realPath = servletContext.getRealPath(""); if (realPath == null) realPath = System.getProperty("user.dir"); File f = new File(Paths.get(realPath, "WEB-INF", "dwr-modules.xml").toString()); f.delete(); WebModuleUtil.startModule(mod, servletContext, true); assertTrue(f.exists()); ModuleFactory.getStartedModulesMap().clear(); }
Source:
<code>protected boolean validateBackupDomainNotFirstInPool() { <START> if (getStoragePool() != null) { if (getStoragePool().getStatus() == StoragePoolStatus.Uninitialized && getStorageDomain().isBackup()) <END> { return failValidation(EngineMessage.ACTION_TYPE_FAILED_FIRST_DOMAIN_CANNOT_BE_BACKUP); } } return true; }</code><technical_language>Please if condition: if (getStoragePool() != null && getStoragePool().getStatus() == StoragePoolStatus.Uninitialized && getStorageDomain().isBackup())</technical_language>

Target:
protected boolean validateBackupDomainNotFirstInPool() { if (getStoragePool() != null && getStoragePool().getStatus() == StoragePoolStatus.Uninitialized && getStorageDomain().isBackup()) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_FIRST_DOMAIN_CANNOT_BE_BACKUP); } return true; }
Source:
<code>public void verifyUnclickable(WebElement element) { try { assertTrue(element.getAttribute("class").contains("disabled")); } catch (AssertionError e) { assertNotNull(element.getAttribute("disabled")); <START> } <END> }</code><technical_language>This logic better: if element is anchor, check for class, else check for attribute</technical_language>

Target:
public void verifyUnclickable(WebElement element) { if (element.getTagName().equals("a")) { assertTrue(element.getAttribute("class").contains("disabled")); } else { assertNotNull(element.getAttribute("disabled")); } }
Source:
<code>private Cache<K, V> getBaseCache() { Cache<K, V> cache = null; try { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext .getThreadLocalCarbonContext(); carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID); carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); CacheManager cacheManager = Caching.getCacheManagerFactory() .getCacheManager(CACHE_MANAGER_NAME); if (cacheTimeout > 0 && cacheBuilder == null) { synchronized (cacheName.intern()) { if (cacheBuilder == null) { cacheManager.removeCache(cacheName); cacheBuilder = cacheManager.<K, V>createCacheBuilder(cacheName). setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration .Duration(TimeUnit.SECONDS, cacheTimeout)). setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration .Duration(TimeUnit.SECONDS, cacheTimeout)). setStoreByValue(false); cache = cacheBuilder.build(); <START> if(cacheListeners != null) { <END> for (AbstractCacheListener cacheListener : cacheListeners) { this.cacheBuilder.registerCacheEntryListener(cacheListener); } } if (capacity != 0) { ((CacheImpl) cache).setCapacity(capacity); } } else { cache = cacheManager.getCache(cacheName); } } } else { cache = cacheManager.getCache(cacheName); } } finally { PrivilegedCarbonContext.endTenantFlow(); } return cache; }</code><technical_language>need check null if initialized empty list</technical_language>

Target:
private Cache<K, V> getBaseCache() { Cache<K, V> cache = null; try { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext .getThreadLocalCarbonContext(); carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID); carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); CacheManager cacheManager = Caching.getCacheManagerFactory() .getCacheManager(CACHE_MANAGER_NAME); if (cacheTimeout > 0 && cacheBuilder == null) { synchronized (cacheName.intern()) { if (cacheBuilder == null) { cacheManager.removeCache(cacheName); cacheBuilder = cacheManager.<K, V>createCacheBuilder(cacheName). setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration .Duration(TimeUnit.SECONDS, cacheTimeout)). setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration .Duration(TimeUnit.SECONDS, cacheTimeout)). setStoreByValue(false); cache = cacheBuilder.build(); for (AbstractCacheListener cacheListener : cacheListeners) { this.cacheBuilder.registerCacheEntryListener(cacheListener); } if (capacity != 0) { ((CacheImpl) cache).setCapacity(capacity); } } else { cache = cacheManager.getCache(cacheName); } } } else { cache = cacheManager.getCache(cacheName); } } finally { PrivilegedCarbonContext.endTenantFlow(); } return cache; }