auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public List<String> getResourceCrnListByResourceNameList(List<String> resourceNames) { <START> return repository.findByNameIn(resourceNames).stream() <END> .map(db -> db.getResourceCrn().toString()).collect(Collectors.toList()); }</code><technical_language>get crns database</technical_language>

Target:
public List<String> getResourceCrnListByResourceNameList(List<String> resourceNames) { return repository.findResourceCrnsByNames(resourceNames) .stream().map(Crn::toString).collect(Collectors.toList()); }
Source:
<code>private void handleStateChange(ConnectionState newState) { switch ( newState ) { case SUSPENDED: publishEvent(TreeCacheEvent.Type.CONNECTION_SUSPENDED); break; case LOST: publishEvent(TreeCacheEvent.Type.CONNECTION_LOST); break; case RECONNECTED: try { root.wasReconnected(); publishEvent(TreeCacheEvent.Type.CONNECTION_RECONNECTED); } catch ( Exception e ) { handleException(e); } break; <START> } <END> }</code><technical_language>is edge case is handled here. If tree cache is started prior a connection ZooKeeper available, state change CONNECTED RECONNECTED. This means necessary watches get set up. LeaderLatch recipe a similar issue, solved waiting a connection (in background) in start()</technical_language>

Target:
private void handleStateChange(ConnectionState newState) { switch ( newState ) { case SUSPENDED: publishEvent(TreeCacheEvent.Type.CONNECTION_SUSPENDED); break; case LOST: publishEvent(TreeCacheEvent.Type.CONNECTION_LOST); break; case CONNECTED: try { root.wasCreated(); } catch ( Exception e ) { handleException(e); } break; case RECONNECTED: try { root.wasReconnected(); publishEvent(TreeCacheEvent.Type.CONNECTION_RECONNECTED); } catch ( Exception e ) { handleException(e); } break; } }
Source:
<code>protected ProcessingResult process(List<KnowledgeMotionDataRow> rows, ProcessingResult processingResult) { for (KnowledgeMotionDataRow row : rows) { try { Optional<Content> written = dataHandler.handle(row); if (written.isPresent()) { seenUris.add(written.get().getCanonicalUri()); } } catch (RuntimeException e) { processingResult.error(row.getId(), e.getMessage()); } } <START> Iterator<Content> allStoredKmContent = contentLister.listContent(ContentListingCriteria.defaultCriteria().forContent(ContentCategory.TOP_LEVEL_ITEM).forPublishers(allKmPublishers).build()); <END> while (allStoredKmContent.hasNext()) { Content item = allStoredKmContent.next(); if (! seenUris.contains(item.getCanonicalUri())) { item.setActivelyPublished(false); dataHandler.write(item); } } return processingResult; }</code><technical_language>call this if failed write rows. problems previously file malformed, deleted content</technical_language>

Target:
protected ProcessingResult process(List<KnowledgeMotionDataRow> rows, ProcessingResult processingResult) { boolean allRowsSuccess = true; for (KnowledgeMotionDataRow row : rows) { try { Optional<Content> written = dataHandler.handle(row); if (written.isPresent()) { seenUris.add(written.get().getCanonicalUri()); } } catch (RuntimeException e) { allRowsSuccess = false; processingResult.error(row.getId(), e.getMessage()); } } if (allRowsSuccess) { Iterator<Content> allStoredKmContent = contentLister.listContent(ContentListingCriteria.defaultCriteria().forContent(ContentCategory.TOP_LEVEL_ITEM).forPublishers(allKmPublishers).build()); while (allStoredKmContent.hasNext()) { Content item = allStoredKmContent.next(); if (!seenUris.contains(item.getCanonicalUri())) { item.setActivelyPublished(false); dataHandler.write(item); } } } return processingResult; }
Source:
<code>private void requestRoutingTable() { LOG.log(Level.FINE, "Sends a request for the routing table"); <START> try (final TraceScope traceScope = Trace.startSpan("ROUTING_INIT_REQUEST")) { <END> final TraceInfo traceInfo = TraceInfo.fromSpan(traceScope.getSpan()); msgSender.get().sendRoutingTableInitReqMsg(traceInfo); } }</code><technical_language>good name span ROUTING_TABLE_REQUEST. sound</technical_language>

Target:
private void requestRoutingTable() { LOG.log(Level.FINE, "Sends a request for the routing table"); try (final TraceScope traceScope = Trace.startSpan("ROUTING_TABLE_REQUEST")) { final TraceInfo traceInfo = TraceInfo.fromSpan(traceScope.getSpan()); msgSender.get().sendRoutingTableInitReqMsg(traceInfo); } }
Source:
<code>public Record afterRead(Record record, LogOffset offset) { <START> for (RecordFilter filter : filters) { <END> if (record != null) { record = filter.afterRead(record, offset); } } return record; }</code><technical_language>methods executed in reverse order ones</technical_language>

Target:
public Record afterRead(Record record, LogOffset offset) { for (Iterator iterator = filters.descendingIterator(); record != null && iterator.hasNext();) { RecordFilter filter = (RecordFilter) iterator.next(); record = filter.afterRead(record, offset); } return record; }
Source:
<code>protected boolean executeAnalysis(@NonNull IProgressMonitor monitor) throws TmfAnalysisException { ITmfTrace trace = getTrace(); if (trace == null) { <START> initialize(false); <END> return false; } File segmentStoreFile = getSupplementaryFile(getSegmentStoreFileName()); File stateSystemFile = getSupplementaryFile(getStateSystemFileName()); if (segmentStoreFile == null || stateSystemFile == null) { return false; } if (!segmentStoreFile.exists()) { fStateSystemModule.cancel(); stateSystemFile.delete(); } IStatus segmentStoreStatus = fSegmentStoreModule.schedule(); IStatus stateSystemStatus = fStateSystemModule.schedule(); if (!(segmentStoreStatus.isOK() && stateSystemStatus.isOK())) { cancelSubAnalyses(); initialize(false); return false; } if (!fStateSystemModule.waitForInitialization()) { initialize(false); return false; } ITmfStateSystem stateSystem = fStateSystemModule.getStateSystem(); if (stateSystem == null) { initialize(false); return false; } initialize(true); return fStateSystemModule.waitForCompletion(monitor) && fSegmentStoreModule.waitForCompletion(monitor); }</code><technical_language>change analysisReady()</technical_language>

Target:
protected boolean executeAnalysis(@NonNull IProgressMonitor monitor) throws TmfAnalysisException { ITmfTrace trace = getTrace(); if (trace == null) { analysisReady(false); return false; } File segmentStoreFile = getSupplementaryFile(getSegmentStoreFileName()); File stateSystemFile = getSupplementaryFile(getStateSystemFileName()); if (segmentStoreFile == null || stateSystemFile == null) { analysisReady(false); return false; } if (!segmentStoreFile.exists()) { fStateSystemModule.cancel(); stateSystemFile.delete(); } IStatus segmentStoreStatus = fSegmentStoreModule.schedule(); IStatus stateSystemStatus = fStateSystemModule.schedule(); if (!(segmentStoreStatus.isOK() && stateSystemStatus.isOK())) { cancelSubAnalyses(); analysisReady(false); return false; } if (!fStateSystemModule.waitForInitialization()) { analysisReady(false); cancelSubAnalyses(); return false; } ITmfStateSystem stateSystem = fStateSystemModule.getStateSystem(); if (stateSystem == null) { analysisReady(false); throw new IllegalStateException("Initialization of the state system module succeeded but the statesystem is null"); } analysisReady(true); return fStateSystemModule.waitForCompletion(monitor) && fSegmentStoreModule.waitForCompletion(monitor); }
Source:
<code>public static String getString(IMolecularFormula formula, String[] orderElements, boolean setOne, boolean setMassNumber) { StringBuffer stringMF = new StringBuffer(); List<IIsotope> isotopesList = putInOrder(orderElements, formula); List<String> elemSet = new ArrayList<String>(); for (IIsotope isotope : isotopesList) { String symbol = isotope.getSymbol(); if (!elemSet.contains(symbol)) elemSet.add(symbol); } if (!setMassNumber) { for (String elem : elemSet) { int count = 0; for (IIsotope isotope : formula.isotopes()) { if (isotope.getSymbol().equals(elem)) count += formula.getIsotopeCount(isotope); } stringMF.append(elem); if (!(count == 1 && !setOne)) stringMF.append(count); } } else { for (IIsotope isotope : isotopesList) { int count = formula.getIsotopeCount(isotope); try { <START> IIsotope major = Isotopes.getInstance().getMajorIsotope(isotope.getSymbol()); <END> if (Objects.equals(isotope.getMassNumber(), major.getMassNumber())) stringMF.append(isotope.getSymbol()); else stringMF.append("["+isotope.getMassNumber()+isotope.getSymbol()+"]"); } catch (IOException e) { e.printStackTrace(); } if (!(count == 1 && !setOne)) stringMF.append(count); } } return stringMF.toString(); }</code><technical_language>This is wrong, test **isotope.getMassNumber() == null**. is valid input [12CH3]CO CCO</technical_language>

Target:
public static String getString(IMolecularFormula formula, String[] orderElements, boolean setOne, boolean setMassNumber) { StringBuffer stringMF = new StringBuffer(); List<IIsotope> isotopesList = putInOrder(orderElements, formula); List<String> elemSet = new ArrayList<String>(); for (IIsotope isotope : isotopesList) { String symbol = isotope.getSymbol(); if (!elemSet.contains(symbol)) elemSet.add(symbol); } if (!setMassNumber) { for (String elem : elemSet) { int count = 0; for (IIsotope isotope : formula.isotopes()) { if (isotope.getSymbol().equals(elem)) count += formula.getIsotopeCount(isotope); } stringMF.append(elem); if (!(count == 1 && !setOne)) stringMF.append(count); } } else { for (IIsotope isotope : isotopesList) { int count = formula.getIsotopeCount(isotope); try { IIsotope major = Isotopes.getInstance().getMajorIsotope(isotope.getSymbol()); if (isotope.getMassNumber() == null) stringMF.append(isotope.getSymbol()); else stringMF.append("[") .append(isotope.getMassNumber()) .append(isotope.getSymbol()) .append("]"); } catch (IOException e) { e.printStackTrace(); } if (!(count == 1 && !setOne)) stringMF.append(count); } } return stringMF.toString(); }
Source:
<code>public void onConnectionStateChange(String newConnectionState) { switch (newConnectionState) { case CONNECTION_LOST: updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, <START> "The connection to the digitalSTROM-Server can't established"); <END> devStatMan.stop(); break; case CONNECTION_RESUMED: setStatus(ThingStatus.ONLINE); devStatMan.start(); sceneMan.start(); break; case APPLICATION_TOKEN_GENERATED: if (connMan != null) { Configuration config = this.getConfig(); if (config != null) { config.remove(USER_NAME); config.remove(PASSWORD); config.put(APPLICATION_TOKEN, connMan.getApplicationToken()); this.updateConfiguration(config); } } default: } }</code><technical_language>typo: "cannot established"</technical_language>

Target:
public void onConnectionStateChange(String newConnectionState) { switch (newConnectionState) { case CONNECTION_LOST: updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "The connection to the digitalSTROM-Server cannot be established."); devStatMan.stop(); break; case CONNECTION_RESUMED: if (connectionTimeoutCounter > 0) { setStatus(ThingStatus.ONLINE); devStatMan.start(); } break; case APPLICATION_TOKEN_GENERATED: if (connMan != null) { Configuration config = this.getConfig(); if (config != null) { config.remove(USER_NAME); config.remove(PASSWORD); config.put(APPLICATION_TOKEN, connMan.getApplicationToken()); this.updateConfiguration(config); } } return; default: } connectionTimeoutCounter = 0; }
Source:
<code>GridUserInterface decode(Map<String, Object> inputParam) { String member_DN = new String("userDN"); String member_Fqans = new String("userFQANS"); String dnString = (String) inputParam.get(member_DN); <START> List<Object> fqansList = null; <END> try { fqansList = Arrays.asList((Object[]) inputParam.get(member_Fqans)); } catch (NullPointerException e) { log.debug("Empty FQAN[] found.", e); } FQAN[] fqans = null; if (fqansList != null) { fqans = new FQAN[fqansList.size()]; log.debug("fqans_vector Size: {}" , fqansList.size()); for (int i = 0; i < fqansList.size(); i++) { String fqan_string = (String) fqansList.get(i); log.debug("FQAN[{}]: {}",i, fqan_string); FQAN fq = new FQAN(fqan_string); fqans[i] = fq; } } if (dnString != null) { log.debug("DN: {}" , dnString); if (fqans != null && fqans.length > 0) { log.debug("VomsGU with FQAN"); try { return createGridUser(dnString, fqans); } catch (IllegalArgumentException e) { log.error(e.getMessage(), e); } } else { return createGridUser(dnString); } } return null; }</code><technical_language>fqans strings well</technical_language>

Target:
GridUserInterface decode(Map<String, Object> inputParam) { String member_DN = new String("userDN"); String member_Fqans = new String("userFQANS"); String dnString = (String) inputParam.get(member_DN); Object[] fqansArr = (Object[]) inputParam.get(member_Fqans); FQAN[] fqans = null; if (fqansArr != null) { fqans = new FQAN[fqansArr.length]; log.debug("fqans_vector Size: {}" , fqansArr.length); for (int i = 0; i < fqansArr.length; i++) { log.debug("FQAN[{}]: {}",i, (String) fqansArr[i]); fqans[i] = new FQAN((String) fqansArr[i]); } } if (dnString != null) { log.debug("DN: {}" , dnString); if (fqans != null && fqans.length > 0) { log.debug("VomsGU with FQAN"); try { return createGridUser(dnString, fqans); } catch (IllegalArgumentException e) { log.error(e.getMessage(), e); } } else { return createGridUser(dnString); } } return null; }
Source:
<code><START> public List<PermissionSubject> getPermissionCheckSubjects() { <END> if (getNetwork() == null) { return Collections.<PermissionSubject> emptyList(); } NGuid dataCenterId = getNetwork().getDataCenterId(); return Collections.singletonList(new PermissionSubject(dataCenterId == null ? null : dataCenterId.getValue(), VdcObjectType.StoragePool, getActionType().getActionGroup())); }</code><technical_language>CommandBase.checkPermissions return true for this, meaning authorize user perform this action. assign null dataCenterId</technical_language>

Target:
public List<PermissionSubject> getPermissionCheckSubjects() { Network network = getNetwork(); NGuid dataCenterId = network == null ? null : network.getDataCenterId(); return Collections.singletonList(new PermissionSubject(dataCenterId == null ? null : dataCenterId.getValue(), VdcObjectType.StoragePool, getActionType().getActionGroup())); }
Source:
<code>private void closeAllActivities() { if (!shutdown) { Intent intent = null; if (BuildConfig.CREATE_AT_SCHOOL) { try { intent = new Intent(currentActivity.getApplicationContext(), Class.forName("org.catrobat.catroid.createatschool.ui" + ".CreateAtSchoolMainMenuActivity")); } catch (ClassNotFoundException e) { Log.e(TAG, e.getMessage()); } } else if (BuildConfig.PHIRO_CODE) { <START> try { <END> intent = new Intent(currentActivity.getApplicationContext(), Class.forName("org.catrobat.catroid.phiro.ui" + ".PhiroMainMenuActivity")); } catch (ClassNotFoundException e) { Log.e(TAG, e.getMessage()); } } else { intent = new Intent(currentActivity.getApplicationContext(), MainMenuActivity.class); } intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); currentActivity.startActivity(intent); } }</code><technical_language>duplicate code, set string a variable</technical_language>

Target:
private void closeAllActivities() { if (!shutdown) { Intent intent = new Intent(currentActivity.getApplicationContext(), MainMenuActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); currentActivity.startActivity(intent); } }
Source:
<code>default Map<String, Object> getStats() { <START> return null; <END> }</code><technical_language>empty map</technical_language>

Target:
default Map<String, Map<String, Object>> getStats() { return ImmutableMap.of(); }
Source:
<code>public List<HistoryToken> findByIdInSerializedValueAndElementType(Integer id, String elementTypeTableName, boolean lastOnly) { return em().createNativeQuery("" + "SELECT ht.* " + "FROM " + EntityConstants.HISTORY_TOKEN_TABLE + " ht " + "WHERE (ht." + EntityConstants.HISTORY_TOKEN_COLUMN_VALUE + " = :id " + "OR ht." + EntityConstants.HISTORY_TOKEN_COLUMN_VALUE + " ~ ('^(.*~)?'||:id||'(~.*)?$') ) " + (elementTypeTableName == null ? "" : "AND EXISTS (SELECT * FROM " + elementTypeTableName + ") ") + "ORDER BY ht." + EntityConstants.HISTORY_TOKEN_COLUMN_DATE + " DESC" + <START> (lastOnly ? " LIMIT 1" : ""), HistoryToken.class) <END> .setParameter("id", String.valueOf(id)) .getResultList(); }</code><technical_language>do a LIMIT sql statement instead of Hibernate setMaxResult(1) (like in method)</technical_language>

Target:
public List<HistoryToken> findByIdInSerializedValueAndElementType(Integer id, String elementTypeTableName, boolean lastOnly) { Query q = em().createNativeQuery("" + "SELECT ht.* " + "FROM " + EntityConstants.HISTORY_TOKEN_TABLE + " ht " + "WHERE (ht." + EntityConstants.HISTORY_TOKEN_COLUMN_VALUE + " = :id " + "OR ht." + EntityConstants.HISTORY_TOKEN_COLUMN_VALUE + " ~ ('^(.*~)?'||:id||'(~.*)?$') ) " + (elementTypeTableName == null ? "" : "AND EXISTS (SELECT * FROM " + elementTypeTableName + ") ") + "ORDER BY ht." + EntityConstants.HISTORY_TOKEN_COLUMN_DATE + " DESC", HistoryToken.class) .setParameter("id", String.valueOf(id)); if (lastOnly) { q = q.setMaxResults(1); } return q.getResultList(); }
Source:
<code><START> public synchronized AuthAwareConfigContext reload() { <END> final int newFingerprint = calculateAuthParamsFingerprint(this); if (newFingerprint == parametersFingerprint) { return this; } if (this.authContext != null) { final ThreadLocalSigner signer = authContext.signer; if (signer != null) { signer.clearAll(); } this.authContext = null; } if (BooleanUtils.isNotTrue(noAuth())) { this.authContext = doLoad(); } parametersFingerprint = newFingerprint; return this; }</code><technical_language>staring a this synchronized doubt necessity afraid I another concern. If thread A calls setEncryptionPrivateKeyPath, thread B calls setMantaKeyId, thread C calls reload() I *think* a potential problem this synchronized is effectively protecting read of fields, writes. I copy of JCIP hand verify right term. Please if is confusing. possibility avoid a lot of unnecessary synchronization create a ConfigContext a ReentrantReadWriteLock inherent that</technical_language>

Target:
public AuthAwareConfigContext reload() { synchronized (lock) { final int newParamsFingerprint = calculateAuthParamsFingerprint(this); if (authContext != null) { if (authContext.paramsFingerprint == newParamsFingerprint) { return this; } else { authContext.signer.clearAll(); authContext = null; } } if (BooleanUtils.isNotTrue(noAuth())) { authContext = doLoad(newParamsFingerprint); } } return this; }
Source:
<code>public String getUnstableTotalAll() { <START> return thresholds.unstableTotalHigh; <END> }</code><technical_language>totalAll</technical_language>

Target:
public String getUnstableTotalAll() { return thresholds.unstableTotalAll; }
Source:
<code>protected void validationStatusChanged(final IStatus status) { updateTextEditorFeedback(status); messageManager.removeAllMessages(); if (!status.isOK() && getViewer().isCellEditorActive()) { <START> messageManager.addMessage("", status.getMessage(), null, new StatusToMessageSeverity(status).toMessageSeverity()); <END> } }</code><technical_language>empty string argument</technical_language>

Target:
protected void validationStatusChanged(final IStatus status) { updateTextEditorFeedback(status); messageManager.removeAllMessages(); if (!status.isOK() && getViewer().isCellEditorActive()) { messageManager.addMessage(null, status.getMessage(), null, new StatusToMessageSeverity(status).toMessageSeverity()); } }
Source:
<code><START> protected BufferedReader getHtml(ClientConnection connection) { <END> if (connection.inputStream == null) { return null; } BufferedReader br = new BufferedReader( new InputStreamReader(connection.inputStream, StandardCharsets.UTF_8)); return br; }</code><technical_language>This public. Other modules this too</technical_language>

Target:
public BufferedReader getHtml(ClientConnection connection) { if (connection.inputStream == null) { return null; } BufferedReader br = new BufferedReader( new InputStreamReader(connection.inputStream, StandardCharsets.UTF_8)); return br; }
Source:
<code>protected void scanFile(XmlFile xmlFile) { if (!"pom.xml".equalsIgnoreCase(xmlFile.getInputFile().filename())) { return; } <START> NodeList dependencies = evaluate(dependencyExpression, xmlFile.getNamespaceUnawareDocument()); <END> for (int i = 0; i < dependencies.getLength(); i++) { Element dependency = (Element) dependencies.item(i); checkDependency(dependency); } }</code><technical_language>rely new methods AbstracXPathBasedCheck iterate list of nodes</technical_language>

Target:
protected void scanFile(XmlFile xmlFile) { if (!"pom.xml".equalsIgnoreCase(xmlFile.getInputFile().filename())) { return; } evaluateAsList(dependencyExpression, xmlFile.getNamespaceUnawareDocument()) .forEach(dependency -> checkDependency((Element) dependency)); }
Source:
<code>protected void hookOnSubscribe(Subscription subscription) { this.subscription = subscription; <START> logger.info("[{}] onSubscribe Pending: {}, Scheduling receive timeout task '{}'.", initialWork.getId(), <END> initialWork.getNumberOfEvents(), initialWork.getTimeout()); queueWork(initialWork); }</code><technical_language>This verbose. get noisy</technical_language>

Target:
protected void hookOnSubscribe(Subscription subscription) { if (Operators.setOnce(UPSTREAM, this, subscription)) { this.subscription = subscription; remaining.addAndGet(requested); subscription.request(requested); subscriberInitialized = true; drain(); } else { logger.error("Already subscribed once."); } }
Source:
<code>public MaskOverviewProvider(DatasetLayout layout, File inputFile, ImageReaderSpi suggestedSPI) throws IOException { <START> this (layout, inputFile, new SpiHelper(inputFile.toURI().toURL(), suggestedSPI)); <END> }</code><technical_language>toURI().toURL() need modified URLs.fileToUrl(file) (marked this one, others, please fix all)</technical_language>

Target:
public MaskOverviewProvider(DatasetLayout layout, File inputFile, ImageReaderSpi suggestedSPI) throws IOException { this (layout, inputFile, new SpiHelper(URLs.fileToUrl(inputFile), suggestedSPI)); }
Source:
<code>private void deleteSearchItem(String item) { ArrayList<String> recents = new ArrayList<>(); Query<Preferences> query = mBucketPreferences.query(); try (ObjectCursor<Preferences> cursor = query.execute()) { if (cursor.moveToNext()) { recents = cursor.getObject().getRecentSearches(); } Preferences preferences = cursor.getObject(); mIndex = recents.indexOf(item); recents.remove(item); preferences.setRecentSearches(recents); preferences.save(); } <START> } <END></code><technical_language>if getPreferences() java private void deleteSearchItem(String item) { Preferences preferences = getPreferences(); ArrayList<String> recentSearches = preferences.getRecentSearches(); mIndex = recentSearches.indexOf(item); recentSearches.remove(item); preferences.setRecentSearches(recentSearches); preferences.save(); }</technical_language>

Target:
private void deleteSearchItem(String item) { Preferences preferences = getPreferences(); if (preferences != null) { List<String> recents = preferences.getRecentSearches(); mDeletedItemIndex = recents.indexOf(item); recents.remove(item); preferences.setRecentSearches(recents); preferences.save(); } else { Log.e("deleteSearchItem", "Could not get preferences entity"); } }
Source:
<code>private void registerMethod(@Nonnull final MethodHandles.Lookup caller, @Nonnull final AbstractServer server, @Nonnull final Method method) { final RequestHandler annotation = method.getAnnotation(RequestHandler.class); <START> if(handlerMap.containsKey(annotation.type())) { <END> throw new UnrecoverableCorfuError("HandlerMethod for " + annotation.type() + " already registered!"); } try { HandlerMethod h; if (Modifier.isStatic(method.getModifiers())) { MethodHandle mh = caller.unreflect(method); h = (HandlerMethod) LambdaMetafactory.metafactory(caller, "handle", MethodType.methodType(HandlerMethod.class), mh.type(), mh, mh.type()).getTarget().invokeExact(); } else { MethodType mt = MethodType.methodType(method.getReturnType(), method.getParameterTypes()); MethodHandle mh = caller.findVirtual(server.getClass(), method.getName(), mt); MethodType mtt = mh.type().dropParameterTypes(0, 1); h = (HandlerMethod) LambdaMetafactory.metafactory(caller, "handle", MethodType.methodType(HandlerMethod.class, server.getClass()), mtt, mh, mtt).getTarget().bindTo(server).invoke(); } final HandlerMethod handler = generateConditionalHandler(annotation.type(), h); handlerMap.put(annotation.type(), handler); } catch(Throwable e) { log.error("registerMethod: Exception during request handler registration", e); throw new UnrecoverableCorfuError(e); } }</code><technical_language>nit: if (handlerMap.containsKey(annotation.type())) {</technical_language>

Target:
private void registerMethod(@Nonnull final MethodHandles.Lookup caller, @Nonnull final AbstractServer server, @Nonnull final Method method) { final RequestHandler annotation = method.getAnnotation(RequestHandler.class); if (handlerMap.containsKey(annotation.type())) { throw new IllegalStateException("HandlerMethod for " + annotation.type() + " already registered!"); } try { HandlerMethod h; if (Modifier.isStatic(method.getModifiers())) { MethodHandle mh = caller.unreflect(method); h = (HandlerMethod) LambdaMetafactory.metafactory(caller, "handle", MethodType.methodType(HandlerMethod.class), mh.type(), mh, mh.type()).getTarget().invokeExact(); } else { MethodType mt = MethodType.methodType(method.getReturnType(), method.getParameterTypes()); MethodHandle mh = caller.findVirtual(server.getClass(), method.getName(), mt); MethodType mtt = mh.type().dropParameterTypes(0, 1); h = (HandlerMethod) LambdaMetafactory.metafactory(caller, "handle", MethodType.methodType(HandlerMethod.class, server.getClass()), mtt, mh, mtt).getTarget().bindTo(server).invoke(); } final HandlerMethod handler = generateConditionalHandler(annotation.type(), h); handlerMap.put(annotation.type(), handler); } catch (Throwable e) { throw new UnrecoverableCorfuError("Exception during request handler registration", e); } }
Source:
<code>protected StreamTaskListener createListener() { File f = getLogFile(); if (f.isFile()) { if ((lastRotateMillis == null) || (lastRotateMillis + logRotateMillis < System.currentTimeMillis()) || (logRotateSize > 0 && f.length() > logRotateSize)) { lastRotateMillis = System.currentTimeMillis(); File p = null; for (int i = 5; i >= 0; i--) { File o = i == 0 ? f : new File(f.getParentFile(), f.getName() + "." + i); if (o.isFile()) { if (p != null && !p.exists()) { if (!o.renameTo(p)) { logger.log(getErrorLoggingLevel(), "Could not rotate log files {0} to {1}", new Object[]{o, p}); } } else { if (!o.delete()) { <START> logger.log(getErrorLoggingLevel(), "Could not delete log files {0} to enable rotation", <END> o); } } p = o; } } } } if (!f.getParentFile().isDirectory()) { if (!f.getParentFile().mkdirs()) { logger.log(getErrorLoggingLevel(), "Could not create directory {0}", f.getParentFile()); } } try { return new StreamTaskListener(f, true, null); } catch (IOException e) { throw new Error(e); } }</code><technical_language>delete **log** file (singular)</technical_language>

Target:
protected StreamTaskListener createListener() { File f = getLogFile(); if (!f.getParentFile().isDirectory()) { if (!f.getParentFile().mkdirs()) { logger.log(getErrorLoggingLevel(), "Could not create directory {0}", f.getParentFile()); } } if (f.isFile()) { if ((lastRotateMillis + logRotateMillis < System.currentTimeMillis()) || (logRotateSize > 0 && f.length() > logRotateSize)) { lastRotateMillis = System.currentTimeMillis(); File prev = null; for (int i = 5; i >= 0; i--) { File curr = i == 0 ? f : new File(f.getParentFile(), f.getName() + "." + i); if (curr.isFile()) { if (prev != null && !prev.exists()) { if (!curr.renameTo(prev)) { logger.log(getErrorLoggingLevel(), "Could not rotate log files {0} to {1}", new Object[]{curr, prev}); } } else { if (!curr.delete()) { logger.log(getErrorLoggingLevel(), "Could not delete log file {0} to enable rotation", curr); } } } prev = curr; } } } else { lastRotateMillis = System.currentTimeMillis(); File oldFile = new File(Jenkins.getActiveInstance().getRootDir(), f.getName()); if (oldFile.isFile()) { File newFile = new File(f.getParentFile(), f.getName() + ".1"); if (!newFile.isFile()) { if (oldFile.renameTo(newFile)) { logger.log(getNormalLoggingLevel(), "Moved {0} to {1}", new Object[]{oldFile, newFile}); } else { logger.log(getErrorLoggingLevel(), "Could not move {0} to {1}", new Object[]{oldFile, newFile}); } } } } try { return new StreamTaskListener(f, true, null); } catch (IOException e) { throw new Error(e); } }
Source:
<code><START> public void canSerializeAndDeserializeKeepingNonLoggability() { <END> TableMetadataPersistence.NameComponentDescription.Builder builder = NAME_NOT_LOGGABLE_DESCRIPTION.persistToProto(); assertThat(NameComponentDescription.hydrateFromProto(builder.build())) .isEqualTo(NAME_NOT_LOGGABLE_DESCRIPTION) .matches(description -> !description.isNameLoggable()); }</code><technical_language>check serialise deserialise default description, too</technical_language>

Target:
public void canSerializeAndDeserializeKeepingNonLoggability() { assertCanSerializeAndDeserializeWithLoggability(NAME_NOT_LOGGABLE_DESCRIPTION, false); }
Source:
<code><START> private boolean jsonExists(String path){ <END> File test = new File(path + "/" + JSON_POM_FILE); return test.exists() && test.isFile(); }</code><technical_language>nice provide some feedback if this check fails. "The file BLABLA exist in directory provided. Please try again..."</technical_language>

Target:
private boolean jsonExists(String path) { File test = new File(path, JSON_POM_FILE); return test.exists() && test.isFile(); }
Source:
<code>public boolean shouldShowNoResponseText(String giverEmail, String recipientEmail, FeedbackQuestionAttributes question) { return !(question.recipientType == FeedbackParticipantType.STUDENTS <START> || question.recipientType == FeedbackParticipantType.TEAMS); <END> }</code><technical_language>PMD complain this? surprising. this one: java question.recipientType != FeedbackParticipantType.STUDENTS && question.recipientType != FeedbackParticipantType.TEAMS</technical_language>

Target:
public boolean shouldShowNoResponseText(String giverEmail, String recipientEmail, FeedbackQuestionAttributes question) { return question.recipientType != FeedbackParticipantType.STUDENTS && question.recipientType != FeedbackParticipantType.TEAMS; }
Source:
<code>protected Map<List<String>, Object> getParamsForBean(SimulationDescriptor simulationDescriptor, FactIdentifier factIdentifier, List<FactMappingValue> factMappingValues, ExpressionEvaluatorFactory expressionEvaluatorFactory) { Map<List<String>, Object> paramsForBean = new HashMap<>(); <START> for (FactMappingValue factMappingValue : factMappingValues) { <END> ExpressionIdentifier expressionIdentifier = factMappingValue.getExpressionIdentifier(); FactMapping factMapping = simulationDescriptor.getFactMapping(factIdentifier, expressionIdentifier) .orElseThrow(() -> new IllegalStateException("Wrong expression, this should not happen")); List<String> pathToField = factMapping.getExpressionElementsWithoutClass().stream() .map(ExpressionElement::getStep).collect(toList()); ExpressionEvaluator expressionEvaluator = expressionEvaluatorFactory.getOrCreate(factMappingValue); try { Object value = expressionEvaluator.evaluateLiteralExpression(factMapping.getClassName(), factMapping.getGenericTypes(), factMappingValue.getRawValue()); paramsForBean.put(pathToField, value); } catch (RuntimeException e) { factMappingValue.setExceptionMessage(e.getMessage()); throw new ScenarioException(e.getMessage(), e); } } return paramsForBean; }</code><technical_language>Suggestion: is regression case Create instance of IllegalStateException("Wrong expression, this happen")) loop reuse inside</technical_language>

Target:
protected Map<List<String>, Object> getParamsForBean(SimulationDescriptor simulationDescriptor, FactIdentifier factIdentifier, List<FactMappingValue> factMappingValues, ExpressionEvaluatorFactory expressionEvaluatorFactory) { Map<List<String>, Object> paramsForBean = new HashMap<>(); boolean hasError = false; for (FactMappingValue factMappingValue : factMappingValues) { ExpressionIdentifier expressionIdentifier = factMappingValue.getExpressionIdentifier(); FactMapping factMapping = simulationDescriptor.getFactMapping(factIdentifier, expressionIdentifier) .orElseThrow(() -> new IllegalStateException("Wrong expression, this should not happen")); List<String> pathToField = factMapping.getExpressionElementsWithoutClass().stream() .map(ExpressionElement::getStep).collect(toList()); ExpressionEvaluator expressionEvaluator = expressionEvaluatorFactory.getOrCreate(factMappingValue); try { Object value = expressionEvaluator.evaluateLiteralExpression(factMapping.getClassName(), factMapping.getGenericTypes(), factMappingValue.getRawValue()); paramsForBean.put(pathToField, value); } catch (RuntimeException e) { factMappingValue.setExceptionMessage(e.getMessage()); hasError = true; } } if (hasError) { throw new ScenarioException("Error in one or more input values"); } return paramsForBean; }
Source:
<code>public void singleStudent() { String student = "Alice"; String plants = "RC\nGG"; String[] expected = {"radishes", "clover", "grass", "grass"}; <START> assertEquals(expected, new KindergartenGarden(plants) <END> .getPlantsOfStudent(student)); }</code><technical_language>I argument a new line is a bit more readable :)</technical_language>

Target:
public void singleStudent() { String student = "Alice"; String plants = "RC\nGG"; List<Plant> expected = Arrays.asList(Plant.RADISHES, Plant.CLOVER, Plant.GRASS, Plant.GRASS); assertEquals( expected, new KindergartenGarden(plants).getPlantsOfStudent(student) ); }
Source:
<code>public void scrollToIndex(int index) { ListModel<Object> model = getModel(); double scrollRatio; if (model != null) { <START> if (index < 0 || index > model.getSize() - 1) { <END> throw new IndexOutOfBoundsException("Illegal index: " + index); } scrollRatio = (double) index / model.getSize(); } else { int itemCount = getItemCount(); if (index < 0 || index > itemCount - 1) { throw new IndexOutOfBoundsException("Illegal index: " + index); } scrollRatio = (double) index / itemCount; } response(new AuInvoke(this, "_scrollToIndex", index, scrollRatio)); }</code><technical_language>int itemCount = model.getSize();</technical_language>

Target:
public void scrollToIndex(int index) { ListModel<Object> model = getModel(); int itemCount = model != null ? model.getSize() : getItemCount(); if (index < 0 || index > itemCount - 1) { throw new IndexOutOfBoundsException("Illegal index: " + index); } response(new AuInvoke(this, "scrollToIndex", index, (double) index / itemCount)); }
Source:
<code>private ProgramState handleSpecialMethods(ProgramState ps, MethodInvocationTree mit) { <START> if (AnnotationUtils.isAnnotatedNonNull(mit.symbol())) { <END> return ps.addConstraint(ps.peekValue(), ObjectConstraint.NOT_NULL); } else if (OBJECT_WAIT_MATCHER.matches(mit)) { return ps.resetFieldValues(constraintManager, false); } return ps; }</code><technical_language>Wondering a static import for AnnotationUtils method</technical_language>

Target:
private ProgramState handleSpecialMethods(ProgramState ps, MethodInvocationTree mit) { if (isAnnotatedNonNull(mit.symbol())) { return ps.addConstraint(ps.peekValue(), ObjectConstraint.NOT_NULL); } else if (OBJECT_WAIT_MATCHER.matches(mit)) { return ps.resetFieldValues(constraintManager, false); } return ps; }
Source:
<code>public RepositoryObjectDataLoader loadHeaders(RepositoryObject obj) throws FedoraException { PID pid = obj.getPid(); try (FcrepoResponse response = getClient().head(pid.getRepositoryUri()).perform()) { <START> if (response.getStatusCode() != 200) { <END> throw new FedoraException("Received " + response.getStatusCode() + " response while retrieving headers for " + pid.getRepositoryUri()); } obj.setEtag(response.getHeaderValue("Etag")); String lastModString = response.getHeaderValue("Last-Modified"); if (lastModString != null) { obj.setLastModified(DateUtils.parseDate(lastModString)); } } catch (IOException e) { throw new FedoraException("Unable to create deposit record at " + pid.getRepositoryUri(), e); } catch (FcrepoOperationFailedException e) { throw ClientFaultResolver.resolve(e); } return this; }</code><technical_language>I tend prefer constants, Apache's SC_OK, hardcoded numbers, a matter of personal taste</technical_language>

Target:
public RepositoryObjectDataLoader loadHeaders(RepositoryObject obj) throws FedoraException { PID pid = obj.getPid(); try (FcrepoResponse response = getClient().head(pid.getRepositoryUri()).perform()) { if (response.getStatusCode() != HttpStatus.SC_OK) { throw new FedoraException("Received " + response.getStatusCode() + " response while retrieving headers for " + pid.getRepositoryUri()); } obj.setEtag(response.getHeaderValue("Etag")); String lastModString = response.getHeaderValue("Last-Modified"); if (lastModString != null) { obj.setLastModified(DateUtils.parseDate(lastModString)); } } catch (IOException e) { throw new FedoraException("Unable to create deposit record at " + pid.getRepositoryUri(), e); } catch (FcrepoOperationFailedException e) { throw ClientFaultResolver.resolve(e); } return this; }
Source:
<code>private String createSwaggerSpecification() { String json = ""; try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.INDENT_OUTPUT, true); mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, true); mapper.setSerializationInclusion(Include.NON_NULL); mapper.getSerializerProvider().setNullKeySerializer(new NullSerializer()); json = mapper.writeValueAsString(swaggerSpecification); <START> } catch (Exception exp) { <END> exp.printStackTrace(); } return json; }</code><technical_language>reason for catching generic exception remove print stack trace</technical_language>

Target:
private String createSwaggerSpecification() { String json = ""; try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.INDENT_OUTPUT, true); mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, true); mapper.setSerializationInclusion(Include.NON_NULL); mapper.getSerializerProvider().setNullKeySerializer(new NullSerializer()); json = mapper.writeValueAsString(swaggerSpecification); } catch (Exception exp) { log.error("Error while creating object mapper", exp); } return json; }
Source:
<code>private void marshalAndSaveFact(FactHandle factHandle) { Object factObject = m_kieSession.getObject(factHandle); try { factObjects.put(DroolsStreamUtils.streamOut(factObject), factObject.getClass()); } catch (IOException e) { <START> LOG.error("Exception while marshalling fact {}", e); <END> } }</code><technical_language>Add factObject & factObject class exception</technical_language>

Target:
private void marshalAndSaveFact(FactHandle factHandle) { Object factObject = m_kieSession.getObject(factHandle); try { factObjects.put(DroolsStreamUtils.streamOut(factObject), factObject.getClass()); } catch (IOException e) { LOG.error("Exception while marshalling fact with Class {}", factObject, factObject.getClass().getCanonicalName(), e); } }
Source:
<code>public static boolean isAlreadyPresent(ArrayList<Order> ordersPlaced, Order newOrder) { for (Order orderPlaced : ordersPlaced) { if <START> (((orderPlaced instanceof BuyOrder) && (newOrder instanceof BuyOrder)) || ((orderPlaced instanceof SellOrder) && (newOrder instanceof SellOrder))) { <END> if (orderPlaced.getStockSymbol().equals( newOrder.getStockSymbol())) { return true; } } } return false; }</code><technical_language>long list of boolean expressions lowers readability. consider extracting local variables</technical_language>

Target:
public static boolean isAlreadyPresent(ArrayList<Order> ordersPlaced, Order newOrder) { for (Order orderPlaced : ordersPlaced) { boolean buyOrderPlaced; boolean newBuyOrder; if(orderPlaced instanceof BuyOrder) buyOrderPlaced = true; else if (orderPlaced instanceof SellOrder) buyOrderPlaced = false; if(newBuyOrder instanceof BuyOrder) newBuyOrder = true; else if (newBuyOrder instanceof SellOrder) newBuyOrder = false; if (buyOrderPlaced && newBuyOrder) { if (orderPlaced.getStockSymbol().equals( newOrder.getStockSymbol())) { return true; } } } return false; }
Source:
<code>public static Calendar convertToUserTimeZone(Calendar time, double timeZone) { int serverOffset = time.getTimeZone().getRawOffset(); int sessionOffset = (int) (60 * 60 * 1000 * timeZone); int offset = sessionOffset - serverOffset; <START> TimeZone sessionTimeZone = getTimeZone(timeZone); <END> if (time.getTimeZone().equals(sessionTimeZone)) { return time; } else { time.setTimeZone(sessionTimeZone); time.add(Calendar.MILLISECOND, offset); } return time; }</code><technical_language>@sznicci do need this line? This of a behaviour change for issue is specific</technical_language>

Target:
public static Calendar convertToUserTimeZone(Calendar time, double timeZone) { time.add(Calendar.MILLISECOND, (int) (60 * 60 * 1000 * timeZone)); return time; }
Source:
<code>public void discardCountsBelow(double i) { List<T> labelsToRemove = new ArrayList<>(); for (Entry<T, Double> entry : map.entrySet()) { <START> final T label = entry.getKey(); <END> Double sum = entry.getValue(); if (sum == null) sum = 0.0; if (sum < i) labelsToRemove.add(label); } for (T label : labelsToRemove) { map.remove(label); } }</code><technical_language>final</technical_language>

Target:
public void discardCountsBelow(double i) { List<T> labelsToRemove = new ArrayList<>(); for (Entry<T, Double> entry : map.entrySet()) { T label = entry.getKey(); Double sum = entry.getValue(); if (sum == null) sum = 0.0; if (sum < i) labelsToRemove.add(label); } for (T label : labelsToRemove) { map.remove(label); } }
Source:
<code>public Response createOrUpdateWorldpay3dsCredentials(@PathParam("accountId") Long gatewayAccountId, @Valid WorldpayUpdate3dsFlexCredentialsRequest worldpay3dsCredentials) { return gatewayAccountService.getGatewayAccount(gatewayAccountId) <START> .map((gatewayAccountEntity) -> { <END> if (gatewayAccountEntity.getGatewayName().equalsIgnoreCase("worldpay")) { worldpay3DsFlexCredentialsService.setGatewayAccountWorldpay3ds2Credentials(worldpay3dsCredentials, gatewayAccountEntity); return Response.ok().build(); } else { return notFoundResponse("Not a Worldpay gateway account"); } }) .orElseGet(() -> notFoundResponse("Not a Worldpay gateway account")); }</code><technical_language>need this brackets</technical_language>

Target:
public Response createOrUpdateWorldpay3dsCredentials(@PathParam("accountId") Long gatewayAccountId, @Valid WorldpayUpdate3dsFlexCredentialsRequest worldpay3dsCredentials) { return gatewayAccountService.getGatewayAccount(gatewayAccountId) .filter(gatewayAccountEntity -> gatewayAccountEntity.getGatewayName().equals(PaymentGatewayName.WORLDPAY.getName())) .map(gatewayAccountEntity -> { worldpay3dsFlexCredentialsService.setGatewayAccountWorldpay3dsFlexCredentials(worldpay3dsCredentials, gatewayAccountEntity); return Response.ok().build(); }) .orElseGet(() -> notFoundResponse("Not a Worldpay gateway account")); }
Source:
<code>public void makesRequestsAgainIfTimestampRangeDoesNotIncludeCorrectModuli() { when(allocator.getRelevantModuli(UUID_ONE)).thenReturn(MODULUS_ONE); when(allocator.getRelevantModuli(UUID_TWO)).thenReturn(MODULUS_TWO); when(timestamps.getFreshTimestamps(anyInt())) .thenReturn(TIMESTAMP_ZERO) .thenReturn(TIMESTAMP_ZERO) .thenReturn(TIMESTAMP_RANGE); <START> assertThat(service.getFreshTimestampForClient(UUID_ONE)).isEqualTo(MODULUS_ONE_TIMESTAMP_IN_RANGE); <END> verify(allocator, times(3)).getRelevantModuli(UUID_ONE); verify(timestamps, times(3)).getFreshTimestamps(anyInt()); }</code><technical_language>UUID_TWO get slightly coverage</technical_language>

Target:
public void makesRequestsAgainIfTimestampRangeDoesNotIncludeCorrectModuli() { when(allocator.getRelevantModuli(UUID_ONE)).thenReturn(RESIDUE_ONE); when(allocator.getRelevantModuli(UUID_TWO)).thenReturn(RESIDUE_TWO); when(timestamps.getFreshTimestamps(anyInt())) .thenReturn(TIMESTAMP_SEVEN) .thenReturn(TIMESTAMP_SEVEN) .thenReturn(TIMESTAMP_RANGE); assertThat(service.getFreshTimestampForClient(UUID_TWO)).isEqualTo(RESIDUE_TWO_TIMESTAMP_IN_RANGE); verify(allocator, times(3)).getRelevantModuli(UUID_TWO); verify(timestamps, times(3)).getFreshTimestamps(anyInt()); }
Source:
<code>public void testFeatureAfterExcludingFolder() { String fileNameForExcluding = "AppController.java"; String pathToJavaFile = "/projects/" + PROJECT_NAME + "/src/main/java/org/eclipse/qa/examples"; doFileWatcherExcludeOperation( PROJECT_NAME + "/" + FOLDER_NAME_FOR_EXCLUDE, ADD_TO_FILE_WATCHER_EXCLUDES); projectExplorer.waitItem(PROJECT_NAME); projectExplorer.openItemByVisibleNameInExplorer(fileNameForExcluding); editor.waitActiveEditor(); terminal.selectTerminalTab(); terminal.waitTerminalConsole(); terminal.waitTerminalIsNotEmpty(); terminal.typeIntoTerminal("cd " + pathToJavaFile + Keys.ENTER); terminal.waitExpectedTextIntoTerminal(pathToJavaFile); <START> terminal.typeIntoTerminal( <END> "pwd | cat - " + fileNameForExcluding + "> temp && mv temp " + "AppController.java" + Keys.ENTER); editor.selectTabByName("AppController"); editor.waitTextNotPresentIntoEditor(pathToJavaFile); editor.clickOnCloseFileIcon("AppController"); projectExplorer.openItemByVisibleNameInExplorer(fileNameForExcluding); editor.waitActiveEditor(); editor.waitTextIntoEditor(pathToJavaFile); doFileWatcherExcludeOperation( PROJECT_NAME + "/" + FOLDER_NAME_FOR_EXCLUDE, REMOVE_FROM_FILE_WATCHER_EXCLUDES); editor.closeAllTabsByContextMenu(); }</code><technical_language>hard read multi line string. rewrote **String.format()** method</technical_language>

Target:
public void testFeatureAfterExcludingFolder() { String fileNameForExcluding = "AppController.java"; String pathToJavaFile = format("/projects/%s/src/main/java/org/eclipse/qa/examples", PROJECT_NAME); doFileWatcherExcludeOperation( PROJECT_NAME + "/" + FOLDER_NAME_FOR_EXCLUDE, ADD_TO_FILE_WATCHER_EXCLUDES); projectExplorer.waitItem(PROJECT_NAME); projectExplorer.openItemByVisibleNameInExplorer(fileNameForExcluding); editor.waitActiveEditor(); terminal.selectTerminalTab(); terminal.waitTerminalConsole(); terminal.waitTerminalIsNotEmpty(); terminal.typeIntoTerminal(format("cd %s%s", pathToJavaFile, ENTER)); terminal.waitExpectedTextIntoTerminal(pathToJavaFile); terminal.typeIntoTerminal( format( "pwd | cat - %s > temp && mv temp %s%s", fileNameForExcluding, fileNameForExcluding, ENTER)); editor.selectTabByName("AppController"); editor.waitTextNotPresentIntoEditor(pathToJavaFile); editor.clickOnCloseFileIcon("AppController"); projectExplorer.openItemByVisibleNameInExplorer(fileNameForExcluding); editor.waitActiveEditor(); editor.waitTextIntoEditor(pathToJavaFile); doFileWatcherExcludeOperation( PROJECT_NAME + "/" + FOLDER_NAME_FOR_EXCLUDE, REMOVE_FROM_FILE_WATCHER_EXCLUDES); editor.closeAllTabsByContextMenu(); }
Source:
<code>public static void main(String[] args) throws Exception { final PerformanceTestConfiguration configuration = new PerformanceTestConfiguration(args[0]); final ResponseTimeCache responseTimeCache = new ResponseTimeCache(); final GatewayMetricsReporter metricsReporter = new GatewayMetricsReporter(configuration, responseTimeCache); metricsReporter.start(); final List<PerformanceTestLifeCyleListener> lifeCyleListeners = Arrays.asList(metricsReporter); <START> for (PerformanceTestUseCase useCase : PerformanceTestUseCase.values()) { <END> if (configuration.isUseCaseEnabled(useCase)) { useCase.getUseCaseRunner().setResponseTimeCache(responseTimeCache); useCase.getUseCaseRunner().execute(configuration, lifeCyleListeners); } } }</code><technical_language>ServiceLoader instead of a hard-coded enum find PerformanceTestUseCase implementations</technical_language>

Target:
public static void main(String[] args) throws Exception { final PerformanceTestConfiguration configuration = new PerformanceTestConfiguration(args[0]); final ResponseTimeCache responseTimeCache = new ResponseTimeCache(); final GatewayMetricsReporter metricsReporter = new GatewayMetricsReporter(configuration, responseTimeCache); metricsReporter.start(); final List<PerformanceTestLifeCyleListener> lifeCyleListeners = Arrays.asList(metricsReporter); for (UseCaseRunner useCaseRunner : getUseCaseRunners()) { if (configuration.isUseCaseEnabled(useCaseRunner.getUseCaseName())) { useCaseRunner.setResponseTimeCache(responseTimeCache); useCaseRunner.execute(configuration, lifeCyleListeners); } } }