auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void indexerTest() throws Exception { // add triples sparqlIndexer.update(uri, createDefaultModel().read( new StringReader(fooRDF), "", "N3")); waitForTriples(3); // triples should be present in the triplestore assertEquals("Triples should be present!", 3, countDescribeTriples(uri)); // SPARQL search should work final String sparqlQuery = "PREFIX fcrepo: <http://fedora.info/definitions/v4/repository#> \n" + "SELECT ?p \n" + "WHERE \n" + "{ ?p fcrepo:hasParent ?c }"; assertEquals("Triple should return from search!", 3, countQueryTriples(sparqlQuery)); // remove object sparqlIndexer.remove(uri); waitForTriples(0); // triples should not be present in the triplestore assertTrue("Triples should not be present!", countDescribeTriples(uri) == 0); }

Target:
public void indexerTest() throws Exception { // add triples sparqlIndexer.update(uri, createDefaultModel().read( new StringReader(fooRDF), "", "N3")); waitForTriples(3); // triples should be present in the triplestore assertEquals("Triples should be present!", 3, countDescribeTriples(uri)); // SPARQL search should work final String sparqlQuery = "PREFIX fcrepo: <http://fedora.info/definitions/v4/repository#> \n" + "SELECT ?p \n" + "WHERE \n" + "{ ?p fcrepo:hasParent ?c }"; assertTrue("Triple should return from search!", countQueryTriples(sparqlQuery) > 0 ); // remove object sparqlIndexer.remove(uri); waitForTriples(0); // triples should not be present in the triplestore assertTrue("Triples should not be present!", countDescribeTriples(uri) == 0); }
Source:
public static boolean isTransientError(int code) { // Note: Status.NOT_ACCEPTABLE = 406, Status.REQUEST_TIMEOUT = 408 return code == 406 || code == 408 || code == 500 || code == 502 || code == 503 || code == 504; }

Target:
public static boolean isTransientError(int code) { // Note: Status.REQUEST_TIMEOUT = 408 return code == 408 || code == 500 || code == 502 || code == 503 || code == 504; }
Source:
public CustomFuture submit(boolean gzip) { com.couchbase.lite.replicator.RemoteRequest request = generateRemoteRequest(); if (gzip) request.setCompressedRequest(true); synchronized (requestExecutor) { if (!requestExecutor.isShutdown()) { Future future = requestExecutor.submit(request); pendingRequests.add(future); runnables.put(future, request); } } return this; }

Target:
public CustomFuture submit(boolean gzip) { RemoteRequest request = generateRemoteRequest(); if (gzip) request.setCompressedRequest(true); synchronized (requestExecutor) { if (!requestExecutor.isShutdown()) { Future future = requestExecutor.submit(request); pendingRequests.add(future); runnables.put(future, request); } } return this; }
Source:
private void pruneFailedDownload(String docId) { Log.e(TAG, "pruneFailedDownload: " + docId); try { getLocalDatabase().deleteLocalDocument(docId); } catch (CouchbaseLiteException e) { Log.w(TAG, "Failed to delete local document: " + docId, e); } }

Target:
private void pruneFailedDownload(String docId) { try { getLocalDatabase().deleteLocalDocument(docId); } catch (CouchbaseLiteException e) { Log.w(TAG, "Failed to delete local document: " + docId, e); } }
Source:
protected void setError(Throwable throwable) { // TODO - needs to port //if (error.code == NSURLErrorCancelled && $equal(error.domain, NSURLErrorDomain)) // return; if (throwable != this.error) { Log.e(Log.TAG_SYNC, "%s: Progress: set error = %s", this, throwable); parentReplication.setLastError(throwable); this.error = throwable; // if permanent error, stop immediately if(Utils.isPermanentError(this.error)) { stop(); } // iOS version sends notification from stop() method, but java version does not. // following codes are always executed. { Replication.ChangeEvent changeEvent = new Replication.ChangeEvent(this); changeEvent.setError(this.error); notifyChangeListeners(changeEvent); } } }

Target:
protected void setError(Throwable throwable) { // TODO - needs to port //if (error.code == NSURLErrorCancelled && $equal(error.domain, NSURLErrorDomain)) // return; if (throwable != this.error) { Log.e(Log.TAG_SYNC, "%s: Progress: set error = %s", this, throwable); parentReplication.setLastError(throwable); this.error = throwable; // if permanent error, stop immediately if(Utils.isPermanentError(this.error)) { stop(); } // iOS version sends notification from stop() method, but java version does not. // following codes are always executed. Replication.ChangeEvent changeEvent = new Replication.ChangeEvent(this); changeEvent.setError(this.error); notifyChangeListeners(changeEvent); } }
Source:
protected void stop() { if (!isRunning()) return; // clear batcher batcher.clear(); // set non-continuous setLifecycle(Replication.Lifecycle.ONESHOT); // cancel if middle of retry cancelRetryFuture(); // cancel all pending future tasks. while (!pendingFutures.isEmpty()) { Future future = pendingFutures.poll(); if (future != null && !future.isCancelled() && future.isDone()) { future.cancel(true); } } }

Target:
protected void stop() { if (!isRunning()) return; // clear batcher batcher.clear(); // set non-continuous setLifecycle(Replication.Lifecycle.ONESHOT); // cancel if middle of retry cancelRetryFuture(); // cancel all pending future tasks. while (!pendingFutures.isEmpty()) { Future future = pendingFutures.poll(); if (future != null && !future.isCancelled() && !future.isDone()) { future.cancel(true); } } }
Source:
public E take() throws InterruptedException { E e = super.take(); if(listener != null) listener.changed(BlockingQueueListener.EventType.TAKE, e, this); return e; }

Target:
public E take() throws InterruptedException { E e = super.take(); if(listener != null) { listener.changed(BlockingQueueListener.EventType.TAKE, e, this); } return e; }
Source:
public @NotNull MetaTag getCharsetMetaTag(@NotNull String charsetStr) { if (ECharset.getCharset(charsetStr).isPresent()) { ECharset charset = ECharset.getCharset(charsetStr).get(); if (charset != null) { return new MetaTag(charset); } } return new MetaTag(ECharset.ATTRIB_NAME, charsetStr, null); }

Target:
public @NotNull MetaTag getCharsetMetaTag(@NotNull String charsetStr) { Optional<ECharset> charset = ECharset.getCharset(charsetStr); if (charset.isPresent()) { return new MetaTag(charset.get()); } return new MetaTag(ECharset.ATTRIB_NAME, charsetStr, null); }
Source:
void checkNotTranslation(XWikiDocument doc) { String msg = "Trying to access XObjects on translation ''{0}'' of doc ''{1}''"; checkState(!isTranslation(doc), MessageFormat.format(msg, doc.getLanguage(), doc.getDocumentReference())); }

Target:
void checkNotTranslation(XWikiDocument doc) { checkState(!isTranslation(doc), MessageFormat.format( "Trying to access XObjects on translation ''{0}'' of doc ''{1}''", doc.getLanguage(), doc.getDocumentReference())); }
Source:
protected String getEndpointId(Endpoint ep) { String answer = doGetEndpointId(ep); boolean sanitize = camelContext != null && camelContext.getManagementStrategy().getManagementAgent().getMask(); if (sanitize != null && sanitize) { // use xxxxxx as replacements as * has to be quoted for MBean names answer = URISupport.sanitizeUri(answer); } return answer; }

Target:
protected String getEndpointId(Endpoint ep) { String answer = doGetEndpointId(ep); boolean sanitize = camelContext != null && camelContext.getManagementStrategy().getManagementAgent().getMask(); if (sanitize) { // use xxxxxx as replacements as * has to be quoted for MBean names answer = URISupport.sanitizeUri(answer); } return answer; }
Source:
private void doCreateTable(Exchange exchange, String tableName) throws KuduException { LOG.trace("Creating table {}", tableName); KuduClient connection = endpoint.getKuduClient(); try { Schema schema = (Schema) exchange.getIn().getHeader(KuduConstants.CAMEL_KUDU_SCHEMA); CreateTableOptions builder = (CreateTableOptions) exchange.getIn() .getHeader(KuduConstants.CAMEL_KUDU_TABLE_OPTIONS); connection.createTable(tableName, schema, builder); } catch (Throwable t) { t.printStackTrace(); throw t; } }

Target:
private void doCreateTable(Exchange exchange, String tableName) throws KuduException { LOG.trace("Creating table {}", tableName); KuduClient connection = endpoint.getKuduClient(); Schema schema = (Schema) exchange.getIn().getHeader(KuduConstants.CAMEL_KUDU_SCHEMA); CreateTableOptions builder = (CreateTableOptions) exchange.getIn() .getHeader(KuduConstants.CAMEL_KUDU_TABLE_OPTIONS); connection.createTable(tableName, schema, builder); }
Source:
public void onApplicationEvent(ApplicationEvent event) { LOG.debug("onApplicationEvent: {}", event); if (event instanceof ContextRefreshedEvent && ((ContextRefreshedEvent) event).getApplicationContext().getId().equals(this.applicationContext.getId())) { // nominally we would prefer to use Lifecycle interface that // would invoke start() method, but in order to do that // SpringCamelContext needs to implement SmartLifecycle // (look at DefaultLifecycleProcessor::startBeans), but it // cannot implement it as it already implements // RuntimeConfiguration, and both SmartLifecycle and // RuntimeConfiguration declare isAutoStartup method but // with boolean and Boolean return types, and covariant // methods with primitive types are not allowed by the JLS // so we need to listen for ContextRefreshedEvent and start // on its reception start(); } if (eventComponent != null) { eventComponent.onApplicationEvent(event); } }

Target:
public void onApplicationEvent(ApplicationEvent event) { LOG.debug("onApplicationEvent: {}", event); if (event instanceof ContextRefreshedEvent && ((ContextRefreshedEvent) event).getApplicationContext() == this.applicationContext) { // nominally we would prefer to use Lifecycle interface that // would invoke start() method, but in order to do that // SpringCamelContext needs to implement SmartLifecycle // (look at DefaultLifecycleProcessor::startBeans), but it // cannot implement it as it already implements // RuntimeConfiguration, and both SmartLifecycle and // RuntimeConfiguration declare isAutoStartup method but // with boolean and Boolean return types, and covariant // methods with primitive types are not allowed by the JLS // so we need to listen for ContextRefreshedEvent and start // on its reception start(); } if (eventComponent != null) { eventComponent.onApplicationEvent(event); } }
Source:
public boolean isFifoQueue() { // AWS docs suggest this is valid derivation. // FIFO queue names must end with .fifo, and standard queues cannot if (queueName.endsWith(".fifo")) { return true; } return false; }

Target:
boolean isFifoQueue() { // AWS docs suggest this is valid derivation. // FIFO queue names must end with .fifo, and standard queues cannot if (queueName.endsWith(".fifo")) { return true; } return false; }
Source:
public DropboxFileUploadResult put(String localPath, String remotePath, DropboxUploadMode mode) throws DropboxException { // in case the remote path is not specified, the remotePath = localPath String dropboxPath = remotePath == null ? localPath : remotePath; UploadUploader entry; try { entry = client.files().upload(localPath); } catch (DbxException e) { throw new DropboxException(dropboxPath + " does not exist or can't obtain metadata"); } if (localPath != null) { return putFile(localPath, mode, dropboxPath, entry); } else { return putBody(exchange, mode, dropboxPath, entry); } }

Target:
public DropboxFileUploadResult put(String localPath, String remotePath, DropboxUploadMode mode) throws DropboxException { // in case the remote path is not specified, the remotePath = localPath String dropboxPath = remotePath == null ? localPath : remotePath; UploadUploader entry; try { entry = client.files().upload(dropboxPath); } catch (DbxException e) { throw new DropboxException(dropboxPath + " does not exist or can't obtain metadata"); } if (localPath != null) { return putFile(localPath, mode, dropboxPath, entry); } else { return putBody(exchange, mode, dropboxPath, entry); } }
Source:
public InputStream getContentStreamFor(QueryResult item) { Document document = getDocument(item); ContentStream contentStream = document.getContentStream(); if (document != null && contentStream != null) { return contentStream.getStream(); } return null; }

Target:
public InputStream getContentStreamFor(QueryResult item) { Document document = getDocument(item); if(document != null) { ContentStream contentStream = document.getContentStream(); if (contentStream != null) { return contentStream.getStream(); } } return null; }
Source:
protected void afterConfigureProperties() { // create connection eagerly, a good way to validate configuration getZendesk(); }

Target:
protected void afterConfigureProperties() { }
Source:
public void testSelectorWidget() { final Button b1 = new Button("Button click"); RootPanel.get().add(b1); GQuery g = $(b1); assertTrue($(b1).isVisible()); g.hide(); assertFalse($(b1).isVisible()); b1.removeFromParent(); }

Target:
public void testSelectorWidget() { final Button b1 = new Button("Button click"); RootPanel.get().add(b1); GQuery g = $(b1); assertTrue(g.isVisible()); g.hide(); assertFalse(g.isVisible()); b1.removeFromParent(); }
Source:
private boolean isMultipartRequest(WebRequest request) { String contentType = request.getHeader("Content-Type"); return StringUtils.startsWithIgnoreCase(contentType, "multipart"); }

Target:
private boolean isMultipartRequest(WebRequest request) { String contentType = request.getHeader("Content-Type"); return (contentType != null && StringUtils.startsWithIgnoreCase(contentType, "multipart")); }
Source:
protected void prepareContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) { context.getEnvironment().setActiveProfiles(mergedConfig.getActiveProfiles()); TestPropertySourceUtils.addPropertiesFilesToEnvironment(context, mergedConfig.getPropertySourceLocations()); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, mergedConfig.getPropertySourceProperties()); invokeApplicationContextInitializers(context, mergedConfig); for (ContextCustomizer contextCustomizer : mergedConfig.getContextCustomizers()) { contextCustomizer.prepareContext(context, mergedConfig); } }

Target:
protected void prepareContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) { context.getEnvironment().setActiveProfiles(mergedConfig.getActiveProfiles()); TestPropertySourceUtils.addPropertiesFilesToEnvironment(context, mergedConfig.getPropertySourceLocations()); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, mergedConfig.getPropertySourceProperties()); invokeApplicationContextInitializers(context, mergedConfig); }
Source:
public List<TriggerTask> getTriggerTaskList() { return this.triggerTasks; }

Target:
public List<TriggerTask> getTriggerTaskList() { List<TriggerTask> result = new ArrayList<TriggerTask>(); synchronized (this.triggerTasks) { result.addAll(this.triggerTasks); } return result; }
Source:
protected FluentList<FluentWebElement> find() { FluentListImpl<FluentWebElement> elements = new FluentListImpl<>(); if (this.untilElements != null) { for (FluentWebElement untilElement : this.untilElements) { try { untilElement.getTagName(); elements.add(untilElement); } catch (NoSuchElementException e) { // untilElement is a proxy element and is not found. } } } return elements; }

Target:
protected FluentList<FluentWebElement> find() { FluentListImpl<FluentWebElement> elements = new FluentListImpl<>(); if (untilElements != null) { for (FluentWebElement untilElement : untilElements) { try { untilElement.getTagName(); elements.add(untilElement); } catch (NoSuchElementException e) { // untilElement is a proxy element and is not found. } } } return elements; }
Source:
private UrlUtil() { throw new UnsupportedOperationException("No instances allowed"); }

Target:
private UrlUtil() { // No instances allowed }
Source:
public UsageStats getUsage(final Object o) { if (!(o instanceof Identifiable) || !(o instanceof Locatable)) { // only track objects with an identifier and a location return null; } final String id = ((Identifiable) o).getIdentifier(); final String url = ((Locatable) o).getLocation(); if (!stats.containsKey(id)) stats.put(id, new UsageStats(id, url)); return stats.get(id); }

Target:
public UsageStats getUsage(final Object o) { if (!(o instanceof Identifiable && o instanceof Locatable)) { // only track objects with an identifier and a location return null; } final String id = ((Identifiable) o).getIdentifier(); final String url = ((Locatable) o).getLocation(); if (!stats.containsKey(id)) stats.put(id, new UsageStats(id, url)); return stats.get(id); }
Source:
public static void logMetricForSum(String name, double sum, int quantity) { logMetricInternal(name, "S,C", String.format("%s,%.2f", sum, quantity)); }

Target:
public static void logMetricForSum(String name, double sum, int quantity) { logMetricInternal(name, "S,C", String.format("%s,%.2f", quantity, sum)); }
Source:
public int compare(AbstractComponent o1, AbstractComponent o2) { // Handles null situations if(o1.getComponentId() == null) { if(o2.getComponentId() == null) return 0; //equal else return -1; // null is before other strings } else { if(o2.getComponentId() == null) return 1; // all other strings are after null else return o1.getComponentId().compareTo(o2.getComponentId()); } }

Target:
public int compare(AbstractComponent o1, AbstractComponent o2) { // Handles null situations if (o1.getComponentId() == null) { if (o2.getComponentId() == null) { return 0; // equal } else { return -1; // null is before other strings } } else { if (o2.getComponentId() == null) { return 1; // all other strings are after null } else { return o1.getComponentId().compareTo(o2.getComponentId()); } } }
Source:
} catch (URISyntaxException e) { // will not throw throw new RuntimeException(e); }

Target:
} catch (URISyntaxException e) { // will not throw throw new IllegalArgumentException(e); }
Source:
public UserInfo[] getBrokerUsers() throws OperationCanceledException, AuthenticatorException, IOException { // Calling this on main thread will cause exception since this is // waiting on AccountManagerFuture if (Looper.myLooper() == Looper.getMainLooper()) { throw new IllegalArgumentException("Calling getBrokerUsers on main thread"); } if (isBrokerAccountServiceSupported()) { return BrokerAccountServiceHandler.getInstance().getBrokerUsers(mContext); } else { return getUserInfoFromAccountManager(); } }

Target:
public UserInfo[] getBrokerUsers() throws OperationCanceledException, AuthenticatorException, IOException { // Calling this on main thread will cause exception since this is // waiting on AccountManagerFuture if (Looper.myLooper() == Looper.getMainLooper()) { throw new IllegalArgumentException("Calling getBrokerUsers on main thread"); } if (isBrokerAccountServiceSupported()) { return BrokerAccountServiceHandler.getInstance().getBrokerUsers(mContext); } return getUserInfoFromAccountManager(); }
Source:
private IWindowComponent wrapActivity(final Activity activity) { if (activity == null) { throw new IllegalArgumentException("activity"); } return new IWindowComponent() { //CHECKSTYLE:OFF: checkstyle:MemberName //CHECKSTYLE:OFF: checkstyle:VisibilityModifier Activity mRefActivity = activity; @Override public void startActivityForResult(Intent intent, int requestCode) { // if user closed an app or switched to another activity // mRefActivity can die before this method got invoked if (mRefActivity != null) { mRefActivity.startActivityForResult(intent, requestCode); } } //CHECKSTYLE:ON: checkstyle:MemberName //CHECKSTYLE:ON: checkstyle:VisibilityModifier }; }

Target:
private IWindowComponent wrapActivity(final Activity activity) { if (activity == null) { throw new IllegalArgumentException("activity"); } return new IWindowComponent() { private Activity mRefActivity = activity; @Override public void startActivityForResult(Intent intent, int requestCode) { // if user closed an app or switched to another activity // mRefActivity can die before this method got invoked if (mRefActivity != null) { mRefActivity.startActivityForResult(intent, requestCode); } } }; }
Source:
final Date getExtendedExpiresOn() { return this.mExtendedExpiresOn; }

Target:
final Date getExtendedExpiresOn() { return mExtendedExpiresOn; }
Source:
public List<TokenCacheItem> getTokensForResource(String resource) { Iterator<TokenCacheItem> results = this.getAll(); List<TokenCacheItem> tokenItems = new ArrayList<>(); while (results.hasNext()) { final TokenCacheItem tokenCacheItem = results.next(); // MRRT and FRT don't store resource in the token cache item. if (resource.equals(tokenCacheItem.getResource())) { tokenItems.add(tokenCacheItem); } } return tokenItems; }

Target:
public List<TokenCacheItem> getTokensForResource(String resource) { Iterator<TokenCacheItem> results = this.getAll(); final List<TokenCacheItem> tokenItems = new ArrayList<>(); while (results.hasNext()) { final TokenCacheItem tokenCacheItem = results.next(); // MRRT and FRT don't store resource in the token cache item. if (resource.equals(tokenCacheItem.getResource())) { tokenItems.add(tokenCacheItem); } } return tokenItems; }
Source:
public AuthenticationResult getTokenForCode(String code) throws IOException, AuthenticationException { String requestMessage; if (mWebRequestHandler == null) { throw new IllegalArgumentException("webRequestHandler"); } // Token request message try { requestMessage = buildTokenRequestMessage(code); } catch (UnsupportedEncodingException encoding) { Logger.e(TAG, encoding.getMessage(), "", ADALError.ENCODING_IS_NOT_SUPPORTED, encoding); return null; } HashMap<String, String> headers = getRequestHeaders(); return postMessage(requestMessage, headers); }

Target:
public AuthenticationResult getTokenForCode(String code) throws IOException, AuthenticationException { final String requestMessage; if (mWebRequestHandler == null) { throw new IllegalArgumentException("webRequestHandler"); } // Token request message try { requestMessage = buildTokenRequestMessage(code); } catch (UnsupportedEncodingException encoding) { Logger.e(TAG, encoding.getMessage(), "", ADALError.ENCODING_IS_NOT_SUPPORTED, encoding); return null; } final Map<String, String> headers = getRequestHeaders(); return postMessage(requestMessage, headers); }
Source:
private boolean isUserMisMatch(final String user, final TokenCacheItem tokenCacheItem) { // If user if provided, it needs to match either displayId or userId. if (!StringExtensions.IsNullOrBlank(user)) { return !user.equalsIgnoreCase(tokenCacheItem.getUserInfo().getDisplayableId()) && !user.equalsIgnoreCase(tokenCacheItem.getUserInfo().getUserId()); } return false; }

Target:
private boolean isUserMisMatch(final String user, final TokenCacheItem tokenCacheItem) { // If user is not passed in the request or userInfo does not exist in the token cache item, // it's a match case. We do wildcard find, return whatever match with cache key. if (StringExtensions.IsNullOrBlank(user) || tokenCacheItem.getUserInfo() == null) { return false; } // If user if provided, it needs to match either displayId or userId. return !user.equalsIgnoreCase(tokenCacheItem.getUserInfo().getDisplayableId()) && !user.equalsIgnoreCase(tokenCacheItem.getUserInfo().getUserId()); }
Source:
private boolean isBrokerWithPRTSupport(final Intent intent) { if (intent == null) { throw new IllegalArgumentException("intent"); } // Only new broker with PRT support will send down the value and the version will be v2 final String brokerVersion = intent.getStringExtra(AuthenticationConstants.Broker.BROKER_VERSION); return !StringExtensions.IsNullOrBlank(brokerVersion) && AuthenticationConstants.Broker.BROKER_PROTOCOL_VERSION.equalsIgnoreCase(brokerVersion); }

Target:
private boolean isBrokerWithPRTSupport(final Intent intent) { if (intent == null) { throw new IllegalArgumentException("intent"); } // Only new broker with PRT support will send down the value and the version will be v2 final String brokerVersion = intent.getStringExtra(AuthenticationConstants.Broker.BROKER_VERSION); return AuthenticationConstants.Broker.BROKER_PROTOCOL_VERSION.equalsIgnoreCase(brokerVersion); }
Source:
private boolean promptUser(PromptBehavior prompt) { return prompt == PromptBehavior.Always || prompt == PromptBehavior.REFRESH_SESSION // Force broker with PRT support to prompt user. || PromptBehavior.FORCE_PROMPT == prompt; }

Target:
private boolean promptUser(PromptBehavior prompt) { return prompt == PromptBehavior.Always || prompt == PromptBehavior.REFRESH_SESSION || prompt == PromptBehavior.FORCE_PROMPT; }
Source:
private synchronized SecretKey getKey(final String keyVersion) throws GeneralSecurityException, IOException { switch (keyVersion) { case VERSION_USER_DEFINED : return getSecretKey(AuthenticationSettings.INSTANCE.getSecretKeyData()); case VERSION_ANDROID_KEY_STORE : if (Build.VERSION.SDK_INT >= 18) { // androidKeyStore can store app specific self signed cert. // Asymmetric cryptography is used to protect the session key // used for Encryption and HMac mKeyPair = readKeyPair(); mSecretKeyFromAndroidKeyStore = getUnwrappedSecretKey(); return mSecretKeyFromAndroidKeyStore; } default : throw new IOException("Unknown keyVersion."); } }

Target:
private synchronized SecretKey getKey(final String keyVersion) throws GeneralSecurityException, IOException { switch (keyVersion) { case VERSION_USER_DEFINED : return getSecretKey(AuthenticationSettings.INSTANCE.getSecretKeyData()); case VERSION_ANDROID_KEY_STORE : // androidKeyStore can store app specific self signed cert. // Asymmetric cryptography is used to protect the session key // used for Encryption and HMac mKeyPair = readKeyPair(); mSecretKeyFromAndroidKeyStore = getUnwrappedSecretKey(); return mSecretKeyFromAndroidKeyStore; default : throw new IOException("Unknown keyVersion."); } }
Source:
public void saveAccount(String accountName) { if (accountName == null || accountName.isEmpty()) return; SharedPreferences prefs = mContext.getSharedPreferences(KEY_SHARED_PREF_ACCOUNT_LIST, Activity.MODE_PRIVATE); String accountList = prefs.getString(KEY_APP_ACCOUNTS_FOR_TOKEN_REMOVAL, ""); accountList += KEY_ACCOUNT_LIST_DELIM + accountName; Editor prefsEditor = prefs.edit(); prefsEditor.putString(KEY_APP_ACCOUNTS_FOR_TOKEN_REMOVAL, accountList); // apply will do Async disk write operation. prefsEditor.apply(); }

Target:
public void saveAccount(String accountName) { if (accountName == null || accountName.isEmpty()) return; SharedPreferences prefs = mContext.getSharedPreferences(KEY_SHARED_PREF_ACCOUNT_LIST, Activity.MODE_PRIVATE); String accountList = prefs.getString(KEY_APP_ACCOUNTS_FOR_TOKEN_REMOVAL, ""); if (!accountList.contains(KEY_ACCOUNT_LIST_DELIM + accountName)) { accountList += KEY_ACCOUNT_LIST_DELIM + accountName; Editor prefsEditor = prefs.edit(); prefsEditor.putString(KEY_APP_ACCOUNTS_FOR_TOKEN_REMOVAL, accountList); // apply will do Async disk write operation. prefsEditor.apply(); } }
Source:
private String getBrokerUrl(String loadUrl, String packageName, String signatureDigest) { if (!StringExtensions.IsNullOrBlank(packageName) && !StringExtensions.IsNullOrBlank(signatureDigest)) { try { return loadUrl + "&package_name=" + URLEncoder.encode(packageName, AuthenticationConstants.ENCODING_UTF8) + "&signature=" + signatureDigest; } catch (UnsupportedEncodingException e) { // This encoding issue will happen at the beginning of API call, // if it is not supported on this device. ADAL uses one encoding // type. Log.e(TAG, "Encoding", e); } } return loadUrl; }

Target:
private String getBrokerUrl(String loadUrl, String packageName, String signatureDigest) { if (!StringExtensions.IsNullOrBlank(packageName) && !StringExtensions.IsNullOrBlank(signatureDigest)) { try { return loadUrl + "&package_name=" + URLEncoder.encode(packageName, AuthenticationConstants.ENCODING_UTF8) + "&signature=" + URLEncoder.encode(signatureDigest, AuthenticationConstants.ENCODING_UTF8); } catch (UnsupportedEncodingException e) { // This encoding issue will happen at the beginning of API call, // if it is not supported on this device. ADAL uses one encoding // type. Log.e(TAG, "Encoding", e); } } return loadUrl; }
Source:
public Builder(String packageName, TypeSpec typeSpec) { this.packageName = checkNotNull(packageName, "packageName == null"); this.typeSpec = checkNotNull(typeSpec, "typeSpec == null"); }

Target:
private Builder(String packageName, TypeSpec typeSpec) { this.packageName = checkNotNull(packageName, "packageName == null"); this.typeSpec = checkNotNull(typeSpec, "typeSpec == null"); }
Source:
private void emitModifiers(Set<Modifier> modifiers) throws IOException { // Use an EnumSet to ensure the proper ordering if (!(modifiers instanceof EnumSet)) { // This branch avoids an IllegalArgumentException within copyOf if(modifiers.isEmpty()) modifiers = EnumSet.noneOf(Modifier.class); else modifiers = EnumSet.copyOf(modifiers); } for (Modifier modifier : modifiers) { out.append(modifier.toString()).append(' '); } }

Target:
private void emitModifiers(Set<Modifier> modifiers) throws IOException { // Preserve "natural" ordering of modifiers if (!modifiers.isEmpty()) { modifiers = EnumSet.copyOf(modifiers); } for (Modifier modifier : modifiers) { out.append(modifier.toString()).append(' '); } }
Source:
public void unloadView() { // TODO: Unload the view correctly. this.view.removeAll(); this.view.revalidate(); this.getParentController().getView().remove(this.view); this.getParentController().getView().revalidate(); this.getParentController().getView().repaint(); this.popoverView = null; this.welcomeView = null; this.timelineView = null; this.view = null; }

Target:
public void unloadView() { this.view.removeAll(); this.view.revalidate(); this.popoverView = null; this.welcomeView = null; this.timelineView = null; this.view = null; }
Source:
public void removeInstallation(Installation installation) { //Let manually remove the categories and update the installations before deleting //check AGPUSH-1295 for more information installation.setCategories(null); updateInstallation(installation); installationDao.delete(installation); }

Target:
public void removeInstallation(Installation installation) { installationDao.delete(installation); }
Source:
default void onConfigurationSuccess(ITestResult itr) { throw new UnsupportedOperationException("Method is not implemented"); }

Target:
default void onConfigurationSuccess(ITestResult itr) { // not implemented }
Source:
default void onExecutionStart() { throw new UnsupportedOperationException("Method is not implemented"); }

Target:
default void onExecutionStart() { // not implemented }
Source:
public String[] getGroupFilters() { String[] result = new String[0]; IBeforeMethod before = m_annotationFinder.findAnnotation(getConstructorOrMethod(), IBeforeMethod.class); if (before != null) { result = before.getGroupFilters(); } return result; }

Target:
public String[] getGroupFilters() { IBeforeMethod before = m_annotationFinder.findAnnotation(getConstructorOrMethod(), IBeforeMethod.class); if (before == null) { return new String[0]; } return before.getGroupFilters(); }
Source:
public static boolean hasFileScheme(String uri) { URI constructedURI = constructURI(uri); if (constructedURI == null) { constructedURI = new File(uri).toURI(); } String scheme = constructedURI.getScheme(); //A URI is regarded as having a file scheme if it either has its scheme as "file" //(or) if the scheme is null (which is true when uri's represent local file system path.) return scheme == null || "file".equalsIgnoreCase(scheme); }

Target:
public static boolean hasFileScheme(String uri) { URI constructedURI = constructURI(uri); if (constructedURI == null) { //There were difficulties in constructing the URI. Falling back to considering the URI as a file. return true; } String scheme = constructedURI.getScheme(); //A URI is regarded as having a file scheme if it either has its scheme as "file" //(or) if the scheme is null (which is true when uri's represent local file system path.) return scheme == null || "file".equalsIgnoreCase(scheme); }
Source:
private static Map<String, String> getParameters(IMethodInstance im) { XmlTest xmlTest = im.getMethod().getXmlTest(); Map<String, String> params = xmlTest.getAllParameters(); params.putAll(im.getMethod().findMethodParameters(xmlTest)); return params; }

Target:
private static Map<String, String> getParameters(IMethodInstance im) { XmlTest xmlTest = im.getMethod().getXmlTest(); return im.getMethod().findMethodParameters(xmlTest); }
Source:
public void rollback() throws IOException { if( writeTransactionId!=-1 ) { if (tmpFile != null) { getTempFile().delete(); tmpFile.close(); tmpFile = null; txFile = null; } // Release the pages that were allocated in the transaction... freePages(allocateList); freeList.clear(); allocateList.clear(); writes.clear(); writeTransactionId = -1; } else { freePages(allocateList); } size = 0; }

Target:
public void rollback() throws IOException { if( writeTransactionId!=-1 ) { if (tmpFile != null) { tmpFile.close(); getTempFile().delete(); tmpFile = null; txFile = null; } // Release the pages that were allocated in the transaction... freePages(allocateList); freeList.clear(); allocateList.clear(); writes.clear(); writeTransactionId = -1; } else { freePages(allocateList); } size = 0; }
Source:
private static String getUserName(Cause cause) { if (cause instanceof UserIdCause) { Cause.UserIdCause userIdCause = (UserIdCause) cause; return userIdCause.getUserName(); }else if (cause instanceof UserCause) { Cause.UserCause userCause = (UserCause) cause; return userCause.getUserName(); } return null; }

Target:
private static String getUserName(Cause cause) { if (cause instanceof UserIdCause) { Cause.UserIdCause userIdCause = (UserIdCause) cause; return userIdCause.getUserName(); } else if (cause instanceof UserCause) { Cause.UserCause userCause = (UserCause) cause; return userCause.getUserName(); } return ""; }
Source:
public int getProxyPort() { if (proxyPort > 0) { return proxyPort; } else { return getProxyPortProperty(); } }

Target:
public int getProxyPort() { return (proxyPort >= 0) ? proxyPort : getProxyPortProperty(); }
Source:
private static void speedUpDcoumentBuilderFactory() { String className = System.getProperty(DOCUMENT_BUILDER_FACTORY_PROP_NAME); if (className == null) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); if (DOCUMENT_BUILDER_FACTORY_IMPL_CLASS_NAME.equals(factory.getClass().getName())) { // This would avoid the file system to be accessed every time // the internal DocumentBuilderFactory is instantiated. System.setProperty(DOCUMENT_BUILDER_FACTORY_PROP_NAME, DOCUMENT_BUILDER_FACTORY_IMPL_CLASS_NAME); } } }

Target:
private static void speedUpDcoumentBuilderFactory() { if (System.getProperty(DOCUMENT_BUILDER_FACTORY_PROP_NAME) == null) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); if (DOCUMENT_BUILDER_FACTORY_IMPL_CLASS_NAME.equals(factory.getClass().getName())) { // This would avoid the file system to be accessed every time // the internal DocumentBuilderFactory is instantiated. System.setProperty(DOCUMENT_BUILDER_FACTORY_PROP_NAME, DOCUMENT_BUILDER_FACTORY_IMPL_CLASS_NAME); } } }
Source:
public AWSCredentials getCredentials() { if (profilesConfigFile == null) { synchronized (this) { if (profilesConfigFile == null) { profilesConfigFile = new ProfilesConfigFile(); } } } if (ProfilesConfigFile.DEFAULT_PROFILE_NAME.equals(profileName)) { // only override profileName if current profileName is the default one String profileOverride = System.getenv(ProfilesConfigFile.AWS_PROFILE_ENVIRONMENT_VARIABLE); profileOverride = StringUtils.trim(profileOverride); if (!StringUtils.isNullOrEmpty(profileOverride)) { return profilesConfigFile.getCredentials(profileOverride); } } return profilesConfigFile.getCredentials(profileName); }

Target:
public AWSCredentials getCredentials() { if (profilesConfigFile == null) { synchronized (this) { if (profilesConfigFile == null) { profilesConfigFile = new ProfilesConfigFile(); } } } return profilesConfigFile.getCredentials(profileName); }
Source:
private List<ExtensionComponent<T>> ensureLoaded() { if(extensions!=null) return extensions; // already loaded if (jenkins != null && jenkins.getInitLevel().compareTo(InitMilestone.PLUGINS_PREPARED) < 0) return legacyInstances; // can't perform the auto discovery until all plugins are loaded, so just make the legacy instances visible synchronized (getLoadLock()) { if(extensions==null) { List<ExtensionComponent<T>> r = load(); r.addAll(legacyInstances); extensions = sort(r); } return extensions; } }

Target:
private List<ExtensionComponent<T>> ensureLoaded() { if(extensions!=null) return extensions; // already loaded if (jenkins == null || jenkins.getInitLevel().compareTo(InitMilestone.PLUGINS_PREPARED) < 0) return legacyInstances; // can't perform the auto discovery until all plugins are loaded, so just make the legacy instances visible synchronized (getLoadLock()) { if(extensions==null) { List<ExtensionComponent<T>> r = load(); r.addAll(legacyInstances); extensions = sort(r); } return extensions; } }
Source:
public Set<String> getDisabledAdministrativeMonitors(){ synchronized (disabledAdministrativeMonitors) { return disabledAdministrativeMonitors; } }

Target:
public Set<String> getDisabledAdministrativeMonitors(){ synchronized (this.disabledAdministrativeMonitors) { return new HashSet<>(disabledAdministrativeMonitors); } }
Source:
public synchronized void setDisabledAdministrativeMonitors(Set<String> disabledAdministrativeMonitors) { synchronized (this.disabledAdministrativeMonitors) { this.disabledAdministrativeMonitors.clear(); this.disabledAdministrativeMonitors.addAll(disabledAdministrativeMonitors); } }

Target:
public void setDisabledAdministrativeMonitors(Set<String> disabledAdministrativeMonitors) { synchronized (this.disabledAdministrativeMonitors) { this.disabledAdministrativeMonitors.clear(); this.disabledAdministrativeMonitors.addAll(disabledAdministrativeMonitors); } }
Source:
public void cancelQuietDownShouldSuccessOnQuietDownedJenkins() throws Exception { j.jenkins.get().doQuietDown(); QuietDownCommandTest.assertJenkinsInQuietMode(j); final CLICommandInvoker.Result result = command .authorizedTo(Jenkins.READ, Jenkins.ADMINISTER) .invoke(); assertThat(result, succeededSilently()); QuietDownCommandTest.assertJenkinsNotInQuietMode(j); }

Target:
public void cancelQuietDownShouldSuccessOnQuietDownedJenkins() throws Exception { j.jenkins.doQuietDown(); QuietDownCommandTest.assertJenkinsInQuietMode(j); final CLICommandInvoker.Result result = command .authorizedTo(Jenkins.READ, Jenkins.ADMINISTER) .invoke(); assertThat(result, succeededSilently()); QuietDownCommandTest.assertJenkinsNotInQuietMode(j); }
Source:
public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException { if (!ResourceDomainConfiguration.isResourceRequest(req) && ResourceDomainConfiguration.isResourceDomainConfigured()) { resourceToken = ExtensionList.lookupSingleton(ResourceDomainRootAction.class).getToken(this, req); } try { serveFile(req,rsp,base,icon,serveDirIndex); } catch (InterruptedException e) { throw new IOException("interrupted",e); } }

Target:
public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException { if (!ResourceDomainConfiguration.isResourceRequest(req) && ResourceDomainConfiguration.isResourceDomainConfigured()) { resourceToken = ResourceDomainRootAction.get().getToken(this, req); } try { serveFile(req,rsp,base,icon,serveDirIndex); } catch (InterruptedException e) { throw new IOException("interrupted",e); } }
Source:
public ListBoxModel doFillTimeZoneNameItems() { String current = forCurrentUser(); ListBoxModel items = new ListBoxModel(); items.add(Messages.TimeZoneProperty_DisplayDefaultTimeZone(), ""); for (String id : TimeZone.getAvailableIDs()) { if (id.equalsIgnoreCase(current)) { items.add(new Option(id, id, true)); } else { items.add(id); } } Messages.TimeZoneProperty_DisplayName(); return items; }

Target:
public ListBoxModel doFillTimeZoneNameItems() { String current = forCurrentUser(); ListBoxModel items = new ListBoxModel(); items.add(Messages.TimeZoneProperty_DisplayDefaultTimeZone(), ""); for (String id : TimeZone.getAvailableIDs()) { if (id.equalsIgnoreCase(current)) { items.add(new Option(id, id, true)); } else { items.add(id); } } return items; }
Source:
public FormValidation doCheckURIEncoding(StaplerRequest request) { Jenkins.get().checkPermission(Jenkins.ADMINISTER); // expected is non-ASCII String final String expected = "\u57f7\u4e8b"; final String value = fixEmpty(request.getParameter("value")); if (!expected.equals(value)) return FormValidation.warningWithMarkup(hudson.model.Messages.Hudson_NotUsesUTF8ToDecodeURL()); return FormValidation.ok(); }

Target:
public FormValidation doCheckURIEncoding(StaplerRequest request) throws IOException { Jenkins.get().checkPermission(Jenkins.ADMINISTER); // expected is non-ASCII String final String expected = "\u57f7\u4e8b"; final String value = fixEmpty(request.getParameter("value")); if (!expected.equals(value)) return FormValidation.warningWithMarkup(hudson.model.Messages.Hudson_NotUsesUTF8ToDecodeURL()); return FormValidation.ok(); }
Source:
public void startupShouldNotFailOnIOExceptionOnlineListener() { // We do nothing, IOExceptionOnOnlineListener & JenkinsRule should cause the // boot failure if the issue is not fixed. Assert.assertEquals(1, IOExceptionOnOnlineListener.onOnlineCount); }

Target:
public void startupShouldNotFailOnIOExceptionOnlineListener() { // We do nothing, IOExceptionOnOnlineListener & JenkinsRule should cause the // boot failure if the issue is not fixed. assertEquals(1, IOExceptionOnOnlineListener.onOnlineCount); }
Source:
private JSONArray formatEventsAndInitialize() { // Save the current events and clean for next (not this one) telemetry send ConcurrentHashMap<List<StackTraceElement>, MissingClassEvent> toReport = MissingClassTelemetry.events.getEventsAndClean(); if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine("Cleaned events for missing classes"); return formatEvents(toReport); }

Target:
private JSONArray formatEventsAndInitialize() { // Save the current events and clean for next (not this one) telemetry send ConcurrentHashMap<List<StackTraceElement>, MissingClassEvent> toReport = MissingClassTelemetry.events.getEventsAndClean(); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Cleaned events for missing classes"); } return formatEvents(toReport); }
Source:
protected Object readResolve() { if(defaultExcludes == null) { defaultExcludes = true; } if(caseSensitive == null) { caseSensitive = true; } return this; }

Target:
private Object readResolve() { if(defaultExcludes == null) { defaultExcludes = true; } if(caseSensitive == null) { caseSensitive = true; } return this; }
Source:
public boolean isActivePeriod() { LocalDate now = LocalDate.now(); if (getStart().isAfter(now)) { return false; } if (getEnd().isBefore(now)) { return false; } return true; }

Target:
public boolean isActivePeriod() { LocalDate now = LocalDate.now(); return now.isAfter(getStart()) && now.isBefore(getEnd()); }
Source:
private boolean verifySignature(Signature signature, String providedSignature) { // We can only make one call to Signature#verify here. // Since we need to potentially check two values (one decoded from hex, the other decoded from base64), // try hex first: It's almost certainly going to fail decoding if a base64 string was passed. // It is extremely unlikely for base64 strings to be a valid hex string. // This way, if it's base64, the #verify call will be skipped, and we continue with the #verify for decoded base64. // This approach might look unnecessarily clever, but short of having redundant Signature instances, // there doesn't seem to be a better approach for this. try { if (signature.verify(Hex.decodeHex(providedSignature.toCharArray()))) { return true; } } catch (SignatureException|DecoderException ignore) { // ignore } try { if (signature.verify(Base64.getDecoder().decode(providedSignature))) { return true; } } catch (SignatureException ignore) { // ignore } return false; }

Target:
private boolean verifySignature(Signature signature, String providedSignature) { // We can only make one call to Signature#verify here. // Since we need to potentially check two values (one decoded from hex, the other decoded from base64), // try hex first: It's almost certainly going to fail decoding if a base64 string was passed. // It is extremely unlikely for base64 strings to be a valid hex string. // This way, if it's base64, the #verify call will be skipped, and we continue with the #verify for decoded base64. // This approach might look unnecessarily clever, but short of having redundant Signature instances, // there doesn't seem to be a better approach for this. try { if (signature.verify(Hex.decodeHex(providedSignature.toCharArray()))) { return true; } } catch (SignatureException|DecoderException ignore) { // ignore } try { if (signature.verify(Base64.getDecoder().decode(providedSignature))) { return true; } } catch (SignatureException|IllegalArgumentException ignore) { // ignore } return false; }
Source:
private static void sendOneZipEntry(ZipOutputStream zos, VirtualFile vf, String relativePath) throws IOException { // In ZIP archives "All slashes MUST be forward slashes" (http://pkware.com/documents/casestudies/APPNOTE.TXT) // TODO On Linux file names can contain backslashes which should not treated as file separators. // Unfortunately, only the file separator char of the master is known (File.separatorChar) // but not the file separator char of the (maybe remote) "dir". ZipEntry e = new ZipEntry(relativePath.replace('\\', '/')); e.setTime(vf.lastModified()); zos.putNextEntry(e); try (InputStream in = vf.open()) { IOUtils.copy(in, zos); } zos.closeEntry(); }

Target:
private static void sendOneZipEntry(ZipOutputStream zos, VirtualFile vf, String relativePath) throws IOException { // In ZIP archives "All slashes MUST be forward slashes" (http://pkware.com/documents/casestudies/APPNOTE.TXT) // TODO On Linux file names can contain backslashes which should not treated as file separators. // Unfortunately, only the file separator char of the master is known (File.separatorChar) // but not the file separator char of the (maybe remote) "dir". ZipEntry e = new ZipEntry(relativePath.replace('\\', '/')); e.setTime(vf.lastModified()); zos.putNextEntry(e); try (InputStream in = vf.open()) { IOUtils.copy(in, zos); } finally { zos.closeEntry(); } }
Source:
private static void sendZipUsingMap(ZipOutputStream zos, VirtualFile dir, Map<String, VirtualFile> nameToVirtualFiles) throws IOException { for (Map.Entry<String, VirtualFile> entry : nameToVirtualFiles.entrySet()) { String n = entry.getKey(); String relativePath; // JENKINS-19947: traditional behavior is to prepend the directory name relativePath = dir.getName() + '/' + n; VirtualFile f = entry.getValue(); sendOneZipEntry(zos, f, relativePath); } }

Target:
private static void sendZipUsingMap(ZipOutputStream zos, VirtualFile dir, Map<String, VirtualFile> nameToVirtualFiles) throws IOException { for (Map.Entry<String, VirtualFile> entry : nameToVirtualFiles.entrySet()) { String n = entry.getKey(); // JENKINS-19947: traditional behavior is to prepend the directory name String relativePath = dir.getName() + '/' + n; VirtualFile f = entry.getValue(); sendOneZipEntry(zos, f, relativePath); } }
Source:
private Set<String> dependantsToCheck(PluginDisableStrategy strategy) { Set<String> dependantsToCheck; switch (strategy) { case MANDATORY: // As of getDependants has all the dependants, we get the difference between them and only the optionals dependantsToCheck = Sets.difference(this.getDependants(), this.getOptionalDependants()); break; case ALL: // getDependants returns all the dependant plugins, mandatory or optional. dependantsToCheck = this.getDependants(); break; case NONE: default: // with NONE, the process only fail if mandatory dependant plugins exists dependantsToCheck = Sets.difference(this.getDependants(), this.getOptionalDependants()); } return dependantsToCheck; }

Target:
private Set<String> dependantsToCheck(PluginDisableStrategy strategy) { Set<String> dependantsToCheck; switch (strategy) { case ALL: // getDependants returns all the dependant plugins, mandatory or optional. dependantsToCheck = this.getDependants(); break; default: // It includes MANDATORY, NONE: // with NONE, the process only fail if mandatory dependant plugins exists // As of getDependants has all the dependants, we get the difference between them and only the optionals dependantsToCheck = Sets.difference(this.getDependants(), this.getOptionalDependants()); } return dependantsToCheck; }