auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static void refreshFeed(Context context, Feed feed, boolean loadAllPages, boolean force) throws DownloadRequestException { Feed f; String lastUpdate = feed.hasLastUpdateFailed() ? null : feed.getLastUpdate(); if (feed.getPreferences() == null) { f = new Feed(feed.getDownload_url(), lastUpdate, feed.getTitle()); } else { f = new Feed(feed.getDownload_url(), lastUpdate, feed.getTitle(), feed.getPreferences().getUsername(), feed.getPreferences().getPassword()); } f.setId(feed.getId()); if (f.isLocalFeed()) { String path = f.getDownload_url().substring("file:".length()); Uri uri = new Uri.Builder().scheme("file").path(path).build(); f.setItems(feed.getItems()); <START> LocalFeedUpdater.updateFeed(f, context); <END> } else { DownloadRequester.getInstance().downloadFeed(context, f, loadAllPages, force); } }</code><technical_language>This changed do this: new Thread(() -> LocalFeedUpdater.updateFeed(feed, context)).start();</technical_language>

Target:
private static void refreshFeed(Context context, Feed feed, boolean loadAllPages, boolean force) throws DownloadRequestException { Feed f; String lastUpdate = feed.hasLastUpdateFailed() ? null : feed.getLastUpdate(); if (feed.getPreferences() == null) { f = new Feed(feed.getDownload_url(), lastUpdate, feed.getTitle()); } else { f = new Feed(feed.getDownload_url(), lastUpdate, feed.getTitle(), feed.getPreferences().getUsername(), feed.getPreferences().getPassword()); } f.setId(feed.getId()); if (f.isLocalFeed()) { f.setItems(feed.getItems()); new Thread(() -> LocalFeedUpdater.updateFeed(f, context)).start(); } else { DownloadRequester.getInstance().downloadFeed(context, f, loadAllPages, force); } }
Source:
<code><START> public void writeMutationAsync(Mutation m) { <END> try { MutationBatch mb = new MutationBatch(m); mb.isAsync = true; asyncBatchesAdded.incrementAndGet(); mQueue.put(mb); } catch (Exception e) { throw new RuntimeException(e); } }</code><technical_language>This method call writeMutationsAsync(List<Mutation>)</technical_language>

Target:
public void writeMutationAsync(Mutation m) { writeMutationsAsync(Collections.singletonList(m)); }
Source:
<code>public static File makeNumericDimFile(File dir, String dimension, ByteOrder order) { <START> return new File(dir, StringUtils.safeFormat("numeric_dim_%s_%s.drd", dimension, order)); <END> }</code><technical_language>crash if bad format string</technical_language>

Target:
public static File makeNumericDimFile(File dir, String dimension, ByteOrder order) { return new File(dir, StringUtils.format("numeric_dim_%s_%s.drd", dimension, order)); }
Source:
<code>private void createTempFeatureXMLFile() throws IOException, MSDKException { final Logger logger = LoggerFactory.getLogger(this.getClass()); <START> logger.info(execShellCommand(OPENMS_FEATURE_FINDER_METABO_LIBRARY_NAME + " -in " + mzMLFile.getAbsolutePath() <END> + " -out " + FEATURE_XML_FILE.getAbsolutePath())); if (!FEATURE_XML_FILE.exists()) throw new MSDKException("Could not create featureXML File"); FEATURE_XML_FILE.deleteOnExit(); }</code><technical_language>is a good practice in Java avoid combining function calls line - if exception is thrown (e.g., a NullPointerException IOException), Java runtime line number, if exception thrown logger.info() execShellCommand() mzMLFile.getAbsolutePath(). is split this separate code lines, line performing function. Again, improves code readability</technical_language>

Target:
private void createTempFeatureXMLFile() throws IOException, MSDKException { final Logger logger = LoggerFactory.getLogger(this.getClass()); if (Strings.isNullOrEmpty(OPENMS_FEATURE_FINDER_METABO_LIBRARY_NAME)) { throw new MSDKException("FeatureFinderMetabo not found. Please install OpenMS on your machine."); } final String cmdOutput = execShellCommand( OPENMS_FEATURE_FINDER_METABO_LIBRARY_NAME + " -in " + mzMLFILE_PATH + " -out " + FEATURE_XML_FILE_PATH); logger.info(cmdOutput); if (!FEATURE_XML_FILE.exists()) { String error = ""; Scanner cmdOutputParser = new Scanner(cmdOutput); while (cmdOutputParser.hasNext()) { String curLine = cmdOutputParser.nextLine(); if (curLine.toLowerCase().contains("error")) error += curLine; } cmdOutputParser.close(); throw new MSDKException("The input mzML could not be processed.\n" + error); } FEATURE_XML_FILE.deleteOnExit(); }
Source:
<code>private ResourceBundle getResourceBundle(Locale locale) { try { if (!resourceBundlesByLocale.containsKey(locale)) { <START> resourceBundlesByLocale.put(locale, ResourceBundle.getBundle(messageSource, locale)); <END> } } catch (RuntimeException e) { log.error("File: '{}' could not be loaded: {}", messageSource, e.getMessage()); log.debug("Exception", e); } return resourceBundlesByLocale.get(locale); }</code><technical_language>initializing existing localizations in constructors, need do here. other hand, logic return default locale if client locale translation</technical_language>

Target:
private synchronized ResourceBundle getResourceBundle(Locale locale) { try { if (!resourceBundlesByLocale.containsKey(locale)) { resourceBundlesByLocale.put(locale, ResourceBundle.getBundle(messageSource, locale)); } } catch (RuntimeException e) { log.error("File: '{}' could not be loaded: {}", messageSource, e.getMessage()); log.debug("Exception", e); } return resourceBundlesByLocale.get(locale); }
Source:
<code>private PushButton createButton(final Pair<T, V> item) { boolean ghostItem = isGhost(item.getFirst()); final PushButton button = new PushButton(new Image(ghostItem ? resources.increaseIcon() : resources.decreaseIcon())); button.addStyleName(style.buttonStyle()); <START> button.setEnabled(!ghostItem); <END> button.addClickHandler(ghostItem ? new ClickHandler() { @Override public void onClick(ClickEvent event) { swapAddButton(item, button); addGhostEntry(); } } : new ClickHandler() { @Override public void onClick(ClickEvent event) { removeEntry(item); } }); return button; }</code><technical_language>disable for non-ghost</technical_language>

Target:
private PushButton createButton(final Pair<T, V> item) { boolean ghostItem = isGhost(item.getFirst()); final PushButton button = new PushButton(new Image(ghostItem ? resources.increaseIcon() : resources.decreaseIcon())); button.addStyleName(style.buttonStyle()); button.setEnabled(!ghostItem); button.addClickHandler(ghostItem ? new ClickHandler() { @Override public void onClick(ClickEvent event) { ((AddRemoveRowPanel) item.getSecond().getParent()).swapButton(createButton(item)); addGhostEntry(); } } : new ClickHandler() { @Override public void onClick(ClickEvent event) { removeEntry(item); } }); return button; }
Source:
<code>private void newStream(HeadersFrame frame, Promise<Stream> promise, Stream.Listener listener) { Slot slot = new Slot(); try { int streamId = frame.getStreamId(); if (streamId <= 0) { synchronized (this) { streamId = localStreamIds.getAndAdd(2); slots.offer(slot); } PriorityFrame priority = frame.getPriority(); priority = priority == null ? null : new PriorityFrame(streamId, priority); frame = new HeadersFrame(streamId, priority, frame); } else { synchronized (this) { slots.offer(slot); } <START> } <END> fillSlotWithNewLocalStream(slot, frame, promise, listener, streamId); } catch (Throwable x) { removeSlotAndFailPromise(slot, promise, x); } }</code><technical_language>I this block of code try method throws is fillSlot.... introduction of newSlot() this cleaner</technical_language>

Target:
private void newStream(HeadersFrame frame, Promise<Stream> promise, Stream.Listener listener) { Slot slot = new Slot(); int currentStreamId = frame.getStreamId(); int streamId = reserveSlot(slot, currentStreamId); if (currentStreamId <= 0) { PriorityFrame priority = frame.getPriority(); priority = priority == null ? null : new PriorityFrame(streamId, priority.getParentStreamId(), priority.getWeight(), priority.isExclusive()); frame = new HeadersFrame(streamId, frame.getMetaData(), priority, frame.isEndStream()); } try { createLocalStream(slot, frame, promise, listener, streamId); } catch (Throwable x) { freeSlotAndFailPromise(slot, promise, x); } }
Source:
<code>private void loadMetadata(AlluxioURI path, boolean recursive) throws IOException { LoadMetadataPOptions options; try { <START> if (recursive) { <END> options = LoadMetadataPOptions.newBuilder() .setLoadDescendantType(LoadDescendantPType.ALL) .build(); } else { options = LoadMetadataPOptions.newBuilder() .setLoadDescendantType(LoadDescendantPType.ONE) .build(); } mFileSystem.loadMetadata(path, options); } catch (AlluxioException e) { throw new IOException(e.getMessage()); } }</code><technical_language>verbose. LoadMetadataPOptions.newBuilder(). .setLoadDescendantType(recursive ? LoadDescendantPType.ALL : LoadDescendantPType.ONE) .build()</technical_language>

Target:
private void loadMetadata(AlluxioURI path, boolean recursive) throws IOException { try { ListStatusPOptions options = ListStatusPOptions.newBuilder() .setRecursive(recursive).build(); mFileSystem.loadMetadata(path, options); } catch (AlluxioException e) { throw new IOException(e.getMessage()); } }
Source:
<code>public void checkCanCreateViewWithSelectFromColumns(TransactionId transactionId, Identity identity, QualifiedObjectName tableName, Set<String> columnNames) { if (shouldDenyPrivilege(identity.getUser(), tableName.getObjectName(), CREATE_VIEW_WITH_SELECT_COLUMNS)) { <START> denyCreateViewWithSelect(tableName.toString()); <END> } if (denyPrivileges.isEmpty()) { super.checkCanCreateViewWithSelectFromColumns(transactionId, identity, tableName, columnNames); } }</code><technical_language>change this other checkCanCreateViewXXX methods</technical_language>

Target:
public void checkCanCreateViewWithSelectFromColumns(TransactionId transactionId, Identity identity, QualifiedObjectName tableName, Set<String> columnNames) { if (shouldDenyPrivilege(identity.getUser(), tableName.getObjectName(), CREATE_VIEW_WITH_SELECT_COLUMNS)) { denyCreateViewWithSelect(tableName.toString(), identity); } if (denyPrivileges.isEmpty()) { super.checkCanCreateViewWithSelectFromColumns(transactionId, identity, tableName, columnNames); } }
Source:
<code>public void readNodesFromXML() { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder; try { dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(nodeXMLfile); doc.getDocumentElement().normalize(); nodes = new ArrayList<ArrayList<String>>(); NodeList nList = doc.getElementsByTagName("node"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; ArrayList<String> info = new ArrayList<String>(); info.add(eElement.getElementsByTagName("id").item(0).getTextContent()); info.add(eElement.getElementsByTagName("cluster_ip").item(0).getTextContent()); nodes.add(info); } } } catch (ParserConfigurationException e) { <START> System.err.println(e); <END> } catch (SAXException e) { System.err.println(e); } catch (IOException e) { System.err.println(e); } }</code><technical_language>file prints error messages. Is practice? a logger? exception through</technical_language>

Target:
public void readNodesFromXML() throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder; dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(nodeXMLfile); doc.getDocumentElement().normalize(); nodes = new ArrayList<ArrayList<String>>(); NodeList nList = doc.getElementsByTagName("node"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; ArrayList<String> info = new ArrayList<String>(); info.add(eElement.getElementsByTagName("id").item(0).getTextContent()); info.add(eElement.getElementsByTagName("cluster_ip").item(0).getTextContent()); nodes.add(info); } } }
Source:
<code>public WorkspaceCache( ExecutionContext context, String repositoryKey, String workspaceName, WorkspaceCache systemWorkspace, DocumentStore documentStore, DocumentTranslator translator, NodeKey rootKey, ConcurrentMap<NodeKey, CachedNode> cache, ChangeBus changeBus ) { this.context = context; this.documentStore = documentStore; this.changeBus = changeBus; this.translator = translator; this.rootKey = rootKey; this.childReferenceForRoot = new ChildReference(rootKey, Path.ROOT_NAME, 1); this.repositoryKey = repositoryKey; this.workspaceName = workspaceName; this.workspaceKey = rootKey.getWorkspaceKey(); this.sourceKey = rootKey.getSourceKey(); this.pathFactory = context.getValueFactories().getPathFactory(); this.nameFactory = context.getValueFactories().getNameFactory(); this.nodesByKey = cache; if (systemWorkspace != null) { this.systemChangeNotifier = new SystemChangeNotifier(systemWorkspace.getWorkspaceName()); this.nonSystemChangeNotifier = new NonSystemChangeNotifier(systemWorkspace.getWorkspaceName()); this.changeBus.registerInThread(this.systemChangeNotifier); this.changeBus.register(this.nonSystemChangeNotifier); <START> } else if (this.changeBus != null) { <END> this.nonSystemChangeNotifier = null; this.systemChangeNotifier = new SystemChangeNotifier(this.workspaceName); this.changeBus.registerInThread(this.systemChangeNotifier); } else { this.systemChangeNotifier = null; this.nonSystemChangeNotifier = null; } }</code><technical_language>changeBus null ? If yes, scope of statement broader</technical_language>

Target:
public WorkspaceCache( ExecutionContext context, String repositoryKey, String workspaceName, WorkspaceCache systemWorkspace, DocumentStore documentStore, DocumentTranslator translator, NodeKey rootKey, ConcurrentMap<NodeKey, CachedNode> cache, ChangeBus changeBus ) { assert context != null; assert repositoryKey != null; assert workspaceName != null; assert documentStore != null; assert translator != null; assert rootKey != null; assert cache != null; assert changeBus != null; this.context = context; this.documentStore = documentStore; this.changeBus = changeBus; this.translator = translator; this.rootKey = rootKey; this.childReferenceForRoot = new ChildReference(rootKey, Path.ROOT_NAME, 1); this.repositoryKey = repositoryKey; this.workspaceName = workspaceName; this.workspaceKey = rootKey.getWorkspaceKey(); this.sourceKey = rootKey.getSourceKey(); this.pathFactory = context.getValueFactories().getPathFactory(); this.nameFactory = context.getValueFactories().getNameFactory(); this.nodesByKey = cache; if (systemWorkspace != null) { this.systemChangeNotifier = new SystemChangeNotifier(systemWorkspace.getWorkspaceName()); this.nonSystemChangeNotifier = new NonSystemChangeNotifier(systemWorkspace.getWorkspaceName()); this.changeBus.registerInThread(this.systemChangeNotifier); this.changeBus.register(this.nonSystemChangeNotifier); } else { this.nonSystemChangeNotifier = null; this.systemChangeNotifier = new SystemChangeNotifier(this.workspaceName); this.changeBus.registerInThread(this.systemChangeNotifier); } }
Source:
<code>public void addToList(File directory) { try { File[] allfiles = directory.listFiles(); <START> for (int i = 0; i < allfiles.length; i++) { <END> if (allfiles[i].length() >= 4 && allfiles[i].toString().endsWith(".mp3")) { list.add(allfiles[i].toString()); } else if (allfiles[i].isDirectory()) { FolderLoader loader = new FolderLoader(allfiles[i].toString()); File submap = new File(allfiles[i].toString()); loader.addToList(submap); list.addAll(loader.getList()); } } } catch (NullPointerException e) { System.out.println("No such directory"); } }</code><technical_language>A foreach loop a lot more readable. Lines 34-36 replaced by: for(File file : directory.listFiles()) { allfiles[i] simply file</technical_language>

Target:
private void addToList(File directory) { try { for (File file : directory.listFiles()) { if (file.length() >= 4 && file.toString().endsWith(".mp3")) { list.add(file.toString()); } else if (file.isDirectory()) { this.addToList(file); } } } catch (NullPointerException e) { System.out.println("No such directory"); } }
Source:
<code>protected void execute(Context context) throws SQLException { long sonarUsersGroupId = selectSonarUsersGroup(context); MassUpdate massUpdate = context.prepareMassUpdate().rowPluralName("users"); massUpdate.select("SELECT u.id FROM users u " + "WHERE u.active=? AND NOT EXISTS " + <START> "(SELECT 1 FROM groups_users gu " + <END> "INNER JOIN groups g on g.id=gu.group_id AND g.name=? " + "WHERE gu.user_id=u.id)") .setBoolean(1, true) .setString(2, SONAR_USERS_NAME); massUpdate.update("INSERT INTO groups_users (user_id, group_id) values (?, ?)"); massUpdate.execute((row, update) -> { update.setLong(1, row.getLong(1)); update.setLong(2, sonarUsersGroupId); return true; }); }</code><technical_language>I understand sonarUsersGroupId simply query: "SELECT u.id " + "FROM users u " + "WHERE u.active=? EXISTS " + "(SELECT 1 groups_users gu " + "WHERE gu.user_id=u.id gu.group_id=?)"</technical_language>

Target:
protected void execute(Context context) throws SQLException { long sonarUsersGroupId = selectSonarUsersGroup(context); MassUpdate massUpdate = context.prepareMassUpdate().rowPluralName("users"); massUpdate.select("SELECT u.id FROM users u " + "WHERE u.active=? AND NOT EXISTS " + "(SELECT 1 FROM groups_users gu WHERE gu.user_id=u.id AND gu.group_id=?)") .setBoolean(1, true) .setLong(2, sonarUsersGroupId); massUpdate.update("INSERT INTO groups_users (user_id, group_id) values (?, ?)"); massUpdate.execute((row, update) -> { update.setLong(1, row.getLong(1)); update.setLong(2, sonarUsersGroupId); return true; }); }
Source:
<code>public void testValidateNameSizeImportAsCloned() { <START> checkVmName(true, StringUtils.repeat("A", 300)); <END> }</code><technical_language>I create a string includes more letter 'A'. Possibly unicode (if support for this field) other (supported) standard characters. repeat entire string fill requested size pad</technical_language>

Target:
public void testValidateNameSizeImportAsCloned() { checkVmName(true, StringUtils.repeat("aA0._", 60)); }
Source:
<code>void partialBinaryOperator() { assertThat(parseErrorFromParsing("& foo")).contains("& at <0> missing lhs operand"); <START> assertThat(parseErrorFromParsing("foo |")).contains("| at <1> missing rhs operand"); <END> }</code><technical_language>error messages pretty good! wondering store character index for token emit part of error message instead of "token index". Thoughts</technical_language>

Target:
void partialBinaryOperator() { assertThat(parseErrorFromParsing("& foo")).contains("& at <0> missing lhs operand"); assertThat(parseErrorFromParsing("foo |")).contains("| at <4> missing rhs operand"); }
Source:
<code>private static void setParameterTypes(Symbol symbol, FunctionDef functionDef) { if (symbol.is(Symbol.Kind.FUNCTION)) { FunctionSymbolImpl functionSymbol = (FunctionSymbolImpl) symbol; ParameterList parameters = functionDef.parameters(); if (parameters != null) { <START> functionSymbol.parameters().clear(); <END> functionSymbol.addParameters(parameters); } } else if (symbol.is(Symbol.Kind.AMBIGUOUS)) { ((AmbiguousSymbol) symbol).alternatives().stream().filter(s -> s.equals(functionDef.name().symbol())).findFirst().ifPresent(s -> setParameterTypes(s, functionDef)); } }</code><technical_language>I I prefer a method setParametersDeclaredType(ParameterList parameterList) instead of separate methods clear add</technical_language>

Target:
private static void setParameterTypes(Symbol symbol, FunctionDef functionDef) { if (symbol.is(Symbol.Kind.FUNCTION)) { FunctionSymbolImpl functionSymbol = (FunctionSymbolImpl) symbol; ParameterList parameters = functionDef.parameters(); if (parameters != null) { functionSymbol.setParametersWithType(parameters); } } else if (symbol.is(Symbol.Kind.AMBIGUOUS)) { FunctionSymbol funcDefSymbol = ((FunctionDefImpl) functionDef).functionSymbol(); if (funcDefSymbol != null) { setParameterTypes(funcDefSymbol, functionDef); } } }
Source:
<code>public static boolean hasPostConstruct(Class<?> clazz, Function<Method, Boolean> validateParameterCount) { <START> for (Method m : clazz.getDeclaredMethods()) <END> { if (m.getAnnotation(PostConstruct.class) != null) { if (validatePostConstructMethod(m, validateParameterCount)) { return true; } } } return false; }</code><technical_language>Hmmm. right, getMethods() returns public methods. other hand, getDeclaredMethods() inherited methods. needs call getDeclaredMethods() while recursively visiting superclasses. Thank you</technical_language>

Target:
public static boolean hasPostConstruct(Class<?> clazz, Function<Method, Boolean> validateParameterCount) { for (Method m : clazz.getDeclaredMethods()) { if (m.getAnnotation(PostConstruct.class) != null) { if (validatePostConstructMethod(m, validateParameterCount)) { return true; } } } Class<?> parent = clazz.getSuperclass(); if (parent != null && parent != Object.class) { return hasPostConstruct(parent, validateParameterCount); } return false; }
Source:
<code>public void testRemoveValueNoStoreEntryUnequalCacheWriterEntry() throws Exception { final MockStore realStore = new MockStore(Collections.<String, String>emptyMap()); this.store = spy(realStore); final MockCacheWriter realCache = new MockCacheWriter(Collections.singletonMap("key", "unequalValue")); final Ehcache<String, String> ehcache = this.getEhcache(realCache); assertFalse(ehcache.remove("key", "value")); verify(this.store).computeIfPresent(eq("key"), getAnyBiFunction()); verifyZeroInteractions(this.spiedResilienceStrategy); assertThat(realStore.getMap().containsKey("key"), is(false)); assertThat(realCache.getEntries().get("key"), is(equalTo("unequalValue"))); <START> validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.RemoveOutcome.FAILURE)); END> }</code><technical_language>Sounds ok outcome matches false return</technical_language>

Target:
public void testRemoveValueNoStoreEntryUnequalCacheWriterEntry() throws Exception { final FakeStore fakeStore = new FakeStore(Collections.<String, String>emptyMap()); this.store = spy(fakeStore); final FakeCacheWriter fakeWriter = new FakeCacheWriter(Collections.singletonMap("key", "unequalValue")); final Ehcache<String, String> ehcache = this.getEhcache(fakeWriter); assertFalse(ehcache.remove("key", "value")); verify(this.store).computeIfPresent(eq("key"), getAnyBiFunction()); verifyZeroInteractions(this.spiedResilienceStrategy); assertThat(fakeStore.getEntryMap().containsKey("key"), is(false)); assertThat(fakeWriter.getEntryMap().get("key"), is(equalTo("unequalValue"))); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.RemoveOutcome.FAILURE)); }
Source:
<code>private boolean validateKeyFromKeyStore(KeyStore store, String alias) throws KeyStoreException { Certificate[] certifChain = null; logger.debug("Testing " + alias); Certificate cert = store.getCertificate(alias); if (cert != null) { certifChain = new Certificate[]{cert}; } else { certifChain = store.getCertificateChain(alias); } if(certifChain == null) { <START> logger.warn("Alias \"" + alias + "\" not found"); <END> return false; } int len = certifChain.length; boolean res = true; Date nextMonth = new Date(); nextMonth.setMonth((nextMonth.getMonth()%12) + 1); for (int i = 0; i < len; i++) { if(certifChain[i].getType().equals("X.509")) { res = res && validateCertificate((X509Certificate) certifChain[i], nextMonth); } } logger.debug(alias + " is valid: " + res); return res; }</code><technical_language>in form of a Messages.getString(...) message for i18n</technical_language>

Target:
private void validateKeyFromKeyStore(KeyStore store, String alias) throws KeyStoreException, CertificateExpiredException, CertificateNotYetValidException { Certificate[] certifChain = null; Certificate cert = store.getCertificate(alias); if (cert != null) { certifChain = new Certificate[]{cert}; } else { certifChain = store.getCertificateChain(alias); } if(certifChain == null) { throw new KeyStoreException("Alias not found: " + alias); } int len = certifChain.length; Date nextMonth = new Date(); nextMonth.setMonth((nextMonth.getMonth()%12) + 1); for (int i = 0; i < len; i++) { if(certifChain[i].getType().equals("X.509")) { X509Certificate xCertif = (X509Certificate)certifChain[i]; boolean valid = false; try { xCertif.checkValidity(); valid = true; xCertif.checkValidity(nextMonth); } catch (CertificateExpiredException e) { if(!valid) { throw new CertificateExpiredException("Alias: " + alias + ". The folowing certificate has expired\n" + xCertif); } logger.warn("Alias: " + alias + ". The following certificate will expire soon\n" + xCertif); } catch (CertificateNotYetValidException e) { throw new CertificateNotYetValidException("Alias: " + alias + ". The following certificate is not yet valid\n" + xCertif); } } } return; }
Source:
<code><START> public void testDataSyncToPassiveCustomBatchSize() throws Exception { <END> System.setProperty(ClusterTierActiveEntity.SYNC_DATA_SIZE_PROP, "512"); try { prepareAndRunActiveEntityForPassiveSync((activeEntity, concurrencyKey) -> { @SuppressWarnings("unchecked") PassiveSynchronizationChannel<EhcacheEntityMessage> syncChannel = mock(PassiveSynchronizationChannel.class); activeEntity.synchronizeKeyToPassive(syncChannel, concurrencyKey); verify(syncChannel, atLeast(1)).synchronizeToPassive(any(EhcacheDataSyncMessage.class)); }); } finally { System.clearProperty(ClusterTierActiveEntity.SYNC_DATA_SIZE_PROP); } }</code><technical_language>This needs changing code invoke context issues. This fixed in PR I checked</technical_language>

Target:
public void testDataSyncToPassiveCustomBatchSize() throws Exception { System.setProperty(ClusterTierActiveEntity.SYNC_DATA_SIZE_PROP, "512"); try { prepareAndRunActiveEntityForPassiveSync((activeEntity, concurrencyKey) -> { @SuppressWarnings("unchecked") PassiveSynchronizationChannel<EhcacheEntityMessage> syncChannel = mock(PassiveSynchronizationChannel.class); activeEntity.synchronizeKeyToPassive(syncChannel, concurrencyKey); verify(syncChannel, atLeast(2)).synchronizeToPassive(any(EhcacheDataSyncMessage.class)); }); } finally { System.clearProperty(ClusterTierActiveEntity.SYNC_DATA_SIZE_PROP); } }
Source:
<code>private static void visitParameterList( @NotNull ProblemsHolder holder, @Nullable GoParameters parameters, String ownerType, String what) { if (parameters == null || parameters.getParameterDeclarationList().isEmpty()) return; ProgressManager.checkCanceled(); boolean hasNamed = false; boolean hasUnnamed = false; for (GoParameterDeclaration parameterDeclaration : parameters.getParameterDeclarationList()) { if (parameterDeclaration.getParamDefinitionList().isEmpty()) { hasUnnamed = true; } else { hasNamed = true; } } <START> if (hasNamed && hasUnnamed) { <END> holder.registerProblem( parameters, ownerType + " has both named and unnamed " + what + " <code>#ref</code> #loc", ProblemHighlightType.GENERIC_ERROR_OR_WARNING); } }</code><technical_language>for</technical_language>

Target:
private static void visitParameterList( @NotNull ProblemsHolder holder, @Nullable GoParameters parameters, String ownerType, String what) { if (parameters == null || parameters.getParameterDeclarationList().isEmpty()) return; ProgressManager.checkCanceled(); boolean hasNamed = false; boolean hasUnnamed = false; for (GoParameterDeclaration parameterDeclaration : parameters.getParameterDeclarationList()) { if (parameterDeclaration.getParamDefinitionList().isEmpty()) { hasUnnamed = true; } else { hasNamed = true; } if (hasNamed && hasUnnamed) { holder.registerProblem( parameters, ownerType + " has both named and unnamed " + what + " <code>#ref</code> #loc", ProblemHighlightType.GENERIC_ERROR_OR_WARNING); return; } } }
Source:
<code>private Map<String,String> getMapFromRawClientInfo( String clientInfo) { <START> Map<String,String> clientInfoMap = new LinkedHashMap<>(); <END> List<String> myList = new ArrayList<String>(Arrays.asList(clientInfo.split(" "))); for (String entry : myList) { String[] kvArray = entry.split("="); clientInfoMap.put(kvArray[0], (kvArray.length ==2)?kvArray[1]:"" ); } return clientInfoMap; }</code><technical_language>is LinkedHashMap required? I is more efficient: java String[] entries = clientInfo.split(" "); Map<String,String> clientInfoMap = new LinkedHashMap<>(entries.length); for (String entry : entries) { String[] kvArray = entry.split("="); clientInfoMap.put(kvArray[0], (kvArray.length ==2)?kvArray[1]:"" ); }</technical_language>

Target:
private Map<String,String> getMapFromRawClientInfo( String clientInfo) { String[] entries = clientInfo.split(" "); Map<String,String> clientInfoMap = new LinkedHashMap<>(entries.length); for (String entry : entries) { String[] kvArray = entry.split("="); clientInfoMap.put(kvArray[0], (kvArray.length ==2)?kvArray[1]:"" ); } return clientInfoMap; }
Source:
<code>public ModelNode execute(Operation operation) throws IOException { <START> return execute(operation.getOperation()); <END> }</code><technical_language>Operation InputStreams attached. a translate HTTP, figure out. throw exception if attachments</technical_language>

Target:
public ModelNode execute(Operation operation) throws IOException { if (!operation.getInputStreams().isEmpty()) { throw new IllegalStateException("Operation has one or more attachments which is not allowed."); } return execute(operation.getOperation()); }
Source:
<code>public String toString() { String roles = ""; if (!this.isEmpty()) { for (String role: this.keySet()) { <START> roles += role.toLowerCase() + this.get(role) + ","; <END> } } return getClass().getSimpleName() + "[" + roles + "]"; }</code><technical_language>upperCase format too</technical_language>

Target:
public String toString() { String roles = ""; if (!this.isEmpty()) { for (String role: this.keySet()) { roles += role + this.get(role) + ","; } } return getClass().getSimpleName() + "[" + roles + "]"; }
Source:
<code>public synchronized boolean isUITestRunning() { if (isUITestRunning == null) { boolean istest; try { Class.forName("org.openobservatory.ooniprobe.AutomateScreenshotsTest"); istest = true; } catch (ClassNotFoundException e) { istest = false; } <START> isUITestRunning = new AtomicBoolean (istest); <END> } return isUITestRunning.get(); }</code><technical_language>I need cache this result, return false try in try catch</technical_language>

Target:
public boolean isUITestRunning() { try { Class.forName("org.openobservatory.ooniprobe.AutomateScreenshotsTest"); return true; } catch (ClassNotFoundException e) { return false; } }
Source:
<code>private void removeTemplateBackup() { <START> AsyncDataProvider.getInstance().getDataCentersByStorageDomain(new AsyncQuery(this, new INewAsyncCallback() { <END> @Override public void onSuccess(Object model, Object returnValue) { TemplateBackupModel templateBackupModel = (TemplateBackupModel) model; ArrayList<StoragePool> pools = (ArrayList<StoragePool>) returnValue; if (pools != null && pools.size() > 0) { StoragePool pool = pools.get(0); ArrayList<VdcActionParametersBase> prms = new ArrayList<VdcActionParametersBase>(); for (Object a : templateBackupModel.getSelectedItems()) { VmTemplate template = (VmTemplate) a; prms.add(new VmTemplateImportExportParameters(template.getId(), getEntity().getId(), pool.getId())); } Frontend.getInstance().runMultipleAction(VdcActionType.RemoveVmTemplateFromImportExport, prms); cancel(); } } }), getEntity().getId()); }</code><technical_language>do u need call (it's called in line 100)</technical_language>

Target:
private void removeTemplateBackup() { ArrayList<VdcActionParametersBase> prms = new ArrayList<VdcActionParametersBase>(); for (Object a : getSelectedItems()) { VmTemplate template = (VmTemplate) a; prms.add(new VmTemplateImportExportParameters(template.getId(), getEntity().getId(), pool.getId())); } Frontend.getInstance().runMultipleAction(VdcActionType.RemoveVmTemplateFromImportExport, prms); cancel(); }
Source:
<code>public ToStringHelper string() { return super.string() .add("app", app) .add("script", script) .add("location", locations) .add("port", port) .add("noConsole", noConsole) <START> .add("noShutdwonOnExit", noShutdownOnExit) <END> .add("stopOnKeyPress", stopOnKeyPress); }</code><technical_language>add("noShutdownOnExit", noShutdownOnExit) (was shutd **wo** n)</technical_language>

Target:
public ToStringHelper string() { return super.string() .add("app", app) .add("script", script) .add("location", locations) .add("port", port) .add("noConsole", noConsole) .add("noShutdownOnExit", noShutdownOnExit) .add("stopOnKeyPress", stopOnKeyPress); }
Source:
<code>default <R> Try<R> collect(PartialFunction<? super T, ? extends R> partialFunction){ Objects.requireNonNull(partialFunction, "partialFunction is null"); final Try<T> valueInDomain = filter(partialFunction::isDefinedAt); if (valueInDomain.isFailure()) { return (Failure<R>) valueInDomain; } else { try { return new Success<>(partialFunction.apply(valueInDomain.get())); } catch (Throwable t) { return new Failure<>(t); } <START> } <END> }</code><technical_language>Please java Objects.requireNonNull(partialFunction, "partialFunction is null"); return filter(partialFunction::isDefinedAt).map(partialFunction::apply); (Yes, please map instead of mapTry - difference of JIT magic)</technical_language>

Target:
default <R> Try<R> collect(PartialFunction<? super T, ? extends R> partialFunction){ Objects.requireNonNull(partialFunction, "partialFunction is null"); return filter(partialFunction::isDefinedAt).map(partialFunction::apply); }
Source:
<code>public boolean reschedule(String cronExpression) { try { Trigger trigger = newTrigger() .withSchedule( cronSchedule(cronExpression) ) .build(); scheduler.rescheduleJob(triggerKey, trigger); this.triggerKey = trigger.getKey(); this.cancelled = false; this.cronExpression = cronExpression; this.terminated = false; return true; } catch (SchedulerException e) { logger.warn("An error occured while rescheduling the job '{}': {}", new String[] { jobKey.toString(), e.getMessage() }); return false; <START> } <END> }</code><technical_language>copied reschedule() replaced Trigger creation. For sake of Don't-Repeat-Yourself (DRY) please extract Trigger-Creation methods resulting method reschedules Job properly</technical_language>

Target:
public boolean reschedule(String cronExpression) { try { Trigger oldTrigger = scheduler.getTrigger(triggerKey); TriggerBuilder tb = oldTrigger.getTriggerBuilder(); trigger = tb .withDescription("cron " + cronExpression) .withSchedule( cronSchedule(cronExpression) ) .build(); return update(trigger); } catch (Exception e) { logger.warn("An error occured while creating a new timer for rescheduling the job '{}': {}", new String[] { jobKey.toString(), e.getMessage() }); return false; } }
Source:
<code>public final void close() throws SQLException { if (delegate != ClosedConnection.CLOSED_CONNECTION) { leakTask.cancel(); <START> closeOpenStatements(); <END> try { if (isCommitStateDirty) { lastAccess = clockSource.currentTime(); if (!poolEntry.isAutoCommit) { delegate.rollback(); LOGGER.debug("{} - Executed rollback on connection due to dirty commit state on close().", poolEntry.parentPool, delegate); } } if (isConnectionStateDirty) { poolEntry.resetConnectionState(); lastAccess = clockSource.currentTime(); } delegate.clearWarnings(); } catch (SQLException e) { if (!poolEntry.aborted) { throw checkException(e); } } finally { delegate = ClosedConnection.CLOSED_CONNECTION; poolEntry.releaseConnection(lastAccess); } } }</code><technical_language>closeOpenStatements() accidentally moved out of try block ... move back</technical_language>

Target:
public final void close() throws SQLException { if (delegate != ClosedConnection.CLOSED_CONNECTION) { leakTask.cancel(); try { closeOpenStatements(); if (isCommitStateDirty) { lastAccess = clockSource.currentTime(); if (!poolEntry.isAutoCommit) { delegate.rollback(); LOGGER.debug("{} - Executed rollback on connection due to dirty commit state on close().", poolEntry.parentPool, delegate); } } if (isConnectionStateDirty) { poolEntry.resetConnectionState(); lastAccess = clockSource.currentTime(); } delegate.clearWarnings(); } catch (SQLException e) { if (!poolEntry.aborted) { throw checkException(e); } } finally { delegate = ClosedConnection.CLOSED_CONNECTION; poolEntry.releaseConnection(lastAccess); } } }
Source:
<code>public boolean isCompatibleWith(LuceneIndexSchemaFieldNode<?> other) { return converter.isDslCompatibleWith( other.converter ) && Objects.equals( codec, other.codec ) && predicateBuilderFactory.isDslCompatibleWith( other.predicateBuilderFactory ) && Objects.equals( sortContributor, other.sortContributor ) <START> && Objects.equals( projectionBuilderFactory, other.projectionBuilderFactory ); <END> }</code><technical_language>Ok, discussed HipChat, drop support for index-sensitive projections for now, restore (maybe)</technical_language>

Target:
public boolean isCompatibleWith(LuceneIndexSchemaFieldNode<?> other) { return converter.isDslCompatibleWith( other.converter ) && Objects.equals( codec, other.codec ) && predicateBuilderFactory.isDslCompatibleWith( other.predicateBuilderFactory ) && Objects.equals( sortContributor, other.sortContributor ) && projectionBuilderFactory.isDslCompatibleWith( other.projectionBuilderFactory ); }
Source:
<code>public void createDatabase(final String name) { Preconditions.checkArgument(!name.contains("-"), "Databasename cant contain -"); String createDatabaseQueryString = String.format("CREATE DATABASE IF NOT EXISTS \"%s\"", name); <START> DefaultArtifactVersion versionCurrent = new DefaultArtifactVersion(this.version()); <END> DefaultArtifactVersion version1 = new DefaultArtifactVersion("1.0.0"); if (versionCurrent.compareTo(version1) >= 0 ) { createDatabaseQueryString = String.format("CREATE DATABASE \"%s\"", name); } this.influxDBService.query(this.username, this.password, createDatabaseQueryString); }</code><technical_language>Wouldnt sufficient check for this.version().startsWith("0.") check for influxdb version < 1</technical_language>

Target:
public void createDatabase(final String name) { Preconditions.checkArgument(!name.contains("-"), "Databasename cant contain -"); String createDatabaseQueryString = String.format("CREATE DATABASE \"%s\"", name); if ( this.version().startsWith("0.") ) { createDatabaseQueryString = String.format("CREATE DATABASE IF NOT EXISTS \"%s\"", name); } this.influxDBService.query(this.username, this.password, createDatabaseQueryString); }
Source:
<code>public long waitFor1(long sequence, Sequence cursorSequence, Sequence dependentSequence, com.lmax.disruptor.SequenceBarrier barrier) throws AlertException, InterruptedException, SuspendExecution { long availableSequence; if ((availableSequence = cursorSequence.get()) < sequence) { Object token = processorNotifyCondition.register(); try { for (int i = 0; (availableSequence = cursorSequence.get()) < sequence; i++) { barrier.checkAlert(); <START> processorNotifyCondition.await(i, 1, TimeUnit.NANOSECONDS); <END> } } finally { processorNotifyCondition.unregister(token); } } while ((availableSequence = dependentSequence.get()) < sequence) { barrier.checkAlert(); } return availableSequence; }</code><technical_language>that. This is a blocking strategy, block</technical_language>

Target:
public long waitFor1(long sequence, Sequence cursorSequence, Sequence dependentSequence, com.lmax.disruptor.SequenceBarrier barrier) throws AlertException, InterruptedException, SuspendExecution { long availableSequence; if ((availableSequence = cursorSequence.get()) < sequence) { Object token = processorNotifyCondition.register(); try { for (int i = 0; (availableSequence = cursorSequence.get()) < sequence; i++) { barrier.checkAlert(); processorNotifyCondition.await(i); } } finally { processorNotifyCondition.unregister(token); } } while ((availableSequence = dependentSequence.get()) < sequence) { barrier.checkAlert(); } return availableSequence; }
Source:
<code>public Void visitAnnotation(final AnnotationTree node, final Void p) { AnnotationMirror anno = TreeUtils.annotationFromAnnotationTree(node); if (atypeFactory.isPredicate(anno)) { String errorMessage = atypeFactory.isValidPredicate(anno); if (errorMessage != null) { <START> checker.report( <END> node, new DiagMessage(Diagnostic.Kind.ERROR, "predicate.invalid", errorMessage)); return null; } } return super.visitAnnotation(node, p); }</code><technical_language>reportError report</technical_language>

Target:
public Void visitAnnotation(final AnnotationTree node, final Void p) { AnnotationMirror anno = TreeUtils.annotationFromAnnotationTree(node); if (atypeFactory.isPredicate(anno)) { String errorMessage = atypeFactory.isValidPredicate(anno); if (errorMessage != null) { checker.reportError(node, "predicate.invalid", errorMessage); } } return super.visitAnnotation(node, p); }
Source:
<code>public ManageDomainsResult(ManageDomainsResultEnum enumResult, String... params) { <START> this("Default error.", enumResult, params); <END> }</code><technical_language>blank null, "Default error"</technical_language>

Target:
public ManageDomainsResult(ManageDomainsResultEnum enumResult, String... params) { this("", enumResult, params); }
Source:
<code>public SignInPage clickForgotPasswordLink() { <START> forgottenPasswordLink.click(); <END> return this; }</code><technical_language>wait for element clickable click</technical_language>

Target:
public SignInPage clickForgotPasswordLink() { wait.forElementClickable(forgottenPasswordLink); forgottenPasswordLink.click(); return this; }
Source:
<code>private void assertOneMessage(String fileName, String expectedMessage) throws Exception { File sourceFile = new File(baseDir, fileName); LocalizedMessages messages = processFile(sourceFile, check); assertThat(messages, is(not(nullValue()))); <START> assertThat(messages.getMessages().isEmpty(), is(false)); <END> assertThat(messages.getMessages().size(), is(1)); assertThat(messages.getMessages().first().getMessage(), is(expectedMessage)); }</code><technical_language>Redundant next assertion</technical_language>

Target:
private void assertOneMessage(String fileName, String expectedMessage) throws Exception { File sourceFile = new File(baseDir, fileName); LocalizedMessages messages = processFile(sourceFile, check); assertThat(messages.getMessages().isEmpty(), is(false)); assertThat(messages.getMessages().size(), is(1)); assertThat(messages.getMessages().first().getMessage(), is(expectedMessage)); }
Source:
<code>public void configure(Binder binder) { if (!slackConfiguration.isPresent()) { LOG.info("Slack is not configured, not binding slack related resources or slack build notification visitors"); return; } <START> binder.bind(SlackSession.class).toInstance(makeNewSlackSession()); <END> binder.bind(SlackMessageBuildingUtils.class); repositoryBuildVisitorMultibinder.addBinding().to(SlackDmNotificationVisitor.class); repositoryBuildVisitorMultibinder.addBinding().to(SlackRoomNotificationVisitor.class); binder.bind(UserFeedbackResource.class); binder.bind(SlackClientWrapper.class); binder.bind(SlackResource.class); if (slackConfiguration.get().getFeedbackRoom().isPresent()) { binder.bindConstant().annotatedWith(Names.named(SLACK_FEEDBACK_ROOM)).to(slackConfiguration.get().getFeedbackRoom().get()); binder.bind(UserFeedbackResource.class); } else { LOG.info("Not configuring feedback endpoint -- no room configured"); } }</code><technical_language>create a provider method instead? want session a singleton? i.e. a single slack session app lifecycle? Do need get a new session instance time inject session class</technical_language>

Target:
public void configure(Binder binder) { if (!slackConfiguration.isPresent()) { LOG.info("Slack is not configured, not binding slack related resources or slack build notification visitors"); return; } Multibinder<RepositoryBuildVisitor> repositoryBuildVisitorMultibinder = Multibinder.newSetBinder(binder, RepositoryBuildVisitor.class); repositoryBuildVisitorMultibinder.addBinding().to(SlackDmNotificationVisitor.class); repositoryBuildVisitorMultibinder.addBinding().to(SlackRoomNotificationVisitor.class); binder.bind(SlackSession.class).toInstance(SlackSessionFactory.createWebSocketSlackSession(slackConfiguration.get().getSlackApiToken())); binder.bind(SlackResource.class); binder.bind(UserFeedbackResource.class); }
Source:
<code>public void readFields(DataInput input) throws IOException { byte[] tableNameBytes = Bytes.readByteArray(input); PName tableName = new PNameImpl(tableNameBytes); PTableType tableType = PTableType.values()[WritableUtils.readVInt(input)]; long sequenceNumber = WritableUtils.readVLong(input); long timeStamp = input.readLong(); byte[] pkNameBytes = Bytes.readByteArray(input); String pkName = pkNameBytes.length == 0 ? null : Bytes.toString(pkNameBytes); Integer bucketNum = WritableUtils.readVInt(input); int nColumns = WritableUtils.readVInt(input); List<PColumn> columns = Lists.newArrayListWithExpectedSize(nColumns); for (int i = 0; i < nColumns; i++) { PColumn column = new PColumnImpl(); column.readFields(input); columns.add(column); } Map<String, byte[][]> guidePosts = new HashMap<String, byte[][]>(); int size = WritableUtils.readVInt(input); for (int i=0; i<size; i++) { String key = WritableUtils.readString(input); int valueSize = WritableUtils.readVInt(input); byte[][] value = new byte[valueSize][]; for (int j=0; j<valueSize; j++) { value[j] = Bytes.readByteArray(input); } guidePosts.put(key, value); } PTableStats stats = new PTableStatsImpl(guidePosts); init(tableName, tableType, timeStamp, sequenceNumber, pkName, <START> bucketNum == QueryConstants.NO_SALTING ? null : bucketNum, columns, stats); <END> }</code><technical_language>move QueryConstants.NO_SALTING constant a private static here? I this'll place need it</technical_language>

Target:
public void readFields(DataInput input) throws IOException { byte[] tableNameBytes = Bytes.readByteArray(input); PName tableName = new PNameImpl(tableNameBytes); PTableType tableType = PTableType.values()[WritableUtils.readVInt(input)]; long sequenceNumber = WritableUtils.readVLong(input); long timeStamp = input.readLong(); byte[] pkNameBytes = Bytes.readByteArray(input); String pkName = pkNameBytes.length == 0 ? null : Bytes.toString(pkNameBytes); Integer bucketNum = WritableUtils.readVInt(input); int nColumns = WritableUtils.readVInt(input); List<PColumn> columns = Lists.newArrayListWithExpectedSize(nColumns); for (int i = 0; i < nColumns; i++) { PColumn column = new PColumnImpl(); column.readFields(input); columns.add(column); } Map<String, byte[][]> guidePosts = new HashMap<String, byte[][]>(); int size = WritableUtils.readVInt(input); for (int i=0; i<size; i++) { String key = WritableUtils.readString(input); int valueSize = WritableUtils.readVInt(input); byte[][] value = new byte[valueSize][]; for (int j=0; j<valueSize; j++) { value[j] = Bytes.readByteArray(input); } guidePosts.put(key, value); } PTableStats stats = new PTableStatsImpl(guidePosts); init(tableName, tableType, timeStamp, sequenceNumber, pkName, bucketNum == NO_SALTING ? null : bucketNum, columns, stats); }
Source:
<code>public static Charset getCharset(final MediaType mediaType) { if (mediaType != null) { String charset = mediaType.getParameters().get("charset"); if (charset != null) return Charset.forName(charset); } <START> return Charset.forName("utf-8"); <END> }</code><technical_language>RFC7159: Adding (charset) effect compliant recipients. @asoldano, @ronsigal WDYT this</technical_language>

Target:
public static Charset getCharset(final MediaType mediaType) { if (DISABLE_CHARSET) { return Charset.forName("utf-8"); } if (mediaType != null) { String charset = mediaType.getParameters().get("charset"); if (charset != null) return Charset.forName(charset); } return Charset.defaultCharset(); }