auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testAddOlderBlock() { CachedBlockQueue queue = new CachedBlockQueue(10000L, 1000L); CachedBlock cb1 = new CachedBlock(5000L, "cb1", 3L); cb1.recordSize(new AtomicLong(5000L)); CachedBlock cb2 = new CachedBlock(5000, "cb2", 2L); cb2.recordSize(new AtomicLong(5000L)); CachedBlock cb3 = new CachedBlock(5000, "cb3", 1L); cb3.recordSize(new AtomicLong(5000L)); assertTrue(queue.add(cb1)); assertTrue(queue.add(cb2)); assertTrue(queue.add(cb3)); assertEquals(2, queue.size()); }

Target:
public void testAddOlderBlock() { CachedBlockQueue queue = new CachedBlockQueue(10000L, 1000L); CachedBlock cb1 = new CachedBlock(5000L, "cb1", 3L); CachedBlock cb2 = new CachedBlock(5000, "cb2", 2L); CachedBlock cb3 = new CachedBlock(5000, "cb3", 1L); assertTrue(queue.add(cb1)); assertTrue(queue.add(cb2)); assertTrue(queue.add(cb3)); assertEquals(Arrays.asList("cb3", "cb2"), queue.getBlocks().stream().map(cb -> cb.getName()).collect(Collectors.toList())); assertEquals(2, queue.size()); }
Source:
public void handleIndexUpdate(Entry entry, ElasticMode command) { if (entry == null) { return; } LOGGER.info("Performing index update with " + command + "."); if (ElasticManager.hostname == null || ElasticManager.hostname.isEmpty()) { LOGGER.error("No elastic search host found."); return; } if (!checkValid(entry, command)) { LOGGER.info("Could not perform the elastic search index update."); return; } String json = getDocumentValueFromEntry(entry); try (RestClient restClient = RestClient.builder(new HttpHost(ElasticManager.hostname, ElasticManager.port, "http")).build()) { String entryType = entry instanceof Tool ? "tool" : "workflow"; HttpEntity entity = new NStringEntity(json, ContentType.APPLICATION_JSON); org.elasticsearch.client.Response post; switch (command) { case UPDATE: post = restClient .performRequest("POST", "/entry/" + entryType + "/" + entry.getId() + "/_update" + "?refresh=wait_for", Collections.emptyMap(), entity); break; case DELETE: post = restClient.performRequest("DELETE", "/entry/" + entryType + "/" + entry.getId() + "?refresh=wait_for", Collections.emptyMap(), entity); break; default: throw new RuntimeException("Unknown index command: " + command); } int statusCode = post.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) { LOGGER.info("Successful " + command + "."); } else { LOGGER.error("Could not submit index to elastic search. " + post.getStatusLine().getReasonPhrase()); } } catch (IOException e) { LOGGER.error("Could not submit index to elastic search. " + e.getMessage()); } }

Target:
public void handleIndexUpdate(Entry entry, ElasticMode command) { entry = filterCheckerWorkflows(entry); if (entry == null) { return; } LOGGER.info("Performing index update with " + command + "."); if (ElasticManager.hostname == null || ElasticManager.hostname.isEmpty()) { LOGGER.error("No elastic search host found."); return; } if (!checkValid(entry, command)) { LOGGER.error("Could not perform the elastic search index update."); return; } String json = getDocumentValueFromEntry(entry); try (RestClient restClient = RestClient.builder(new HttpHost(ElasticManager.hostname, ElasticManager.port, "http")).build()) { String entryType = entry instanceof Tool ? "tool" : "workflow"; HttpEntity entity = new NStringEntity(json, ContentType.APPLICATION_JSON); org.elasticsearch.client.Response post; switch (command) { case UPDATE: post = restClient .performRequest("POST", "/entry/" + entryType + "/" + entry.getId() + "/_update", Collections.emptyMap(), entity); break; case DELETE: post = restClient.performRequest("DELETE", "/entry/" + entryType + "/" + entry.getId(), Collections.emptyMap(), entity); break; default: throw new RuntimeException("Unknown index command: " + command); } int statusCode = post.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) { LOGGER.info("Successful " + command + "."); } else { LOGGER.info("Could not submit index to elastic search. " + post.getStatusLine().getReasonPhrase()); } } catch (IOException e) { LOGGER.error("Could not submit index to elastic search. " + e.getMessage()); } }
Source:
public void should_not_call_listener_when_verify_was_called_incorrectly() { VerificationListener listener = mock(VerificationListener.class); framework().addListener(listener); Foo foo = null; try { verify(foo).doSomething(""); fail("Exception expected."); } catch (Exception e) { verify(listener, never()).onVerification(any(VerificationEvent.class)); } }

Target:
public void should_not_call_listener_when_verify_was_called_incorrectly() { Foo foo = null; VerificationListener mockListener = mock(VerificationListener.class); framework().addListener(mockListener); try { verify(foo).doSomething(""); fail("Exception expected."); } catch (Exception e) { verify(mockListener, never()).onVerification(any(VerificationEvent.class)); } }
Source:
public final void close() throws SQLException { if (delegate != ClosedConnection.CLOSED_CONNECTION) { leakTask.cancel(); closeStatements(); try { if (isCommitStateDirty) { if (!poolEntry.isAutoCommit) { delegate.rollback(); lastAccess = clockSource.currentTime(); 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.evict) { throw checkException(e); } } finally { delegate = ClosedConnection.CLOSED_CONNECTION; poolEntry.releaseConnection(lastAccess); } } }

Target:
public final void close() throws SQLException { if (delegate != ClosedConnection.CLOSED_CONNECTION) { leakTask.cancel(); try { closeStatements(); if (isCommitStateDirty) { if (!poolEntry.isAutoCommit) { delegate.rollback(); lastAccess = clockSource.currentTime(); 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.evict) { throw checkException(e); } } finally { delegate = ClosedConnection.CLOSED_CONNECTION; poolEntry.releaseConnection(lastAccess); } } }
Source:
Long getTimestamp(long runId, AggregationConstants.AGGREGATION_TYPE aggType) { if (AggregationConstants.AGGREGATION_TYPE.DAILY.equals(aggType)) { long dayTimestamp = runId - (runId % Constants.MILLIS_ONE_DAY); return dayTimestamp; } else if (AggregationConstants.AGGREGATION_TYPE.WEEKLY.equals(aggType)) { Calendar c = Calendar.getInstance(); c.setTimeInMillis(runId); int d = c.get(Calendar.DAY_OF_WEEK); long weekTimestamp = runId - (d - 1) * Constants.MILLIS_ONE_DAY; weekTimestamp = weekTimestamp - weekTimestamp % Constants.MILLIS_ONE_DAY; return weekTimestamp; } return 0L; }

Target:
long getTimestamp(long runId, AggregationConstants.AGGREGATION_TYPE aggType) { if (AggregationConstants.AGGREGATION_TYPE.DAILY.equals(aggType)) { long dayTimestamp = runId - (runId % Constants.MILLIS_ONE_DAY); return dayTimestamp; } else if (AggregationConstants.AGGREGATION_TYPE.WEEKLY.equals(aggType)) { Calendar c = Calendar.getInstance(); c.setTimeInMillis(runId); int d = c.get(Calendar.DAY_OF_WEEK); long weekTimestamp = runId - (d - 1) * Constants.MILLIS_ONE_DAY; weekTimestamp = weekTimestamp - weekTimestamp % Constants.MILLIS_ONE_DAY; return weekTimestamp; } return 0L; }
Source:
public IRubyObject update(final ThreadContext context, final IRubyObject arg, IRubyObject buffer) { final Ruby runtime = context.runtime; if ( isDebug(runtime) ) dumpVars( runtime.getOut(), "update()" ); checkCipherNotNull(runtime); checkAuthTag(runtime); final ByteList data = arg.asString().getByteList(); final int length = data.getRealSize(); if ( length == 0 ) { throw runtime.newArgumentError("data must not be empty"); } if ( ! cipherInited ) doInitCipher(runtime); final ByteList str; try { updateAuthData(runtime); final byte[] in = data.getUnsafeBytes(); final int offset = data.begin(); final byte[] out = cipher.update(in, offset, length); if ( out != null ) { str = new ByteList(out, false); if ( realIV != null ) { if ( encryptMode ) setLastIVIfNeeded( out ); else setLastIVIfNeeded( in, offset, length ); } processedDataBytes += length; } else { str = new ByteList(ByteList.NULL_ARRAY); } } catch (Exception e) { debugStackTrace( runtime, e ); throw newCipherError(runtime, e); } if( buffer == null ) { return RubyString.newString(runtime, str); } else { return ((RubyString) buffer).replace(RubyString.newString(runtime, str)); } }

Target:
public IRubyObject update(final ThreadContext context, final IRubyObject arg, IRubyObject buffer) { final Ruby runtime = context.runtime; if ( isDebug(runtime) ) dumpVars( runtime.getOut(), "update()" ); checkCipherNotNull(runtime); checkAuthTag(runtime); final ByteList data = arg.asString().getByteList(); final int length = data.getRealSize(); if ( length == 0 ) { throw runtime.newArgumentError("data must not be empty"); } if ( ! cipherInited ) doInitCipher(runtime); final ByteList str; try { updateAuthData(runtime); final byte[] in = data.getUnsafeBytes(); final int offset = data.begin(); final byte[] out = cipher.update(in, offset, length); if ( out != null ) { str = new ByteList(out, false); if ( realIV != null ) { if ( encryptMode ) setLastIVIfNeeded( out ); else setLastIVIfNeeded( in, offset, length ); } processedDataBytes += length; } else { str = new ByteList(ByteList.NULL_ARRAY); } } catch (Exception e) { debugStackTrace( runtime, e ); throw newCipherError(runtime, e); } if( buffer == null ) { return RubyString.newString(runtime, str); } else { buffer = TypeConverter.convertToType(buffer, context.runtime.getString(), "to_str", true); return ((RubyString) buffer).replace(RubyString.newString(runtime, str)); } }
Source:
public void mergeUpdatePidFromNitro( HttpServletResponse response, @PathVariable("pid") String pid ) throws IOException { Set<Item> mergedItems; try { Iterable<List<Item>> items = contentAdapter .fetchEpisodes(ProgrammesQuery.builder() .withPid(pid) .withMixins(ANCESTOR_TITLES, CONTRIBUTIONS, IMAGES, GENRE_GROUPINGS) .withPageSize(1) .build()); mergedItems = localOrRemoteNitroFetcher.resolveItemsForMerge(items).getAll(); } catch (NitroException e) { log.error("Failed to get Nitro item {}", pid, e); writeServerErrorWithStack(response, e); return; } if (mergedItems.isEmpty()) { log.error("No items found in Nitro for pid {}", pid); response.setStatus(HttpStatusCode.NOT_FOUND.code()); response.setContentLength(0); return; } createOrUpdateItems(response, pid, mergedItems.iterator()); }

Target:
public void mergeUpdatePidFromNitro( HttpServletResponse response, @PathVariable("pid") String pid ) throws IOException { Item item; try { Iterable<List<Item>> itemListIterable = contentAdapter .fetchEpisodes(ProgrammesQuery.builder() .withPid(pid) .withMixins(ANCESTOR_TITLES, CONTRIBUTIONS, IMAGES, GENRE_GROUPINGS) .withPageSize(1) .build()); Iterable<Item> allItems = Iterables.concat(itemListIterable); item = Iterables.getOnlyElement(localOrRemoteNitroFetcher.resolveItems(allItems).getAll()); } catch (NoSuchElementException e) { log.error("No items found in Nitro for pid {}", pid); response.setStatus(HttpStatusCode.NOT_FOUND.code()); response.setContentLength(0); return; } catch (NitroException e) { log.error("Failed to get Nitro item {}", pid, e); writeServerErrorWithStack(response, e); return; } createOrUpdateItem(response, pid, item); }
Source:
private static boolean canCreateBlockCompresedIndexedFastaSequence(final Path path) { try { return IOUtil.isBlockCompressed(path) && Files.exists(GZIIndex.resolveIndexNameForBgzipFile(path)); } catch (IOException e) { return false; } }

Target:
private static boolean canCreateBlockCompresedIndexedFastaSequence(final Path path) { try { return IOUtil.isBlockCompressed(path, true) && Files.exists(GZIIndex.resolveIndexNameForBgzipFile(path)); } catch (IOException e) { return false; } }
Source:
protected boolean showMoveUpButton() { return true; }

Target:
protected boolean showMoveUpButton() { return false; }
Source:
public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Basic usage", "char_is_uppercase('a')"), new ExampleScript("", "char_is_uppercase('D')"),}; }

Target:
public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Basic usage", "char_is_uppercase('a')"), new ExampleScript("Basic usage", "char_is_uppercase('D')"),}; }
Source:
public void close() throws IOException { try { lock.lockInterruptibly(); try { if (!close) { if (err != null) { len = 0; flush = false; } close = true; execute(); } } finally { lock.unlock(); } copier.join(); } catch (InterruptedException e) { throw interrupted(e); } }

Target:
public void close() throws IOException { if (!copier.isShutdown()) { try { execute(new Callable<Void>() { @Override public Void call() throws IOException { dst.close(); return null; } }); } finally { copier.shutdown(); } } }
Source:
public void addFunction( final String name, final String description, final String outputType, final Boolean isMultiValued, final String binary) throws DbException { if (!isValid()) { connect(); } String tableName = MyriaConstants.PYUDF_RELATION.toString(MyriaConstants.STORAGE_SYSTEM_POSTGRESQL); StringBuilder sb = new StringBuilder(); sb.append("DELETE FROM "); sb.append(tableName); sb.append(" where function_name='"); sb.append(name); sb.append("'"); String sql = sb.toString(); accessMethod.execute(sql); pyFunctions.putString(0, name); pyFunctions.putString(1, description); pyFunctions.putString(2, outputType); pyFunctions.putBoolean(3, isMultiValued); pyFunctions.putString(4, binary); accessMethod.tupleBatchInsert(MyriaConstants.PYUDF_RELATION, pyFunctions.popAny()); return; }

Target:
public void addFunction( final String name, final String description, final String outputType, final Boolean isMultiValued, final String binary) throws DbException { if (!isValid()) { connect(); } String tableName = MyriaConstants.PYUDF_RELATION.toString(MyriaConstants.STORAGE_SYSTEM_POSTGRESQL); StringBuilder sb = new StringBuilder(); sb.append("DELETE FROM "); sb.append(tableName); sb.append(" where function_name='"); sb.append(name); sb.append("'"); String sql = sb.toString(); accessMethod.execute(sql); pyFunctions.putString(0, name); pyFunctions.putString(1, description); pyFunctions.putString(2, outputType); pyFunctions.putBoolean(3, isMultiValued); pyFunctions.putString(4, binary); accessMethod.tupleBatchInsert(MyriaConstants.PYUDF_RELATION, pyFunctions.popAny()); }
Source:
public void testNothing() throws CacheAccessException { final ServiceLocator serviceLocator = new ServiceLocator(); try { serviceLocator.startAllServices(new HashMap<Service, ServiceConfiguration<?>>()); } catch (Exception e) { throw new CacheAccessException(e); } final CacheConfiguration<String, String> config = newCacheConfigurationBuilder().buildConfig(String.class, String.class); final Store.Provider service = serviceLocator.findService(Store.Provider.class); Collection<ServiceConfiguration<?>> serviceConfigs = config.getServiceConfigurations(); ServiceConfiguration<?>[] serviceConfigArray = serviceConfigs.toArray(new ServiceConfiguration[serviceConfigs.size()]); final Store<String, String> store = service.createStore(new StoreConfigurationImpl<String, String>(config), serviceConfigArray); @SuppressWarnings("unchecked") final Cache<String, String> cache = new HeapCache<String, String>(mock(CacheConfiguration.class), store, LoggerFactory.getLogger(Ehcache.class + "-" + "CachingTierConfigurationBuilderTest")); assertThat(cache, not(hasKey("key"))); cache.put("key", "value"); assertThat(cache, hasKey("key")); }

Target:
public void testNothing() throws Exception { final ServiceLocator serviceLocator = new ServiceLocator(); serviceLocator.startAllServices(new HashMap<Service, ServiceConfiguration<?>>()); final CacheConfiguration<String, String> config = newCacheConfigurationBuilder().buildConfig(String.class, String.class); final Store.Provider service = serviceLocator.findService(Store.Provider.class); Collection<ServiceConfiguration<?>> serviceConfigs = config.getServiceConfigurations(); ServiceConfiguration<?>[] serviceConfigArray = serviceConfigs.toArray(new ServiceConfiguration[serviceConfigs.size()]); final Store<String, String> store = service.createStore(new StoreConfigurationImpl<String, String>(config), serviceConfigArray); @SuppressWarnings("unchecked") final Cache<String, String> cache = new HeapCache<String, String>(mock(CacheConfiguration.class), store, LoggerFactory.getLogger(Ehcache.class + "-" + "CachingTierConfigurationBuilderTest")); assertThat(cache, not(hasKey("key"))); cache.put("key", "value"); assertThat(cache, hasKey("key")); }
Source:
private Supplier<DruidLongPredicate> getLongPredicateSupplier() { return new Supplier<DruidLongPredicate>() { private final Object initLock = new Object(); private DruidLongPredicate predicate; private void initLongValues() { if (predicate != null) { return; } synchronized (initLock) { if (predicate != null) { return; } List<Long> longs = new ArrayList<>(); for (String value : values) { Long longValue = GuavaUtils.tryParseLong(value); if (longValue != null) { longs.add(longValue); } } if (longs.size() > LONG_HASHING_THRESHOLD) { final HashSet<Long> longHashSet = new HashSet<>(longs); predicate = new DruidLongPredicate() { @Override public boolean applyLong(long input) { return longHashSet.contains(input); } }; } else { final long[] longArray; longArray = new long[longs.size()]; for (int i = 0; i < longs.size(); i++) { longArray[i] = longs.get(i).longValue(); } Arrays.sort(longArray); predicate = new DruidLongPredicate() { @Override public boolean applyLong(long input) { return Arrays.binarySearch(longArray, input) >= 0; } }; } } } @Override public DruidLongPredicate get() { initLongValues(); return predicate; } }; }

Target:
private Supplier<DruidLongPredicate> getLongPredicateSupplier() { return new Supplier<DruidLongPredicate>() { private final Object initLock = new Object(); private DruidLongPredicate predicate; private void initLongValues() { if (predicate != null) { return; } synchronized (initLock) { if (predicate != null) { return; } LongArrayList longs = new LongArrayList(values.size()); for (String value : values) { Long longValue = GuavaUtils.tryParseLong(value); if (longValue != null) { longs.add(longValue); } } if (longs.size() > NUMERIC_HASHING_THRESHOLD) { final LongOpenHashSet longHashSet = new LongOpenHashSet(longs); predicate = new DruidLongPredicate() { @Override public boolean applyLong(long input) { return longHashSet.contains(input); } }; } else { final long[] longArray = longs.toLongArray(); Arrays.sort(longArray); predicate = new DruidLongPredicate() { @Override public boolean applyLong(long input) { return Arrays.binarySearch(longArray, input) >= 0; } }; } } } @Override public DruidLongPredicate get() { initLongValues(); return predicate; } }; }
Source:
public SessionWindowOperator(final String queryId, final String operatorId, final int sessionInterval) { super(queryId, operatorId); this.sessionInterval = sessionInterval; this.latestEventTimestamp = Long.MIN_VALUE; }

Target:
public SessionWindowOperator(final String queryId, final String operatorId, final int sessionInterval) { super(queryId, operatorId); this.sessionInterval = sessionInterval; currentWindow = null; }
Source:
public JedisPool(final String host) { URI uri = URI.create(host); if (JedisURIHelper.isValid(uri)) { this.internalPool = new GenericObjectPool<Jedis>(new JedisFactory(uri, Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, null), new GenericObjectPoolConfig<Jedis>()); } else { this.internalPool = new GenericObjectPool<Jedis>(new JedisFactory(host, Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE, null), new GenericObjectPoolConfig<Jedis>()); } }

Target:
public JedisPool(final String host) { URI uri = URI.create(host); if (JedisURIHelper.isValid(uri)) { this.internalPool = new GenericObjectPool<>(new JedisFactory(uri, Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, null), new GenericObjectPoolConfig()); } else { this.internalPool = new GenericObjectPool<>(new JedisFactory(host, Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE, null), new GenericObjectPoolConfig()); } }
Source:
public Authentication.Result findAuthenticationResult(URI uri) { requireNonNull(uri, "uri is null"); if (uri.getScheme().equalsIgnoreCase("https")) { return results.getIfPresent(UrlUtil.normalizedUri(uri)); } return null; }

Target:
public Authentication.Result findAuthenticationResult(URI uri) { requireNonNull(uri, "uri is null"); if ("https".equalsIgnoreCase(uri.getScheme())) { return results.getIfPresent(UriUtil.normalizedUri(uri)); } return null; }
Source:
public int compareTo(Duration other) { if (count == 0 && other.count == 0) { return 0; } if (count < 0 && other.count >= 0) { return -1; } if (count >= 0 && other.count < 0) { return 1; } if (unit == other.unit) { return Long.compare(count, other.count); } return Long.compare(toNanoseconds(), other.toNanoseconds()); }

Target:
public int compareTo(Duration other) { if (unit == other.unit) { return Long.compare(count, other.count); } return Long.compare(toNanoseconds(), other.toNanoseconds()); }
Source:
public static OMClientRequest createClientRequest(OMRequest omRequest) { Type cmdType = omRequest.getCmdType(); switch (cmdType) { case CreateVolume: return new OMVolumeCreateRequest(omRequest); case SetVolumeProperty: boolean hasQuota = omRequest.getSetVolumePropertyRequest() .hasQuotaInBytes(); boolean hasOwner = omRequest.getSetVolumePropertyRequest().hasOwnerName(); Preconditions.checkState(hasOwner || hasQuota, "Either Quota or owner " + "shuould be set in the SetVolumeProperty request"); if (omRequest.getSetVolumePropertyRequest().hasQuotaInBytes()) { return new OMVolumeSetQuotaRequest(omRequest); } else if(omRequest.getSetVolumePropertyRequest().hasOwnerName()) { return new OMVolumeSetOwnerRequest(omRequest); } case DeleteVolume: return new OMVolumeDeleteRequest(omRequest); case CreateBucket: return new OMBucketCreateRequest(omRequest); case DeleteBucket: return new OMBucketDeleteRequest(omRequest); case SetBucketProperty: return new OMBucketSetPropertyRequest(omRequest); default: return null; } }

Target:
public static OMClientRequest createClientRequest(OMRequest omRequest) { Type cmdType = omRequest.getCmdType(); switch (cmdType) { case CreateVolume: return new OMVolumeCreateRequest(omRequest); case SetVolumeProperty: boolean hasQuota = omRequest.getSetVolumePropertyRequest() .hasQuotaInBytes(); boolean hasOwner = omRequest.getSetVolumePropertyRequest().hasOwnerName(); Preconditions.checkState(hasOwner || hasQuota, "Either Quota or owner " + "should be set in the SetVolumeProperty request"); Preconditions.checkState(!(hasOwner && hasQuota), "Either Quota or " + "owner should be set in the SetVolumeProperty request. Should not " + "set both"); if (hasQuota) { return new OMVolumeSetQuotaRequest(omRequest); } else { return new OMVolumeSetOwnerRequest(omRequest); } case DeleteVolume: return new OMVolumeDeleteRequest(omRequest); case CreateBucket: return new OMBucketCreateRequest(omRequest); case DeleteBucket: return new OMBucketDeleteRequest(omRequest); case SetBucketProperty: return new OMBucketSetPropertyRequest(omRequest); default: return null; } }
Source:
@Test public void testSpaceInUrl() { String url = "file:/ final Source foo = Sources.url(url); assertEquals(url + " .file().getAbsolutePath()", "/dir name/test file.json", foo.file().getAbsolutePath().replace('\\', '/')); }

Target:
@Test public void testSpaceInUrl() { String url = "file:" + ROOT_PREFIX + "dir%20name/test%20file.json"; final Source foo = url(url); assertEquals(url + " .file().getAbsolutePath()", new File(ROOT_PREFIX + "dir name/test file.json").getAbsolutePath(), foo.file().getAbsolutePath()); }
Source:
public void getValues(MeasurementReport report, Set<MeasurementScheduleRequest> schedules) throws Exception { if (ApacheServerComponent.getUseBMX()) getBMXValues(report, schedules); else getSNMPValues(report, schedules); }

Target:
public void getValues(MeasurementReport report, Set<MeasurementScheduleRequest> schedules) throws Exception { if (resourceContext.getParentResourceComponent().getUseBMX()) getBMXValues(report, schedules); else getSNMPValues(report, schedules); }
Source:
public <T> List<T> getList(String filename, int type) { List<T> list = new ArrayList<T>(); BufferedReader br = null; try{ br = new BufferedReader(new InputStreamReader(context.getAssets().open(filename))); while ((line = br.readLine()) != null) { row = line.split(csvSplitBy); if(row.length > 0) { switch (type) { case 0: list.add((T) new Question(Integer.valueOf(row[0]), Integer.valueOf(row[1]), row[2])); break; case 1: list.add((T) new Answer(Integer.valueOf(row[0]), Integer.valueOf(row[1]), row[2], Integer.valueOf(row[3]), Integer.valueOf(row[4]))); break; case 2: list.add((T) new Scenario(Integer.valueOf(row[0]), row[1], row[2], row[3], Integer.valueOf(row[4]), Integer.valueOf(row[5]), 0, Integer.valueOf(row[6]), 0)); break; case 3: list.add((T) new Clothes(Integer.valueOf(row[0]), row[1], Integer.valueOf(row[2]), 0)); break; case 4: list.add((T) new Hair(Integer.valueOf(row[0]), row[1], Integer.valueOf(row[2]), 0)); break; case 5: list.add((T) new Accessory(Integer.valueOf(row[0]), row[1], Integer.valueOf(row[2]), 0)); } } } } catch (IOException e) { Log.e(TAG, e.toString()); } finally { try { if (br != null) { br.close(); } } catch (IOException e) { Log.e(TAG, e.toString()); } } return list; }

Target:
public <T> List<T> getList(String filename, int type) { List<T> list = new ArrayList<T>(); BufferedReader br = null; try{ br = new BufferedReader(new InputStreamReader(context.getAssets().open(filename))); while ((line = br.readLine()) != null) { row = line.split(csvSplitBy); if(row.length > 0) { switch (type) { case 0: list.add((T) new Question(Integer.valueOf(row[0]), Integer.valueOf(row[1]), row[2])); break; case 1: list.add((T) new Answer(Integer.valueOf(row[0]), Integer.valueOf(row[1]), row[2], Integer.valueOf(row[3]), Integer.valueOf(row[4]))); break; case 2: list.add((T) new Scenario(Integer.valueOf(row[0]), row[1], row[2], row[3], Integer.valueOf(row[4]), Integer.valueOf(row[5]), 0, Integer.valueOf(row[6]), 0)); break; case 3: list.add((T) new Clothes(Integer.valueOf(row[0]), row[1], Integer.valueOf(row[2]), 0)); break; case 4: list.add((T) new Hair(Integer.valueOf(row[0]), row[1], Integer.valueOf(row[2]), 0)); break; case 5: list.add((T) new Accessory(Integer.valueOf(row[0]), row[1], Integer.valueOf(row[2]), 0)); break; default: Log.e(TAG, "Invalid file type"); } } } } catch (IOException e) { Log.e(TAG, "IOException while opening the file: "+ filename); } finally { try { if (br != null) { br.close(); } } catch (IOException e) { Log.e(TAG, "IOException while closing the file: "+ filename); } } return list; }
Source:
public NodeMetadata apply(VirtualGuest from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId() + ""); builder.name(from.getHostname()); builder.hostname(from.getHostname() + from.getDomain()); if (from.getDatacenter() != null) { builder.location(from(locations.get()).firstMatch( LocationPredicates.idEquals(from.getDatacenter().getId() + "")).orNull()); } builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from.getHostname())); builder.hardware(new VirtualGuestToHardware().apply(from)); Image image = virtualGuestToImage.apply(from); if (image != null) { builder.imageId(image.getId()); builder.operatingSystem(image.getOperatingSystem()); } if(from.getPowerState() != null) { builder.status(serverStateToNodeStatus.get(from.getPowerState().getKeyName())); } if (from.getPrimaryIpAddress() != null) builder.publicAddresses(ImmutableSet.of(from.getPrimaryIpAddress())); if (from.getPrimaryBackendIpAddress() != null) builder.privateAddresses(ImmutableSet.of(from.getPrimaryBackendIpAddress())); if(from.getTagReferences() != null && !from.getTagReferences().isEmpty()) { List<String> tags = Lists.newArrayList(); for (TagReference tagReference : from.getTagReferences()) { if (tagReference != null) { tags.add(tagReference.getTag().getName()); } } builder.tags(tags); } return builder.build(); }

Target:
public NodeMetadata apply(VirtualGuest from) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(from.getId() + ""); builder.name(from.getHostname()); builder.hostname(from.getHostname() + from.getDomain()); if (from.getDatacenter() != null) { builder.location(from(locations.get()).firstMatch( LocationPredicates.idEquals(from.getDatacenter().getId() + "")).orNull()); } builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from.getHostname())); builder.hardware(virtualGuestToHardware.apply(from)); Image image = virtualGuestToImage.apply(from); if (image != null) { builder.imageId(image.getId()); builder.operatingSystem(image.getOperatingSystem()); } if (from.getPowerState() != null) { builder.status(serverStateToNodeStatus.get(from.getPowerState().getKeyName())); } if (from.getPrimaryIpAddress() != null) builder.publicAddresses(ImmutableSet.of(from.getPrimaryIpAddress())); if (from.getPrimaryBackendIpAddress() != null) builder.privateAddresses(ImmutableSet.of(from.getPrimaryBackendIpAddress())); if (from.getTagReferences() != null && !from.getTagReferences().isEmpty()) { List<String> tags = Lists.newArrayList(); for (TagReference tagReference : from.getTagReferences()) { if (tagReference != null) { tags.add(tagReference.getTag().getName()); } } builder.tags(tags); } return builder.build(); }
Source:
public static Map<ZooType,InstantiableModel> select(ZooType zooType, int numLabels, int seed, int iterations) { Map<ZooType,InstantiableModel> netmap = new HashMap<>(); switch(zooType) { case ALL: netmap.putAll(ModelSelector.select(ZooType.CNN, numLabels, seed, iterations)); netmap.putAll(ModelSelector.select(ZooType.RNN, numLabels, seed, iterations)); break; case CNN: netmap.putAll(ModelSelector.select(ZooType.ALEXNET, numLabels, seed, iterations)); netmap.putAll(ModelSelector.select(ZooType.VGG16, numLabels, seed, iterations)); break; case ALEXNET: netmap.put(ZooType.ALEXNET, new AlexNet(numLabels, seed, iterations)); break; case LENET: netmap.put(ZooType.LENET, new LeNet(numLabels, seed, iterations)); break; case INCEPTIONRESNETV1: netmap.put(ZooType.INCEPTIONRESNETV1, new InceptionResNetV1(numLabels, seed, iterations)); break; case FACENETNN4SMALL2: netmap.put(ZooType.FACENETNN4SMALL2, new FaceNetNN4Small2(numLabels, seed, iterations)); break; case VGG16: netmap.put(ZooType.VGG16, new VGG16(numLabels, seed, iterations)); break; default: } if(netmap.size()==0) throw new IllegalArgumentException("Zero models have been selected for benchmarking."); return netmap; }

Target:
public static Map<ZooType, ZooModel> select(ZooType zooType, int numLabels, int seed, int iterations) { return select(zooType, numLabels, 123, 1, WorkspaceMode.SEPARATE); }
Source:
private SignupPageObject typeBirthdate(String month, String day, String year) { wait.forElementVisible(signupBirthdate); signupBirthdate.click(); safelySetValue(signupBirthMonth, month); safelySetValue(signupBirthDay, day); safelySetValue(signupBirthYear, year); return this; }

Target:
private SignupPageObject typeBirthdate(String month, String day, String year) { wait.forElementVisible(signupBirthdate); signupBirthdate.click(); setValue(signupBirthMonth, month); setValue(signupBirthDay, day); setValue(signupBirthYear, year); return this; }
Source:
public ParallelRowProcessor(RecordReader reader, EventHandler<GenericRow> handler) { this.reader = reader; this.disruptor = new Disruptor<GenericRow>( GenericRow::new, RING_SIZE, DaemonThreadFactory.INSTANCE, ProducerType.SINGLE, new BusySpinWaitStrategy()); this.disruptor.handleEventsWith(handler); }

Target:
public ParallelRowProcessor(RecordReader reader, EventHandler<GenericRow> handler) { _reader = reader; _disruptor = new Disruptor<GenericRow>( GenericRow::new, RING_SIZE, DaemonThreadFactory.INSTANCE, ProducerType.SINGLE, new BusySpinWaitStrategy()); _disruptor.handleEventsWith(handler); }
Source:
public static void setNetworkVdsmName(Network network) { if (network == null) { return; } String networkName = network.getName(); Guid networkId = network.getId(); if (networkId == null ) { networkId = Guid.newGuid(); } Matcher vdsmNameMatcher = VALID_VDS_NAME_PATTERN.matcher(networkName); if (networkName.length() > BusinessEntitiesDefinitions.HOST_NIC_NAME_LENGTH || !vdsmNameMatcher.matches()) { network.setVdsmName("on" + networkId.toString() .replaceAll("[^a-zA-Z0-9]+", "") .substring(0, BusinessEntitiesDefinitions.HOST_NIC_NAME_LENGTH - 2)); } else { network.setVdsmName(networkName); } }

Target:
public static void setNetworkVdsmName(Network network) { String networkName = network.getName(); if (VALID_VDS_NAME_PATTERN.matcher(networkName).matches()) { network.setVdsmName(networkName); } else { network.setVdsmName("on" + network.getId().toString() .replaceAll("[^a-zA-Z0-9]+", "") .substring(0, BusinessEntitiesDefinitions.HOST_NIC_NAME_LENGTH - 2)); } }
Source:
public boolean disconnect(Node fromNode, Node toNode) { Preconditions.checkNotNull(fromNode, "fromNode cannot be null!"); Preconditions.checkNotNull(toNode, "toNode cannot be null!"); return graph.removeEdge(fromNode, toNode); }

Target:
public void disconnect(Node fromNode, Node toNode) { Preconditions.checkNotNull(fromNode, "fromNode cannot be null!"); Preconditions.checkNotNull(toNode, "toNode cannot be null!"); if (!graph.hasEdgeConnecting(fromNode, toNode)) { logger.warn("Trying to disconnect two nodes that aren't connected, " + fromNode.getUri() + " and " + toNode.getUri()); } graph.removeEdge(fromNode, toNode); }
Source:
public ActualProperties visitWindow(WindowNode node, List<ActualProperties> inputProperties) { ActualProperties properties = Iterables.getOnlyElement(inputProperties); Optional<OrderingScheme> orderingScheme = node.getOrderingScheme(); if (ImmutableSet.copyOf(node.getPartitionBy()).equals(node.getPrePartitionedInputs()) && orderingScheme.isPresent() && node.getPreSortedOrderPrefix() == orderingScheme.get().getOrderBy().size()) { return properties; } ImmutableList.Builder<LocalProperty<Symbol>> localProperties = ImmutableList.builder(); if (!node.getPrePartitionedInputs().isEmpty()) { GroupingProperty<Symbol> prePartitionedProperty = new GroupingProperty<>(node.getPrePartitionedInputs()); for (LocalProperty<Symbol> localProperty : properties.getLocalProperties()) { if (!prePartitionedProperty.isSimplifiedBy(localProperty)) { break; } localProperties.add(localProperty); } } if (!node.getPartitionBy().isEmpty()) { localProperties.add(new GroupingProperty<>(node.getPartitionBy())); } orderingScheme.ifPresent(scheme -> scheme.getOrderBy().stream() .map(column -> new SortingProperty<>(column, scheme.getOrdering(column))) .forEach(localProperties::add)); return ActualProperties.builderFrom(properties) .local(LocalProperties.normalizeAndPrune(localProperties.build())) .build(); }

Target:
public ActualProperties visitWindow(WindowNode node, List<ActualProperties> inputProperties) { ActualProperties properties = Iterables.getOnlyElement(inputProperties); Optional<OrderingScheme> orderingScheme = node.getOrderingScheme(); if (ImmutableSet.copyOf(node.getPartitionBy()).equals(node.getPrePartitionedInputs()) && (!orderingScheme.isPresent() || node.getPreSortedOrderPrefix() == orderingScheme.get().getOrderBy().size())) { return properties; } ImmutableList.Builder<LocalProperty<Symbol>> localProperties = ImmutableList.builder(); if (!node.getPrePartitionedInputs().isEmpty()) { GroupingProperty<Symbol> prePartitionedProperty = new GroupingProperty<>(node.getPrePartitionedInputs()); for (LocalProperty<Symbol> localProperty : properties.getLocalProperties()) { if (!prePartitionedProperty.isSimplifiedBy(localProperty)) { break; } localProperties.add(localProperty); } } if (!node.getPartitionBy().isEmpty()) { localProperties.add(new GroupingProperty<>(node.getPartitionBy())); } orderingScheme.ifPresent(scheme -> scheme.getOrderBy().stream() .map(column -> new SortingProperty<>(column, scheme.getOrdering(column))) .forEach(localProperties::add)); return ActualProperties.builderFrom(properties) .local(LocalProperties.normalizeAndPrune(localProperties.build())) .build(); }
Source:
public final <T> Cursor getCursor(@NonNull final Query<T> query) { String[] projection = query.mProjection != null ? query.mProjection : getFullProjection(query.mTable.mType); String orderBy = query.mOrderBy; String groupBy = query.mGroupBy; if (query.mJoins.length > 0) { final String prefix = query.mTable.sqlPrefix(this); projection = projection.clone(); for (int i = 0; i < projection.length; i++) { projection[i] = projection[i].contains(".") ? projection[i] : prefix + projection[i]; } addPrefixToFields(orderBy, prefix); addPrefixToFields(groupBy, prefix); } final Pair<String, String[]> from = query.buildSqlFrom(this); final String tables = from.first; String[] args = from.second; final Pair<String, String[]> where = query.buildSqlWhere(this); args = ArrayUtils.merge(String.class, args, where.second); final Pair<String, String[]> having = query.buildSqlHaving(this); args = ArrayUtils.merge(String.class, args, having.second); final Cursor c = mDbHelper.getReadableDatabase() .query(query.mDistinct, tables, projection, where.first, args, groupBy, having.first, orderBy, null); c.moveToPosition(-1); return c; }

Target:
public final <T> Cursor getCursor(@NonNull final Query<T> query) { String[] projection = query.mProjection != null ? query.mProjection : getFullProjection(query.mTable.mType); String orderBy = query.mOrderBy; if (query.mJoins.length > 0) { final String prefix = query.mTable.sqlPrefix(this); projection = projection.clone(); for (int i = 0; i < projection.length; i++) { projection[i] = projection[i].contains(".") ? projection[i] : prefix + projection[i]; } orderBy = addPrefixToFields(orderBy, prefix); } final Pair<String, String[]> from = query.buildSqlFrom(this); final String tables = from.first; String[] args = from.second; final Pair<String, String[]> where = query.buildSqlWhere(this); args = ArrayUtils.merge(String.class, args, where.second); String groupBy = null; String having = null; if (query.mGroupBy.length > 0) { final StringBuilder groupByBuilder = new StringBuilder(); boolean firstTime = true; for (final Field field : query.mGroupBy) { if (!firstTime) { groupByBuilder.append(','); } groupByBuilder.append(field.buildSql(this).first); firstTime = false; } groupBy = groupByBuilder.toString(); final Pair<String, String[]> havingRaw = query.buildSqlHaving(this); having = havingRaw.first; args = ArrayUtils.merge(String.class, args, havingRaw.second); } final Cursor c = mDbHelper.getReadableDatabase() .query(query.mDistinct, tables, projection, where.first, args, groupBy, having, orderBy, null); c.moveToPosition(-1); return c; }
Source:
public void testMatches() { fFilter.addChild(TRUE_NODE); fFilter.addChild(TRUE_NODE); assertTrue(fFilter.matches(fEvent)); fFilter.replaceChild(0, FALSE_NODE); assertFalse(fFilter.matches(fEvent)); fFilter.setNot(true); assertTrue(fFilter.matches(fEvent)); }

Target:
public void testMatches() { fFilter.setNot(false); assertFalse(fFilter.matches(fEvent)); fFilter.setNot(true); assertTrue(fFilter.matches(fEvent)); fFilter.setNot(false); fFilter.addChild(TRUE_NODE); fFilter.addChild(TRUE_NODE); assertTrue(fFilter.matches(fEvent)); fFilter.setNot(true); assertFalse(fFilter.matches(fEvent)); fFilter.replaceChild(0, FALSE_NODE); assertTrue(fFilter.matches(fEvent)); fFilter.replaceChild(1, FALSE_NODE); fFilter.setNot(true); assertTrue(fFilter.matches(fEvent)); fFilter.setNot(false); assertFalse(fFilter.matches(fEvent)); }
Source:
protected boolean checkVmOnHost(final VirtualMachine vm, final long hostId) throws AgentUnavailableException, OperationTimedoutException { final Answer answer = _agentMgr.send(hostId, new CheckVirtualMachineCommand(vm.getInstanceName())); if (answer == null || !answer.getResult()) { return false; } if (answer instanceof CheckVirtualMachineAnswer) { final CheckVirtualMachineAnswer vmAnswer = (CheckVirtualMachineAnswer)answer; if (vmAnswer.getState() == PowerState.PowerOff) { return false; } } UserVmVO userVm = _userVmDao.findById(vm.getId()); if (userVm != null) { List<VMSnapshotVO> vmSnapshots = _vmSnapshotDao.findByVm(vm.getId()); RestoreVMSnapshotCommand command = _vmSnapshotMgr.createRestoreCommand(userVm, vmSnapshots); if (command != null) { RestoreVMSnapshotAnswer restoreVMSnapshotAnswer = (RestoreVMSnapshotAnswer) _agentMgr.send(hostId, command); if (restoreVMSnapshotAnswer == null || !restoreVMSnapshotAnswer.getResult()) { s_logger.warn("Unable to restore the vm snapshot from image file after migration to the VM: " + restoreVMSnapshotAnswer.getDetails()); } } } return true; }

Target:
protected boolean checkVmOnHost(final VirtualMachine vm, final long hostId) throws AgentUnavailableException, OperationTimedoutException { final Answer answer = _agentMgr.send(hostId, new CheckVirtualMachineCommand(vm.getInstanceName())); if (answer == null || !answer.getResult()) { return false; } if (answer instanceof CheckVirtualMachineAnswer) { final CheckVirtualMachineAnswer vmAnswer = (CheckVirtualMachineAnswer)answer; if (vmAnswer.getState() == PowerState.PowerOff) { return false; } } UserVmVO userVm = _userVmDao.findById(vm.getId()); if (userVm != null) { List<VMSnapshotVO> vmSnapshots = _vmSnapshotDao.findByVm(vm.getId()); RestoreVMSnapshotCommand command = _vmSnapshotMgr.createRestoreCommand(userVm, vmSnapshots); if (command != null) { RestoreVMSnapshotAnswer restoreVMSnapshotAnswer = (RestoreVMSnapshotAnswer) _agentMgr.send(hostId, command); if (restoreVMSnapshotAnswer == null || !restoreVMSnapshotAnswer.getResult()) { s_logger.warn("Unable to restore the vm snapshot from image file after live migration of vm with vmsnapshots: " + restoreVMSnapshotAnswer.getDetails()); } } } return true; }
Source:
public static void writeTo(ObjectOutput output, DataConversion dataConversion) throws IOException { byte flags = 0; boolean isDefault = isDefault(dataConversion); if (isDefault(dataConversion)) flags = 1; if (dataConversion.isKey) flags = (byte) (flags | 2); output.writeByte(flags); if (!isDefault) { output.writeShort(dataConversion.encoder.id()); output.writeByte(dataConversion.wrapper.id()); output.writeObject(dataConversion.requestMediaType); } }

Target:
public static void writeTo(ObjectOutput output, DataConversion dataConversion) throws IOException { byte flags = 0; boolean isDefault = isDefault(dataConversion); if (isDefault) flags = 1; if (dataConversion.isKey) flags = (byte) (flags | 2); output.writeByte(flags); if (!isDefault) { output.writeShort(dataConversion.encoder.id()); output.writeByte(dataConversion.wrapper.id()); output.writeObject(dataConversion.requestMediaType); } }
Source:
public void testQuery() throws Exception { try (Connection connection = createConnection(); Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery("SELECT orderkey FROM tpch.tiny.orders")) { while (rs.next()) { rs.getString("orderkey"); } } }

Target:
public void testQuery() throws Exception { try (Connection connection = createConnection(); Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery("SELECT row_number() OVER () n FROM tpch.tiny.orders")) { long count = 0; long sum = 0; while (rs.next()) { count++; sum += rs.getLong("n"); } assertEquals(count, 15000); assertEquals(sum, (count / 2) * (1 + count)); } }
Source:
public int hashCode() { Long result = articleId; result = 31 * result + doi.hashCode(); return result.intValue(); }

Target:
public int hashCode() { int result = Long.hashCode(articleId); result = 31 * result + doi.hashCode(); return result; }
Source:
protected java.util.ArrayList<Guid> getTemplatesList() { return getParameters().getEntitiesId(); }

Target:
protected ArrayList<Guid> getTemplatesList() { return getParameters().getEntitiesId(); }
Source:
public GeppettoManager(IGeppettoManager manager) { super(); if(manager instanceof GeppettoManager) { IUser u = manager.getUser(); System.out.println(u.getLogin()); GeppettoManager other = (GeppettoManager) manager; u = other.getUser(); System.out.println(u.getLogin()); if(other.projects!=null) { this.projects.putAll(other.projects); } this.user = DataManagerHelper.getDataManager().getUserByLogin(other.getUser().getLogin()); } }

Target:
public GeppettoManager(IGeppettoManager manager) { super(); if(manager instanceof GeppettoManager) { GeppettoManager other = (GeppettoManager) manager; if(other.projects!=null) { this.projects.putAll(other.projects); } this.user = DataManagerHelper.getDataManager().getUserByLogin(other.getUser().getLogin()); } }
Source:
public void booleanMapping() { OgmSession session = openSession(); Transaction transaction = session.beginTransaction(); rowAssertion( session.getSessionFactory(), "Bookmark" ) .id( "id", bookmarkId ) .assertColumn( "favourite", true ) .execute(); transaction.commit(); session.close(); }

Target:
public void booleanMapping() { OgmSession session = openSession(); Transaction transaction = session.beginTransaction(); rowAssertion( session.getSessionFactory(), "Bookmark" ) .keyColumn( "id", bookmarkId ) .assertColumn( "favourite", true ) .execute(); transaction.commit(); session.close(); }
Source:
public Object apply(AccountResource rsrc, Input input) throws AuthException, ResourceNotFoundException, OrmException { if (self.get() != rsrc.getUser() && !self.get().getCapabilities().canAdministrateServer()) { throw new AuthException("not allowed to set HTTP password"); } if (input == null) { input = new Input(); } AccountExternalId.Key key = new AccountExternalId.Key(SCHEME_USERNAME, rsrc.getUser().getUserName()); AccountExternalId id = dbProvider.get().accountExternalIds().get(key); if (id == null) { throw new ResourceNotFoundException(); } String newPassword; if (input.generate) { newPassword = generate(); } else { if (!Strings.isNullOrEmpty(input.httpPassword) && !self.get().getCapabilities().canAdministrateServer()) { throw new AuthException("not allowed to set HTTP password directly, " + "need to be Gerrit administrator"); } newPassword = Strings.emptyToNull(input.httpPassword); } id.setPassword(newPassword); dbProvider.get().accountExternalIds().update(Collections.singleton(id)); accountCache.evict(rsrc.getUser().getAccountId()); return Strings.isNullOrEmpty(newPassword) ? Response.none() : newPassword; }

Target:
public Response<String> apply(AccountResource rsrc, Input input) throws AuthException, ResourceNotFoundException, ResourceConflictException, OrmException { if (self.get() != rsrc.getUser() && !self.get().getCapabilities().canAdministrateServer()) { throw new AuthException("not allowed to set HTTP password"); } if (input == null) { input = new Input(); } if (rsrc.getUser().getUserName() == null) { throw new ResourceConflictException("no username"); } AccountExternalId.Key key = new AccountExternalId.Key(SCHEME_USERNAME, rsrc.getUser().getUserName()); AccountExternalId id = dbProvider.get().accountExternalIds().get(key); if (id == null) { throw new ResourceNotFoundException(); } String newPassword; if (input.generate) { newPassword = generate(); } else { if (!Strings.isNullOrEmpty(input.httpPassword) && !self.get().getCapabilities().canAdministrateServer()) { throw new AuthException("not allowed to set HTTP password directly, " + "need to be Gerrit administrator"); } newPassword = Strings.emptyToNull(input.httpPassword); } id.setPassword(newPassword); dbProvider.get().accountExternalIds().update(Collections.singleton(id)); accountCache.evict(rsrc.getUser().getAccountId()); return Strings.isNullOrEmpty(newPassword) ? Response.<String>none() : Response.ok(newPassword); }