auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private boolean canStorageSystemCreateVolumeFromVolume(SnapshotInfo snapshotInfo) { boolean supportsCloningVolumeFromVolume = false; DataStore dataStore = _dataStoreMgr.getDataStore(snapshotInfo.getDataStore().getId(), DataStoreRole.Primary); Map<String, String> mapCapabilities = dataStore.getDriver().getCapabilities(); if (mapCapabilities != null) { String value = mapCapabilities.get(DataStoreCapabilities.CAN_CREATE_VOLUME_FROM_VOLUME.toString()); <START> supportsCloningVolumeFromVolume = new Boolean(value); <END> } return supportsCloningVolumeFromVolume; }</code><technical_language>new Boolean avoid constant pool -- putting unnecessary pressure garbage collector. Please Boolean.valueOf instead</technical_language>

Target:
private boolean canStorageSystemCreateVolumeFromVolume(SnapshotInfo snapshotInfo) { boolean supportsCloningVolumeFromVolume = false; DataStore dataStore = dataStoreMgr.getDataStore(snapshotInfo.getDataStore().getId(), DataStoreRole.Primary); Map<String, String> mapCapabilities = dataStore.getDriver().getCapabilities(); if (mapCapabilities != null) { String value = mapCapabilities.get(DataStoreCapabilities.CAN_CREATE_VOLUME_FROM_VOLUME.toString()); supportsCloningVolumeFromVolume = Boolean.valueOf(value); } return supportsCloningVolumeFromVolume; }
Source:
<code>synchronized void stopVirtual() { userCounter--; if ( userCounter == 0 ) { if ( status != ServiceStatus.RUNNING ) { stateExpectedFailure(); } <START> stopReal(); <END> } else if ( status != ServiceStatus.RUNNING ) { stateExpectedFailure(); } }</code><technical_language>If I understand correctly, this commit wrappers remain in cache stopped. I suppose is purpose</technical_language>

Target:
synchronized void stopVirtual() { userCounter--; if ( userCounter == 0 ) { stopReal(); } }
Source:
<code>protected File createTempDirectory(String name) throws IOException { String gitdirName = createUniqueTestFolderPrefix(); File parent = new File(trash, gitdirName); <START> File directory = new File(parent, name); <END> return directory.getCanonicalFile(); }</code><technical_language>other previous implementation in subclasses this create directory anymore</technical_language>

Target:
protected File createTempDirectory(String name) throws IOException { String gitdirName = createUniqueTestFolderPrefix(); File parent = new File(trash, gitdirName); File directory = new File(parent, name); FileUtils.mkdirs(directory); return directory.getCanonicalFile(); }
Source:
<code>private Path retrieveFinalTargetDirectory() throws IOException { Path unpackDirectory = carbonHomeDirectoryOption.getUnpackDirectory(); if (unpackDirectory == null) { unpackDirectory = Paths.get("target", UUID.randomUUID().toString()); } <START> boolean isCreated = true; <END> if (!unpackDirectory.toFile().exists()) { isCreated = unpackDirectory.toFile().mkdir(); } if (!isCreated) { throw new TestContainerException("Couldn't create the directory: " + unpackDirectory.toFile().toString()); } return unpackDirectory; }</code><technical_language>Try initialize variables well-known defaults build logic default for boolean is false</technical_language>

Target:
private Path retrieveFinalTargetDirectory() throws IOException { Path unpackDirectory = carbonHomeDirectoryOption.getUnpackDirectory(); if (unpackDirectory == null) { unpackDirectory = Paths.get("target", UUID.randomUUID().toString()); } boolean isCreated = unpackDirectory.toFile().exists() || unpackDirectory.toFile().mkdir(); if (!isCreated) { throw new TestContainerException("Couldn't create the directory: " + unpackDirectory.toFile().toString()); } return unpackDirectory; }
Source:
<code>public void updated(Dictionary<String, ?> config) throws ConfigurationException { if (config != null) { String refreshIntervalString = (String) config.get("refresh"); if (StringUtils.isNotBlank(refreshIntervalString)) { refreshInterval = Long.parseLong(refreshIntervalString); } for (Enumeration<?> e = config.keys(); e.hasMoreElements();) { String tv = (String) e.nextElement(); if (tv.equalsIgnoreCase("service.pid") || tv.equalsIgnoreCase("refresh")) continue; logger.info("TV registered '" + tv + "' with IP '" + config.get(tv) + "'"); registeredTVs.put(tv, config.get(tv).toString()); } if (registeredTVs.isEmpty()) { <START> setProperlyConfigured(true); <END> logger.debug("No TV was registered in config file"); } else setProperlyConfigured(true); } }</code><technical_language>"false" here. "false" is default handle positive branch of this if</technical_language>

Target:
public void updated(Dictionary<String, ?> config) throws ConfigurationException { if (config != null) { String refreshIntervalString = (String) config.get("refresh"); if (StringUtils.isNotBlank(refreshIntervalString)) { refreshInterval = Long.parseLong(refreshIntervalString); } for (Enumeration<?> e = config.keys(); e.hasMoreElements();) { String tv = (String) e.nextElement(); if (tv.equalsIgnoreCase("service.pid") || tv.equalsIgnoreCase("refresh")) continue; logger.info("TV registered '" + tv + "' with IP '" + config.get(tv) + "'"); registeredTVs.put(tv, config.get(tv).toString()); } if (registeredTVs.isEmpty()) { logger.debug("No TV was registered in config file"); } } }
Source:
<code>public GenericContainer(@NonNull final Future<String> image) { <START> this.nameResolverProvider = new ImageNameResolverProvider(image); <END> }</code><technical_language>please create another constructor accepting nameResolverProvider</technical_language>

Target:
public GenericContainer(@NonNull final Future<String> image) { this(new ImageNameResolverProvider(image)); }
Source:
<code>public List<String> getLines() throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); List<String> lines = new ArrayList<String>(); <START> String line; <END> while ((line = reader.readLine()) != null) { lines.add(line); } return lines; }</code><technical_language>remove explicit initialization</technical_language>

Target:
public List<String> getLines() throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); List<String> lines = new ArrayList<String>(); String line = null; while ((line = reader.readLine()) != null) { lines.add(line); } return lines; }
Source:
<code>public void findByCandidateEntityShouldFindAMaximumNumberOfApplicationsGivenInThePageRequest() throws ParseException { CandidateEntity candidateEntityC = this.candidateRepository.findOne(CANDIDATE_C_ID); ChannelEntity expectedChannelEntity = ChannelEntity.builder() .id(2L) .name("profession hírdetés") .build(); ChannelEntity expectedSecondChannelEntity = ChannelEntity.builder() .id(3L) .name("profession adatbázis") .build(); PositionEntity expectedPositionEntity = PositionEntity.builder() .id(1L) .name("Fejlesztő") .build(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); <START> Date expectedDate = simpleDateFormat.parse("2016-07-26 11:48:55"); <END> Page<ApplicationEntity> pageResult = this.repository.findByCandidateEntity(candidateEntityC, PAGE_REQUEST_ZERO_TWO); List<ApplicationEntity> result = pageResult.getContent(); assertThat(result, notNullValue()); assertThat(result.size(), is(2)); assertApplicationEntity(result.get(0), candidateEntityC, expectedChannelEntity, expectedPositionEntity, expectedDate); assertApplicationEntity(result.get(1), candidateEntityC, expectedSecondChannelEntity, expectedPositionEntity, expectedDate); }</code><technical_language>please refactor string literal constant in this test class</technical_language>

Target:
public void findByCandidateEntityShouldFindAMaximumNumberOfApplicationsGivenInThePageRequest() throws ParseException { CandidateEntity candidateEntityC = this.candidateRepository.findOne(CANDIDATE_C_ID); ChannelEntity expectedChannelEntity = ChannelEntity.builder() .id(2L) .name(CHANNEL_NAME_PROFESSION_ADVERTISEMENT) .deleted(false) .build(); ChannelEntity expectedSecondChannelEntity = ChannelEntity.builder() .id(3L) .name(CHANNEL_NAME_PROFESSION_DATABASE) .deleted(false) .build(); PositionEntity expectedPositionEntity = PositionEntity.builder() .id(1L) .name(POSITION_NAME_DEVELOPER) .deleted(false) .build(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_FORMAT_PATTERN); Date expectedDate = simpleDateFormat.parse(DATE_SAMPLE); Page<ApplicationEntity> pageResult = this.repository.findByCandidateEntity(candidateEntityC, ZERO_TWO_PAGE_REQUEST); List<ApplicationEntity> result = pageResult.getContent(); assertThat(pageResult.getTotalPages(), is(2)); assertThat(pageResult.getTotalElements(), is(3L)); assertThat(result, notNullValue()); assertThat(result.size(), is(2)); assertApplicationEntity(result.get(0), candidateEntityC, expectedChannelEntity, expectedPositionEntity, expectedDate); assertApplicationEntity(result.get(1), candidateEntityC, expectedSecondChannelEntity, expectedPositionEntity, expectedDate); }
Source:
<code>public void testGetJobs() throws Exception { <START> String jobId = UUID.randomUUID().toString(); createJob(jobId); <END> JobsGet.getJobs(PROJECT_ID, "i-" + jobId); String output = bout.toString(); assertThat(output, CoreMatchers.containsString("Job got successfully.")); }</code><technical_language>Great - this deleted some point tests run times / day</technical_language>

Target:
public void testGetJobs() throws Exception { String jobId = UUID.randomUUID().toString(); DlpJob createdDlpJob = createJob(jobId); JobsGet.getJobs(PROJECT_ID, "i-" + jobId); String output = bout.toString(); assertThat(output, CoreMatchers.containsString("Job got successfully.")); String dlpJobName = createdDlpJob.getName(); DeleteDlpJobRequest deleteDlpJobRequest = DeleteDlpJobRequest.newBuilder().setName(dlpJobName).build(); try (DlpServiceClient client = DlpServiceClient.create()) { client.deleteDlpJob(deleteDlpJobRequest); } }
Source:
<code>public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { filterChain.doFilter(servletRequest, servletResponse); HttpServletRequest request = (HttpServletRequest) servletRequest; String tmpFolder = request.getParameter("path"); File file = new File(tmpFolder + "/output.txt"); file.createNewFile(); try(FileWriter fw = new FileWriter(file)) { fw.write("servletPath: " + request.getServletPath()); fw.write("\nrequestUrl: " + request.getRequestURL().toString()); } <START> } <END></code><technical_language>I noticed this change affects getRequestURI method. is mentioned in analysis. extend test coverage for this method too</technical_language>

Target:
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { filterChain.doFilter(servletRequest, servletResponse); HttpServletRequest request = (HttpServletRequest) servletRequest; String tmpFolder = request.getParameter("path"); File file = new File(tmpFolder + "/output.txt"); file.createNewFile(); try( BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file))) { String text = "servletPath: " + request.getServletPath() + "\nrequestUrl: " + request.getRequestURL().toString() + "\nrequestUri: " + request.getRequestURI(); bufferedWriter.write(text); } }
Source:
<code>public void afterPropertiesSet() throws Exception { <START> Hooks.onLastOperator(REQUEST_CONTEXT_OPERATOR_KEY, Operators.lift((s, sub) -> createRequestContextSubscriber(sub))); <END> }</code><technical_language>Operators.liftPublisher() create unnecessary transformations Scannable of a publisher</technical_language>

Target:
public void afterPropertiesSet() throws Exception { Hooks.onLastOperator(REQUEST_CONTEXT_OPERATOR_KEY, Operators.liftPublisher((s, sub) -> createRequestContextSubscriber(sub))); }
Source:
<code>public int onStartCommand(Intent intent, int flags, int startId) { mLocalBlogId = intent.getIntExtra(ARG_LOCAL_BLOG_ID, 0); <START> downloadGlobalPlans(); <END> return START_NOT_STICKY; }</code><technical_language>Features Globals Plans strictly tied together. download in parallel, need serialize them. I a more aggressive download policy here, enqueue Features downloading instead line 91</technical_language>

Target:
public int onStartCommand(Intent intent, int flags, int startId) { mLocalBlogId = intent.getIntExtra(ARG_LOCAL_BLOG_ID, 0); mNumActiveRequests = 3; downloadGlobalPlans(); downloadPlanFeatures(); downloadAvailablePlansForSite(); return START_NOT_STICKY; }
Source:
<code>private static int findNumberOfFirstMonthDaysOnSunday(int startYear, int endYear) { <START> return List.range(startYear, endYear + 1). <END> map( y -> List.range(1, 13).filter(m -> isFirstDayOfMonthSunday(y, m)).length() ).sum().intValue(); }</code><technical_language>@ashrko619 For(List.range(startYear, endYear + 1), List.range(1, 13))? :)</technical_language>

Target:
private static int findNumberOfFirstMonthDaysOnSunday(int startYear, int endYear) { return For(List.rangeClosed(startYear, endYear), List.of(Month.values())) .yield(Tuple::of) .filter(t -> isFirstDayOfMonthSunday(t._1, t._2)) .length(); }
Source:
<code>private int percentageSync() { int chainHeadHeight = blockChain.getChainHead().getHeight(); int mostCommonChainHeight; <START> if (peerGroup.getMostCommonChainHeight() > 0) { <END> mostCommonChainHeight = peerGroup.getMostCommonChainHeight(); } else { mostCommonChainHeight = chainHeadHeight; } float percentage = ((float) chainHeadHeight / (float) mostCommonChainHeight) * 100; log.info("mostCommonChainHeight: " + mostCommonChainHeight + "\tchainHeadHeight: " + chainHeadHeight + "\t" + percentage + "%\t" + config.getBestChainHeightEver()); return (int) percentage; }</code><technical_language>This generate a NullPointerException if peerGroup is null</technical_language>

Target:
private int percentageSync() { int chainHeadHeight = blockChain.getChainHead().getHeight(); int mostCommonChainHeight; if (peerGroup == null) { return 0; } if (peerGroup.getMostCommonChainHeight() > 0) { mostCommonChainHeight = peerGroup.getMostCommonChainHeight(); } else { mostCommonChainHeight = chainHeadHeight; } float percentage = ((float) chainHeadHeight / (float) mostCommonChainHeight) * 100; log.info("mostCommonChainHeight: " + mostCommonChainHeight + "\tchainHeadHeight: " + chainHeadHeight + "\t" + percentage + "%\t" + config.getBestChainHeightEver()); return (int) percentage; }
Source:
<code><START> private static File getFileFromClassLoaderBeforeLuna(String filename, ClassLoader classLoader) throws IOException { <END> try { Method getClasspathManager = classLoader.getClass().getMethod("getClasspathManager"); if (getClasspathManager != null) { Object classpathManager = getClasspathManager.invoke(classLoader); if (classpathManager != null && classpathManager.getClass() .getName() .equals("org.eclipse.osgi.baseadaptor.loader.ClasspathManager")) { Method getBaseData = classpathManager.getClass().getMethod("getBaseData"); if (getBaseData != null) { Object baseData = getBaseData.invoke(classpathManager, null); if (baseData != null && baseData.getClass().getName().equals("org.eclipse.osgi.baseadaptor.BaseData")) { Method getBundle = baseData.getClass().getMethod("getBundle"); if (getBundle != null) { Object bundle = getBundle.invoke(baseData, null); if (bundle != null && bundle.getClass() .getName() .equals("org.eclipse.osgi.framework.internal.core.BundleHost")) { Method getEntry = bundle.getClass().getMethod("getEntry", String.class); if (getEntry != null) { Object entry = getEntry.invoke(bundle, filename); if (entry != null && entry.getClass().getName().equals("java.net.URL")) { if (entry != null) { URL localURL = FileLocator.toFileURL((URL) entry); return new File(localURL.getFile()); } } } } } } } } } } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } throw new AssertionFailedError("no file found " + filename); }</code><technical_language>easier follow if leveraged utils org.apache.commons.lang.reflect. fit perfectly :)</technical_language>

Target:
private static File getFileFromClassLoaderBeforeLuna(String filename, ClassLoader classLoader) throws IOException { try { Object classpathManager = MethodUtils.invokeExactMethod(classLoader, "getClasspathManager", null); if (classpathManager != null) { Object baseData = MethodUtils.invokeExactMethod(classpathManager, "getBaseData", null); if (baseData != null) { Object bundle = MethodUtils.invokeExactMethod(baseData, "getBundle", null); if (bundle != null) { Object entry = MethodUtils.invokeExactMethod(bundle, "getEntry", String.class); if (entry != null) { URL localURL = FileLocator.toFileURL((URL) entry); return new File(localURL.getFile()); } } } } } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } throw new AssertionFailedError("no file found " + filename); }
Source:
<code>private void rescheduleUnknownWorkflowType(WorkflowInstance instance) { logger.warn("Workflow type not configured to this nFlow instance - rescheduling workflow instance", instance.type); instance = new WorkflowInstance.Builder(instance).setNextActivation(now().plusMinutes(unknownWorkflowTypeRetryDelay)) .setStatus(inProgress).setStateText("Unsupported workflow type").build(); <START> workflowInstanceDao.updateWorkflowInstance(instance, null); <END> logger.debug("Finished."); }</code><technical_language>null clear current start time db</technical_language>

Target:
private void rescheduleUnknownWorkflowType(WorkflowInstance instance) { logger.warn("Workflow type not configured to this nFlow instance - rescheduling workflow instance", instance.type); instance = new WorkflowInstance.Builder(instance).setNextActivation(now().plusMinutes(unknownWorkflowTypeRetryDelay)) .setStatus(inProgress).setStateText("Unsupported workflow type").build(); workflowInstanceDao.updateWorkflowInstance(instance); logger.debug("Finished."); }
Source:
<code>public void write(CorfuPayloadMsg<WriteRequest> msg, ChannelHandlerContext ctx, IServerRouter r) { LogData logData = (LogData) msg.getPayload().getData(); log.debug("log write: type: {}, address: {}, streams: {}", logData.getType(), logData.getToken(), logData.getBackpointerMap()); if (logData.isHole()) { msg.setPriorityLevel(PriorityLevel.HIGH); } batchWriter.addTask(WRITE, msg) .thenRunAsync(() -> { <START> logData.serializeMetadata(); <END> dataCache.put(msg.getPayload().getGlobalAddress(), logData); r.sendResponse(ctx, msg, CorfuMsgType.WRITE_OK.msg()); }, executor).exceptionally(ex -> { handleException(ex, ctx, msg, r); return null; }); }</code><technical_language>This in cache put function. is a bug</technical_language>

Target:
public void write(CorfuPayloadMsg<WriteRequest> msg, ChannelHandlerContext ctx, IServerRouter r) { LogData logData = (LogData) msg.getPayload().getData(); log.debug("log write: type: {}, address: {}, streams: {}", logData.getType(), logData.getToken(), logData.getBackpointerMap()); if (logData.isHole()) { msg.setPriorityLevel(PriorityLevel.HIGH); } batchWriter.addTask(WRITE, msg) .thenRunAsync(() -> { dataCache.put(msg.getPayload().getGlobalAddress(), logData); r.sendResponse(ctx, msg, CorfuMsgType.WRITE_OK.msg()); }, executor).exceptionally(ex -> { handleException(ex, ctx, msg, r); return null; }); }
Source:
<code>public static FeignClientFactory withMapper(ObjectMapper mapper) { return FeignClientFactory.of( new JAXRSContract(), new JacksonEncoder(mapper), <START> new OptionalAwareDecoder(new TextDelegateDecoder(new JacksonDecoder(mapper)), <END> SerializableErrorErrorDecoder.INSTANCE), SerializableErrorErrorDecoder.INSTANCE, FeignClientFactory.okHttpClient()); }</code><technical_language>is order correct</technical_language>

Target:
public static FeignClientFactory withMapper(ObjectMapper mapper) { return FeignClientFactory.of( new JAXRSContract(), new JacksonEncoder(mapper), new OptionalAwareDecoder(new TextDelegateDecoder(new JacksonDecoder(mapper))), SerializableErrorErrorDecoder.INSTANCE, FeignClientFactory.okHttpClient()); }
Source:
<code>public synchronized String rewrite(Configuration conf, String query) throws GrillException { this.query = query; this.conf = conf; StringBuilder mergedQuery = new StringBuilder(); rewrittenQuery.setLength(0); String queryReplacedUdf = ""; reset(); try { if (query.toLowerCase().matches("(.*)union all(.*)")) { String finalRewrittenQuery = ""; String[] queries = query.toLowerCase().split("union all"); for (int i = 0; i < queries.length; i++) { LOG.info("Union Query Part " + i + " : " + queries[i]); ast = HQLParser.parseHQL(queries[i]); buildQuery(); mergedQuery = rewrittenQuery.append(" union all "); finalRewrittenQuery = mergedQuery.toString().substring(0, mergedQuery.lastIndexOf("union all")); reset(); } queryReplacedUdf = replaceUDFForDB(finalRewrittenQuery); LOG.info("Input Query : " + query); LOG.info("Rewritten Query : " + queryReplacedUdf); } else { ast = HQLParser.parseHQL(query); buildQuery(); queryReplacedUdf = replaceUDFForDB(rewrittenQuery.toString()); LOG.info("Input Query : " + query); LOG.info("Rewritten Query : " + queryReplacedUdf); } } catch (ParseException e) { e.printStackTrace(); <START> } catch (SemanticException e) { <END> e.printStackTrace(); } return queryReplacedUdf; }</code><technical_language>thrown up. catching anywhere. If signature expects GrillException, catch throw this</technical_language>

Target:
public synchronized String rewrite(Configuration conf, String query) throws GrillException { this.query = query; this.conf = conf; StringBuilder mergedQuery = new StringBuilder(); rewrittenQuery.setLength(0); String queryReplacedUdf = ""; reset(); try { if (query.toLowerCase().matches("(.*)union all(.*)")) { String finalRewrittenQuery = ""; String[] queries = query.toLowerCase().split("union all"); for (int i = 0; i < queries.length; i++) { LOG.info("Union Query Part " + i + " : " + queries[i]); ast = HQLParser.parseHQL(queries[i]); buildQuery(); mergedQuery = rewrittenQuery.append(" union all "); finalRewrittenQuery = mergedQuery.toString().substring(0, mergedQuery.lastIndexOf("union all")); reset(); } queryReplacedUdf = replaceUDFForDB(finalRewrittenQuery); LOG.info("Input Query : " + query); LOG.info("Rewritten Query : " + queryReplacedUdf); } else { ast = HQLParser.parseHQL(query); buildQuery(); queryReplacedUdf = replaceUDFForDB(rewrittenQuery.toString()); LOG.info("Input Query : " + query); LOG.info("Rewritten Query : " + queryReplacedUdf); } } catch (ParseException e) { throw new GrillException(e); } catch (SemanticException e) { throw new GrillException(e); } catch (HiveException e) { throw new GrillException(e); } return queryReplacedUdf; }
Source:
<code>public void physicallyDeleteSurveyNotEmptySharedModules() { when(mockSharedModuleMetadataService.queryAllMetadata(anyBoolean(), anyBoolean(), anyString(), any(), any(), anyBoolean())).thenReturn(ImmutableList.of(makeValidMetadata())); Survey survey = createSurvey(); when(mockSurveyDao.getSurvey(any(), eq(false))).thenReturn(survey); <START> <END> service.deleteSurveyPermanently(TEST_STUDY, survey); }</code><technical_language>fix this for other tests well? * physicallyDeleteSurveyNotEmptySharedModules() * deleteSurveyPermanentlyNotConstrainedByScheduleWithMultiplePublishedSurveys() * deleteSurveyPermanentlyNotConstrainedByCompoundScheduleWithMultiplePublishedSurveys()</technical_language>

Target:
public void physicallyDeleteSurveyNotEmptySharedModules() { when(mockSharedModuleMetadataService.queryAllMetadata(anyBoolean(), anyBoolean(), anyString(), any(), any(), anyBoolean())).thenReturn(ImmutableList.of(makeValidMetadata())); Survey survey = createSurvey(); when(mockSurveyDao.getSurvey(any(), eq(false))).thenReturn(survey); when(mockSchedulePlanService.getSchedulePlans(ClientInfo.UNKNOWN_CLIENT, TEST_STUDY, true)) .thenReturn(ImmutableList.of()); service.deleteSurveyPermanently(TEST_STUDY, survey); }
Source:
<code>public void registerProbe(ProbeDescriptor descriptor) { Class<? extends Probe> probeClass = descriptor.getProbeClass(); Probe probe; try { probe = probeClass.newInstance(); } catch (ReflectiveOperationException e) { throw new ManagementRuntimeException("Cannot create management probe for " + descriptor); } ProbeInfoImpl info = new ProbeInfoImpl(descriptor); infosByTypes.put(probeClass, info); infosByShortcuts.put(descriptor.getShortcut(), info); probesByShortcuts.put(descriptor.getShortcut(), probe); if (probesForHealthCheck.containsKey(descriptor.getShortcut())) { probesForHealthCheck.put(descriptor.getShortcut(), info); <START> } <END> }</code><technical_language>logic wrong here. Do !probesForHealthCheck.containsKey</technical_language>

Target:
public void registerProbe(ProbeDescriptor descriptor) { Class<? extends Probe> probeClass = descriptor.getProbeClass(); Probe probe; try { probe = probeClass.newInstance(); } catch (ReflectiveOperationException e) { throw new ManagementRuntimeException("Cannot create management probe for " + descriptor); } ProbeInfoImpl info = new ProbeInfoImpl(descriptor); infosByTypes.put(probeClass, info); infosByShortcuts.put(descriptor.getShortcut(), info); probesByShortcuts.put(descriptor.getShortcut(), probe); }
Source:
<code>public String add(Network network) { NetworkForCreate networkForCreate = new NetworkForCreate(); networkForCreate.setAdminStateUp(true); networkForCreate.setName(network.getName()); if (network.getLabel() != null) { networkForCreate.setProviderPhysicalNetwork(network.getLabel()); if (network.getVlanId() == null) { <START> networkForCreate.setProviderNetworkType("flat"); <END> } else { networkForCreate.setProviderNetworkType("vlan"); networkForCreate.setProviderSegmentationId(network.getVlanId()); } } try { org.openstack.quantum.model.Network createdNetwork = getQuantumClient().execute(new CreateNetwork(networkForCreate)); return createdNetwork.getId(); } catch (RuntimeException e) { throw new VdcBLLException(VdcBllErrors.PROVIDER_FAILURE, new RuntimeException(e)); } }</code><technical_language>worth a global constants file for advanced networking provider</technical_language>

Target:
public String add(Network network) { NetworkForCreate networkForCreate = new NetworkForCreate(); networkForCreate.setAdminStateUp(true); networkForCreate.setName(network.getName()); if (network.getLabel() != null) { networkForCreate.setProviderPhysicalNetwork(network.getLabel()); if (network.getVlanId() == null) { networkForCreate.setProviderNetworkType("flat"); } else { networkForCreate.setProviderNetworkType("vlan"); networkForCreate.setProviderSegmentationId(network.getVlanId()); } } try { org.openstack.quantum.model.Network createdNetwork = getQuantumClient().networks().create(networkForCreate).execute(); return createdNetwork.getId(); } catch (RuntimeException e) { throw new VdcBLLException(VdcBllErrors.PROVIDER_FAILURE, new RuntimeException(e)); } }
Source:
<code><START> public static TextSelection getSelection(IEditorPart editorPart) { <END> Objects.requireNonNull(editorPart, "The given editor part must not be null"); if (!(editorPart instanceof ITextEditor)) { return TextSelection.EMPTY_SELECTION; } ITextEditor textEditor = (ITextEditor) editorPart; ISelectionProvider selectionProvider = textEditor.getSelectionProvider(); if (selectionProvider == null) { return TextSelection.EMPTY_SELECTION; } IDocument document = textEditor.getDocumentProvider().getDocument(editorPart.getEditorInput()); ITextSelection textSelection = (ITextSelection) selectionProvider.getSelection(); int offset = textSelection.getOffset(); int length = textSelection.getLength(); return calculateSelection(document, offset, length); }</code><technical_language>[ITextSelection](<LINK_0> provides methods getStartLine is this another context</technical_language>

Target:
public static TextSelection getSelection(IEditorPart editorPart) { if (!(editorPart instanceof ITextEditor)) { return TextSelection.EMPTY_SELECTION; } ITextEditor textEditor = (ITextEditor) editorPart; ISelectionProvider selectionProvider = textEditor.getSelectionProvider(); if (selectionProvider == null) { return TextSelection.EMPTY_SELECTION; } IDocumentProvider documentProvider = textEditor.getDocumentProvider(); if (documentProvider == null) { return TextSelection.EMPTY_SELECTION; } IDocument document = documentProvider.getDocument(editorPart.getEditorInput()); if (document == null) { return TextSelection.EMPTY_SELECTION; } ITextSelection textSelection = (ITextSelection) selectionProvider.getSelection(); int offset = textSelection.getOffset(); int length = textSelection.getLength(); return calculateSelection(document, offset, length); }
Source:
<code>public static void SetNetworkStatus(Guid vdsGroupId, final Network net) { NetworkStatus status = NetworkStatus.Operational; VDSGroup vdsGroup = DbFacade.getInstance().getVdsGroupDAO().get(vdsGroupId); network_cluster networkCluster = net.getCluster(); <START> if (networkCluster == null) { <END> networkCluster = DbFacade.getInstance().getNetworkClusterDAO().get(new NetworkClusterId(vdsGroupId, net.getId())); } SearchParameters searchParams = new SearchParameters("hosts: cluster = " + vdsGroup.getname(), SearchType.VDS); searchParams.setMaxCount(Integer.MAX_VALUE); List<VDS> vdsList = (List) Backend.getInstance() .runInternalQuery(VdcQueryType.Search, searchParams).getReturnValue(); if (networkCluster.isRequired()) { for (VDS vds : vdsList) { if (vds.getstatus() != VDSStatus.Up) { continue; } List<VdsNetworkInterface> interfaces = (List<VdsNetworkInterface>) Backend .getInstance() .runInternalQuery(VdcQueryType.GetVdsInterfacesByVdsId, new GetVdsByVdsIdParameters(vds.getId())).getReturnValue(); VdsNetworkInterface iface = LinqUtils.firstOrNull(interfaces, new Predicate<VdsNetworkInterface>() { @Override public boolean eval(VdsNetworkInterface i) { return StringHelper.EqOp(i.getNetworkName(), net.getname()); } }); if (iface == null) { status = NetworkStatus.NonOperational; break; } } } List<network_cluster> all = DbFacade.getInstance() .getNetworkClusterDAO().getAllForCluster(vdsGroupId); for (network_cluster nc : all) { if (net.getId().equals(nc.getnetwork_id())) { nc.setstatus(status.getValue()); DbFacade.getInstance().getNetworkClusterDAO().updateStatus(nc); break; } } }</code><technical_language>please verify networkCluster null</technical_language>

Target:
public static void SetNetworkStatus(Guid vdsGroupId, final Network net) { NetworkStatus status = NetworkStatus.Operational; network_cluster networkCluster = DbFacade.getInstance().getNetworkClusterDAO().get(new NetworkClusterId(vdsGroupId, net.getId())); if (networkCluster != null) { VDSGroup vdsGroup = DbFacade.getInstance().getVdsGroupDAO().get(vdsGroupId); SearchParameters searchParams = new SearchParameters("hosts: cluster = " + vdsGroup.getname(), SearchType.VDS); searchParams.setMaxCount(Integer.MAX_VALUE); List<VDS> vdsList = (List) Backend.getInstance() .runInternalQuery(VdcQueryType.Search, searchParams).getReturnValue(); if (networkCluster.isRequired()) { for (VDS vds : vdsList) { if (vds.getstatus() != VDSStatus.Up) { continue; } List<VdsNetworkInterface> interfaces = (List<VdsNetworkInterface>) Backend .getInstance() .runInternalQuery(VdcQueryType.GetVdsInterfacesByVdsId, new GetVdsByVdsIdParameters(vds.getId())).getReturnValue(); VdsNetworkInterface iface = LinqUtils.firstOrNull(interfaces, new Predicate<VdsNetworkInterface>() { @Override public boolean eval(VdsNetworkInterface i) { return StringHelper.EqOp(i.getNetworkName(), net.getname()); } }); if (iface == null) { status = NetworkStatus.NonOperational; break; } } } networkCluster.setstatus(status.getValue()); DbFacade.getInstance().getNetworkClusterDAO().updateStatus(networkCluster); } }
Source:
<code><START> public Map<String, Host> getSpmMap() { <END> return this.spmMap; }</code><technical_language>do want return if methods manage it. encapsulation issue</technical_language>

Target:
public ConcurrentHashMap getSpmMap() { return this.spmMap; }
Source:
<code>public int prepare(Xid xid) throws XAException { if (LOG.isTraceEnabled()) { <START> LOG.trace("DummyXAResource.prepare(xid=" + xid + ")"); <END> } return 0; }</code><technical_language>info</technical_language>

Target:
public int prepare(Xid xid) throws XAException { LOG.info("DummyXAResource.prepare(xid=" + xid + ")"); return 0; }
Source:
<code>public JSONObject getSnapshot() { JSONObject snapshot = new JSONObject(); <START> DataNodeId dataNodeId = getDataNodeId(); <END> snapshot.put(REPLICA_NODE, dataNodeId.getHostname() + ":" + dataNodeId.getPort()); snapshot.put(REPLICA_PARTITION, getPartitionId().toPathString()); snapshot.put(REPLICA_PATH, getReplicaPath()); snapshot.put(CAPACITY_BYTES, getCapacityInBytes()); return snapshot; }</code><technical_language>Minor: need call getDataNodeId() a class member</technical_language>

Target:
public JSONObject getSnapshot() { JSONObject snapshot = new JSONObject(); snapshot.put(REPLICA_NODE, dataNodeId.getHostname() + ":" + dataNodeId.getPort()); snapshot.put(REPLICA_PARTITION, getPartitionId().toPathString()); snapshot.put(REPLICA_PATH, getReplicaPath()); snapshot.put(CAPACITY_BYTES, getCapacityInBytes()); return snapshot; }
Source:
<code><START> public Long getId() { <END> return boxId; }</code><technical_language>I get changing UNSAVED_ID constants primitive, change getters Long object field is a primitive? necessitates a lot of boxing/unboxing</technical_language>

Target:
public long getId() { return boxId; }
Source:
<code>public void verifyModeName() { Assertion.assertEquals(MobilePageContent.editModeHeader, getModeName()); <START> PageObjectLogging.log("verifyModeName", <END> "verifying the header shows '" + MobilePageContent.editModeHeader + "'", true); }</code><technical_language>wrong formatting - parameter in new line</technical_language>

Target:
public void verifyModeName() { Assertion.assertEquals(MobilePageContent.editModeHeader, getModeName()); PageObjectLogging.log( "verifyModeName", "The header shows '" + MobilePageContent.editModeHeader + "'", true ); }
Source:
<code>public static ObjectLink decodeObjlnk(byte[] value) throws TlvException { ByteBuffer bff = ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN); bff.put(value); int val1 = bff.getShort(0); <START> if (val1 < 0) val1 = 65536 + val1; <END> int val2 = bff.getShort(2); if (val2 < 0) val2 = 65536 + val2; return new ObjectLink(val1, val2); }</code><technical_language>please put statement curly braces a new line</technical_language>

Target:
public static ObjectLink decodeObjlnk(byte[] value) throws TlvException { ByteBuffer bff = ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN); bff.put(value); int val1 = bff.getShort(0) & 0xFFFF; int val2 = bff.getShort(2) & 0xFFFF; return new ObjectLink(val1, val2); }
Source:
<code>public static void main(String[] args) throws IOException, SQLException, InterruptedException { Configuration configuration = new Configuration(args); Set<String> registers = configuration.getRegisters(); ScheduledExecutorService executorService = Executors.newScheduledThreadPool((int) registers.stream().filter(r -> configuration.cloudSearchEndPoint(r).isPresent()).count() + registers.size()); addShutdownHook(executorService); for (String register : registers) { try { DBI dbi = new DBI(configuration.getProperty(register + ".destination.postgres.db.connectionString")); DestinationDBUpdateDAO destinationDBUpdateDAO = createDestinationDBUpdateDAO(dbi); executorService.scheduleAtFixedRate( new IndexerTask(register, createSourceDAO(register, configuration), destinationDBUpdateDAO), 0, 10, TimeUnit.SECONDS ); configuration.cloudSearchEndPoint(register).ifPresent( endPoint -> executorService.scheduleAtFixedRate( new CloudSearchDataUploadTask(register, endPoint, configuration.cloudSearchWaterMarkEndPoint(register).get(), dbi.onDemand(IndexedEntriesUpdateDAO.class)), 0, <START> 10, <END> TimeUnit.SECONDS ) ); } catch (Throwable e) { e.printStackTrace(); ConsoleLogger.log("Error occurred while setting indexer for register: " + register + ". Error is -> " + e.getMessage()); } } Thread.currentThread().join(); }</code><technical_language>search systems a greater latency anyway, I if want this a frequent. A minute</technical_language>

Target:
public static void main(String[] args) throws IOException, SQLException, InterruptedException { Configuration configuration = new Configuration(args); Set<String> registers = configuration.getRegisters(); ScheduledExecutorService executorService = Executors.newScheduledThreadPool((int) registers.stream().filter(r -> configuration.cloudSearchEndPoint(r).isPresent()).count() + registers.size()); addShutdownHook(executorService); for (String register : registers) { try { DBI dbi = new DBI(configuration.getProperty(register + ".destination.postgres.db.connectionString")); DestinationDBUpdateDAO destinationDBUpdateDAO = createDestinationDBUpdateDAO(dbi); executorService.scheduleAtFixedRate( new IndexerTask(register, createSourceDAO(register, configuration), destinationDBUpdateDAO), 0, 10, TimeUnit.SECONDS ); configuration.cloudSearchEndPoint(register).ifPresent( endPoint -> executorService.scheduleAtFixedRate( new CloudSearchDataUploadTask(register, endPoint, configuration.cloudSearchWaterMarkEndPoint(register).get(), dbi.onDemand(IndexedEntriesUpdateDAO.class)), 0, 5, TimeUnit.MINUTES ) ); } catch (Throwable e) { e.printStackTrace(); ConsoleLogger.log("Error occurred while setting indexer for register: " + register + ". Error is -> " + e.getMessage()); } } Thread.currentThread().join(); }
Source:
<code>public List<Map<String, String>> linkify(HttpServletRequest req, String message) { String baseGerritUrl = urls.getBaseGerritUrl(req); <START> CommentLinkInfo changeIds = <END> new CommentLinkInfo("ChangeIdLinks", CHANGE_ID_PATTERN, baseGerritUrl + "#/q/$2,n,z", ""); List<CommentLinkInfo> operationalCommentLinks = new ArrayList<>(commentLinks); operationalCommentLinks.add(changeIds); List<Map<String, String>> parsed = Lists.newArrayList(); parsed.add(ImmutableMap.of("text", message)); for (int index = 0; index < parsed.size(); index++) { Map<String, String> piece = parsed.get(index); if (piece.get("url") == null) { String text = piece.get("text"); Matcher m = allPattern.matcher(text); if (m.find()) { for (CommentLinkInfo cli : operationalCommentLinks) { List<Map<String, String>> resultingReplacement = cli.replace(piece.get("text")); if (resultingReplacement != null) { parsed.remove(index); for (Map<String, String> it : resultingReplacement) { parsed.add(index, it); index++; } } } } } } return parsed; }</code><technical_language>now, support baseGerritUrl set, in case omit this one</technical_language>

Target:
public List<Map<String, String>> linkify(HttpServletRequest req, String message) { String baseGerritUrl = urls.getBaseGerritUrl(req); List<Map<String, String>> parsed = Lists.newArrayList(); Matcher m = LINK_PATTERN.matcher(message); int last = 0; while (m.find()) { addText(parsed, message.substring(last, m.start())); if (m.group(1) != null) { parsed.add(link(m.group(1), m.group(1))); } else if (m.group(2) != null) { if (baseGerritUrl != null) { parsed.add(link(m.group(2), baseGerritUrl + "#/q/" + m.group(2) + ",n,z")); } else { addText(parsed, m.group(2)); } } last = m.end(); } addText(parsed, message.substring(last)); return parsed; }
Source:
<code><START> public Collection<Bundle> getBundles() <END> { return new ArrayList<>(Arrays.asList( new AssetsBundle("/assets", "/app", "index.html"), new ViewBundle(), new FlywayBundle<T>() { @Override public DataSourceFactory getDataSourceFactory(T configuration) { return configuration.getDataSourceFactory(); } @Override public FlywayFactory getFlywayFactory(T configuration) { return super.getFlywayFactory(configuration); } })); }</code><technical_language>Iterable of Bundle ConfiguredBundle</technical_language>

Target:
public Iterable<Bundle> getBundles() { return Arrays.asList( new AssetsBundle("/assets", "/app", "index.html"), new ViewBundle(), new FlywayBundle<T>() { @Override public DataSourceFactory getDataSourceFactory(T configuration) { return configuration.getDataSourceFactory(); } @Override public FlywayFactory getFlywayFactory(T configuration) { return super.getFlywayFactory(configuration); } }); }
Source:
<code><START> private void createUIComponents() { <END> patternHelp = new HyperlinkLabel(""); Icon infoIcon = SonarLintIcons.INFO; patternHelp.setIcon(infoIcon); patternHelp.addMouseListener(new MouseAdapter() { public void mouseEntered(MouseEvent e) { final JLabel label = new JLabel("<<html><body style=\"margin-bottom:1pt\">Configure GLOB patterns to be applied to files in all projects.<br/><br/><b>Examples:</b><br/><table border=\"1\" cellpadding=\"1\" cellspacing=\"0\"><tr><td><pre>** *{!.java}</pre></td><td>Exclude everything except Java files</td></tr></table></body></html>"); label.setBorder(HintUtil.createHintBorder()); label.setBackground(HintUtil.INFORMATION_COLOR); label.setOpaque(true); HintManager.getInstance().showHint(label, RelativePoint.getSouthWestOf(patternHelp), HintManager.HIDE_BY_ANY_KEY | HintManager.HIDE_BY_TEXT_CHANGE, -1); } public void mouseExited(MouseEvent e) { HintManager.getInstance().hideAllHints(); } }); }</code><technical_language>![MAJOR](<LINK_1> 'Severity: MAJOR') Remove this unused private "createUIComponents" method. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
private void createUIComponents() { patternHelp = new HyperlinkLabel(""); Icon infoIcon = SonarLintIcons.INFO; patternHelp.setIcon(infoIcon); patternHelp.addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { final JLabel label = new JLabel("<<html><body style=\"margin-bottom:1pt\">" + "Configure GLOB patterns to be applied to files in all projects.<br/><br/><b>Examples:</b><br/>" + "<table border=\"1\" cellpadding=\"1\" cellspacing=\"0\"><tr><td><pre>** *{!.java}</pre></td>" + "<td>Exclude everything except Java files</td></tr></table></body></html>"); label.setBorder(HintUtil.createHintBorder()); label.setBackground(HintUtil.INFORMATION_COLOR); label.setOpaque(true); HintManager.getInstance().showHint(label, RelativePoint.getSouthWestOf(patternHelp), HintManager.HIDE_BY_ANY_KEY | HintManager.HIDE_BY_TEXT_CHANGE, -1); } @Override public void mouseExited(MouseEvent e) { HintManager.getInstance().hideAllHints(); } }); }
Source:
<code>private short getNewUid() { write.lock(); try { this.maxUid += 1; } finally { write.unlock(); } <START> return this.maxUid; <END> }</code><technical_language>This statement in try block</technical_language>

Target:
private short getNewUid() { write.lock(); try { this.maxUid += 1; return this.maxUid; } finally { write.unlock(); } }
Source:
<code>public boolean isTrue(ZestResponse response) { if(getChildrenCondition().isEmpty()){ return false; } boolean toReturn = true; for (ZestExpressionElement con : getChildrenCondition()) { toReturn = toReturn && con.evaluate(response); <START> if(!toReturn) break; END> } return toReturn; }</code><technical_language>this one? ;)</technical_language>

Target:
public boolean isTrue(ZestResponse response) { if(getChildrenCondition().isEmpty()){ return false; } boolean toReturn = true; for (ZestExpressionElement con : getChildrenCondition()) { toReturn = toReturn && con.evaluate(response); if(!toReturn) { break; } } return toReturn; }
Source:
<code>public void setupMocks() { MockitoAnnotations.initMocks(this); <START> when(uris.isEntityNamespace(0)).thenReturn(true); <END> when(uris.getHost()).thenReturn(DOMAIN); URIBuilder b = new URIBuilder(); b.setScheme("https"); b.setHost("acme.test"); when(uris.builder()).thenReturn(b); }</code><technical_language>Do need mock Uris</technical_language>

Target:
public void setupMocks() { MockitoAnnotations.initMocks(this); uris = new Uris("https", DOMAIN, 443, new long[] {0}); }
Source:
<code>public static Map<String,String> parseLine(VCFHeaderVersion version, String valueLine, List<String> expectedTagOrder) { <START> return mapping.get(version).parseLine(valueLine,expectedTagOrder,Collections.emptySet()); <END> }</code><technical_language>IMO avoid code duplication. suggestion return parseLine(version, valueLine, expectedTagOrder, Collections.emptySet());</technical_language>

Target:
public static Map<String,String> parseLine(VCFHeaderVersion version, String valueLine, List<String> expectedTagOrder) { return parseLine(version, valueLine, expectedTagOrder, Collections.emptyList()); }
Source:
<code>protected String buildTransactionDescription(ConcurStandardAccountingExtractDetailLine saeLine) { String formattedEndDate = dateFormatter.apply(saeLine.getReportEndDate(), ConcurConstants.DATE_FORMAT); return new StringBuilder(INITIAL_BUILDER_SIZE) .append(StringUtils.left(saeLine.getEmployeeLastName(), NAME_LENGTH_FOR_DESCRIPTION)) <START> .append(',').append(StringUtils.left(saeLine.getEmployeeFirstName(), NAME_LENGTH_FOR_DESCRIPTION)) <END> .append(',').append(formattedEndDate) .toString(); }</code><technical_language>constant for comma</technical_language>

Target:
protected String buildTransactionDescription(ConcurStandardAccountingExtractDetailLine saeLine) { String formattedEndDate = dateTimeService.toString(saeLine.getReportEndDate(), ConcurConstants.DATE_FORMAT); return new StringBuilder(INITIAL_BUILDER_SIZE) .append(StringUtils.left(saeLine.getEmployeeLastName(), NAME_LENGTH_FOR_DESCRIPTION)) .append(COMMA_CHAR).append(StringUtils.left(saeLine.getEmployeeFirstName(), NAME_LENGTH_FOR_DESCRIPTION)) .append(COMMA_CHAR).append(formattedEndDate) .toString(); }
Source:
<code>public void doQuery(List<ITmfStateInterval> stateInfo, long t) throws TimeRangeException, StateSystemDisposedException { checkValidTime(t); Deque<HTNode> queue = new LinkedList<>(); queue.add(fSht.getRootNode()); try { while (!queue.isEmpty()) { HTNode currentNode = queue.pop(); <START> if ((currentNode.getNodeType() == HTNode.NodeType.CORE)) { <END> queue.addAll(fSht.selectNextChildren((CoreNode) currentNode, t)); } currentNode.writeInfoFromNode(stateInfo, t); } } catch (ClosedChannelException e) { throw new StateSystemDisposedException(e); } }</code><technical_language>2 ((</technical_language>

Target:
public void doQuery(List<ITmfStateInterval> stateInfo, long t) throws TimeRangeException, StateSystemDisposedException { checkValidTime(t); Deque<HTNode> queue = new LinkedList<>(); queue.add(fSht.getRootNode()); try { while (!queue.isEmpty()) { HTNode currentNode = queue.pop(); if (currentNode.getNodeType() == HTNode.NodeType.CORE) { queue.addAll(fSht.selectNextChildren((CoreNode) currentNode, t)); } currentNode.writeInfoFromNode(stateInfo, t); } } catch (ClosedChannelException e) { throw new StateSystemDisposedException(e); } }